]> Git Repo - binutils.git/blob - gdb/dwarf2/read.c
Change file_full_name and file_file_name methods
[binutils.git] / gdb / dwarf2 / read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2020 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck ([email protected]), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "dwarf2/read.h"
33 #include "dwarf2/abbrev.h"
34 #include "dwarf2/attribute.h"
35 #include "dwarf2/index-cache.h"
36 #include "dwarf2/index-common.h"
37 #include "dwarf2/leb.h"
38 #include "bfd.h"
39 #include "elf-bfd.h"
40 #include "symtab.h"
41 #include "gdbtypes.h"
42 #include "objfiles.h"
43 #include "dwarf2.h"
44 #include "buildsym.h"
45 #include "demangle.h"
46 #include "gdb-demangle.h"
47 #include "filenames.h"  /* for DOSish file names */
48 #include "macrotab.h"
49 #include "language.h"
50 #include "complaints.h"
51 #include "dwarf2/expr.h"
52 #include "dwarf2/loc.h"
53 #include "cp-support.h"
54 #include "hashtab.h"
55 #include "command.h"
56 #include "gdbcmd.h"
57 #include "block.h"
58 #include "addrmap.h"
59 #include "typeprint.h"
60 #include "psympriv.h"
61 #include "c-lang.h"
62 #include "go-lang.h"
63 #include "valprint.h"
64 #include "gdbcore.h" /* for gnutarget */
65 #include "gdb/gdb-index.h"
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "build-id.h"
70 #include "namespace.h"
71 #include "gdbsupport/function-view.h"
72 #include "gdbsupport/gdb_optional.h"
73 #include "gdbsupport/underlying.h"
74 #include "gdbsupport/hash_enum.h"
75 #include "filename-seen-cache.h"
76 #include "producer.h"
77 #include <fcntl.h>
78 #include <algorithm>
79 #include <unordered_map>
80 #include "gdbsupport/selftest.h"
81 #include "rust-lang.h"
82 #include "gdbsupport/pathstuff.h"
83
84 /* When == 1, print basic high level tracing messages.
85    When > 1, be more verbose.
86    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
87 static unsigned int dwarf_read_debug = 0;
88
89 /* When non-zero, dump DIEs after they are read in.  */
90 static unsigned int dwarf_die_debug = 0;
91
92 /* When non-zero, dump line number entries as they are read in.  */
93 static unsigned int dwarf_line_debug = 0;
94
95 /* When true, cross-check physname against demangler.  */
96 static bool check_physname = false;
97
98 /* When true, do not reject deprecated .gdb_index sections.  */
99 static bool use_deprecated_index_sections = false;
100
101 static const struct objfile_key<dwarf2_per_objfile> dwarf2_objfile_data_key;
102
103 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
104
105 static int dwarf2_locexpr_index;
106 static int dwarf2_loclist_index;
107 static int dwarf2_locexpr_block_index;
108 static int dwarf2_loclist_block_index;
109
110 /* An index into a (C++) symbol name component in a symbol name as
111    recorded in the mapped_index's symbol table.  For each C++ symbol
112    in the symbol table, we record one entry for the start of each
113    component in the symbol in a table of name components, and then
114    sort the table, in order to be able to binary search symbol names,
115    ignoring leading namespaces, both completion and regular look up.
116    For example, for symbol "A::B::C", we'll have an entry that points
117    to "A::B::C", another that points to "B::C", and another for "C".
118    Note that function symbols in GDB index have no parameter
119    information, just the function/method names.  You can convert a
120    name_component to a "const char *" using the
121    'mapped_index::symbol_name_at(offset_type)' method.  */
122
123 struct name_component
124 {
125   /* Offset in the symbol name where the component starts.  Stored as
126      a (32-bit) offset instead of a pointer to save memory and improve
127      locality on 64-bit architectures.  */
128   offset_type name_offset;
129
130   /* The symbol's index in the symbol and constant pool tables of a
131      mapped_index.  */
132   offset_type idx;
133 };
134
135 /* Base class containing bits shared by both .gdb_index and
136    .debug_name indexes.  */
137
138 struct mapped_index_base
139 {
140   mapped_index_base () = default;
141   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
142
143   /* The name_component table (a sorted vector).  See name_component's
144      description above.  */
145   std::vector<name_component> name_components;
146
147   /* How NAME_COMPONENTS is sorted.  */
148   enum case_sensitivity name_components_casing;
149
150   /* Return the number of names in the symbol table.  */
151   virtual size_t symbol_name_count () const = 0;
152
153   /* Get the name of the symbol at IDX in the symbol table.  */
154   virtual const char *symbol_name_at (offset_type idx) const = 0;
155
156   /* Return whether the name at IDX in the symbol table should be
157      ignored.  */
158   virtual bool symbol_name_slot_invalid (offset_type idx) const
159   {
160     return false;
161   }
162
163   /* Build the symbol name component sorted vector, if we haven't
164      yet.  */
165   void build_name_components ();
166
167   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
168      possible matches for LN_NO_PARAMS in the name component
169      vector.  */
170   std::pair<std::vector<name_component>::const_iterator,
171             std::vector<name_component>::const_iterator>
172     find_name_components_bounds (const lookup_name_info &ln_no_params,
173                                  enum language lang) const;
174
175   /* Prevent deleting/destroying via a base class pointer.  */
176 protected:
177   ~mapped_index_base() = default;
178 };
179
180 /* A description of the mapped index.  The file format is described in
181    a comment by the code that writes the index.  */
182 struct mapped_index final : public mapped_index_base
183 {
184   /* A slot/bucket in the symbol table hash.  */
185   struct symbol_table_slot
186   {
187     const offset_type name;
188     const offset_type vec;
189   };
190
191   /* Index data format version.  */
192   int version = 0;
193
194   /* The address table data.  */
195   gdb::array_view<const gdb_byte> address_table;
196
197   /* The symbol table, implemented as a hash table.  */
198   gdb::array_view<symbol_table_slot> symbol_table;
199
200   /* A pointer to the constant pool.  */
201   const char *constant_pool = nullptr;
202
203   bool symbol_name_slot_invalid (offset_type idx) const override
204   {
205     const auto &bucket = this->symbol_table[idx];
206     return bucket.name == 0 && bucket.vec == 0;
207   }
208
209   /* Convenience method to get at the name of the symbol at IDX in the
210      symbol table.  */
211   const char *symbol_name_at (offset_type idx) const override
212   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
213
214   size_t symbol_name_count () const override
215   { return this->symbol_table.size (); }
216 };
217
218 /* A description of the mapped .debug_names.
219    Uninitialized map has CU_COUNT 0.  */
220 struct mapped_debug_names final : public mapped_index_base
221 {
222   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
223   : dwarf2_per_objfile (dwarf2_per_objfile_)
224   {}
225
226   struct dwarf2_per_objfile *dwarf2_per_objfile;
227   bfd_endian dwarf5_byte_order;
228   bool dwarf5_is_dwarf64;
229   bool augmentation_is_gdb;
230   uint8_t offset_size;
231   uint32_t cu_count = 0;
232   uint32_t tu_count, bucket_count, name_count;
233   const gdb_byte *cu_table_reordered, *tu_table_reordered;
234   const uint32_t *bucket_table_reordered, *hash_table_reordered;
235   const gdb_byte *name_table_string_offs_reordered;
236   const gdb_byte *name_table_entry_offs_reordered;
237   const gdb_byte *entry_pool;
238
239   struct index_val
240   {
241     ULONGEST dwarf_tag;
242     struct attr
243     {
244       /* Attribute name DW_IDX_*.  */
245       ULONGEST dw_idx;
246
247       /* Attribute form DW_FORM_*.  */
248       ULONGEST form;
249
250       /* Value if FORM is DW_FORM_implicit_const.  */
251       LONGEST implicit_const;
252     };
253     std::vector<attr> attr_vec;
254   };
255
256   std::unordered_map<ULONGEST, index_val> abbrev_map;
257
258   const char *namei_to_name (uint32_t namei) const;
259
260   /* Implementation of the mapped_index_base virtual interface, for
261      the name_components cache.  */
262
263   const char *symbol_name_at (offset_type idx) const override
264   { return namei_to_name (idx); }
265
266   size_t symbol_name_count () const override
267   { return this->name_count; }
268 };
269
270 /* See dwarf2read.h.  */
271
272 dwarf2_per_objfile *
273 get_dwarf2_per_objfile (struct objfile *objfile)
274 {
275   return dwarf2_objfile_data_key.get (objfile);
276 }
277
278 /* Default names of the debugging sections.  */
279
280 /* Note that if the debugging section has been compressed, it might
281    have a name like .zdebug_info.  */
282
283 static const struct dwarf2_debug_sections dwarf2_elf_names =
284 {
285   { ".debug_info", ".zdebug_info" },
286   { ".debug_abbrev", ".zdebug_abbrev" },
287   { ".debug_line", ".zdebug_line" },
288   { ".debug_loc", ".zdebug_loc" },
289   { ".debug_loclists", ".zdebug_loclists" },
290   { ".debug_macinfo", ".zdebug_macinfo" },
291   { ".debug_macro", ".zdebug_macro" },
292   { ".debug_str", ".zdebug_str" },
293   { ".debug_str_offsets", ".zdebug_str_offsets" },
294   { ".debug_line_str", ".zdebug_line_str" },
295   { ".debug_ranges", ".zdebug_ranges" },
296   { ".debug_rnglists", ".zdebug_rnglists" },
297   { ".debug_types", ".zdebug_types" },
298   { ".debug_addr", ".zdebug_addr" },
299   { ".debug_frame", ".zdebug_frame" },
300   { ".eh_frame", NULL },
301   { ".gdb_index", ".zgdb_index" },
302   { ".debug_names", ".zdebug_names" },
303   { ".debug_aranges", ".zdebug_aranges" },
304   23
305 };
306
307 /* List of DWO/DWP sections.  */
308
309 static const struct dwop_section_names
310 {
311   struct dwarf2_section_names abbrev_dwo;
312   struct dwarf2_section_names info_dwo;
313   struct dwarf2_section_names line_dwo;
314   struct dwarf2_section_names loc_dwo;
315   struct dwarf2_section_names loclists_dwo;
316   struct dwarf2_section_names macinfo_dwo;
317   struct dwarf2_section_names macro_dwo;
318   struct dwarf2_section_names str_dwo;
319   struct dwarf2_section_names str_offsets_dwo;
320   struct dwarf2_section_names types_dwo;
321   struct dwarf2_section_names cu_index;
322   struct dwarf2_section_names tu_index;
323 }
324 dwop_section_names =
325 {
326   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
327   { ".debug_info.dwo", ".zdebug_info.dwo" },
328   { ".debug_line.dwo", ".zdebug_line.dwo" },
329   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
330   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
331   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
332   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
333   { ".debug_str.dwo", ".zdebug_str.dwo" },
334   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
335   { ".debug_types.dwo", ".zdebug_types.dwo" },
336   { ".debug_cu_index", ".zdebug_cu_index" },
337   { ".debug_tu_index", ".zdebug_tu_index" },
338 };
339
340 /* local data types */
341
342 /* The data in a compilation unit header, after target2host
343    translation, looks like this.  */
344 struct comp_unit_head
345 {
346   unsigned int length;
347   short version;
348   unsigned char addr_size;
349   unsigned char signed_addr_p;
350   sect_offset abbrev_sect_off;
351
352   /* Size of file offsets; either 4 or 8.  */
353   unsigned int offset_size;
354
355   /* Size of the length field; either 4 or 12.  */
356   unsigned int initial_length_size;
357
358   enum dwarf_unit_type unit_type;
359
360   /* Offset to the first byte of this compilation unit header in the
361      .debug_info section, for resolving relative reference dies.  */
362   sect_offset sect_off;
363
364   /* Offset to first die in this cu from the start of the cu.
365      This will be the first byte following the compilation unit header.  */
366   cu_offset first_die_cu_offset;
367
368
369   /* 64-bit signature of this unit. For type units, it denotes the signature of
370      the type (DW_UT_type in DWARF 4, additionally DW_UT_split_type in DWARF 5).
371      Also used in DWARF 5, to denote the dwo id when the unit type is
372      DW_UT_skeleton or DW_UT_split_compile.  */
373   ULONGEST signature;
374
375   /* For types, offset in the type's DIE of the type defined by this TU.  */
376   cu_offset type_cu_offset_in_tu;
377 };
378
379 /* Type used for delaying computation of method physnames.
380    See comments for compute_delayed_physnames.  */
381 struct delayed_method_info
382 {
383   /* The type to which the method is attached, i.e., its parent class.  */
384   struct type *type;
385
386   /* The index of the method in the type's function fieldlists.  */
387   int fnfield_index;
388
389   /* The index of the method in the fieldlist.  */
390   int index;
391
392   /* The name of the DIE.  */
393   const char *name;
394
395   /*  The DIE associated with this method.  */
396   struct die_info *die;
397 };
398
399 /* Internal state when decoding a particular compilation unit.  */
400 struct dwarf2_cu
401 {
402   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
403   ~dwarf2_cu ();
404
405   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
406
407   /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
408      Create the set of symtabs used by this TU, or if this TU is sharing
409      symtabs with another TU and the symtabs have already been created
410      then restore those symtabs in the line header.
411      We don't need the pc/line-number mapping for type units.  */
412   void setup_type_unit_groups (struct die_info *die);
413
414   /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
415      buildsym_compunit constructor.  */
416   struct compunit_symtab *start_symtab (const char *name,
417                                         const char *comp_dir,
418                                         CORE_ADDR low_pc);
419
420   /* Reset the builder.  */
421   void reset_builder () { m_builder.reset (); }
422
423   /* The header of the compilation unit.  */
424   struct comp_unit_head header {};
425
426   /* Base address of this compilation unit.  */
427   CORE_ADDR base_address = 0;
428
429   /* Non-zero if base_address has been set.  */
430   int base_known = 0;
431
432   /* The language we are debugging.  */
433   enum language language = language_unknown;
434   const struct language_defn *language_defn = nullptr;
435
436   const char *producer = nullptr;
437
438 private:
439   /* The symtab builder for this CU.  This is only non-NULL when full
440      symbols are being read.  */
441   std::unique_ptr<buildsym_compunit> m_builder;
442
443 public:
444   /* The generic symbol table building routines have separate lists for
445      file scope symbols and all all other scopes (local scopes).  So
446      we need to select the right one to pass to add_symbol_to_list().
447      We do it by keeping a pointer to the correct list in list_in_scope.
448
449      FIXME: The original dwarf code just treated the file scope as the
450      first local scope, and all other local scopes as nested local
451      scopes, and worked fine.  Check to see if we really need to
452      distinguish these in buildsym.c.  */
453   struct pending **list_in_scope = nullptr;
454
455   /* Hash table holding all the loaded partial DIEs
456      with partial_die->offset.SECT_OFF as hash.  */
457   htab_t partial_dies = nullptr;
458
459   /* Storage for things with the same lifetime as this read-in compilation
460      unit, including partial DIEs.  */
461   auto_obstack comp_unit_obstack;
462
463   /* When multiple dwarf2_cu structures are living in memory, this field
464      chains them all together, so that they can be released efficiently.
465      We will probably also want a generation counter so that most-recently-used
466      compilation units are cached...  */
467   struct dwarf2_per_cu_data *read_in_chain = nullptr;
468
469   /* Backlink to our per_cu entry.  */
470   struct dwarf2_per_cu_data *per_cu;
471
472   /* How many compilation units ago was this CU last referenced?  */
473   int last_used = 0;
474
475   /* A hash table of DIE cu_offset for following references with
476      die_info->offset.sect_off as hash.  */
477   htab_t die_hash = nullptr;
478
479   /* Full DIEs if read in.  */
480   struct die_info *dies = nullptr;
481
482   /* A set of pointers to dwarf2_per_cu_data objects for compilation
483      units referenced by this one.  Only set during full symbol processing;
484      partial symbol tables do not have dependencies.  */
485   htab_t dependencies = nullptr;
486
487   /* Header data from the line table, during full symbol processing.  */
488   struct line_header *line_header = nullptr;
489   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
490      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
491      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
492      to the line header as long as this DIE is being processed.  See
493      process_die_scope.  */
494   die_info *line_header_die_owner = nullptr;
495
496   /* A list of methods which need to have physnames computed
497      after all type information has been read.  */
498   std::vector<delayed_method_info> method_list;
499
500   /* To be copied to symtab->call_site_htab.  */
501   htab_t call_site_htab = nullptr;
502
503   /* Non-NULL if this CU came from a DWO file.
504      There is an invariant here that is important to remember:
505      Except for attributes copied from the top level DIE in the "main"
506      (or "stub") file in preparation for reading the DWO file
507      (e.g., DW_AT_addr_base), we KISS: there is only *one* CU.
508      Either there isn't a DWO file (in which case this is NULL and the point
509      is moot), or there is and either we're not going to read it (in which
510      case this is NULL) or there is and we are reading it (in which case this
511      is non-NULL).  */
512   struct dwo_unit *dwo_unit = nullptr;
513
514   /* The DW_AT_addr_base (DW_AT_GNU_addr_base) attribute if present.
515      Note this value comes from the Fission stub CU/TU's DIE.  */
516   gdb::optional<ULONGEST> addr_base;
517
518   /* The DW_AT_rnglists_base attribute if present.
519      Note this value comes from the Fission stub CU/TU's DIE.
520      Also note that the value is zero in the non-DWO case so this value can
521      be used without needing to know whether DWO files are in use or not.
522      N.B. This does not apply to DW_AT_ranges appearing in
523      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
524      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
525      DW_AT_rnglists_base *would* have to be applied, and we'd have to care
526      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
527   ULONGEST ranges_base = 0;
528
529   /* When reading debug info generated by older versions of rustc, we
530      have to rewrite some union types to be struct types with a
531      variant part.  This rewriting must be done after the CU is fully
532      read in, because otherwise at the point of rewriting some struct
533      type might not have been fully processed.  So, we keep a list of
534      all such types here and process them after expansion.  */
535   std::vector<struct type *> rust_unions;
536
537   /* The DW_AT_str_offsets_base attribute if present.  For DWARF 4 version DWO
538      files, the value is implicitly zero.  For DWARF 5 version DWO files, the
539      value is often implicit and is the size of the header of
540      .debug_str_offsets section (8 or 4, depending on the address size).  */
541   gdb::optional<ULONGEST> str_offsets_base;
542
543   /* Mark used when releasing cached dies.  */
544   bool mark : 1;
545
546   /* This CU references .debug_loc.  See the symtab->locations_valid field.
547      This test is imperfect as there may exist optimized debug code not using
548      any location list and still facing inlining issues if handled as
549      unoptimized code.  For a future better test see GCC PR other/32998.  */
550   bool has_loclist : 1;
551
552   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is true
553      if all the producer_is_* fields are valid.  This information is cached
554      because profiling CU expansion showed excessive time spent in
555      producer_is_gxx_lt_4_6.  */
556   bool checked_producer : 1;
557   bool producer_is_gxx_lt_4_6 : 1;
558   bool producer_is_gcc_lt_4_3 : 1;
559   bool producer_is_icc : 1;
560   bool producer_is_icc_lt_14 : 1;
561   bool producer_is_codewarrior : 1;
562
563   /* When true, the file that we're processing is known to have
564      debugging info for C++ namespaces.  GCC 3.3.x did not produce
565      this information, but later versions do.  */
566
567   bool processing_has_namespace_info : 1;
568
569   struct partial_die_info *find_partial_die (sect_offset sect_off);
570
571   /* If this CU was inherited by another CU (via specification,
572      abstract_origin, etc), this is the ancestor CU.  */
573   dwarf2_cu *ancestor;
574
575   /* Get the buildsym_compunit for this CU.  */
576   buildsym_compunit *get_builder ()
577   {
578     /* If this CU has a builder associated with it, use that.  */
579     if (m_builder != nullptr)
580       return m_builder.get ();
581
582     /* Otherwise, search ancestors for a valid builder.  */
583     if (ancestor != nullptr)
584       return ancestor->get_builder ();
585
586     return nullptr;
587   }
588 };
589
590 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
591    This includes type_unit_group and quick_file_names.  */
592
593 struct stmt_list_hash
594 {
595   /* The DWO unit this table is from or NULL if there is none.  */
596   struct dwo_unit *dwo_unit;
597
598   /* Offset in .debug_line or .debug_line.dwo.  */
599   sect_offset line_sect_off;
600 };
601
602 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
603    an object of this type.  */
604
605 struct type_unit_group
606 {
607   /* dwarf2read.c's main "handle" on a TU symtab.
608      To simplify things we create an artificial CU that "includes" all the
609      type units using this stmt_list so that the rest of the code still has
610      a "per_cu" handle on the symtab.
611      This PER_CU is recognized by having no section.  */
612 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
613   struct dwarf2_per_cu_data per_cu;
614
615   /* The TUs that share this DW_AT_stmt_list entry.
616      This is added to while parsing type units to build partial symtabs,
617      and is deleted afterwards and not used again.  */
618   std::vector<signatured_type *> *tus;
619
620   /* The compunit symtab.
621      Type units in a group needn't all be defined in the same source file,
622      so we create an essentially anonymous symtab as the compunit symtab.  */
623   struct compunit_symtab *compunit_symtab;
624
625   /* The data used to construct the hash key.  */
626   struct stmt_list_hash hash;
627
628   /* The number of symtabs from the line header.
629      The value here must match line_header.num_file_names.  */
630   unsigned int num_symtabs;
631
632   /* The symbol tables for this TU (obtained from the files listed in
633      DW_AT_stmt_list).
634      WARNING: The order of entries here must match the order of entries
635      in the line header.  After the first TU using this type_unit_group, the
636      line header for the subsequent TUs is recreated from this.  This is done
637      because we need to use the same symtabs for each TU using the same
638      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
639      there's no guarantee the line header doesn't have duplicate entries.  */
640   struct symtab **symtabs;
641 };
642
643 /* These sections are what may appear in a (real or virtual) DWO file.  */
644
645 struct dwo_sections
646 {
647   struct dwarf2_section_info abbrev;
648   struct dwarf2_section_info line;
649   struct dwarf2_section_info loc;
650   struct dwarf2_section_info loclists;
651   struct dwarf2_section_info macinfo;
652   struct dwarf2_section_info macro;
653   struct dwarf2_section_info str;
654   struct dwarf2_section_info str_offsets;
655   /* In the case of a virtual DWO file, these two are unused.  */
656   struct dwarf2_section_info info;
657   std::vector<dwarf2_section_info> types;
658 };
659
660 /* CUs/TUs in DWP/DWO files.  */
661
662 struct dwo_unit
663 {
664   /* Backlink to the containing struct dwo_file.  */
665   struct dwo_file *dwo_file;
666
667   /* The "id" that distinguishes this CU/TU.
668      .debug_info calls this "dwo_id", .debug_types calls this "signature".
669      Since signatures came first, we stick with it for consistency.  */
670   ULONGEST signature;
671
672   /* The section this CU/TU lives in, in the DWO file.  */
673   struct dwarf2_section_info *section;
674
675   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
676   sect_offset sect_off;
677   unsigned int length;
678
679   /* For types, offset in the type's DIE of the type defined by this TU.  */
680   cu_offset type_offset_in_tu;
681 };
682
683 /* include/dwarf2.h defines the DWP section codes.
684    It defines a max value but it doesn't define a min value, which we
685    use for error checking, so provide one.  */
686
687 enum dwp_v2_section_ids
688 {
689   DW_SECT_MIN = 1
690 };
691
692 /* Data for one DWO file.
693
694    This includes virtual DWO files (a virtual DWO file is a DWO file as it
695    appears in a DWP file).  DWP files don't really have DWO files per se -
696    comdat folding of types "loses" the DWO file they came from, and from
697    a high level view DWP files appear to contain a mass of random types.
698    However, to maintain consistency with the non-DWP case we pretend DWP
699    files contain virtual DWO files, and we assign each TU with one virtual
700    DWO file (generally based on the line and abbrev section offsets -
701    a heuristic that seems to work in practice).  */
702
703 struct dwo_file
704 {
705   dwo_file () = default;
706   DISABLE_COPY_AND_ASSIGN (dwo_file);
707
708   /* The DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.
709      For virtual DWO files the name is constructed from the section offsets
710      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
711      from related CU+TUs.  */
712   const char *dwo_name = nullptr;
713
714   /* The DW_AT_comp_dir attribute.  */
715   const char *comp_dir = nullptr;
716
717   /* The bfd, when the file is open.  Otherwise this is NULL.
718      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
719   gdb_bfd_ref_ptr dbfd;
720
721   /* The sections that make up this DWO file.
722      Remember that for virtual DWO files in DWP V2, these are virtual
723      sections (for lack of a better name).  */
724   struct dwo_sections sections {};
725
726   /* The CUs in the file.
727      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
728      an extension to handle LLVM's Link Time Optimization output (where
729      multiple source files may be compiled into a single object/dwo pair). */
730   htab_up cus;
731
732   /* Table of TUs in the file.
733      Each element is a struct dwo_unit.  */
734   htab_up tus;
735 };
736
737 /* These sections are what may appear in a DWP file.  */
738
739 struct dwp_sections
740 {
741   /* These are used by both DWP version 1 and 2.  */
742   struct dwarf2_section_info str;
743   struct dwarf2_section_info cu_index;
744   struct dwarf2_section_info tu_index;
745
746   /* These are only used by DWP version 2 files.
747      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
748      sections are referenced by section number, and are not recorded here.
749      In DWP version 2 there is at most one copy of all these sections, each
750      section being (effectively) comprised of the concatenation of all of the
751      individual sections that exist in the version 1 format.
752      To keep the code simple we treat each of these concatenated pieces as a
753      section itself (a virtual section?).  */
754   struct dwarf2_section_info abbrev;
755   struct dwarf2_section_info info;
756   struct dwarf2_section_info line;
757   struct dwarf2_section_info loc;
758   struct dwarf2_section_info macinfo;
759   struct dwarf2_section_info macro;
760   struct dwarf2_section_info str_offsets;
761   struct dwarf2_section_info types;
762 };
763
764 /* These sections are what may appear in a virtual DWO file in DWP version 1.
765    A virtual DWO file is a DWO file as it appears in a DWP file.  */
766
767 struct virtual_v1_dwo_sections
768 {
769   struct dwarf2_section_info abbrev;
770   struct dwarf2_section_info line;
771   struct dwarf2_section_info loc;
772   struct dwarf2_section_info macinfo;
773   struct dwarf2_section_info macro;
774   struct dwarf2_section_info str_offsets;
775   /* Each DWP hash table entry records one CU or one TU.
776      That is recorded here, and copied to dwo_unit.section.  */
777   struct dwarf2_section_info info_or_types;
778 };
779
780 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
781    In version 2, the sections of the DWO files are concatenated together
782    and stored in one section of that name.  Thus each ELF section contains
783    several "virtual" sections.  */
784
785 struct virtual_v2_dwo_sections
786 {
787   bfd_size_type abbrev_offset;
788   bfd_size_type abbrev_size;
789
790   bfd_size_type line_offset;
791   bfd_size_type line_size;
792
793   bfd_size_type loc_offset;
794   bfd_size_type loc_size;
795
796   bfd_size_type macinfo_offset;
797   bfd_size_type macinfo_size;
798
799   bfd_size_type macro_offset;
800   bfd_size_type macro_size;
801
802   bfd_size_type str_offsets_offset;
803   bfd_size_type str_offsets_size;
804
805   /* Each DWP hash table entry records one CU or one TU.
806      That is recorded here, and copied to dwo_unit.section.  */
807   bfd_size_type info_or_types_offset;
808   bfd_size_type info_or_types_size;
809 };
810
811 /* Contents of DWP hash tables.  */
812
813 struct dwp_hash_table
814 {
815   uint32_t version, nr_columns;
816   uint32_t nr_units, nr_slots;
817   const gdb_byte *hash_table, *unit_table;
818   union
819   {
820     struct
821     {
822       const gdb_byte *indices;
823     } v1;
824     struct
825     {
826       /* This is indexed by column number and gives the id of the section
827          in that column.  */
828 #define MAX_NR_V2_DWO_SECTIONS \
829   (1 /* .debug_info or .debug_types */ \
830    + 1 /* .debug_abbrev */ \
831    + 1 /* .debug_line */ \
832    + 1 /* .debug_loc */ \
833    + 1 /* .debug_str_offsets */ \
834    + 1 /* .debug_macro or .debug_macinfo */)
835       int section_ids[MAX_NR_V2_DWO_SECTIONS];
836       const gdb_byte *offsets;
837       const gdb_byte *sizes;
838     } v2;
839   } section_pool;
840 };
841
842 /* Data for one DWP file.  */
843
844 struct dwp_file
845 {
846   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
847     : name (name_),
848       dbfd (std::move (abfd))
849   {
850   }
851
852   /* Name of the file.  */
853   const char *name;
854
855   /* File format version.  */
856   int version = 0;
857
858   /* The bfd.  */
859   gdb_bfd_ref_ptr dbfd;
860
861   /* Section info for this file.  */
862   struct dwp_sections sections {};
863
864   /* Table of CUs in the file.  */
865   const struct dwp_hash_table *cus = nullptr;
866
867   /* Table of TUs in the file.  */
868   const struct dwp_hash_table *tus = nullptr;
869
870   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
871   htab_up loaded_cus;
872   htab_up loaded_tus;
873
874   /* Table to map ELF section numbers to their sections.
875      This is only needed for the DWP V1 file format.  */
876   unsigned int num_sections = 0;
877   asection **elf_sections = nullptr;
878 };
879
880 /* Struct used to pass misc. parameters to read_die_and_children, et
881    al.  which are used for both .debug_info and .debug_types dies.
882    All parameters here are unchanging for the life of the call.  This
883    struct exists to abstract away the constant parameters of die reading.  */
884
885 struct die_reader_specs
886 {
887   /* The bfd of die_section.  */
888   bfd* abfd;
889
890   /* The CU of the DIE we are parsing.  */
891   struct dwarf2_cu *cu;
892
893   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
894   struct dwo_file *dwo_file;
895
896   /* The section the die comes from.
897      This is either .debug_info or .debug_types, or the .dwo variants.  */
898   struct dwarf2_section_info *die_section;
899
900   /* die_section->buffer.  */
901   const gdb_byte *buffer;
902
903   /* The end of the buffer.  */
904   const gdb_byte *buffer_end;
905
906   /* The abbreviation table to use when reading the DIEs.  */
907   struct abbrev_table *abbrev_table;
908 };
909
910 /* A subclass of die_reader_specs that holds storage and has complex
911    constructor and destructor behavior.  */
912
913 class cutu_reader : public die_reader_specs
914 {
915 public:
916
917   cutu_reader (struct dwarf2_per_cu_data *this_cu,
918                struct abbrev_table *abbrev_table,
919                int use_existing_cu, int keep,
920                bool skip_partial);
921
922   explicit cutu_reader (struct dwarf2_per_cu_data *this_cu,
923                         struct dwarf2_cu *parent_cu = nullptr,
924                         struct dwo_file *dwo_file = nullptr);
925
926   ~cutu_reader ();
927
928   DISABLE_COPY_AND_ASSIGN (cutu_reader);
929
930   const gdb_byte *info_ptr = nullptr;
931   struct die_info *comp_unit_die = nullptr;
932   bool dummy_p = false;
933
934 private:
935   void init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
936                                   int use_existing_cu, int keep);
937
938   struct dwarf2_per_cu_data *m_this_cu;
939   int m_keep = 0;
940   std::unique_ptr<dwarf2_cu> m_new_cu;
941
942   /* The ordinary abbreviation table.  */
943   abbrev_table_up m_abbrev_table_holder;
944
945   /* The DWO abbreviation table.  */
946   abbrev_table_up m_dwo_abbrev_table;
947 };
948
949 /* dir_index is 1-based in DWARF 4 and before, and is 0-based in DWARF 5 and
950    later.  */
951 typedef int dir_index;
952
953 /* file_name_index is 1-based in DWARF 4 and before, and is 0-based in DWARF 5
954    and later.  */
955 typedef int file_name_index;
956
957 struct file_entry
958 {
959   file_entry () = default;
960
961   file_entry (const char *name_, dir_index d_index_,
962               unsigned int mod_time_, unsigned int length_)
963     : name (name_),
964       d_index (d_index_),
965       mod_time (mod_time_),
966       length (length_)
967   {}
968
969   /* Return the include directory at D_INDEX stored in LH.  Returns
970      NULL if D_INDEX is out of bounds.  */
971   const char *include_dir (const line_header *lh) const;
972
973   /* The file name.  Note this is an observing pointer.  The memory is
974      owned by debug_line_buffer.  */
975   const char *name {};
976
977   /* The directory index (1-based).  */
978   dir_index d_index {};
979
980   unsigned int mod_time {};
981
982   unsigned int length {};
983
984   /* True if referenced by the Line Number Program.  */
985   bool included_p {};
986
987   /* The associated symbol table, if any.  */
988   struct symtab *symtab {};
989 };
990
991 /* The line number information for a compilation unit (found in the
992    .debug_line section) begins with a "statement program header",
993    which contains the following information.  */
994 struct line_header
995 {
996   line_header ()
997     : offset_in_dwz {}
998   {}
999
1000   /* Add an entry to the include directory table.  */
1001   void add_include_dir (const char *include_dir);
1002
1003   /* Add an entry to the file name table.  */
1004   void add_file_name (const char *name, dir_index d_index,
1005                       unsigned int mod_time, unsigned int length);
1006
1007   /* Return the include dir at INDEX (0-based in DWARF 5 and 1-based before).
1008      Returns NULL if INDEX is out of bounds.  */
1009   const char *include_dir_at (dir_index index) const
1010   {
1011     int vec_index;
1012     if (version >= 5)
1013       vec_index = index;
1014     else
1015       vec_index = index - 1;
1016     if (vec_index < 0 || vec_index >= m_include_dirs.size ())
1017       return NULL;
1018     return m_include_dirs[vec_index];
1019   }
1020
1021   bool is_valid_file_index (int file_index)
1022   {
1023     if (version >= 5)
1024       return 0 <= file_index && file_index < file_names_size ();
1025     return 1 <= file_index && file_index <= file_names_size ();
1026   }
1027
1028   /* Return the file name at INDEX (0-based in DWARF 5 and 1-based before).
1029      Returns NULL if INDEX is out of bounds.  */
1030   file_entry *file_name_at (file_name_index index)
1031   {
1032     int vec_index;
1033     if (version >= 5)
1034       vec_index = index;
1035     else
1036       vec_index = index - 1;
1037     if (vec_index < 0 || vec_index >= m_file_names.size ())
1038       return NULL;
1039     return &m_file_names[vec_index];
1040   }
1041
1042   /* The indexes are 0-based in DWARF 5 and 1-based in DWARF 4. Therefore,
1043      this method should only be used to iterate through all file entries in an
1044      index-agnostic manner.  */
1045   std::vector<file_entry> &file_names ()
1046   { return m_file_names; }
1047
1048   /* Offset of line number information in .debug_line section.  */
1049   sect_offset sect_off {};
1050
1051   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1052   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1053
1054   unsigned int total_length {};
1055   unsigned short version {};
1056   unsigned int header_length {};
1057   unsigned char minimum_instruction_length {};
1058   unsigned char maximum_ops_per_instruction {};
1059   unsigned char default_is_stmt {};
1060   int line_base {};
1061   unsigned char line_range {};
1062   unsigned char opcode_base {};
1063
1064   /* standard_opcode_lengths[i] is the number of operands for the
1065      standard opcode whose value is i.  This means that
1066      standard_opcode_lengths[0] is unused, and the last meaningful
1067      element is standard_opcode_lengths[opcode_base - 1].  */
1068   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1069
1070   int file_names_size ()
1071   { return m_file_names.size(); }
1072
1073   /* The start and end of the statement program following this
1074      header.  These point into dwarf2_per_objfile->line_buffer.  */
1075   const gdb_byte *statement_program_start {}, *statement_program_end {};
1076
1077   /* Return the full name of file number I in this object's file name
1078      table.  Use COMP_DIR as the name of the current directory of the
1079      compilation.  The result is allocated using xmalloc; the caller
1080      is responsible for freeing it.  */
1081   char *file_full_name (int file, const char *comp_dir);
1082
1083   /* Return file name relative to the compilation directory of file
1084      number I in this object's file name table.  The result is
1085      allocated using xmalloc; the caller is responsible for freeing
1086      it.  */
1087   char *file_file_name (int file);
1088
1089  private:
1090   /* The include_directories table.  Note these are observing
1091      pointers.  The memory is owned by debug_line_buffer.  */
1092   std::vector<const char *> m_include_dirs;
1093
1094   /* The file_names table. This is private because the meaning of indexes
1095      differs among DWARF versions (The first valid index is 1 in DWARF 4 and
1096      before, and is 0 in DWARF 5 and later).  So the client should use
1097      file_name_at method for access.  */
1098   std::vector<file_entry> m_file_names;
1099 };
1100
1101 typedef std::unique_ptr<line_header> line_header_up;
1102
1103 const char *
1104 file_entry::include_dir (const line_header *lh) const
1105 {
1106   return lh->include_dir_at (d_index);
1107 }
1108
1109 /* When we construct a partial symbol table entry we only
1110    need this much information.  */
1111 struct partial_die_info : public allocate_on_obstack
1112   {
1113     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1114
1115     /* Disable assign but still keep copy ctor, which is needed
1116        load_partial_dies.   */
1117     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1118
1119     /* Adjust the partial die before generating a symbol for it.  This
1120        function may set the is_external flag or change the DIE's
1121        name.  */
1122     void fixup (struct dwarf2_cu *cu);
1123
1124     /* Read a minimal amount of information into the minimal die
1125        structure.  */
1126     const gdb_byte *read (const struct die_reader_specs *reader,
1127                           const struct abbrev_info &abbrev,
1128                           const gdb_byte *info_ptr);
1129
1130     /* Offset of this DIE.  */
1131     const sect_offset sect_off;
1132
1133     /* DWARF-2 tag for this DIE.  */
1134     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1135
1136     /* Assorted flags describing the data found in this DIE.  */
1137     const unsigned int has_children : 1;
1138
1139     unsigned int is_external : 1;
1140     unsigned int is_declaration : 1;
1141     unsigned int has_type : 1;
1142     unsigned int has_specification : 1;
1143     unsigned int has_pc_info : 1;
1144     unsigned int may_be_inlined : 1;
1145
1146     /* This DIE has been marked DW_AT_main_subprogram.  */
1147     unsigned int main_subprogram : 1;
1148
1149     /* Flag set if the SCOPE field of this structure has been
1150        computed.  */
1151     unsigned int scope_set : 1;
1152
1153     /* Flag set if the DIE has a byte_size attribute.  */
1154     unsigned int has_byte_size : 1;
1155
1156     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1157     unsigned int has_const_value : 1;
1158
1159     /* Flag set if any of the DIE's children are template arguments.  */
1160     unsigned int has_template_arguments : 1;
1161
1162     /* Flag set if fixup has been called on this die.  */
1163     unsigned int fixup_called : 1;
1164
1165     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1166     unsigned int is_dwz : 1;
1167
1168     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1169     unsigned int spec_is_dwz : 1;
1170
1171     /* The name of this DIE.  Normally the value of DW_AT_name, but
1172        sometimes a default name for unnamed DIEs.  */
1173     const char *name = nullptr;
1174
1175     /* The linkage name, if present.  */
1176     const char *linkage_name = nullptr;
1177
1178     /* The scope to prepend to our children.  This is generally
1179        allocated on the comp_unit_obstack, so will disappear
1180        when this compilation unit leaves the cache.  */
1181     const char *scope = nullptr;
1182
1183     /* Some data associated with the partial DIE.  The tag determines
1184        which field is live.  */
1185     union
1186     {
1187       /* The location description associated with this DIE, if any.  */
1188       struct dwarf_block *locdesc;
1189       /* The offset of an import, for DW_TAG_imported_unit.  */
1190       sect_offset sect_off;
1191     } d {};
1192
1193     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1194     CORE_ADDR lowpc = 0;
1195     CORE_ADDR highpc = 0;
1196
1197     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1198        DW_AT_sibling, if any.  */
1199     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1200        could return DW_AT_sibling values to its caller load_partial_dies.  */
1201     const gdb_byte *sibling = nullptr;
1202
1203     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1204        DW_AT_specification (or DW_AT_abstract_origin or
1205        DW_AT_extension).  */
1206     sect_offset spec_offset {};
1207
1208     /* Pointers to this DIE's parent, first child, and next sibling,
1209        if any.  */
1210     struct partial_die_info *die_parent = nullptr;
1211     struct partial_die_info *die_child = nullptr;
1212     struct partial_die_info *die_sibling = nullptr;
1213
1214     friend struct partial_die_info *
1215     dwarf2_cu::find_partial_die (sect_offset sect_off);
1216
1217   private:
1218     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1219     partial_die_info (sect_offset sect_off)
1220       : partial_die_info (sect_off, DW_TAG_padding, 0)
1221     {
1222     }
1223
1224     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1225                       int has_children_)
1226       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1227     {
1228       is_external = 0;
1229       is_declaration = 0;
1230       has_type = 0;
1231       has_specification = 0;
1232       has_pc_info = 0;
1233       may_be_inlined = 0;
1234       main_subprogram = 0;
1235       scope_set = 0;
1236       has_byte_size = 0;
1237       has_const_value = 0;
1238       has_template_arguments = 0;
1239       fixup_called = 0;
1240       is_dwz = 0;
1241       spec_is_dwz = 0;
1242     }
1243   };
1244
1245 /* This data structure holds a complete die structure.  */
1246 struct die_info
1247   {
1248     /* DWARF-2 tag for this DIE.  */
1249     ENUM_BITFIELD(dwarf_tag) tag : 16;
1250
1251     /* Number of attributes */
1252     unsigned char num_attrs;
1253
1254     /* True if we're presently building the full type name for the
1255        type derived from this DIE.  */
1256     unsigned char building_fullname : 1;
1257
1258     /* True if this die is in process.  PR 16581.  */
1259     unsigned char in_process : 1;
1260
1261     /* True if this DIE has children.  */
1262     unsigned char has_children : 1;
1263
1264     /* Abbrev number */
1265     unsigned int abbrev;
1266
1267     /* Offset in .debug_info or .debug_types section.  */
1268     sect_offset sect_off;
1269
1270     /* The dies in a compilation unit form an n-ary tree.  PARENT
1271        points to this die's parent; CHILD points to the first child of
1272        this node; and all the children of a given node are chained
1273        together via their SIBLING fields.  */
1274     struct die_info *child;     /* Its first child, if any.  */
1275     struct die_info *sibling;   /* Its next sibling, if any.  */
1276     struct die_info *parent;    /* Its parent, if any.  */
1277
1278     /* An array of attributes, with NUM_ATTRS elements.  There may be
1279        zero, but it's not common and zero-sized arrays are not
1280        sufficiently portable C.  */
1281     struct attribute attrs[1];
1282   };
1283
1284 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1285    but this would require a corresponding change in unpack_field_as_long
1286    and friends.  */
1287 static int bits_per_byte = 8;
1288
1289 /* When reading a variant or variant part, we track a bit more
1290    information about the field, and store it in an object of this
1291    type.  */
1292
1293 struct variant_field
1294 {
1295   /* If we see a DW_TAG_variant, then this will be the discriminant
1296      value.  */
1297   ULONGEST discriminant_value;
1298   /* If we see a DW_TAG_variant, then this will be set if this is the
1299      default branch.  */
1300   bool default_branch;
1301   /* While reading a DW_TAG_variant_part, this will be set if this
1302      field is the discriminant.  */
1303   bool is_discriminant;
1304 };
1305
1306 struct nextfield
1307 {
1308   int accessibility = 0;
1309   int virtuality = 0;
1310   /* Extra information to describe a variant or variant part.  */
1311   struct variant_field variant {};
1312   struct field field {};
1313 };
1314
1315 struct fnfieldlist
1316 {
1317   const char *name = nullptr;
1318   std::vector<struct fn_field> fnfields;
1319 };
1320
1321 /* The routines that read and process dies for a C struct or C++ class
1322    pass lists of data member fields and lists of member function fields
1323    in an instance of a field_info structure, as defined below.  */
1324 struct field_info
1325   {
1326     /* List of data member and baseclasses fields.  */
1327     std::vector<struct nextfield> fields;
1328     std::vector<struct nextfield> baseclasses;
1329
1330     /* Number of fields (including baseclasses).  */
1331     int nfields = 0;
1332
1333     /* Set if the accessibility of one of the fields is not public.  */
1334     int non_public_fields = 0;
1335
1336     /* Member function fieldlist array, contains name of possibly overloaded
1337        member function, number of overloaded member functions and a pointer
1338        to the head of the member function field chain.  */
1339     std::vector<struct fnfieldlist> fnfieldlists;
1340
1341     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1342        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1343     std::vector<struct decl_field> typedef_field_list;
1344
1345     /* Nested types defined by this class and the number of elements in this
1346        list.  */
1347     std::vector<struct decl_field> nested_types_list;
1348   };
1349
1350 /* Loaded secondary compilation units are kept in memory until they
1351    have not been referenced for the processing of this many
1352    compilation units.  Set this to zero to disable caching.  Cache
1353    sizes of up to at least twenty will improve startup time for
1354    typical inter-CU-reference binaries, at an obvious memory cost.  */
1355 static int dwarf_max_cache_age = 5;
1356 static void
1357 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1358                           struct cmd_list_element *c, const char *value)
1359 {
1360   fprintf_filtered (file, _("The upper bound on the age of cached "
1361                             "DWARF compilation units is %s.\n"),
1362                     value);
1363 }
1364 \f
1365 /* local function prototypes */
1366
1367 static void dwarf2_find_base_address (struct die_info *die,
1368                                       struct dwarf2_cu *cu);
1369
1370 static dwarf2_psymtab *create_partial_symtab
1371   (struct dwarf2_per_cu_data *per_cu, const char *name);
1372
1373 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1374                                         const gdb_byte *info_ptr,
1375                                         struct die_info *type_unit_die);
1376
1377 static void dwarf2_build_psymtabs_hard
1378   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1379
1380 static void scan_partial_symbols (struct partial_die_info *,
1381                                   CORE_ADDR *, CORE_ADDR *,
1382                                   int, struct dwarf2_cu *);
1383
1384 static void add_partial_symbol (struct partial_die_info *,
1385                                 struct dwarf2_cu *);
1386
1387 static void add_partial_namespace (struct partial_die_info *pdi,
1388                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1389                                    int set_addrmap, struct dwarf2_cu *cu);
1390
1391 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1392                                 CORE_ADDR *highpc, int set_addrmap,
1393                                 struct dwarf2_cu *cu);
1394
1395 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1396                                      struct dwarf2_cu *cu);
1397
1398 static void add_partial_subprogram (struct partial_die_info *pdi,
1399                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1400                                     int need_pc, struct dwarf2_cu *cu);
1401
1402 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1403
1404 static struct partial_die_info *load_partial_dies
1405   (const struct die_reader_specs *, const gdb_byte *, int);
1406
1407 /* A pair of partial_die_info and compilation unit.  */
1408 struct cu_partial_die_info
1409 {
1410   /* The compilation unit of the partial_die_info.  */
1411   struct dwarf2_cu *cu;
1412   /* A partial_die_info.  */
1413   struct partial_die_info *pdi;
1414
1415   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1416     : cu (cu),
1417       pdi (pdi)
1418   { /* Nothing.  */ }
1419
1420 private:
1421   cu_partial_die_info () = delete;
1422 };
1423
1424 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1425                                                           struct dwarf2_cu *);
1426
1427 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1428                                        struct attribute *, struct attr_abbrev *,
1429                                        const gdb_byte *, bool *need_reprocess);
1430
1431 static void read_attribute_reprocess (const struct die_reader_specs *reader,
1432                                       struct attribute *attr);
1433
1434 static CORE_ADDR read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index);
1435
1436 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1437                                unsigned int *);
1438
1439 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1440
1441 static LONGEST read_checked_initial_length_and_offset
1442   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1443    unsigned int *, unsigned int *);
1444
1445 static LONGEST read_offset (bfd *, const gdb_byte *,
1446                             const struct comp_unit_head *,
1447                             unsigned int *);
1448
1449 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1450
1451 static sect_offset read_abbrev_offset
1452   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1453    struct dwarf2_section_info *, sect_offset);
1454
1455 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1456
1457 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1458
1459 static const char *read_indirect_string
1460   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1461    const struct comp_unit_head *, unsigned int *);
1462
1463 static const char *read_indirect_line_string
1464   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1465    const struct comp_unit_head *, unsigned int *);
1466
1467 static const char *read_indirect_string_at_offset
1468   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1469    LONGEST str_offset);
1470
1471 static const char *read_indirect_string_from_dwz
1472   (struct objfile *objfile, struct dwz_file *, LONGEST);
1473
1474 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1475                                               const gdb_byte *,
1476                                               unsigned int *);
1477
1478 static const char *read_dwo_str_index (const struct die_reader_specs *reader,
1479                                        ULONGEST str_index);
1480
1481 static const char *read_stub_str_index (struct dwarf2_cu *cu,
1482                                         ULONGEST str_index);
1483
1484 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1485
1486 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1487                                       struct dwarf2_cu *);
1488
1489 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1490                                                 unsigned int);
1491
1492 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1493                                        struct dwarf2_cu *cu);
1494
1495 static const char *dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu);
1496
1497 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1498                                struct dwarf2_cu *cu);
1499
1500 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1501
1502 static struct die_info *die_specification (struct die_info *die,
1503                                            struct dwarf2_cu **);
1504
1505 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1506                                                 struct dwarf2_cu *cu);
1507
1508 static void dwarf_decode_lines (struct line_header *, const char *,
1509                                 struct dwarf2_cu *, dwarf2_psymtab *,
1510                                 CORE_ADDR, int decode_mapping);
1511
1512 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1513                                   const char *);
1514
1515 static struct symbol *new_symbol (struct die_info *, struct type *,
1516                                   struct dwarf2_cu *, struct symbol * = NULL);
1517
1518 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1519                                 struct dwarf2_cu *);
1520
1521 static void dwarf2_const_value_attr (const struct attribute *attr,
1522                                      struct type *type,
1523                                      const char *name,
1524                                      struct obstack *obstack,
1525                                      struct dwarf2_cu *cu, LONGEST *value,
1526                                      const gdb_byte **bytes,
1527                                      struct dwarf2_locexpr_baton **baton);
1528
1529 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1530
1531 static int need_gnat_info (struct dwarf2_cu *);
1532
1533 static struct type *die_descriptive_type (struct die_info *,
1534                                           struct dwarf2_cu *);
1535
1536 static void set_descriptive_type (struct type *, struct die_info *,
1537                                   struct dwarf2_cu *);
1538
1539 static struct type *die_containing_type (struct die_info *,
1540                                          struct dwarf2_cu *);
1541
1542 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1543                                      struct dwarf2_cu *);
1544
1545 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1546
1547 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1548
1549 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1550
1551 static char *typename_concat (struct obstack *obs, const char *prefix,
1552                               const char *suffix, int physname,
1553                               struct dwarf2_cu *cu);
1554
1555 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1556
1557 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1558
1559 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1560
1561 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1562
1563 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1564
1565 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1566
1567 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1568                                struct dwarf2_cu *, dwarf2_psymtab *);
1569
1570 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1571    values.  Keep the items ordered with increasing constraints compliance.  */
1572 enum pc_bounds_kind
1573 {
1574   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1575   PC_BOUNDS_NOT_PRESENT,
1576
1577   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1578      were present but they do not form a valid range of PC addresses.  */
1579   PC_BOUNDS_INVALID,
1580
1581   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1582   PC_BOUNDS_RANGES,
1583
1584   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1585   PC_BOUNDS_HIGH_LOW,
1586 };
1587
1588 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1589                                                  CORE_ADDR *, CORE_ADDR *,
1590                                                  struct dwarf2_cu *,
1591                                                  dwarf2_psymtab *);
1592
1593 static void get_scope_pc_bounds (struct die_info *,
1594                                  CORE_ADDR *, CORE_ADDR *,
1595                                  struct dwarf2_cu *);
1596
1597 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1598                                         CORE_ADDR, struct dwarf2_cu *);
1599
1600 static void dwarf2_add_field (struct field_info *, struct die_info *,
1601                               struct dwarf2_cu *);
1602
1603 static void dwarf2_attach_fields_to_type (struct field_info *,
1604                                           struct type *, struct dwarf2_cu *);
1605
1606 static void dwarf2_add_member_fn (struct field_info *,
1607                                   struct die_info *, struct type *,
1608                                   struct dwarf2_cu *);
1609
1610 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1611                                              struct type *,
1612                                              struct dwarf2_cu *);
1613
1614 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1615
1616 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1617
1618 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1619
1620 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1621
1622 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1623
1624 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1625
1626 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1627
1628 static struct type *read_module_type (struct die_info *die,
1629                                       struct dwarf2_cu *cu);
1630
1631 static const char *namespace_name (struct die_info *die,
1632                                    int *is_anonymous, struct dwarf2_cu *);
1633
1634 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1635
1636 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1637
1638 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1639                                                        struct dwarf2_cu *);
1640
1641 static struct die_info *read_die_and_siblings_1
1642   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1643    struct die_info *);
1644
1645 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1646                                                const gdb_byte *info_ptr,
1647                                                const gdb_byte **new_info_ptr,
1648                                                struct die_info *parent);
1649
1650 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1651                                         struct die_info **, const gdb_byte *,
1652                                         int);
1653
1654 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1655                                       struct die_info **, const gdb_byte *);
1656
1657 static void process_die (struct die_info *, struct dwarf2_cu *);
1658
1659 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1660                                              struct obstack *);
1661
1662 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1663
1664 static const char *dwarf2_full_name (const char *name,
1665                                      struct die_info *die,
1666                                      struct dwarf2_cu *cu);
1667
1668 static const char *dwarf2_physname (const char *name, struct die_info *die,
1669                                     struct dwarf2_cu *cu);
1670
1671 static struct die_info *dwarf2_extension (struct die_info *die,
1672                                           struct dwarf2_cu **);
1673
1674 static const char *dwarf_tag_name (unsigned int);
1675
1676 static const char *dwarf_attr_name (unsigned int);
1677
1678 static const char *dwarf_unit_type_name (int unit_type);
1679
1680 static const char *dwarf_form_name (unsigned int);
1681
1682 static const char *dwarf_bool_name (unsigned int);
1683
1684 static const char *dwarf_type_encoding_name (unsigned int);
1685
1686 static struct die_info *sibling_die (struct die_info *);
1687
1688 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1689
1690 static void dump_die_for_error (struct die_info *);
1691
1692 static void dump_die_1 (struct ui_file *, int level, int max_level,
1693                         struct die_info *);
1694
1695 /*static*/ void dump_die (struct die_info *, int max_level);
1696
1697 static void store_in_ref_table (struct die_info *,
1698                                 struct dwarf2_cu *);
1699
1700 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1701
1702 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1703
1704 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1705                                                const struct attribute *,
1706                                                struct dwarf2_cu **);
1707
1708 static struct die_info *follow_die_ref (struct die_info *,
1709                                         const struct attribute *,
1710                                         struct dwarf2_cu **);
1711
1712 static struct die_info *follow_die_sig (struct die_info *,
1713                                         const struct attribute *,
1714                                         struct dwarf2_cu **);
1715
1716 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1717                                          struct dwarf2_cu *);
1718
1719 static struct type *get_DW_AT_signature_type (struct die_info *,
1720                                               const struct attribute *,
1721                                               struct dwarf2_cu *);
1722
1723 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1724
1725 static void read_signatured_type (struct signatured_type *);
1726
1727 static int attr_to_dynamic_prop (const struct attribute *attr,
1728                                  struct die_info *die, struct dwarf2_cu *cu,
1729                                  struct dynamic_prop *prop, struct type *type);
1730
1731 /* memory allocation interface */
1732
1733 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1734
1735 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1736
1737 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1738
1739 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1740                                    struct dwarf2_loclist_baton *baton,
1741                                    const struct attribute *attr);
1742
1743 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1744                                          struct symbol *sym,
1745                                          struct dwarf2_cu *cu,
1746                                          int is_block);
1747
1748 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1749                                      const gdb_byte *info_ptr,
1750                                      struct abbrev_info *abbrev);
1751
1752 static hashval_t partial_die_hash (const void *item);
1753
1754 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1755
1756 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1757   (sect_offset sect_off, unsigned int offset_in_dwz,
1758    struct dwarf2_per_objfile *dwarf2_per_objfile);
1759
1760 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1761                                    struct die_info *comp_unit_die,
1762                                    enum language pretend_language);
1763
1764 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1765
1766 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1767
1768 static struct type *set_die_type (struct die_info *, struct type *,
1769                                   struct dwarf2_cu *);
1770
1771 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1772
1773 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1774
1775 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1776                                  enum language);
1777
1778 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1779                                     enum language);
1780
1781 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1782                                     enum language);
1783
1784 static void dwarf2_add_dependence (struct dwarf2_cu *,
1785                                    struct dwarf2_per_cu_data *);
1786
1787 static void dwarf2_mark (struct dwarf2_cu *);
1788
1789 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1790
1791 static struct type *get_die_type_at_offset (sect_offset,
1792                                             struct dwarf2_per_cu_data *);
1793
1794 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1795
1796 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1797                              enum language pretend_language);
1798
1799 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1800
1801 static struct type *dwarf2_per_cu_addr_type (struct dwarf2_per_cu_data *per_cu);
1802 static struct type *dwarf2_per_cu_addr_sized_int_type
1803         (struct dwarf2_per_cu_data *per_cu, bool unsigned_p);
1804 static struct type *dwarf2_per_cu_int_type
1805         (struct dwarf2_per_cu_data *per_cu, int size_in_bytes,
1806          bool unsigned_p);
1807
1808 /* Class, the destructor of which frees all allocated queue entries.  This
1809    will only have work to do if an error was thrown while processing the
1810    dwarf.  If no error was thrown then the queue entries should have all
1811    been processed, and freed, as we went along.  */
1812
1813 class dwarf2_queue_guard
1814 {
1815 public:
1816   explicit dwarf2_queue_guard (dwarf2_per_objfile *per_objfile)
1817     : m_per_objfile (per_objfile)
1818   {
1819   }
1820
1821   /* Free any entries remaining on the queue.  There should only be
1822      entries left if we hit an error while processing the dwarf.  */
1823   ~dwarf2_queue_guard ()
1824   {
1825     /* Ensure that no memory is allocated by the queue.  */
1826     std::queue<dwarf2_queue_item> empty;
1827     std::swap (m_per_objfile->queue, empty);
1828   }
1829
1830   DISABLE_COPY_AND_ASSIGN (dwarf2_queue_guard);
1831
1832 private:
1833   dwarf2_per_objfile *m_per_objfile;
1834 };
1835
1836 dwarf2_queue_item::~dwarf2_queue_item ()
1837 {
1838   /* Anything still marked queued is likely to be in an
1839      inconsistent state, so discard it.  */
1840   if (per_cu->queued)
1841     {
1842       if (per_cu->cu != NULL)
1843         free_one_cached_comp_unit (per_cu);
1844       per_cu->queued = 0;
1845     }
1846 }
1847
1848 /* The return type of find_file_and_directory.  Note, the enclosed
1849    string pointers are only valid while this object is valid.  */
1850
1851 struct file_and_directory
1852 {
1853   /* The filename.  This is never NULL.  */
1854   const char *name;
1855
1856   /* The compilation directory.  NULL if not known.  If we needed to
1857      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1858      points directly to the DW_AT_comp_dir string attribute owned by
1859      the obstack that owns the DIE.  */
1860   const char *comp_dir;
1861
1862   /* If we needed to build a new string for comp_dir, this is what
1863      owns the storage.  */
1864   std::string comp_dir_storage;
1865 };
1866
1867 static file_and_directory find_file_and_directory (struct die_info *die,
1868                                                    struct dwarf2_cu *cu);
1869
1870 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1871 enum class rcuh_kind { COMPILE, TYPE };
1872
1873 static const gdb_byte *read_and_check_comp_unit_head
1874   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1875    struct comp_unit_head *header,
1876    struct dwarf2_section_info *section,
1877    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1878    rcuh_kind section_kind);
1879
1880 static htab_up allocate_signatured_type_table (struct objfile *objfile);
1881
1882 static htab_up allocate_dwo_unit_table (struct objfile *objfile);
1883
1884 static struct dwo_unit *lookup_dwo_unit_in_dwp
1885   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1886    struct dwp_file *dwp_file, const char *comp_dir,
1887    ULONGEST signature, int is_debug_types);
1888
1889 static struct dwp_file *get_dwp_file
1890   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1891
1892 static struct dwo_unit *lookup_dwo_comp_unit
1893   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1894
1895 static struct dwo_unit *lookup_dwo_type_unit
1896   (struct signatured_type *, const char *, const char *);
1897
1898 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1899
1900 /* A unique pointer to a dwo_file.  */
1901
1902 typedef std::unique_ptr<struct dwo_file> dwo_file_up;
1903
1904 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1905
1906 static void check_producer (struct dwarf2_cu *cu);
1907
1908 static void free_line_header_voidp (void *arg);
1909 \f
1910 /* Various complaints about symbol reading that don't abort the process.  */
1911
1912 static void
1913 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1914 {
1915   complaint (_("statement list doesn't fit in .debug_line section"));
1916 }
1917
1918 static void
1919 dwarf2_debug_line_missing_file_complaint (void)
1920 {
1921   complaint (_(".debug_line section has line data without a file"));
1922 }
1923
1924 static void
1925 dwarf2_debug_line_missing_end_sequence_complaint (void)
1926 {
1927   complaint (_(".debug_line section has line "
1928                "program sequence without an end"));
1929 }
1930
1931 static void
1932 dwarf2_complex_location_expr_complaint (void)
1933 {
1934   complaint (_("location expression too complex"));
1935 }
1936
1937 static void
1938 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1939                                               int arg3)
1940 {
1941   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
1942              arg1, arg2, arg3);
1943 }
1944
1945 static void
1946 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1947 {
1948   complaint (_("debug info runs off end of %s section"
1949                " [in module %s]"),
1950              section->get_name (),
1951              section->get_file_name ());
1952 }
1953
1954 static void
1955 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1956 {
1957   complaint (_("macro debug info contains a "
1958                "malformed macro definition:\n`%s'"),
1959              arg1);
1960 }
1961
1962 static void
1963 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1964 {
1965   complaint (_("invalid attribute class or form for '%s' in '%s'"),
1966              arg1, arg2);
1967 }
1968
1969 /* Hash function for line_header_hash.  */
1970
1971 static hashval_t
1972 line_header_hash (const struct line_header *ofs)
1973 {
1974   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
1975 }
1976
1977 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
1978
1979 static hashval_t
1980 line_header_hash_voidp (const void *item)
1981 {
1982   const struct line_header *ofs = (const struct line_header *) item;
1983
1984   return line_header_hash (ofs);
1985 }
1986
1987 /* Equality function for line_header_hash.  */
1988
1989 static int
1990 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
1991 {
1992   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
1993   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
1994
1995   return (ofs_lhs->sect_off == ofs_rhs->sect_off
1996           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
1997 }
1998
1999 \f
2000
2001 /* See declaration.  */
2002
2003 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2004                                         const dwarf2_debug_sections *names,
2005                                         bool can_copy_)
2006   : objfile (objfile_),
2007     can_copy (can_copy_)
2008 {
2009   if (names == NULL)
2010     names = &dwarf2_elf_names;
2011
2012   bfd *obfd = objfile->obfd;
2013
2014   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2015     locate_sections (obfd, sec, *names);
2016 }
2017
2018 dwarf2_per_objfile::~dwarf2_per_objfile ()
2019 {
2020   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2021   free_cached_comp_units ();
2022
2023   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2024     per_cu->imported_symtabs_free ();
2025
2026   for (signatured_type *sig_type : all_type_units)
2027     sig_type->per_cu.imported_symtabs_free ();
2028
2029   /* Everything else should be on the objfile obstack.  */
2030 }
2031
2032 /* See declaration.  */
2033
2034 void
2035 dwarf2_per_objfile::free_cached_comp_units ()
2036 {
2037   dwarf2_per_cu_data *per_cu = read_in_chain;
2038   dwarf2_per_cu_data **last_chain = &read_in_chain;
2039   while (per_cu != NULL)
2040     {
2041       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2042
2043       delete per_cu->cu;
2044       *last_chain = next_cu;
2045       per_cu = next_cu;
2046     }
2047 }
2048
2049 /* A helper class that calls free_cached_comp_units on
2050    destruction.  */
2051
2052 class free_cached_comp_units
2053 {
2054 public:
2055
2056   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2057     : m_per_objfile (per_objfile)
2058   {
2059   }
2060
2061   ~free_cached_comp_units ()
2062   {
2063     m_per_objfile->free_cached_comp_units ();
2064   }
2065
2066   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2067
2068 private:
2069
2070   dwarf2_per_objfile *m_per_objfile;
2071 };
2072
2073 /* Try to locate the sections we need for DWARF 2 debugging
2074    information and return true if we have enough to do something.
2075    NAMES points to the dwarf2 section names, or is NULL if the standard
2076    ELF names are used.  CAN_COPY is true for formats where symbol
2077    interposition is possible and so symbol values must follow copy
2078    relocation rules.  */
2079
2080 int
2081 dwarf2_has_info (struct objfile *objfile,
2082                  const struct dwarf2_debug_sections *names,
2083                  bool can_copy)
2084 {
2085   if (objfile->flags & OBJF_READNEVER)
2086     return 0;
2087
2088   struct dwarf2_per_objfile *dwarf2_per_objfile
2089     = get_dwarf2_per_objfile (objfile);
2090
2091   if (dwarf2_per_objfile == NULL)
2092     dwarf2_per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile,
2093                                                           names,
2094                                                           can_copy);
2095
2096   return (!dwarf2_per_objfile->info.is_virtual
2097           && dwarf2_per_objfile->info.s.section != NULL
2098           && !dwarf2_per_objfile->abbrev.is_virtual
2099           && dwarf2_per_objfile->abbrev.s.section != NULL);
2100 }
2101
2102 /* When loading sections, we look either for uncompressed section or for
2103    compressed section names.  */
2104
2105 static int
2106 section_is_p (const char *section_name,
2107               const struct dwarf2_section_names *names)
2108 {
2109   if (names->normal != NULL
2110       && strcmp (section_name, names->normal) == 0)
2111     return 1;
2112   if (names->compressed != NULL
2113       && strcmp (section_name, names->compressed) == 0)
2114     return 1;
2115   return 0;
2116 }
2117
2118 /* See declaration.  */
2119
2120 void
2121 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2122                                      const dwarf2_debug_sections &names)
2123 {
2124   flagword aflag = bfd_section_flags (sectp);
2125
2126   if ((aflag & SEC_HAS_CONTENTS) == 0)
2127     {
2128     }
2129   else if (elf_section_data (sectp)->this_hdr.sh_size
2130            > bfd_get_file_size (abfd))
2131     {
2132       bfd_size_type size = elf_section_data (sectp)->this_hdr.sh_size;
2133       warning (_("Discarding section %s which has a section size (%s"
2134                  ") larger than the file size [in module %s]"),
2135                bfd_section_name (sectp), phex_nz (size, sizeof (size)),
2136                bfd_get_filename (abfd));
2137     }
2138   else if (section_is_p (sectp->name, &names.info))
2139     {
2140       this->info.s.section = sectp;
2141       this->info.size = bfd_section_size (sectp);
2142     }
2143   else if (section_is_p (sectp->name, &names.abbrev))
2144     {
2145       this->abbrev.s.section = sectp;
2146       this->abbrev.size = bfd_section_size (sectp);
2147     }
2148   else if (section_is_p (sectp->name, &names.line))
2149     {
2150       this->line.s.section = sectp;
2151       this->line.size = bfd_section_size (sectp);
2152     }
2153   else if (section_is_p (sectp->name, &names.loc))
2154     {
2155       this->loc.s.section = sectp;
2156       this->loc.size = bfd_section_size (sectp);
2157     }
2158   else if (section_is_p (sectp->name, &names.loclists))
2159     {
2160       this->loclists.s.section = sectp;
2161       this->loclists.size = bfd_section_size (sectp);
2162     }
2163   else if (section_is_p (sectp->name, &names.macinfo))
2164     {
2165       this->macinfo.s.section = sectp;
2166       this->macinfo.size = bfd_section_size (sectp);
2167     }
2168   else if (section_is_p (sectp->name, &names.macro))
2169     {
2170       this->macro.s.section = sectp;
2171       this->macro.size = bfd_section_size (sectp);
2172     }
2173   else if (section_is_p (sectp->name, &names.str))
2174     {
2175       this->str.s.section = sectp;
2176       this->str.size = bfd_section_size (sectp);
2177     }
2178   else if (section_is_p (sectp->name, &names.str_offsets))
2179     {
2180       this->str_offsets.s.section = sectp;
2181       this->str_offsets.size = bfd_section_size (sectp);
2182     }
2183   else if (section_is_p (sectp->name, &names.line_str))
2184     {
2185       this->line_str.s.section = sectp;
2186       this->line_str.size = bfd_section_size (sectp);
2187     }
2188   else if (section_is_p (sectp->name, &names.addr))
2189     {
2190       this->addr.s.section = sectp;
2191       this->addr.size = bfd_section_size (sectp);
2192     }
2193   else if (section_is_p (sectp->name, &names.frame))
2194     {
2195       this->frame.s.section = sectp;
2196       this->frame.size = bfd_section_size (sectp);
2197     }
2198   else if (section_is_p (sectp->name, &names.eh_frame))
2199     {
2200       this->eh_frame.s.section = sectp;
2201       this->eh_frame.size = bfd_section_size (sectp);
2202     }
2203   else if (section_is_p (sectp->name, &names.ranges))
2204     {
2205       this->ranges.s.section = sectp;
2206       this->ranges.size = bfd_section_size (sectp);
2207     }
2208   else if (section_is_p (sectp->name, &names.rnglists))
2209     {
2210       this->rnglists.s.section = sectp;
2211       this->rnglists.size = bfd_section_size (sectp);
2212     }
2213   else if (section_is_p (sectp->name, &names.types))
2214     {
2215       struct dwarf2_section_info type_section;
2216
2217       memset (&type_section, 0, sizeof (type_section));
2218       type_section.s.section = sectp;
2219       type_section.size = bfd_section_size (sectp);
2220
2221       this->types.push_back (type_section);
2222     }
2223   else if (section_is_p (sectp->name, &names.gdb_index))
2224     {
2225       this->gdb_index.s.section = sectp;
2226       this->gdb_index.size = bfd_section_size (sectp);
2227     }
2228   else if (section_is_p (sectp->name, &names.debug_names))
2229     {
2230       this->debug_names.s.section = sectp;
2231       this->debug_names.size = bfd_section_size (sectp);
2232     }
2233   else if (section_is_p (sectp->name, &names.debug_aranges))
2234     {
2235       this->debug_aranges.s.section = sectp;
2236       this->debug_aranges.size = bfd_section_size (sectp);
2237     }
2238
2239   if ((bfd_section_flags (sectp) & (SEC_LOAD | SEC_ALLOC))
2240       && bfd_section_vma (sectp) == 0)
2241     this->has_section_at_zero = true;
2242 }
2243
2244 /* A helper function that returns the size of a section in a safe way.
2245    If you are positive that the section has been read before using the
2246    size, then it is safe to refer to the dwarf2_section_info object's
2247    "size" field directly.  In other cases, you must call this
2248    function, because for compressed sections the size field is not set
2249    correctly until the section has been read.  */
2250
2251 static bfd_size_type
2252 dwarf2_section_size (struct objfile *objfile,
2253                      struct dwarf2_section_info *info)
2254 {
2255   if (!info->readin)
2256     info->read (objfile);
2257   return info->size;
2258 }
2259
2260 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2261    SECTION_NAME.  */
2262
2263 void
2264 dwarf2_get_section_info (struct objfile *objfile,
2265                          enum dwarf2_section_enum sect,
2266                          asection **sectp, const gdb_byte **bufp,
2267                          bfd_size_type *sizep)
2268 {
2269   struct dwarf2_per_objfile *data = dwarf2_objfile_data_key.get (objfile);
2270   struct dwarf2_section_info *info;
2271
2272   /* We may see an objfile without any DWARF, in which case we just
2273      return nothing.  */
2274   if (data == NULL)
2275     {
2276       *sectp = NULL;
2277       *bufp = NULL;
2278       *sizep = 0;
2279       return;
2280     }
2281   switch (sect)
2282     {
2283     case DWARF2_DEBUG_FRAME:
2284       info = &data->frame;
2285       break;
2286     case DWARF2_EH_FRAME:
2287       info = &data->eh_frame;
2288       break;
2289     default:
2290       gdb_assert_not_reached ("unexpected section");
2291     }
2292
2293   info->read (objfile);
2294
2295   *sectp = info->get_bfd_section ();
2296   *bufp = info->buffer;
2297   *sizep = info->size;
2298 }
2299
2300 /* A helper function to find the sections for a .dwz file.  */
2301
2302 static void
2303 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2304 {
2305   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2306
2307   /* Note that we only support the standard ELF names, because .dwz
2308      is ELF-only (at the time of writing).  */
2309   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2310     {
2311       dwz_file->abbrev.s.section = sectp;
2312       dwz_file->abbrev.size = bfd_section_size (sectp);
2313     }
2314   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2315     {
2316       dwz_file->info.s.section = sectp;
2317       dwz_file->info.size = bfd_section_size (sectp);
2318     }
2319   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2320     {
2321       dwz_file->str.s.section = sectp;
2322       dwz_file->str.size = bfd_section_size (sectp);
2323     }
2324   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2325     {
2326       dwz_file->line.s.section = sectp;
2327       dwz_file->line.size = bfd_section_size (sectp);
2328     }
2329   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2330     {
2331       dwz_file->macro.s.section = sectp;
2332       dwz_file->macro.size = bfd_section_size (sectp);
2333     }
2334   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2335     {
2336       dwz_file->gdb_index.s.section = sectp;
2337       dwz_file->gdb_index.size = bfd_section_size (sectp);
2338     }
2339   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2340     {
2341       dwz_file->debug_names.s.section = sectp;
2342       dwz_file->debug_names.size = bfd_section_size (sectp);
2343     }
2344 }
2345
2346 /* See dwarf2read.h.  */
2347
2348 struct dwz_file *
2349 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2350 {
2351   const char *filename;
2352   bfd_size_type buildid_len_arg;
2353   size_t buildid_len;
2354   bfd_byte *buildid;
2355
2356   if (dwarf2_per_objfile->dwz_file != NULL)
2357     return dwarf2_per_objfile->dwz_file.get ();
2358
2359   bfd_set_error (bfd_error_no_error);
2360   gdb::unique_xmalloc_ptr<char> data
2361     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2362                                   &buildid_len_arg, &buildid));
2363   if (data == NULL)
2364     {
2365       if (bfd_get_error () == bfd_error_no_error)
2366         return NULL;
2367       error (_("could not read '.gnu_debugaltlink' section: %s"),
2368              bfd_errmsg (bfd_get_error ()));
2369     }
2370
2371   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2372
2373   buildid_len = (size_t) buildid_len_arg;
2374
2375   filename = data.get ();
2376
2377   std::string abs_storage;
2378   if (!IS_ABSOLUTE_PATH (filename))
2379     {
2380       gdb::unique_xmalloc_ptr<char> abs
2381         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2382
2383       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2384       filename = abs_storage.c_str ();
2385     }
2386
2387   /* First try the file name given in the section.  If that doesn't
2388      work, try to use the build-id instead.  */
2389   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2390   if (dwz_bfd != NULL)
2391     {
2392       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2393         dwz_bfd.reset (nullptr);
2394     }
2395
2396   if (dwz_bfd == NULL)
2397     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2398
2399   if (dwz_bfd == NULL)
2400     error (_("could not find '.gnu_debugaltlink' file for %s"),
2401            objfile_name (dwarf2_per_objfile->objfile));
2402
2403   std::unique_ptr<struct dwz_file> result
2404     (new struct dwz_file (std::move (dwz_bfd)));
2405
2406   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2407                          result.get ());
2408
2409   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2410                             result->dwz_bfd.get ());
2411   dwarf2_per_objfile->dwz_file = std::move (result);
2412   return dwarf2_per_objfile->dwz_file.get ();
2413 }
2414 \f
2415 /* DWARF quick_symbols_functions support.  */
2416
2417 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2418    unique line tables, so we maintain a separate table of all .debug_line
2419    derived entries to support the sharing.
2420    All the quick functions need is the list of file names.  We discard the
2421    line_header when we're done and don't need to record it here.  */
2422 struct quick_file_names
2423 {
2424   /* The data used to construct the hash key.  */
2425   struct stmt_list_hash hash;
2426
2427   /* The number of entries in file_names, real_names.  */
2428   unsigned int num_file_names;
2429
2430   /* The file names from the line table, after being run through
2431      file_full_name.  */
2432   const char **file_names;
2433
2434   /* The file names from the line table after being run through
2435      gdb_realpath.  These are computed lazily.  */
2436   const char **real_names;
2437 };
2438
2439 /* When using the index (and thus not using psymtabs), each CU has an
2440    object of this type.  This is used to hold information needed by
2441    the various "quick" methods.  */
2442 struct dwarf2_per_cu_quick_data
2443 {
2444   /* The file table.  This can be NULL if there was no file table
2445      or it's currently not read in.
2446      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2447   struct quick_file_names *file_names;
2448
2449   /* The corresponding symbol table.  This is NULL if symbols for this
2450      CU have not yet been read.  */
2451   struct compunit_symtab *compunit_symtab;
2452
2453   /* A temporary mark bit used when iterating over all CUs in
2454      expand_symtabs_matching.  */
2455   unsigned int mark : 1;
2456
2457   /* True if we've tried to read the file table and found there isn't one.
2458      There will be no point in trying to read it again next time.  */
2459   unsigned int no_file_data : 1;
2460 };
2461
2462 /* Utility hash function for a stmt_list_hash.  */
2463
2464 static hashval_t
2465 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2466 {
2467   hashval_t v = 0;
2468
2469   if (stmt_list_hash->dwo_unit != NULL)
2470     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2471   v += to_underlying (stmt_list_hash->line_sect_off);
2472   return v;
2473 }
2474
2475 /* Utility equality function for a stmt_list_hash.  */
2476
2477 static int
2478 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2479                     const struct stmt_list_hash *rhs)
2480 {
2481   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2482     return 0;
2483   if (lhs->dwo_unit != NULL
2484       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2485     return 0;
2486
2487   return lhs->line_sect_off == rhs->line_sect_off;
2488 }
2489
2490 /* Hash function for a quick_file_names.  */
2491
2492 static hashval_t
2493 hash_file_name_entry (const void *e)
2494 {
2495   const struct quick_file_names *file_data
2496     = (const struct quick_file_names *) e;
2497
2498   return hash_stmt_list_entry (&file_data->hash);
2499 }
2500
2501 /* Equality function for a quick_file_names.  */
2502
2503 static int
2504 eq_file_name_entry (const void *a, const void *b)
2505 {
2506   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2507   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2508
2509   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2510 }
2511
2512 /* Delete function for a quick_file_names.  */
2513
2514 static void
2515 delete_file_name_entry (void *e)
2516 {
2517   struct quick_file_names *file_data = (struct quick_file_names *) e;
2518   int i;
2519
2520   for (i = 0; i < file_data->num_file_names; ++i)
2521     {
2522       xfree ((void*) file_data->file_names[i]);
2523       if (file_data->real_names)
2524         xfree ((void*) file_data->real_names[i]);
2525     }
2526
2527   /* The space for the struct itself lives on objfile_obstack,
2528      so we don't free it here.  */
2529 }
2530
2531 /* Create a quick_file_names hash table.  */
2532
2533 static htab_up
2534 create_quick_file_names_table (unsigned int nr_initial_entries)
2535 {
2536   return htab_up (htab_create_alloc (nr_initial_entries,
2537                                      hash_file_name_entry, eq_file_name_entry,
2538                                      delete_file_name_entry, xcalloc, xfree));
2539 }
2540
2541 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2542    have to be created afterwards.  You should call age_cached_comp_units after
2543    processing PER_CU->CU.  dw2_setup must have been already called.  */
2544
2545 static void
2546 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2547 {
2548   if (per_cu->is_debug_types)
2549     load_full_type_unit (per_cu);
2550   else
2551     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2552
2553   if (per_cu->cu == NULL)
2554     return;  /* Dummy CU.  */
2555
2556   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2557 }
2558
2559 /* Read in the symbols for PER_CU.  */
2560
2561 static void
2562 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2563 {
2564   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2565
2566   /* Skip type_unit_groups, reading the type units they contain
2567      is handled elsewhere.  */
2568   if (IS_TYPE_UNIT_GROUP (per_cu))
2569     return;
2570
2571   /* The destructor of dwarf2_queue_guard frees any entries left on
2572      the queue.  After this point we're guaranteed to leave this function
2573      with the dwarf queue empty.  */
2574   dwarf2_queue_guard q_guard (dwarf2_per_objfile);
2575
2576   if (dwarf2_per_objfile->using_index
2577       ? per_cu->v.quick->compunit_symtab == NULL
2578       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2579     {
2580       queue_comp_unit (per_cu, language_minimal);
2581       load_cu (per_cu, skip_partial);
2582
2583       /* If we just loaded a CU from a DWO, and we're working with an index
2584          that may badly handle TUs, load all the TUs in that DWO as well.
2585          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2586       if (!per_cu->is_debug_types
2587           && per_cu->cu != NULL
2588           && per_cu->cu->dwo_unit != NULL
2589           && dwarf2_per_objfile->index_table != NULL
2590           && dwarf2_per_objfile->index_table->version <= 7
2591           /* DWP files aren't supported yet.  */
2592           && get_dwp_file (dwarf2_per_objfile) == NULL)
2593         queue_and_load_all_dwo_tus (per_cu);
2594     }
2595
2596   process_queue (dwarf2_per_objfile);
2597
2598   /* Age the cache, releasing compilation units that have not
2599      been used recently.  */
2600   age_cached_comp_units (dwarf2_per_objfile);
2601 }
2602
2603 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2604    the objfile from which this CU came.  Returns the resulting symbol
2605    table.  */
2606
2607 static struct compunit_symtab *
2608 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2609 {
2610   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2611
2612   gdb_assert (dwarf2_per_objfile->using_index);
2613   if (!per_cu->v.quick->compunit_symtab)
2614     {
2615       free_cached_comp_units freer (dwarf2_per_objfile);
2616       scoped_restore decrementer = increment_reading_symtab ();
2617       dw2_do_instantiate_symtab (per_cu, skip_partial);
2618       process_cu_includes (dwarf2_per_objfile);
2619     }
2620
2621   return per_cu->v.quick->compunit_symtab;
2622 }
2623
2624 /* See declaration.  */
2625
2626 dwarf2_per_cu_data *
2627 dwarf2_per_objfile::get_cutu (int index)
2628 {
2629   if (index >= this->all_comp_units.size ())
2630     {
2631       index -= this->all_comp_units.size ();
2632       gdb_assert (index < this->all_type_units.size ());
2633       return &this->all_type_units[index]->per_cu;
2634     }
2635
2636   return this->all_comp_units[index];
2637 }
2638
2639 /* See declaration.  */
2640
2641 dwarf2_per_cu_data *
2642 dwarf2_per_objfile::get_cu (int index)
2643 {
2644   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2645
2646   return this->all_comp_units[index];
2647 }
2648
2649 /* See declaration.  */
2650
2651 signatured_type *
2652 dwarf2_per_objfile::get_tu (int index)
2653 {
2654   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2655
2656   return this->all_type_units[index];
2657 }
2658
2659 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2660    objfile_obstack, and constructed with the specified field
2661    values.  */
2662
2663 static dwarf2_per_cu_data *
2664 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2665                           struct dwarf2_section_info *section,
2666                           int is_dwz,
2667                           sect_offset sect_off, ULONGEST length)
2668 {
2669   struct objfile *objfile = dwarf2_per_objfile->objfile;
2670   dwarf2_per_cu_data *the_cu
2671     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2672                      struct dwarf2_per_cu_data);
2673   the_cu->sect_off = sect_off;
2674   the_cu->length = length;
2675   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2676   the_cu->section = section;
2677   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2678                                    struct dwarf2_per_cu_quick_data);
2679   the_cu->is_dwz = is_dwz;
2680   return the_cu;
2681 }
2682
2683 /* A helper for create_cus_from_index that handles a given list of
2684    CUs.  */
2685
2686 static void
2687 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2688                             const gdb_byte *cu_list, offset_type n_elements,
2689                             struct dwarf2_section_info *section,
2690                             int is_dwz)
2691 {
2692   for (offset_type i = 0; i < n_elements; i += 2)
2693     {
2694       gdb_static_assert (sizeof (ULONGEST) >= 8);
2695
2696       sect_offset sect_off
2697         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2698       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2699       cu_list += 2 * 8;
2700
2701       dwarf2_per_cu_data *per_cu
2702         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2703                                      sect_off, length);
2704       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2705     }
2706 }
2707
2708 /* Read the CU list from the mapped index, and use it to create all
2709    the CU objects for this objfile.  */
2710
2711 static void
2712 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
2713                        const gdb_byte *cu_list, offset_type cu_list_elements,
2714                        const gdb_byte *dwz_list, offset_type dwz_elements)
2715 {
2716   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
2717   dwarf2_per_objfile->all_comp_units.reserve
2718     ((cu_list_elements + dwz_elements) / 2);
2719
2720   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
2721                               &dwarf2_per_objfile->info, 0);
2722
2723   if (dwz_elements == 0)
2724     return;
2725
2726   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
2727   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
2728                               &dwz->info, 1);
2729 }
2730
2731 /* Create the signatured type hash table from the index.  */
2732
2733 static void
2734 create_signatured_type_table_from_index
2735   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2736    struct dwarf2_section_info *section,
2737    const gdb_byte *bytes,
2738    offset_type elements)
2739 {
2740   struct objfile *objfile = dwarf2_per_objfile->objfile;
2741
2742   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
2743   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
2744
2745   htab_up sig_types_hash = allocate_signatured_type_table (objfile);
2746
2747   for (offset_type i = 0; i < elements; i += 3)
2748     {
2749       struct signatured_type *sig_type;
2750       ULONGEST signature;
2751       void **slot;
2752       cu_offset type_offset_in_tu;
2753
2754       gdb_static_assert (sizeof (ULONGEST) >= 8);
2755       sect_offset sect_off
2756         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2757       type_offset_in_tu
2758         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
2759                                                 BFD_ENDIAN_LITTLE);
2760       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2761       bytes += 3 * 8;
2762
2763       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2764                                  struct signatured_type);
2765       sig_type->signature = signature;
2766       sig_type->type_offset_in_tu = type_offset_in_tu;
2767       sig_type->per_cu.is_debug_types = 1;
2768       sig_type->per_cu.section = section;
2769       sig_type->per_cu.sect_off = sect_off;
2770       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
2771       sig_type->per_cu.v.quick
2772         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2773                           struct dwarf2_per_cu_quick_data);
2774
2775       slot = htab_find_slot (sig_types_hash.get (), sig_type, INSERT);
2776       *slot = sig_type;
2777
2778       dwarf2_per_objfile->all_type_units.push_back (sig_type);
2779     }
2780
2781   dwarf2_per_objfile->signatured_types = std::move (sig_types_hash);
2782 }
2783
2784 /* Create the signatured type hash table from .debug_names.  */
2785
2786 static void
2787 create_signatured_type_table_from_debug_names
2788   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2789    const mapped_debug_names &map,
2790    struct dwarf2_section_info *section,
2791    struct dwarf2_section_info *abbrev_section)
2792 {
2793   struct objfile *objfile = dwarf2_per_objfile->objfile;
2794
2795   section->read (objfile);
2796   abbrev_section->read (objfile);
2797
2798   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
2799   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
2800
2801   htab_up sig_types_hash = allocate_signatured_type_table (objfile);
2802
2803   for (uint32_t i = 0; i < map.tu_count; ++i)
2804     {
2805       struct signatured_type *sig_type;
2806       void **slot;
2807
2808       sect_offset sect_off
2809         = (sect_offset) (extract_unsigned_integer
2810                          (map.tu_table_reordered + i * map.offset_size,
2811                           map.offset_size,
2812                           map.dwarf5_byte_order));
2813
2814       comp_unit_head cu_header;
2815       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
2816                                      abbrev_section,
2817                                      section->buffer + to_underlying (sect_off),
2818                                      rcuh_kind::TYPE);
2819
2820       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2821                                  struct signatured_type);
2822       sig_type->signature = cu_header.signature;
2823       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
2824       sig_type->per_cu.is_debug_types = 1;
2825       sig_type->per_cu.section = section;
2826       sig_type->per_cu.sect_off = sect_off;
2827       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
2828       sig_type->per_cu.v.quick
2829         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2830                           struct dwarf2_per_cu_quick_data);
2831
2832       slot = htab_find_slot (sig_types_hash.get (), sig_type, INSERT);
2833       *slot = sig_type;
2834
2835       dwarf2_per_objfile->all_type_units.push_back (sig_type);
2836     }
2837
2838   dwarf2_per_objfile->signatured_types = std::move (sig_types_hash);
2839 }
2840
2841 /* Read the address map data from the mapped index, and use it to
2842    populate the objfile's psymtabs_addrmap.  */
2843
2844 static void
2845 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
2846                            struct mapped_index *index)
2847 {
2848   struct objfile *objfile = dwarf2_per_objfile->objfile;
2849   struct gdbarch *gdbarch = get_objfile_arch (objfile);
2850   const gdb_byte *iter, *end;
2851   struct addrmap *mutable_map;
2852   CORE_ADDR baseaddr;
2853
2854   auto_obstack temp_obstack;
2855
2856   mutable_map = addrmap_create_mutable (&temp_obstack);
2857
2858   iter = index->address_table.data ();
2859   end = iter + index->address_table.size ();
2860
2861   baseaddr = objfile->text_section_offset ();
2862
2863   while (iter < end)
2864     {
2865       ULONGEST hi, lo, cu_index;
2866       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2867       iter += 8;
2868       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2869       iter += 8;
2870       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2871       iter += 4;
2872
2873       if (lo > hi)
2874         {
2875           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
2876                      hex_string (lo), hex_string (hi));
2877           continue;
2878         }
2879
2880       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
2881         {
2882           complaint (_(".gdb_index address table has invalid CU number %u"),
2883                      (unsigned) cu_index);
2884           continue;
2885         }
2886
2887       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
2888       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
2889       addrmap_set_empty (mutable_map, lo, hi - 1,
2890                          dwarf2_per_objfile->get_cu (cu_index));
2891     }
2892
2893   objfile->partial_symtabs->psymtabs_addrmap
2894     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
2895 }
2896
2897 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
2898    populate the objfile's psymtabs_addrmap.  */
2899
2900 static void
2901 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
2902                              struct dwarf2_section_info *section)
2903 {
2904   struct objfile *objfile = dwarf2_per_objfile->objfile;
2905   bfd *abfd = objfile->obfd;
2906   struct gdbarch *gdbarch = get_objfile_arch (objfile);
2907   const CORE_ADDR baseaddr = objfile->text_section_offset ();
2908
2909   auto_obstack temp_obstack;
2910   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
2911
2912   std::unordered_map<sect_offset,
2913                      dwarf2_per_cu_data *,
2914                      gdb::hash_enum<sect_offset>>
2915     debug_info_offset_to_per_cu;
2916   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
2917     {
2918       const auto insertpair
2919         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
2920       if (!insertpair.second)
2921         {
2922           warning (_("Section .debug_aranges in %s has duplicate "
2923                      "debug_info_offset %s, ignoring .debug_aranges."),
2924                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
2925           return;
2926         }
2927     }
2928
2929   section->read (objfile);
2930
2931   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
2932
2933   const gdb_byte *addr = section->buffer;
2934
2935   while (addr < section->buffer + section->size)
2936     {
2937       const gdb_byte *const entry_addr = addr;
2938       unsigned int bytes_read;
2939
2940       const LONGEST entry_length = read_initial_length (abfd, addr,
2941                                                         &bytes_read);
2942       addr += bytes_read;
2943
2944       const gdb_byte *const entry_end = addr + entry_length;
2945       const bool dwarf5_is_dwarf64 = bytes_read != 4;
2946       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
2947       if (addr + entry_length > section->buffer + section->size)
2948         {
2949           warning (_("Section .debug_aranges in %s entry at offset %s "
2950                      "length %s exceeds section length %s, "
2951                      "ignoring .debug_aranges."),
2952                    objfile_name (objfile),
2953                    plongest (entry_addr - section->buffer),
2954                    plongest (bytes_read + entry_length),
2955                    pulongest (section->size));
2956           return;
2957         }
2958
2959       /* The version number.  */
2960       const uint16_t version = read_2_bytes (abfd, addr);
2961       addr += 2;
2962       if (version != 2)
2963         {
2964           warning (_("Section .debug_aranges in %s entry at offset %s "
2965                      "has unsupported version %d, ignoring .debug_aranges."),
2966                    objfile_name (objfile),
2967                    plongest (entry_addr - section->buffer), version);
2968           return;
2969         }
2970
2971       const uint64_t debug_info_offset
2972         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
2973       addr += offset_size;
2974       const auto per_cu_it
2975         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
2976       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
2977         {
2978           warning (_("Section .debug_aranges in %s entry at offset %s "
2979                      "debug_info_offset %s does not exists, "
2980                      "ignoring .debug_aranges."),
2981                    objfile_name (objfile),
2982                    plongest (entry_addr - section->buffer),
2983                    pulongest (debug_info_offset));
2984           return;
2985         }
2986       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
2987
2988       const uint8_t address_size = *addr++;
2989       if (address_size < 1 || address_size > 8)
2990         {
2991           warning (_("Section .debug_aranges in %s entry at offset %s "
2992                      "address_size %u is invalid, ignoring .debug_aranges."),
2993                    objfile_name (objfile),
2994                    plongest (entry_addr - section->buffer), address_size);
2995           return;
2996         }
2997
2998       const uint8_t segment_selector_size = *addr++;
2999       if (segment_selector_size != 0)
3000         {
3001           warning (_("Section .debug_aranges in %s entry at offset %s "
3002                      "segment_selector_size %u is not supported, "
3003                      "ignoring .debug_aranges."),
3004                    objfile_name (objfile),
3005                    plongest (entry_addr - section->buffer),
3006                    segment_selector_size);
3007           return;
3008         }
3009
3010       /* Must pad to an alignment boundary that is twice the address
3011          size.  It is undocumented by the DWARF standard but GCC does
3012          use it.  */
3013       for (size_t padding = ((-(addr - section->buffer))
3014                              & (2 * address_size - 1));
3015            padding > 0; padding--)
3016         if (*addr++ != 0)
3017           {
3018             warning (_("Section .debug_aranges in %s entry at offset %s "
3019                        "padding is not zero, ignoring .debug_aranges."),
3020                      objfile_name (objfile),
3021                      plongest (entry_addr - section->buffer));
3022             return;
3023           }
3024
3025       for (;;)
3026         {
3027           if (addr + 2 * address_size > entry_end)
3028             {
3029               warning (_("Section .debug_aranges in %s entry at offset %s "
3030                          "address list is not properly terminated, "
3031                          "ignoring .debug_aranges."),
3032                        objfile_name (objfile),
3033                        plongest (entry_addr - section->buffer));
3034               return;
3035             }
3036           ULONGEST start = extract_unsigned_integer (addr, address_size,
3037                                                      dwarf5_byte_order);
3038           addr += address_size;
3039           ULONGEST length = extract_unsigned_integer (addr, address_size,
3040                                                       dwarf5_byte_order);
3041           addr += address_size;
3042           if (start == 0 && length == 0)
3043             break;
3044           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3045             {
3046               /* Symbol was eliminated due to a COMDAT group.  */
3047               continue;
3048             }
3049           ULONGEST end = start + length;
3050           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
3051                    - baseaddr);
3052           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3053                  - baseaddr);
3054           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3055         }
3056     }
3057
3058   objfile->partial_symtabs->psymtabs_addrmap
3059     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3060 }
3061
3062 /* Find a slot in the mapped index INDEX for the object named NAME.
3063    If NAME is found, set *VEC_OUT to point to the CU vector in the
3064    constant pool and return true.  If NAME cannot be found, return
3065    false.  */
3066
3067 static bool
3068 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3069                           offset_type **vec_out)
3070 {
3071   offset_type hash;
3072   offset_type slot, step;
3073   int (*cmp) (const char *, const char *);
3074
3075   gdb::unique_xmalloc_ptr<char> without_params;
3076   if (current_language->la_language == language_cplus
3077       || current_language->la_language == language_fortran
3078       || current_language->la_language == language_d)
3079     {
3080       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3081          not contain any.  */
3082
3083       if (strchr (name, '(') != NULL)
3084         {
3085           without_params = cp_remove_params (name);
3086
3087           if (without_params != NULL)
3088             name = without_params.get ();
3089         }
3090     }
3091
3092   /* Index version 4 did not support case insensitive searches.  But the
3093      indices for case insensitive languages are built in lowercase, therefore
3094      simulate our NAME being searched is also lowercased.  */
3095   hash = mapped_index_string_hash ((index->version == 4
3096                                     && case_sensitivity == case_sensitive_off
3097                                     ? 5 : index->version),
3098                                    name);
3099
3100   slot = hash & (index->symbol_table.size () - 1);
3101   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3102   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3103
3104   for (;;)
3105     {
3106       const char *str;
3107
3108       const auto &bucket = index->symbol_table[slot];
3109       if (bucket.name == 0 && bucket.vec == 0)
3110         return false;
3111
3112       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3113       if (!cmp (name, str))
3114         {
3115           *vec_out = (offset_type *) (index->constant_pool
3116                                       + MAYBE_SWAP (bucket.vec));
3117           return true;
3118         }
3119
3120       slot = (slot + step) & (index->symbol_table.size () - 1);
3121     }
3122 }
3123
3124 /* A helper function that reads the .gdb_index from BUFFER and fills
3125    in MAP.  FILENAME is the name of the file containing the data;
3126    it is used for error reporting.  DEPRECATED_OK is true if it is
3127    ok to use deprecated sections.
3128
3129    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3130    out parameters that are filled in with information about the CU and
3131    TU lists in the section.
3132
3133    Returns true if all went well, false otherwise.  */
3134
3135 static bool
3136 read_gdb_index_from_buffer (struct objfile *objfile,
3137                             const char *filename,
3138                             bool deprecated_ok,
3139                             gdb::array_view<const gdb_byte> buffer,
3140                             struct mapped_index *map,
3141                             const gdb_byte **cu_list,
3142                             offset_type *cu_list_elements,
3143                             const gdb_byte **types_list,
3144                             offset_type *types_list_elements)
3145 {
3146   const gdb_byte *addr = &buffer[0];
3147
3148   /* Version check.  */
3149   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3150   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3151      causes the index to behave very poorly for certain requests.  Version 3
3152      contained incomplete addrmap.  So, it seems better to just ignore such
3153      indices.  */
3154   if (version < 4)
3155     {
3156       static int warning_printed = 0;
3157       if (!warning_printed)
3158         {
3159           warning (_("Skipping obsolete .gdb_index section in %s."),
3160                    filename);
3161           warning_printed = 1;
3162         }
3163       return 0;
3164     }
3165   /* Index version 4 uses a different hash function than index version
3166      5 and later.
3167
3168      Versions earlier than 6 did not emit psymbols for inlined
3169      functions.  Using these files will cause GDB not to be able to
3170      set breakpoints on inlined functions by name, so we ignore these
3171      indices unless the user has done
3172      "set use-deprecated-index-sections on".  */
3173   if (version < 6 && !deprecated_ok)
3174     {
3175       static int warning_printed = 0;
3176       if (!warning_printed)
3177         {
3178           warning (_("\
3179 Skipping deprecated .gdb_index section in %s.\n\
3180 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3181 to use the section anyway."),
3182                    filename);
3183           warning_printed = 1;
3184         }
3185       return 0;
3186     }
3187   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3188      of the TU (for symbols coming from TUs),
3189      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3190      Plus gold-generated indices can have duplicate entries for global symbols,
3191      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3192      These are just performance bugs, and we can't distinguish gdb-generated
3193      indices from gold-generated ones, so issue no warning here.  */
3194
3195   /* Indexes with higher version than the one supported by GDB may be no
3196      longer backward compatible.  */
3197   if (version > 8)
3198     return 0;
3199
3200   map->version = version;
3201
3202   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3203
3204   int i = 0;
3205   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3206   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3207                        / 8);
3208   ++i;
3209
3210   *types_list = addr + MAYBE_SWAP (metadata[i]);
3211   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3212                            - MAYBE_SWAP (metadata[i]))
3213                           / 8);
3214   ++i;
3215
3216   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3217   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3218   map->address_table
3219     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3220   ++i;
3221
3222   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3223   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3224   map->symbol_table
3225     = gdb::array_view<mapped_index::symbol_table_slot>
3226        ((mapped_index::symbol_table_slot *) symbol_table,
3227         (mapped_index::symbol_table_slot *) symbol_table_end);
3228
3229   ++i;
3230   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3231
3232   return 1;
3233 }
3234
3235 /* Callback types for dwarf2_read_gdb_index.  */
3236
3237 typedef gdb::function_view
3238     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
3239     get_gdb_index_contents_ftype;
3240 typedef gdb::function_view
3241     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3242     get_gdb_index_contents_dwz_ftype;
3243
3244 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3245    elements of all the CUs and return 1.  Otherwise, return 0.  */
3246
3247 static int
3248 dwarf2_read_gdb_index
3249   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3250    get_gdb_index_contents_ftype get_gdb_index_contents,
3251    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3252 {
3253   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3254   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3255   struct dwz_file *dwz;
3256   struct objfile *objfile = dwarf2_per_objfile->objfile;
3257
3258   gdb::array_view<const gdb_byte> main_index_contents
3259     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3260
3261   if (main_index_contents.empty ())
3262     return 0;
3263
3264   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3265   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3266                                    use_deprecated_index_sections,
3267                                    main_index_contents, map.get (), &cu_list,
3268                                    &cu_list_elements, &types_list,
3269                                    &types_list_elements))
3270     return 0;
3271
3272   /* Don't use the index if it's empty.  */
3273   if (map->symbol_table.empty ())
3274     return 0;
3275
3276   /* If there is a .dwz file, read it so we can get its CU list as
3277      well.  */
3278   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3279   if (dwz != NULL)
3280     {
3281       struct mapped_index dwz_map;
3282       const gdb_byte *dwz_types_ignore;
3283       offset_type dwz_types_elements_ignore;
3284
3285       gdb::array_view<const gdb_byte> dwz_index_content
3286         = get_gdb_index_contents_dwz (objfile, dwz);
3287
3288       if (dwz_index_content.empty ())
3289         return 0;
3290
3291       if (!read_gdb_index_from_buffer (objfile,
3292                                        bfd_get_filename (dwz->dwz_bfd.get ()),
3293                                        1, dwz_index_content, &dwz_map,
3294                                        &dwz_list, &dwz_list_elements,
3295                                        &dwz_types_ignore,
3296                                        &dwz_types_elements_ignore))
3297         {
3298           warning (_("could not read '.gdb_index' section from %s; skipping"),
3299                    bfd_get_filename (dwz->dwz_bfd.get ()));
3300           return 0;
3301         }
3302     }
3303
3304   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3305                          dwz_list, dwz_list_elements);
3306
3307   if (types_list_elements)
3308     {
3309       /* We can only handle a single .debug_types when we have an
3310          index.  */
3311       if (dwarf2_per_objfile->types.size () != 1)
3312         return 0;
3313
3314       dwarf2_section_info *section = &dwarf2_per_objfile->types[0];
3315
3316       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3317                                                types_list, types_list_elements);
3318     }
3319
3320   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3321
3322   dwarf2_per_objfile->index_table = std::move (map);
3323   dwarf2_per_objfile->using_index = 1;
3324   dwarf2_per_objfile->quick_file_names_table =
3325     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3326
3327   return 1;
3328 }
3329
3330 /* die_reader_func for dw2_get_file_names.  */
3331
3332 static void
3333 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3334                            const gdb_byte *info_ptr,
3335                            struct die_info *comp_unit_die)
3336 {
3337   struct dwarf2_cu *cu = reader->cu;
3338   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3339   struct dwarf2_per_objfile *dwarf2_per_objfile
3340     = cu->per_cu->dwarf2_per_objfile;
3341   struct objfile *objfile = dwarf2_per_objfile->objfile;
3342   struct dwarf2_per_cu_data *lh_cu;
3343   struct attribute *attr;
3344   void **slot;
3345   struct quick_file_names *qfn;
3346
3347   gdb_assert (! this_cu->is_debug_types);
3348
3349   /* Our callers never want to match partial units -- instead they
3350      will match the enclosing full CU.  */
3351   if (comp_unit_die->tag == DW_TAG_partial_unit)
3352     {
3353       this_cu->v.quick->no_file_data = 1;
3354       return;
3355     }
3356
3357   lh_cu = this_cu;
3358   slot = NULL;
3359
3360   line_header_up lh;
3361   sect_offset line_offset {};
3362
3363   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3364   if (attr != nullptr)
3365     {
3366       struct quick_file_names find_entry;
3367
3368       line_offset = (sect_offset) DW_UNSND (attr);
3369
3370       /* We may have already read in this line header (TU line header sharing).
3371          If we have we're done.  */
3372       find_entry.hash.dwo_unit = cu->dwo_unit;
3373       find_entry.hash.line_sect_off = line_offset;
3374       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table.get (),
3375                              &find_entry, INSERT);
3376       if (*slot != NULL)
3377         {
3378           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3379           return;
3380         }
3381
3382       lh = dwarf_decode_line_header (line_offset, cu);
3383     }
3384   if (lh == NULL)
3385     {
3386       lh_cu->v.quick->no_file_data = 1;
3387       return;
3388     }
3389
3390   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3391   qfn->hash.dwo_unit = cu->dwo_unit;
3392   qfn->hash.line_sect_off = line_offset;
3393   gdb_assert (slot != NULL);
3394   *slot = qfn;
3395
3396   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3397
3398   int offset = 0;
3399   if (strcmp (fnd.name, "<unknown>") != 0)
3400     ++offset;
3401
3402   qfn->num_file_names = offset + lh->file_names_size ();
3403   qfn->file_names =
3404     XOBNEWVEC (&objfile->objfile_obstack, const char *, qfn->num_file_names);
3405   if (offset != 0)
3406     qfn->file_names[0] = xstrdup (fnd.name);
3407   for (int i = 0; i < lh->file_names_size (); ++i)
3408     qfn->file_names[i + offset] = lh->file_full_name (i + 1, fnd.comp_dir);
3409   qfn->real_names = NULL;
3410
3411   lh_cu->v.quick->file_names = qfn;
3412 }
3413
3414 /* A helper for the "quick" functions which attempts to read the line
3415    table for THIS_CU.  */
3416
3417 static struct quick_file_names *
3418 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3419 {
3420   /* This should never be called for TUs.  */
3421   gdb_assert (! this_cu->is_debug_types);
3422   /* Nor type unit groups.  */
3423   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3424
3425   if (this_cu->v.quick->file_names != NULL)
3426     return this_cu->v.quick->file_names;
3427   /* If we know there is no line data, no point in looking again.  */
3428   if (this_cu->v.quick->no_file_data)
3429     return NULL;
3430
3431   cutu_reader reader (this_cu);
3432   if (!reader.dummy_p)
3433     dw2_get_file_names_reader (&reader, reader.info_ptr, reader.comp_unit_die);
3434
3435   if (this_cu->v.quick->no_file_data)
3436     return NULL;
3437   return this_cu->v.quick->file_names;
3438 }
3439
3440 /* A helper for the "quick" functions which computes and caches the
3441    real path for a given file name from the line table.  */
3442
3443 static const char *
3444 dw2_get_real_path (struct objfile *objfile,
3445                    struct quick_file_names *qfn, int index)
3446 {
3447   if (qfn->real_names == NULL)
3448     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3449                                       qfn->num_file_names, const char *);
3450
3451   if (qfn->real_names[index] == NULL)
3452     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3453
3454   return qfn->real_names[index];
3455 }
3456
3457 static struct symtab *
3458 dw2_find_last_source_symtab (struct objfile *objfile)
3459 {
3460   struct dwarf2_per_objfile *dwarf2_per_objfile
3461     = get_dwarf2_per_objfile (objfile);
3462   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3463   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3464
3465   if (cust == NULL)
3466     return NULL;
3467
3468   return compunit_primary_filetab (cust);
3469 }
3470
3471 /* Traversal function for dw2_forget_cached_source_info.  */
3472
3473 static int
3474 dw2_free_cached_file_names (void **slot, void *info)
3475 {
3476   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3477
3478   if (file_data->real_names)
3479     {
3480       int i;
3481
3482       for (i = 0; i < file_data->num_file_names; ++i)
3483         {
3484           xfree ((void*) file_data->real_names[i]);
3485           file_data->real_names[i] = NULL;
3486         }
3487     }
3488
3489   return 1;
3490 }
3491
3492 static void
3493 dw2_forget_cached_source_info (struct objfile *objfile)
3494 {
3495   struct dwarf2_per_objfile *dwarf2_per_objfile
3496     = get_dwarf2_per_objfile (objfile);
3497
3498   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table.get (),
3499                           dw2_free_cached_file_names, NULL);
3500 }
3501
3502 /* Helper function for dw2_map_symtabs_matching_filename that expands
3503    the symtabs and calls the iterator.  */
3504
3505 static int
3506 dw2_map_expand_apply (struct objfile *objfile,
3507                       struct dwarf2_per_cu_data *per_cu,
3508                       const char *name, const char *real_path,
3509                       gdb::function_view<bool (symtab *)> callback)
3510 {
3511   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3512
3513   /* Don't visit already-expanded CUs.  */
3514   if (per_cu->v.quick->compunit_symtab)
3515     return 0;
3516
3517   /* This may expand more than one symtab, and we want to iterate over
3518      all of them.  */
3519   dw2_instantiate_symtab (per_cu, false);
3520
3521   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3522                                     last_made, callback);
3523 }
3524
3525 /* Implementation of the map_symtabs_matching_filename method.  */
3526
3527 static bool
3528 dw2_map_symtabs_matching_filename
3529   (struct objfile *objfile, const char *name, const char *real_path,
3530    gdb::function_view<bool (symtab *)> callback)
3531 {
3532   const char *name_basename = lbasename (name);
3533   struct dwarf2_per_objfile *dwarf2_per_objfile
3534     = get_dwarf2_per_objfile (objfile);
3535
3536   /* The rule is CUs specify all the files, including those used by
3537      any TU, so there's no need to scan TUs here.  */
3538
3539   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3540     {
3541       /* We only need to look at symtabs not already expanded.  */
3542       if (per_cu->v.quick->compunit_symtab)
3543         continue;
3544
3545       quick_file_names *file_data = dw2_get_file_names (per_cu);
3546       if (file_data == NULL)
3547         continue;
3548
3549       for (int j = 0; j < file_data->num_file_names; ++j)
3550         {
3551           const char *this_name = file_data->file_names[j];
3552           const char *this_real_name;
3553
3554           if (compare_filenames_for_search (this_name, name))
3555             {
3556               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3557                                         callback))
3558                 return true;
3559               continue;
3560             }
3561
3562           /* Before we invoke realpath, which can get expensive when many
3563              files are involved, do a quick comparison of the basenames.  */
3564           if (! basenames_may_differ
3565               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3566             continue;
3567
3568           this_real_name = dw2_get_real_path (objfile, file_data, j);
3569           if (compare_filenames_for_search (this_real_name, name))
3570             {
3571               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3572                                         callback))
3573                 return true;
3574               continue;
3575             }
3576
3577           if (real_path != NULL)
3578             {
3579               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3580               gdb_assert (IS_ABSOLUTE_PATH (name));
3581               if (this_real_name != NULL
3582                   && FILENAME_CMP (real_path, this_real_name) == 0)
3583                 {
3584                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3585                                             callback))
3586                     return true;
3587                   continue;
3588                 }
3589             }
3590         }
3591     }
3592
3593   return false;
3594 }
3595
3596 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3597
3598 struct dw2_symtab_iterator
3599 {
3600   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3601   struct dwarf2_per_objfile *dwarf2_per_objfile;
3602   /* If set, only look for symbols that match that block.  Valid values are
3603      GLOBAL_BLOCK and STATIC_BLOCK.  */
3604   gdb::optional<block_enum> block_index;
3605   /* The kind of symbol we're looking for.  */
3606   domain_enum domain;
3607   /* The list of CUs from the index entry of the symbol,
3608      or NULL if not found.  */
3609   offset_type *vec;
3610   /* The next element in VEC to look at.  */
3611   int next;
3612   /* The number of elements in VEC, or zero if there is no match.  */
3613   int length;
3614   /* Have we seen a global version of the symbol?
3615      If so we can ignore all further global instances.
3616      This is to work around gold/15646, inefficient gold-generated
3617      indices.  */
3618   int global_seen;
3619 };
3620
3621 /* Initialize the index symtab iterator ITER.  */
3622
3623 static void
3624 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3625                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3626                       gdb::optional<block_enum> block_index,
3627                       domain_enum domain,
3628                       const char *name)
3629 {
3630   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3631   iter->block_index = block_index;
3632   iter->domain = domain;
3633   iter->next = 0;
3634   iter->global_seen = 0;
3635
3636   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3637
3638   /* index is NULL if OBJF_READNOW.  */
3639   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3640     iter->length = MAYBE_SWAP (*iter->vec);
3641   else
3642     {
3643       iter->vec = NULL;
3644       iter->length = 0;
3645     }
3646 }
3647
3648 /* Return the next matching CU or NULL if there are no more.  */
3649
3650 static struct dwarf2_per_cu_data *
3651 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3652 {
3653   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3654
3655   for ( ; iter->next < iter->length; ++iter->next)
3656     {
3657       offset_type cu_index_and_attrs =
3658         MAYBE_SWAP (iter->vec[iter->next + 1]);
3659       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3660       gdb_index_symbol_kind symbol_kind =
3661         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3662       /* Only check the symbol attributes if they're present.
3663          Indices prior to version 7 don't record them,
3664          and indices >= 7 may elide them for certain symbols
3665          (gold does this).  */
3666       int attrs_valid =
3667         (dwarf2_per_objfile->index_table->version >= 7
3668          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3669
3670       /* Don't crash on bad data.  */
3671       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3672                        + dwarf2_per_objfile->all_type_units.size ()))
3673         {
3674           complaint (_(".gdb_index entry has bad CU index"
3675                        " [in module %s]"),
3676                      objfile_name (dwarf2_per_objfile->objfile));
3677           continue;
3678         }
3679
3680       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3681
3682       /* Skip if already read in.  */
3683       if (per_cu->v.quick->compunit_symtab)
3684         continue;
3685
3686       /* Check static vs global.  */
3687       if (attrs_valid)
3688         {
3689           bool is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3690
3691           if (iter->block_index.has_value ())
3692             {
3693               bool want_static = *iter->block_index == STATIC_BLOCK;
3694
3695               if (is_static != want_static)
3696                 continue;
3697             }
3698
3699           /* Work around gold/15646.  */
3700           if (!is_static && iter->global_seen)
3701             continue;
3702           if (!is_static)
3703             iter->global_seen = 1;
3704         }
3705
3706       /* Only check the symbol's kind if it has one.  */
3707       if (attrs_valid)
3708         {
3709           switch (iter->domain)
3710             {
3711             case VAR_DOMAIN:
3712               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3713                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3714                   /* Some types are also in VAR_DOMAIN.  */
3715                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3716                 continue;
3717               break;
3718             case STRUCT_DOMAIN:
3719               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3720                 continue;
3721               break;
3722             case LABEL_DOMAIN:
3723               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3724                 continue;
3725               break;
3726             case MODULE_DOMAIN:
3727               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3728                 continue;
3729               break;
3730             default:
3731               break;
3732             }
3733         }
3734
3735       ++iter->next;
3736       return per_cu;
3737     }
3738
3739   return NULL;
3740 }
3741
3742 static struct compunit_symtab *
3743 dw2_lookup_symbol (struct objfile *objfile, block_enum block_index,
3744                    const char *name, domain_enum domain)
3745 {
3746   struct compunit_symtab *stab_best = NULL;
3747   struct dwarf2_per_objfile *dwarf2_per_objfile
3748     = get_dwarf2_per_objfile (objfile);
3749
3750   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3751
3752   struct dw2_symtab_iterator iter;
3753   struct dwarf2_per_cu_data *per_cu;
3754
3755   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, block_index, domain, name);
3756
3757   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3758     {
3759       struct symbol *sym, *with_opaque = NULL;
3760       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
3761       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3762       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3763
3764       sym = block_find_symbol (block, name, domain,
3765                                block_find_non_opaque_type_preferred,
3766                                &with_opaque);
3767
3768       /* Some caution must be observed with overloaded functions
3769          and methods, since the index will not contain any overload
3770          information (but NAME might contain it).  */
3771
3772       if (sym != NULL
3773           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3774         return stab;
3775       if (with_opaque != NULL
3776           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3777         stab_best = stab;
3778
3779       /* Keep looking through other CUs.  */
3780     }
3781
3782   return stab_best;
3783 }
3784
3785 static void
3786 dw2_print_stats (struct objfile *objfile)
3787 {
3788   struct dwarf2_per_objfile *dwarf2_per_objfile
3789     = get_dwarf2_per_objfile (objfile);
3790   int total = (dwarf2_per_objfile->all_comp_units.size ()
3791                + dwarf2_per_objfile->all_type_units.size ());
3792   int count = 0;
3793
3794   for (int i = 0; i < total; ++i)
3795     {
3796       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
3797
3798       if (!per_cu->v.quick->compunit_symtab)
3799         ++count;
3800     }
3801   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3802   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3803 }
3804
3805 /* This dumps minimal information about the index.
3806    It is called via "mt print objfiles".
3807    One use is to verify .gdb_index has been loaded by the
3808    gdb.dwarf2/gdb-index.exp testcase.  */
3809
3810 static void
3811 dw2_dump (struct objfile *objfile)
3812 {
3813   struct dwarf2_per_objfile *dwarf2_per_objfile
3814     = get_dwarf2_per_objfile (objfile);
3815
3816   gdb_assert (dwarf2_per_objfile->using_index);
3817   printf_filtered (".gdb_index:");
3818   if (dwarf2_per_objfile->index_table != NULL)
3819     {
3820       printf_filtered (" version %d\n",
3821                        dwarf2_per_objfile->index_table->version);
3822     }
3823   else
3824     printf_filtered (" faked for \"readnow\"\n");
3825   printf_filtered ("\n");
3826 }
3827
3828 static void
3829 dw2_expand_symtabs_for_function (struct objfile *objfile,
3830                                  const char *func_name)
3831 {
3832   struct dwarf2_per_objfile *dwarf2_per_objfile
3833     = get_dwarf2_per_objfile (objfile);
3834
3835   struct dw2_symtab_iterator iter;
3836   struct dwarf2_per_cu_data *per_cu;
3837
3838   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, {}, VAR_DOMAIN, func_name);
3839
3840   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3841     dw2_instantiate_symtab (per_cu, false);
3842
3843 }
3844
3845 static void
3846 dw2_expand_all_symtabs (struct objfile *objfile)
3847 {
3848   struct dwarf2_per_objfile *dwarf2_per_objfile
3849     = get_dwarf2_per_objfile (objfile);
3850   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
3851                      + dwarf2_per_objfile->all_type_units.size ());
3852
3853   for (int i = 0; i < total_units; ++i)
3854     {
3855       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
3856
3857       /* We don't want to directly expand a partial CU, because if we
3858          read it with the wrong language, then assertion failures can
3859          be triggered later on.  See PR symtab/23010.  So, tell
3860          dw2_instantiate_symtab to skip partial CUs -- any important
3861          partial CU will be read via DW_TAG_imported_unit anyway.  */
3862       dw2_instantiate_symtab (per_cu, true);
3863     }
3864 }
3865
3866 static void
3867 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3868                                   const char *fullname)
3869 {
3870   struct dwarf2_per_objfile *dwarf2_per_objfile
3871     = get_dwarf2_per_objfile (objfile);
3872
3873   /* We don't need to consider type units here.
3874      This is only called for examining code, e.g. expand_line_sal.
3875      There can be an order of magnitude (or more) more type units
3876      than comp units, and we avoid them if we can.  */
3877
3878   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3879     {
3880       /* We only need to look at symtabs not already expanded.  */
3881       if (per_cu->v.quick->compunit_symtab)
3882         continue;
3883
3884       quick_file_names *file_data = dw2_get_file_names (per_cu);
3885       if (file_data == NULL)
3886         continue;
3887
3888       for (int j = 0; j < file_data->num_file_names; ++j)
3889         {
3890           const char *this_fullname = file_data->file_names[j];
3891
3892           if (filename_cmp (this_fullname, fullname) == 0)
3893             {
3894               dw2_instantiate_symtab (per_cu, false);
3895               break;
3896             }
3897         }
3898     }
3899 }
3900
3901 static void
3902 dw2_map_matching_symbols
3903   (struct objfile *objfile,
3904    const lookup_name_info &name, domain_enum domain,
3905    int global,
3906    gdb::function_view<symbol_found_callback_ftype> callback,
3907    symbol_compare_ftype *ordered_compare)
3908 {
3909   /* Currently unimplemented; used for Ada.  The function can be called if the
3910      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3911      does not look for non-Ada symbols this function should just return.  */
3912 }
3913
3914 /* Starting from a search name, return the string that finds the upper
3915    bound of all strings that start with SEARCH_NAME in a sorted name
3916    list.  Returns the empty string to indicate that the upper bound is
3917    the end of the list.  */
3918
3919 static std::string
3920 make_sort_after_prefix_name (const char *search_name)
3921 {
3922   /* When looking to complete "func", we find the upper bound of all
3923      symbols that start with "func" by looking for where we'd insert
3924      the closest string that would follow "func" in lexicographical
3925      order.  Usually, that's "func"-with-last-character-incremented,
3926      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
3927      will be UTF-8 multi-byte sequences, but we can't be certain.
3928      Especially mind the 0xff character, which is a valid character in
3929      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
3930      rule out compilers allowing it in identifiers.  Note that
3931      conveniently, strcmp/strcasecmp are specified to compare
3932      characters interpreted as unsigned char.  So what we do is treat
3933      the whole string as a base 256 number composed of a sequence of
3934      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
3935      to 0, and carries 1 to the following more-significant position.
3936      If the very first character in SEARCH_NAME ends up incremented
3937      and carries/overflows, then the upper bound is the end of the
3938      list.  The string after the empty string is also the empty
3939      string.
3940
3941      Some examples of this operation:
3942
3943        SEARCH_NAME  => "+1" RESULT
3944
3945        "abc"              => "abd"
3946        "ab\xff"           => "ac"
3947        "\xff" "a" "\xff"  => "\xff" "b"
3948        "\xff"             => ""
3949        "\xff\xff"         => ""
3950        ""                 => ""
3951
3952      Then, with these symbols for example:
3953
3954       func
3955       func1
3956       fund
3957
3958      completing "func" looks for symbols between "func" and
3959      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
3960      which finds "func" and "func1", but not "fund".
3961
3962      And with:
3963
3964       funcÿ     (Latin1 'ÿ' [0xff])
3965       funcÿ1
3966       fund
3967
3968      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
3969      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
3970
3971      And with:
3972
3973       ÿÿ        (Latin1 'ÿ' [0xff])
3974       ÿÿ1
3975
3976      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
3977      the end of the list.
3978   */
3979   std::string after = search_name;
3980   while (!after.empty () && (unsigned char) after.back () == 0xff)
3981     after.pop_back ();
3982   if (!after.empty ())
3983     after.back () = (unsigned char) after.back () + 1;
3984   return after;
3985 }
3986
3987 /* See declaration.  */
3988
3989 std::pair<std::vector<name_component>::const_iterator,
3990           std::vector<name_component>::const_iterator>
3991 mapped_index_base::find_name_components_bounds
3992   (const lookup_name_info &lookup_name_without_params, language lang) const
3993 {
3994   auto *name_cmp
3995     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3996
3997   const char *lang_name
3998     = lookup_name_without_params.language_lookup_name (lang).c_str ();
3999
4000   /* Comparison function object for lower_bound that matches against a
4001      given symbol name.  */
4002   auto lookup_compare_lower = [&] (const name_component &elem,
4003                                    const char *name)
4004     {
4005       const char *elem_qualified = this->symbol_name_at (elem.idx);
4006       const char *elem_name = elem_qualified + elem.name_offset;
4007       return name_cmp (elem_name, name) < 0;
4008     };
4009
4010   /* Comparison function object for upper_bound that matches against a
4011      given symbol name.  */
4012   auto lookup_compare_upper = [&] (const char *name,
4013                                    const name_component &elem)
4014     {
4015       const char *elem_qualified = this->symbol_name_at (elem.idx);
4016       const char *elem_name = elem_qualified + elem.name_offset;
4017       return name_cmp (name, elem_name) < 0;
4018     };
4019
4020   auto begin = this->name_components.begin ();
4021   auto end = this->name_components.end ();
4022
4023   /* Find the lower bound.  */
4024   auto lower = [&] ()
4025     {
4026       if (lookup_name_without_params.completion_mode () && lang_name[0] == '\0')
4027         return begin;
4028       else
4029         return std::lower_bound (begin, end, lang_name, lookup_compare_lower);
4030     } ();
4031
4032   /* Find the upper bound.  */
4033   auto upper = [&] ()
4034     {
4035       if (lookup_name_without_params.completion_mode ())
4036         {
4037           /* In completion mode, we want UPPER to point past all
4038              symbols names that have the same prefix.  I.e., with
4039              these symbols, and completing "func":
4040
4041               function        << lower bound
4042               function1
4043               other_function  << upper bound
4044
4045              We find the upper bound by looking for the insertion
4046              point of "func"-with-last-character-incremented,
4047              i.e. "fund".  */
4048           std::string after = make_sort_after_prefix_name (lang_name);
4049           if (after.empty ())
4050             return end;
4051           return std::lower_bound (lower, end, after.c_str (),
4052                                    lookup_compare_lower);
4053         }
4054       else
4055         return std::upper_bound (lower, end, lang_name, lookup_compare_upper);
4056     } ();
4057
4058   return {lower, upper};
4059 }
4060
4061 /* See declaration.  */
4062
4063 void
4064 mapped_index_base::build_name_components ()
4065 {
4066   if (!this->name_components.empty ())
4067     return;
4068
4069   this->name_components_casing = case_sensitivity;
4070   auto *name_cmp
4071     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4072
4073   /* The code below only knows how to break apart components of C++
4074      symbol names (and other languages that use '::' as
4075      namespace/module separator) and Ada symbol names.  */
4076   auto count = this->symbol_name_count ();
4077   for (offset_type idx = 0; idx < count; idx++)
4078     {
4079       if (this->symbol_name_slot_invalid (idx))
4080         continue;
4081
4082       const char *name = this->symbol_name_at (idx);
4083
4084       /* Add each name component to the name component table.  */
4085       unsigned int previous_len = 0;
4086
4087       if (strstr (name, "::") != nullptr)
4088         {
4089           for (unsigned int current_len = cp_find_first_component (name);
4090                name[current_len] != '\0';
4091                current_len += cp_find_first_component (name + current_len))
4092             {
4093               gdb_assert (name[current_len] == ':');
4094               this->name_components.push_back ({previous_len, idx});
4095               /* Skip the '::'.  */
4096               current_len += 2;
4097               previous_len = current_len;
4098             }
4099         }
4100       else
4101         {
4102           /* Handle the Ada encoded (aka mangled) form here.  */
4103           for (const char *iter = strstr (name, "__");
4104                iter != nullptr;
4105                iter = strstr (iter, "__"))
4106             {
4107               this->name_components.push_back ({previous_len, idx});
4108               iter += 2;
4109               previous_len = iter - name;
4110             }
4111         }
4112
4113       this->name_components.push_back ({previous_len, idx});
4114     }
4115
4116   /* Sort name_components elements by name.  */
4117   auto name_comp_compare = [&] (const name_component &left,
4118                                 const name_component &right)
4119     {
4120       const char *left_qualified = this->symbol_name_at (left.idx);
4121       const char *right_qualified = this->symbol_name_at (right.idx);
4122
4123       const char *left_name = left_qualified + left.name_offset;
4124       const char *right_name = right_qualified + right.name_offset;
4125
4126       return name_cmp (left_name, right_name) < 0;
4127     };
4128
4129   std::sort (this->name_components.begin (),
4130              this->name_components.end (),
4131              name_comp_compare);
4132 }
4133
4134 /* Helper for dw2_expand_symtabs_matching that works with a
4135    mapped_index_base instead of the containing objfile.  This is split
4136    to a separate function in order to be able to unit test the
4137    name_components matching using a mock mapped_index_base.  For each
4138    symbol name that matches, calls MATCH_CALLBACK, passing it the
4139    symbol's index in the mapped_index_base symbol table.  */
4140
4141 static void
4142 dw2_expand_symtabs_matching_symbol
4143   (mapped_index_base &index,
4144    const lookup_name_info &lookup_name_in,
4145    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4146    enum search_domain kind,
4147    gdb::function_view<bool (offset_type)> match_callback)
4148 {
4149   lookup_name_info lookup_name_without_params
4150     = lookup_name_in.make_ignore_params ();
4151
4152   /* Build the symbol name component sorted vector, if we haven't
4153      yet.  */
4154   index.build_name_components ();
4155
4156   /* The same symbol may appear more than once in the range though.
4157      E.g., if we're looking for symbols that complete "w", and we have
4158      a symbol named "w1::w2", we'll find the two name components for
4159      that same symbol in the range.  To be sure we only call the
4160      callback once per symbol, we first collect the symbol name
4161      indexes that matched in a temporary vector and ignore
4162      duplicates.  */
4163   std::vector<offset_type> matches;
4164
4165   struct name_and_matcher
4166   {
4167     symbol_name_matcher_ftype *matcher;
4168     const std::string &name;
4169
4170     bool operator== (const name_and_matcher &other) const
4171     {
4172       return matcher == other.matcher && name == other.name;
4173     }
4174   };
4175
4176   /* A vector holding all the different symbol name matchers, for all
4177      languages.  */
4178   std::vector<name_and_matcher> matchers;
4179
4180   for (int i = 0; i < nr_languages; i++)
4181     {
4182       enum language lang_e = (enum language) i;
4183
4184       const language_defn *lang = language_def (lang_e);
4185       symbol_name_matcher_ftype *name_matcher
4186         = get_symbol_name_matcher (lang, lookup_name_without_params);
4187
4188       name_and_matcher key {
4189          name_matcher,
4190          lookup_name_without_params.language_lookup_name (lang_e)
4191       };
4192
4193       /* Don't insert the same comparison routine more than once.
4194          Note that we do this linear walk.  This is not a problem in
4195          practice because the number of supported languages is
4196          low.  */
4197       if (std::find (matchers.begin (), matchers.end (), key)
4198           != matchers.end ())
4199         continue;
4200       matchers.push_back (std::move (key));
4201
4202       auto bounds
4203         = index.find_name_components_bounds (lookup_name_without_params,
4204                                              lang_e);
4205
4206       /* Now for each symbol name in range, check to see if we have a name
4207          match, and if so, call the MATCH_CALLBACK callback.  */
4208
4209       for (; bounds.first != bounds.second; ++bounds.first)
4210         {
4211           const char *qualified = index.symbol_name_at (bounds.first->idx);
4212
4213           if (!name_matcher (qualified, lookup_name_without_params, NULL)
4214               || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4215             continue;
4216
4217           matches.push_back (bounds.first->idx);
4218         }
4219     }
4220
4221   std::sort (matches.begin (), matches.end ());
4222
4223   /* Finally call the callback, once per match.  */
4224   ULONGEST prev = -1;
4225   for (offset_type idx : matches)
4226     {
4227       if (prev != idx)
4228         {
4229           if (!match_callback (idx))
4230             break;
4231           prev = idx;
4232         }
4233     }
4234
4235   /* Above we use a type wider than idx's for 'prev', since 0 and
4236      (offset_type)-1 are both possible values.  */
4237   static_assert (sizeof (prev) > sizeof (offset_type), "");
4238 }
4239
4240 #if GDB_SELF_TEST
4241
4242 namespace selftests { namespace dw2_expand_symtabs_matching {
4243
4244 /* A mock .gdb_index/.debug_names-like name index table, enough to
4245    exercise dw2_expand_symtabs_matching_symbol, which works with the
4246    mapped_index_base interface.  Builds an index from the symbol list
4247    passed as parameter to the constructor.  */
4248 class mock_mapped_index : public mapped_index_base
4249 {
4250 public:
4251   mock_mapped_index (gdb::array_view<const char *> symbols)
4252     : m_symbol_table (symbols)
4253   {}
4254
4255   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4256
4257   /* Return the number of names in the symbol table.  */
4258   size_t symbol_name_count () const override
4259   {
4260     return m_symbol_table.size ();
4261   }
4262
4263   /* Get the name of the symbol at IDX in the symbol table.  */
4264   const char *symbol_name_at (offset_type idx) const override
4265   {
4266     return m_symbol_table[idx];
4267   }
4268
4269 private:
4270   gdb::array_view<const char *> m_symbol_table;
4271 };
4272
4273 /* Convenience function that converts a NULL pointer to a "<null>"
4274    string, to pass to print routines.  */
4275
4276 static const char *
4277 string_or_null (const char *str)
4278 {
4279   return str != NULL ? str : "<null>";
4280 }
4281
4282 /* Check if a lookup_name_info built from
4283    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4284    index.  EXPECTED_LIST is the list of expected matches, in expected
4285    matching order.  If no match expected, then an empty list is
4286    specified.  Returns true on success.  On failure prints a warning
4287    indicating the file:line that failed, and returns false.  */
4288
4289 static bool
4290 check_match (const char *file, int line,
4291              mock_mapped_index &mock_index,
4292              const char *name, symbol_name_match_type match_type,
4293              bool completion_mode,
4294              std::initializer_list<const char *> expected_list)
4295 {
4296   lookup_name_info lookup_name (name, match_type, completion_mode);
4297
4298   bool matched = true;
4299
4300   auto mismatch = [&] (const char *expected_str,
4301                        const char *got)
4302   {
4303     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4304                "expected=\"%s\", got=\"%s\"\n"),
4305              file, line,
4306              (match_type == symbol_name_match_type::FULL
4307               ? "FULL" : "WILD"),
4308              name, string_or_null (expected_str), string_or_null (got));
4309     matched = false;
4310   };
4311
4312   auto expected_it = expected_list.begin ();
4313   auto expected_end = expected_list.end ();
4314
4315   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4316                                       NULL, ALL_DOMAIN,
4317                                       [&] (offset_type idx)
4318   {
4319     const char *matched_name = mock_index.symbol_name_at (idx);
4320     const char *expected_str
4321       = expected_it == expected_end ? NULL : *expected_it++;
4322
4323     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4324       mismatch (expected_str, matched_name);
4325     return true;
4326   });
4327
4328   const char *expected_str
4329   = expected_it == expected_end ? NULL : *expected_it++;
4330   if (expected_str != NULL)
4331     mismatch (expected_str, NULL);
4332
4333   return matched;
4334 }
4335
4336 /* The symbols added to the mock mapped_index for testing (in
4337    canonical form).  */
4338 static const char *test_symbols[] = {
4339   "function",
4340   "std::bar",
4341   "std::zfunction",
4342   "std::zfunction2",
4343   "w1::w2",
4344   "ns::foo<char*>",
4345   "ns::foo<int>",
4346   "ns::foo<long>",
4347   "ns2::tmpl<int>::foo2",
4348   "(anonymous namespace)::A::B::C",
4349
4350   /* These are used to check that the increment-last-char in the
4351      matching algorithm for completion doesn't match "t1_fund" when
4352      completing "t1_func".  */
4353   "t1_func",
4354   "t1_func1",
4355   "t1_fund",
4356   "t1_fund1",
4357
4358   /* A UTF-8 name with multi-byte sequences to make sure that
4359      cp-name-parser understands this as a single identifier ("função"
4360      is "function" in PT).  */
4361   u8"u8função",
4362
4363   /* \377 (0xff) is Latin1 'ÿ'.  */
4364   "yfunc\377",
4365
4366   /* \377 (0xff) is Latin1 'ÿ'.  */
4367   "\377",
4368   "\377\377123",
4369
4370   /* A name with all sorts of complications.  Starts with "z" to make
4371      it easier for the completion tests below.  */
4372 #define Z_SYM_NAME \
4373   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4374     "::tuple<(anonymous namespace)::ui*, " \
4375     "std::default_delete<(anonymous namespace)::ui>, void>"
4376
4377   Z_SYM_NAME
4378 };
4379
4380 /* Returns true if the mapped_index_base::find_name_component_bounds
4381    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4382    in completion mode.  */
4383
4384 static bool
4385 check_find_bounds_finds (mapped_index_base &index,
4386                          const char *search_name,
4387                          gdb::array_view<const char *> expected_syms)
4388 {
4389   lookup_name_info lookup_name (search_name,
4390                                 symbol_name_match_type::FULL, true);
4391
4392   auto bounds = index.find_name_components_bounds (lookup_name,
4393                                                    language_cplus);
4394
4395   size_t distance = std::distance (bounds.first, bounds.second);
4396   if (distance != expected_syms.size ())
4397     return false;
4398
4399   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4400     {
4401       auto nc_elem = bounds.first + exp_elem;
4402       const char *qualified = index.symbol_name_at (nc_elem->idx);
4403       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4404         return false;
4405     }
4406
4407   return true;
4408 }
4409
4410 /* Test the lower-level mapped_index::find_name_component_bounds
4411    method.  */
4412
4413 static void
4414 test_mapped_index_find_name_component_bounds ()
4415 {
4416   mock_mapped_index mock_index (test_symbols);
4417
4418   mock_index.build_name_components ();
4419
4420   /* Test the lower-level mapped_index::find_name_component_bounds
4421      method in completion mode.  */
4422   {
4423     static const char *expected_syms[] = {
4424       "t1_func",
4425       "t1_func1",
4426     };
4427
4428     SELF_CHECK (check_find_bounds_finds (mock_index,
4429                                          "t1_func", expected_syms));
4430   }
4431
4432   /* Check that the increment-last-char in the name matching algorithm
4433      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4434   {
4435     static const char *expected_syms1[] = {
4436       "\377",
4437       "\377\377123",
4438     };
4439     SELF_CHECK (check_find_bounds_finds (mock_index,
4440                                          "\377", expected_syms1));
4441
4442     static const char *expected_syms2[] = {
4443       "\377\377123",
4444     };
4445     SELF_CHECK (check_find_bounds_finds (mock_index,
4446                                          "\377\377", expected_syms2));
4447   }
4448 }
4449
4450 /* Test dw2_expand_symtabs_matching_symbol.  */
4451
4452 static void
4453 test_dw2_expand_symtabs_matching_symbol ()
4454 {
4455   mock_mapped_index mock_index (test_symbols);
4456
4457   /* We let all tests run until the end even if some fails, for debug
4458      convenience.  */
4459   bool any_mismatch = false;
4460
4461   /* Create the expected symbols list (an initializer_list).  Needed
4462      because lists have commas, and we need to pass them to CHECK,
4463      which is a macro.  */
4464 #define EXPECT(...) { __VA_ARGS__ }
4465
4466   /* Wrapper for check_match that passes down the current
4467      __FILE__/__LINE__.  */
4468 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4469   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4470                                 mock_index,                             \
4471                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4472                                 EXPECTED_LIST)
4473
4474   /* Identity checks.  */
4475   for (const char *sym : test_symbols)
4476     {
4477       /* Should be able to match all existing symbols.  */
4478       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4479                    EXPECT (sym));
4480
4481       /* Should be able to match all existing symbols with
4482          parameters.  */
4483       std::string with_params = std::string (sym) + "(int)";
4484       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4485                    EXPECT (sym));
4486
4487       /* Should be able to match all existing symbols with
4488          parameters and qualifiers.  */
4489       with_params = std::string (sym) + " ( int ) const";
4490       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4491                    EXPECT (sym));
4492
4493       /* This should really find sym, but cp-name-parser.y doesn't
4494          know about lvalue/rvalue qualifiers yet.  */
4495       with_params = std::string (sym) + " ( int ) &&";
4496       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4497                    {});
4498     }
4499
4500   /* Check that the name matching algorithm for completion doesn't get
4501      confused with Latin1 'ÿ' / 0xff.  */
4502   {
4503     static const char str[] = "\377";
4504     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4505                  EXPECT ("\377", "\377\377123"));
4506   }
4507
4508   /* Check that the increment-last-char in the matching algorithm for
4509      completion doesn't match "t1_fund" when completing "t1_func".  */
4510   {
4511     static const char str[] = "t1_func";
4512     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4513                  EXPECT ("t1_func", "t1_func1"));
4514   }
4515
4516   /* Check that completion mode works at each prefix of the expected
4517      symbol name.  */
4518   {
4519     static const char str[] = "function(int)";
4520     size_t len = strlen (str);
4521     std::string lookup;
4522
4523     for (size_t i = 1; i < len; i++)
4524       {
4525         lookup.assign (str, i);
4526         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4527                      EXPECT ("function"));
4528       }
4529   }
4530
4531   /* While "w" is a prefix of both components, the match function
4532      should still only be called once.  */
4533   {
4534     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4535                  EXPECT ("w1::w2"));
4536     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4537                  EXPECT ("w1::w2"));
4538   }
4539
4540   /* Same, with a "complicated" symbol.  */
4541   {
4542     static const char str[] = Z_SYM_NAME;
4543     size_t len = strlen (str);
4544     std::string lookup;
4545
4546     for (size_t i = 1; i < len; i++)
4547       {
4548         lookup.assign (str, i);
4549         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4550                      EXPECT (Z_SYM_NAME));
4551       }
4552   }
4553
4554   /* In FULL mode, an incomplete symbol doesn't match.  */
4555   {
4556     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4557                  {});
4558   }
4559
4560   /* A complete symbol with parameters matches any overload, since the
4561      index has no overload info.  */
4562   {
4563     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4564                  EXPECT ("std::zfunction", "std::zfunction2"));
4565     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4566                  EXPECT ("std::zfunction", "std::zfunction2"));
4567     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4568                  EXPECT ("std::zfunction", "std::zfunction2"));
4569   }
4570
4571   /* Check that whitespace is ignored appropriately.  A symbol with a
4572      template argument list. */
4573   {
4574     static const char expected[] = "ns::foo<int>";
4575     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4576                  EXPECT (expected));
4577     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4578                  EXPECT (expected));
4579   }
4580
4581   /* Check that whitespace is ignored appropriately.  A symbol with a
4582      template argument list that includes a pointer.  */
4583   {
4584     static const char expected[] = "ns::foo<char*>";
4585     /* Try both completion and non-completion modes.  */
4586     static const bool completion_mode[2] = {false, true};
4587     for (size_t i = 0; i < 2; i++)
4588       {
4589         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4590                      completion_mode[i], EXPECT (expected));
4591         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4592                      completion_mode[i], EXPECT (expected));
4593
4594         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4595                      completion_mode[i], EXPECT (expected));
4596         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4597                      completion_mode[i], EXPECT (expected));
4598       }
4599   }
4600
4601   {
4602     /* Check method qualifiers are ignored.  */
4603     static const char expected[] = "ns::foo<char*>";
4604     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4605                  symbol_name_match_type::FULL, true, EXPECT (expected));
4606     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4607                  symbol_name_match_type::FULL, true, EXPECT (expected));
4608     CHECK_MATCH ("foo < char * >  ( int ) const",
4609                  symbol_name_match_type::WILD, true, EXPECT (expected));
4610     CHECK_MATCH ("foo < char * >  ( int ) &&",
4611                  symbol_name_match_type::WILD, true, EXPECT (expected));
4612   }
4613
4614   /* Test lookup names that don't match anything.  */
4615   {
4616     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4617                  {});
4618
4619     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4620                  {});
4621   }
4622
4623   /* Some wild matching tests, exercising "(anonymous namespace)",
4624      which should not be confused with a parameter list.  */
4625   {
4626     static const char *syms[] = {
4627       "A::B::C",
4628       "B::C",
4629       "C",
4630       "A :: B :: C ( int )",
4631       "B :: C ( int )",
4632       "C ( int )",
4633     };
4634
4635     for (const char *s : syms)
4636       {
4637         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4638                      EXPECT ("(anonymous namespace)::A::B::C"));
4639       }
4640   }
4641
4642   {
4643     static const char expected[] = "ns2::tmpl<int>::foo2";
4644     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4645                  EXPECT (expected));
4646     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4647                  EXPECT (expected));
4648   }
4649
4650   SELF_CHECK (!any_mismatch);
4651
4652 #undef EXPECT
4653 #undef CHECK_MATCH
4654 }
4655
4656 static void
4657 run_test ()
4658 {
4659   test_mapped_index_find_name_component_bounds ();
4660   test_dw2_expand_symtabs_matching_symbol ();
4661 }
4662
4663 }} // namespace selftests::dw2_expand_symtabs_matching
4664
4665 #endif /* GDB_SELF_TEST */
4666
4667 /* If FILE_MATCHER is NULL or if PER_CU has
4668    dwarf2_per_cu_quick_data::MARK set (see
4669    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4670    EXPANSION_NOTIFY on it.  */
4671
4672 static void
4673 dw2_expand_symtabs_matching_one
4674   (struct dwarf2_per_cu_data *per_cu,
4675    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4676    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4677 {
4678   if (file_matcher == NULL || per_cu->v.quick->mark)
4679     {
4680       bool symtab_was_null
4681         = (per_cu->v.quick->compunit_symtab == NULL);
4682
4683       dw2_instantiate_symtab (per_cu, false);
4684
4685       if (expansion_notify != NULL
4686           && symtab_was_null
4687           && per_cu->v.quick->compunit_symtab != NULL)
4688         expansion_notify (per_cu->v.quick->compunit_symtab);
4689     }
4690 }
4691
4692 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4693    matched, to expand corresponding CUs that were marked.  IDX is the
4694    index of the symbol name that matched.  */
4695
4696 static void
4697 dw2_expand_marked_cus
4698   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
4699    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4700    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4701    search_domain kind)
4702 {
4703   offset_type *vec, vec_len, vec_idx;
4704   bool global_seen = false;
4705   mapped_index &index = *dwarf2_per_objfile->index_table;
4706
4707   vec = (offset_type *) (index.constant_pool
4708                          + MAYBE_SWAP (index.symbol_table[idx].vec));
4709   vec_len = MAYBE_SWAP (vec[0]);
4710   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4711     {
4712       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4713       /* This value is only valid for index versions >= 7.  */
4714       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4715       gdb_index_symbol_kind symbol_kind =
4716         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4717       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4718       /* Only check the symbol attributes if they're present.
4719          Indices prior to version 7 don't record them,
4720          and indices >= 7 may elide them for certain symbols
4721          (gold does this).  */
4722       int attrs_valid =
4723         (index.version >= 7
4724          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4725
4726       /* Work around gold/15646.  */
4727       if (attrs_valid)
4728         {
4729           if (!is_static && global_seen)
4730             continue;
4731           if (!is_static)
4732             global_seen = true;
4733         }
4734
4735       /* Only check the symbol's kind if it has one.  */
4736       if (attrs_valid)
4737         {
4738           switch (kind)
4739             {
4740             case VARIABLES_DOMAIN:
4741               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4742                 continue;
4743               break;
4744             case FUNCTIONS_DOMAIN:
4745               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4746                 continue;
4747               break;
4748             case TYPES_DOMAIN:
4749               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4750                 continue;
4751               break;
4752             case MODULES_DOMAIN:
4753               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4754                 continue;
4755               break;
4756             default:
4757               break;
4758             }
4759         }
4760
4761       /* Don't crash on bad data.  */
4762       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
4763                        + dwarf2_per_objfile->all_type_units.size ()))
4764         {
4765           complaint (_(".gdb_index entry has bad CU index"
4766                        " [in module %s]"),
4767                        objfile_name (dwarf2_per_objfile->objfile));
4768           continue;
4769         }
4770
4771       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
4772       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
4773                                        expansion_notify);
4774     }
4775 }
4776
4777 /* If FILE_MATCHER is non-NULL, set all the
4778    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
4779    that match FILE_MATCHER.  */
4780
4781 static void
4782 dw_expand_symtabs_matching_file_matcher
4783   (struct dwarf2_per_objfile *dwarf2_per_objfile,
4784    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
4785 {
4786   if (file_matcher == NULL)
4787     return;
4788
4789   objfile *const objfile = dwarf2_per_objfile->objfile;
4790
4791   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4792                                             htab_eq_pointer,
4793                                             NULL, xcalloc, xfree));
4794   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4795                                                 htab_eq_pointer,
4796                                                 NULL, xcalloc, xfree));
4797
4798   /* The rule is CUs specify all the files, including those used by
4799      any TU, so there's no need to scan TUs here.  */
4800
4801   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4802     {
4803       QUIT;
4804
4805       per_cu->v.quick->mark = 0;
4806
4807       /* We only need to look at symtabs not already expanded.  */
4808       if (per_cu->v.quick->compunit_symtab)
4809         continue;
4810
4811       quick_file_names *file_data = dw2_get_file_names (per_cu);
4812       if (file_data == NULL)
4813         continue;
4814
4815       if (htab_find (visited_not_found.get (), file_data) != NULL)
4816         continue;
4817       else if (htab_find (visited_found.get (), file_data) != NULL)
4818         {
4819           per_cu->v.quick->mark = 1;
4820           continue;
4821         }
4822
4823       for (int j = 0; j < file_data->num_file_names; ++j)
4824         {
4825           const char *this_real_name;
4826
4827           if (file_matcher (file_data->file_names[j], false))
4828             {
4829               per_cu->v.quick->mark = 1;
4830               break;
4831             }
4832
4833           /* Before we invoke realpath, which can get expensive when many
4834              files are involved, do a quick comparison of the basenames.  */
4835           if (!basenames_may_differ
4836               && !file_matcher (lbasename (file_data->file_names[j]),
4837                                 true))
4838             continue;
4839
4840           this_real_name = dw2_get_real_path (objfile, file_data, j);
4841           if (file_matcher (this_real_name, false))
4842             {
4843               per_cu->v.quick->mark = 1;
4844               break;
4845             }
4846         }
4847
4848       void **slot = htab_find_slot (per_cu->v.quick->mark
4849                                     ? visited_found.get ()
4850                                     : visited_not_found.get (),
4851                                     file_data, INSERT);
4852       *slot = file_data;
4853     }
4854 }
4855
4856 static void
4857 dw2_expand_symtabs_matching
4858   (struct objfile *objfile,
4859    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4860    const lookup_name_info &lookup_name,
4861    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4862    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4863    enum search_domain kind)
4864 {
4865   struct dwarf2_per_objfile *dwarf2_per_objfile
4866     = get_dwarf2_per_objfile (objfile);
4867
4868   /* index_table is NULL if OBJF_READNOW.  */
4869   if (!dwarf2_per_objfile->index_table)
4870     return;
4871
4872   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
4873
4874   mapped_index &index = *dwarf2_per_objfile->index_table;
4875
4876   dw2_expand_symtabs_matching_symbol (index, lookup_name,
4877                                       symbol_matcher,
4878                                       kind, [&] (offset_type idx)
4879     {
4880       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
4881                              expansion_notify, kind);
4882       return true;
4883     });
4884 }
4885
4886 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4887    symtab.  */
4888
4889 static struct compunit_symtab *
4890 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4891                                           CORE_ADDR pc)
4892 {
4893   int i;
4894
4895   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4896       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4897     return cust;
4898
4899   if (cust->includes == NULL)
4900     return NULL;
4901
4902   for (i = 0; cust->includes[i]; ++i)
4903     {
4904       struct compunit_symtab *s = cust->includes[i];
4905
4906       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4907       if (s != NULL)
4908         return s;
4909     }
4910
4911   return NULL;
4912 }
4913
4914 static struct compunit_symtab *
4915 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4916                                   struct bound_minimal_symbol msymbol,
4917                                   CORE_ADDR pc,
4918                                   struct obj_section *section,
4919                                   int warn_if_readin)
4920 {
4921   struct dwarf2_per_cu_data *data;
4922   struct compunit_symtab *result;
4923
4924   if (!objfile->partial_symtabs->psymtabs_addrmap)
4925     return NULL;
4926
4927   CORE_ADDR baseaddr = objfile->text_section_offset ();
4928   data = (struct dwarf2_per_cu_data *) addrmap_find
4929     (objfile->partial_symtabs->psymtabs_addrmap, pc - baseaddr);
4930   if (!data)
4931     return NULL;
4932
4933   if (warn_if_readin && data->v.quick->compunit_symtab)
4934     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4935              paddress (get_objfile_arch (objfile), pc));
4936
4937   result
4938     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
4939                                                                         false),
4940                                                 pc);
4941   gdb_assert (result != NULL);
4942   return result;
4943 }
4944
4945 static void
4946 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4947                           void *data, int need_fullname)
4948 {
4949   struct dwarf2_per_objfile *dwarf2_per_objfile
4950     = get_dwarf2_per_objfile (objfile);
4951
4952   if (!dwarf2_per_objfile->filenames_cache)
4953     {
4954       dwarf2_per_objfile->filenames_cache.emplace ();
4955
4956       htab_up visited (htab_create_alloc (10,
4957                                           htab_hash_pointer, htab_eq_pointer,
4958                                           NULL, xcalloc, xfree));
4959
4960       /* The rule is CUs specify all the files, including those used
4961          by any TU, so there's no need to scan TUs here.  We can
4962          ignore file names coming from already-expanded CUs.  */
4963
4964       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4965         {
4966           if (per_cu->v.quick->compunit_symtab)
4967             {
4968               void **slot = htab_find_slot (visited.get (),
4969                                             per_cu->v.quick->file_names,
4970                                             INSERT);
4971
4972               *slot = per_cu->v.quick->file_names;
4973             }
4974         }
4975
4976       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4977         {
4978           /* We only need to look at symtabs not already expanded.  */
4979           if (per_cu->v.quick->compunit_symtab)
4980             continue;
4981
4982           quick_file_names *file_data = dw2_get_file_names (per_cu);
4983           if (file_data == NULL)
4984             continue;
4985
4986           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
4987           if (*slot)
4988             {
4989               /* Already visited.  */
4990               continue;
4991             }
4992           *slot = file_data;
4993
4994           for (int j = 0; j < file_data->num_file_names; ++j)
4995             {
4996               const char *filename = file_data->file_names[j];
4997               dwarf2_per_objfile->filenames_cache->seen (filename);
4998             }
4999         }
5000     }
5001
5002   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5003     {
5004       gdb::unique_xmalloc_ptr<char> this_real_name;
5005
5006       if (need_fullname)
5007         this_real_name = gdb_realpath (filename);
5008       (*fun) (filename, this_real_name.get (), data);
5009     });
5010 }
5011
5012 static int
5013 dw2_has_symbols (struct objfile *objfile)
5014 {
5015   return 1;
5016 }
5017
5018 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5019 {
5020   dw2_has_symbols,
5021   dw2_find_last_source_symtab,
5022   dw2_forget_cached_source_info,
5023   dw2_map_symtabs_matching_filename,
5024   dw2_lookup_symbol,
5025   dw2_print_stats,
5026   dw2_dump,
5027   dw2_expand_symtabs_for_function,
5028   dw2_expand_all_symtabs,
5029   dw2_expand_symtabs_with_fullname,
5030   dw2_map_matching_symbols,
5031   dw2_expand_symtabs_matching,
5032   dw2_find_pc_sect_compunit_symtab,
5033   NULL,
5034   dw2_map_symbol_filenames
5035 };
5036
5037 /* DWARF-5 debug_names reader.  */
5038
5039 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5040 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5041
5042 /* A helper function that reads the .debug_names section in SECTION
5043    and fills in MAP.  FILENAME is the name of the file containing the
5044    section; it is used for error reporting.
5045
5046    Returns true if all went well, false otherwise.  */
5047
5048 static bool
5049 read_debug_names_from_section (struct objfile *objfile,
5050                                const char *filename,
5051                                struct dwarf2_section_info *section,
5052                                mapped_debug_names &map)
5053 {
5054   if (section->empty ())
5055     return false;
5056
5057   /* Older elfutils strip versions could keep the section in the main
5058      executable while splitting it for the separate debug info file.  */
5059   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5060     return false;
5061
5062   section->read (objfile);
5063
5064   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5065
5066   const gdb_byte *addr = section->buffer;
5067
5068   bfd *const abfd = section->get_bfd_owner ();
5069
5070   unsigned int bytes_read;
5071   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5072   addr += bytes_read;
5073
5074   map.dwarf5_is_dwarf64 = bytes_read != 4;
5075   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5076   if (bytes_read + length != section->size)
5077     {
5078       /* There may be multiple per-CU indices.  */
5079       warning (_("Section .debug_names in %s length %s does not match "
5080                  "section length %s, ignoring .debug_names."),
5081                filename, plongest (bytes_read + length),
5082                pulongest (section->size));
5083       return false;
5084     }
5085
5086   /* The version number.  */
5087   uint16_t version = read_2_bytes (abfd, addr);
5088   addr += 2;
5089   if (version != 5)
5090     {
5091       warning (_("Section .debug_names in %s has unsupported version %d, "
5092                  "ignoring .debug_names."),
5093                filename, version);
5094       return false;
5095     }
5096
5097   /* Padding.  */
5098   uint16_t padding = read_2_bytes (abfd, addr);
5099   addr += 2;
5100   if (padding != 0)
5101     {
5102       warning (_("Section .debug_names in %s has unsupported padding %d, "
5103                  "ignoring .debug_names."),
5104                filename, padding);
5105       return false;
5106     }
5107
5108   /* comp_unit_count - The number of CUs in the CU list.  */
5109   map.cu_count = read_4_bytes (abfd, addr);
5110   addr += 4;
5111
5112   /* local_type_unit_count - The number of TUs in the local TU
5113      list.  */
5114   map.tu_count = read_4_bytes (abfd, addr);
5115   addr += 4;
5116
5117   /* foreign_type_unit_count - The number of TUs in the foreign TU
5118      list.  */
5119   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5120   addr += 4;
5121   if (foreign_tu_count != 0)
5122     {
5123       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5124                  "ignoring .debug_names."),
5125                filename, static_cast<unsigned long> (foreign_tu_count));
5126       return false;
5127     }
5128
5129   /* bucket_count - The number of hash buckets in the hash lookup
5130      table.  */
5131   map.bucket_count = read_4_bytes (abfd, addr);
5132   addr += 4;
5133
5134   /* name_count - The number of unique names in the index.  */
5135   map.name_count = read_4_bytes (abfd, addr);
5136   addr += 4;
5137
5138   /* abbrev_table_size - The size in bytes of the abbreviations
5139      table.  */
5140   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5141   addr += 4;
5142
5143   /* augmentation_string_size - The size in bytes of the augmentation
5144      string.  This value is rounded up to a multiple of 4.  */
5145   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5146   addr += 4;
5147   map.augmentation_is_gdb = ((augmentation_string_size
5148                               == sizeof (dwarf5_augmentation))
5149                              && memcmp (addr, dwarf5_augmentation,
5150                                         sizeof (dwarf5_augmentation)) == 0);
5151   augmentation_string_size += (-augmentation_string_size) & 3;
5152   addr += augmentation_string_size;
5153
5154   /* List of CUs */
5155   map.cu_table_reordered = addr;
5156   addr += map.cu_count * map.offset_size;
5157
5158   /* List of Local TUs */
5159   map.tu_table_reordered = addr;
5160   addr += map.tu_count * map.offset_size;
5161
5162   /* Hash Lookup Table */
5163   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5164   addr += map.bucket_count * 4;
5165   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5166   addr += map.name_count * 4;
5167
5168   /* Name Table */
5169   map.name_table_string_offs_reordered = addr;
5170   addr += map.name_count * map.offset_size;
5171   map.name_table_entry_offs_reordered = addr;
5172   addr += map.name_count * map.offset_size;
5173
5174   const gdb_byte *abbrev_table_start = addr;
5175   for (;;)
5176     {
5177       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5178       addr += bytes_read;
5179       if (index_num == 0)
5180         break;
5181
5182       const auto insertpair
5183         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5184       if (!insertpair.second)
5185         {
5186           warning (_("Section .debug_names in %s has duplicate index %s, "
5187                      "ignoring .debug_names."),
5188                    filename, pulongest (index_num));
5189           return false;
5190         }
5191       mapped_debug_names::index_val &indexval = insertpair.first->second;
5192       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5193       addr += bytes_read;
5194
5195       for (;;)
5196         {
5197           mapped_debug_names::index_val::attr attr;
5198           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5199           addr += bytes_read;
5200           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5201           addr += bytes_read;
5202           if (attr.form == DW_FORM_implicit_const)
5203             {
5204               attr.implicit_const = read_signed_leb128 (abfd, addr,
5205                                                         &bytes_read);
5206               addr += bytes_read;
5207             }
5208           if (attr.dw_idx == 0 && attr.form == 0)
5209             break;
5210           indexval.attr_vec.push_back (std::move (attr));
5211         }
5212     }
5213   if (addr != abbrev_table_start + abbrev_table_size)
5214     {
5215       warning (_("Section .debug_names in %s has abbreviation_table "
5216                  "of size %s vs. written as %u, ignoring .debug_names."),
5217                filename, plongest (addr - abbrev_table_start),
5218                abbrev_table_size);
5219       return false;
5220     }
5221   map.entry_pool = addr;
5222
5223   return true;
5224 }
5225
5226 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5227    list.  */
5228
5229 static void
5230 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5231                                   const mapped_debug_names &map,
5232                                   dwarf2_section_info &section,
5233                                   bool is_dwz)
5234 {
5235   sect_offset sect_off_prev;
5236   for (uint32_t i = 0; i <= map.cu_count; ++i)
5237     {
5238       sect_offset sect_off_next;
5239       if (i < map.cu_count)
5240         {
5241           sect_off_next
5242             = (sect_offset) (extract_unsigned_integer
5243                              (map.cu_table_reordered + i * map.offset_size,
5244                               map.offset_size,
5245                               map.dwarf5_byte_order));
5246         }
5247       else
5248         sect_off_next = (sect_offset) section.size;
5249       if (i >= 1)
5250         {
5251           const ULONGEST length = sect_off_next - sect_off_prev;
5252           dwarf2_per_cu_data *per_cu
5253             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5254                                          sect_off_prev, length);
5255           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5256         }
5257       sect_off_prev = sect_off_next;
5258     }
5259 }
5260
5261 /* Read the CU list from the mapped index, and use it to create all
5262    the CU objects for this dwarf2_per_objfile.  */
5263
5264 static void
5265 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5266                              const mapped_debug_names &map,
5267                              const mapped_debug_names &dwz_map)
5268 {
5269   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5270   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5271
5272   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5273                                     dwarf2_per_objfile->info,
5274                                     false /* is_dwz */);
5275
5276   if (dwz_map.cu_count == 0)
5277     return;
5278
5279   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5280   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5281                                     true /* is_dwz */);
5282 }
5283
5284 /* Read .debug_names.  If everything went ok, initialize the "quick"
5285    elements of all the CUs and return true.  Otherwise, return false.  */
5286
5287 static bool
5288 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5289 {
5290   std::unique_ptr<mapped_debug_names> map
5291     (new mapped_debug_names (dwarf2_per_objfile));
5292   mapped_debug_names dwz_map (dwarf2_per_objfile);
5293   struct objfile *objfile = dwarf2_per_objfile->objfile;
5294
5295   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5296                                       &dwarf2_per_objfile->debug_names,
5297                                       *map))
5298     return false;
5299
5300   /* Don't use the index if it's empty.  */
5301   if (map->name_count == 0)
5302     return false;
5303
5304   /* If there is a .dwz file, read it so we can get its CU list as
5305      well.  */
5306   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5307   if (dwz != NULL)
5308     {
5309       if (!read_debug_names_from_section (objfile,
5310                                           bfd_get_filename (dwz->dwz_bfd.get ()),
5311                                           &dwz->debug_names, dwz_map))
5312         {
5313           warning (_("could not read '.debug_names' section from %s; skipping"),
5314                    bfd_get_filename (dwz->dwz_bfd.get ()));
5315           return false;
5316         }
5317     }
5318
5319   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5320
5321   if (map->tu_count != 0)
5322     {
5323       /* We can only handle a single .debug_types when we have an
5324          index.  */
5325       if (dwarf2_per_objfile->types.size () != 1)
5326         return false;
5327
5328       dwarf2_section_info *section = &dwarf2_per_objfile->types[0];
5329
5330       create_signatured_type_table_from_debug_names
5331         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5332     }
5333
5334   create_addrmap_from_aranges (dwarf2_per_objfile,
5335                                &dwarf2_per_objfile->debug_aranges);
5336
5337   dwarf2_per_objfile->debug_names_table = std::move (map);
5338   dwarf2_per_objfile->using_index = 1;
5339   dwarf2_per_objfile->quick_file_names_table =
5340     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5341
5342   return true;
5343 }
5344
5345 /* Type used to manage iterating over all CUs looking for a symbol for
5346    .debug_names.  */
5347
5348 class dw2_debug_names_iterator
5349 {
5350 public:
5351   dw2_debug_names_iterator (const mapped_debug_names &map,
5352                             gdb::optional<block_enum> block_index,
5353                             domain_enum domain,
5354                             const char *name)
5355     : m_map (map), m_block_index (block_index), m_domain (domain),
5356       m_addr (find_vec_in_debug_names (map, name))
5357   {}
5358
5359   dw2_debug_names_iterator (const mapped_debug_names &map,
5360                             search_domain search, uint32_t namei)
5361     : m_map (map),
5362       m_search (search),
5363       m_addr (find_vec_in_debug_names (map, namei))
5364   {}
5365
5366   dw2_debug_names_iterator (const mapped_debug_names &map,
5367                             block_enum block_index, domain_enum domain,
5368                             uint32_t namei)
5369     : m_map (map), m_block_index (block_index), m_domain (domain),
5370       m_addr (find_vec_in_debug_names (map, namei))
5371   {}
5372
5373   /* Return the next matching CU or NULL if there are no more.  */
5374   dwarf2_per_cu_data *next ();
5375
5376 private:
5377   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5378                                                   const char *name);
5379   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5380                                                   uint32_t namei);
5381
5382   /* The internalized form of .debug_names.  */
5383   const mapped_debug_names &m_map;
5384
5385   /* If set, only look for symbols that match that block.  Valid values are
5386      GLOBAL_BLOCK and STATIC_BLOCK.  */
5387   const gdb::optional<block_enum> m_block_index;
5388
5389   /* The kind of symbol we're looking for.  */
5390   const domain_enum m_domain = UNDEF_DOMAIN;
5391   const search_domain m_search = ALL_DOMAIN;
5392
5393   /* The list of CUs from the index entry of the symbol, or NULL if
5394      not found.  */
5395   const gdb_byte *m_addr;
5396 };
5397
5398 const char *
5399 mapped_debug_names::namei_to_name (uint32_t namei) const
5400 {
5401   const ULONGEST namei_string_offs
5402     = extract_unsigned_integer ((name_table_string_offs_reordered
5403                                  + namei * offset_size),
5404                                 offset_size,
5405                                 dwarf5_byte_order);
5406   return read_indirect_string_at_offset
5407     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5408 }
5409
5410 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5411    found, return pointer to its pool data.  If NAME cannot be found,
5412    return NULL.  */
5413
5414 const gdb_byte *
5415 dw2_debug_names_iterator::find_vec_in_debug_names
5416   (const mapped_debug_names &map, const char *name)
5417 {
5418   int (*cmp) (const char *, const char *);
5419
5420   gdb::unique_xmalloc_ptr<char> without_params;
5421   if (current_language->la_language == language_cplus
5422       || current_language->la_language == language_fortran
5423       || current_language->la_language == language_d)
5424     {
5425       /* NAME is already canonical.  Drop any qualifiers as
5426          .debug_names does not contain any.  */
5427
5428       if (strchr (name, '(') != NULL)
5429         {
5430           without_params = cp_remove_params (name);
5431           if (without_params != NULL)
5432             name = without_params.get ();
5433         }
5434     }
5435
5436   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5437
5438   const uint32_t full_hash = dwarf5_djb_hash (name);
5439   uint32_t namei
5440     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5441                                 (map.bucket_table_reordered
5442                                  + (full_hash % map.bucket_count)), 4,
5443                                 map.dwarf5_byte_order);
5444   if (namei == 0)
5445     return NULL;
5446   --namei;
5447   if (namei >= map.name_count)
5448     {
5449       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5450                    "[in module %s]"),
5451                  namei, map.name_count,
5452                  objfile_name (map.dwarf2_per_objfile->objfile));
5453       return NULL;
5454     }
5455
5456   for (;;)
5457     {
5458       const uint32_t namei_full_hash
5459         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5460                                     (map.hash_table_reordered + namei), 4,
5461                                     map.dwarf5_byte_order);
5462       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5463         return NULL;
5464
5465       if (full_hash == namei_full_hash)
5466         {
5467           const char *const namei_string = map.namei_to_name (namei);
5468
5469 #if 0 /* An expensive sanity check.  */
5470           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5471             {
5472               complaint (_("Wrong .debug_names hash for string at index %u "
5473                            "[in module %s]"),
5474                          namei, objfile_name (dwarf2_per_objfile->objfile));
5475               return NULL;
5476             }
5477 #endif
5478
5479           if (cmp (namei_string, name) == 0)
5480             {
5481               const ULONGEST namei_entry_offs
5482                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5483                                              + namei * map.offset_size),
5484                                             map.offset_size, map.dwarf5_byte_order);
5485               return map.entry_pool + namei_entry_offs;
5486             }
5487         }
5488
5489       ++namei;
5490       if (namei >= map.name_count)
5491         return NULL;
5492     }
5493 }
5494
5495 const gdb_byte *
5496 dw2_debug_names_iterator::find_vec_in_debug_names
5497   (const mapped_debug_names &map, uint32_t namei)
5498 {
5499   if (namei >= map.name_count)
5500     {
5501       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5502                    "[in module %s]"),
5503                  namei, map.name_count,
5504                  objfile_name (map.dwarf2_per_objfile->objfile));
5505       return NULL;
5506     }
5507
5508   const ULONGEST namei_entry_offs
5509     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5510                                  + namei * map.offset_size),
5511                                 map.offset_size, map.dwarf5_byte_order);
5512   return map.entry_pool + namei_entry_offs;
5513 }
5514
5515 /* See dw2_debug_names_iterator.  */
5516
5517 dwarf2_per_cu_data *
5518 dw2_debug_names_iterator::next ()
5519 {
5520   if (m_addr == NULL)
5521     return NULL;
5522
5523   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5524   struct objfile *objfile = dwarf2_per_objfile->objfile;
5525   bfd *const abfd = objfile->obfd;
5526
5527  again:
5528
5529   unsigned int bytes_read;
5530   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5531   m_addr += bytes_read;
5532   if (abbrev == 0)
5533     return NULL;
5534
5535   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5536   if (indexval_it == m_map.abbrev_map.cend ())
5537     {
5538       complaint (_("Wrong .debug_names undefined abbrev code %s "
5539                    "[in module %s]"),
5540                  pulongest (abbrev), objfile_name (objfile));
5541       return NULL;
5542     }
5543   const mapped_debug_names::index_val &indexval = indexval_it->second;
5544   enum class symbol_linkage {
5545     unknown,
5546     static_,
5547     extern_,
5548   } symbol_linkage_ = symbol_linkage::unknown;
5549   dwarf2_per_cu_data *per_cu = NULL;
5550   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5551     {
5552       ULONGEST ull;
5553       switch (attr.form)
5554         {
5555         case DW_FORM_implicit_const:
5556           ull = attr.implicit_const;
5557           break;
5558         case DW_FORM_flag_present:
5559           ull = 1;
5560           break;
5561         case DW_FORM_udata:
5562           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5563           m_addr += bytes_read;
5564           break;
5565         default:
5566           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5567                      dwarf_form_name (attr.form),
5568                      objfile_name (objfile));
5569           return NULL;
5570         }
5571       switch (attr.dw_idx)
5572         {
5573         case DW_IDX_compile_unit:
5574           /* Don't crash on bad data.  */
5575           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5576             {
5577               complaint (_(".debug_names entry has bad CU index %s"
5578                            " [in module %s]"),
5579                          pulongest (ull),
5580                          objfile_name (dwarf2_per_objfile->objfile));
5581               continue;
5582             }
5583           per_cu = dwarf2_per_objfile->get_cutu (ull);
5584           break;
5585         case DW_IDX_type_unit:
5586           /* Don't crash on bad data.  */
5587           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5588             {
5589               complaint (_(".debug_names entry has bad TU index %s"
5590                            " [in module %s]"),
5591                          pulongest (ull),
5592                          objfile_name (dwarf2_per_objfile->objfile));
5593               continue;
5594             }
5595           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5596           break;
5597         case DW_IDX_GNU_internal:
5598           if (!m_map.augmentation_is_gdb)
5599             break;
5600           symbol_linkage_ = symbol_linkage::static_;
5601           break;
5602         case DW_IDX_GNU_external:
5603           if (!m_map.augmentation_is_gdb)
5604             break;
5605           symbol_linkage_ = symbol_linkage::extern_;
5606           break;
5607         }
5608     }
5609
5610   /* Skip if already read in.  */
5611   if (per_cu->v.quick->compunit_symtab)
5612     goto again;
5613
5614   /* Check static vs global.  */
5615   if (symbol_linkage_ != symbol_linkage::unknown && m_block_index.has_value ())
5616     {
5617         const bool want_static = *m_block_index == STATIC_BLOCK;
5618         const bool symbol_is_static =
5619           symbol_linkage_ == symbol_linkage::static_;
5620         if (want_static != symbol_is_static)
5621           goto again;
5622     }
5623
5624   /* Match dw2_symtab_iter_next, symbol_kind
5625      and debug_names::psymbol_tag.  */
5626   switch (m_domain)
5627     {
5628     case VAR_DOMAIN:
5629       switch (indexval.dwarf_tag)
5630         {
5631         case DW_TAG_variable:
5632         case DW_TAG_subprogram:
5633         /* Some types are also in VAR_DOMAIN.  */
5634         case DW_TAG_typedef:
5635         case DW_TAG_structure_type:
5636           break;
5637         default:
5638           goto again;
5639         }
5640       break;
5641     case STRUCT_DOMAIN:
5642       switch (indexval.dwarf_tag)
5643         {
5644         case DW_TAG_typedef:
5645         case DW_TAG_structure_type:
5646           break;
5647         default:
5648           goto again;
5649         }
5650       break;
5651     case LABEL_DOMAIN:
5652       switch (indexval.dwarf_tag)
5653         {
5654         case 0:
5655         case DW_TAG_variable:
5656           break;
5657         default:
5658           goto again;
5659         }
5660       break;
5661     case MODULE_DOMAIN:
5662       switch (indexval.dwarf_tag)
5663         {
5664         case DW_TAG_module:
5665           break;
5666         default:
5667           goto again;
5668         }
5669       break;
5670     default:
5671       break;
5672     }
5673
5674   /* Match dw2_expand_symtabs_matching, symbol_kind and
5675      debug_names::psymbol_tag.  */
5676   switch (m_search)
5677     {
5678     case VARIABLES_DOMAIN:
5679       switch (indexval.dwarf_tag)
5680         {
5681         case DW_TAG_variable:
5682           break;
5683         default:
5684           goto again;
5685         }
5686       break;
5687     case FUNCTIONS_DOMAIN:
5688       switch (indexval.dwarf_tag)
5689         {
5690         case DW_TAG_subprogram:
5691           break;
5692         default:
5693           goto again;
5694         }
5695       break;
5696     case TYPES_DOMAIN:
5697       switch (indexval.dwarf_tag)
5698         {
5699         case DW_TAG_typedef:
5700         case DW_TAG_structure_type:
5701           break;
5702         default:
5703           goto again;
5704         }
5705       break;
5706     case MODULES_DOMAIN:
5707       switch (indexval.dwarf_tag)
5708         {
5709         case DW_TAG_module:
5710           break;
5711         default:
5712           goto again;
5713         }
5714     default:
5715       break;
5716     }
5717
5718   return per_cu;
5719 }
5720
5721 static struct compunit_symtab *
5722 dw2_debug_names_lookup_symbol (struct objfile *objfile, block_enum block_index,
5723                                const char *name, domain_enum domain)
5724 {
5725   struct dwarf2_per_objfile *dwarf2_per_objfile
5726     = get_dwarf2_per_objfile (objfile);
5727
5728   const auto &mapp = dwarf2_per_objfile->debug_names_table;
5729   if (!mapp)
5730     {
5731       /* index is NULL if OBJF_READNOW.  */
5732       return NULL;
5733     }
5734   const auto &map = *mapp;
5735
5736   dw2_debug_names_iterator iter (map, block_index, domain, name);
5737
5738   struct compunit_symtab *stab_best = NULL;
5739   struct dwarf2_per_cu_data *per_cu;
5740   while ((per_cu = iter.next ()) != NULL)
5741     {
5742       struct symbol *sym, *with_opaque = NULL;
5743       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
5744       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
5745       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
5746
5747       sym = block_find_symbol (block, name, domain,
5748                                block_find_non_opaque_type_preferred,
5749                                &with_opaque);
5750
5751       /* Some caution must be observed with overloaded functions and
5752          methods, since the index will not contain any overload
5753          information (but NAME might contain it).  */
5754
5755       if (sym != NULL
5756           && strcmp_iw (sym->search_name (), name) == 0)
5757         return stab;
5758       if (with_opaque != NULL
5759           && strcmp_iw (with_opaque->search_name (), name) == 0)
5760         stab_best = stab;
5761
5762       /* Keep looking through other CUs.  */
5763     }
5764
5765   return stab_best;
5766 }
5767
5768 /* This dumps minimal information about .debug_names.  It is called
5769    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
5770    uses this to verify that .debug_names has been loaded.  */
5771
5772 static void
5773 dw2_debug_names_dump (struct objfile *objfile)
5774 {
5775   struct dwarf2_per_objfile *dwarf2_per_objfile
5776     = get_dwarf2_per_objfile (objfile);
5777
5778   gdb_assert (dwarf2_per_objfile->using_index);
5779   printf_filtered (".debug_names:");
5780   if (dwarf2_per_objfile->debug_names_table)
5781     printf_filtered (" exists\n");
5782   else
5783     printf_filtered (" faked for \"readnow\"\n");
5784   printf_filtered ("\n");
5785 }
5786
5787 static void
5788 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
5789                                              const char *func_name)
5790 {
5791   struct dwarf2_per_objfile *dwarf2_per_objfile
5792     = get_dwarf2_per_objfile (objfile);
5793
5794   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
5795   if (dwarf2_per_objfile->debug_names_table)
5796     {
5797       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5798
5799       dw2_debug_names_iterator iter (map, {}, VAR_DOMAIN, func_name);
5800
5801       struct dwarf2_per_cu_data *per_cu;
5802       while ((per_cu = iter.next ()) != NULL)
5803         dw2_instantiate_symtab (per_cu, false);
5804     }
5805 }
5806
5807 static void
5808 dw2_debug_names_map_matching_symbols
5809   (struct objfile *objfile,
5810    const lookup_name_info &name, domain_enum domain,
5811    int global,
5812    gdb::function_view<symbol_found_callback_ftype> callback,
5813    symbol_compare_ftype *ordered_compare)
5814 {
5815   struct dwarf2_per_objfile *dwarf2_per_objfile
5816     = get_dwarf2_per_objfile (objfile);
5817
5818   /* debug_names_table is NULL if OBJF_READNOW.  */
5819   if (!dwarf2_per_objfile->debug_names_table)
5820     return;
5821
5822   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5823   const block_enum block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5824
5825   const char *match_name = name.ada ().lookup_name ().c_str ();
5826   auto matcher = [&] (const char *symname)
5827     {
5828       if (ordered_compare == nullptr)
5829         return true;
5830       return ordered_compare (symname, match_name) == 0;
5831     };
5832
5833   dw2_expand_symtabs_matching_symbol (map, name, matcher, ALL_DOMAIN,
5834                                       [&] (offset_type namei)
5835     {
5836       /* The name was matched, now expand corresponding CUs that were
5837          marked.  */
5838       dw2_debug_names_iterator iter (map, block_kind, domain, namei);
5839
5840       struct dwarf2_per_cu_data *per_cu;
5841       while ((per_cu = iter.next ()) != NULL)
5842         dw2_expand_symtabs_matching_one (per_cu, nullptr, nullptr);
5843       return true;
5844     });
5845
5846   /* It's a shame we couldn't do this inside the
5847      dw2_expand_symtabs_matching_symbol callback, but that skips CUs
5848      that have already been expanded.  Instead, this loop matches what
5849      the psymtab code does.  */
5850   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5851     {
5852       struct compunit_symtab *cust = per_cu->v.quick->compunit_symtab;
5853       if (cust != nullptr)
5854         {
5855           const struct block *block
5856             = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cust), block_kind);
5857           if (!iterate_over_symbols_terminated (block, name,
5858                                                 domain, callback))
5859             break;
5860         }
5861     }
5862 }
5863
5864 static void
5865 dw2_debug_names_expand_symtabs_matching
5866   (struct objfile *objfile,
5867    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5868    const lookup_name_info &lookup_name,
5869    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5870    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5871    enum search_domain kind)
5872 {
5873   struct dwarf2_per_objfile *dwarf2_per_objfile
5874     = get_dwarf2_per_objfile (objfile);
5875
5876   /* debug_names_table is NULL if OBJF_READNOW.  */
5877   if (!dwarf2_per_objfile->debug_names_table)
5878     return;
5879
5880   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5881
5882   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5883
5884   dw2_expand_symtabs_matching_symbol (map, lookup_name,
5885                                       symbol_matcher,
5886                                       kind, [&] (offset_type namei)
5887     {
5888       /* The name was matched, now expand corresponding CUs that were
5889          marked.  */
5890       dw2_debug_names_iterator iter (map, kind, namei);
5891
5892       struct dwarf2_per_cu_data *per_cu;
5893       while ((per_cu = iter.next ()) != NULL)
5894         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5895                                          expansion_notify);
5896       return true;
5897     });
5898 }
5899
5900 const struct quick_symbol_functions dwarf2_debug_names_functions =
5901 {
5902   dw2_has_symbols,
5903   dw2_find_last_source_symtab,
5904   dw2_forget_cached_source_info,
5905   dw2_map_symtabs_matching_filename,
5906   dw2_debug_names_lookup_symbol,
5907   dw2_print_stats,
5908   dw2_debug_names_dump,
5909   dw2_debug_names_expand_symtabs_for_function,
5910   dw2_expand_all_symtabs,
5911   dw2_expand_symtabs_with_fullname,
5912   dw2_debug_names_map_matching_symbols,
5913   dw2_debug_names_expand_symtabs_matching,
5914   dw2_find_pc_sect_compunit_symtab,
5915   NULL,
5916   dw2_map_symbol_filenames
5917 };
5918
5919 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
5920    to either a dwarf2_per_objfile or dwz_file object.  */
5921
5922 template <typename T>
5923 static gdb::array_view<const gdb_byte>
5924 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
5925 {
5926   dwarf2_section_info *section = &section_owner->gdb_index;
5927
5928   if (section->empty ())
5929     return {};
5930
5931   /* Older elfutils strip versions could keep the section in the main
5932      executable while splitting it for the separate debug info file.  */
5933   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5934     return {};
5935
5936   section->read (obj);
5937
5938   /* dwarf2_section_info::size is a bfd_size_type, while
5939      gdb::array_view works with size_t.  On 32-bit hosts, with
5940      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
5941      is 32-bit.  So we need an explicit narrowing conversion here.
5942      This is fine, because it's impossible to allocate or mmap an
5943      array/buffer larger than what size_t can represent.  */
5944   return gdb::make_array_view (section->buffer, section->size);
5945 }
5946
5947 /* Lookup the index cache for the contents of the index associated to
5948    DWARF2_OBJ.  */
5949
5950 static gdb::array_view<const gdb_byte>
5951 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_objfile *dwarf2_obj)
5952 {
5953   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
5954   if (build_id == nullptr)
5955     return {};
5956
5957   return global_index_cache.lookup_gdb_index (build_id,
5958                                               &dwarf2_obj->index_cache_res);
5959 }
5960
5961 /* Same as the above, but for DWZ.  */
5962
5963 static gdb::array_view<const gdb_byte>
5964 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
5965 {
5966   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
5967   if (build_id == nullptr)
5968     return {};
5969
5970   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
5971 }
5972
5973 /* See symfile.h.  */
5974
5975 bool
5976 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
5977 {
5978   struct dwarf2_per_objfile *dwarf2_per_objfile
5979     = get_dwarf2_per_objfile (objfile);
5980
5981   /* If we're about to read full symbols, don't bother with the
5982      indices.  In this case we also don't care if some other debug
5983      format is making psymtabs, because they are all about to be
5984      expanded anyway.  */
5985   if ((objfile->flags & OBJF_READNOW))
5986     {
5987       dwarf2_per_objfile->using_index = 1;
5988       create_all_comp_units (dwarf2_per_objfile);
5989       create_all_type_units (dwarf2_per_objfile);
5990       dwarf2_per_objfile->quick_file_names_table
5991         = create_quick_file_names_table
5992             (dwarf2_per_objfile->all_comp_units.size ());
5993
5994       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
5995                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
5996         {
5997           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
5998
5999           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6000                                             struct dwarf2_per_cu_quick_data);
6001         }
6002
6003       /* Return 1 so that gdb sees the "quick" functions.  However,
6004          these functions will be no-ops because we will have expanded
6005          all symtabs.  */
6006       *index_kind = dw_index_kind::GDB_INDEX;
6007       return true;
6008     }
6009
6010   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6011     {
6012       *index_kind = dw_index_kind::DEBUG_NAMES;
6013       return true;
6014     }
6015
6016   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6017                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
6018                              get_gdb_index_contents_from_section<dwz_file>))
6019     {
6020       *index_kind = dw_index_kind::GDB_INDEX;
6021       return true;
6022     }
6023
6024   /* ... otherwise, try to find the index in the index cache.  */
6025   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6026                              get_gdb_index_contents_from_cache,
6027                              get_gdb_index_contents_from_cache_dwz))
6028     {
6029       global_index_cache.hit ();
6030       *index_kind = dw_index_kind::GDB_INDEX;
6031       return true;
6032     }
6033
6034   global_index_cache.miss ();
6035   return false;
6036 }
6037
6038 \f
6039
6040 /* Build a partial symbol table.  */
6041
6042 void
6043 dwarf2_build_psymtabs (struct objfile *objfile)
6044 {
6045   struct dwarf2_per_objfile *dwarf2_per_objfile
6046     = get_dwarf2_per_objfile (objfile);
6047
6048   init_psymbol_list (objfile, 1024);
6049
6050   try
6051     {
6052       /* This isn't really ideal: all the data we allocate on the
6053          objfile's obstack is still uselessly kept around.  However,
6054          freeing it seems unsafe.  */
6055       psymtab_discarder psymtabs (objfile);
6056       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6057       psymtabs.keep ();
6058
6059       /* (maybe) store an index in the cache.  */
6060       global_index_cache.store (dwarf2_per_objfile);
6061     }
6062   catch (const gdb_exception_error &except)
6063     {
6064       exception_print (gdb_stderr, except);
6065     }
6066 }
6067
6068 /* Return the total length of the CU described by HEADER.  */
6069
6070 static unsigned int
6071 get_cu_length (const struct comp_unit_head *header)
6072 {
6073   return header->initial_length_size + header->length;
6074 }
6075
6076 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6077
6078 static inline bool
6079 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6080 {
6081   sect_offset bottom = cu_header->sect_off;
6082   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6083
6084   return sect_off >= bottom && sect_off < top;
6085 }
6086
6087 /* Find the base address of the compilation unit for range lists and
6088    location lists.  It will normally be specified by DW_AT_low_pc.
6089    In DWARF-3 draft 4, the base address could be overridden by
6090    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6091    compilation units with discontinuous ranges.  */
6092
6093 static void
6094 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6095 {
6096   struct attribute *attr;
6097
6098   cu->base_known = 0;
6099   cu->base_address = 0;
6100
6101   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6102   if (attr != nullptr)
6103     {
6104       cu->base_address = attr->value_as_address ();
6105       cu->base_known = 1;
6106     }
6107   else
6108     {
6109       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6110       if (attr != nullptr)
6111         {
6112           cu->base_address = attr->value_as_address ();
6113           cu->base_known = 1;
6114         }
6115     }
6116 }
6117
6118 /* Read in the comp unit header information from the debug_info at info_ptr.
6119    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6120    NOTE: This leaves members offset, first_die_offset to be filled in
6121    by the caller.  */
6122
6123 static const gdb_byte *
6124 read_comp_unit_head (struct comp_unit_head *cu_header,
6125                      const gdb_byte *info_ptr,
6126                      struct dwarf2_section_info *section,
6127                      rcuh_kind section_kind)
6128 {
6129   int signed_addr;
6130   unsigned int bytes_read;
6131   const char *filename = section->get_file_name ();
6132   bfd *abfd = section->get_bfd_owner ();
6133
6134   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6135   cu_header->initial_length_size = bytes_read;
6136   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6137   info_ptr += bytes_read;
6138   cu_header->version = read_2_bytes (abfd, info_ptr);
6139   if (cu_header->version < 2 || cu_header->version > 5)
6140     error (_("Dwarf Error: wrong version in compilation unit header "
6141            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6142            cu_header->version, filename);
6143   info_ptr += 2;
6144   if (cu_header->version < 5)
6145     switch (section_kind)
6146       {
6147       case rcuh_kind::COMPILE:
6148         cu_header->unit_type = DW_UT_compile;
6149         break;
6150       case rcuh_kind::TYPE:
6151         cu_header->unit_type = DW_UT_type;
6152         break;
6153       default:
6154         internal_error (__FILE__, __LINE__,
6155                         _("read_comp_unit_head: invalid section_kind"));
6156       }
6157   else
6158     {
6159       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6160                                                  (read_1_byte (abfd, info_ptr));
6161       info_ptr += 1;
6162       switch (cu_header->unit_type)
6163         {
6164         case DW_UT_compile:
6165         case DW_UT_partial:
6166         case DW_UT_skeleton:
6167         case DW_UT_split_compile:
6168           if (section_kind != rcuh_kind::COMPILE)
6169             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6170                    "(is %s, should be %s) [in module %s]"),
6171                    dwarf_unit_type_name (cu_header->unit_type),
6172                    dwarf_unit_type_name (DW_UT_type), filename);
6173           break;
6174         case DW_UT_type:
6175         case DW_UT_split_type:
6176           section_kind = rcuh_kind::TYPE;
6177           break;
6178         default:
6179           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6180                  "(is %#04x, should be one of: %s, %s, %s, %s or %s) "
6181                  "[in module %s]"), cu_header->unit_type,
6182                  dwarf_unit_type_name (DW_UT_compile),
6183                  dwarf_unit_type_name (DW_UT_skeleton),
6184                  dwarf_unit_type_name (DW_UT_split_compile),
6185                  dwarf_unit_type_name (DW_UT_type),
6186                  dwarf_unit_type_name (DW_UT_split_type), filename);
6187         }
6188
6189       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6190       info_ptr += 1;
6191     }
6192   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6193                                                           cu_header,
6194                                                           &bytes_read);
6195   info_ptr += bytes_read;
6196   if (cu_header->version < 5)
6197     {
6198       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6199       info_ptr += 1;
6200     }
6201   signed_addr = bfd_get_sign_extend_vma (abfd);
6202   if (signed_addr < 0)
6203     internal_error (__FILE__, __LINE__,
6204                     _("read_comp_unit_head: dwarf from non elf file"));
6205   cu_header->signed_addr_p = signed_addr;
6206
6207   bool header_has_signature = section_kind == rcuh_kind::TYPE
6208     || cu_header->unit_type == DW_UT_skeleton
6209     || cu_header->unit_type == DW_UT_split_compile;
6210
6211   if (header_has_signature)
6212     {
6213       cu_header->signature = read_8_bytes (abfd, info_ptr);
6214       info_ptr += 8;
6215     }
6216
6217   if (section_kind == rcuh_kind::TYPE)
6218     {
6219       LONGEST type_offset;
6220       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6221       info_ptr += bytes_read;
6222       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6223       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6224         error (_("Dwarf Error: Too big type_offset in compilation unit "
6225                "header (is %s) [in module %s]"), plongest (type_offset),
6226                filename);
6227     }
6228
6229   return info_ptr;
6230 }
6231
6232 /* Helper function that returns the proper abbrev section for
6233    THIS_CU.  */
6234
6235 static struct dwarf2_section_info *
6236 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6237 {
6238   struct dwarf2_section_info *abbrev;
6239   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6240
6241   if (this_cu->is_dwz)
6242     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6243   else
6244     abbrev = &dwarf2_per_objfile->abbrev;
6245
6246   return abbrev;
6247 }
6248
6249 /* Subroutine of read_and_check_comp_unit_head and
6250    read_and_check_type_unit_head to simplify them.
6251    Perform various error checking on the header.  */
6252
6253 static void
6254 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6255                             struct comp_unit_head *header,
6256                             struct dwarf2_section_info *section,
6257                             struct dwarf2_section_info *abbrev_section)
6258 {
6259   const char *filename = section->get_file_name ();
6260
6261   if (to_underlying (header->abbrev_sect_off)
6262       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6263     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6264            "(offset %s + 6) [in module %s]"),
6265            sect_offset_str (header->abbrev_sect_off),
6266            sect_offset_str (header->sect_off),
6267            filename);
6268
6269   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6270      avoid potential 32-bit overflow.  */
6271   if (((ULONGEST) header->sect_off + get_cu_length (header))
6272       > section->size)
6273     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6274            "(offset %s + 0) [in module %s]"),
6275            header->length, sect_offset_str (header->sect_off),
6276            filename);
6277 }
6278
6279 /* Read in a CU/TU header and perform some basic error checking.
6280    The contents of the header are stored in HEADER.
6281    The result is a pointer to the start of the first DIE.  */
6282
6283 static const gdb_byte *
6284 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6285                                struct comp_unit_head *header,
6286                                struct dwarf2_section_info *section,
6287                                struct dwarf2_section_info *abbrev_section,
6288                                const gdb_byte *info_ptr,
6289                                rcuh_kind section_kind)
6290 {
6291   const gdb_byte *beg_of_comp_unit = info_ptr;
6292
6293   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6294
6295   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6296
6297   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6298
6299   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6300                               abbrev_section);
6301
6302   return info_ptr;
6303 }
6304
6305 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6306
6307 static sect_offset
6308 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6309                     struct dwarf2_section_info *section,
6310                     sect_offset sect_off)
6311 {
6312   bfd *abfd = section->get_bfd_owner ();
6313   const gdb_byte *info_ptr;
6314   unsigned int initial_length_size, offset_size;
6315   uint16_t version;
6316
6317   section->read (dwarf2_per_objfile->objfile);
6318   info_ptr = section->buffer + to_underlying (sect_off);
6319   read_initial_length (abfd, info_ptr, &initial_length_size);
6320   offset_size = initial_length_size == 4 ? 4 : 8;
6321   info_ptr += initial_length_size;
6322
6323   version = read_2_bytes (abfd, info_ptr);
6324   info_ptr += 2;
6325   if (version >= 5)
6326     {
6327       /* Skip unit type and address size.  */
6328       info_ptr += 2;
6329     }
6330
6331   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6332 }
6333
6334 /* Allocate a new partial symtab for file named NAME and mark this new
6335    partial symtab as being an include of PST.  */
6336
6337 static void
6338 dwarf2_create_include_psymtab (const char *name, dwarf2_psymtab *pst,
6339                                struct objfile *objfile)
6340 {
6341   dwarf2_psymtab *subpst = new dwarf2_psymtab (name, objfile);
6342
6343   if (!IS_ABSOLUTE_PATH (subpst->filename))
6344     {
6345       /* It shares objfile->objfile_obstack.  */
6346       subpst->dirname = pst->dirname;
6347     }
6348
6349   subpst->dependencies = objfile->partial_symtabs->allocate_dependencies (1);
6350   subpst->dependencies[0] = pst;
6351   subpst->number_of_dependencies = 1;
6352
6353   /* No private part is necessary for include psymtabs.  This property
6354      can be used to differentiate between such include psymtabs and
6355      the regular ones.  */
6356   subpst->per_cu_data = nullptr;
6357 }
6358
6359 /* Read the Line Number Program data and extract the list of files
6360    included by the source file represented by PST.  Build an include
6361    partial symtab for each of these included files.  */
6362
6363 static void
6364 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6365                                struct die_info *die,
6366                                dwarf2_psymtab *pst)
6367 {
6368   line_header_up lh;
6369   struct attribute *attr;
6370
6371   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6372   if (attr != nullptr)
6373     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6374   if (lh == NULL)
6375     return;  /* No linetable, so no includes.  */
6376
6377   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6378      that we pass in the raw text_low here; that is ok because we're
6379      only decoding the line table to make include partial symtabs, and
6380      so the addresses aren't really used.  */
6381   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6382                       pst->raw_text_low (), 1);
6383 }
6384
6385 static hashval_t
6386 hash_signatured_type (const void *item)
6387 {
6388   const struct signatured_type *sig_type
6389     = (const struct signatured_type *) item;
6390
6391   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6392   return sig_type->signature;
6393 }
6394
6395 static int
6396 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6397 {
6398   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6399   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6400
6401   return lhs->signature == rhs->signature;
6402 }
6403
6404 /* Allocate a hash table for signatured types.  */
6405
6406 static htab_up
6407 allocate_signatured_type_table (struct objfile *objfile)
6408 {
6409   return htab_up (htab_create_alloc (41,
6410                                      hash_signatured_type,
6411                                      eq_signatured_type,
6412                                      NULL, xcalloc, xfree));
6413 }
6414
6415 /* A helper function to add a signatured type CU to a table.  */
6416
6417 static int
6418 add_signatured_type_cu_to_table (void **slot, void *datum)
6419 {
6420   struct signatured_type *sigt = (struct signatured_type *) *slot;
6421   std::vector<signatured_type *> *all_type_units
6422     = (std::vector<signatured_type *> *) datum;
6423
6424   all_type_units->push_back (sigt);
6425
6426   return 1;
6427 }
6428
6429 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6430    and fill them into TYPES_HTAB.  It will process only type units,
6431    therefore DW_UT_type.  */
6432
6433 static void
6434 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6435                               struct dwo_file *dwo_file,
6436                               dwarf2_section_info *section, htab_up &types_htab,
6437                               rcuh_kind section_kind)
6438 {
6439   struct objfile *objfile = dwarf2_per_objfile->objfile;
6440   struct dwarf2_section_info *abbrev_section;
6441   bfd *abfd;
6442   const gdb_byte *info_ptr, *end_ptr;
6443
6444   abbrev_section = (dwo_file != NULL
6445                     ? &dwo_file->sections.abbrev
6446                     : &dwarf2_per_objfile->abbrev);
6447
6448   if (dwarf_read_debug)
6449     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6450                         section->get_name (),
6451                         abbrev_section->get_file_name ());
6452
6453   section->read (objfile);
6454   info_ptr = section->buffer;
6455
6456   if (info_ptr == NULL)
6457     return;
6458
6459   /* We can't set abfd until now because the section may be empty or
6460      not present, in which case the bfd is unknown.  */
6461   abfd = section->get_bfd_owner ();
6462
6463   /* We don't use cutu_reader here because we don't need to read
6464      any dies: the signature is in the header.  */
6465
6466   end_ptr = info_ptr + section->size;
6467   while (info_ptr < end_ptr)
6468     {
6469       struct signatured_type *sig_type;
6470       struct dwo_unit *dwo_tu;
6471       void **slot;
6472       const gdb_byte *ptr = info_ptr;
6473       struct comp_unit_head header;
6474       unsigned int length;
6475
6476       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6477
6478       /* Initialize it due to a false compiler warning.  */
6479       header.signature = -1;
6480       header.type_cu_offset_in_tu = (cu_offset) -1;
6481
6482       /* We need to read the type's signature in order to build the hash
6483          table, but we don't need anything else just yet.  */
6484
6485       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6486                                            abbrev_section, ptr, section_kind);
6487
6488       length = get_cu_length (&header);
6489
6490       /* Skip dummy type units.  */
6491       if (ptr >= info_ptr + length
6492           || peek_abbrev_code (abfd, ptr) == 0
6493           || header.unit_type != DW_UT_type)
6494         {
6495           info_ptr += length;
6496           continue;
6497         }
6498
6499       if (types_htab == NULL)
6500         {
6501           if (dwo_file)
6502             types_htab = allocate_dwo_unit_table (objfile);
6503           else
6504             types_htab = allocate_signatured_type_table (objfile);
6505         }
6506
6507       if (dwo_file)
6508         {
6509           sig_type = NULL;
6510           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6511                                    struct dwo_unit);
6512           dwo_tu->dwo_file = dwo_file;
6513           dwo_tu->signature = header.signature;
6514           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6515           dwo_tu->section = section;
6516           dwo_tu->sect_off = sect_off;
6517           dwo_tu->length = length;
6518         }
6519       else
6520         {
6521           /* N.B.: type_offset is not usable if this type uses a DWO file.
6522              The real type_offset is in the DWO file.  */
6523           dwo_tu = NULL;
6524           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6525                                      struct signatured_type);
6526           sig_type->signature = header.signature;
6527           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6528           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6529           sig_type->per_cu.is_debug_types = 1;
6530           sig_type->per_cu.section = section;
6531           sig_type->per_cu.sect_off = sect_off;
6532           sig_type->per_cu.length = length;
6533         }
6534
6535       slot = htab_find_slot (types_htab.get (),
6536                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6537                              INSERT);
6538       gdb_assert (slot != NULL);
6539       if (*slot != NULL)
6540         {
6541           sect_offset dup_sect_off;
6542
6543           if (dwo_file)
6544             {
6545               const struct dwo_unit *dup_tu
6546                 = (const struct dwo_unit *) *slot;
6547
6548               dup_sect_off = dup_tu->sect_off;
6549             }
6550           else
6551             {
6552               const struct signatured_type *dup_tu
6553                 = (const struct signatured_type *) *slot;
6554
6555               dup_sect_off = dup_tu->per_cu.sect_off;
6556             }
6557
6558           complaint (_("debug type entry at offset %s is duplicate to"
6559                        " the entry at offset %s, signature %s"),
6560                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6561                      hex_string (header.signature));
6562         }
6563       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6564
6565       if (dwarf_read_debug > 1)
6566         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6567                             sect_offset_str (sect_off),
6568                             hex_string (header.signature));
6569
6570       info_ptr += length;
6571     }
6572 }
6573
6574 /* Create the hash table of all entries in the .debug_types
6575    (or .debug_types.dwo) section(s).
6576    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6577    otherwise it is NULL.
6578
6579    The result is a pointer to the hash table or NULL if there are no types.
6580
6581    Note: This function processes DWO files only, not DWP files.  */
6582
6583 static void
6584 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6585                                struct dwo_file *dwo_file,
6586                                gdb::array_view<dwarf2_section_info> type_sections,
6587                                htab_up &types_htab)
6588 {
6589   for (dwarf2_section_info &section : type_sections)
6590     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, &section,
6591                                   types_htab, rcuh_kind::TYPE);
6592 }
6593
6594 /* Create the hash table of all entries in the .debug_types section,
6595    and initialize all_type_units.
6596    The result is zero if there is an error (e.g. missing .debug_types section),
6597    otherwise non-zero.  */
6598
6599 static int
6600 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6601 {
6602   htab_up types_htab;
6603
6604   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6605                                 &dwarf2_per_objfile->info, types_htab,
6606                                 rcuh_kind::COMPILE);
6607   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6608                                  dwarf2_per_objfile->types, types_htab);
6609   if (types_htab == NULL)
6610     {
6611       dwarf2_per_objfile->signatured_types = NULL;
6612       return 0;
6613     }
6614
6615   dwarf2_per_objfile->signatured_types = std::move (types_htab);
6616
6617   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6618   dwarf2_per_objfile->all_type_units.reserve
6619     (htab_elements (dwarf2_per_objfile->signatured_types.get ()));
6620
6621   htab_traverse_noresize (dwarf2_per_objfile->signatured_types.get (),
6622                           add_signatured_type_cu_to_table,
6623                           &dwarf2_per_objfile->all_type_units);
6624
6625   return 1;
6626 }
6627
6628 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6629    If SLOT is non-NULL, it is the entry to use in the hash table.
6630    Otherwise we find one.  */
6631
6632 static struct signatured_type *
6633 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6634                void **slot)
6635 {
6636   struct objfile *objfile = dwarf2_per_objfile->objfile;
6637
6638   if (dwarf2_per_objfile->all_type_units.size ()
6639       == dwarf2_per_objfile->all_type_units.capacity ())
6640     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6641
6642   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6643                                               struct signatured_type);
6644
6645   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6646   sig_type->signature = sig;
6647   sig_type->per_cu.is_debug_types = 1;
6648   if (dwarf2_per_objfile->using_index)
6649     {
6650       sig_type->per_cu.v.quick =
6651         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6652                         struct dwarf2_per_cu_quick_data);
6653     }
6654
6655   if (slot == NULL)
6656     {
6657       slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6658                              sig_type, INSERT);
6659     }
6660   gdb_assert (*slot == NULL);
6661   *slot = sig_type;
6662   /* The rest of sig_type must be filled in by the caller.  */
6663   return sig_type;
6664 }
6665
6666 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6667    Fill in SIG_ENTRY with DWO_ENTRY.  */
6668
6669 static void
6670 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6671                                   struct signatured_type *sig_entry,
6672                                   struct dwo_unit *dwo_entry)
6673 {
6674   /* Make sure we're not clobbering something we don't expect to.  */
6675   gdb_assert (! sig_entry->per_cu.queued);
6676   gdb_assert (sig_entry->per_cu.cu == NULL);
6677   if (dwarf2_per_objfile->using_index)
6678     {
6679       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6680       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6681     }
6682   else
6683       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6684   gdb_assert (sig_entry->signature == dwo_entry->signature);
6685   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6686   gdb_assert (sig_entry->type_unit_group == NULL);
6687   gdb_assert (sig_entry->dwo_unit == NULL);
6688
6689   sig_entry->per_cu.section = dwo_entry->section;
6690   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6691   sig_entry->per_cu.length = dwo_entry->length;
6692   sig_entry->per_cu.reading_dwo_directly = 1;
6693   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6694   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6695   sig_entry->dwo_unit = dwo_entry;
6696 }
6697
6698 /* Subroutine of lookup_signatured_type.
6699    If we haven't read the TU yet, create the signatured_type data structure
6700    for a TU to be read in directly from a DWO file, bypassing the stub.
6701    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6702    using .gdb_index, then when reading a CU we want to stay in the DWO file
6703    containing that CU.  Otherwise we could end up reading several other DWO
6704    files (due to comdat folding) to process the transitive closure of all the
6705    mentioned TUs, and that can be slow.  The current DWO file will have every
6706    type signature that it needs.
6707    We only do this for .gdb_index because in the psymtab case we already have
6708    to read all the DWOs to build the type unit groups.  */
6709
6710 static struct signatured_type *
6711 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6712 {
6713   struct dwarf2_per_objfile *dwarf2_per_objfile
6714     = cu->per_cu->dwarf2_per_objfile;
6715   struct objfile *objfile = dwarf2_per_objfile->objfile;
6716   struct dwo_file *dwo_file;
6717   struct dwo_unit find_dwo_entry, *dwo_entry;
6718   struct signatured_type find_sig_entry, *sig_entry;
6719   void **slot;
6720
6721   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6722
6723   /* If TU skeletons have been removed then we may not have read in any
6724      TUs yet.  */
6725   if (dwarf2_per_objfile->signatured_types == NULL)
6726     {
6727       dwarf2_per_objfile->signatured_types
6728         = allocate_signatured_type_table (objfile);
6729     }
6730
6731   /* We only ever need to read in one copy of a signatured type.
6732      Use the global signatured_types array to do our own comdat-folding
6733      of types.  If this is the first time we're reading this TU, and
6734      the TU has an entry in .gdb_index, replace the recorded data from
6735      .gdb_index with this TU.  */
6736
6737   find_sig_entry.signature = sig;
6738   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6739                          &find_sig_entry, INSERT);
6740   sig_entry = (struct signatured_type *) *slot;
6741
6742   /* We can get here with the TU already read, *or* in the process of being
6743      read.  Don't reassign the global entry to point to this DWO if that's
6744      the case.  Also note that if the TU is already being read, it may not
6745      have come from a DWO, the program may be a mix of Fission-compiled
6746      code and non-Fission-compiled code.  */
6747
6748   /* Have we already tried to read this TU?
6749      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6750      needn't exist in the global table yet).  */
6751   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6752     return sig_entry;
6753
6754   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6755      dwo_unit of the TU itself.  */
6756   dwo_file = cu->dwo_unit->dwo_file;
6757
6758   /* Ok, this is the first time we're reading this TU.  */
6759   if (dwo_file->tus == NULL)
6760     return NULL;
6761   find_dwo_entry.signature = sig;
6762   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
6763                                              &find_dwo_entry);
6764   if (dwo_entry == NULL)
6765     return NULL;
6766
6767   /* If the global table doesn't have an entry for this TU, add one.  */
6768   if (sig_entry == NULL)
6769     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6770
6771   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6772   sig_entry->per_cu.tu_read = 1;
6773   return sig_entry;
6774 }
6775
6776 /* Subroutine of lookup_signatured_type.
6777    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6778    then try the DWP file.  If the TU stub (skeleton) has been removed then
6779    it won't be in .gdb_index.  */
6780
6781 static struct signatured_type *
6782 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6783 {
6784   struct dwarf2_per_objfile *dwarf2_per_objfile
6785     = cu->per_cu->dwarf2_per_objfile;
6786   struct objfile *objfile = dwarf2_per_objfile->objfile;
6787   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6788   struct dwo_unit *dwo_entry;
6789   struct signatured_type find_sig_entry, *sig_entry;
6790   void **slot;
6791
6792   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6793   gdb_assert (dwp_file != NULL);
6794
6795   /* If TU skeletons have been removed then we may not have read in any
6796      TUs yet.  */
6797   if (dwarf2_per_objfile->signatured_types == NULL)
6798     {
6799       dwarf2_per_objfile->signatured_types
6800         = allocate_signatured_type_table (objfile);
6801     }
6802
6803   find_sig_entry.signature = sig;
6804   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6805                          &find_sig_entry, INSERT);
6806   sig_entry = (struct signatured_type *) *slot;
6807
6808   /* Have we already tried to read this TU?
6809      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6810      needn't exist in the global table yet).  */
6811   if (sig_entry != NULL)
6812     return sig_entry;
6813
6814   if (dwp_file->tus == NULL)
6815     return NULL;
6816   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
6817                                       sig, 1 /* is_debug_types */);
6818   if (dwo_entry == NULL)
6819     return NULL;
6820
6821   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6822   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6823
6824   return sig_entry;
6825 }
6826
6827 /* Lookup a signature based type for DW_FORM_ref_sig8.
6828    Returns NULL if signature SIG is not present in the table.
6829    It is up to the caller to complain about this.  */
6830
6831 static struct signatured_type *
6832 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6833 {
6834   struct dwarf2_per_objfile *dwarf2_per_objfile
6835     = cu->per_cu->dwarf2_per_objfile;
6836
6837   if (cu->dwo_unit
6838       && dwarf2_per_objfile->using_index)
6839     {
6840       /* We're in a DWO/DWP file, and we're using .gdb_index.
6841          These cases require special processing.  */
6842       if (get_dwp_file (dwarf2_per_objfile) == NULL)
6843         return lookup_dwo_signatured_type (cu, sig);
6844       else
6845         return lookup_dwp_signatured_type (cu, sig);
6846     }
6847   else
6848     {
6849       struct signatured_type find_entry, *entry;
6850
6851       if (dwarf2_per_objfile->signatured_types == NULL)
6852         return NULL;
6853       find_entry.signature = sig;
6854       entry = ((struct signatured_type *)
6855                htab_find (dwarf2_per_objfile->signatured_types.get (),
6856                           &find_entry));
6857       return entry;
6858     }
6859 }
6860
6861 /* Return the address base of the compile unit, which, if exists, is stored
6862    either at the attribute DW_AT_GNU_addr_base, or DW_AT_addr_base.  */
6863 static gdb::optional<ULONGEST>
6864 lookup_addr_base (struct die_info *comp_unit_die)
6865 {
6866   struct attribute *attr;
6867   attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_addr_base);
6868   if (attr == nullptr)
6869     attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_GNU_addr_base);
6870   if (attr == nullptr)
6871     return gdb::optional<ULONGEST> ();
6872   return DW_UNSND (attr);
6873 }
6874
6875 /* Return range lists base of the compile unit, which, if exists, is stored
6876    either at the attribute DW_AT_rnglists_base or DW_AT_GNU_ranges_base.  */
6877 static ULONGEST
6878 lookup_ranges_base (struct die_info *comp_unit_die)
6879 {
6880   struct attribute *attr;
6881   attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_rnglists_base);
6882   if (attr == nullptr)
6883     attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_GNU_ranges_base);
6884   if (attr == nullptr)
6885     return 0;
6886   return DW_UNSND (attr);
6887 }
6888
6889 /* Low level DIE reading support.  */
6890
6891 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6892
6893 static void
6894 init_cu_die_reader (struct die_reader_specs *reader,
6895                     struct dwarf2_cu *cu,
6896                     struct dwarf2_section_info *section,
6897                     struct dwo_file *dwo_file,
6898                     struct abbrev_table *abbrev_table)
6899 {
6900   gdb_assert (section->readin && section->buffer != NULL);
6901   reader->abfd = section->get_bfd_owner ();
6902   reader->cu = cu;
6903   reader->dwo_file = dwo_file;
6904   reader->die_section = section;
6905   reader->buffer = section->buffer;
6906   reader->buffer_end = section->buffer + section->size;
6907   reader->abbrev_table = abbrev_table;
6908 }
6909
6910 /* Subroutine of cutu_reader to simplify it.
6911    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6912    There's just a lot of work to do, and cutu_reader is big enough
6913    already.
6914
6915    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6916    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6917    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6918    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6919    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6920    STUB_COMP_DIR may be non-NULL.
6921    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE
6922    are filled in with the info of the DIE from the DWO file.
6923    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
6924    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
6925    kept around for at least as long as *RESULT_READER.
6926
6927    The result is non-zero if a valid (non-dummy) DIE was found.  */
6928
6929 static int
6930 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
6931                         struct dwo_unit *dwo_unit,
6932                         struct die_info *stub_comp_unit_die,
6933                         const char *stub_comp_dir,
6934                         struct die_reader_specs *result_reader,
6935                         const gdb_byte **result_info_ptr,
6936                         struct die_info **result_comp_unit_die,
6937                         abbrev_table_up *result_dwo_abbrev_table)
6938 {
6939   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6940   struct objfile *objfile = dwarf2_per_objfile->objfile;
6941   struct dwarf2_cu *cu = this_cu->cu;
6942   bfd *abfd;
6943   const gdb_byte *begin_info_ptr, *info_ptr;
6944   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6945   int i,num_extra_attrs;
6946   struct dwarf2_section_info *dwo_abbrev_section;
6947   struct die_info *comp_unit_die;
6948
6949   /* At most one of these may be provided.  */
6950   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6951
6952   /* These attributes aren't processed until later:
6953      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6954      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6955      referenced later.  However, these attributes are found in the stub
6956      which we won't have later.  In order to not impose this complication
6957      on the rest of the code, we read them here and copy them to the
6958      DWO CU/TU die.  */
6959
6960   stmt_list = NULL;
6961   low_pc = NULL;
6962   high_pc = NULL;
6963   ranges = NULL;
6964   comp_dir = NULL;
6965
6966   if (stub_comp_unit_die != NULL)
6967     {
6968       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6969          DWO file.  */
6970       if (! this_cu->is_debug_types)
6971         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6972       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6973       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6974       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6975       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6976
6977       cu->addr_base = lookup_addr_base (stub_comp_unit_die);
6978
6979       /* There should be a DW_AT_rnglists_base (DW_AT_GNU_ranges_base) attribute
6980          here (if needed). We need the value before we can process
6981          DW_AT_ranges.  */
6982       cu->ranges_base = lookup_ranges_base (stub_comp_unit_die);
6983     }
6984   else if (stub_comp_dir != NULL)
6985     {
6986       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6987       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
6988       comp_dir->name = DW_AT_comp_dir;
6989       comp_dir->form = DW_FORM_string;
6990       DW_STRING_IS_CANONICAL (comp_dir) = 0;
6991       DW_STRING (comp_dir) = stub_comp_dir;
6992     }
6993
6994   /* Set up for reading the DWO CU/TU.  */
6995   cu->dwo_unit = dwo_unit;
6996   dwarf2_section_info *section = dwo_unit->section;
6997   section->read (objfile);
6998   abfd = section->get_bfd_owner ();
6999   begin_info_ptr = info_ptr = (section->buffer
7000                                + to_underlying (dwo_unit->sect_off));
7001   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7002
7003   if (this_cu->is_debug_types)
7004     {
7005       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7006
7007       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7008                                                 &cu->header, section,
7009                                                 dwo_abbrev_section,
7010                                                 info_ptr, rcuh_kind::TYPE);
7011       /* This is not an assert because it can be caused by bad debug info.  */
7012       if (sig_type->signature != cu->header.signature)
7013         {
7014           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7015                    " TU at offset %s [in module %s]"),
7016                  hex_string (sig_type->signature),
7017                  hex_string (cu->header.signature),
7018                  sect_offset_str (dwo_unit->sect_off),
7019                  bfd_get_filename (abfd));
7020         }
7021       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7022       /* For DWOs coming from DWP files, we don't know the CU length
7023          nor the type's offset in the TU until now.  */
7024       dwo_unit->length = get_cu_length (&cu->header);
7025       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7026
7027       /* Establish the type offset that can be used to lookup the type.
7028          For DWO files, we don't know it until now.  */
7029       sig_type->type_offset_in_section
7030         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7031     }
7032   else
7033     {
7034       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7035                                                 &cu->header, section,
7036                                                 dwo_abbrev_section,
7037                                                 info_ptr, rcuh_kind::COMPILE);
7038       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7039       /* For DWOs coming from DWP files, we don't know the CU length
7040          until now.  */
7041       dwo_unit->length = get_cu_length (&cu->header);
7042     }
7043
7044   *result_dwo_abbrev_table
7045     = abbrev_table::read (objfile, dwo_abbrev_section,
7046                           cu->header.abbrev_sect_off);
7047   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7048                       result_dwo_abbrev_table->get ());
7049
7050   /* Read in the die, but leave space to copy over the attributes
7051      from the stub.  This has the benefit of simplifying the rest of
7052      the code - all the work to maintain the illusion of a single
7053      DW_TAG_{compile,type}_unit DIE is done here.  */
7054   num_extra_attrs = ((stmt_list != NULL)
7055                      + (low_pc != NULL)
7056                      + (high_pc != NULL)
7057                      + (ranges != NULL)
7058                      + (comp_dir != NULL));
7059   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7060                               num_extra_attrs);
7061
7062   /* Copy over the attributes from the stub to the DIE we just read in.  */
7063   comp_unit_die = *result_comp_unit_die;
7064   i = comp_unit_die->num_attrs;
7065   if (stmt_list != NULL)
7066     comp_unit_die->attrs[i++] = *stmt_list;
7067   if (low_pc != NULL)
7068     comp_unit_die->attrs[i++] = *low_pc;
7069   if (high_pc != NULL)
7070     comp_unit_die->attrs[i++] = *high_pc;
7071   if (ranges != NULL)
7072     comp_unit_die->attrs[i++] = *ranges;
7073   if (comp_dir != NULL)
7074     comp_unit_die->attrs[i++] = *comp_dir;
7075   comp_unit_die->num_attrs += num_extra_attrs;
7076
7077   if (dwarf_die_debug)
7078     {
7079       fprintf_unfiltered (gdb_stdlog,
7080                           "Read die from %s@0x%x of %s:\n",
7081                           section->get_name (),
7082                           (unsigned) (begin_info_ptr - section->buffer),
7083                           bfd_get_filename (abfd));
7084       dump_die (comp_unit_die, dwarf_die_debug);
7085     }
7086
7087   /* Skip dummy compilation units.  */
7088   if (info_ptr >= begin_info_ptr + dwo_unit->length
7089       || peek_abbrev_code (abfd, info_ptr) == 0)
7090     return 0;
7091
7092   *result_info_ptr = info_ptr;
7093   return 1;
7094 }
7095
7096 /* Return the signature of the compile unit, if found. In DWARF 4 and before,
7097    the signature is in the DW_AT_GNU_dwo_id attribute. In DWARF 5 and later, the
7098    signature is part of the header.  */
7099 static gdb::optional<ULONGEST>
7100 lookup_dwo_id (struct dwarf2_cu *cu, struct die_info* comp_unit_die)
7101 {
7102   if (cu->header.version >= 5)
7103     return cu->header.signature;
7104   struct attribute *attr;
7105   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7106   if (attr == nullptr)
7107     return gdb::optional<ULONGEST> ();
7108   return DW_UNSND (attr);
7109 }
7110
7111 /* Subroutine of cutu_reader to simplify it.
7112    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7113    Returns NULL if the specified DWO unit cannot be found.  */
7114
7115 static struct dwo_unit *
7116 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7117                  struct die_info *comp_unit_die,
7118                  const char *dwo_name)
7119 {
7120   struct dwarf2_cu *cu = this_cu->cu;
7121   struct dwo_unit *dwo_unit;
7122   const char *comp_dir;
7123
7124   gdb_assert (cu != NULL);
7125
7126   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7127   dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
7128   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7129
7130   if (this_cu->is_debug_types)
7131     {
7132       struct signatured_type *sig_type;
7133
7134       /* Since this_cu is the first member of struct signatured_type,
7135          we can go from a pointer to one to a pointer to the other.  */
7136       sig_type = (struct signatured_type *) this_cu;
7137       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7138     }
7139   else
7140     {
7141       gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
7142       if (!signature.has_value ())
7143         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7144                  " [in module %s]"),
7145                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7146       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7147                                        *signature);
7148     }
7149
7150   return dwo_unit;
7151 }
7152
7153 /* Subroutine of cutu_reader to simplify it.
7154    See it for a description of the parameters.
7155    Read a TU directly from a DWO file, bypassing the stub.  */
7156
7157 void
7158 cutu_reader::init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7159                                         int use_existing_cu, int keep)
7160 {
7161   struct signatured_type *sig_type;
7162   struct die_reader_specs reader;
7163
7164   /* Verify we can do the following downcast, and that we have the
7165      data we need.  */
7166   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7167   sig_type = (struct signatured_type *) this_cu;
7168   gdb_assert (sig_type->dwo_unit != NULL);
7169
7170   if (use_existing_cu && this_cu->cu != NULL)
7171     {
7172       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7173       /* There's no need to do the rereading_dwo_cu handling that
7174          cutu_reader does since we don't read the stub.  */
7175     }
7176   else
7177     {
7178       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7179       gdb_assert (this_cu->cu == NULL);
7180       m_new_cu.reset (new dwarf2_cu (this_cu));
7181     }
7182
7183   /* A future optimization, if needed, would be to use an existing
7184      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7185      could share abbrev tables.  */
7186
7187   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7188                               NULL /* stub_comp_unit_die */,
7189                               sig_type->dwo_unit->dwo_file->comp_dir,
7190                               &reader, &info_ptr,
7191                               &comp_unit_die,
7192                               &m_dwo_abbrev_table) == 0)
7193     {
7194       /* Dummy die.  */
7195       dummy_p = true;
7196     }
7197 }
7198
7199 /* Initialize a CU (or TU) and read its DIEs.
7200    If the CU defers to a DWO file, read the DWO file as well.
7201
7202    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7203    Otherwise the table specified in the comp unit header is read in and used.
7204    This is an optimization for when we already have the abbrev table.
7205
7206    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7207    Otherwise, a new CU is allocated with xmalloc.
7208
7209    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7210    read_in_chain.  Otherwise the dwarf2_cu data is freed at the
7211    end.  */
7212
7213 cutu_reader::cutu_reader (struct dwarf2_per_cu_data *this_cu,
7214                           struct abbrev_table *abbrev_table,
7215                           int use_existing_cu, int keep,
7216                           bool skip_partial)
7217   : die_reader_specs {},
7218     m_this_cu (this_cu),
7219     m_keep (keep)
7220 {
7221   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7222   struct objfile *objfile = dwarf2_per_objfile->objfile;
7223   struct dwarf2_section_info *section = this_cu->section;
7224   bfd *abfd = section->get_bfd_owner ();
7225   struct dwarf2_cu *cu;
7226   const gdb_byte *begin_info_ptr;
7227   struct signatured_type *sig_type = NULL;
7228   struct dwarf2_section_info *abbrev_section;
7229   /* Non-zero if CU currently points to a DWO file and we need to
7230      reread it.  When this happens we need to reread the skeleton die
7231      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7232   int rereading_dwo_cu = 0;
7233
7234   if (dwarf_die_debug)
7235     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7236                         this_cu->is_debug_types ? "type" : "comp",
7237                         sect_offset_str (this_cu->sect_off));
7238
7239   if (use_existing_cu)
7240     gdb_assert (keep);
7241
7242   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7243      file (instead of going through the stub), short-circuit all of this.  */
7244   if (this_cu->reading_dwo_directly)
7245     {
7246       /* Narrow down the scope of possibilities to have to understand.  */
7247       gdb_assert (this_cu->is_debug_types);
7248       gdb_assert (abbrev_table == NULL);
7249       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep);
7250       return;
7251     }
7252
7253   /* This is cheap if the section is already read in.  */
7254   section->read (objfile);
7255
7256   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7257
7258   abbrev_section = get_abbrev_section_for_cu (this_cu);
7259
7260   if (use_existing_cu && this_cu->cu != NULL)
7261     {
7262       cu = this_cu->cu;
7263       /* If this CU is from a DWO file we need to start over, we need to
7264          refetch the attributes from the skeleton CU.
7265          This could be optimized by retrieving those attributes from when we
7266          were here the first time: the previous comp_unit_die was stored in
7267          comp_unit_obstack.  But there's no data yet that we need this
7268          optimization.  */
7269       if (cu->dwo_unit != NULL)
7270         rereading_dwo_cu = 1;
7271     }
7272   else
7273     {
7274       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7275       gdb_assert (this_cu->cu == NULL);
7276       m_new_cu.reset (new dwarf2_cu (this_cu));
7277       cu = m_new_cu.get ();
7278     }
7279
7280   /* Get the header.  */
7281   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7282     {
7283       /* We already have the header, there's no need to read it in again.  */
7284       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7285     }
7286   else
7287     {
7288       if (this_cu->is_debug_types)
7289         {
7290           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7291                                                     &cu->header, section,
7292                                                     abbrev_section, info_ptr,
7293                                                     rcuh_kind::TYPE);
7294
7295           /* Since per_cu is the first member of struct signatured_type,
7296              we can go from a pointer to one to a pointer to the other.  */
7297           sig_type = (struct signatured_type *) this_cu;
7298           gdb_assert (sig_type->signature == cu->header.signature);
7299           gdb_assert (sig_type->type_offset_in_tu
7300                       == cu->header.type_cu_offset_in_tu);
7301           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7302
7303           /* LENGTH has not been set yet for type units if we're
7304              using .gdb_index.  */
7305           this_cu->length = get_cu_length (&cu->header);
7306
7307           /* Establish the type offset that can be used to lookup the type.  */
7308           sig_type->type_offset_in_section =
7309             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7310
7311           this_cu->dwarf_version = cu->header.version;
7312         }
7313       else
7314         {
7315           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7316                                                     &cu->header, section,
7317                                                     abbrev_section,
7318                                                     info_ptr,
7319                                                     rcuh_kind::COMPILE);
7320
7321           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7322           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7323           this_cu->dwarf_version = cu->header.version;
7324         }
7325     }
7326
7327   /* Skip dummy compilation units.  */
7328   if (info_ptr >= begin_info_ptr + this_cu->length
7329       || peek_abbrev_code (abfd, info_ptr) == 0)
7330     {
7331       dummy_p = true;
7332       return;
7333     }
7334
7335   /* If we don't have them yet, read the abbrevs for this compilation unit.
7336      And if we need to read them now, make sure they're freed when we're
7337      done.  */
7338   if (abbrev_table != NULL)
7339     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7340   else
7341     {
7342       m_abbrev_table_holder
7343         = abbrev_table::read (objfile, abbrev_section,
7344                               cu->header.abbrev_sect_off);
7345       abbrev_table = m_abbrev_table_holder.get ();
7346     }
7347
7348   /* Read the top level CU/TU die.  */
7349   init_cu_die_reader (this, cu, section, NULL, abbrev_table);
7350   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
7351
7352   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7353     {
7354       dummy_p = true;
7355       return;
7356     }
7357
7358   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7359      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7360      table from the DWO file and pass the ownership over to us.  It will be
7361      referenced from READER, so we must make sure to free it after we're done
7362      with READER.
7363
7364      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7365      DWO CU, that this test will fail (the attribute will not be present).  */
7366   const char *dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
7367   if (dwo_name != nullptr)
7368     {
7369       struct dwo_unit *dwo_unit;
7370       struct die_info *dwo_comp_unit_die;
7371
7372       if (comp_unit_die->has_children)
7373         {
7374           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7375                        " has children (offset %s) [in module %s]"),
7376                      sect_offset_str (this_cu->sect_off),
7377                      bfd_get_filename (abfd));
7378         }
7379       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die, dwo_name);
7380       if (dwo_unit != NULL)
7381         {
7382           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7383                                       comp_unit_die, NULL,
7384                                       this, &info_ptr,
7385                                       &dwo_comp_unit_die,
7386                                       &m_dwo_abbrev_table) == 0)
7387             {
7388               /* Dummy die.  */
7389               dummy_p = true;
7390               return;
7391             }
7392           comp_unit_die = dwo_comp_unit_die;
7393         }
7394       else
7395         {
7396           /* Yikes, we couldn't find the rest of the DIE, we only have
7397              the stub.  A complaint has already been logged.  There's
7398              not much more we can do except pass on the stub DIE to
7399              die_reader_func.  We don't want to throw an error on bad
7400              debug info.  */
7401         }
7402     }
7403 }
7404
7405 cutu_reader::~cutu_reader ()
7406 {
7407   /* Done, clean up.  */
7408   if (m_new_cu != NULL && m_keep && !dummy_p)
7409     {
7410       struct dwarf2_per_objfile *dwarf2_per_objfile
7411         = m_this_cu->dwarf2_per_objfile;
7412       /* Link this CU into read_in_chain.  */
7413       m_this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7414       dwarf2_per_objfile->read_in_chain = m_this_cu;
7415       /* The chain owns it now.  */
7416       m_new_cu.release ();
7417     }
7418 }
7419
7420 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name (DW_AT_dwo_name)
7421    if present. DWO_FILE, if non-NULL, is the DWO file to read (the caller is
7422    assumed to have already done the lookup to find the DWO file).
7423
7424    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7425    THIS_CU->is_debug_types, but nothing else.
7426
7427    We fill in THIS_CU->length.
7428
7429    THIS_CU->cu is always freed when done.
7430    This is done in order to not leave THIS_CU->cu in a state where we have
7431    to care whether it refers to the "main" CU or the DWO CU.
7432
7433    When parent_cu is passed, it is used to provide a default value for
7434    str_offsets_base and addr_base from the parent.  */
7435
7436 cutu_reader::cutu_reader (struct dwarf2_per_cu_data *this_cu,
7437                           struct dwarf2_cu *parent_cu,
7438                           struct dwo_file *dwo_file)
7439   : die_reader_specs {},
7440     m_this_cu (this_cu)
7441 {
7442   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7443   struct objfile *objfile = dwarf2_per_objfile->objfile;
7444   struct dwarf2_section_info *section = this_cu->section;
7445   bfd *abfd = section->get_bfd_owner ();
7446   struct dwarf2_section_info *abbrev_section;
7447   const gdb_byte *begin_info_ptr, *info_ptr;
7448
7449   if (dwarf_die_debug)
7450     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7451                         this_cu->is_debug_types ? "type" : "comp",
7452                         sect_offset_str (this_cu->sect_off));
7453
7454   gdb_assert (this_cu->cu == NULL);
7455
7456   abbrev_section = (dwo_file != NULL
7457                     ? &dwo_file->sections.abbrev
7458                     : get_abbrev_section_for_cu (this_cu));
7459
7460   /* This is cheap if the section is already read in.  */
7461   section->read (objfile);
7462
7463   m_new_cu.reset (new dwarf2_cu (this_cu));
7464
7465   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7466   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7467                                             &m_new_cu->header, section,
7468                                             abbrev_section, info_ptr,
7469                                             (this_cu->is_debug_types
7470                                              ? rcuh_kind::TYPE
7471                                              : rcuh_kind::COMPILE));
7472
7473   if (parent_cu != nullptr)
7474     {
7475       m_new_cu->str_offsets_base = parent_cu->str_offsets_base;
7476       m_new_cu->addr_base = parent_cu->addr_base;
7477     }
7478   this_cu->length = get_cu_length (&m_new_cu->header);
7479
7480   /* Skip dummy compilation units.  */
7481   if (info_ptr >= begin_info_ptr + this_cu->length
7482       || peek_abbrev_code (abfd, info_ptr) == 0)
7483     {
7484       dummy_p = true;
7485       return;
7486     }
7487
7488   m_abbrev_table_holder
7489     = abbrev_table::read (objfile, abbrev_section,
7490                           m_new_cu->header.abbrev_sect_off);
7491
7492   init_cu_die_reader (this, m_new_cu.get (), section, dwo_file,
7493                       m_abbrev_table_holder.get ());
7494   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
7495 }
7496
7497 \f
7498 /* Type Unit Groups.
7499
7500    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7501    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7502    so that all types coming from the same compilation (.o file) are grouped
7503    together.  A future step could be to put the types in the same symtab as
7504    the CU the types ultimately came from.  */
7505
7506 static hashval_t
7507 hash_type_unit_group (const void *item)
7508 {
7509   const struct type_unit_group *tu_group
7510     = (const struct type_unit_group *) item;
7511
7512   return hash_stmt_list_entry (&tu_group->hash);
7513 }
7514
7515 static int
7516 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7517 {
7518   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7519   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7520
7521   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7522 }
7523
7524 /* Allocate a hash table for type unit groups.  */
7525
7526 static htab_up
7527 allocate_type_unit_groups_table (struct objfile *objfile)
7528 {
7529   return htab_up (htab_create_alloc (3,
7530                                      hash_type_unit_group,
7531                                      eq_type_unit_group,
7532                                      NULL, xcalloc, xfree));
7533 }
7534
7535 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7536    partial symtabs.  We combine several TUs per psymtab to not let the size
7537    of any one psymtab grow too big.  */
7538 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7539 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7540
7541 /* Helper routine for get_type_unit_group.
7542    Create the type_unit_group object used to hold one or more TUs.  */
7543
7544 static struct type_unit_group *
7545 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7546 {
7547   struct dwarf2_per_objfile *dwarf2_per_objfile
7548     = cu->per_cu->dwarf2_per_objfile;
7549   struct objfile *objfile = dwarf2_per_objfile->objfile;
7550   struct dwarf2_per_cu_data *per_cu;
7551   struct type_unit_group *tu_group;
7552
7553   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7554                              struct type_unit_group);
7555   per_cu = &tu_group->per_cu;
7556   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7557
7558   if (dwarf2_per_objfile->using_index)
7559     {
7560       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7561                                         struct dwarf2_per_cu_quick_data);
7562     }
7563   else
7564     {
7565       unsigned int line_offset = to_underlying (line_offset_struct);
7566       dwarf2_psymtab *pst;
7567       std::string name;
7568
7569       /* Give the symtab a useful name for debug purposes.  */
7570       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7571         name = string_printf ("<type_units_%d>",
7572                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7573       else
7574         name = string_printf ("<type_units_at_0x%x>", line_offset);
7575
7576       pst = create_partial_symtab (per_cu, name.c_str ());
7577       pst->anonymous = true;
7578     }
7579
7580   tu_group->hash.dwo_unit = cu->dwo_unit;
7581   tu_group->hash.line_sect_off = line_offset_struct;
7582
7583   return tu_group;
7584 }
7585
7586 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7587    STMT_LIST is a DW_AT_stmt_list attribute.  */
7588
7589 static struct type_unit_group *
7590 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7591 {
7592   struct dwarf2_per_objfile *dwarf2_per_objfile
7593     = cu->per_cu->dwarf2_per_objfile;
7594   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7595   struct type_unit_group *tu_group;
7596   void **slot;
7597   unsigned int line_offset;
7598   struct type_unit_group type_unit_group_for_lookup;
7599
7600   if (dwarf2_per_objfile->type_unit_groups == NULL)
7601     {
7602       dwarf2_per_objfile->type_unit_groups =
7603         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7604     }
7605
7606   /* Do we need to create a new group, or can we use an existing one?  */
7607
7608   if (stmt_list)
7609     {
7610       line_offset = DW_UNSND (stmt_list);
7611       ++tu_stats->nr_symtab_sharers;
7612     }
7613   else
7614     {
7615       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7616          We can do various things here like create one group per TU or
7617          spread them over multiple groups to split up the expansion work.
7618          To avoid worst case scenarios (too many groups or too large groups)
7619          we, umm, group them in bunches.  */
7620       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7621                      | (tu_stats->nr_stmt_less_type_units
7622                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7623       ++tu_stats->nr_stmt_less_type_units;
7624     }
7625
7626   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7627   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7628   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups.get (),
7629                          &type_unit_group_for_lookup, INSERT);
7630   if (*slot != NULL)
7631     {
7632       tu_group = (struct type_unit_group *) *slot;
7633       gdb_assert (tu_group != NULL);
7634     }
7635   else
7636     {
7637       sect_offset line_offset_struct = (sect_offset) line_offset;
7638       tu_group = create_type_unit_group (cu, line_offset_struct);
7639       *slot = tu_group;
7640       ++tu_stats->nr_symtabs;
7641     }
7642
7643   return tu_group;
7644 }
7645 \f
7646 /* Partial symbol tables.  */
7647
7648 /* Create a psymtab named NAME and assign it to PER_CU.
7649
7650    The caller must fill in the following details:
7651    dirname, textlow, texthigh.  */
7652
7653 static dwarf2_psymtab *
7654 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7655 {
7656   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7657   dwarf2_psymtab *pst;
7658
7659   pst = new dwarf2_psymtab (name, objfile, 0);
7660
7661   pst->psymtabs_addrmap_supported = true;
7662
7663   /* This is the glue that links PST into GDB's symbol API.  */
7664   pst->per_cu_data = per_cu;
7665   per_cu->v.psymtab = pst;
7666
7667   return pst;
7668 }
7669
7670 /* DIE reader function for process_psymtab_comp_unit.  */
7671
7672 static void
7673 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7674                                   const gdb_byte *info_ptr,
7675                                   struct die_info *comp_unit_die,
7676                                   int want_partial_unit,
7677                                   enum language pretend_language)
7678 {
7679   struct dwarf2_cu *cu = reader->cu;
7680   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7681   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7682   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7683   CORE_ADDR baseaddr;
7684   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7685   dwarf2_psymtab *pst;
7686   enum pc_bounds_kind cu_bounds_kind;
7687   const char *filename;
7688
7689   if (comp_unit_die->tag == DW_TAG_partial_unit && !want_partial_unit)
7690     return;
7691
7692   gdb_assert (! per_cu->is_debug_types);
7693
7694   prepare_one_comp_unit (cu, comp_unit_die, pretend_language);
7695
7696   /* Allocate a new partial symbol table structure.  */
7697   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7698   if (filename == NULL)
7699     filename = "";
7700
7701   pst = create_partial_symtab (per_cu, filename);
7702
7703   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7704   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7705
7706   baseaddr = objfile->text_section_offset ();
7707
7708   dwarf2_find_base_address (comp_unit_die, cu);
7709
7710   /* Possibly set the default values of LOWPC and HIGHPC from
7711      `DW_AT_ranges'.  */
7712   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7713                                          &best_highpc, cu, pst);
7714   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7715     {
7716       CORE_ADDR low
7717         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
7718            - baseaddr);
7719       CORE_ADDR high
7720         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
7721            - baseaddr - 1);
7722       /* Store the contiguous range if it is not empty; it can be
7723          empty for CUs with no code.  */
7724       addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
7725                          low, high, pst);
7726     }
7727
7728   /* Check if comp unit has_children.
7729      If so, read the rest of the partial symbols from this comp unit.
7730      If not, there's no more debug_info for this comp unit.  */
7731   if (comp_unit_die->has_children)
7732     {
7733       struct partial_die_info *first_die;
7734       CORE_ADDR lowpc, highpc;
7735
7736       lowpc = ((CORE_ADDR) -1);
7737       highpc = ((CORE_ADDR) 0);
7738
7739       first_die = load_partial_dies (reader, info_ptr, 1);
7740
7741       scan_partial_symbols (first_die, &lowpc, &highpc,
7742                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7743
7744       /* If we didn't find a lowpc, set it to highpc to avoid
7745          complaints from `maint check'.  */
7746       if (lowpc == ((CORE_ADDR) -1))
7747         lowpc = highpc;
7748
7749       /* If the compilation unit didn't have an explicit address range,
7750          then use the information extracted from its child dies.  */
7751       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7752         {
7753           best_lowpc = lowpc;
7754           best_highpc = highpc;
7755         }
7756     }
7757   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
7758                                                  best_lowpc + baseaddr)
7759                      - baseaddr);
7760   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
7761                                                   best_highpc + baseaddr)
7762                       - baseaddr);
7763
7764   end_psymtab_common (objfile, pst);
7765
7766   if (!cu->per_cu->imported_symtabs_empty ())
7767     {
7768       int i;
7769       int len = cu->per_cu->imported_symtabs_size ();
7770
7771       /* Fill in 'dependencies' here; we fill in 'users' in a
7772          post-pass.  */
7773       pst->number_of_dependencies = len;
7774       pst->dependencies
7775         = objfile->partial_symtabs->allocate_dependencies (len);
7776       for (i = 0; i < len; ++i)
7777         {
7778           pst->dependencies[i]
7779             = cu->per_cu->imported_symtabs->at (i)->v.psymtab;
7780         }
7781
7782       cu->per_cu->imported_symtabs_free ();
7783     }
7784
7785   /* Get the list of files included in the current compilation unit,
7786      and build a psymtab for each of them.  */
7787   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7788
7789   if (dwarf_read_debug)
7790     fprintf_unfiltered (gdb_stdlog,
7791                         "Psymtab for %s unit @%s: %s - %s"
7792                         ", %d global, %d static syms\n",
7793                         per_cu->is_debug_types ? "type" : "comp",
7794                         sect_offset_str (per_cu->sect_off),
7795                         paddress (gdbarch, pst->text_low (objfile)),
7796                         paddress (gdbarch, pst->text_high (objfile)),
7797                         pst->n_global_syms, pst->n_static_syms);
7798 }
7799
7800 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7801    Process compilation unit THIS_CU for a psymtab.  */
7802
7803 static void
7804 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
7805                            int want_partial_unit,
7806                            enum language pretend_language)
7807 {
7808   /* If this compilation unit was already read in, free the
7809      cached copy in order to read it in again.  This is
7810      necessary because we skipped some symbols when we first
7811      read in the compilation unit (see load_partial_dies).
7812      This problem could be avoided, but the benefit is unclear.  */
7813   if (this_cu->cu != NULL)
7814     free_one_cached_comp_unit (this_cu);
7815
7816   cutu_reader reader (this_cu, NULL, 0, 0, false);
7817
7818   if (reader.dummy_p)
7819     {
7820       /* Nothing.  */
7821     }
7822   else if (this_cu->is_debug_types)
7823     build_type_psymtabs_reader (&reader, reader.info_ptr,
7824                                 reader.comp_unit_die);
7825   else
7826     process_psymtab_comp_unit_reader (&reader, reader.info_ptr,
7827                                       reader.comp_unit_die,
7828                                       want_partial_unit,
7829                                       pretend_language);
7830
7831   /* Age out any secondary CUs.  */
7832   age_cached_comp_units (this_cu->dwarf2_per_objfile);
7833 }
7834
7835 /* Reader function for build_type_psymtabs.  */
7836
7837 static void
7838 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7839                             const gdb_byte *info_ptr,
7840                             struct die_info *type_unit_die)
7841 {
7842   struct dwarf2_per_objfile *dwarf2_per_objfile
7843     = reader->cu->per_cu->dwarf2_per_objfile;
7844   struct objfile *objfile = dwarf2_per_objfile->objfile;
7845   struct dwarf2_cu *cu = reader->cu;
7846   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7847   struct signatured_type *sig_type;
7848   struct type_unit_group *tu_group;
7849   struct attribute *attr;
7850   struct partial_die_info *first_die;
7851   CORE_ADDR lowpc, highpc;
7852   dwarf2_psymtab *pst;
7853
7854   gdb_assert (per_cu->is_debug_types);
7855   sig_type = (struct signatured_type *) per_cu;
7856
7857   if (! type_unit_die->has_children)
7858     return;
7859
7860   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
7861   tu_group = get_type_unit_group (cu, attr);
7862
7863   if (tu_group->tus == nullptr)
7864     tu_group->tus = new std::vector<signatured_type *>;
7865   tu_group->tus->push_back (sig_type);
7866
7867   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7868   pst = create_partial_symtab (per_cu, "");
7869   pst->anonymous = true;
7870
7871   first_die = load_partial_dies (reader, info_ptr, 1);
7872
7873   lowpc = (CORE_ADDR) -1;
7874   highpc = (CORE_ADDR) 0;
7875   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7876
7877   end_psymtab_common (objfile, pst);
7878 }
7879
7880 /* Struct used to sort TUs by their abbreviation table offset.  */
7881
7882 struct tu_abbrev_offset
7883 {
7884   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
7885   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
7886   {}
7887
7888   signatured_type *sig_type;
7889   sect_offset abbrev_offset;
7890 };
7891
7892 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
7893
7894 static bool
7895 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
7896                           const struct tu_abbrev_offset &b)
7897 {
7898   return a.abbrev_offset < b.abbrev_offset;
7899 }
7900
7901 /* Efficiently read all the type units.
7902    This does the bulk of the work for build_type_psymtabs.
7903
7904    The efficiency is because we sort TUs by the abbrev table they use and
7905    only read each abbrev table once.  In one program there are 200K TUs
7906    sharing 8K abbrev tables.
7907
7908    The main purpose of this function is to support building the
7909    dwarf2_per_objfile->type_unit_groups table.
7910    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7911    can collapse the search space by grouping them by stmt_list.
7912    The savings can be significant, in the same program from above the 200K TUs
7913    share 8K stmt_list tables.
7914
7915    FUNC is expected to call get_type_unit_group, which will create the
7916    struct type_unit_group if necessary and add it to
7917    dwarf2_per_objfile->type_unit_groups.  */
7918
7919 static void
7920 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
7921 {
7922   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7923   abbrev_table_up abbrev_table;
7924   sect_offset abbrev_offset;
7925
7926   /* It's up to the caller to not call us multiple times.  */
7927   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
7928
7929   if (dwarf2_per_objfile->all_type_units.empty ())
7930     return;
7931
7932   /* TUs typically share abbrev tables, and there can be way more TUs than
7933      abbrev tables.  Sort by abbrev table to reduce the number of times we
7934      read each abbrev table in.
7935      Alternatives are to punt or to maintain a cache of abbrev tables.
7936      This is simpler and efficient enough for now.
7937
7938      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7939      symtab to use).  Typically TUs with the same abbrev offset have the same
7940      stmt_list value too so in practice this should work well.
7941
7942      The basic algorithm here is:
7943
7944       sort TUs by abbrev table
7945       for each TU with same abbrev table:
7946         read abbrev table if first user
7947         read TU top level DIE
7948           [IWBN if DWO skeletons had DW_AT_stmt_list]
7949         call FUNC  */
7950
7951   if (dwarf_read_debug)
7952     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
7953
7954   /* Sort in a separate table to maintain the order of all_type_units
7955      for .gdb_index: TU indices directly index all_type_units.  */
7956   std::vector<tu_abbrev_offset> sorted_by_abbrev;
7957   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
7958
7959   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
7960     sorted_by_abbrev.emplace_back
7961       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
7962                                      sig_type->per_cu.section,
7963                                      sig_type->per_cu.sect_off));
7964
7965   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
7966              sort_tu_by_abbrev_offset);
7967
7968   abbrev_offset = (sect_offset) ~(unsigned) 0;
7969
7970   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
7971     {
7972       /* Switch to the next abbrev table if necessary.  */
7973       if (abbrev_table == NULL
7974           || tu.abbrev_offset != abbrev_offset)
7975         {
7976           abbrev_offset = tu.abbrev_offset;
7977           abbrev_table =
7978             abbrev_table::read (dwarf2_per_objfile->objfile,
7979                                 &dwarf2_per_objfile->abbrev,
7980                                 abbrev_offset);
7981           ++tu_stats->nr_uniq_abbrev_tables;
7982         }
7983
7984       cutu_reader reader (&tu.sig_type->per_cu, abbrev_table.get (),
7985                           0, 0, false);
7986       if (!reader.dummy_p)
7987         build_type_psymtabs_reader (&reader, reader.info_ptr,
7988                                     reader.comp_unit_die);
7989     }
7990 }
7991
7992 /* Print collected type unit statistics.  */
7993
7994 static void
7995 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
7996 {
7997   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7998
7999   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8000   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8001                       dwarf2_per_objfile->all_type_units.size ());
8002   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8003                       tu_stats->nr_uniq_abbrev_tables);
8004   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8005                       tu_stats->nr_symtabs);
8006   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8007                       tu_stats->nr_symtab_sharers);
8008   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8009                       tu_stats->nr_stmt_less_type_units);
8010   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8011                       tu_stats->nr_all_type_units_reallocs);
8012 }
8013
8014 /* Traversal function for build_type_psymtabs.  */
8015
8016 static int
8017 build_type_psymtab_dependencies (void **slot, void *info)
8018 {
8019   struct dwarf2_per_objfile *dwarf2_per_objfile
8020     = (struct dwarf2_per_objfile *) info;
8021   struct objfile *objfile = dwarf2_per_objfile->objfile;
8022   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8023   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8024   dwarf2_psymtab *pst = per_cu->v.psymtab;
8025   int len = (tu_group->tus == nullptr) ? 0 : tu_group->tus->size ();
8026   int i;
8027
8028   gdb_assert (len > 0);
8029   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8030
8031   pst->number_of_dependencies = len;
8032   pst->dependencies = objfile->partial_symtabs->allocate_dependencies (len);
8033   for (i = 0; i < len; ++i)
8034     {
8035       struct signatured_type *iter = tu_group->tus->at (i);
8036       gdb_assert (iter->per_cu.is_debug_types);
8037       pst->dependencies[i] = iter->per_cu.v.psymtab;
8038       iter->type_unit_group = tu_group;
8039     }
8040
8041   delete tu_group->tus;
8042   tu_group->tus = nullptr;
8043
8044   return 1;
8045 }
8046
8047 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8048    Build partial symbol tables for the .debug_types comp-units.  */
8049
8050 static void
8051 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8052 {
8053   if (! create_all_type_units (dwarf2_per_objfile))
8054     return;
8055
8056   build_type_psymtabs_1 (dwarf2_per_objfile);
8057 }
8058
8059 /* Traversal function for process_skeletonless_type_unit.
8060    Read a TU in a DWO file and build partial symbols for it.  */
8061
8062 static int
8063 process_skeletonless_type_unit (void **slot, void *info)
8064 {
8065   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8066   struct dwarf2_per_objfile *dwarf2_per_objfile
8067     = (struct dwarf2_per_objfile *) info;
8068   struct signatured_type find_entry, *entry;
8069
8070   /* If this TU doesn't exist in the global table, add it and read it in.  */
8071
8072   if (dwarf2_per_objfile->signatured_types == NULL)
8073     {
8074       dwarf2_per_objfile->signatured_types
8075         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8076     }
8077
8078   find_entry.signature = dwo_unit->signature;
8079   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
8080                          &find_entry, INSERT);
8081   /* If we've already seen this type there's nothing to do.  What's happening
8082      is we're doing our own version of comdat-folding here.  */
8083   if (*slot != NULL)
8084     return 1;
8085
8086   /* This does the job that create_all_type_units would have done for
8087      this TU.  */
8088   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8089   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8090   *slot = entry;
8091
8092   /* This does the job that build_type_psymtabs_1 would have done.  */
8093   cutu_reader reader (&entry->per_cu, NULL, 0, 0, false);
8094   if (!reader.dummy_p)
8095     build_type_psymtabs_reader (&reader, reader.info_ptr,
8096                                 reader.comp_unit_die);
8097
8098   return 1;
8099 }
8100
8101 /* Traversal function for process_skeletonless_type_units.  */
8102
8103 static int
8104 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8105 {
8106   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8107
8108   if (dwo_file->tus != NULL)
8109     htab_traverse_noresize (dwo_file->tus.get (),
8110                             process_skeletonless_type_unit, info);
8111
8112   return 1;
8113 }
8114
8115 /* Scan all TUs of DWO files, verifying we've processed them.
8116    This is needed in case a TU was emitted without its skeleton.
8117    Note: This can't be done until we know what all the DWO files are.  */
8118
8119 static void
8120 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8121 {
8122   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8123   if (get_dwp_file (dwarf2_per_objfile) == NULL
8124       && dwarf2_per_objfile->dwo_files != NULL)
8125     {
8126       htab_traverse_noresize (dwarf2_per_objfile->dwo_files.get (),
8127                               process_dwo_file_for_skeletonless_type_units,
8128                               dwarf2_per_objfile);
8129     }
8130 }
8131
8132 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8133
8134 static void
8135 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8136 {
8137   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8138     {
8139       dwarf2_psymtab *pst = per_cu->v.psymtab;
8140
8141       if (pst == NULL)
8142         continue;
8143
8144       for (int j = 0; j < pst->number_of_dependencies; ++j)
8145         {
8146           /* Set the 'user' field only if it is not already set.  */
8147           if (pst->dependencies[j]->user == NULL)
8148             pst->dependencies[j]->user = pst;
8149         }
8150     }
8151 }
8152
8153 /* Build the partial symbol table by doing a quick pass through the
8154    .debug_info and .debug_abbrev sections.  */
8155
8156 static void
8157 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8158 {
8159   struct objfile *objfile = dwarf2_per_objfile->objfile;
8160
8161   if (dwarf_read_debug)
8162     {
8163       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8164                           objfile_name (objfile));
8165     }
8166
8167   dwarf2_per_objfile->reading_partial_symbols = 1;
8168
8169   dwarf2_per_objfile->info.read (objfile);
8170
8171   /* Any cached compilation units will be linked by the per-objfile
8172      read_in_chain.  Make sure to free them when we're done.  */
8173   free_cached_comp_units freer (dwarf2_per_objfile);
8174
8175   build_type_psymtabs (dwarf2_per_objfile);
8176
8177   create_all_comp_units (dwarf2_per_objfile);
8178
8179   /* Create a temporary address map on a temporary obstack.  We later
8180      copy this to the final obstack.  */
8181   auto_obstack temp_obstack;
8182
8183   scoped_restore save_psymtabs_addrmap
8184     = make_scoped_restore (&objfile->partial_symtabs->psymtabs_addrmap,
8185                            addrmap_create_mutable (&temp_obstack));
8186
8187   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8188     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8189
8190   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8191   process_skeletonless_type_units (dwarf2_per_objfile);
8192
8193   /* Now that all TUs have been processed we can fill in the dependencies.  */
8194   if (dwarf2_per_objfile->type_unit_groups != NULL)
8195     {
8196       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups.get (),
8197                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8198     }
8199
8200   if (dwarf_read_debug)
8201     print_tu_stats (dwarf2_per_objfile);
8202
8203   set_partial_user (dwarf2_per_objfile);
8204
8205   objfile->partial_symtabs->psymtabs_addrmap
8206     = addrmap_create_fixed (objfile->partial_symtabs->psymtabs_addrmap,
8207                             objfile->partial_symtabs->obstack ());
8208   /* At this point we want to keep the address map.  */
8209   save_psymtabs_addrmap.release ();
8210
8211   if (dwarf_read_debug)
8212     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8213                         objfile_name (objfile));
8214 }
8215
8216 /* Load the partial DIEs for a secondary CU into memory.
8217    This is also used when rereading a primary CU with load_all_dies.  */
8218
8219 static void
8220 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8221 {
8222   cutu_reader reader (this_cu, NULL, 1, 1, false);
8223
8224   if (!reader.dummy_p)
8225     {
8226       prepare_one_comp_unit (reader.cu, reader.comp_unit_die,
8227                              language_minimal);
8228
8229       /* Check if comp unit has_children.
8230          If so, read the rest of the partial symbols from this comp unit.
8231          If not, there's no more debug_info for this comp unit.  */
8232       if (reader.comp_unit_die->has_children)
8233         load_partial_dies (&reader, reader.info_ptr, 0);
8234     }
8235 }
8236
8237 static void
8238 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8239                               struct dwarf2_section_info *section,
8240                               struct dwarf2_section_info *abbrev_section,
8241                               unsigned int is_dwz)
8242 {
8243   const gdb_byte *info_ptr;
8244   struct objfile *objfile = dwarf2_per_objfile->objfile;
8245
8246   if (dwarf_read_debug)
8247     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8248                         section->get_name (),
8249                         section->get_file_name ());
8250
8251   section->read (objfile);
8252
8253   info_ptr = section->buffer;
8254
8255   while (info_ptr < section->buffer + section->size)
8256     {
8257       struct dwarf2_per_cu_data *this_cu;
8258
8259       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8260
8261       comp_unit_head cu_header;
8262       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8263                                      abbrev_section, info_ptr,
8264                                      rcuh_kind::COMPILE);
8265
8266       /* Save the compilation unit for later lookup.  */
8267       if (cu_header.unit_type != DW_UT_type)
8268         {
8269           this_cu = XOBNEW (&objfile->objfile_obstack,
8270                             struct dwarf2_per_cu_data);
8271           memset (this_cu, 0, sizeof (*this_cu));
8272         }
8273       else
8274         {
8275           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8276                                   struct signatured_type);
8277           memset (sig_type, 0, sizeof (*sig_type));
8278           sig_type->signature = cu_header.signature;
8279           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8280           this_cu = &sig_type->per_cu;
8281         }
8282       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8283       this_cu->sect_off = sect_off;
8284       this_cu->length = cu_header.length + cu_header.initial_length_size;
8285       this_cu->is_dwz = is_dwz;
8286       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8287       this_cu->section = section;
8288
8289       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8290
8291       info_ptr = info_ptr + this_cu->length;
8292     }
8293 }
8294
8295 /* Create a list of all compilation units in OBJFILE.
8296    This is only done for -readnow and building partial symtabs.  */
8297
8298 static void
8299 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8300 {
8301   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8302   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8303                                 &dwarf2_per_objfile->abbrev, 0);
8304
8305   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8306   if (dwz != NULL)
8307     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8308                                   1);
8309 }
8310
8311 /* Process all loaded DIEs for compilation unit CU, starting at
8312    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8313    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8314    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8315    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8316
8317 static void
8318 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8319                       CORE_ADDR *highpc, int set_addrmap,
8320                       struct dwarf2_cu *cu)
8321 {
8322   struct partial_die_info *pdi;
8323
8324   /* Now, march along the PDI's, descending into ones which have
8325      interesting children but skipping the children of the other ones,
8326      until we reach the end of the compilation unit.  */
8327
8328   pdi = first_die;
8329
8330   while (pdi != NULL)
8331     {
8332       pdi->fixup (cu);
8333
8334       /* Anonymous namespaces or modules have no name but have interesting
8335          children, so we need to look at them.  Ditto for anonymous
8336          enums.  */
8337
8338       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8339           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8340           || pdi->tag == DW_TAG_imported_unit
8341           || pdi->tag == DW_TAG_inlined_subroutine)
8342         {
8343           switch (pdi->tag)
8344             {
8345             case DW_TAG_subprogram:
8346             case DW_TAG_inlined_subroutine:
8347               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8348               break;
8349             case DW_TAG_constant:
8350             case DW_TAG_variable:
8351             case DW_TAG_typedef:
8352             case DW_TAG_union_type:
8353               if (!pdi->is_declaration)
8354                 {
8355                   add_partial_symbol (pdi, cu);
8356                 }
8357               break;
8358             case DW_TAG_class_type:
8359             case DW_TAG_interface_type:
8360             case DW_TAG_structure_type:
8361               if (!pdi->is_declaration)
8362                 {
8363                   add_partial_symbol (pdi, cu);
8364                 }
8365               if ((cu->language == language_rust
8366                    || cu->language == language_cplus) && pdi->has_children)
8367                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8368                                       set_addrmap, cu);
8369               break;
8370             case DW_TAG_enumeration_type:
8371               if (!pdi->is_declaration)
8372                 add_partial_enumeration (pdi, cu);
8373               break;
8374             case DW_TAG_base_type:
8375             case DW_TAG_subrange_type:
8376               /* File scope base type definitions are added to the partial
8377                  symbol table.  */
8378               add_partial_symbol (pdi, cu);
8379               break;
8380             case DW_TAG_namespace:
8381               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8382               break;
8383             case DW_TAG_module:
8384               if (!pdi->is_declaration)
8385                 add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8386               break;
8387             case DW_TAG_imported_unit:
8388               {
8389                 struct dwarf2_per_cu_data *per_cu;
8390
8391                 /* For now we don't handle imported units in type units.  */
8392                 if (cu->per_cu->is_debug_types)
8393                   {
8394                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8395                              " supported in type units [in module %s]"),
8396                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8397                   }
8398
8399                 per_cu = dwarf2_find_containing_comp_unit
8400                            (pdi->d.sect_off, pdi->is_dwz,
8401                             cu->per_cu->dwarf2_per_objfile);
8402
8403                 /* Go read the partial unit, if needed.  */
8404                 if (per_cu->v.psymtab == NULL)
8405                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8406
8407                 cu->per_cu->imported_symtabs_push (per_cu);
8408               }
8409               break;
8410             case DW_TAG_imported_declaration:
8411               add_partial_symbol (pdi, cu);
8412               break;
8413             default:
8414               break;
8415             }
8416         }
8417
8418       /* If the die has a sibling, skip to the sibling.  */
8419
8420       pdi = pdi->die_sibling;
8421     }
8422 }
8423
8424 /* Functions used to compute the fully scoped name of a partial DIE.
8425
8426    Normally, this is simple.  For C++, the parent DIE's fully scoped
8427    name is concatenated with "::" and the partial DIE's name.
8428    Enumerators are an exception; they use the scope of their parent
8429    enumeration type, i.e. the name of the enumeration type is not
8430    prepended to the enumerator.
8431
8432    There are two complexities.  One is DW_AT_specification; in this
8433    case "parent" means the parent of the target of the specification,
8434    instead of the direct parent of the DIE.  The other is compilers
8435    which do not emit DW_TAG_namespace; in this case we try to guess
8436    the fully qualified name of structure types from their members'
8437    linkage names.  This must be done using the DIE's children rather
8438    than the children of any DW_AT_specification target.  We only need
8439    to do this for structures at the top level, i.e. if the target of
8440    any DW_AT_specification (if any; otherwise the DIE itself) does not
8441    have a parent.  */
8442
8443 /* Compute the scope prefix associated with PDI's parent, in
8444    compilation unit CU.  The result will be allocated on CU's
8445    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8446    field.  NULL is returned if no prefix is necessary.  */
8447 static const char *
8448 partial_die_parent_scope (struct partial_die_info *pdi,
8449                           struct dwarf2_cu *cu)
8450 {
8451   const char *grandparent_scope;
8452   struct partial_die_info *parent, *real_pdi;
8453
8454   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8455      then this means the parent of the specification DIE.  */
8456
8457   real_pdi = pdi;
8458   while (real_pdi->has_specification)
8459     {
8460       auto res = find_partial_die (real_pdi->spec_offset,
8461                                    real_pdi->spec_is_dwz, cu);
8462       real_pdi = res.pdi;
8463       cu = res.cu;
8464     }
8465
8466   parent = real_pdi->die_parent;
8467   if (parent == NULL)
8468     return NULL;
8469
8470   if (parent->scope_set)
8471     return parent->scope;
8472
8473   parent->fixup (cu);
8474
8475   grandparent_scope = partial_die_parent_scope (parent, cu);
8476
8477   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8478      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8479      Work around this problem here.  */
8480   if (cu->language == language_cplus
8481       && parent->tag == DW_TAG_namespace
8482       && strcmp (parent->name, "::") == 0
8483       && grandparent_scope == NULL)
8484     {
8485       parent->scope = NULL;
8486       parent->scope_set = 1;
8487       return NULL;
8488     }
8489
8490   /* Nested subroutines in Fortran get a prefix.  */
8491   if (pdi->tag == DW_TAG_enumerator)
8492     /* Enumerators should not get the name of the enumeration as a prefix.  */
8493     parent->scope = grandparent_scope;
8494   else if (parent->tag == DW_TAG_namespace
8495       || parent->tag == DW_TAG_module
8496       || parent->tag == DW_TAG_structure_type
8497       || parent->tag == DW_TAG_class_type
8498       || parent->tag == DW_TAG_interface_type
8499       || parent->tag == DW_TAG_union_type
8500       || parent->tag == DW_TAG_enumeration_type
8501       || (cu->language == language_fortran
8502           && parent->tag == DW_TAG_subprogram
8503           && pdi->tag == DW_TAG_subprogram))
8504     {
8505       if (grandparent_scope == NULL)
8506         parent->scope = parent->name;
8507       else
8508         parent->scope = typename_concat (&cu->comp_unit_obstack,
8509                                          grandparent_scope,
8510                                          parent->name, 0, cu);
8511     }
8512   else
8513     {
8514       /* FIXME drow/2004-04-01: What should we be doing with
8515          function-local names?  For partial symbols, we should probably be
8516          ignoring them.  */
8517       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
8518                  dwarf_tag_name (parent->tag),
8519                  sect_offset_str (pdi->sect_off));
8520       parent->scope = grandparent_scope;
8521     }
8522
8523   parent->scope_set = 1;
8524   return parent->scope;
8525 }
8526
8527 /* Return the fully scoped name associated with PDI, from compilation unit
8528    CU.  The result will be allocated with malloc.  */
8529
8530 static gdb::unique_xmalloc_ptr<char>
8531 partial_die_full_name (struct partial_die_info *pdi,
8532                        struct dwarf2_cu *cu)
8533 {
8534   const char *parent_scope;
8535
8536   /* If this is a template instantiation, we can not work out the
8537      template arguments from partial DIEs.  So, unfortunately, we have
8538      to go through the full DIEs.  At least any work we do building
8539      types here will be reused if full symbols are loaded later.  */
8540   if (pdi->has_template_arguments)
8541     {
8542       pdi->fixup (cu);
8543
8544       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8545         {
8546           struct die_info *die;
8547           struct attribute attr;
8548           struct dwarf2_cu *ref_cu = cu;
8549
8550           /* DW_FORM_ref_addr is using section offset.  */
8551           attr.name = (enum dwarf_attribute) 0;
8552           attr.form = DW_FORM_ref_addr;
8553           attr.u.unsnd = to_underlying (pdi->sect_off);
8554           die = follow_die_ref (NULL, &attr, &ref_cu);
8555
8556           return make_unique_xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8557         }
8558     }
8559
8560   parent_scope = partial_die_parent_scope (pdi, cu);
8561   if (parent_scope == NULL)
8562     return NULL;
8563   else
8564     return gdb::unique_xmalloc_ptr<char> (typename_concat (NULL, parent_scope,
8565                                                            pdi->name, 0, cu));
8566 }
8567
8568 static void
8569 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8570 {
8571   struct dwarf2_per_objfile *dwarf2_per_objfile
8572     = cu->per_cu->dwarf2_per_objfile;
8573   struct objfile *objfile = dwarf2_per_objfile->objfile;
8574   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8575   CORE_ADDR addr = 0;
8576   const char *actual_name = NULL;
8577   CORE_ADDR baseaddr;
8578
8579   baseaddr = objfile->text_section_offset ();
8580
8581   gdb::unique_xmalloc_ptr<char> built_actual_name
8582     = partial_die_full_name (pdi, cu);
8583   if (built_actual_name != NULL)
8584     actual_name = built_actual_name.get ();
8585
8586   if (actual_name == NULL)
8587     actual_name = pdi->name;
8588
8589   switch (pdi->tag)
8590     {
8591     case DW_TAG_inlined_subroutine:
8592     case DW_TAG_subprogram:
8593       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8594               - baseaddr);
8595       if (pdi->is_external
8596           || cu->language == language_ada
8597           || (cu->language == language_fortran
8598               && pdi->die_parent != NULL
8599               && pdi->die_parent->tag == DW_TAG_subprogram))
8600         {
8601           /* Normally, only "external" DIEs are part of the global scope.
8602              But in Ada and Fortran, we want to be able to access nested
8603              procedures globally.  So all Ada and Fortran subprograms are
8604              stored in the global scope.  */
8605           add_psymbol_to_list (actual_name,
8606                                built_actual_name != NULL,
8607                                VAR_DOMAIN, LOC_BLOCK,
8608                                SECT_OFF_TEXT (objfile),
8609                                psymbol_placement::GLOBAL,
8610                                addr,
8611                                cu->language, objfile);
8612         }
8613       else
8614         {
8615           add_psymbol_to_list (actual_name,
8616                                built_actual_name != NULL,
8617                                VAR_DOMAIN, LOC_BLOCK,
8618                                SECT_OFF_TEXT (objfile),
8619                                psymbol_placement::STATIC,
8620                                addr, cu->language, objfile);
8621         }
8622
8623       if (pdi->main_subprogram && actual_name != NULL)
8624         set_objfile_main_name (objfile, actual_name, cu->language);
8625       break;
8626     case DW_TAG_constant:
8627       add_psymbol_to_list (actual_name,
8628                            built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8629                            -1, (pdi->is_external
8630                                 ? psymbol_placement::GLOBAL
8631                                 : psymbol_placement::STATIC),
8632                            0, cu->language, objfile);
8633       break;
8634     case DW_TAG_variable:
8635       if (pdi->d.locdesc)
8636         addr = decode_locdesc (pdi->d.locdesc, cu);
8637
8638       if (pdi->d.locdesc
8639           && addr == 0
8640           && !dwarf2_per_objfile->has_section_at_zero)
8641         {
8642           /* A global or static variable may also have been stripped
8643              out by the linker if unused, in which case its address
8644              will be nullified; do not add such variables into partial
8645              symbol table then.  */
8646         }
8647       else if (pdi->is_external)
8648         {
8649           /* Global Variable.
8650              Don't enter into the minimal symbol tables as there is
8651              a minimal symbol table entry from the ELF symbols already.
8652              Enter into partial symbol table if it has a location
8653              descriptor or a type.
8654              If the location descriptor is missing, new_symbol will create
8655              a LOC_UNRESOLVED symbol, the address of the variable will then
8656              be determined from the minimal symbol table whenever the variable
8657              is referenced.
8658              The address for the partial symbol table entry is not
8659              used by GDB, but it comes in handy for debugging partial symbol
8660              table building.  */
8661
8662           if (pdi->d.locdesc || pdi->has_type)
8663             add_psymbol_to_list (actual_name,
8664                                  built_actual_name != NULL,
8665                                  VAR_DOMAIN, LOC_STATIC,
8666                                  SECT_OFF_TEXT (objfile),
8667                                  psymbol_placement::GLOBAL,
8668                                  addr, cu->language, objfile);
8669         }
8670       else
8671         {
8672           int has_loc = pdi->d.locdesc != NULL;
8673
8674           /* Static Variable.  Skip symbols whose value we cannot know (those
8675              without location descriptors or constant values).  */
8676           if (!has_loc && !pdi->has_const_value)
8677             return;
8678
8679           add_psymbol_to_list (actual_name,
8680                                built_actual_name != NULL,
8681                                VAR_DOMAIN, LOC_STATIC,
8682                                SECT_OFF_TEXT (objfile),
8683                                psymbol_placement::STATIC,
8684                                has_loc ? addr : 0,
8685                                cu->language, objfile);
8686         }
8687       break;
8688     case DW_TAG_typedef:
8689     case DW_TAG_base_type:
8690     case DW_TAG_subrange_type:
8691       add_psymbol_to_list (actual_name,
8692                            built_actual_name != NULL,
8693                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8694                            psymbol_placement::STATIC,
8695                            0, cu->language, objfile);
8696       break;
8697     case DW_TAG_imported_declaration:
8698     case DW_TAG_namespace:
8699       add_psymbol_to_list (actual_name,
8700                            built_actual_name != NULL,
8701                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8702                            psymbol_placement::GLOBAL,
8703                            0, cu->language, objfile);
8704       break;
8705     case DW_TAG_module:
8706       /* With Fortran 77 there might be a "BLOCK DATA" module
8707          available without any name.  If so, we skip the module as it
8708          doesn't bring any value.  */
8709       if (actual_name != nullptr)
8710         add_psymbol_to_list (actual_name,
8711                              built_actual_name != NULL,
8712                              MODULE_DOMAIN, LOC_TYPEDEF, -1,
8713                              psymbol_placement::GLOBAL,
8714                              0, cu->language, objfile);
8715       break;
8716     case DW_TAG_class_type:
8717     case DW_TAG_interface_type:
8718     case DW_TAG_structure_type:
8719     case DW_TAG_union_type:
8720     case DW_TAG_enumeration_type:
8721       /* Skip external references.  The DWARF standard says in the section
8722          about "Structure, Union, and Class Type Entries": "An incomplete
8723          structure, union or class type is represented by a structure,
8724          union or class entry that does not have a byte size attribute
8725          and that has a DW_AT_declaration attribute."  */
8726       if (!pdi->has_byte_size && pdi->is_declaration)
8727         return;
8728
8729       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8730          static vs. global.  */
8731       add_psymbol_to_list (actual_name,
8732                            built_actual_name != NULL,
8733                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
8734                            cu->language == language_cplus
8735                            ? psymbol_placement::GLOBAL
8736                            : psymbol_placement::STATIC,
8737                            0, cu->language, objfile);
8738
8739       break;
8740     case DW_TAG_enumerator:
8741       add_psymbol_to_list (actual_name,
8742                            built_actual_name != NULL,
8743                            VAR_DOMAIN, LOC_CONST, -1,
8744                            cu->language == language_cplus
8745                            ? psymbol_placement::GLOBAL
8746                            : psymbol_placement::STATIC,
8747                            0, cu->language, objfile);
8748       break;
8749     default:
8750       break;
8751     }
8752 }
8753
8754 /* Read a partial die corresponding to a namespace; also, add a symbol
8755    corresponding to that namespace to the symbol table.  NAMESPACE is
8756    the name of the enclosing namespace.  */
8757
8758 static void
8759 add_partial_namespace (struct partial_die_info *pdi,
8760                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8761                        int set_addrmap, struct dwarf2_cu *cu)
8762 {
8763   /* Add a symbol for the namespace.  */
8764
8765   add_partial_symbol (pdi, cu);
8766
8767   /* Now scan partial symbols in that namespace.  */
8768
8769   if (pdi->has_children)
8770     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8771 }
8772
8773 /* Read a partial die corresponding to a Fortran module.  */
8774
8775 static void
8776 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8777                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8778 {
8779   /* Add a symbol for the namespace.  */
8780
8781   add_partial_symbol (pdi, cu);
8782
8783   /* Now scan partial symbols in that module.  */
8784
8785   if (pdi->has_children)
8786     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8787 }
8788
8789 /* Read a partial die corresponding to a subprogram or an inlined
8790    subprogram and create a partial symbol for that subprogram.
8791    When the CU language allows it, this routine also defines a partial
8792    symbol for each nested subprogram that this subprogram contains.
8793    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
8794    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
8795
8796    PDI may also be a lexical block, in which case we simply search
8797    recursively for subprograms defined inside that lexical block.
8798    Again, this is only performed when the CU language allows this
8799    type of definitions.  */
8800
8801 static void
8802 add_partial_subprogram (struct partial_die_info *pdi,
8803                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
8804                         int set_addrmap, struct dwarf2_cu *cu)
8805 {
8806   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
8807     {
8808       if (pdi->has_pc_info)
8809         {
8810           if (pdi->lowpc < *lowpc)
8811             *lowpc = pdi->lowpc;
8812           if (pdi->highpc > *highpc)
8813             *highpc = pdi->highpc;
8814           if (set_addrmap)
8815             {
8816               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8817               struct gdbarch *gdbarch = get_objfile_arch (objfile);
8818               CORE_ADDR baseaddr;
8819               CORE_ADDR this_highpc;
8820               CORE_ADDR this_lowpc;
8821
8822               baseaddr = objfile->text_section_offset ();
8823               this_lowpc
8824                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8825                                                pdi->lowpc + baseaddr)
8826                    - baseaddr);
8827               this_highpc
8828                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8829                                                pdi->highpc + baseaddr)
8830                    - baseaddr);
8831               addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
8832                                  this_lowpc, this_highpc - 1,
8833                                  cu->per_cu->v.psymtab);
8834             }
8835         }
8836
8837       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8838         {
8839           if (!pdi->is_declaration)
8840             /* Ignore subprogram DIEs that do not have a name, they are
8841                illegal.  Do not emit a complaint at this point, we will
8842                do so when we convert this psymtab into a symtab.  */
8843             if (pdi->name)
8844               add_partial_symbol (pdi, cu);
8845         }
8846     }
8847
8848   if (! pdi->has_children)
8849     return;
8850
8851   if (cu->language == language_ada || cu->language == language_fortran)
8852     {
8853       pdi = pdi->die_child;
8854       while (pdi != NULL)
8855         {
8856           pdi->fixup (cu);
8857           if (pdi->tag == DW_TAG_subprogram
8858               || pdi->tag == DW_TAG_inlined_subroutine
8859               || pdi->tag == DW_TAG_lexical_block)
8860             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8861           pdi = pdi->die_sibling;
8862         }
8863     }
8864 }
8865
8866 /* Read a partial die corresponding to an enumeration type.  */
8867
8868 static void
8869 add_partial_enumeration (struct partial_die_info *enum_pdi,
8870                          struct dwarf2_cu *cu)
8871 {
8872   struct partial_die_info *pdi;
8873
8874   if (enum_pdi->name != NULL)
8875     add_partial_symbol (enum_pdi, cu);
8876
8877   pdi = enum_pdi->die_child;
8878   while (pdi)
8879     {
8880       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
8881         complaint (_("malformed enumerator DIE ignored"));
8882       else
8883         add_partial_symbol (pdi, cu);
8884       pdi = pdi->die_sibling;
8885     }
8886 }
8887
8888 /* Return the initial uleb128 in the die at INFO_PTR.  */
8889
8890 static unsigned int
8891 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8892 {
8893   unsigned int bytes_read;
8894
8895   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8896 }
8897
8898 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
8899    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
8900
8901    Return the corresponding abbrev, or NULL if the number is zero (indicating
8902    an empty DIE).  In either case *BYTES_READ will be set to the length of
8903    the initial number.  */
8904
8905 static struct abbrev_info *
8906 peek_die_abbrev (const die_reader_specs &reader,
8907                  const gdb_byte *info_ptr, unsigned int *bytes_read)
8908 {
8909   dwarf2_cu *cu = reader.cu;
8910   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
8911   unsigned int abbrev_number
8912     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8913
8914   if (abbrev_number == 0)
8915     return NULL;
8916
8917   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
8918   if (!abbrev)
8919     {
8920       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8921                " at offset %s [in module %s]"),
8922              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8923              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
8924     }
8925
8926   return abbrev;
8927 }
8928
8929 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8930    Returns a pointer to the end of a series of DIEs, terminated by an empty
8931    DIE.  Any children of the skipped DIEs will also be skipped.  */
8932
8933 static const gdb_byte *
8934 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8935 {
8936   while (1)
8937     {
8938       unsigned int bytes_read;
8939       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
8940
8941       if (abbrev == NULL)
8942         return info_ptr + bytes_read;
8943       else
8944         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8945     }
8946 }
8947
8948 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8949    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8950    abbrev corresponding to that skipped uleb128 should be passed in
8951    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8952    children.  */
8953
8954 static const gdb_byte *
8955 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8956               struct abbrev_info *abbrev)
8957 {
8958   unsigned int bytes_read;
8959   struct attribute attr;
8960   bfd *abfd = reader->abfd;
8961   struct dwarf2_cu *cu = reader->cu;
8962   const gdb_byte *buffer = reader->buffer;
8963   const gdb_byte *buffer_end = reader->buffer_end;
8964   unsigned int form, i;
8965
8966   for (i = 0; i < abbrev->num_attrs; i++)
8967     {
8968       /* The only abbrev we care about is DW_AT_sibling.  */
8969       if (abbrev->attrs[i].name == DW_AT_sibling)
8970         {
8971           bool ignored;
8972           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr,
8973                           &ignored);
8974           if (attr.form == DW_FORM_ref_addr)
8975             complaint (_("ignoring absolute DW_AT_sibling"));
8976           else
8977             {
8978               sect_offset off = dwarf2_get_ref_die_offset (&attr);
8979               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8980
8981               if (sibling_ptr < info_ptr)
8982                 complaint (_("DW_AT_sibling points backwards"));
8983               else if (sibling_ptr > reader->buffer_end)
8984                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
8985               else
8986                 return sibling_ptr;
8987             }
8988         }
8989
8990       /* If it isn't DW_AT_sibling, skip this attribute.  */
8991       form = abbrev->attrs[i].form;
8992     skip_attribute:
8993       switch (form)
8994         {
8995         case DW_FORM_ref_addr:
8996           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8997              and later it is offset sized.  */
8998           if (cu->header.version == 2)
8999             info_ptr += cu->header.addr_size;
9000           else
9001             info_ptr += cu->header.offset_size;
9002           break;
9003         case DW_FORM_GNU_ref_alt:
9004           info_ptr += cu->header.offset_size;
9005           break;
9006         case DW_FORM_addr:
9007           info_ptr += cu->header.addr_size;
9008           break;
9009         case DW_FORM_data1:
9010         case DW_FORM_ref1:
9011         case DW_FORM_flag:
9012         case DW_FORM_strx1:
9013           info_ptr += 1;
9014           break;
9015         case DW_FORM_flag_present:
9016         case DW_FORM_implicit_const:
9017           break;
9018         case DW_FORM_data2:
9019         case DW_FORM_ref2:
9020         case DW_FORM_strx2:
9021           info_ptr += 2;
9022           break;
9023         case DW_FORM_strx3:
9024           info_ptr += 3;
9025           break;
9026         case DW_FORM_data4:
9027         case DW_FORM_ref4:
9028         case DW_FORM_strx4:
9029           info_ptr += 4;
9030           break;
9031         case DW_FORM_data8:
9032         case DW_FORM_ref8:
9033         case DW_FORM_ref_sig8:
9034           info_ptr += 8;
9035           break;
9036         case DW_FORM_data16:
9037           info_ptr += 16;
9038           break;
9039         case DW_FORM_string:
9040           read_direct_string (abfd, info_ptr, &bytes_read);
9041           info_ptr += bytes_read;
9042           break;
9043         case DW_FORM_sec_offset:
9044         case DW_FORM_strp:
9045         case DW_FORM_GNU_strp_alt:
9046           info_ptr += cu->header.offset_size;
9047           break;
9048         case DW_FORM_exprloc:
9049         case DW_FORM_block:
9050           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9051           info_ptr += bytes_read;
9052           break;
9053         case DW_FORM_block1:
9054           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9055           break;
9056         case DW_FORM_block2:
9057           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9058           break;
9059         case DW_FORM_block4:
9060           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9061           break;
9062         case DW_FORM_addrx:
9063         case DW_FORM_strx:
9064         case DW_FORM_sdata:
9065         case DW_FORM_udata:
9066         case DW_FORM_ref_udata:
9067         case DW_FORM_GNU_addr_index:
9068         case DW_FORM_GNU_str_index:
9069         case DW_FORM_rnglistx:
9070           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9071           break;
9072         case DW_FORM_indirect:
9073           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9074           info_ptr += bytes_read;
9075           /* We need to continue parsing from here, so just go back to
9076              the top.  */
9077           goto skip_attribute;
9078
9079         default:
9080           error (_("Dwarf Error: Cannot handle %s "
9081                    "in DWARF reader [in module %s]"),
9082                  dwarf_form_name (form),
9083                  bfd_get_filename (abfd));
9084         }
9085     }
9086
9087   if (abbrev->has_children)
9088     return skip_children (reader, info_ptr);
9089   else
9090     return info_ptr;
9091 }
9092
9093 /* Locate ORIG_PDI's sibling.
9094    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9095
9096 static const gdb_byte *
9097 locate_pdi_sibling (const struct die_reader_specs *reader,
9098                     struct partial_die_info *orig_pdi,
9099                     const gdb_byte *info_ptr)
9100 {
9101   /* Do we know the sibling already?  */
9102
9103   if (orig_pdi->sibling)
9104     return orig_pdi->sibling;
9105
9106   /* Are there any children to deal with?  */
9107
9108   if (!orig_pdi->has_children)
9109     return info_ptr;
9110
9111   /* Skip the children the long way.  */
9112
9113   return skip_children (reader, info_ptr);
9114 }
9115
9116 /* Expand this partial symbol table into a full symbol table.  SELF is
9117    not NULL.  */
9118
9119 void
9120 dwarf2_psymtab::read_symtab (struct objfile *objfile)
9121 {
9122   struct dwarf2_per_objfile *dwarf2_per_objfile
9123     = get_dwarf2_per_objfile (objfile);
9124
9125   gdb_assert (!readin);
9126   /* If this psymtab is constructed from a debug-only objfile, the
9127      has_section_at_zero flag will not necessarily be correct.  We
9128      can get the correct value for this flag by looking at the data
9129      associated with the (presumably stripped) associated objfile.  */
9130   if (objfile->separate_debug_objfile_backlink)
9131     {
9132       struct dwarf2_per_objfile *dpo_backlink
9133         = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9134
9135       dwarf2_per_objfile->has_section_at_zero
9136         = dpo_backlink->has_section_at_zero;
9137     }
9138
9139   dwarf2_per_objfile->reading_partial_symbols = 0;
9140
9141   expand_psymtab (objfile);
9142
9143   process_cu_includes (dwarf2_per_objfile);
9144 }
9145 \f
9146 /* Reading in full CUs.  */
9147
9148 /* Add PER_CU to the queue.  */
9149
9150 static void
9151 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9152                  enum language pretend_language)
9153 {
9154   per_cu->queued = 1;
9155   per_cu->dwarf2_per_objfile->queue.emplace (per_cu, pretend_language);
9156 }
9157
9158 /* If PER_CU is not yet queued, add it to the queue.
9159    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9160    dependency.
9161    The result is non-zero if PER_CU was queued, otherwise the result is zero
9162    meaning either PER_CU is already queued or it is already loaded.
9163
9164    N.B. There is an invariant here that if a CU is queued then it is loaded.
9165    The caller is required to load PER_CU if we return non-zero.  */
9166
9167 static int
9168 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9169                        struct dwarf2_per_cu_data *per_cu,
9170                        enum language pretend_language)
9171 {
9172   /* We may arrive here during partial symbol reading, if we need full
9173      DIEs to process an unusual case (e.g. template arguments).  Do
9174      not queue PER_CU, just tell our caller to load its DIEs.  */
9175   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9176     {
9177       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9178         return 1;
9179       return 0;
9180     }
9181
9182   /* Mark the dependence relation so that we don't flush PER_CU
9183      too early.  */
9184   if (dependent_cu != NULL)
9185     dwarf2_add_dependence (dependent_cu, per_cu);
9186
9187   /* If it's already on the queue, we have nothing to do.  */
9188   if (per_cu->queued)
9189     return 0;
9190
9191   /* If the compilation unit is already loaded, just mark it as
9192      used.  */
9193   if (per_cu->cu != NULL)
9194     {
9195       per_cu->cu->last_used = 0;
9196       return 0;
9197     }
9198
9199   /* Add it to the queue.  */
9200   queue_comp_unit (per_cu, pretend_language);
9201
9202   return 1;
9203 }
9204
9205 /* Process the queue.  */
9206
9207 static void
9208 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9209 {
9210   if (dwarf_read_debug)
9211     {
9212       fprintf_unfiltered (gdb_stdlog,
9213                           "Expanding one or more symtabs of objfile %s ...\n",
9214                           objfile_name (dwarf2_per_objfile->objfile));
9215     }
9216
9217   /* The queue starts out with one item, but following a DIE reference
9218      may load a new CU, adding it to the end of the queue.  */
9219   while (!dwarf2_per_objfile->queue.empty ())
9220     {
9221       dwarf2_queue_item &item = dwarf2_per_objfile->queue.front ();
9222
9223       if ((dwarf2_per_objfile->using_index
9224            ? !item.per_cu->v.quick->compunit_symtab
9225            : (item.per_cu->v.psymtab && !item.per_cu->v.psymtab->readin))
9226           /* Skip dummy CUs.  */
9227           && item.per_cu->cu != NULL)
9228         {
9229           struct dwarf2_per_cu_data *per_cu = item.per_cu;
9230           unsigned int debug_print_threshold;
9231           char buf[100];
9232
9233           if (per_cu->is_debug_types)
9234             {
9235               struct signatured_type *sig_type =
9236                 (struct signatured_type *) per_cu;
9237
9238               sprintf (buf, "TU %s at offset %s",
9239                        hex_string (sig_type->signature),
9240                        sect_offset_str (per_cu->sect_off));
9241               /* There can be 100s of TUs.
9242                  Only print them in verbose mode.  */
9243               debug_print_threshold = 2;
9244             }
9245           else
9246             {
9247               sprintf (buf, "CU at offset %s",
9248                        sect_offset_str (per_cu->sect_off));
9249               debug_print_threshold = 1;
9250             }
9251
9252           if (dwarf_read_debug >= debug_print_threshold)
9253             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9254
9255           if (per_cu->is_debug_types)
9256             process_full_type_unit (per_cu, item.pretend_language);
9257           else
9258             process_full_comp_unit (per_cu, item.pretend_language);
9259
9260           if (dwarf_read_debug >= debug_print_threshold)
9261             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9262         }
9263
9264       item.per_cu->queued = 0;
9265       dwarf2_per_objfile->queue.pop ();
9266     }
9267
9268   if (dwarf_read_debug)
9269     {
9270       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9271                           objfile_name (dwarf2_per_objfile->objfile));
9272     }
9273 }
9274
9275 /* Read in full symbols for PST, and anything it depends on.  */
9276
9277 void
9278 dwarf2_psymtab::expand_psymtab (struct objfile *objfile)
9279 {
9280   struct dwarf2_per_cu_data *per_cu;
9281
9282   if (readin)
9283     return;
9284
9285   read_dependencies (objfile);
9286
9287   per_cu = per_cu_data;
9288
9289   if (per_cu == NULL)
9290     {
9291       /* It's an include file, no symbols to read for it.
9292          Everything is in the parent symtab.  */
9293       readin = true;
9294       return;
9295     }
9296
9297   dw2_do_instantiate_symtab (per_cu, false);
9298 }
9299
9300 /* Trivial hash function for die_info: the hash value of a DIE
9301    is its offset in .debug_info for this objfile.  */
9302
9303 static hashval_t
9304 die_hash (const void *item)
9305 {
9306   const struct die_info *die = (const struct die_info *) item;
9307
9308   return to_underlying (die->sect_off);
9309 }
9310
9311 /* Trivial comparison function for die_info structures: two DIEs
9312    are equal if they have the same offset.  */
9313
9314 static int
9315 die_eq (const void *item_lhs, const void *item_rhs)
9316 {
9317   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9318   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9319
9320   return die_lhs->sect_off == die_rhs->sect_off;
9321 }
9322
9323 /* Load the DIEs associated with PER_CU into memory.  */
9324
9325 static void
9326 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9327                      bool skip_partial,
9328                      enum language pretend_language)
9329 {
9330   gdb_assert (! this_cu->is_debug_types);
9331
9332   cutu_reader reader (this_cu, NULL, 1, 1, skip_partial);
9333   if (reader.dummy_p)
9334     return;
9335
9336   struct dwarf2_cu *cu = reader.cu;
9337   const gdb_byte *info_ptr = reader.info_ptr;
9338
9339   gdb_assert (cu->die_hash == NULL);
9340   cu->die_hash =
9341     htab_create_alloc_ex (cu->header.length / 12,
9342                           die_hash,
9343                           die_eq,
9344                           NULL,
9345                           &cu->comp_unit_obstack,
9346                           hashtab_obstack_allocate,
9347                           dummy_obstack_deallocate);
9348
9349   if (reader.comp_unit_die->has_children)
9350     reader.comp_unit_die->child
9351       = read_die_and_siblings (&reader, reader.info_ptr,
9352                                &info_ptr, reader.comp_unit_die);
9353   cu->dies = reader.comp_unit_die;
9354   /* comp_unit_die is not stored in die_hash, no need.  */
9355
9356   /* We try not to read any attributes in this function, because not
9357      all CUs needed for references have been loaded yet, and symbol
9358      table processing isn't initialized.  But we have to set the CU language,
9359      or we won't be able to build types correctly.
9360      Similarly, if we do not read the producer, we can not apply
9361      producer-specific interpretation.  */
9362   prepare_one_comp_unit (cu, cu->dies, pretend_language);
9363 }
9364
9365 /* Add a DIE to the delayed physname list.  */
9366
9367 static void
9368 add_to_method_list (struct type *type, int fnfield_index, int index,
9369                     const char *name, struct die_info *die,
9370                     struct dwarf2_cu *cu)
9371 {
9372   struct delayed_method_info mi;
9373   mi.type = type;
9374   mi.fnfield_index = fnfield_index;
9375   mi.index = index;
9376   mi.name = name;
9377   mi.die = die;
9378   cu->method_list.push_back (mi);
9379 }
9380
9381 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9382    "const" / "volatile".  If so, decrements LEN by the length of the
9383    modifier and return true.  Otherwise return false.  */
9384
9385 template<size_t N>
9386 static bool
9387 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9388 {
9389   size_t mod_len = sizeof (mod) - 1;
9390   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9391     {
9392       len -= mod_len;
9393       return true;
9394     }
9395   return false;
9396 }
9397
9398 /* Compute the physnames of any methods on the CU's method list.
9399
9400    The computation of method physnames is delayed in order to avoid the
9401    (bad) condition that one of the method's formal parameters is of an as yet
9402    incomplete type.  */
9403
9404 static void
9405 compute_delayed_physnames (struct dwarf2_cu *cu)
9406 {
9407   /* Only C++ delays computing physnames.  */
9408   if (cu->method_list.empty ())
9409     return;
9410   gdb_assert (cu->language == language_cplus);
9411
9412   for (const delayed_method_info &mi : cu->method_list)
9413     {
9414       const char *physname;
9415       struct fn_fieldlist *fn_flp
9416         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9417       physname = dwarf2_physname (mi.name, mi.die, cu);
9418       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9419         = physname ? physname : "";
9420
9421       /* Since there's no tag to indicate whether a method is a
9422          const/volatile overload, extract that information out of the
9423          demangled name.  */
9424       if (physname != NULL)
9425         {
9426           size_t len = strlen (physname);
9427
9428           while (1)
9429             {
9430               if (physname[len] == ')') /* shortcut */
9431                 break;
9432               else if (check_modifier (physname, len, " const"))
9433                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9434               else if (check_modifier (physname, len, " volatile"))
9435                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9436               else
9437                 break;
9438             }
9439         }
9440     }
9441
9442   /* The list is no longer needed.  */
9443   cu->method_list.clear ();
9444 }
9445
9446 /* Go objects should be embedded in a DW_TAG_module DIE,
9447    and it's not clear if/how imported objects will appear.
9448    To keep Go support simple until that's worked out,
9449    go back through what we've read and create something usable.
9450    We could do this while processing each DIE, and feels kinda cleaner,
9451    but that way is more invasive.
9452    This is to, for example, allow the user to type "p var" or "b main"
9453    without having to specify the package name, and allow lookups
9454    of module.object to work in contexts that use the expression
9455    parser.  */
9456
9457 static void
9458 fixup_go_packaging (struct dwarf2_cu *cu)
9459 {
9460   gdb::unique_xmalloc_ptr<char> package_name;
9461   struct pending *list;
9462   int i;
9463
9464   for (list = *cu->get_builder ()->get_global_symbols ();
9465        list != NULL;
9466        list = list->next)
9467     {
9468       for (i = 0; i < list->nsyms; ++i)
9469         {
9470           struct symbol *sym = list->symbol[i];
9471
9472           if (sym->language () == language_go
9473               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9474             {
9475               gdb::unique_xmalloc_ptr<char> this_package_name
9476                 (go_symbol_package_name (sym));
9477
9478               if (this_package_name == NULL)
9479                 continue;
9480               if (package_name == NULL)
9481                 package_name = std::move (this_package_name);
9482               else
9483                 {
9484                   struct objfile *objfile
9485                     = cu->per_cu->dwarf2_per_objfile->objfile;
9486                   if (strcmp (package_name.get (), this_package_name.get ()) != 0)
9487                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9488                                (symbol_symtab (sym) != NULL
9489                                 ? symtab_to_filename_for_display
9490                                     (symbol_symtab (sym))
9491                                 : objfile_name (objfile)),
9492                                this_package_name.get (), package_name.get ());
9493                 }
9494             }
9495         }
9496     }
9497
9498   if (package_name != NULL)
9499     {
9500       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9501       const char *saved_package_name
9502         = obstack_strdup (&objfile->per_bfd->storage_obstack, package_name.get ());
9503       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9504                                      saved_package_name);
9505       struct symbol *sym;
9506
9507       sym = allocate_symbol (objfile);
9508       sym->set_language (language_go, &objfile->objfile_obstack);
9509       sym->compute_and_set_names (saved_package_name, false, objfile->per_bfd);
9510       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9511          e.g., "main" finds the "main" module and not C's main().  */
9512       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9513       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9514       SYMBOL_TYPE (sym) = type;
9515
9516       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
9517     }
9518 }
9519
9520 /* Allocate a fully-qualified name consisting of the two parts on the
9521    obstack.  */
9522
9523 static const char *
9524 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9525 {
9526   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9527 }
9528
9529 /* A helper that allocates a struct discriminant_info to attach to a
9530    union type.  */
9531
9532 static struct discriminant_info *
9533 alloc_discriminant_info (struct type *type, int discriminant_index,
9534                          int default_index)
9535 {
9536   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9537   gdb_assert (discriminant_index == -1
9538               || (discriminant_index >= 0
9539                   && discriminant_index < TYPE_NFIELDS (type)));
9540   gdb_assert (default_index == -1
9541               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9542
9543   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9544
9545   struct discriminant_info *disc
9546     = ((struct discriminant_info *)
9547        TYPE_ZALLOC (type,
9548                     offsetof (struct discriminant_info, discriminants)
9549                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9550   disc->default_index = default_index;
9551   disc->discriminant_index = discriminant_index;
9552
9553   struct dynamic_prop prop;
9554   prop.kind = PROP_UNDEFINED;
9555   prop.data.baton = disc;
9556
9557   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9558
9559   return disc;
9560 }
9561
9562 /* Some versions of rustc emitted enums in an unusual way.
9563
9564    Ordinary enums were emitted as unions.  The first element of each
9565    structure in the union was named "RUST$ENUM$DISR".  This element
9566    held the discriminant.
9567
9568    These versions of Rust also implemented the "non-zero"
9569    optimization.  When the enum had two values, and one is empty and
9570    the other holds a pointer that cannot be zero, the pointer is used
9571    as the discriminant, with a zero value meaning the empty variant.
9572    Here, the union's first member is of the form
9573    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9574    where the fieldnos are the indices of the fields that should be
9575    traversed in order to find the field (which may be several fields deep)
9576    and the variantname is the name of the variant of the case when the
9577    field is zero.
9578
9579    This function recognizes whether TYPE is of one of these forms,
9580    and, if so, smashes it to be a variant type.  */
9581
9582 static void
9583 quirk_rust_enum (struct type *type, struct objfile *objfile)
9584 {
9585   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9586
9587   /* We don't need to deal with empty enums.  */
9588   if (TYPE_NFIELDS (type) == 0)
9589     return;
9590
9591 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9592   if (TYPE_NFIELDS (type) == 1
9593       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9594     {
9595       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9596
9597       /* Decode the field name to find the offset of the
9598          discriminant.  */
9599       ULONGEST bit_offset = 0;
9600       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9601       while (name[0] >= '0' && name[0] <= '9')
9602         {
9603           char *tail;
9604           unsigned long index = strtoul (name, &tail, 10);
9605           name = tail;
9606           if (*name != '$'
9607               || index >= TYPE_NFIELDS (field_type)
9608               || (TYPE_FIELD_LOC_KIND (field_type, index)
9609                   != FIELD_LOC_KIND_BITPOS))
9610             {
9611               complaint (_("Could not parse Rust enum encoding string \"%s\""
9612                            "[in module %s]"),
9613                          TYPE_FIELD_NAME (type, 0),
9614                          objfile_name (objfile));
9615               return;
9616             }
9617           ++name;
9618
9619           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9620           field_type = TYPE_FIELD_TYPE (field_type, index);
9621         }
9622
9623       /* Make a union to hold the variants.  */
9624       struct type *union_type = alloc_type (objfile);
9625       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9626       TYPE_NFIELDS (union_type) = 3;
9627       TYPE_FIELDS (union_type)
9628         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9629       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9630       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9631
9632       /* Put the discriminant must at index 0.  */
9633       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9634       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9635       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9636       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9637
9638       /* The order of fields doesn't really matter, so put the real
9639          field at index 1 and the data-less field at index 2.  */
9640       struct discriminant_info *disc
9641         = alloc_discriminant_info (union_type, 0, 1);
9642       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9643       TYPE_FIELD_NAME (union_type, 1)
9644         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9645       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9646         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9647                               TYPE_FIELD_NAME (union_type, 1));
9648
9649       const char *dataless_name
9650         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9651                               name);
9652       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9653                                               dataless_name);
9654       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9655       /* NAME points into the original discriminant name, which
9656          already has the correct lifetime.  */
9657       TYPE_FIELD_NAME (union_type, 2) = name;
9658       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9659       disc->discriminants[2] = 0;
9660
9661       /* Smash this type to be a structure type.  We have to do this
9662          because the type has already been recorded.  */
9663       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9664       TYPE_NFIELDS (type) = 1;
9665       TYPE_FIELDS (type)
9666         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9667
9668       /* Install the variant part.  */
9669       TYPE_FIELD_TYPE (type, 0) = union_type;
9670       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9671       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9672     }
9673   /* A union with a single anonymous field is probably an old-style
9674      univariant enum.  */
9675   else if (TYPE_NFIELDS (type) == 1 && streq (TYPE_FIELD_NAME (type, 0), ""))
9676     {
9677       /* Smash this type to be a structure type.  We have to do this
9678          because the type has already been recorded.  */
9679       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9680
9681       /* Make a union to hold the variants.  */
9682       struct type *union_type = alloc_type (objfile);
9683       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9684       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9685       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9686       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9687       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9688
9689       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9690       const char *variant_name
9691         = rust_last_path_segment (TYPE_NAME (field_type));
9692       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9693       TYPE_NAME (field_type)
9694         = rust_fully_qualify (&objfile->objfile_obstack,
9695                               TYPE_NAME (type), variant_name);
9696
9697       /* Install the union in the outer struct type.  */
9698       TYPE_NFIELDS (type) = 1;
9699       TYPE_FIELDS (type)
9700         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9701       TYPE_FIELD_TYPE (type, 0) = union_type;
9702       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9703       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9704
9705       alloc_discriminant_info (union_type, -1, 0);
9706     }
9707   else
9708     {
9709       struct type *disr_type = nullptr;
9710       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9711         {
9712           disr_type = TYPE_FIELD_TYPE (type, i);
9713
9714           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9715             {
9716               /* All fields of a true enum will be structs.  */
9717               return;
9718             }
9719           else if (TYPE_NFIELDS (disr_type) == 0)
9720             {
9721               /* Could be data-less variant, so keep going.  */
9722               disr_type = nullptr;
9723             }
9724           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9725                            "RUST$ENUM$DISR") != 0)
9726             {
9727               /* Not a Rust enum.  */
9728               return;
9729             }
9730           else
9731             {
9732               /* Found one.  */
9733               break;
9734             }
9735         }
9736
9737       /* If we got here without a discriminant, then it's probably
9738          just a union.  */
9739       if (disr_type == nullptr)
9740         return;
9741
9742       /* Smash this type to be a structure type.  We have to do this
9743          because the type has already been recorded.  */
9744       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9745
9746       /* Make a union to hold the variants.  */
9747       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
9748       struct type *union_type = alloc_type (objfile);
9749       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9750       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
9751       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9752       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9753       TYPE_FIELDS (union_type)
9754         = (struct field *) TYPE_ZALLOC (union_type,
9755                                         (TYPE_NFIELDS (union_type)
9756                                          * sizeof (struct field)));
9757
9758       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
9759               TYPE_NFIELDS (type) * sizeof (struct field));
9760
9761       /* Install the discriminant at index 0 in the union.  */
9762       TYPE_FIELD (union_type, 0) = *disr_field;
9763       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9764       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9765
9766       /* Install the union in the outer struct type.  */
9767       TYPE_FIELD_TYPE (type, 0) = union_type;
9768       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9769       TYPE_NFIELDS (type) = 1;
9770
9771       /* Set the size and offset of the union type.  */
9772       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9773
9774       /* We need a way to find the correct discriminant given a
9775          variant name.  For convenience we build a map here.  */
9776       struct type *enum_type = FIELD_TYPE (*disr_field);
9777       std::unordered_map<std::string, ULONGEST> discriminant_map;
9778       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
9779         {
9780           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
9781             {
9782               const char *name
9783                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
9784               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
9785             }
9786         }
9787
9788       int n_fields = TYPE_NFIELDS (union_type);
9789       struct discriminant_info *disc
9790         = alloc_discriminant_info (union_type, 0, -1);
9791       /* Skip the discriminant here.  */
9792       for (int i = 1; i < n_fields; ++i)
9793         {
9794           /* Find the final word in the name of this variant's type.
9795              That name can be used to look up the correct
9796              discriminant.  */
9797           const char *variant_name
9798             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
9799                                                                   i)));
9800
9801           auto iter = discriminant_map.find (variant_name);
9802           if (iter != discriminant_map.end ())
9803             disc->discriminants[i] = iter->second;
9804
9805           /* Remove the discriminant field, if it exists.  */
9806           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
9807           if (TYPE_NFIELDS (sub_type) > 0)
9808             {
9809               --TYPE_NFIELDS (sub_type);
9810               ++TYPE_FIELDS (sub_type);
9811             }
9812           TYPE_FIELD_NAME (union_type, i) = variant_name;
9813           TYPE_NAME (sub_type)
9814             = rust_fully_qualify (&objfile->objfile_obstack,
9815                                   TYPE_NAME (type), variant_name);
9816         }
9817     }
9818 }
9819
9820 /* Rewrite some Rust unions to be structures with variants parts.  */
9821
9822 static void
9823 rust_union_quirks (struct dwarf2_cu *cu)
9824 {
9825   gdb_assert (cu->language == language_rust);
9826   for (type *type_ : cu->rust_unions)
9827     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
9828   /* We don't need this any more.  */
9829   cu->rust_unions.clear ();
9830 }
9831
9832 /* Return the symtab for PER_CU.  This works properly regardless of
9833    whether we're using the index or psymtabs.  */
9834
9835 static struct compunit_symtab *
9836 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
9837 {
9838   return (per_cu->dwarf2_per_objfile->using_index
9839           ? per_cu->v.quick->compunit_symtab
9840           : per_cu->v.psymtab->compunit_symtab);
9841 }
9842
9843 /* A helper function for computing the list of all symbol tables
9844    included by PER_CU.  */
9845
9846 static void
9847 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
9848                                 htab_t all_children, htab_t all_type_symtabs,
9849                                 struct dwarf2_per_cu_data *per_cu,
9850                                 struct compunit_symtab *immediate_parent)
9851 {
9852   void **slot;
9853   struct compunit_symtab *cust;
9854
9855   slot = htab_find_slot (all_children, per_cu, INSERT);
9856   if (*slot != NULL)
9857     {
9858       /* This inclusion and its children have been processed.  */
9859       return;
9860     }
9861
9862   *slot = per_cu;
9863   /* Only add a CU if it has a symbol table.  */
9864   cust = get_compunit_symtab (per_cu);
9865   if (cust != NULL)
9866     {
9867       /* If this is a type unit only add its symbol table if we haven't
9868          seen it yet (type unit per_cu's can share symtabs).  */
9869       if (per_cu->is_debug_types)
9870         {
9871           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9872           if (*slot == NULL)
9873             {
9874               *slot = cust;
9875               result->push_back (cust);
9876               if (cust->user == NULL)
9877                 cust->user = immediate_parent;
9878             }
9879         }
9880       else
9881         {
9882           result->push_back (cust);
9883           if (cust->user == NULL)
9884             cust->user = immediate_parent;
9885         }
9886     }
9887
9888   if (!per_cu->imported_symtabs_empty ())
9889     for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9890       {
9891         recursively_compute_inclusions (result, all_children,
9892                                         all_type_symtabs, ptr, cust);
9893       }
9894 }
9895
9896 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9897    PER_CU.  */
9898
9899 static void
9900 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
9901 {
9902   gdb_assert (! per_cu->is_debug_types);
9903
9904   if (!per_cu->imported_symtabs_empty ())
9905     {
9906       int len;
9907       std::vector<compunit_symtab *> result_symtabs;
9908       htab_t all_children, all_type_symtabs;
9909       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
9910
9911       /* If we don't have a symtab, we can just skip this case.  */
9912       if (cust == NULL)
9913         return;
9914
9915       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9916                                         NULL, xcalloc, xfree);
9917       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9918                                             NULL, xcalloc, xfree);
9919
9920       for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9921         {
9922           recursively_compute_inclusions (&result_symtabs, all_children,
9923                                           all_type_symtabs, ptr, cust);
9924         }
9925
9926       /* Now we have a transitive closure of all the included symtabs.  */
9927       len = result_symtabs.size ();
9928       cust->includes
9929         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
9930                      struct compunit_symtab *, len + 1);
9931       memcpy (cust->includes, result_symtabs.data (),
9932               len * sizeof (compunit_symtab *));
9933       cust->includes[len] = NULL;
9934
9935       htab_delete (all_children);
9936       htab_delete (all_type_symtabs);
9937     }
9938 }
9939
9940 /* Compute the 'includes' field for the symtabs of all the CUs we just
9941    read.  */
9942
9943 static void
9944 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
9945 {
9946   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
9947     {
9948       if (! iter->is_debug_types)
9949         compute_compunit_symtab_includes (iter);
9950     }
9951
9952   dwarf2_per_objfile->just_read_cus.clear ();
9953 }
9954
9955 /* Generate full symbol information for PER_CU, whose DIEs have
9956    already been loaded into memory.  */
9957
9958 static void
9959 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
9960                         enum language pretend_language)
9961 {
9962   struct dwarf2_cu *cu = per_cu->cu;
9963   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
9964   struct objfile *objfile = dwarf2_per_objfile->objfile;
9965   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9966   CORE_ADDR lowpc, highpc;
9967   struct compunit_symtab *cust;
9968   CORE_ADDR baseaddr;
9969   struct block *static_block;
9970   CORE_ADDR addr;
9971
9972   baseaddr = objfile->text_section_offset ();
9973
9974   /* Clear the list here in case something was left over.  */
9975   cu->method_list.clear ();
9976
9977   cu->language = pretend_language;
9978   cu->language_defn = language_def (cu->language);
9979
9980   /* Do line number decoding in read_file_scope () */
9981   process_die (cu->dies, cu);
9982
9983   /* For now fudge the Go package.  */
9984   if (cu->language == language_go)
9985     fixup_go_packaging (cu);
9986
9987   /* Now that we have processed all the DIEs in the CU, all the types
9988      should be complete, and it should now be safe to compute all of the
9989      physnames.  */
9990   compute_delayed_physnames (cu);
9991
9992   if (cu->language == language_rust)
9993     rust_union_quirks (cu);
9994
9995   /* Some compilers don't define a DW_AT_high_pc attribute for the
9996      compilation unit.  If the DW_AT_high_pc is missing, synthesize
9997      it, by scanning the DIE's below the compilation unit.  */
9998   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
9999
10000   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10001   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
10002
10003   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10004      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10005      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10006      addrmap to help ensure it has an accurate map of pc values belonging to
10007      this comp unit.  */
10008   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10009
10010   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
10011                                                     SECT_OFF_TEXT (objfile),
10012                                                     0);
10013
10014   if (cust != NULL)
10015     {
10016       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10017
10018       /* Set symtab language to language from DW_AT_language.  If the
10019          compilation is from a C file generated by language preprocessors, do
10020          not set the language if it was already deduced by start_subfile.  */
10021       if (!(cu->language == language_c
10022             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10023         COMPUNIT_FILETABS (cust)->language = cu->language;
10024
10025       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10026          produce DW_AT_location with location lists but it can be possibly
10027          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10028          there were bugs in prologue debug info, fixed later in GCC-4.5
10029          by "unwind info for epilogues" patch (which is not directly related).
10030
10031          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10032          needed, it would be wrong due to missing DW_AT_producer there.
10033
10034          Still one can confuse GDB by using non-standard GCC compilation
10035          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10036          */
10037       if (cu->has_loclist && gcc_4_minor >= 5)
10038         cust->locations_valid = 1;
10039
10040       if (gcc_4_minor >= 5)
10041         cust->epilogue_unwind_valid = 1;
10042
10043       cust->call_site_htab = cu->call_site_htab;
10044     }
10045
10046   if (dwarf2_per_objfile->using_index)
10047     per_cu->v.quick->compunit_symtab = cust;
10048   else
10049     {
10050       dwarf2_psymtab *pst = per_cu->v.psymtab;
10051       pst->compunit_symtab = cust;
10052       pst->readin = true;
10053     }
10054
10055   /* Push it for inclusion processing later.  */
10056   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10057
10058   /* Not needed any more.  */
10059   cu->reset_builder ();
10060 }
10061
10062 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10063    already been loaded into memory.  */
10064
10065 static void
10066 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10067                         enum language pretend_language)
10068 {
10069   struct dwarf2_cu *cu = per_cu->cu;
10070   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10071   struct objfile *objfile = dwarf2_per_objfile->objfile;
10072   struct compunit_symtab *cust;
10073   struct signatured_type *sig_type;
10074
10075   gdb_assert (per_cu->is_debug_types);
10076   sig_type = (struct signatured_type *) per_cu;
10077
10078   /* Clear the list here in case something was left over.  */
10079   cu->method_list.clear ();
10080
10081   cu->language = pretend_language;
10082   cu->language_defn = language_def (cu->language);
10083
10084   /* The symbol tables are set up in read_type_unit_scope.  */
10085   process_die (cu->dies, cu);
10086
10087   /* For now fudge the Go package.  */
10088   if (cu->language == language_go)
10089     fixup_go_packaging (cu);
10090
10091   /* Now that we have processed all the DIEs in the CU, all the types
10092      should be complete, and it should now be safe to compute all of the
10093      physnames.  */
10094   compute_delayed_physnames (cu);
10095
10096   if (cu->language == language_rust)
10097     rust_union_quirks (cu);
10098
10099   /* TUs share symbol tables.
10100      If this is the first TU to use this symtab, complete the construction
10101      of it with end_expandable_symtab.  Otherwise, complete the addition of
10102      this TU's symbols to the existing symtab.  */
10103   if (sig_type->type_unit_group->compunit_symtab == NULL)
10104     {
10105       buildsym_compunit *builder = cu->get_builder ();
10106       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10107       sig_type->type_unit_group->compunit_symtab = cust;
10108
10109       if (cust != NULL)
10110         {
10111           /* Set symtab language to language from DW_AT_language.  If the
10112              compilation is from a C file generated by language preprocessors,
10113              do not set the language if it was already deduced by
10114              start_subfile.  */
10115           if (!(cu->language == language_c
10116                 && COMPUNIT_FILETABS (cust)->language != language_c))
10117             COMPUNIT_FILETABS (cust)->language = cu->language;
10118         }
10119     }
10120   else
10121     {
10122       cu->get_builder ()->augment_type_symtab ();
10123       cust = sig_type->type_unit_group->compunit_symtab;
10124     }
10125
10126   if (dwarf2_per_objfile->using_index)
10127     per_cu->v.quick->compunit_symtab = cust;
10128   else
10129     {
10130       dwarf2_psymtab *pst = per_cu->v.psymtab;
10131       pst->compunit_symtab = cust;
10132       pst->readin = true;
10133     }
10134
10135   /* Not needed any more.  */
10136   cu->reset_builder ();
10137 }
10138
10139 /* Process an imported unit DIE.  */
10140
10141 static void
10142 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10143 {
10144   struct attribute *attr;
10145
10146   /* For now we don't handle imported units in type units.  */
10147   if (cu->per_cu->is_debug_types)
10148     {
10149       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10150                " supported in type units [in module %s]"),
10151              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10152     }
10153
10154   attr = dwarf2_attr (die, DW_AT_import, cu);
10155   if (attr != NULL)
10156     {
10157       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10158       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10159       dwarf2_per_cu_data *per_cu
10160         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10161                                             cu->per_cu->dwarf2_per_objfile);
10162
10163       /* If necessary, add it to the queue and load its DIEs.  */
10164       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10165         load_full_comp_unit (per_cu, false, cu->language);
10166
10167       cu->per_cu->imported_symtabs_push (per_cu);
10168     }
10169 }
10170
10171 /* RAII object that represents a process_die scope: i.e.,
10172    starts/finishes processing a DIE.  */
10173 class process_die_scope
10174 {
10175 public:
10176   process_die_scope (die_info *die, dwarf2_cu *cu)
10177     : m_die (die), m_cu (cu)
10178   {
10179     /* We should only be processing DIEs not already in process.  */
10180     gdb_assert (!m_die->in_process);
10181     m_die->in_process = true;
10182   }
10183
10184   ~process_die_scope ()
10185   {
10186     m_die->in_process = false;
10187
10188     /* If we're done processing the DIE for the CU that owns the line
10189        header, we don't need the line header anymore.  */
10190     if (m_cu->line_header_die_owner == m_die)
10191       {
10192         delete m_cu->line_header;
10193         m_cu->line_header = NULL;
10194         m_cu->line_header_die_owner = NULL;
10195       }
10196   }
10197
10198 private:
10199   die_info *m_die;
10200   dwarf2_cu *m_cu;
10201 };
10202
10203 /* Process a die and its children.  */
10204
10205 static void
10206 process_die (struct die_info *die, struct dwarf2_cu *cu)
10207 {
10208   process_die_scope scope (die, cu);
10209
10210   switch (die->tag)
10211     {
10212     case DW_TAG_padding:
10213       break;
10214     case DW_TAG_compile_unit:
10215     case DW_TAG_partial_unit:
10216       read_file_scope (die, cu);
10217       break;
10218     case DW_TAG_type_unit:
10219       read_type_unit_scope (die, cu);
10220       break;
10221     case DW_TAG_subprogram:
10222       /* Nested subprograms in Fortran get a prefix.  */
10223       if (cu->language == language_fortran
10224           && die->parent != NULL
10225           && die->parent->tag == DW_TAG_subprogram)
10226         cu->processing_has_namespace_info = true;
10227       /* Fall through.  */
10228     case DW_TAG_inlined_subroutine:
10229       read_func_scope (die, cu);
10230       break;
10231     case DW_TAG_lexical_block:
10232     case DW_TAG_try_block:
10233     case DW_TAG_catch_block:
10234       read_lexical_block_scope (die, cu);
10235       break;
10236     case DW_TAG_call_site:
10237     case DW_TAG_GNU_call_site:
10238       read_call_site_scope (die, cu);
10239       break;
10240     case DW_TAG_class_type:
10241     case DW_TAG_interface_type:
10242     case DW_TAG_structure_type:
10243     case DW_TAG_union_type:
10244       process_structure_scope (die, cu);
10245       break;
10246     case DW_TAG_enumeration_type:
10247       process_enumeration_scope (die, cu);
10248       break;
10249
10250     /* These dies have a type, but processing them does not create
10251        a symbol or recurse to process the children.  Therefore we can
10252        read them on-demand through read_type_die.  */
10253     case DW_TAG_subroutine_type:
10254     case DW_TAG_set_type:
10255     case DW_TAG_array_type:
10256     case DW_TAG_pointer_type:
10257     case DW_TAG_ptr_to_member_type:
10258     case DW_TAG_reference_type:
10259     case DW_TAG_rvalue_reference_type:
10260     case DW_TAG_string_type:
10261       break;
10262
10263     case DW_TAG_base_type:
10264     case DW_TAG_subrange_type:
10265     case DW_TAG_typedef:
10266       /* Add a typedef symbol for the type definition, if it has a
10267          DW_AT_name.  */
10268       new_symbol (die, read_type_die (die, cu), cu);
10269       break;
10270     case DW_TAG_common_block:
10271       read_common_block (die, cu);
10272       break;
10273     case DW_TAG_common_inclusion:
10274       break;
10275     case DW_TAG_namespace:
10276       cu->processing_has_namespace_info = true;
10277       read_namespace (die, cu);
10278       break;
10279     case DW_TAG_module:
10280       cu->processing_has_namespace_info = true;
10281       read_module (die, cu);
10282       break;
10283     case DW_TAG_imported_declaration:
10284       cu->processing_has_namespace_info = true;
10285       if (read_namespace_alias (die, cu))
10286         break;
10287       /* The declaration is not a global namespace alias.  */
10288       /* Fall through.  */
10289     case DW_TAG_imported_module:
10290       cu->processing_has_namespace_info = true;
10291       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10292                                  || cu->language != language_fortran))
10293         complaint (_("Tag '%s' has unexpected children"),
10294                    dwarf_tag_name (die->tag));
10295       read_import_statement (die, cu);
10296       break;
10297
10298     case DW_TAG_imported_unit:
10299       process_imported_unit_die (die, cu);
10300       break;
10301
10302     case DW_TAG_variable:
10303       read_variable (die, cu);
10304       break;
10305
10306     default:
10307       new_symbol (die, NULL, cu);
10308       break;
10309     }
10310 }
10311 \f
10312 /* DWARF name computation.  */
10313
10314 /* A helper function for dwarf2_compute_name which determines whether DIE
10315    needs to have the name of the scope prepended to the name listed in the
10316    die.  */
10317
10318 static int
10319 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10320 {
10321   struct attribute *attr;
10322
10323   switch (die->tag)
10324     {
10325     case DW_TAG_namespace:
10326     case DW_TAG_typedef:
10327     case DW_TAG_class_type:
10328     case DW_TAG_interface_type:
10329     case DW_TAG_structure_type:
10330     case DW_TAG_union_type:
10331     case DW_TAG_enumeration_type:
10332     case DW_TAG_enumerator:
10333     case DW_TAG_subprogram:
10334     case DW_TAG_inlined_subroutine:
10335     case DW_TAG_member:
10336     case DW_TAG_imported_declaration:
10337       return 1;
10338
10339     case DW_TAG_variable:
10340     case DW_TAG_constant:
10341       /* We only need to prefix "globally" visible variables.  These include
10342          any variable marked with DW_AT_external or any variable that
10343          lives in a namespace.  [Variables in anonymous namespaces
10344          require prefixing, but they are not DW_AT_external.]  */
10345
10346       if (dwarf2_attr (die, DW_AT_specification, cu))
10347         {
10348           struct dwarf2_cu *spec_cu = cu;
10349
10350           return die_needs_namespace (die_specification (die, &spec_cu),
10351                                       spec_cu);
10352         }
10353
10354       attr = dwarf2_attr (die, DW_AT_external, cu);
10355       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10356           && die->parent->tag != DW_TAG_module)
10357         return 0;
10358       /* A variable in a lexical block of some kind does not need a
10359          namespace, even though in C++ such variables may be external
10360          and have a mangled name.  */
10361       if (die->parent->tag ==  DW_TAG_lexical_block
10362           || die->parent->tag ==  DW_TAG_try_block
10363           || die->parent->tag ==  DW_TAG_catch_block
10364           || die->parent->tag == DW_TAG_subprogram)
10365         return 0;
10366       return 1;
10367
10368     default:
10369       return 0;
10370     }
10371 }
10372
10373 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10374    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10375    defined for the given DIE.  */
10376
10377 static struct attribute *
10378 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10379 {
10380   struct attribute *attr;
10381
10382   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10383   if (attr == NULL)
10384     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10385
10386   return attr;
10387 }
10388
10389 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10390    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10391    defined for the given DIE.  */
10392
10393 static const char *
10394 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10395 {
10396   const char *linkage_name;
10397
10398   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10399   if (linkage_name == NULL)
10400     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10401
10402   return linkage_name;
10403 }
10404
10405 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10406    compute the physname for the object, which include a method's:
10407    - formal parameters (C++),
10408    - receiver type (Go),
10409
10410    The term "physname" is a bit confusing.
10411    For C++, for example, it is the demangled name.
10412    For Go, for example, it's the mangled name.
10413
10414    For Ada, return the DIE's linkage name rather than the fully qualified
10415    name.  PHYSNAME is ignored..
10416
10417    The result is allocated on the objfile_obstack and canonicalized.  */
10418
10419 static const char *
10420 dwarf2_compute_name (const char *name,
10421                      struct die_info *die, struct dwarf2_cu *cu,
10422                      int physname)
10423 {
10424   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10425
10426   if (name == NULL)
10427     name = dwarf2_name (die, cu);
10428
10429   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10430      but otherwise compute it by typename_concat inside GDB.
10431      FIXME: Actually this is not really true, or at least not always true.
10432      It's all very confusing.  compute_and_set_names doesn't try to demangle
10433      Fortran names because there is no mangling standard.  So new_symbol
10434      will set the demangled name to the result of dwarf2_full_name, and it is
10435      the demangled name that GDB uses if it exists.  */
10436   if (cu->language == language_ada
10437       || (cu->language == language_fortran && physname))
10438     {
10439       /* For Ada unit, we prefer the linkage name over the name, as
10440          the former contains the exported name, which the user expects
10441          to be able to reference.  Ideally, we want the user to be able
10442          to reference this entity using either natural or linkage name,
10443          but we haven't started looking at this enhancement yet.  */
10444       const char *linkage_name = dw2_linkage_name (die, cu);
10445
10446       if (linkage_name != NULL)
10447         return linkage_name;
10448     }
10449
10450   /* These are the only languages we know how to qualify names in.  */
10451   if (name != NULL
10452       && (cu->language == language_cplus
10453           || cu->language == language_fortran || cu->language == language_d
10454           || cu->language == language_rust))
10455     {
10456       if (die_needs_namespace (die, cu))
10457         {
10458           const char *prefix;
10459           const char *canonical_name = NULL;
10460
10461           string_file buf;
10462
10463           prefix = determine_prefix (die, cu);
10464           if (*prefix != '\0')
10465             {
10466               gdb::unique_xmalloc_ptr<char> prefixed_name
10467                 (typename_concat (NULL, prefix, name, physname, cu));
10468
10469               buf.puts (prefixed_name.get ());
10470             }
10471           else
10472             buf.puts (name);
10473
10474           /* Template parameters may be specified in the DIE's DW_AT_name, or
10475              as children with DW_TAG_template_type_param or
10476              DW_TAG_value_type_param.  If the latter, add them to the name
10477              here.  If the name already has template parameters, then
10478              skip this step; some versions of GCC emit both, and
10479              it is more efficient to use the pre-computed name.
10480
10481              Something to keep in mind about this process: it is very
10482              unlikely, or in some cases downright impossible, to produce
10483              something that will match the mangled name of a function.
10484              If the definition of the function has the same debug info,
10485              we should be able to match up with it anyway.  But fallbacks
10486              using the minimal symbol, for instance to find a method
10487              implemented in a stripped copy of libstdc++, will not work.
10488              If we do not have debug info for the definition, we will have to
10489              match them up some other way.
10490
10491              When we do name matching there is a related problem with function
10492              templates; two instantiated function templates are allowed to
10493              differ only by their return types, which we do not add here.  */
10494
10495           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10496             {
10497               struct attribute *attr;
10498               struct die_info *child;
10499               int first = 1;
10500
10501               die->building_fullname = 1;
10502
10503               for (child = die->child; child != NULL; child = child->sibling)
10504                 {
10505                   struct type *type;
10506                   LONGEST value;
10507                   const gdb_byte *bytes;
10508                   struct dwarf2_locexpr_baton *baton;
10509                   struct value *v;
10510
10511                   if (child->tag != DW_TAG_template_type_param
10512                       && child->tag != DW_TAG_template_value_param)
10513                     continue;
10514
10515                   if (first)
10516                     {
10517                       buf.puts ("<");
10518                       first = 0;
10519                     }
10520                   else
10521                     buf.puts (", ");
10522
10523                   attr = dwarf2_attr (child, DW_AT_type, cu);
10524                   if (attr == NULL)
10525                     {
10526                       complaint (_("template parameter missing DW_AT_type"));
10527                       buf.puts ("UNKNOWN_TYPE");
10528                       continue;
10529                     }
10530                   type = die_type (child, cu);
10531
10532                   if (child->tag == DW_TAG_template_type_param)
10533                     {
10534                       c_print_type (type, "", &buf, -1, 0, cu->language,
10535                                     &type_print_raw_options);
10536                       continue;
10537                     }
10538
10539                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10540                   if (attr == NULL)
10541                     {
10542                       complaint (_("template parameter missing "
10543                                    "DW_AT_const_value"));
10544                       buf.puts ("UNKNOWN_VALUE");
10545                       continue;
10546                     }
10547
10548                   dwarf2_const_value_attr (attr, type, name,
10549                                            &cu->comp_unit_obstack, cu,
10550                                            &value, &bytes, &baton);
10551
10552                   if (TYPE_NOSIGN (type))
10553                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10554                        changed, this can use value_print instead.  */
10555                     c_printchar (value, type, &buf);
10556                   else
10557                     {
10558                       struct value_print_options opts;
10559
10560                       if (baton != NULL)
10561                         v = dwarf2_evaluate_loc_desc (type, NULL,
10562                                                       baton->data,
10563                                                       baton->size,
10564                                                       baton->per_cu);
10565                       else if (bytes != NULL)
10566                         {
10567                           v = allocate_value (type);
10568                           memcpy (value_contents_writeable (v), bytes,
10569                                   TYPE_LENGTH (type));
10570                         }
10571                       else
10572                         v = value_from_longest (type, value);
10573
10574                       /* Specify decimal so that we do not depend on
10575                          the radix.  */
10576                       get_formatted_print_options (&opts, 'd');
10577                       opts.raw = 1;
10578                       value_print (v, &buf, &opts);
10579                       release_value (v);
10580                     }
10581                 }
10582
10583               die->building_fullname = 0;
10584
10585               if (!first)
10586                 {
10587                   /* Close the argument list, with a space if necessary
10588                      (nested templates).  */
10589                   if (!buf.empty () && buf.string ().back () == '>')
10590                     buf.puts (" >");
10591                   else
10592                     buf.puts (">");
10593                 }
10594             }
10595
10596           /* For C++ methods, append formal parameter type
10597              information, if PHYSNAME.  */
10598
10599           if (physname && die->tag == DW_TAG_subprogram
10600               && cu->language == language_cplus)
10601             {
10602               struct type *type = read_type_die (die, cu);
10603
10604               c_type_print_args (type, &buf, 1, cu->language,
10605                                  &type_print_raw_options);
10606
10607               if (cu->language == language_cplus)
10608                 {
10609                   /* Assume that an artificial first parameter is
10610                      "this", but do not crash if it is not.  RealView
10611                      marks unnamed (and thus unused) parameters as
10612                      artificial; there is no way to differentiate
10613                      the two cases.  */
10614                   if (TYPE_NFIELDS (type) > 0
10615                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10616                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10617                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10618                                                                         0))))
10619                     buf.puts (" const");
10620                 }
10621             }
10622
10623           const std::string &intermediate_name = buf.string ();
10624
10625           if (cu->language == language_cplus)
10626             canonical_name
10627               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10628                                           &objfile->per_bfd->storage_obstack);
10629
10630           /* If we only computed INTERMEDIATE_NAME, or if
10631              INTERMEDIATE_NAME is already canonical, then we need to
10632              copy it to the appropriate obstack.  */
10633           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10634             name = obstack_strdup (&objfile->per_bfd->storage_obstack,
10635                                    intermediate_name);
10636           else
10637             name = canonical_name;
10638         }
10639     }
10640
10641   return name;
10642 }
10643
10644 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10645    If scope qualifiers are appropriate they will be added.  The result
10646    will be allocated on the storage_obstack, or NULL if the DIE does
10647    not have a name.  NAME may either be from a previous call to
10648    dwarf2_name or NULL.
10649
10650    The output string will be canonicalized (if C++).  */
10651
10652 static const char *
10653 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10654 {
10655   return dwarf2_compute_name (name, die, cu, 0);
10656 }
10657
10658 /* Construct a physname for the given DIE in CU.  NAME may either be
10659    from a previous call to dwarf2_name or NULL.  The result will be
10660    allocated on the objfile_objstack or NULL if the DIE does not have a
10661    name.
10662
10663    The output string will be canonicalized (if C++).  */
10664
10665 static const char *
10666 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10667 {
10668   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10669   const char *retval, *mangled = NULL, *canon = NULL;
10670   int need_copy = 1;
10671
10672   /* In this case dwarf2_compute_name is just a shortcut not building anything
10673      on its own.  */
10674   if (!die_needs_namespace (die, cu))
10675     return dwarf2_compute_name (name, die, cu, 1);
10676
10677   mangled = dw2_linkage_name (die, cu);
10678
10679   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10680      See https://github.com/rust-lang/rust/issues/32925.  */
10681   if (cu->language == language_rust && mangled != NULL
10682       && strchr (mangled, '{') != NULL)
10683     mangled = NULL;
10684
10685   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10686      has computed.  */
10687   gdb::unique_xmalloc_ptr<char> demangled;
10688   if (mangled != NULL)
10689     {
10690
10691       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10692         {
10693           /* Do nothing (do not demangle the symbol name).  */
10694         }
10695       else if (cu->language == language_go)
10696         {
10697           /* This is a lie, but we already lie to the caller new_symbol.
10698              new_symbol assumes we return the mangled name.
10699              This just undoes that lie until things are cleaned up.  */
10700         }
10701       else
10702         {
10703           /* Use DMGL_RET_DROP for C++ template functions to suppress
10704              their return type.  It is easier for GDB users to search
10705              for such functions as `name(params)' than `long name(params)'.
10706              In such case the minimal symbol names do not match the full
10707              symbol names but for template functions there is never a need
10708              to look up their definition from their declaration so
10709              the only disadvantage remains the minimal symbol variant
10710              `long name(params)' does not have the proper inferior type.  */
10711           demangled.reset (gdb_demangle (mangled,
10712                                          (DMGL_PARAMS | DMGL_ANSI
10713                                           | DMGL_RET_DROP)));
10714         }
10715       if (demangled)
10716         canon = demangled.get ();
10717       else
10718         {
10719           canon = mangled;
10720           need_copy = 0;
10721         }
10722     }
10723
10724   if (canon == NULL || check_physname)
10725     {
10726       const char *physname = dwarf2_compute_name (name, die, cu, 1);
10727
10728       if (canon != NULL && strcmp (physname, canon) != 0)
10729         {
10730           /* It may not mean a bug in GDB.  The compiler could also
10731              compute DW_AT_linkage_name incorrectly.  But in such case
10732              GDB would need to be bug-to-bug compatible.  */
10733
10734           complaint (_("Computed physname <%s> does not match demangled <%s> "
10735                        "(from linkage <%s>) - DIE at %s [in module %s]"),
10736                      physname, canon, mangled, sect_offset_str (die->sect_off),
10737                      objfile_name (objfile));
10738
10739           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
10740              is available here - over computed PHYSNAME.  It is safer
10741              against both buggy GDB and buggy compilers.  */
10742
10743           retval = canon;
10744         }
10745       else
10746         {
10747           retval = physname;
10748           need_copy = 0;
10749         }
10750     }
10751   else
10752     retval = canon;
10753
10754   if (need_copy)
10755     retval = obstack_strdup (&objfile->per_bfd->storage_obstack, retval);
10756
10757   return retval;
10758 }
10759
10760 /* Inspect DIE in CU for a namespace alias.  If one exists, record
10761    a new symbol for it.
10762
10763    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
10764
10765 static int
10766 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
10767 {
10768   struct attribute *attr;
10769
10770   /* If the die does not have a name, this is not a namespace
10771      alias.  */
10772   attr = dwarf2_attr (die, DW_AT_name, cu);
10773   if (attr != NULL)
10774     {
10775       int num;
10776       struct die_info *d = die;
10777       struct dwarf2_cu *imported_cu = cu;
10778
10779       /* If the compiler has nested DW_AT_imported_declaration DIEs,
10780          keep inspecting DIEs until we hit the underlying import.  */
10781 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
10782       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
10783         {
10784           attr = dwarf2_attr (d, DW_AT_import, cu);
10785           if (attr == NULL)
10786             break;
10787
10788           d = follow_die_ref (d, attr, &imported_cu);
10789           if (d->tag != DW_TAG_imported_declaration)
10790             break;
10791         }
10792
10793       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10794         {
10795           complaint (_("DIE at %s has too many recursively imported "
10796                        "declarations"), sect_offset_str (d->sect_off));
10797           return 0;
10798         }
10799
10800       if (attr != NULL)
10801         {
10802           struct type *type;
10803           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10804
10805           type = get_die_type_at_offset (sect_off, cu->per_cu);
10806           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
10807             {
10808               /* This declaration is a global namespace alias.  Add
10809                  a symbol for it whose type is the aliased namespace.  */
10810               new_symbol (die, type, cu);
10811               return 1;
10812             }
10813         }
10814     }
10815
10816   return 0;
10817 }
10818
10819 /* Return the using directives repository (global or local?) to use in the
10820    current context for CU.
10821
10822    For Ada, imported declarations can materialize renamings, which *may* be
10823    global.  However it is impossible (for now?) in DWARF to distinguish
10824    "external" imported declarations and "static" ones.  As all imported
10825    declarations seem to be static in all other languages, make them all CU-wide
10826    global only in Ada.  */
10827
10828 static struct using_direct **
10829 using_directives (struct dwarf2_cu *cu)
10830 {
10831   if (cu->language == language_ada
10832       && cu->get_builder ()->outermost_context_p ())
10833     return cu->get_builder ()->get_global_using_directives ();
10834   else
10835     return cu->get_builder ()->get_local_using_directives ();
10836 }
10837
10838 /* Read the import statement specified by the given die and record it.  */
10839
10840 static void
10841 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10842 {
10843   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10844   struct attribute *import_attr;
10845   struct die_info *imported_die, *child_die;
10846   struct dwarf2_cu *imported_cu;
10847   const char *imported_name;
10848   const char *imported_name_prefix;
10849   const char *canonical_name;
10850   const char *import_alias;
10851   const char *imported_declaration = NULL;
10852   const char *import_prefix;
10853   std::vector<const char *> excludes;
10854
10855   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10856   if (import_attr == NULL)
10857     {
10858       complaint (_("Tag '%s' has no DW_AT_import"),
10859                  dwarf_tag_name (die->tag));
10860       return;
10861     }
10862
10863   imported_cu = cu;
10864   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10865   imported_name = dwarf2_name (imported_die, imported_cu);
10866   if (imported_name == NULL)
10867     {
10868       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10869
10870         The import in the following code:
10871         namespace A
10872           {
10873             typedef int B;
10874           }
10875
10876         int main ()
10877           {
10878             using A::B;
10879             B b;
10880             return b;
10881           }
10882
10883         ...
10884          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10885             <52>   DW_AT_decl_file   : 1
10886             <53>   DW_AT_decl_line   : 6
10887             <54>   DW_AT_import      : <0x75>
10888          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10889             <59>   DW_AT_name        : B
10890             <5b>   DW_AT_decl_file   : 1
10891             <5c>   DW_AT_decl_line   : 2
10892             <5d>   DW_AT_type        : <0x6e>
10893         ...
10894          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10895             <76>   DW_AT_byte_size   : 4
10896             <77>   DW_AT_encoding    : 5        (signed)
10897
10898         imports the wrong die ( 0x75 instead of 0x58 ).
10899         This case will be ignored until the gcc bug is fixed.  */
10900       return;
10901     }
10902
10903   /* Figure out the local name after import.  */
10904   import_alias = dwarf2_name (die, cu);
10905
10906   /* Figure out where the statement is being imported to.  */
10907   import_prefix = determine_prefix (die, cu);
10908
10909   /* Figure out what the scope of the imported die is and prepend it
10910      to the name of the imported die.  */
10911   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10912
10913   if (imported_die->tag != DW_TAG_namespace
10914       && imported_die->tag != DW_TAG_module)
10915     {
10916       imported_declaration = imported_name;
10917       canonical_name = imported_name_prefix;
10918     }
10919   else if (strlen (imported_name_prefix) > 0)
10920     canonical_name = obconcat (&objfile->objfile_obstack,
10921                                imported_name_prefix,
10922                                (cu->language == language_d ? "." : "::"),
10923                                imported_name, (char *) NULL);
10924   else
10925     canonical_name = imported_name;
10926
10927   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
10928     for (child_die = die->child; child_die && child_die->tag;
10929          child_die = sibling_die (child_die))
10930       {
10931         /* DWARF-4: A Fortran use statement with a “rename list” may be
10932            represented by an imported module entry with an import attribute
10933            referring to the module and owned entries corresponding to those
10934            entities that are renamed as part of being imported.  */
10935
10936         if (child_die->tag != DW_TAG_imported_declaration)
10937           {
10938             complaint (_("child DW_TAG_imported_declaration expected "
10939                          "- DIE at %s [in module %s]"),
10940                        sect_offset_str (child_die->sect_off),
10941                        objfile_name (objfile));
10942             continue;
10943           }
10944
10945         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10946         if (import_attr == NULL)
10947           {
10948             complaint (_("Tag '%s' has no DW_AT_import"),
10949                        dwarf_tag_name (child_die->tag));
10950             continue;
10951           }
10952
10953         imported_cu = cu;
10954         imported_die = follow_die_ref_or_sig (child_die, import_attr,
10955                                               &imported_cu);
10956         imported_name = dwarf2_name (imported_die, imported_cu);
10957         if (imported_name == NULL)
10958           {
10959             complaint (_("child DW_TAG_imported_declaration has unknown "
10960                          "imported name - DIE at %s [in module %s]"),
10961                        sect_offset_str (child_die->sect_off),
10962                        objfile_name (objfile));
10963             continue;
10964           }
10965
10966         excludes.push_back (imported_name);
10967
10968         process_die (child_die, cu);
10969       }
10970
10971   add_using_directive (using_directives (cu),
10972                        import_prefix,
10973                        canonical_name,
10974                        import_alias,
10975                        imported_declaration,
10976                        excludes,
10977                        0,
10978                        &objfile->objfile_obstack);
10979 }
10980
10981 /* ICC<14 does not output the required DW_AT_declaration on incomplete
10982    types, but gives them a size of zero.  Starting with version 14,
10983    ICC is compatible with GCC.  */
10984
10985 static bool
10986 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
10987 {
10988   if (!cu->checked_producer)
10989     check_producer (cu);
10990
10991   return cu->producer_is_icc_lt_14;
10992 }
10993
10994 /* ICC generates a DW_AT_type for C void functions.  This was observed on
10995    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
10996    which says that void functions should not have a DW_AT_type.  */
10997
10998 static bool
10999 producer_is_icc (struct dwarf2_cu *cu)
11000 {
11001   if (!cu->checked_producer)
11002     check_producer (cu);
11003
11004   return cu->producer_is_icc;
11005 }
11006
11007 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11008    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11009    this, it was first present in GCC release 4.3.0.  */
11010
11011 static bool
11012 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11013 {
11014   if (!cu->checked_producer)
11015     check_producer (cu);
11016
11017   return cu->producer_is_gcc_lt_4_3;
11018 }
11019
11020 static file_and_directory
11021 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11022 {
11023   file_and_directory res;
11024
11025   /* Find the filename.  Do not use dwarf2_name here, since the filename
11026      is not a source language identifier.  */
11027   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11028   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11029
11030   if (res.comp_dir == NULL
11031       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11032       && IS_ABSOLUTE_PATH (res.name))
11033     {
11034       res.comp_dir_storage = ldirname (res.name);
11035       if (!res.comp_dir_storage.empty ())
11036         res.comp_dir = res.comp_dir_storage.c_str ();
11037     }
11038   if (res.comp_dir != NULL)
11039     {
11040       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11041          directory, get rid of it.  */
11042       const char *cp = strchr (res.comp_dir, ':');
11043
11044       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11045         res.comp_dir = cp + 1;
11046     }
11047
11048   if (res.name == NULL)
11049     res.name = "<unknown>";
11050
11051   return res;
11052 }
11053
11054 /* Handle DW_AT_stmt_list for a compilation unit.
11055    DIE is the DW_TAG_compile_unit die for CU.
11056    COMP_DIR is the compilation directory.  LOWPC is passed to
11057    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11058
11059 static void
11060 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11061                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11062 {
11063   struct dwarf2_per_objfile *dwarf2_per_objfile
11064     = cu->per_cu->dwarf2_per_objfile;
11065   struct attribute *attr;
11066   struct line_header line_header_local;
11067   hashval_t line_header_local_hash;
11068   void **slot;
11069   int decode_mapping;
11070
11071   gdb_assert (! cu->per_cu->is_debug_types);
11072
11073   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11074   if (attr == NULL)
11075     return;
11076
11077   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11078
11079   /* The line header hash table is only created if needed (it exists to
11080      prevent redundant reading of the line table for partial_units).
11081      If we're given a partial_unit, we'll need it.  If we're given a
11082      compile_unit, then use the line header hash table if it's already
11083      created, but don't create one just yet.  */
11084
11085   if (dwarf2_per_objfile->line_header_hash == NULL
11086       && die->tag == DW_TAG_partial_unit)
11087     {
11088       dwarf2_per_objfile->line_header_hash
11089         .reset (htab_create_alloc (127, line_header_hash_voidp,
11090                                    line_header_eq_voidp,
11091                                    free_line_header_voidp,
11092                                    xcalloc, xfree));
11093     }
11094
11095   line_header_local.sect_off = line_offset;
11096   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11097   line_header_local_hash = line_header_hash (&line_header_local);
11098   if (dwarf2_per_objfile->line_header_hash != NULL)
11099     {
11100       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash.get (),
11101                                        &line_header_local,
11102                                        line_header_local_hash, NO_INSERT);
11103
11104       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11105          is not present in *SLOT (since if there is something in *SLOT then
11106          it will be for a partial_unit).  */
11107       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11108         {
11109           gdb_assert (*slot != NULL);
11110           cu->line_header = (struct line_header *) *slot;
11111           return;
11112         }
11113     }
11114
11115   /* dwarf_decode_line_header does not yet provide sufficient information.
11116      We always have to call also dwarf_decode_lines for it.  */
11117   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11118   if (lh == NULL)
11119     return;
11120
11121   cu->line_header = lh.release ();
11122   cu->line_header_die_owner = die;
11123
11124   if (dwarf2_per_objfile->line_header_hash == NULL)
11125     slot = NULL;
11126   else
11127     {
11128       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash.get (),
11129                                        &line_header_local,
11130                                        line_header_local_hash, INSERT);
11131       gdb_assert (slot != NULL);
11132     }
11133   if (slot != NULL && *slot == NULL)
11134     {
11135       /* This newly decoded line number information unit will be owned
11136          by line_header_hash hash table.  */
11137       *slot = cu->line_header;
11138       cu->line_header_die_owner = NULL;
11139     }
11140   else
11141     {
11142       /* We cannot free any current entry in (*slot) as that struct line_header
11143          may be already used by multiple CUs.  Create only temporary decoded
11144          line_header for this CU - it may happen at most once for each line
11145          number information unit.  And if we're not using line_header_hash
11146          then this is what we want as well.  */
11147       gdb_assert (die->tag != DW_TAG_partial_unit);
11148     }
11149   decode_mapping = (die->tag != DW_TAG_partial_unit);
11150   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11151                       decode_mapping);
11152
11153 }
11154
11155 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11156
11157 static void
11158 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11159 {
11160   struct dwarf2_per_objfile *dwarf2_per_objfile
11161     = cu->per_cu->dwarf2_per_objfile;
11162   struct objfile *objfile = dwarf2_per_objfile->objfile;
11163   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11164   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11165   CORE_ADDR highpc = ((CORE_ADDR) 0);
11166   struct attribute *attr;
11167   struct die_info *child_die;
11168   CORE_ADDR baseaddr;
11169
11170   prepare_one_comp_unit (cu, die, cu->language);
11171   baseaddr = objfile->text_section_offset ();
11172
11173   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11174
11175   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11176      from finish_block.  */
11177   if (lowpc == ((CORE_ADDR) -1))
11178     lowpc = highpc;
11179   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11180
11181   file_and_directory fnd = find_file_and_directory (die, cu);
11182
11183   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11184      standardised yet.  As a workaround for the language detection we fall
11185      back to the DW_AT_producer string.  */
11186   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11187     cu->language = language_opencl;
11188
11189   /* Similar hack for Go.  */
11190   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11191     set_cu_language (DW_LANG_Go, cu);
11192
11193   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
11194
11195   /* Decode line number information if present.  We do this before
11196      processing child DIEs, so that the line header table is available
11197      for DW_AT_decl_file.  */
11198   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11199
11200   /* Process all dies in compilation unit.  */
11201   if (die->child != NULL)
11202     {
11203       child_die = die->child;
11204       while (child_die && child_die->tag)
11205         {
11206           process_die (child_die, cu);
11207           child_die = sibling_die (child_die);
11208         }
11209     }
11210
11211   /* Decode macro information, if present.  Dwarf 2 macro information
11212      refers to information in the line number info statement program
11213      header, so we can only read it if we've read the header
11214      successfully.  */
11215   attr = dwarf2_attr (die, DW_AT_macros, cu);
11216   if (attr == NULL)
11217     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11218   if (attr && cu->line_header)
11219     {
11220       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11221         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11222
11223       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11224     }
11225   else
11226     {
11227       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11228       if (attr && cu->line_header)
11229         {
11230           unsigned int macro_offset = DW_UNSND (attr);
11231
11232           dwarf_decode_macros (cu, macro_offset, 0);
11233         }
11234     }
11235 }
11236
11237 void
11238 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
11239 {
11240   struct type_unit_group *tu_group;
11241   int first_time;
11242   struct attribute *attr;
11243   unsigned int i;
11244   struct signatured_type *sig_type;
11245
11246   gdb_assert (per_cu->is_debug_types);
11247   sig_type = (struct signatured_type *) per_cu;
11248
11249   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
11250
11251   /* If we're using .gdb_index (includes -readnow) then
11252      per_cu->type_unit_group may not have been set up yet.  */
11253   if (sig_type->type_unit_group == NULL)
11254     sig_type->type_unit_group = get_type_unit_group (this, attr);
11255   tu_group = sig_type->type_unit_group;
11256
11257   /* If we've already processed this stmt_list there's no real need to
11258      do it again, we could fake it and just recreate the part we need
11259      (file name,index -> symtab mapping).  If data shows this optimization
11260      is useful we can do it then.  */
11261   first_time = tu_group->compunit_symtab == NULL;
11262
11263   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11264      debug info.  */
11265   line_header_up lh;
11266   if (attr != NULL)
11267     {
11268       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11269       lh = dwarf_decode_line_header (line_offset, this);
11270     }
11271   if (lh == NULL)
11272     {
11273       if (first_time)
11274         start_symtab ("", NULL, 0);
11275       else
11276         {
11277           gdb_assert (tu_group->symtabs == NULL);
11278           gdb_assert (m_builder == nullptr);
11279           struct compunit_symtab *cust = tu_group->compunit_symtab;
11280           m_builder.reset (new struct buildsym_compunit
11281                            (COMPUNIT_OBJFILE (cust), "",
11282                             COMPUNIT_DIRNAME (cust),
11283                             compunit_language (cust),
11284                             0, cust));
11285         }
11286       return;
11287     }
11288
11289   line_header = lh.release ();
11290   line_header_die_owner = die;
11291
11292   if (first_time)
11293     {
11294       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
11295
11296       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11297          still initializing it, and our caller (a few levels up)
11298          process_full_type_unit still needs to know if this is the first
11299          time.  */
11300
11301       tu_group->num_symtabs = line_header->file_names_size ();
11302       tu_group->symtabs = XNEWVEC (struct symtab *,
11303                                    line_header->file_names_size ());
11304
11305       auto &file_names = line_header->file_names ();
11306       for (i = 0; i < file_names.size (); ++i)
11307         {
11308           file_entry &fe = file_names[i];
11309           dwarf2_start_subfile (this, fe.name,
11310                                 fe.include_dir (line_header));
11311           buildsym_compunit *b = get_builder ();
11312           if (b->get_current_subfile ()->symtab == NULL)
11313             {
11314               /* NOTE: start_subfile will recognize when it's been
11315                  passed a file it has already seen.  So we can't
11316                  assume there's a simple mapping from
11317                  cu->line_header->file_names to subfiles, plus
11318                  cu->line_header->file_names may contain dups.  */
11319               b->get_current_subfile ()->symtab
11320                 = allocate_symtab (cust, b->get_current_subfile ()->name);
11321             }
11322
11323           fe.symtab = b->get_current_subfile ()->symtab;
11324           tu_group->symtabs[i] = fe.symtab;
11325         }
11326     }
11327   else
11328     {
11329       gdb_assert (m_builder == nullptr);
11330       struct compunit_symtab *cust = tu_group->compunit_symtab;
11331       m_builder.reset (new struct buildsym_compunit
11332                        (COMPUNIT_OBJFILE (cust), "",
11333                         COMPUNIT_DIRNAME (cust),
11334                         compunit_language (cust),
11335                         0, cust));
11336
11337       auto &file_names = line_header->file_names ();
11338       for (i = 0; i < file_names.size (); ++i)
11339         {
11340           file_entry &fe = file_names[i];
11341           fe.symtab = tu_group->symtabs[i];
11342         }
11343     }
11344
11345   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11346      so they don't have a "real" (so to speak) symtab anyway.
11347      There is later code that will assign the main symtab to all symbols
11348      that don't have one.  We need to handle the case of a symbol with a
11349      missing symtab (DW_AT_decl_file) anyway.  */
11350 }
11351
11352 /* Process DW_TAG_type_unit.
11353    For TUs we want to skip the first top level sibling if it's not the
11354    actual type being defined by this TU.  In this case the first top
11355    level sibling is there to provide context only.  */
11356
11357 static void
11358 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11359 {
11360   struct die_info *child_die;
11361
11362   prepare_one_comp_unit (cu, die, language_minimal);
11363
11364   /* Initialize (or reinitialize) the machinery for building symtabs.
11365      We do this before processing child DIEs, so that the line header table
11366      is available for DW_AT_decl_file.  */
11367   cu->setup_type_unit_groups (die);
11368
11369   if (die->child != NULL)
11370     {
11371       child_die = die->child;
11372       while (child_die && child_die->tag)
11373         {
11374           process_die (child_die, cu);
11375           child_die = sibling_die (child_die);
11376         }
11377     }
11378 }
11379 \f
11380 /* DWO/DWP files.
11381
11382    http://gcc.gnu.org/wiki/DebugFission
11383    http://gcc.gnu.org/wiki/DebugFissionDWP
11384
11385    To simplify handling of both DWO files ("object" files with the DWARF info)
11386    and DWP files (a file with the DWOs packaged up into one file), we treat
11387    DWP files as having a collection of virtual DWO files.  */
11388
11389 static hashval_t
11390 hash_dwo_file (const void *item)
11391 {
11392   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11393   hashval_t hash;
11394
11395   hash = htab_hash_string (dwo_file->dwo_name);
11396   if (dwo_file->comp_dir != NULL)
11397     hash += htab_hash_string (dwo_file->comp_dir);
11398   return hash;
11399 }
11400
11401 static int
11402 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11403 {
11404   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11405   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11406
11407   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11408     return 0;
11409   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11410     return lhs->comp_dir == rhs->comp_dir;
11411   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11412 }
11413
11414 /* Allocate a hash table for DWO files.  */
11415
11416 static htab_up
11417 allocate_dwo_file_hash_table (struct objfile *objfile)
11418 {
11419   auto delete_dwo_file = [] (void *item)
11420     {
11421       struct dwo_file *dwo_file = (struct dwo_file *) item;
11422
11423       delete dwo_file;
11424     };
11425
11426   return htab_up (htab_create_alloc (41,
11427                                      hash_dwo_file,
11428                                      eq_dwo_file,
11429                                      delete_dwo_file,
11430                                      xcalloc, xfree));
11431 }
11432
11433 /* Lookup DWO file DWO_NAME.  */
11434
11435 static void **
11436 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11437                       const char *dwo_name,
11438                       const char *comp_dir)
11439 {
11440   struct dwo_file find_entry;
11441   void **slot;
11442
11443   if (dwarf2_per_objfile->dwo_files == NULL)
11444     dwarf2_per_objfile->dwo_files
11445       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11446
11447   find_entry.dwo_name = dwo_name;
11448   find_entry.comp_dir = comp_dir;
11449   slot = htab_find_slot (dwarf2_per_objfile->dwo_files.get (), &find_entry,
11450                          INSERT);
11451
11452   return slot;
11453 }
11454
11455 static hashval_t
11456 hash_dwo_unit (const void *item)
11457 {
11458   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11459
11460   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11461   return dwo_unit->signature;
11462 }
11463
11464 static int
11465 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11466 {
11467   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11468   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11469
11470   /* The signature is assumed to be unique within the DWO file.
11471      So while object file CU dwo_id's always have the value zero,
11472      that's OK, assuming each object file DWO file has only one CU,
11473      and that's the rule for now.  */
11474   return lhs->signature == rhs->signature;
11475 }
11476
11477 /* Allocate a hash table for DWO CUs,TUs.
11478    There is one of these tables for each of CUs,TUs for each DWO file.  */
11479
11480 static htab_up
11481 allocate_dwo_unit_table (struct objfile *objfile)
11482 {
11483   /* Start out with a pretty small number.
11484      Generally DWO files contain only one CU and maybe some TUs.  */
11485   return htab_up (htab_create_alloc (3,
11486                                      hash_dwo_unit,
11487                                      eq_dwo_unit,
11488                                      NULL, xcalloc, xfree));
11489 }
11490
11491 /* die_reader_func for create_dwo_cu.  */
11492
11493 static void
11494 create_dwo_cu_reader (const struct die_reader_specs *reader,
11495                       const gdb_byte *info_ptr,
11496                       struct die_info *comp_unit_die,
11497                       struct dwo_file *dwo_file,
11498                       struct dwo_unit *dwo_unit)
11499 {
11500   struct dwarf2_cu *cu = reader->cu;
11501   sect_offset sect_off = cu->per_cu->sect_off;
11502   struct dwarf2_section_info *section = cu->per_cu->section;
11503
11504   gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
11505   if (!signature.has_value ())
11506     {
11507       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11508                    " its dwo_id [in module %s]"),
11509                  sect_offset_str (sect_off), dwo_file->dwo_name);
11510       return;
11511     }
11512
11513   dwo_unit->dwo_file = dwo_file;
11514   dwo_unit->signature = *signature;
11515   dwo_unit->section = section;
11516   dwo_unit->sect_off = sect_off;
11517   dwo_unit->length = cu->per_cu->length;
11518
11519   if (dwarf_read_debug)
11520     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11521                         sect_offset_str (sect_off),
11522                         hex_string (dwo_unit->signature));
11523 }
11524
11525 /* Create the dwo_units for the CUs in a DWO_FILE.
11526    Note: This function processes DWO files only, not DWP files.  */
11527
11528 static void
11529 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11530                        dwarf2_cu *cu, struct dwo_file &dwo_file,
11531                        dwarf2_section_info &section, htab_up &cus_htab)
11532 {
11533   struct objfile *objfile = dwarf2_per_objfile->objfile;
11534   const gdb_byte *info_ptr, *end_ptr;
11535
11536   section.read (objfile);
11537   info_ptr = section.buffer;
11538
11539   if (info_ptr == NULL)
11540     return;
11541
11542   if (dwarf_read_debug)
11543     {
11544       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11545                           section.get_name (),
11546                           section.get_file_name ());
11547     }
11548
11549   end_ptr = info_ptr + section.size;
11550   while (info_ptr < end_ptr)
11551     {
11552       struct dwarf2_per_cu_data per_cu;
11553       struct dwo_unit read_unit {};
11554       struct dwo_unit *dwo_unit;
11555       void **slot;
11556       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11557
11558       memset (&per_cu, 0, sizeof (per_cu));
11559       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11560       per_cu.is_debug_types = 0;
11561       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11562       per_cu.section = &section;
11563
11564       cutu_reader reader (&per_cu, cu, &dwo_file);
11565       if (!reader.dummy_p)
11566         create_dwo_cu_reader (&reader, reader.info_ptr, reader.comp_unit_die,
11567                               &dwo_file, &read_unit);
11568       info_ptr += per_cu.length;
11569
11570       // If the unit could not be parsed, skip it.
11571       if (read_unit.dwo_file == NULL)
11572         continue;
11573
11574       if (cus_htab == NULL)
11575         cus_htab = allocate_dwo_unit_table (objfile);
11576
11577       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11578       *dwo_unit = read_unit;
11579       slot = htab_find_slot (cus_htab.get (), dwo_unit, INSERT);
11580       gdb_assert (slot != NULL);
11581       if (*slot != NULL)
11582         {
11583           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11584           sect_offset dup_sect_off = dup_cu->sect_off;
11585
11586           complaint (_("debug cu entry at offset %s is duplicate to"
11587                        " the entry at offset %s, signature %s"),
11588                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11589                      hex_string (dwo_unit->signature));
11590         }
11591       *slot = (void *)dwo_unit;
11592     }
11593 }
11594
11595 /* DWP file .debug_{cu,tu}_index section format:
11596    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11597
11598    DWP Version 1:
11599
11600    Both index sections have the same format, and serve to map a 64-bit
11601    signature to a set of section numbers.  Each section begins with a header,
11602    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11603    indexes, and a pool of 32-bit section numbers.  The index sections will be
11604    aligned at 8-byte boundaries in the file.
11605
11606    The index section header consists of:
11607
11608     V, 32 bit version number
11609     -, 32 bits unused
11610     N, 32 bit number of compilation units or type units in the index
11611     M, 32 bit number of slots in the hash table
11612
11613    Numbers are recorded using the byte order of the application binary.
11614
11615    The hash table begins at offset 16 in the section, and consists of an array
11616    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11617    order of the application binary).  Unused slots in the hash table are 0.
11618    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11619
11620    The parallel table begins immediately after the hash table
11621    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11622    array of 32-bit indexes (using the byte order of the application binary),
11623    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11624    table contains a 32-bit index into the pool of section numbers.  For unused
11625    hash table slots, the corresponding entry in the parallel table will be 0.
11626
11627    The pool of section numbers begins immediately following the hash table
11628    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11629    section numbers consists of an array of 32-bit words (using the byte order
11630    of the application binary).  Each item in the array is indexed starting
11631    from 0.  The hash table entry provides the index of the first section
11632    number in the set.  Additional section numbers in the set follow, and the
11633    set is terminated by a 0 entry (section number 0 is not used in ELF).
11634
11635    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11636    section must be the first entry in the set, and the .debug_abbrev.dwo must
11637    be the second entry. Other members of the set may follow in any order.
11638
11639    ---
11640
11641    DWP Version 2:
11642
11643    DWP Version 2 combines all the .debug_info, etc. sections into one,
11644    and the entries in the index tables are now offsets into these sections.
11645    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11646    section.
11647
11648    Index Section Contents:
11649     Header
11650     Hash Table of Signatures   dwp_hash_table.hash_table
11651     Parallel Table of Indices  dwp_hash_table.unit_table
11652     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11653     Table of Section Sizes     dwp_hash_table.v2.sizes
11654
11655    The index section header consists of:
11656
11657     V, 32 bit version number
11658     L, 32 bit number of columns in the table of section offsets
11659     N, 32 bit number of compilation units or type units in the index
11660     M, 32 bit number of slots in the hash table
11661
11662    Numbers are recorded using the byte order of the application binary.
11663
11664    The hash table has the same format as version 1.
11665    The parallel table of indices has the same format as version 1,
11666    except that the entries are origin-1 indices into the table of sections
11667    offsets and the table of section sizes.
11668
11669    The table of offsets begins immediately following the parallel table
11670    (at offset 16 + 12 * M from the beginning of the section).  The table is
11671    a two-dimensional array of 32-bit words (using the byte order of the
11672    application binary), with L columns and N+1 rows, in row-major order.
11673    Each row in the array is indexed starting from 0.  The first row provides
11674    a key to the remaining rows: each column in this row provides an identifier
11675    for a debug section, and the offsets in the same column of subsequent rows
11676    refer to that section.  The section identifiers are:
11677
11678     DW_SECT_INFO         1  .debug_info.dwo
11679     DW_SECT_TYPES        2  .debug_types.dwo
11680     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11681     DW_SECT_LINE         4  .debug_line.dwo
11682     DW_SECT_LOC          5  .debug_loc.dwo
11683     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11684     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11685     DW_SECT_MACRO        8  .debug_macro.dwo
11686
11687    The offsets provided by the CU and TU index sections are the base offsets
11688    for the contributions made by each CU or TU to the corresponding section
11689    in the package file.  Each CU and TU header contains an abbrev_offset
11690    field, used to find the abbreviations table for that CU or TU within the
11691    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11692    be interpreted as relative to the base offset given in the index section.
11693    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11694    should be interpreted as relative to the base offset for .debug_line.dwo,
11695    and offsets into other debug sections obtained from DWARF attributes should
11696    also be interpreted as relative to the corresponding base offset.
11697
11698    The table of sizes begins immediately following the table of offsets.
11699    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11700    with L columns and N rows, in row-major order.  Each row in the array is
11701    indexed starting from 1 (row 0 is shared by the two tables).
11702
11703    ---
11704
11705    Hash table lookup is handled the same in version 1 and 2:
11706
11707    We assume that N and M will not exceed 2^32 - 1.
11708    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11709
11710    Given a 64-bit compilation unit signature or a type signature S, an entry
11711    in the hash table is located as follows:
11712
11713    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11714       the low-order k bits all set to 1.
11715
11716    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11717
11718    3) If the hash table entry at index H matches the signature, use that
11719       entry.  If the hash table entry at index H is unused (all zeroes),
11720       terminate the search: the signature is not present in the table.
11721
11722    4) Let H = (H + H') modulo M. Repeat at Step 3.
11723
11724    Because M > N and H' and M are relatively prime, the search is guaranteed
11725    to stop at an unused slot or find the match.  */
11726
11727 /* Create a hash table to map DWO IDs to their CU/TU entry in
11728    .debug_{info,types}.dwo in DWP_FILE.
11729    Returns NULL if there isn't one.
11730    Note: This function processes DWP files only, not DWO files.  */
11731
11732 static struct dwp_hash_table *
11733 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11734                        struct dwp_file *dwp_file, int is_debug_types)
11735 {
11736   struct objfile *objfile = dwarf2_per_objfile->objfile;
11737   bfd *dbfd = dwp_file->dbfd.get ();
11738   const gdb_byte *index_ptr, *index_end;
11739   struct dwarf2_section_info *index;
11740   uint32_t version, nr_columns, nr_units, nr_slots;
11741   struct dwp_hash_table *htab;
11742
11743   if (is_debug_types)
11744     index = &dwp_file->sections.tu_index;
11745   else
11746     index = &dwp_file->sections.cu_index;
11747
11748   if (index->empty ())
11749     return NULL;
11750   index->read (objfile);
11751
11752   index_ptr = index->buffer;
11753   index_end = index_ptr + index->size;
11754
11755   version = read_4_bytes (dbfd, index_ptr);
11756   index_ptr += 4;
11757   if (version == 2)
11758     nr_columns = read_4_bytes (dbfd, index_ptr);
11759   else
11760     nr_columns = 0;
11761   index_ptr += 4;
11762   nr_units = read_4_bytes (dbfd, index_ptr);
11763   index_ptr += 4;
11764   nr_slots = read_4_bytes (dbfd, index_ptr);
11765   index_ptr += 4;
11766
11767   if (version != 1 && version != 2)
11768     {
11769       error (_("Dwarf Error: unsupported DWP file version (%s)"
11770                " [in module %s]"),
11771              pulongest (version), dwp_file->name);
11772     }
11773   if (nr_slots != (nr_slots & -nr_slots))
11774     {
11775       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
11776                " is not power of 2 [in module %s]"),
11777              pulongest (nr_slots), dwp_file->name);
11778     }
11779
11780   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
11781   htab->version = version;
11782   htab->nr_columns = nr_columns;
11783   htab->nr_units = nr_units;
11784   htab->nr_slots = nr_slots;
11785   htab->hash_table = index_ptr;
11786   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
11787
11788   /* Exit early if the table is empty.  */
11789   if (nr_slots == 0 || nr_units == 0
11790       || (version == 2 && nr_columns == 0))
11791     {
11792       /* All must be zero.  */
11793       if (nr_slots != 0 || nr_units != 0
11794           || (version == 2 && nr_columns != 0))
11795         {
11796           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
11797                        " all zero [in modules %s]"),
11798                      dwp_file->name);
11799         }
11800       return htab;
11801     }
11802
11803   if (version == 1)
11804     {
11805       htab->section_pool.v1.indices =
11806         htab->unit_table + sizeof (uint32_t) * nr_slots;
11807       /* It's harder to decide whether the section is too small in v1.
11808          V1 is deprecated anyway so we punt.  */
11809     }
11810   else
11811     {
11812       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11813       int *ids = htab->section_pool.v2.section_ids;
11814       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
11815       /* Reverse map for error checking.  */
11816       int ids_seen[DW_SECT_MAX + 1];
11817       int i;
11818
11819       if (nr_columns < 2)
11820         {
11821           error (_("Dwarf Error: bad DWP hash table, too few columns"
11822                    " in section table [in module %s]"),
11823                  dwp_file->name);
11824         }
11825       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11826         {
11827           error (_("Dwarf Error: bad DWP hash table, too many columns"
11828                    " in section table [in module %s]"),
11829                  dwp_file->name);
11830         }
11831       memset (ids, 255, sizeof_ids);
11832       memset (ids_seen, 255, sizeof (ids_seen));
11833       for (i = 0; i < nr_columns; ++i)
11834         {
11835           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11836
11837           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11838             {
11839               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11840                        " in section table [in module %s]"),
11841                      id, dwp_file->name);
11842             }
11843           if (ids_seen[id] != -1)
11844             {
11845               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11846                        " id %d in section table [in module %s]"),
11847                      id, dwp_file->name);
11848             }
11849           ids_seen[id] = i;
11850           ids[i] = id;
11851         }
11852       /* Must have exactly one info or types section.  */
11853       if (((ids_seen[DW_SECT_INFO] != -1)
11854            + (ids_seen[DW_SECT_TYPES] != -1))
11855           != 1)
11856         {
11857           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11858                    " DWO info/types section [in module %s]"),
11859                  dwp_file->name);
11860         }
11861       /* Must have an abbrev section.  */
11862       if (ids_seen[DW_SECT_ABBREV] == -1)
11863         {
11864           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11865                    " section [in module %s]"),
11866                  dwp_file->name);
11867         }
11868       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11869       htab->section_pool.v2.sizes =
11870         htab->section_pool.v2.offsets + (sizeof (uint32_t)
11871                                          * nr_units * nr_columns);
11872       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11873                                           * nr_units * nr_columns))
11874           > index_end)
11875         {
11876           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11877                    " [in module %s]"),
11878                  dwp_file->name);
11879         }
11880     }
11881
11882   return htab;
11883 }
11884
11885 /* Update SECTIONS with the data from SECTP.
11886
11887    This function is like the other "locate" section routines that are
11888    passed to bfd_map_over_sections, but in this context the sections to
11889    read comes from the DWP V1 hash table, not the full ELF section table.
11890
11891    The result is non-zero for success, or zero if an error was found.  */
11892
11893 static int
11894 locate_v1_virtual_dwo_sections (asection *sectp,
11895                                 struct virtual_v1_dwo_sections *sections)
11896 {
11897   const struct dwop_section_names *names = &dwop_section_names;
11898
11899   if (section_is_p (sectp->name, &names->abbrev_dwo))
11900     {
11901       /* There can be only one.  */
11902       if (sections->abbrev.s.section != NULL)
11903         return 0;
11904       sections->abbrev.s.section = sectp;
11905       sections->abbrev.size = bfd_section_size (sectp);
11906     }
11907   else if (section_is_p (sectp->name, &names->info_dwo)
11908            || section_is_p (sectp->name, &names->types_dwo))
11909     {
11910       /* There can be only one.  */
11911       if (sections->info_or_types.s.section != NULL)
11912         return 0;
11913       sections->info_or_types.s.section = sectp;
11914       sections->info_or_types.size = bfd_section_size (sectp);
11915     }
11916   else if (section_is_p (sectp->name, &names->line_dwo))
11917     {
11918       /* There can be only one.  */
11919       if (sections->line.s.section != NULL)
11920         return 0;
11921       sections->line.s.section = sectp;
11922       sections->line.size = bfd_section_size (sectp);
11923     }
11924   else if (section_is_p (sectp->name, &names->loc_dwo))
11925     {
11926       /* There can be only one.  */
11927       if (sections->loc.s.section != NULL)
11928         return 0;
11929       sections->loc.s.section = sectp;
11930       sections->loc.size = bfd_section_size (sectp);
11931     }
11932   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11933     {
11934       /* There can be only one.  */
11935       if (sections->macinfo.s.section != NULL)
11936         return 0;
11937       sections->macinfo.s.section = sectp;
11938       sections->macinfo.size = bfd_section_size (sectp);
11939     }
11940   else if (section_is_p (sectp->name, &names->macro_dwo))
11941     {
11942       /* There can be only one.  */
11943       if (sections->macro.s.section != NULL)
11944         return 0;
11945       sections->macro.s.section = sectp;
11946       sections->macro.size = bfd_section_size (sectp);
11947     }
11948   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11949     {
11950       /* There can be only one.  */
11951       if (sections->str_offsets.s.section != NULL)
11952         return 0;
11953       sections->str_offsets.s.section = sectp;
11954       sections->str_offsets.size = bfd_section_size (sectp);
11955     }
11956   else
11957     {
11958       /* No other kind of section is valid.  */
11959       return 0;
11960     }
11961
11962   return 1;
11963 }
11964
11965 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11966    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11967    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11968    This is for DWP version 1 files.  */
11969
11970 static struct dwo_unit *
11971 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
11972                            struct dwp_file *dwp_file,
11973                            uint32_t unit_index,
11974                            const char *comp_dir,
11975                            ULONGEST signature, int is_debug_types)
11976 {
11977   struct objfile *objfile = dwarf2_per_objfile->objfile;
11978   const struct dwp_hash_table *dwp_htab =
11979     is_debug_types ? dwp_file->tus : dwp_file->cus;
11980   bfd *dbfd = dwp_file->dbfd.get ();
11981   const char *kind = is_debug_types ? "TU" : "CU";
11982   struct dwo_file *dwo_file;
11983   struct dwo_unit *dwo_unit;
11984   struct virtual_v1_dwo_sections sections;
11985   void **dwo_file_slot;
11986   int i;
11987
11988   gdb_assert (dwp_file->version == 1);
11989
11990   if (dwarf_read_debug)
11991     {
11992       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
11993                           kind,
11994                           pulongest (unit_index), hex_string (signature),
11995                           dwp_file->name);
11996     }
11997
11998   /* Fetch the sections of this DWO unit.
11999      Put a limit on the number of sections we look for so that bad data
12000      doesn't cause us to loop forever.  */
12001
12002 #define MAX_NR_V1_DWO_SECTIONS \
12003   (1 /* .debug_info or .debug_types */ \
12004    + 1 /* .debug_abbrev */ \
12005    + 1 /* .debug_line */ \
12006    + 1 /* .debug_loc */ \
12007    + 1 /* .debug_str_offsets */ \
12008    + 1 /* .debug_macro or .debug_macinfo */ \
12009    + 1 /* trailing zero */)
12010
12011   memset (&sections, 0, sizeof (sections));
12012
12013   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12014     {
12015       asection *sectp;
12016       uint32_t section_nr =
12017         read_4_bytes (dbfd,
12018                       dwp_htab->section_pool.v1.indices
12019                       + (unit_index + i) * sizeof (uint32_t));
12020
12021       if (section_nr == 0)
12022         break;
12023       if (section_nr >= dwp_file->num_sections)
12024         {
12025           error (_("Dwarf Error: bad DWP hash table, section number too large"
12026                    " [in module %s]"),
12027                  dwp_file->name);
12028         }
12029
12030       sectp = dwp_file->elf_sections[section_nr];
12031       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12032         {
12033           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12034                    " [in module %s]"),
12035                  dwp_file->name);
12036         }
12037     }
12038
12039   if (i < 2
12040       || sections.info_or_types.empty ()
12041       || sections.abbrev.empty ())
12042     {
12043       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12044                " [in module %s]"),
12045              dwp_file->name);
12046     }
12047   if (i == MAX_NR_V1_DWO_SECTIONS)
12048     {
12049       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12050                " [in module %s]"),
12051              dwp_file->name);
12052     }
12053
12054   /* It's easier for the rest of the code if we fake a struct dwo_file and
12055      have dwo_unit "live" in that.  At least for now.
12056
12057      The DWP file can be made up of a random collection of CUs and TUs.
12058      However, for each CU + set of TUs that came from the same original DWO
12059      file, we can combine them back into a virtual DWO file to save space
12060      (fewer struct dwo_file objects to allocate).  Remember that for really
12061      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12062
12063   std::string virtual_dwo_name =
12064     string_printf ("virtual-dwo/%d-%d-%d-%d",
12065                    sections.abbrev.get_id (),
12066                    sections.line.get_id (),
12067                    sections.loc.get_id (),
12068                    sections.str_offsets.get_id ());
12069   /* Can we use an existing virtual DWO file?  */
12070   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12071                                         virtual_dwo_name.c_str (),
12072                                         comp_dir);
12073   /* Create one if necessary.  */
12074   if (*dwo_file_slot == NULL)
12075     {
12076       if (dwarf_read_debug)
12077         {
12078           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12079                               virtual_dwo_name.c_str ());
12080         }
12081       dwo_file = new struct dwo_file;
12082       dwo_file->dwo_name = obstack_strdup (&objfile->objfile_obstack,
12083                                            virtual_dwo_name);
12084       dwo_file->comp_dir = comp_dir;
12085       dwo_file->sections.abbrev = sections.abbrev;
12086       dwo_file->sections.line = sections.line;
12087       dwo_file->sections.loc = sections.loc;
12088       dwo_file->sections.macinfo = sections.macinfo;
12089       dwo_file->sections.macro = sections.macro;
12090       dwo_file->sections.str_offsets = sections.str_offsets;
12091       /* The "str" section is global to the entire DWP file.  */
12092       dwo_file->sections.str = dwp_file->sections.str;
12093       /* The info or types section is assigned below to dwo_unit,
12094          there's no need to record it in dwo_file.
12095          Also, we can't simply record type sections in dwo_file because
12096          we record a pointer into the vector in dwo_unit.  As we collect more
12097          types we'll grow the vector and eventually have to reallocate space
12098          for it, invalidating all copies of pointers into the previous
12099          contents.  */
12100       *dwo_file_slot = dwo_file;
12101     }
12102   else
12103     {
12104       if (dwarf_read_debug)
12105         {
12106           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12107                               virtual_dwo_name.c_str ());
12108         }
12109       dwo_file = (struct dwo_file *) *dwo_file_slot;
12110     }
12111
12112   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12113   dwo_unit->dwo_file = dwo_file;
12114   dwo_unit->signature = signature;
12115   dwo_unit->section =
12116     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12117   *dwo_unit->section = sections.info_or_types;
12118   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12119
12120   return dwo_unit;
12121 }
12122
12123 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12124    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12125    piece within that section used by a TU/CU, return a virtual section
12126    of just that piece.  */
12127
12128 static struct dwarf2_section_info
12129 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12130                        struct dwarf2_section_info *section,
12131                        bfd_size_type offset, bfd_size_type size)
12132 {
12133   struct dwarf2_section_info result;
12134   asection *sectp;
12135
12136   gdb_assert (section != NULL);
12137   gdb_assert (!section->is_virtual);
12138
12139   memset (&result, 0, sizeof (result));
12140   result.s.containing_section = section;
12141   result.is_virtual = true;
12142
12143   if (size == 0)
12144     return result;
12145
12146   sectp = section->get_bfd_section ();
12147
12148   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12149      bounds of the real section.  This is a pretty-rare event, so just
12150      flag an error (easier) instead of a warning and trying to cope.  */
12151   if (sectp == NULL
12152       || offset + size > bfd_section_size (sectp))
12153     {
12154       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12155                " in section %s [in module %s]"),
12156              sectp ? bfd_section_name (sectp) : "<unknown>",
12157              objfile_name (dwarf2_per_objfile->objfile));
12158     }
12159
12160   result.virtual_offset = offset;
12161   result.size = size;
12162   return result;
12163 }
12164
12165 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12166    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12167    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12168    This is for DWP version 2 files.  */
12169
12170 static struct dwo_unit *
12171 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12172                            struct dwp_file *dwp_file,
12173                            uint32_t unit_index,
12174                            const char *comp_dir,
12175                            ULONGEST signature, int is_debug_types)
12176 {
12177   struct objfile *objfile = dwarf2_per_objfile->objfile;
12178   const struct dwp_hash_table *dwp_htab =
12179     is_debug_types ? dwp_file->tus : dwp_file->cus;
12180   bfd *dbfd = dwp_file->dbfd.get ();
12181   const char *kind = is_debug_types ? "TU" : "CU";
12182   struct dwo_file *dwo_file;
12183   struct dwo_unit *dwo_unit;
12184   struct virtual_v2_dwo_sections sections;
12185   void **dwo_file_slot;
12186   int i;
12187
12188   gdb_assert (dwp_file->version == 2);
12189
12190   if (dwarf_read_debug)
12191     {
12192       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12193                           kind,
12194                           pulongest (unit_index), hex_string (signature),
12195                           dwp_file->name);
12196     }
12197
12198   /* Fetch the section offsets of this DWO unit.  */
12199
12200   memset (&sections, 0, sizeof (sections));
12201
12202   for (i = 0; i < dwp_htab->nr_columns; ++i)
12203     {
12204       uint32_t offset = read_4_bytes (dbfd,
12205                                       dwp_htab->section_pool.v2.offsets
12206                                       + (((unit_index - 1) * dwp_htab->nr_columns
12207                                           + i)
12208                                          * sizeof (uint32_t)));
12209       uint32_t size = read_4_bytes (dbfd,
12210                                     dwp_htab->section_pool.v2.sizes
12211                                     + (((unit_index - 1) * dwp_htab->nr_columns
12212                                         + i)
12213                                        * sizeof (uint32_t)));
12214
12215       switch (dwp_htab->section_pool.v2.section_ids[i])
12216         {
12217         case DW_SECT_INFO:
12218         case DW_SECT_TYPES:
12219           sections.info_or_types_offset = offset;
12220           sections.info_or_types_size = size;
12221           break;
12222         case DW_SECT_ABBREV:
12223           sections.abbrev_offset = offset;
12224           sections.abbrev_size = size;
12225           break;
12226         case DW_SECT_LINE:
12227           sections.line_offset = offset;
12228           sections.line_size = size;
12229           break;
12230         case DW_SECT_LOC:
12231           sections.loc_offset = offset;
12232           sections.loc_size = size;
12233           break;
12234         case DW_SECT_STR_OFFSETS:
12235           sections.str_offsets_offset = offset;
12236           sections.str_offsets_size = size;
12237           break;
12238         case DW_SECT_MACINFO:
12239           sections.macinfo_offset = offset;
12240           sections.macinfo_size = size;
12241           break;
12242         case DW_SECT_MACRO:
12243           sections.macro_offset = offset;
12244           sections.macro_size = size;
12245           break;
12246         }
12247     }
12248
12249   /* It's easier for the rest of the code if we fake a struct dwo_file and
12250      have dwo_unit "live" in that.  At least for now.
12251
12252      The DWP file can be made up of a random collection of CUs and TUs.
12253      However, for each CU + set of TUs that came from the same original DWO
12254      file, we can combine them back into a virtual DWO file to save space
12255      (fewer struct dwo_file objects to allocate).  Remember that for really
12256      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12257
12258   std::string virtual_dwo_name =
12259     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12260                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12261                    (long) (sections.line_size ? sections.line_offset : 0),
12262                    (long) (sections.loc_size ? sections.loc_offset : 0),
12263                    (long) (sections.str_offsets_size
12264                            ? sections.str_offsets_offset : 0));
12265   /* Can we use an existing virtual DWO file?  */
12266   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12267                                         virtual_dwo_name.c_str (),
12268                                         comp_dir);
12269   /* Create one if necessary.  */
12270   if (*dwo_file_slot == NULL)
12271     {
12272       if (dwarf_read_debug)
12273         {
12274           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12275                               virtual_dwo_name.c_str ());
12276         }
12277       dwo_file = new struct dwo_file;
12278       dwo_file->dwo_name = obstack_strdup (&objfile->objfile_obstack,
12279                                            virtual_dwo_name);
12280       dwo_file->comp_dir = comp_dir;
12281       dwo_file->sections.abbrev =
12282         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12283                                sections.abbrev_offset, sections.abbrev_size);
12284       dwo_file->sections.line =
12285         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12286                                sections.line_offset, sections.line_size);
12287       dwo_file->sections.loc =
12288         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12289                                sections.loc_offset, sections.loc_size);
12290       dwo_file->sections.macinfo =
12291         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12292                                sections.macinfo_offset, sections.macinfo_size);
12293       dwo_file->sections.macro =
12294         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12295                                sections.macro_offset, sections.macro_size);
12296       dwo_file->sections.str_offsets =
12297         create_dwp_v2_section (dwarf2_per_objfile,
12298                                &dwp_file->sections.str_offsets,
12299                                sections.str_offsets_offset,
12300                                sections.str_offsets_size);
12301       /* The "str" section is global to the entire DWP file.  */
12302       dwo_file->sections.str = dwp_file->sections.str;
12303       /* The info or types section is assigned below to dwo_unit,
12304          there's no need to record it in dwo_file.
12305          Also, we can't simply record type sections in dwo_file because
12306          we record a pointer into the vector in dwo_unit.  As we collect more
12307          types we'll grow the vector and eventually have to reallocate space
12308          for it, invalidating all copies of pointers into the previous
12309          contents.  */
12310       *dwo_file_slot = dwo_file;
12311     }
12312   else
12313     {
12314       if (dwarf_read_debug)
12315         {
12316           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12317                               virtual_dwo_name.c_str ());
12318         }
12319       dwo_file = (struct dwo_file *) *dwo_file_slot;
12320     }
12321
12322   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12323   dwo_unit->dwo_file = dwo_file;
12324   dwo_unit->signature = signature;
12325   dwo_unit->section =
12326     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12327   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12328                                               is_debug_types
12329                                               ? &dwp_file->sections.types
12330                                               : &dwp_file->sections.info,
12331                                               sections.info_or_types_offset,
12332                                               sections.info_or_types_size);
12333   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12334
12335   return dwo_unit;
12336 }
12337
12338 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12339    Returns NULL if the signature isn't found.  */
12340
12341 static struct dwo_unit *
12342 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12343                         struct dwp_file *dwp_file, const char *comp_dir,
12344                         ULONGEST signature, int is_debug_types)
12345 {
12346   const struct dwp_hash_table *dwp_htab =
12347     is_debug_types ? dwp_file->tus : dwp_file->cus;
12348   bfd *dbfd = dwp_file->dbfd.get ();
12349   uint32_t mask = dwp_htab->nr_slots - 1;
12350   uint32_t hash = signature & mask;
12351   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12352   unsigned int i;
12353   void **slot;
12354   struct dwo_unit find_dwo_cu;
12355
12356   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12357   find_dwo_cu.signature = signature;
12358   slot = htab_find_slot (is_debug_types
12359                          ? dwp_file->loaded_tus.get ()
12360                          : dwp_file->loaded_cus.get (),
12361                          &find_dwo_cu, INSERT);
12362
12363   if (*slot != NULL)
12364     return (struct dwo_unit *) *slot;
12365
12366   /* Use a for loop so that we don't loop forever on bad debug info.  */
12367   for (i = 0; i < dwp_htab->nr_slots; ++i)
12368     {
12369       ULONGEST signature_in_table;
12370
12371       signature_in_table =
12372         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12373       if (signature_in_table == signature)
12374         {
12375           uint32_t unit_index =
12376             read_4_bytes (dbfd,
12377                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12378
12379           if (dwp_file->version == 1)
12380             {
12381               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12382                                                  dwp_file, unit_index,
12383                                                  comp_dir, signature,
12384                                                  is_debug_types);
12385             }
12386           else
12387             {
12388               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12389                                                  dwp_file, unit_index,
12390                                                  comp_dir, signature,
12391                                                  is_debug_types);
12392             }
12393           return (struct dwo_unit *) *slot;
12394         }
12395       if (signature_in_table == 0)
12396         return NULL;
12397       hash = (hash + hash2) & mask;
12398     }
12399
12400   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12401            " [in module %s]"),
12402          dwp_file->name);
12403 }
12404
12405 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12406    Open the file specified by FILE_NAME and hand it off to BFD for
12407    preliminary analysis.  Return a newly initialized bfd *, which
12408    includes a canonicalized copy of FILE_NAME.
12409    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12410    SEARCH_CWD is true if the current directory is to be searched.
12411    It will be searched before debug-file-directory.
12412    If successful, the file is added to the bfd include table of the
12413    objfile's bfd (see gdb_bfd_record_inclusion).
12414    If unable to find/open the file, return NULL.
12415    NOTE: This function is derived from symfile_bfd_open.  */
12416
12417 static gdb_bfd_ref_ptr
12418 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12419                     const char *file_name, int is_dwp, int search_cwd)
12420 {
12421   int desc;
12422   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12423      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12424      to debug_file_directory.  */
12425   const char *search_path;
12426   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12427
12428   gdb::unique_xmalloc_ptr<char> search_path_holder;
12429   if (search_cwd)
12430     {
12431       if (*debug_file_directory != '\0')
12432         {
12433           search_path_holder.reset (concat (".", dirname_separator_string,
12434                                             debug_file_directory,
12435                                             (char *) NULL));
12436           search_path = search_path_holder.get ();
12437         }
12438       else
12439         search_path = ".";
12440     }
12441   else
12442     search_path = debug_file_directory;
12443
12444   openp_flags flags = OPF_RETURN_REALPATH;
12445   if (is_dwp)
12446     flags |= OPF_SEARCH_IN_PATH;
12447
12448   gdb::unique_xmalloc_ptr<char> absolute_name;
12449   desc = openp (search_path, flags, file_name,
12450                 O_RDONLY | O_BINARY, &absolute_name);
12451   if (desc < 0)
12452     return NULL;
12453
12454   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12455                                          gnutarget, desc));
12456   if (sym_bfd == NULL)
12457     return NULL;
12458   bfd_set_cacheable (sym_bfd.get (), 1);
12459
12460   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12461     return NULL;
12462
12463   /* Success.  Record the bfd as having been included by the objfile's bfd.
12464      This is important because things like demangled_names_hash lives in the
12465      objfile's per_bfd space and may have references to things like symbol
12466      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12467   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12468
12469   return sym_bfd;
12470 }
12471
12472 /* Try to open DWO file FILE_NAME.
12473    COMP_DIR is the DW_AT_comp_dir attribute.
12474    The result is the bfd handle of the file.
12475    If there is a problem finding or opening the file, return NULL.
12476    Upon success, the canonicalized path of the file is stored in the bfd,
12477    same as symfile_bfd_open.  */
12478
12479 static gdb_bfd_ref_ptr
12480 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12481                const char *file_name, const char *comp_dir)
12482 {
12483   if (IS_ABSOLUTE_PATH (file_name))
12484     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12485                                0 /*is_dwp*/, 0 /*search_cwd*/);
12486
12487   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12488
12489   if (comp_dir != NULL)
12490     {
12491       gdb::unique_xmalloc_ptr<char> path_to_try
12492         (concat (comp_dir, SLASH_STRING, file_name, (char *) NULL));
12493
12494       /* NOTE: If comp_dir is a relative path, this will also try the
12495          search path, which seems useful.  */
12496       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12497                                                 path_to_try.get (),
12498                                                 0 /*is_dwp*/,
12499                                                 1 /*search_cwd*/));
12500       if (abfd != NULL)
12501         return abfd;
12502     }
12503
12504   /* That didn't work, try debug-file-directory, which, despite its name,
12505      is a list of paths.  */
12506
12507   if (*debug_file_directory == '\0')
12508     return NULL;
12509
12510   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12511                              0 /*is_dwp*/, 1 /*search_cwd*/);
12512 }
12513
12514 /* This function is mapped across the sections and remembers the offset and
12515    size of each of the DWO debugging sections we are interested in.  */
12516
12517 static void
12518 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12519 {
12520   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12521   const struct dwop_section_names *names = &dwop_section_names;
12522
12523   if (section_is_p (sectp->name, &names->abbrev_dwo))
12524     {
12525       dwo_sections->abbrev.s.section = sectp;
12526       dwo_sections->abbrev.size = bfd_section_size (sectp);
12527     }
12528   else if (section_is_p (sectp->name, &names->info_dwo))
12529     {
12530       dwo_sections->info.s.section = sectp;
12531       dwo_sections->info.size = bfd_section_size (sectp);
12532     }
12533   else if (section_is_p (sectp->name, &names->line_dwo))
12534     {
12535       dwo_sections->line.s.section = sectp;
12536       dwo_sections->line.size = bfd_section_size (sectp);
12537     }
12538   else if (section_is_p (sectp->name, &names->loc_dwo))
12539     {
12540       dwo_sections->loc.s.section = sectp;
12541       dwo_sections->loc.size = bfd_section_size (sectp);
12542     }
12543   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12544     {
12545       dwo_sections->macinfo.s.section = sectp;
12546       dwo_sections->macinfo.size = bfd_section_size (sectp);
12547     }
12548   else if (section_is_p (sectp->name, &names->macro_dwo))
12549     {
12550       dwo_sections->macro.s.section = sectp;
12551       dwo_sections->macro.size = bfd_section_size (sectp);
12552     }
12553   else if (section_is_p (sectp->name, &names->str_dwo))
12554     {
12555       dwo_sections->str.s.section = sectp;
12556       dwo_sections->str.size = bfd_section_size (sectp);
12557     }
12558   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12559     {
12560       dwo_sections->str_offsets.s.section = sectp;
12561       dwo_sections->str_offsets.size = bfd_section_size (sectp);
12562     }
12563   else if (section_is_p (sectp->name, &names->types_dwo))
12564     {
12565       struct dwarf2_section_info type_section;
12566
12567       memset (&type_section, 0, sizeof (type_section));
12568       type_section.s.section = sectp;
12569       type_section.size = bfd_section_size (sectp);
12570       dwo_sections->types.push_back (type_section);
12571     }
12572 }
12573
12574 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12575    by PER_CU.  This is for the non-DWP case.
12576    The result is NULL if DWO_NAME can't be found.  */
12577
12578 static struct dwo_file *
12579 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12580                         const char *dwo_name, const char *comp_dir)
12581 {
12582   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12583
12584   gdb_bfd_ref_ptr dbfd = open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir);
12585   if (dbfd == NULL)
12586     {
12587       if (dwarf_read_debug)
12588         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12589       return NULL;
12590     }
12591
12592   dwo_file_up dwo_file (new struct dwo_file);
12593   dwo_file->dwo_name = dwo_name;
12594   dwo_file->comp_dir = comp_dir;
12595   dwo_file->dbfd = std::move (dbfd);
12596
12597   bfd_map_over_sections (dwo_file->dbfd.get (), dwarf2_locate_dwo_sections,
12598                          &dwo_file->sections);
12599
12600   create_cus_hash_table (dwarf2_per_objfile, per_cu->cu, *dwo_file,
12601                          dwo_file->sections.info, dwo_file->cus);
12602
12603   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12604                                  dwo_file->sections.types, dwo_file->tus);
12605
12606   if (dwarf_read_debug)
12607     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12608
12609   return dwo_file.release ();
12610 }
12611
12612 /* This function is mapped across the sections and remembers the offset and
12613    size of each of the DWP debugging sections common to version 1 and 2 that
12614    we are interested in.  */
12615
12616 static void
12617 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12618                                    void *dwp_file_ptr)
12619 {
12620   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12621   const struct dwop_section_names *names = &dwop_section_names;
12622   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12623
12624   /* Record the ELF section number for later lookup: this is what the
12625      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12626   gdb_assert (elf_section_nr < dwp_file->num_sections);
12627   dwp_file->elf_sections[elf_section_nr] = sectp;
12628
12629   /* Look for specific sections that we need.  */
12630   if (section_is_p (sectp->name, &names->str_dwo))
12631     {
12632       dwp_file->sections.str.s.section = sectp;
12633       dwp_file->sections.str.size = bfd_section_size (sectp);
12634     }
12635   else if (section_is_p (sectp->name, &names->cu_index))
12636     {
12637       dwp_file->sections.cu_index.s.section = sectp;
12638       dwp_file->sections.cu_index.size = bfd_section_size (sectp);
12639     }
12640   else if (section_is_p (sectp->name, &names->tu_index))
12641     {
12642       dwp_file->sections.tu_index.s.section = sectp;
12643       dwp_file->sections.tu_index.size = bfd_section_size (sectp);
12644     }
12645 }
12646
12647 /* This function is mapped across the sections and remembers the offset and
12648    size of each of the DWP version 2 debugging sections that we are interested
12649    in.  This is split into a separate function because we don't know if we
12650    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12651
12652 static void
12653 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12654 {
12655   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12656   const struct dwop_section_names *names = &dwop_section_names;
12657   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12658
12659   /* Record the ELF section number for later lookup: this is what the
12660      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12661   gdb_assert (elf_section_nr < dwp_file->num_sections);
12662   dwp_file->elf_sections[elf_section_nr] = sectp;
12663
12664   /* Look for specific sections that we need.  */
12665   if (section_is_p (sectp->name, &names->abbrev_dwo))
12666     {
12667       dwp_file->sections.abbrev.s.section = sectp;
12668       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
12669     }
12670   else if (section_is_p (sectp->name, &names->info_dwo))
12671     {
12672       dwp_file->sections.info.s.section = sectp;
12673       dwp_file->sections.info.size = bfd_section_size (sectp);
12674     }
12675   else if (section_is_p (sectp->name, &names->line_dwo))
12676     {
12677       dwp_file->sections.line.s.section = sectp;
12678       dwp_file->sections.line.size = bfd_section_size (sectp);
12679     }
12680   else if (section_is_p (sectp->name, &names->loc_dwo))
12681     {
12682       dwp_file->sections.loc.s.section = sectp;
12683       dwp_file->sections.loc.size = bfd_section_size (sectp);
12684     }
12685   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12686     {
12687       dwp_file->sections.macinfo.s.section = sectp;
12688       dwp_file->sections.macinfo.size = bfd_section_size (sectp);
12689     }
12690   else if (section_is_p (sectp->name, &names->macro_dwo))
12691     {
12692       dwp_file->sections.macro.s.section = sectp;
12693       dwp_file->sections.macro.size = bfd_section_size (sectp);
12694     }
12695   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12696     {
12697       dwp_file->sections.str_offsets.s.section = sectp;
12698       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
12699     }
12700   else if (section_is_p (sectp->name, &names->types_dwo))
12701     {
12702       dwp_file->sections.types.s.section = sectp;
12703       dwp_file->sections.types.size = bfd_section_size (sectp);
12704     }
12705 }
12706
12707 /* Hash function for dwp_file loaded CUs/TUs.  */
12708
12709 static hashval_t
12710 hash_dwp_loaded_cutus (const void *item)
12711 {
12712   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12713
12714   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
12715   return dwo_unit->signature;
12716 }
12717
12718 /* Equality function for dwp_file loaded CUs/TUs.  */
12719
12720 static int
12721 eq_dwp_loaded_cutus (const void *a, const void *b)
12722 {
12723   const struct dwo_unit *dua = (const struct dwo_unit *) a;
12724   const struct dwo_unit *dub = (const struct dwo_unit *) b;
12725
12726   return dua->signature == dub->signature;
12727 }
12728
12729 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
12730
12731 static htab_up
12732 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
12733 {
12734   return htab_up (htab_create_alloc (3,
12735                                      hash_dwp_loaded_cutus,
12736                                      eq_dwp_loaded_cutus,
12737                                      NULL, xcalloc, xfree));
12738 }
12739
12740 /* Try to open DWP file FILE_NAME.
12741    The result is the bfd handle of the file.
12742    If there is a problem finding or opening the file, return NULL.
12743    Upon success, the canonicalized path of the file is stored in the bfd,
12744    same as symfile_bfd_open.  */
12745
12746 static gdb_bfd_ref_ptr
12747 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12748                const char *file_name)
12749 {
12750   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
12751                                             1 /*is_dwp*/,
12752                                             1 /*search_cwd*/));
12753   if (abfd != NULL)
12754     return abfd;
12755
12756   /* Work around upstream bug 15652.
12757      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
12758      [Whether that's a "bug" is debatable, but it is getting in our way.]
12759      We have no real idea where the dwp file is, because gdb's realpath-ing
12760      of the executable's path may have discarded the needed info.
12761      [IWBN if the dwp file name was recorded in the executable, akin to
12762      .gnu_debuglink, but that doesn't exist yet.]
12763      Strip the directory from FILE_NAME and search again.  */
12764   if (*debug_file_directory != '\0')
12765     {
12766       /* Don't implicitly search the current directory here.
12767          If the user wants to search "." to handle this case,
12768          it must be added to debug-file-directory.  */
12769       return try_open_dwop_file (dwarf2_per_objfile,
12770                                  lbasename (file_name), 1 /*is_dwp*/,
12771                                  0 /*search_cwd*/);
12772     }
12773
12774   return NULL;
12775 }
12776
12777 /* Initialize the use of the DWP file for the current objfile.
12778    By convention the name of the DWP file is ${objfile}.dwp.
12779    The result is NULL if it can't be found.  */
12780
12781 static std::unique_ptr<struct dwp_file>
12782 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
12783 {
12784   struct objfile *objfile = dwarf2_per_objfile->objfile;
12785
12786   /* Try to find first .dwp for the binary file before any symbolic links
12787      resolving.  */
12788
12789   /* If the objfile is a debug file, find the name of the real binary
12790      file and get the name of dwp file from there.  */
12791   std::string dwp_name;
12792   if (objfile->separate_debug_objfile_backlink != NULL)
12793     {
12794       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
12795       const char *backlink_basename = lbasename (backlink->original_name);
12796
12797       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
12798     }
12799   else
12800     dwp_name = objfile->original_name;
12801
12802   dwp_name += ".dwp";
12803
12804   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
12805   if (dbfd == NULL
12806       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
12807     {
12808       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
12809       dwp_name = objfile_name (objfile);
12810       dwp_name += ".dwp";
12811       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
12812     }
12813
12814   if (dbfd == NULL)
12815     {
12816       if (dwarf_read_debug)
12817         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
12818       return std::unique_ptr<dwp_file> ();
12819     }
12820
12821   const char *name = bfd_get_filename (dbfd.get ());
12822   std::unique_ptr<struct dwp_file> dwp_file
12823     (new struct dwp_file (name, std::move (dbfd)));
12824
12825   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
12826   dwp_file->elf_sections =
12827     OBSTACK_CALLOC (&objfile->objfile_obstack,
12828                     dwp_file->num_sections, asection *);
12829
12830   bfd_map_over_sections (dwp_file->dbfd.get (),
12831                          dwarf2_locate_common_dwp_sections,
12832                          dwp_file.get ());
12833
12834   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
12835                                          0);
12836
12837   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
12838                                          1);
12839
12840   /* The DWP file version is stored in the hash table.  Oh well.  */
12841   if (dwp_file->cus && dwp_file->tus
12842       && dwp_file->cus->version != dwp_file->tus->version)
12843     {
12844       /* Technically speaking, we should try to limp along, but this is
12845          pretty bizarre.  We use pulongest here because that's the established
12846          portability solution (e.g, we cannot use %u for uint32_t).  */
12847       error (_("Dwarf Error: DWP file CU version %s doesn't match"
12848                " TU version %s [in DWP file %s]"),
12849              pulongest (dwp_file->cus->version),
12850              pulongest (dwp_file->tus->version), dwp_name.c_str ());
12851     }
12852
12853   if (dwp_file->cus)
12854     dwp_file->version = dwp_file->cus->version;
12855   else if (dwp_file->tus)
12856     dwp_file->version = dwp_file->tus->version;
12857   else
12858     dwp_file->version = 2;
12859
12860   if (dwp_file->version == 2)
12861     bfd_map_over_sections (dwp_file->dbfd.get (),
12862                            dwarf2_locate_v2_dwp_sections,
12863                            dwp_file.get ());
12864
12865   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
12866   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
12867
12868   if (dwarf_read_debug)
12869     {
12870       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
12871       fprintf_unfiltered (gdb_stdlog,
12872                           "    %s CUs, %s TUs\n",
12873                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
12874                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
12875     }
12876
12877   return dwp_file;
12878 }
12879
12880 /* Wrapper around open_and_init_dwp_file, only open it once.  */
12881
12882 static struct dwp_file *
12883 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
12884 {
12885   if (! dwarf2_per_objfile->dwp_checked)
12886     {
12887       dwarf2_per_objfile->dwp_file
12888         = open_and_init_dwp_file (dwarf2_per_objfile);
12889       dwarf2_per_objfile->dwp_checked = 1;
12890     }
12891   return dwarf2_per_objfile->dwp_file.get ();
12892 }
12893
12894 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
12895    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
12896    or in the DWP file for the objfile, referenced by THIS_UNIT.
12897    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
12898    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
12899
12900    This is called, for example, when wanting to read a variable with a
12901    complex location.  Therefore we don't want to do file i/o for every call.
12902    Therefore we don't want to look for a DWO file on every call.
12903    Therefore we first see if we've already seen SIGNATURE in a DWP file,
12904    then we check if we've already seen DWO_NAME, and only THEN do we check
12905    for a DWO file.
12906
12907    The result is a pointer to the dwo_unit object or NULL if we didn't find it
12908    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
12909
12910 static struct dwo_unit *
12911 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
12912                  const char *dwo_name, const char *comp_dir,
12913                  ULONGEST signature, int is_debug_types)
12914 {
12915   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
12916   struct objfile *objfile = dwarf2_per_objfile->objfile;
12917   const char *kind = is_debug_types ? "TU" : "CU";
12918   void **dwo_file_slot;
12919   struct dwo_file *dwo_file;
12920   struct dwp_file *dwp_file;
12921
12922   /* First see if there's a DWP file.
12923      If we have a DWP file but didn't find the DWO inside it, don't
12924      look for the original DWO file.  It makes gdb behave differently
12925      depending on whether one is debugging in the build tree.  */
12926
12927   dwp_file = get_dwp_file (dwarf2_per_objfile);
12928   if (dwp_file != NULL)
12929     {
12930       const struct dwp_hash_table *dwp_htab =
12931         is_debug_types ? dwp_file->tus : dwp_file->cus;
12932
12933       if (dwp_htab != NULL)
12934         {
12935           struct dwo_unit *dwo_cutu =
12936             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
12937                                     signature, is_debug_types);
12938
12939           if (dwo_cutu != NULL)
12940             {
12941               if (dwarf_read_debug)
12942                 {
12943                   fprintf_unfiltered (gdb_stdlog,
12944                                       "Virtual DWO %s %s found: @%s\n",
12945                                       kind, hex_string (signature),
12946                                       host_address_to_string (dwo_cutu));
12947                 }
12948               return dwo_cutu;
12949             }
12950         }
12951     }
12952   else
12953     {
12954       /* No DWP file, look for the DWO file.  */
12955
12956       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12957                                             dwo_name, comp_dir);
12958       if (*dwo_file_slot == NULL)
12959         {
12960           /* Read in the file and build a table of the CUs/TUs it contains.  */
12961           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
12962         }
12963       /* NOTE: This will be NULL if unable to open the file.  */
12964       dwo_file = (struct dwo_file *) *dwo_file_slot;
12965
12966       if (dwo_file != NULL)
12967         {
12968           struct dwo_unit *dwo_cutu = NULL;
12969
12970           if (is_debug_types && dwo_file->tus)
12971             {
12972               struct dwo_unit find_dwo_cutu;
12973
12974               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12975               find_dwo_cutu.signature = signature;
12976               dwo_cutu
12977                 = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
12978                                                  &find_dwo_cutu);
12979             }
12980           else if (!is_debug_types && dwo_file->cus)
12981             {
12982               struct dwo_unit find_dwo_cutu;
12983
12984               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12985               find_dwo_cutu.signature = signature;
12986               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus.get (),
12987                                                        &find_dwo_cutu);
12988             }
12989
12990           if (dwo_cutu != NULL)
12991             {
12992               if (dwarf_read_debug)
12993                 {
12994                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
12995                                       kind, dwo_name, hex_string (signature),
12996                                       host_address_to_string (dwo_cutu));
12997                 }
12998               return dwo_cutu;
12999             }
13000         }
13001     }
13002
13003   /* We didn't find it.  This could mean a dwo_id mismatch, or
13004      someone deleted the DWO/DWP file, or the search path isn't set up
13005      correctly to find the file.  */
13006
13007   if (dwarf_read_debug)
13008     {
13009       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13010                           kind, dwo_name, hex_string (signature));
13011     }
13012
13013   /* This is a warning and not a complaint because it can be caused by
13014      pilot error (e.g., user accidentally deleting the DWO).  */
13015   {
13016     /* Print the name of the DWP file if we looked there, helps the user
13017        better diagnose the problem.  */
13018     std::string dwp_text;
13019
13020     if (dwp_file != NULL)
13021       dwp_text = string_printf (" [in DWP file %s]",
13022                                 lbasename (dwp_file->name));
13023
13024     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13025                " [in module %s]"),
13026              kind, dwo_name, hex_string (signature),
13027              dwp_text.c_str (),
13028              this_unit->is_debug_types ? "TU" : "CU",
13029              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13030   }
13031   return NULL;
13032 }
13033
13034 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13035    See lookup_dwo_cutu_unit for details.  */
13036
13037 static struct dwo_unit *
13038 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13039                       const char *dwo_name, const char *comp_dir,
13040                       ULONGEST signature)
13041 {
13042   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13043 }
13044
13045 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13046    See lookup_dwo_cutu_unit for details.  */
13047
13048 static struct dwo_unit *
13049 lookup_dwo_type_unit (struct signatured_type *this_tu,
13050                       const char *dwo_name, const char *comp_dir)
13051 {
13052   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13053 }
13054
13055 /* Traversal function for queue_and_load_all_dwo_tus.  */
13056
13057 static int
13058 queue_and_load_dwo_tu (void **slot, void *info)
13059 {
13060   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13061   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13062   ULONGEST signature = dwo_unit->signature;
13063   struct signatured_type *sig_type =
13064     lookup_dwo_signatured_type (per_cu->cu, signature);
13065
13066   if (sig_type != NULL)
13067     {
13068       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13069
13070       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13071          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13072          while processing PER_CU.  */
13073       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13074         load_full_type_unit (sig_cu);
13075       per_cu->imported_symtabs_push (sig_cu);
13076     }
13077
13078   return 1;
13079 }
13080
13081 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13082    The DWO may have the only definition of the type, though it may not be
13083    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13084    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13085
13086 static void
13087 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13088 {
13089   struct dwo_unit *dwo_unit;
13090   struct dwo_file *dwo_file;
13091
13092   gdb_assert (!per_cu->is_debug_types);
13093   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13094   gdb_assert (per_cu->cu != NULL);
13095
13096   dwo_unit = per_cu->cu->dwo_unit;
13097   gdb_assert (dwo_unit != NULL);
13098
13099   dwo_file = dwo_unit->dwo_file;
13100   if (dwo_file->tus != NULL)
13101     htab_traverse_noresize (dwo_file->tus.get (), queue_and_load_dwo_tu,
13102                             per_cu);
13103 }
13104
13105 /* Read in various DIEs.  */
13106
13107 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13108    Inherit only the children of the DW_AT_abstract_origin DIE not being
13109    already referenced by DW_AT_abstract_origin from the children of the
13110    current DIE.  */
13111
13112 static void
13113 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13114 {
13115   struct die_info *child_die;
13116   sect_offset *offsetp;
13117   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13118   struct die_info *origin_die;
13119   /* Iterator of the ORIGIN_DIE children.  */
13120   struct die_info *origin_child_die;
13121   struct attribute *attr;
13122   struct dwarf2_cu *origin_cu;
13123   struct pending **origin_previous_list_in_scope;
13124
13125   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13126   if (!attr)
13127     return;
13128
13129   /* Note that following die references may follow to a die in a
13130      different cu.  */
13131
13132   origin_cu = cu;
13133   origin_die = follow_die_ref (die, attr, &origin_cu);
13134
13135   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13136      symbols in.  */
13137   origin_previous_list_in_scope = origin_cu->list_in_scope;
13138   origin_cu->list_in_scope = cu->list_in_scope;
13139
13140   if (die->tag != origin_die->tag
13141       && !(die->tag == DW_TAG_inlined_subroutine
13142            && origin_die->tag == DW_TAG_subprogram))
13143     complaint (_("DIE %s and its abstract origin %s have different tags"),
13144                sect_offset_str (die->sect_off),
13145                sect_offset_str (origin_die->sect_off));
13146
13147   std::vector<sect_offset> offsets;
13148
13149   for (child_die = die->child;
13150        child_die && child_die->tag;
13151        child_die = sibling_die (child_die))
13152     {
13153       struct die_info *child_origin_die;
13154       struct dwarf2_cu *child_origin_cu;
13155
13156       /* We are trying to process concrete instance entries:
13157          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13158          it's not relevant to our analysis here. i.e. detecting DIEs that are
13159          present in the abstract instance but not referenced in the concrete
13160          one.  */
13161       if (child_die->tag == DW_TAG_call_site
13162           || child_die->tag == DW_TAG_GNU_call_site)
13163         continue;
13164
13165       /* For each CHILD_DIE, find the corresponding child of
13166          ORIGIN_DIE.  If there is more than one layer of
13167          DW_AT_abstract_origin, follow them all; there shouldn't be,
13168          but GCC versions at least through 4.4 generate this (GCC PR
13169          40573).  */
13170       child_origin_die = child_die;
13171       child_origin_cu = cu;
13172       while (1)
13173         {
13174           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13175                               child_origin_cu);
13176           if (attr == NULL)
13177             break;
13178           child_origin_die = follow_die_ref (child_origin_die, attr,
13179                                              &child_origin_cu);
13180         }
13181
13182       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13183          counterpart may exist.  */
13184       if (child_origin_die != child_die)
13185         {
13186           if (child_die->tag != child_origin_die->tag
13187               && !(child_die->tag == DW_TAG_inlined_subroutine
13188                    && child_origin_die->tag == DW_TAG_subprogram))
13189             complaint (_("Child DIE %s and its abstract origin %s have "
13190                          "different tags"),
13191                        sect_offset_str (child_die->sect_off),
13192                        sect_offset_str (child_origin_die->sect_off));
13193           if (child_origin_die->parent != origin_die)
13194             complaint (_("Child DIE %s and its abstract origin %s have "
13195                          "different parents"),
13196                        sect_offset_str (child_die->sect_off),
13197                        sect_offset_str (child_origin_die->sect_off));
13198           else
13199             offsets.push_back (child_origin_die->sect_off);
13200         }
13201     }
13202   std::sort (offsets.begin (), offsets.end ());
13203   sect_offset *offsets_end = offsets.data () + offsets.size ();
13204   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13205     if (offsetp[-1] == *offsetp)
13206       complaint (_("Multiple children of DIE %s refer "
13207                    "to DIE %s as their abstract origin"),
13208                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13209
13210   offsetp = offsets.data ();
13211   origin_child_die = origin_die->child;
13212   while (origin_child_die && origin_child_die->tag)
13213     {
13214       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13215       while (offsetp < offsets_end
13216              && *offsetp < origin_child_die->sect_off)
13217         offsetp++;
13218       if (offsetp >= offsets_end
13219           || *offsetp > origin_child_die->sect_off)
13220         {
13221           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13222              Check whether we're already processing ORIGIN_CHILD_DIE.
13223              This can happen with mutually referenced abstract_origins.
13224              PR 16581.  */
13225           if (!origin_child_die->in_process)
13226             process_die (origin_child_die, origin_cu);
13227         }
13228       origin_child_die = sibling_die (origin_child_die);
13229     }
13230   origin_cu->list_in_scope = origin_previous_list_in_scope;
13231
13232   if (cu != origin_cu)
13233     compute_delayed_physnames (origin_cu);
13234 }
13235
13236 static void
13237 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13238 {
13239   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13240   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13241   struct context_stack *newobj;
13242   CORE_ADDR lowpc;
13243   CORE_ADDR highpc;
13244   struct die_info *child_die;
13245   struct attribute *attr, *call_line, *call_file;
13246   const char *name;
13247   CORE_ADDR baseaddr;
13248   struct block *block;
13249   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13250   std::vector<struct symbol *> template_args;
13251   struct template_symbol *templ_func = NULL;
13252
13253   if (inlined_func)
13254     {
13255       /* If we do not have call site information, we can't show the
13256          caller of this inlined function.  That's too confusing, so
13257          only use the scope for local variables.  */
13258       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13259       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13260       if (call_line == NULL || call_file == NULL)
13261         {
13262           read_lexical_block_scope (die, cu);
13263           return;
13264         }
13265     }
13266
13267   baseaddr = objfile->text_section_offset ();
13268
13269   name = dwarf2_name (die, cu);
13270
13271   /* Ignore functions with missing or empty names.  These are actually
13272      illegal according to the DWARF standard.  */
13273   if (name == NULL)
13274     {
13275       complaint (_("missing name for subprogram DIE at %s"),
13276                  sect_offset_str (die->sect_off));
13277       return;
13278     }
13279
13280   /* Ignore functions with missing or invalid low and high pc attributes.  */
13281   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13282       <= PC_BOUNDS_INVALID)
13283     {
13284       attr = dwarf2_attr (die, DW_AT_external, cu);
13285       if (!attr || !DW_UNSND (attr))
13286         complaint (_("cannot get low and high bounds "
13287                      "for subprogram DIE at %s"),
13288                    sect_offset_str (die->sect_off));
13289       return;
13290     }
13291
13292   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13293   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13294
13295   /* If we have any template arguments, then we must allocate a
13296      different sort of symbol.  */
13297   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13298     {
13299       if (child_die->tag == DW_TAG_template_type_param
13300           || child_die->tag == DW_TAG_template_value_param)
13301         {
13302           templ_func = allocate_template_symbol (objfile);
13303           templ_func->subclass = SYMBOL_TEMPLATE;
13304           break;
13305         }
13306     }
13307
13308   newobj = cu->get_builder ()->push_context (0, lowpc);
13309   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13310                              (struct symbol *) templ_func);
13311
13312   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
13313     set_objfile_main_name (objfile, newobj->name->linkage_name (),
13314                            cu->language);
13315
13316   /* If there is a location expression for DW_AT_frame_base, record
13317      it.  */
13318   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13319   if (attr != nullptr)
13320     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13321
13322   /* If there is a location for the static link, record it.  */
13323   newobj->static_link = NULL;
13324   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13325   if (attr != nullptr)
13326     {
13327       newobj->static_link
13328         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13329       attr_to_dynamic_prop (attr, die, cu, newobj->static_link,
13330                             dwarf2_per_cu_addr_type (cu->per_cu));
13331     }
13332
13333   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13334
13335   if (die->child != NULL)
13336     {
13337       child_die = die->child;
13338       while (child_die && child_die->tag)
13339         {
13340           if (child_die->tag == DW_TAG_template_type_param
13341               || child_die->tag == DW_TAG_template_value_param)
13342             {
13343               struct symbol *arg = new_symbol (child_die, NULL, cu);
13344
13345               if (arg != NULL)
13346                 template_args.push_back (arg);
13347             }
13348           else
13349             process_die (child_die, cu);
13350           child_die = sibling_die (child_die);
13351         }
13352     }
13353
13354   inherit_abstract_dies (die, cu);
13355
13356   /* If we have a DW_AT_specification, we might need to import using
13357      directives from the context of the specification DIE.  See the
13358      comment in determine_prefix.  */
13359   if (cu->language == language_cplus
13360       && dwarf2_attr (die, DW_AT_specification, cu))
13361     {
13362       struct dwarf2_cu *spec_cu = cu;
13363       struct die_info *spec_die = die_specification (die, &spec_cu);
13364
13365       while (spec_die)
13366         {
13367           child_die = spec_die->child;
13368           while (child_die && child_die->tag)
13369             {
13370               if (child_die->tag == DW_TAG_imported_module)
13371                 process_die (child_die, spec_cu);
13372               child_die = sibling_die (child_die);
13373             }
13374
13375           /* In some cases, GCC generates specification DIEs that
13376              themselves contain DW_AT_specification attributes.  */
13377           spec_die = die_specification (spec_die, &spec_cu);
13378         }
13379     }
13380
13381   struct context_stack cstk = cu->get_builder ()->pop_context ();
13382   /* Make a block for the local symbols within.  */
13383   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13384                                      cstk.static_link, lowpc, highpc);
13385
13386   /* For C++, set the block's scope.  */
13387   if ((cu->language == language_cplus
13388        || cu->language == language_fortran
13389        || cu->language == language_d
13390        || cu->language == language_rust)
13391       && cu->processing_has_namespace_info)
13392     block_set_scope (block, determine_prefix (die, cu),
13393                      &objfile->objfile_obstack);
13394
13395   /* If we have address ranges, record them.  */
13396   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13397
13398   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13399
13400   /* Attach template arguments to function.  */
13401   if (!template_args.empty ())
13402     {
13403       gdb_assert (templ_func != NULL);
13404
13405       templ_func->n_template_arguments = template_args.size ();
13406       templ_func->template_arguments
13407         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13408                      templ_func->n_template_arguments);
13409       memcpy (templ_func->template_arguments,
13410               template_args.data (),
13411               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13412
13413       /* Make sure that the symtab is set on the new symbols.  Even
13414          though they don't appear in this symtab directly, other parts
13415          of gdb assume that symbols do, and this is reasonably
13416          true.  */
13417       for (symbol *sym : template_args)
13418         symbol_set_symtab (sym, symbol_symtab (templ_func));
13419     }
13420
13421   /* In C++, we can have functions nested inside functions (e.g., when
13422      a function declares a class that has methods).  This means that
13423      when we finish processing a function scope, we may need to go
13424      back to building a containing block's symbol lists.  */
13425   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13426   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13427
13428   /* If we've finished processing a top-level function, subsequent
13429      symbols go in the file symbol list.  */
13430   if (cu->get_builder ()->outermost_context_p ())
13431     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13432 }
13433
13434 /* Process all the DIES contained within a lexical block scope.  Start
13435    a new scope, process the dies, and then close the scope.  */
13436
13437 static void
13438 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13439 {
13440   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13441   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13442   CORE_ADDR lowpc, highpc;
13443   struct die_info *child_die;
13444   CORE_ADDR baseaddr;
13445
13446   baseaddr = objfile->text_section_offset ();
13447
13448   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13449   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13450      as multiple lexical blocks?  Handling children in a sane way would
13451      be nasty.  Might be easier to properly extend generic blocks to
13452      describe ranges.  */
13453   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13454     {
13455     case PC_BOUNDS_NOT_PRESENT:
13456       /* DW_TAG_lexical_block has no attributes, process its children as if
13457          there was no wrapping by that DW_TAG_lexical_block.
13458          GCC does no longer produces such DWARF since GCC r224161.  */
13459       for (child_die = die->child;
13460            child_die != NULL && child_die->tag;
13461            child_die = sibling_die (child_die))
13462         process_die (child_die, cu);
13463       return;
13464     case PC_BOUNDS_INVALID:
13465       return;
13466     }
13467   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13468   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13469
13470   cu->get_builder ()->push_context (0, lowpc);
13471   if (die->child != NULL)
13472     {
13473       child_die = die->child;
13474       while (child_die && child_die->tag)
13475         {
13476           process_die (child_die, cu);
13477           child_die = sibling_die (child_die);
13478         }
13479     }
13480   inherit_abstract_dies (die, cu);
13481   struct context_stack cstk = cu->get_builder ()->pop_context ();
13482
13483   if (*cu->get_builder ()->get_local_symbols () != NULL
13484       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13485     {
13486       struct block *block
13487         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13488                                      cstk.start_addr, highpc);
13489
13490       /* Note that recording ranges after traversing children, as we
13491          do here, means that recording a parent's ranges entails
13492          walking across all its children's ranges as they appear in
13493          the address map, which is quadratic behavior.
13494
13495          It would be nicer to record the parent's ranges before
13496          traversing its children, simply overriding whatever you find
13497          there.  But since we don't even decide whether to create a
13498          block until after we've traversed its children, that's hard
13499          to do.  */
13500       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13501     }
13502   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13503   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13504 }
13505
13506 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13507
13508 static void
13509 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13510 {
13511   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13512   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13513   CORE_ADDR pc, baseaddr;
13514   struct attribute *attr;
13515   struct call_site *call_site, call_site_local;
13516   void **slot;
13517   int nparams;
13518   struct die_info *child_die;
13519
13520   baseaddr = objfile->text_section_offset ();
13521
13522   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13523   if (attr == NULL)
13524     {
13525       /* This was a pre-DWARF-5 GNU extension alias
13526          for DW_AT_call_return_pc.  */
13527       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13528     }
13529   if (!attr)
13530     {
13531       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13532                    "DIE %s [in module %s]"),
13533                  sect_offset_str (die->sect_off), objfile_name (objfile));
13534       return;
13535     }
13536   pc = attr->value_as_address () + baseaddr;
13537   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13538
13539   if (cu->call_site_htab == NULL)
13540     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13541                                                NULL, &objfile->objfile_obstack,
13542                                                hashtab_obstack_allocate, NULL);
13543   call_site_local.pc = pc;
13544   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13545   if (*slot != NULL)
13546     {
13547       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13548                    "DIE %s [in module %s]"),
13549                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13550                  objfile_name (objfile));
13551       return;
13552     }
13553
13554   /* Count parameters at the caller.  */
13555
13556   nparams = 0;
13557   for (child_die = die->child; child_die && child_die->tag;
13558        child_die = sibling_die (child_die))
13559     {
13560       if (child_die->tag != DW_TAG_call_site_parameter
13561           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13562         {
13563           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13564                        "DW_TAG_call_site child DIE %s [in module %s]"),
13565                      child_die->tag, sect_offset_str (child_die->sect_off),
13566                      objfile_name (objfile));
13567           continue;
13568         }
13569
13570       nparams++;
13571     }
13572
13573   call_site
13574     = ((struct call_site *)
13575        obstack_alloc (&objfile->objfile_obstack,
13576                       sizeof (*call_site)
13577                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13578   *slot = call_site;
13579   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13580   call_site->pc = pc;
13581
13582   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13583       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13584     {
13585       struct die_info *func_die;
13586
13587       /* Skip also over DW_TAG_inlined_subroutine.  */
13588       for (func_die = die->parent;
13589            func_die && func_die->tag != DW_TAG_subprogram
13590            && func_die->tag != DW_TAG_subroutine_type;
13591            func_die = func_die->parent);
13592
13593       /* DW_AT_call_all_calls is a superset
13594          of DW_AT_call_all_tail_calls.  */
13595       if (func_die
13596           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13597           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13598           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13599           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13600         {
13601           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13602              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13603              both the initial caller containing the real return address PC and
13604              the final callee containing the current PC of a chain of tail
13605              calls do not need to have the tail call list complete.  But any
13606              function candidate for a virtual tail call frame searched via
13607              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13608              determined unambiguously.  */
13609         }
13610       else
13611         {
13612           struct type *func_type = NULL;
13613
13614           if (func_die)
13615             func_type = get_die_type (func_die, cu);
13616           if (func_type != NULL)
13617             {
13618               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13619
13620               /* Enlist this call site to the function.  */
13621               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13622               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13623             }
13624           else
13625             complaint (_("Cannot find function owning DW_TAG_call_site "
13626                          "DIE %s [in module %s]"),
13627                        sect_offset_str (die->sect_off), objfile_name (objfile));
13628         }
13629     }
13630
13631   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13632   if (attr == NULL)
13633     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13634   if (attr == NULL)
13635     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13636   if (attr == NULL)
13637     {
13638       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13639       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13640     }
13641   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13642   if (!attr || (attr->form_is_block () && DW_BLOCK (attr)->size == 0))
13643     /* Keep NULL DWARF_BLOCK.  */;
13644   else if (attr->form_is_block ())
13645     {
13646       struct dwarf2_locexpr_baton *dlbaton;
13647
13648       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13649       dlbaton->data = DW_BLOCK (attr)->data;
13650       dlbaton->size = DW_BLOCK (attr)->size;
13651       dlbaton->per_cu = cu->per_cu;
13652
13653       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13654     }
13655   else if (attr->form_is_ref ())
13656     {
13657       struct dwarf2_cu *target_cu = cu;
13658       struct die_info *target_die;
13659
13660       target_die = follow_die_ref (die, attr, &target_cu);
13661       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13662       if (die_is_declaration (target_die, target_cu))
13663         {
13664           const char *target_physname;
13665
13666           /* Prefer the mangled name; otherwise compute the demangled one.  */
13667           target_physname = dw2_linkage_name (target_die, target_cu);
13668           if (target_physname == NULL)
13669             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13670           if (target_physname == NULL)
13671             complaint (_("DW_AT_call_target target DIE has invalid "
13672                          "physname, for referencing DIE %s [in module %s]"),
13673                        sect_offset_str (die->sect_off), objfile_name (objfile));
13674           else
13675             SET_FIELD_PHYSNAME (call_site->target, target_physname);
13676         }
13677       else
13678         {
13679           CORE_ADDR lowpc;
13680
13681           /* DW_AT_entry_pc should be preferred.  */
13682           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13683               <= PC_BOUNDS_INVALID)
13684             complaint (_("DW_AT_call_target target DIE has invalid "
13685                          "low pc, for referencing DIE %s [in module %s]"),
13686                        sect_offset_str (die->sect_off), objfile_name (objfile));
13687           else
13688             {
13689               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13690               SET_FIELD_PHYSADDR (call_site->target, lowpc);
13691             }
13692         }
13693     }
13694   else
13695     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
13696                  "block nor reference, for DIE %s [in module %s]"),
13697                sect_offset_str (die->sect_off), objfile_name (objfile));
13698
13699   call_site->per_cu = cu->per_cu;
13700
13701   for (child_die = die->child;
13702        child_die && child_die->tag;
13703        child_die = sibling_die (child_die))
13704     {
13705       struct call_site_parameter *parameter;
13706       struct attribute *loc, *origin;
13707
13708       if (child_die->tag != DW_TAG_call_site_parameter
13709           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13710         {
13711           /* Already printed the complaint above.  */
13712           continue;
13713         }
13714
13715       gdb_assert (call_site->parameter_count < nparams);
13716       parameter = &call_site->parameter[call_site->parameter_count];
13717
13718       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
13719          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
13720          register is contained in DW_AT_call_value.  */
13721
13722       loc = dwarf2_attr (child_die, DW_AT_location, cu);
13723       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
13724       if (origin == NULL)
13725         {
13726           /* This was a pre-DWARF-5 GNU extension alias
13727              for DW_AT_call_parameter.  */
13728           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
13729         }
13730       if (loc == NULL && origin != NULL && origin->form_is_ref ())
13731         {
13732           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
13733
13734           sect_offset sect_off
13735             = (sect_offset) dwarf2_get_ref_die_offset (origin);
13736           if (!offset_in_cu_p (&cu->header, sect_off))
13737             {
13738               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
13739                  binding can be done only inside one CU.  Such referenced DIE
13740                  therefore cannot be even moved to DW_TAG_partial_unit.  */
13741               complaint (_("DW_AT_call_parameter offset is not in CU for "
13742                            "DW_TAG_call_site child DIE %s [in module %s]"),
13743                          sect_offset_str (child_die->sect_off),
13744                          objfile_name (objfile));
13745               continue;
13746             }
13747           parameter->u.param_cu_off
13748             = (cu_offset) (sect_off - cu->header.sect_off);
13749         }
13750       else if (loc == NULL || origin != NULL || !loc->form_is_block ())
13751         {
13752           complaint (_("No DW_FORM_block* DW_AT_location for "
13753                        "DW_TAG_call_site child DIE %s [in module %s]"),
13754                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
13755           continue;
13756         }
13757       else
13758         {
13759           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
13760             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
13761           if (parameter->u.dwarf_reg != -1)
13762             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
13763           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
13764                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
13765                                              &parameter->u.fb_offset))
13766             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
13767           else
13768             {
13769               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
13770                            "for DW_FORM_block* DW_AT_location is supported for "
13771                            "DW_TAG_call_site child DIE %s "
13772                            "[in module %s]"),
13773                          sect_offset_str (child_die->sect_off),
13774                          objfile_name (objfile));
13775               continue;
13776             }
13777         }
13778
13779       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
13780       if (attr == NULL)
13781         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
13782       if (attr == NULL || !attr->form_is_block ())
13783         {
13784           complaint (_("No DW_FORM_block* DW_AT_call_value for "
13785                        "DW_TAG_call_site child DIE %s [in module %s]"),
13786                      sect_offset_str (child_die->sect_off),
13787                      objfile_name (objfile));
13788           continue;
13789         }
13790       parameter->value = DW_BLOCK (attr)->data;
13791       parameter->value_size = DW_BLOCK (attr)->size;
13792
13793       /* Parameters are not pre-cleared by memset above.  */
13794       parameter->data_value = NULL;
13795       parameter->data_value_size = 0;
13796       call_site->parameter_count++;
13797
13798       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
13799       if (attr == NULL)
13800         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
13801       if (attr != nullptr)
13802         {
13803           if (!attr->form_is_block ())
13804             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
13805                          "DW_TAG_call_site child DIE %s [in module %s]"),
13806                        sect_offset_str (child_die->sect_off),
13807                        objfile_name (objfile));
13808           else
13809             {
13810               parameter->data_value = DW_BLOCK (attr)->data;
13811               parameter->data_value_size = DW_BLOCK (attr)->size;
13812             }
13813         }
13814     }
13815 }
13816
13817 /* Helper function for read_variable.  If DIE represents a virtual
13818    table, then return the type of the concrete object that is
13819    associated with the virtual table.  Otherwise, return NULL.  */
13820
13821 static struct type *
13822 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13823 {
13824   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
13825   if (attr == NULL)
13826     return NULL;
13827
13828   /* Find the type DIE.  */
13829   struct die_info *type_die = NULL;
13830   struct dwarf2_cu *type_cu = cu;
13831
13832   if (attr->form_is_ref ())
13833     type_die = follow_die_ref (die, attr, &type_cu);
13834   if (type_die == NULL)
13835     return NULL;
13836
13837   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
13838     return NULL;
13839   return die_containing_type (type_die, type_cu);
13840 }
13841
13842 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
13843
13844 static void
13845 read_variable (struct die_info *die, struct dwarf2_cu *cu)
13846 {
13847   struct rust_vtable_symbol *storage = NULL;
13848
13849   if (cu->language == language_rust)
13850     {
13851       struct type *containing_type = rust_containing_type (die, cu);
13852
13853       if (containing_type != NULL)
13854         {
13855           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13856
13857           storage = new (&objfile->objfile_obstack) rust_vtable_symbol ();
13858           initialize_objfile_symbol (storage);
13859           storage->concrete_type = containing_type;
13860           storage->subclass = SYMBOL_RUST_VTABLE;
13861         }
13862     }
13863
13864   struct symbol *res = new_symbol (die, NULL, cu, storage);
13865   struct attribute *abstract_origin
13866     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13867   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
13868   if (res == NULL && loc && abstract_origin)
13869     {
13870       /* We have a variable without a name, but with a location and an abstract
13871          origin.  This may be a concrete instance of an abstract variable
13872          referenced from an DW_OP_GNU_variable_value, so save it to find it back
13873          later.  */
13874       struct dwarf2_cu *origin_cu = cu;
13875       struct die_info *origin_die
13876         = follow_die_ref (die, abstract_origin, &origin_cu);
13877       dwarf2_per_objfile *dpo = cu->per_cu->dwarf2_per_objfile;
13878       dpo->abstract_to_concrete[origin_die->sect_off].push_back (die->sect_off);
13879     }
13880 }
13881
13882 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
13883    reading .debug_rnglists.
13884    Callback's type should be:
13885     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13886    Return true if the attributes are present and valid, otherwise,
13887    return false.  */
13888
13889 template <typename Callback>
13890 static bool
13891 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
13892                          Callback &&callback)
13893 {
13894   struct dwarf2_per_objfile *dwarf2_per_objfile
13895     = cu->per_cu->dwarf2_per_objfile;
13896   struct objfile *objfile = dwarf2_per_objfile->objfile;
13897   bfd *obfd = objfile->obfd;
13898   /* Base address selection entry.  */
13899   CORE_ADDR base;
13900   int found_base;
13901   const gdb_byte *buffer;
13902   CORE_ADDR baseaddr;
13903   bool overflow = false;
13904
13905   found_base = cu->base_known;
13906   base = cu->base_address;
13907
13908   dwarf2_per_objfile->rnglists.read (objfile);
13909   if (offset >= dwarf2_per_objfile->rnglists.size)
13910     {
13911       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
13912                  offset);
13913       return false;
13914     }
13915   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
13916
13917   baseaddr = objfile->text_section_offset ();
13918
13919   while (1)
13920     {
13921       /* Initialize it due to a false compiler warning.  */
13922       CORE_ADDR range_beginning = 0, range_end = 0;
13923       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
13924                                  + dwarf2_per_objfile->rnglists.size);
13925       unsigned int bytes_read;
13926
13927       if (buffer == buf_end)
13928         {
13929           overflow = true;
13930           break;
13931         }
13932       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
13933       switch (rlet)
13934         {
13935         case DW_RLE_end_of_list:
13936           break;
13937         case DW_RLE_base_address:
13938           if (buffer + cu->header.addr_size > buf_end)
13939             {
13940               overflow = true;
13941               break;
13942             }
13943           base = read_address (obfd, buffer, cu, &bytes_read);
13944           found_base = 1;
13945           buffer += bytes_read;
13946           break;
13947         case DW_RLE_start_length:
13948           if (buffer + cu->header.addr_size > buf_end)
13949             {
13950               overflow = true;
13951               break;
13952             }
13953           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13954           buffer += bytes_read;
13955           range_end = (range_beginning
13956                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13957           buffer += bytes_read;
13958           if (buffer > buf_end)
13959             {
13960               overflow = true;
13961               break;
13962             }
13963           break;
13964         case DW_RLE_offset_pair:
13965           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13966           buffer += bytes_read;
13967           if (buffer > buf_end)
13968             {
13969               overflow = true;
13970               break;
13971             }
13972           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13973           buffer += bytes_read;
13974           if (buffer > buf_end)
13975             {
13976               overflow = true;
13977               break;
13978             }
13979           break;
13980         case DW_RLE_start_end:
13981           if (buffer + 2 * cu->header.addr_size > buf_end)
13982             {
13983               overflow = true;
13984               break;
13985             }
13986           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13987           buffer += bytes_read;
13988           range_end = read_address (obfd, buffer, cu, &bytes_read);
13989           buffer += bytes_read;
13990           break;
13991         default:
13992           complaint (_("Invalid .debug_rnglists data (no base address)"));
13993           return false;
13994         }
13995       if (rlet == DW_RLE_end_of_list || overflow)
13996         break;
13997       if (rlet == DW_RLE_base_address)
13998         continue;
13999
14000       if (!found_base)
14001         {
14002           /* We have no valid base address for the ranges
14003              data.  */
14004           complaint (_("Invalid .debug_rnglists data (no base address)"));
14005           return false;
14006         }
14007
14008       if (range_beginning > range_end)
14009         {
14010           /* Inverted range entries are invalid.  */
14011           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14012           return false;
14013         }
14014
14015       /* Empty range entries have no effect.  */
14016       if (range_beginning == range_end)
14017         continue;
14018
14019       range_beginning += base;
14020       range_end += base;
14021
14022       /* A not-uncommon case of bad debug info.
14023          Don't pollute the addrmap with bad data.  */
14024       if (range_beginning + baseaddr == 0
14025           && !dwarf2_per_objfile->has_section_at_zero)
14026         {
14027           complaint (_(".debug_rnglists entry has start address of zero"
14028                        " [in module %s]"), objfile_name (objfile));
14029           continue;
14030         }
14031
14032       callback (range_beginning, range_end);
14033     }
14034
14035   if (overflow)
14036     {
14037       complaint (_("Offset %d is not terminated "
14038                    "for DW_AT_ranges attribute"),
14039                  offset);
14040       return false;
14041     }
14042
14043   return true;
14044 }
14045
14046 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14047    Callback's type should be:
14048     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14049    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14050
14051 template <typename Callback>
14052 static int
14053 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14054                        Callback &&callback)
14055 {
14056   struct dwarf2_per_objfile *dwarf2_per_objfile
14057       = cu->per_cu->dwarf2_per_objfile;
14058   struct objfile *objfile = dwarf2_per_objfile->objfile;
14059   struct comp_unit_head *cu_header = &cu->header;
14060   bfd *obfd = objfile->obfd;
14061   unsigned int addr_size = cu_header->addr_size;
14062   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14063   /* Base address selection entry.  */
14064   CORE_ADDR base;
14065   int found_base;
14066   unsigned int dummy;
14067   const gdb_byte *buffer;
14068   CORE_ADDR baseaddr;
14069
14070   if (cu_header->version >= 5)
14071     return dwarf2_rnglists_process (offset, cu, callback);
14072
14073   found_base = cu->base_known;
14074   base = cu->base_address;
14075
14076   dwarf2_per_objfile->ranges.read (objfile);
14077   if (offset >= dwarf2_per_objfile->ranges.size)
14078     {
14079       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14080                  offset);
14081       return 0;
14082     }
14083   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14084
14085   baseaddr = objfile->text_section_offset ();
14086
14087   while (1)
14088     {
14089       CORE_ADDR range_beginning, range_end;
14090
14091       range_beginning = read_address (obfd, buffer, cu, &dummy);
14092       buffer += addr_size;
14093       range_end = read_address (obfd, buffer, cu, &dummy);
14094       buffer += addr_size;
14095       offset += 2 * addr_size;
14096
14097       /* An end of list marker is a pair of zero addresses.  */
14098       if (range_beginning == 0 && range_end == 0)
14099         /* Found the end of list entry.  */
14100         break;
14101
14102       /* Each base address selection entry is a pair of 2 values.
14103          The first is the largest possible address, the second is
14104          the base address.  Check for a base address here.  */
14105       if ((range_beginning & mask) == mask)
14106         {
14107           /* If we found the largest possible address, then we already
14108              have the base address in range_end.  */
14109           base = range_end;
14110           found_base = 1;
14111           continue;
14112         }
14113
14114       if (!found_base)
14115         {
14116           /* We have no valid base address for the ranges
14117              data.  */
14118           complaint (_("Invalid .debug_ranges data (no base address)"));
14119           return 0;
14120         }
14121
14122       if (range_beginning > range_end)
14123         {
14124           /* Inverted range entries are invalid.  */
14125           complaint (_("Invalid .debug_ranges data (inverted range)"));
14126           return 0;
14127         }
14128
14129       /* Empty range entries have no effect.  */
14130       if (range_beginning == range_end)
14131         continue;
14132
14133       range_beginning += base;
14134       range_end += base;
14135
14136       /* A not-uncommon case of bad debug info.
14137          Don't pollute the addrmap with bad data.  */
14138       if (range_beginning + baseaddr == 0
14139           && !dwarf2_per_objfile->has_section_at_zero)
14140         {
14141           complaint (_(".debug_ranges entry has start address of zero"
14142                        " [in module %s]"), objfile_name (objfile));
14143           continue;
14144         }
14145
14146       callback (range_beginning, range_end);
14147     }
14148
14149   return 1;
14150 }
14151
14152 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14153    Return 1 if the attributes are present and valid, otherwise, return 0.
14154    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14155
14156 static int
14157 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14158                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14159                     dwarf2_psymtab *ranges_pst)
14160 {
14161   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14162   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14163   const CORE_ADDR baseaddr = objfile->text_section_offset ();
14164   int low_set = 0;
14165   CORE_ADDR low = 0;
14166   CORE_ADDR high = 0;
14167   int retval;
14168
14169   retval = dwarf2_ranges_process (offset, cu,
14170     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14171     {
14172       if (ranges_pst != NULL)
14173         {
14174           CORE_ADDR lowpc;
14175           CORE_ADDR highpc;
14176
14177           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14178                                                range_beginning + baseaddr)
14179                    - baseaddr);
14180           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14181                                                 range_end + baseaddr)
14182                     - baseaddr);
14183           addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
14184                              lowpc, highpc - 1, ranges_pst);
14185         }
14186
14187       /* FIXME: This is recording everything as a low-high
14188          segment of consecutive addresses.  We should have a
14189          data structure for discontiguous block ranges
14190          instead.  */
14191       if (! low_set)
14192         {
14193           low = range_beginning;
14194           high = range_end;
14195           low_set = 1;
14196         }
14197       else
14198         {
14199           if (range_beginning < low)
14200             low = range_beginning;
14201           if (range_end > high)
14202             high = range_end;
14203         }
14204     });
14205   if (!retval)
14206     return 0;
14207
14208   if (! low_set)
14209     /* If the first entry is an end-of-list marker, the range
14210        describes an empty scope, i.e. no instructions.  */
14211     return 0;
14212
14213   if (low_return)
14214     *low_return = low;
14215   if (high_return)
14216     *high_return = high;
14217   return 1;
14218 }
14219
14220 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14221    definition for the return value.  *LOWPC and *HIGHPC are set iff
14222    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14223
14224 static enum pc_bounds_kind
14225 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14226                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14227                       dwarf2_psymtab *pst)
14228 {
14229   struct dwarf2_per_objfile *dwarf2_per_objfile
14230     = cu->per_cu->dwarf2_per_objfile;
14231   struct attribute *attr;
14232   struct attribute *attr_high;
14233   CORE_ADDR low = 0;
14234   CORE_ADDR high = 0;
14235   enum pc_bounds_kind ret;
14236
14237   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14238   if (attr_high)
14239     {
14240       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14241       if (attr != nullptr)
14242         {
14243           low = attr->value_as_address ();
14244           high = attr_high->value_as_address ();
14245           if (cu->header.version >= 4 && attr_high->form_is_constant ())
14246             high += low;
14247         }
14248       else
14249         /* Found high w/o low attribute.  */
14250         return PC_BOUNDS_INVALID;
14251
14252       /* Found consecutive range of addresses.  */
14253       ret = PC_BOUNDS_HIGH_LOW;
14254     }
14255   else
14256     {
14257       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14258       if (attr != NULL)
14259         {
14260           /* DW_AT_rnglists_base does not apply to DIEs from the DWO skeleton.
14261              We take advantage of the fact that DW_AT_ranges does not appear
14262              in DW_TAG_compile_unit of DWO files.  */
14263           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14264           unsigned int ranges_offset = (DW_UNSND (attr)
14265                                         + (need_ranges_base
14266                                            ? cu->ranges_base
14267                                            : 0));
14268
14269           /* Value of the DW_AT_ranges attribute is the offset in the
14270              .debug_ranges section.  */
14271           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14272             return PC_BOUNDS_INVALID;
14273           /* Found discontinuous range of addresses.  */
14274           ret = PC_BOUNDS_RANGES;
14275         }
14276       else
14277         return PC_BOUNDS_NOT_PRESENT;
14278     }
14279
14280   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14281   if (high <= low)
14282     return PC_BOUNDS_INVALID;
14283
14284   /* When using the GNU linker, .gnu.linkonce. sections are used to
14285      eliminate duplicate copies of functions and vtables and such.
14286      The linker will arbitrarily choose one and discard the others.
14287      The AT_*_pc values for such functions refer to local labels in
14288      these sections.  If the section from that file was discarded, the
14289      labels are not in the output, so the relocs get a value of 0.
14290      If this is a discarded function, mark the pc bounds as invalid,
14291      so that GDB will ignore it.  */
14292   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14293     return PC_BOUNDS_INVALID;
14294
14295   *lowpc = low;
14296   if (highpc)
14297     *highpc = high;
14298   return ret;
14299 }
14300
14301 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14302    its low and high PC addresses.  Do nothing if these addresses could not
14303    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14304    and HIGHPC to the high address if greater than HIGHPC.  */
14305
14306 static void
14307 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14308                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14309                                  struct dwarf2_cu *cu)
14310 {
14311   CORE_ADDR low, high;
14312   struct die_info *child = die->child;
14313
14314   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14315     {
14316       *lowpc = std::min (*lowpc, low);
14317       *highpc = std::max (*highpc, high);
14318     }
14319
14320   /* If the language does not allow nested subprograms (either inside
14321      subprograms or lexical blocks), we're done.  */
14322   if (cu->language != language_ada)
14323     return;
14324
14325   /* Check all the children of the given DIE.  If it contains nested
14326      subprograms, then check their pc bounds.  Likewise, we need to
14327      check lexical blocks as well, as they may also contain subprogram
14328      definitions.  */
14329   while (child && child->tag)
14330     {
14331       if (child->tag == DW_TAG_subprogram
14332           || child->tag == DW_TAG_lexical_block)
14333         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14334       child = sibling_die (child);
14335     }
14336 }
14337
14338 /* Get the low and high pc's represented by the scope DIE, and store
14339    them in *LOWPC and *HIGHPC.  If the correct values can't be
14340    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14341
14342 static void
14343 get_scope_pc_bounds (struct die_info *die,
14344                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14345                      struct dwarf2_cu *cu)
14346 {
14347   CORE_ADDR best_low = (CORE_ADDR) -1;
14348   CORE_ADDR best_high = (CORE_ADDR) 0;
14349   CORE_ADDR current_low, current_high;
14350
14351   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14352       >= PC_BOUNDS_RANGES)
14353     {
14354       best_low = current_low;
14355       best_high = current_high;
14356     }
14357   else
14358     {
14359       struct die_info *child = die->child;
14360
14361       while (child && child->tag)
14362         {
14363           switch (child->tag) {
14364           case DW_TAG_subprogram:
14365             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14366             break;
14367           case DW_TAG_namespace:
14368           case DW_TAG_module:
14369             /* FIXME: carlton/2004-01-16: Should we do this for
14370                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14371                that current GCC's always emit the DIEs corresponding
14372                to definitions of methods of classes as children of a
14373                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14374                the DIEs giving the declarations, which could be
14375                anywhere).  But I don't see any reason why the
14376                standards says that they have to be there.  */
14377             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14378
14379             if (current_low != ((CORE_ADDR) -1))
14380               {
14381                 best_low = std::min (best_low, current_low);
14382                 best_high = std::max (best_high, current_high);
14383               }
14384             break;
14385           default:
14386             /* Ignore.  */
14387             break;
14388           }
14389
14390           child = sibling_die (child);
14391         }
14392     }
14393
14394   *lowpc = best_low;
14395   *highpc = best_high;
14396 }
14397
14398 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14399    in DIE.  */
14400
14401 static void
14402 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14403                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14404 {
14405   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14406   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14407   struct attribute *attr;
14408   struct attribute *attr_high;
14409
14410   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14411   if (attr_high)
14412     {
14413       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14414       if (attr != nullptr)
14415         {
14416           CORE_ADDR low = attr->value_as_address ();
14417           CORE_ADDR high = attr_high->value_as_address ();
14418
14419           if (cu->header.version >= 4 && attr_high->form_is_constant ())
14420             high += low;
14421
14422           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14423           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14424           cu->get_builder ()->record_block_range (block, low, high - 1);
14425         }
14426     }
14427
14428   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14429   if (attr != nullptr)
14430     {
14431       /* DW_AT_rnglists_base does not apply to DIEs from the DWO skeleton.
14432          We take advantage of the fact that DW_AT_ranges does not appear
14433          in DW_TAG_compile_unit of DWO files.  */
14434       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14435
14436       /* The value of the DW_AT_ranges attribute is the offset of the
14437          address range list in the .debug_ranges section.  */
14438       unsigned long offset = (DW_UNSND (attr)
14439                               + (need_ranges_base ? cu->ranges_base : 0));
14440
14441       std::vector<blockrange> blockvec;
14442       dwarf2_ranges_process (offset, cu,
14443         [&] (CORE_ADDR start, CORE_ADDR end)
14444         {
14445           start += baseaddr;
14446           end += baseaddr;
14447           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14448           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14449           cu->get_builder ()->record_block_range (block, start, end - 1);
14450           blockvec.emplace_back (start, end);
14451         });
14452
14453       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14454     }
14455 }
14456
14457 /* Check whether the producer field indicates either of GCC < 4.6, or the
14458    Intel C/C++ compiler, and cache the result in CU.  */
14459
14460 static void
14461 check_producer (struct dwarf2_cu *cu)
14462 {
14463   int major, minor;
14464
14465   if (cu->producer == NULL)
14466     {
14467       /* For unknown compilers expect their behavior is DWARF version
14468          compliant.
14469
14470          GCC started to support .debug_types sections by -gdwarf-4 since
14471          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14472          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14473          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14474          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14475     }
14476   else if (producer_is_gcc (cu->producer, &major, &minor))
14477     {
14478       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14479       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14480     }
14481   else if (producer_is_icc (cu->producer, &major, &minor))
14482     {
14483       cu->producer_is_icc = true;
14484       cu->producer_is_icc_lt_14 = major < 14;
14485     }
14486   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14487     cu->producer_is_codewarrior = true;
14488   else
14489     {
14490       /* For other non-GCC compilers, expect their behavior is DWARF version
14491          compliant.  */
14492     }
14493
14494   cu->checked_producer = true;
14495 }
14496
14497 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14498    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14499    during 4.6.0 experimental.  */
14500
14501 static bool
14502 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14503 {
14504   if (!cu->checked_producer)
14505     check_producer (cu);
14506
14507   return cu->producer_is_gxx_lt_4_6;
14508 }
14509
14510
14511 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14512    with incorrect is_stmt attributes.  */
14513
14514 static bool
14515 producer_is_codewarrior (struct dwarf2_cu *cu)
14516 {
14517   if (!cu->checked_producer)
14518     check_producer (cu);
14519
14520   return cu->producer_is_codewarrior;
14521 }
14522
14523 /* Return the default accessibility type if it is not overridden by
14524    DW_AT_accessibility.  */
14525
14526 static enum dwarf_access_attribute
14527 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14528 {
14529   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14530     {
14531       /* The default DWARF 2 accessibility for members is public, the default
14532          accessibility for inheritance is private.  */
14533
14534       if (die->tag != DW_TAG_inheritance)
14535         return DW_ACCESS_public;
14536       else
14537         return DW_ACCESS_private;
14538     }
14539   else
14540     {
14541       /* DWARF 3+ defines the default accessibility a different way.  The same
14542          rules apply now for DW_TAG_inheritance as for the members and it only
14543          depends on the container kind.  */
14544
14545       if (die->parent->tag == DW_TAG_class_type)
14546         return DW_ACCESS_private;
14547       else
14548         return DW_ACCESS_public;
14549     }
14550 }
14551
14552 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14553    offset.  If the attribute was not found return 0, otherwise return
14554    1.  If it was found but could not properly be handled, set *OFFSET
14555    to 0.  */
14556
14557 static int
14558 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14559                              LONGEST *offset)
14560 {
14561   struct attribute *attr;
14562
14563   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14564   if (attr != NULL)
14565     {
14566       *offset = 0;
14567
14568       /* Note that we do not check for a section offset first here.
14569          This is because DW_AT_data_member_location is new in DWARF 4,
14570          so if we see it, we can assume that a constant form is really
14571          a constant and not a section offset.  */
14572       if (attr->form_is_constant ())
14573         *offset = dwarf2_get_attr_constant_value (attr, 0);
14574       else if (attr->form_is_section_offset ())
14575         dwarf2_complex_location_expr_complaint ();
14576       else if (attr->form_is_block ())
14577         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14578       else
14579         dwarf2_complex_location_expr_complaint ();
14580
14581       return 1;
14582     }
14583
14584   return 0;
14585 }
14586
14587 /* Add an aggregate field to the field list.  */
14588
14589 static void
14590 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14591                   struct dwarf2_cu *cu)
14592 {
14593   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14594   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14595   struct nextfield *new_field;
14596   struct attribute *attr;
14597   struct field *fp;
14598   const char *fieldname = "";
14599
14600   if (die->tag == DW_TAG_inheritance)
14601     {
14602       fip->baseclasses.emplace_back ();
14603       new_field = &fip->baseclasses.back ();
14604     }
14605   else
14606     {
14607       fip->fields.emplace_back ();
14608       new_field = &fip->fields.back ();
14609     }
14610
14611   fip->nfields++;
14612
14613   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14614   if (attr != nullptr)
14615     new_field->accessibility = DW_UNSND (attr);
14616   else
14617     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14618   if (new_field->accessibility != DW_ACCESS_public)
14619     fip->non_public_fields = 1;
14620
14621   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14622   if (attr != nullptr)
14623     new_field->virtuality = DW_UNSND (attr);
14624   else
14625     new_field->virtuality = DW_VIRTUALITY_none;
14626
14627   fp = &new_field->field;
14628
14629   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14630     {
14631       LONGEST offset;
14632
14633       /* Data member other than a C++ static data member.  */
14634
14635       /* Get type of field.  */
14636       fp->type = die_type (die, cu);
14637
14638       SET_FIELD_BITPOS (*fp, 0);
14639
14640       /* Get bit size of field (zero if none).  */
14641       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14642       if (attr != nullptr)
14643         {
14644           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14645         }
14646       else
14647         {
14648           FIELD_BITSIZE (*fp) = 0;
14649         }
14650
14651       /* Get bit offset of field.  */
14652       if (handle_data_member_location (die, cu, &offset))
14653         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14654       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14655       if (attr != nullptr)
14656         {
14657           if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
14658             {
14659               /* For big endian bits, the DW_AT_bit_offset gives the
14660                  additional bit offset from the MSB of the containing
14661                  anonymous object to the MSB of the field.  We don't
14662                  have to do anything special since we don't need to
14663                  know the size of the anonymous object.  */
14664               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14665             }
14666           else
14667             {
14668               /* For little endian bits, compute the bit offset to the
14669                  MSB of the anonymous object, subtract off the number of
14670                  bits from the MSB of the field to the MSB of the
14671                  object, and then subtract off the number of bits of
14672                  the field itself.  The result is the bit offset of
14673                  the LSB of the field.  */
14674               int anonymous_size;
14675               int bit_offset = DW_UNSND (attr);
14676
14677               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14678               if (attr != nullptr)
14679                 {
14680                   /* The size of the anonymous object containing
14681                      the bit field is explicit, so use the
14682                      indicated size (in bytes).  */
14683                   anonymous_size = DW_UNSND (attr);
14684                 }
14685               else
14686                 {
14687                   /* The size of the anonymous object containing
14688                      the bit field must be inferred from the type
14689                      attribute of the data member containing the
14690                      bit field.  */
14691                   anonymous_size = TYPE_LENGTH (fp->type);
14692                 }
14693               SET_FIELD_BITPOS (*fp,
14694                                 (FIELD_BITPOS (*fp)
14695                                  + anonymous_size * bits_per_byte
14696                                  - bit_offset - FIELD_BITSIZE (*fp)));
14697             }
14698         }
14699       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14700       if (attr != NULL)
14701         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14702                                 + dwarf2_get_attr_constant_value (attr, 0)));
14703
14704       /* Get name of field.  */
14705       fieldname = dwarf2_name (die, cu);
14706       if (fieldname == NULL)
14707         fieldname = "";
14708
14709       /* The name is already allocated along with this objfile, so we don't
14710          need to duplicate it for the type.  */
14711       fp->name = fieldname;
14712
14713       /* Change accessibility for artificial fields (e.g. virtual table
14714          pointer or virtual base class pointer) to private.  */
14715       if (dwarf2_attr (die, DW_AT_artificial, cu))
14716         {
14717           FIELD_ARTIFICIAL (*fp) = 1;
14718           new_field->accessibility = DW_ACCESS_private;
14719           fip->non_public_fields = 1;
14720         }
14721     }
14722   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
14723     {
14724       /* C++ static member.  */
14725
14726       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
14727          is a declaration, but all versions of G++ as of this writing
14728          (so through at least 3.2.1) incorrectly generate
14729          DW_TAG_variable tags.  */
14730
14731       const char *physname;
14732
14733       /* Get name of field.  */
14734       fieldname = dwarf2_name (die, cu);
14735       if (fieldname == NULL)
14736         return;
14737
14738       attr = dwarf2_attr (die, DW_AT_const_value, cu);
14739       if (attr
14740           /* Only create a symbol if this is an external value.
14741              new_symbol checks this and puts the value in the global symbol
14742              table, which we want.  If it is not external, new_symbol
14743              will try to put the value in cu->list_in_scope which is wrong.  */
14744           && dwarf2_flag_true_p (die, DW_AT_external, cu))
14745         {
14746           /* A static const member, not much different than an enum as far as
14747              we're concerned, except that we can support more types.  */
14748           new_symbol (die, NULL, cu);
14749         }
14750
14751       /* Get physical name.  */
14752       physname = dwarf2_physname (fieldname, die, cu);
14753
14754       /* The name is already allocated along with this objfile, so we don't
14755          need to duplicate it for the type.  */
14756       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
14757       FIELD_TYPE (*fp) = die_type (die, cu);
14758       FIELD_NAME (*fp) = fieldname;
14759     }
14760   else if (die->tag == DW_TAG_inheritance)
14761     {
14762       LONGEST offset;
14763
14764       /* C++ base class field.  */
14765       if (handle_data_member_location (die, cu, &offset))
14766         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14767       FIELD_BITSIZE (*fp) = 0;
14768       FIELD_TYPE (*fp) = die_type (die, cu);
14769       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
14770     }
14771   else if (die->tag == DW_TAG_variant_part)
14772     {
14773       /* process_structure_scope will treat this DIE as a union.  */
14774       process_structure_scope (die, cu);
14775
14776       /* The variant part is relative to the start of the enclosing
14777          structure.  */
14778       SET_FIELD_BITPOS (*fp, 0);
14779       fp->type = get_die_type (die, cu);
14780       fp->artificial = 1;
14781       fp->name = "<<variant>>";
14782
14783       /* Normally a DW_TAG_variant_part won't have a size, but our
14784          representation requires one, so set it to the maximum of the
14785          child sizes, being sure to account for the offset at which
14786          each child is seen.  */
14787       if (TYPE_LENGTH (fp->type) == 0)
14788         {
14789           unsigned max = 0;
14790           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
14791             {
14792               unsigned len = ((TYPE_FIELD_BITPOS (fp->type, i) + 7) / 8
14793                               + TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)));
14794               if (len > max)
14795                 max = len;
14796             }
14797           TYPE_LENGTH (fp->type) = max;
14798         }
14799     }
14800   else
14801     gdb_assert_not_reached ("missing case in dwarf2_add_field");
14802 }
14803
14804 /* Can the type given by DIE define another type?  */
14805
14806 static bool
14807 type_can_define_types (const struct die_info *die)
14808 {
14809   switch (die->tag)
14810     {
14811     case DW_TAG_typedef:
14812     case DW_TAG_class_type:
14813     case DW_TAG_structure_type:
14814     case DW_TAG_union_type:
14815     case DW_TAG_enumeration_type:
14816       return true;
14817
14818     default:
14819       return false;
14820     }
14821 }
14822
14823 /* Add a type definition defined in the scope of the FIP's class.  */
14824
14825 static void
14826 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
14827                       struct dwarf2_cu *cu)
14828 {
14829   struct decl_field fp;
14830   memset (&fp, 0, sizeof (fp));
14831
14832   gdb_assert (type_can_define_types (die));
14833
14834   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
14835   fp.name = dwarf2_name (die, cu);
14836   fp.type = read_type_die (die, cu);
14837
14838   /* Save accessibility.  */
14839   enum dwarf_access_attribute accessibility;
14840   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14841   if (attr != NULL)
14842     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14843   else
14844     accessibility = dwarf2_default_access_attribute (die, cu);
14845   switch (accessibility)
14846     {
14847     case DW_ACCESS_public:
14848       /* The assumed value if neither private nor protected.  */
14849       break;
14850     case DW_ACCESS_private:
14851       fp.is_private = 1;
14852       break;
14853     case DW_ACCESS_protected:
14854       fp.is_protected = 1;
14855       break;
14856     default:
14857       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
14858     }
14859
14860   if (die->tag == DW_TAG_typedef)
14861     fip->typedef_field_list.push_back (fp);
14862   else
14863     fip->nested_types_list.push_back (fp);
14864 }
14865
14866 /* Create the vector of fields, and attach it to the type.  */
14867
14868 static void
14869 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
14870                               struct dwarf2_cu *cu)
14871 {
14872   int nfields = fip->nfields;
14873
14874   /* Record the field count, allocate space for the array of fields,
14875      and create blank accessibility bitfields if necessary.  */
14876   TYPE_NFIELDS (type) = nfields;
14877   TYPE_FIELDS (type) = (struct field *)
14878     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
14879
14880   if (fip->non_public_fields && cu->language != language_ada)
14881     {
14882       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14883
14884       TYPE_FIELD_PRIVATE_BITS (type) =
14885         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14886       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
14887
14888       TYPE_FIELD_PROTECTED_BITS (type) =
14889         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14890       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
14891
14892       TYPE_FIELD_IGNORE_BITS (type) =
14893         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14894       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
14895     }
14896
14897   /* If the type has baseclasses, allocate and clear a bit vector for
14898      TYPE_FIELD_VIRTUAL_BITS.  */
14899   if (!fip->baseclasses.empty () && cu->language != language_ada)
14900     {
14901       int num_bytes = B_BYTES (fip->baseclasses.size ());
14902       unsigned char *pointer;
14903
14904       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14905       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
14906       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
14907       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
14908       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
14909     }
14910
14911   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
14912     {
14913       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
14914
14915       for (int index = 0; index < nfields; ++index)
14916         {
14917           struct nextfield &field = fip->fields[index];
14918
14919           if (field.variant.is_discriminant)
14920             di->discriminant_index = index;
14921           else if (field.variant.default_branch)
14922             di->default_index = index;
14923           else
14924             di->discriminants[index] = field.variant.discriminant_value;
14925         }
14926     }
14927
14928   /* Copy the saved-up fields into the field vector.  */
14929   for (int i = 0; i < nfields; ++i)
14930     {
14931       struct nextfield &field
14932         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
14933            : fip->fields[i - fip->baseclasses.size ()]);
14934
14935       TYPE_FIELD (type, i) = field.field;
14936       switch (field.accessibility)
14937         {
14938         case DW_ACCESS_private:
14939           if (cu->language != language_ada)
14940             SET_TYPE_FIELD_PRIVATE (type, i);
14941           break;
14942
14943         case DW_ACCESS_protected:
14944           if (cu->language != language_ada)
14945             SET_TYPE_FIELD_PROTECTED (type, i);
14946           break;
14947
14948         case DW_ACCESS_public:
14949           break;
14950
14951         default:
14952           /* Unknown accessibility.  Complain and treat it as public.  */
14953           {
14954             complaint (_("unsupported accessibility %d"),
14955                        field.accessibility);
14956           }
14957           break;
14958         }
14959       if (i < fip->baseclasses.size ())
14960         {
14961           switch (field.virtuality)
14962             {
14963             case DW_VIRTUALITY_virtual:
14964             case DW_VIRTUALITY_pure_virtual:
14965               if (cu->language == language_ada)
14966                 error (_("unexpected virtuality in component of Ada type"));
14967               SET_TYPE_FIELD_VIRTUAL (type, i);
14968               break;
14969             }
14970         }
14971     }
14972 }
14973
14974 /* Return true if this member function is a constructor, false
14975    otherwise.  */
14976
14977 static int
14978 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
14979 {
14980   const char *fieldname;
14981   const char *type_name;
14982   int len;
14983
14984   if (die->parent == NULL)
14985     return 0;
14986
14987   if (die->parent->tag != DW_TAG_structure_type
14988       && die->parent->tag != DW_TAG_union_type
14989       && die->parent->tag != DW_TAG_class_type)
14990     return 0;
14991
14992   fieldname = dwarf2_name (die, cu);
14993   type_name = dwarf2_name (die->parent, cu);
14994   if (fieldname == NULL || type_name == NULL)
14995     return 0;
14996
14997   len = strlen (fieldname);
14998   return (strncmp (fieldname, type_name, len) == 0
14999           && (type_name[len] == '\0' || type_name[len] == '<'));
15000 }
15001
15002 /* Check if the given VALUE is a recognized enum
15003    dwarf_defaulted_attribute constant according to DWARF5 spec,
15004    Table 7.24.  */
15005
15006 static bool
15007 is_valid_DW_AT_defaulted (ULONGEST value)
15008 {
15009   switch (value)
15010     {
15011     case DW_DEFAULTED_no:
15012     case DW_DEFAULTED_in_class:
15013     case DW_DEFAULTED_out_of_class:
15014       return true;
15015     }
15016
15017   complaint (_("unrecognized DW_AT_defaulted value (%s)"), pulongest (value));
15018   return false;
15019 }
15020
15021 /* Add a member function to the proper fieldlist.  */
15022
15023 static void
15024 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15025                       struct type *type, struct dwarf2_cu *cu)
15026 {
15027   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15028   struct attribute *attr;
15029   int i;
15030   struct fnfieldlist *flp = nullptr;
15031   struct fn_field *fnp;
15032   const char *fieldname;
15033   struct type *this_type;
15034   enum dwarf_access_attribute accessibility;
15035
15036   if (cu->language == language_ada)
15037     error (_("unexpected member function in Ada type"));
15038
15039   /* Get name of member function.  */
15040   fieldname = dwarf2_name (die, cu);
15041   if (fieldname == NULL)
15042     return;
15043
15044   /* Look up member function name in fieldlist.  */
15045   for (i = 0; i < fip->fnfieldlists.size (); i++)
15046     {
15047       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15048         {
15049           flp = &fip->fnfieldlists[i];
15050           break;
15051         }
15052     }
15053
15054   /* Create a new fnfieldlist if necessary.  */
15055   if (flp == nullptr)
15056     {
15057       fip->fnfieldlists.emplace_back ();
15058       flp = &fip->fnfieldlists.back ();
15059       flp->name = fieldname;
15060       i = fip->fnfieldlists.size () - 1;
15061     }
15062
15063   /* Create a new member function field and add it to the vector of
15064      fnfieldlists.  */
15065   flp->fnfields.emplace_back ();
15066   fnp = &flp->fnfields.back ();
15067
15068   /* Delay processing of the physname until later.  */
15069   if (cu->language == language_cplus)
15070     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15071                         die, cu);
15072   else
15073     {
15074       const char *physname = dwarf2_physname (fieldname, die, cu);
15075       fnp->physname = physname ? physname : "";
15076     }
15077
15078   fnp->type = alloc_type (objfile);
15079   this_type = read_type_die (die, cu);
15080   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15081     {
15082       int nparams = TYPE_NFIELDS (this_type);
15083
15084       /* TYPE is the domain of this method, and THIS_TYPE is the type
15085            of the method itself (TYPE_CODE_METHOD).  */
15086       smash_to_method_type (fnp->type, type,
15087                             TYPE_TARGET_TYPE (this_type),
15088                             TYPE_FIELDS (this_type),
15089                             TYPE_NFIELDS (this_type),
15090                             TYPE_VARARGS (this_type));
15091
15092       /* Handle static member functions.
15093          Dwarf2 has no clean way to discern C++ static and non-static
15094          member functions.  G++ helps GDB by marking the first
15095          parameter for non-static member functions (which is the this
15096          pointer) as artificial.  We obtain this information from
15097          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15098       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15099         fnp->voffset = VOFFSET_STATIC;
15100     }
15101   else
15102     complaint (_("member function type missing for '%s'"),
15103                dwarf2_full_name (fieldname, die, cu));
15104
15105   /* Get fcontext from DW_AT_containing_type if present.  */
15106   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15107     fnp->fcontext = die_containing_type (die, cu);
15108
15109   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15110      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15111
15112   /* Get accessibility.  */
15113   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15114   if (attr != nullptr)
15115     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15116   else
15117     accessibility = dwarf2_default_access_attribute (die, cu);
15118   switch (accessibility)
15119     {
15120     case DW_ACCESS_private:
15121       fnp->is_private = 1;
15122       break;
15123     case DW_ACCESS_protected:
15124       fnp->is_protected = 1;
15125       break;
15126     }
15127
15128   /* Check for artificial methods.  */
15129   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15130   if (attr && DW_UNSND (attr) != 0)
15131     fnp->is_artificial = 1;
15132
15133   /* Check for defaulted methods.  */
15134   attr = dwarf2_attr (die, DW_AT_defaulted, cu);
15135   if (attr != nullptr && is_valid_DW_AT_defaulted (DW_UNSND (attr)))
15136     fnp->defaulted = (enum dwarf_defaulted_attribute) DW_UNSND (attr);
15137
15138   /* Check for deleted methods.  */
15139   attr = dwarf2_attr (die, DW_AT_deleted, cu);
15140   if (attr != nullptr && DW_UNSND (attr) != 0)
15141     fnp->is_deleted = 1;
15142
15143   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15144
15145   /* Get index in virtual function table if it is a virtual member
15146      function.  For older versions of GCC, this is an offset in the
15147      appropriate virtual table, as specified by DW_AT_containing_type.
15148      For everyone else, it is an expression to be evaluated relative
15149      to the object address.  */
15150
15151   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15152   if (attr != nullptr)
15153     {
15154       if (attr->form_is_block () && DW_BLOCK (attr)->size > 0)
15155         {
15156           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15157             {
15158               /* Old-style GCC.  */
15159               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15160             }
15161           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15162                    || (DW_BLOCK (attr)->size > 1
15163                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15164                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15165             {
15166               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15167               if ((fnp->voffset % cu->header.addr_size) != 0)
15168                 dwarf2_complex_location_expr_complaint ();
15169               else
15170                 fnp->voffset /= cu->header.addr_size;
15171               fnp->voffset += 2;
15172             }
15173           else
15174             dwarf2_complex_location_expr_complaint ();
15175
15176           if (!fnp->fcontext)
15177             {
15178               /* If there is no `this' field and no DW_AT_containing_type,
15179                  we cannot actually find a base class context for the
15180                  vtable!  */
15181               if (TYPE_NFIELDS (this_type) == 0
15182                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15183                 {
15184                   complaint (_("cannot determine context for virtual member "
15185                                "function \"%s\" (offset %s)"),
15186                              fieldname, sect_offset_str (die->sect_off));
15187                 }
15188               else
15189                 {
15190                   fnp->fcontext
15191                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15192                 }
15193             }
15194         }
15195       else if (attr->form_is_section_offset ())
15196         {
15197           dwarf2_complex_location_expr_complaint ();
15198         }
15199       else
15200         {
15201           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15202                                                  fieldname);
15203         }
15204     }
15205   else
15206     {
15207       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15208       if (attr && DW_UNSND (attr))
15209         {
15210           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15211           complaint (_("Member function \"%s\" (offset %s) is virtual "
15212                        "but the vtable offset is not specified"),
15213                      fieldname, sect_offset_str (die->sect_off));
15214           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15215           TYPE_CPLUS_DYNAMIC (type) = 1;
15216         }
15217     }
15218 }
15219
15220 /* Create the vector of member function fields, and attach it to the type.  */
15221
15222 static void
15223 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15224                                  struct dwarf2_cu *cu)
15225 {
15226   if (cu->language == language_ada)
15227     error (_("unexpected member functions in Ada type"));
15228
15229   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15230   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15231     TYPE_ALLOC (type,
15232                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15233
15234   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15235     {
15236       struct fnfieldlist &nf = fip->fnfieldlists[i];
15237       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15238
15239       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15240       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15241       fn_flp->fn_fields = (struct fn_field *)
15242         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15243
15244       for (int k = 0; k < nf.fnfields.size (); ++k)
15245         fn_flp->fn_fields[k] = nf.fnfields[k];
15246     }
15247
15248   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15249 }
15250
15251 /* Returns non-zero if NAME is the name of a vtable member in CU's
15252    language, zero otherwise.  */
15253 static int
15254 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15255 {
15256   static const char vptr[] = "_vptr";
15257
15258   /* Look for the C++ form of the vtable.  */
15259   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15260     return 1;
15261
15262   return 0;
15263 }
15264
15265 /* GCC outputs unnamed structures that are really pointers to member
15266    functions, with the ABI-specified layout.  If TYPE describes
15267    such a structure, smash it into a member function type.
15268
15269    GCC shouldn't do this; it should just output pointer to member DIEs.
15270    This is GCC PR debug/28767.  */
15271
15272 static void
15273 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15274 {
15275   struct type *pfn_type, *self_type, *new_type;
15276
15277   /* Check for a structure with no name and two children.  */
15278   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15279     return;
15280
15281   /* Check for __pfn and __delta members.  */
15282   if (TYPE_FIELD_NAME (type, 0) == NULL
15283       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15284       || TYPE_FIELD_NAME (type, 1) == NULL
15285       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15286     return;
15287
15288   /* Find the type of the method.  */
15289   pfn_type = TYPE_FIELD_TYPE (type, 0);
15290   if (pfn_type == NULL
15291       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15292       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15293     return;
15294
15295   /* Look for the "this" argument.  */
15296   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15297   if (TYPE_NFIELDS (pfn_type) == 0
15298       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15299       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15300     return;
15301
15302   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15303   new_type = alloc_type (objfile);
15304   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15305                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15306                         TYPE_VARARGS (pfn_type));
15307   smash_to_methodptr_type (type, new_type);
15308 }
15309
15310 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15311    appropriate error checking and issuing complaints if there is a
15312    problem.  */
15313
15314 static ULONGEST
15315 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15316 {
15317   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15318
15319   if (attr == nullptr)
15320     return 0;
15321
15322   if (!attr->form_is_constant ())
15323     {
15324       complaint (_("DW_AT_alignment must have constant form"
15325                    " - DIE at %s [in module %s]"),
15326                  sect_offset_str (die->sect_off),
15327                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15328       return 0;
15329     }
15330
15331   ULONGEST align;
15332   if (attr->form == DW_FORM_sdata)
15333     {
15334       LONGEST val = DW_SND (attr);
15335       if (val < 0)
15336         {
15337           complaint (_("DW_AT_alignment value must not be negative"
15338                        " - DIE at %s [in module %s]"),
15339                      sect_offset_str (die->sect_off),
15340                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15341           return 0;
15342         }
15343       align = val;
15344     }
15345   else
15346     align = DW_UNSND (attr);
15347
15348   if (align == 0)
15349     {
15350       complaint (_("DW_AT_alignment value must not be zero"
15351                    " - DIE at %s [in module %s]"),
15352                  sect_offset_str (die->sect_off),
15353                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15354       return 0;
15355     }
15356   if ((align & (align - 1)) != 0)
15357     {
15358       complaint (_("DW_AT_alignment value must be a power of 2"
15359                    " - DIE at %s [in module %s]"),
15360                  sect_offset_str (die->sect_off),
15361                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15362       return 0;
15363     }
15364
15365   return align;
15366 }
15367
15368 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15369    the alignment for TYPE.  */
15370
15371 static void
15372 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15373                      struct type *type)
15374 {
15375   if (!set_type_align (type, get_alignment (cu, die)))
15376     complaint (_("DW_AT_alignment value too large"
15377                  " - DIE at %s [in module %s]"),
15378                sect_offset_str (die->sect_off),
15379                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15380 }
15381
15382 /* Check if the given VALUE is a valid enum dwarf_calling_convention
15383    constant for a type, according to DWARF5 spec, Table 5.5.  */
15384
15385 static bool
15386 is_valid_DW_AT_calling_convention_for_type (ULONGEST value)
15387 {
15388   switch (value)
15389     {
15390     case DW_CC_normal:
15391     case DW_CC_pass_by_reference:
15392     case DW_CC_pass_by_value:
15393       return true;
15394
15395     default:
15396       complaint (_("unrecognized DW_AT_calling_convention value "
15397                    "(%s) for a type"), pulongest (value));
15398       return false;
15399     }
15400 }
15401
15402 /* Check if the given VALUE is a valid enum dwarf_calling_convention
15403    constant for a subroutine, according to DWARF5 spec, Table 3.3, and
15404    also according to GNU-specific values (see include/dwarf2.h).  */
15405
15406 static bool
15407 is_valid_DW_AT_calling_convention_for_subroutine (ULONGEST value)
15408 {
15409   switch (value)
15410     {
15411     case DW_CC_normal:
15412     case DW_CC_program:
15413     case DW_CC_nocall:
15414       return true;
15415
15416     case DW_CC_GNU_renesas_sh:
15417     case DW_CC_GNU_borland_fastcall_i386:
15418     case DW_CC_GDB_IBM_OpenCL:
15419       return true;
15420
15421     default:
15422       complaint (_("unrecognized DW_AT_calling_convention value "
15423                    "(%s) for a subroutine"), pulongest (value));
15424       return false;
15425     }
15426 }
15427
15428 /* Called when we find the DIE that starts a structure or union scope
15429    (definition) to create a type for the structure or union.  Fill in
15430    the type's name and general properties; the members will not be
15431    processed until process_structure_scope.  A symbol table entry for
15432    the type will also not be done until process_structure_scope (assuming
15433    the type has a name).
15434
15435    NOTE: we need to call these functions regardless of whether or not the
15436    DIE has a DW_AT_name attribute, since it might be an anonymous
15437    structure or union.  This gets the type entered into our set of
15438    user defined types.  */
15439
15440 static struct type *
15441 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15442 {
15443   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15444   struct type *type;
15445   struct attribute *attr;
15446   const char *name;
15447
15448   /* If the definition of this type lives in .debug_types, read that type.
15449      Don't follow DW_AT_specification though, that will take us back up
15450      the chain and we want to go down.  */
15451   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15452   if (attr != nullptr)
15453     {
15454       type = get_DW_AT_signature_type (die, attr, cu);
15455
15456       /* The type's CU may not be the same as CU.
15457          Ensure TYPE is recorded with CU in die_type_hash.  */
15458       return set_die_type (die, type, cu);
15459     }
15460
15461   type = alloc_type (objfile);
15462   INIT_CPLUS_SPECIFIC (type);
15463
15464   name = dwarf2_name (die, cu);
15465   if (name != NULL)
15466     {
15467       if (cu->language == language_cplus
15468           || cu->language == language_d
15469           || cu->language == language_rust)
15470         {
15471           const char *full_name = dwarf2_full_name (name, die, cu);
15472
15473           /* dwarf2_full_name might have already finished building the DIE's
15474              type.  If so, there is no need to continue.  */
15475           if (get_die_type (die, cu) != NULL)
15476             return get_die_type (die, cu);
15477
15478           TYPE_NAME (type) = full_name;
15479         }
15480       else
15481         {
15482           /* The name is already allocated along with this objfile, so
15483              we don't need to duplicate it for the type.  */
15484           TYPE_NAME (type) = name;
15485         }
15486     }
15487
15488   if (die->tag == DW_TAG_structure_type)
15489     {
15490       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15491     }
15492   else if (die->tag == DW_TAG_union_type)
15493     {
15494       TYPE_CODE (type) = TYPE_CODE_UNION;
15495     }
15496   else if (die->tag == DW_TAG_variant_part)
15497     {
15498       TYPE_CODE (type) = TYPE_CODE_UNION;
15499       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15500     }
15501   else
15502     {
15503       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15504     }
15505
15506   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15507     TYPE_DECLARED_CLASS (type) = 1;
15508
15509   /* Store the calling convention in the type if it's available in
15510      the die.  Otherwise the calling convention remains set to
15511      the default value DW_CC_normal.  */
15512   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15513   if (attr != nullptr
15514       && is_valid_DW_AT_calling_convention_for_type (DW_UNSND (attr)))
15515     {
15516       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15517       TYPE_CPLUS_CALLING_CONVENTION (type)
15518         = (enum dwarf_calling_convention) (DW_UNSND (attr));
15519     }
15520
15521   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15522   if (attr != nullptr)
15523     {
15524       if (attr->form_is_constant ())
15525         TYPE_LENGTH (type) = DW_UNSND (attr);
15526       else
15527         {
15528           /* For the moment, dynamic type sizes are not supported
15529              by GDB's struct type.  The actual size is determined
15530              on-demand when resolving the type of a given object,
15531              so set the type's length to zero for now.  Otherwise,
15532              we record an expression as the length, and that expression
15533              could lead to a very large value, which could eventually
15534              lead to us trying to allocate that much memory when creating
15535              a value of that type.  */
15536           TYPE_LENGTH (type) = 0;
15537         }
15538     }
15539   else
15540     {
15541       TYPE_LENGTH (type) = 0;
15542     }
15543
15544   maybe_set_alignment (cu, die, type);
15545
15546   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15547     {
15548       /* ICC<14 does not output the required DW_AT_declaration on
15549          incomplete types, but gives them a size of zero.  */
15550       TYPE_STUB (type) = 1;
15551     }
15552   else
15553     TYPE_STUB_SUPPORTED (type) = 1;
15554
15555   if (die_is_declaration (die, cu))
15556     TYPE_STUB (type) = 1;
15557   else if (attr == NULL && die->child == NULL
15558            && producer_is_realview (cu->producer))
15559     /* RealView does not output the required DW_AT_declaration
15560        on incomplete types.  */
15561     TYPE_STUB (type) = 1;
15562
15563   /* We need to add the type field to the die immediately so we don't
15564      infinitely recurse when dealing with pointers to the structure
15565      type within the structure itself.  */
15566   set_die_type (die, type, cu);
15567
15568   /* set_die_type should be already done.  */
15569   set_descriptive_type (type, die, cu);
15570
15571   return type;
15572 }
15573
15574 /* A helper for process_structure_scope that handles a single member
15575    DIE.  */
15576
15577 static void
15578 handle_struct_member_die (struct die_info *child_die, struct type *type,
15579                           struct field_info *fi,
15580                           std::vector<struct symbol *> *template_args,
15581                           struct dwarf2_cu *cu)
15582 {
15583   if (child_die->tag == DW_TAG_member
15584       || child_die->tag == DW_TAG_variable
15585       || child_die->tag == DW_TAG_variant_part)
15586     {
15587       /* NOTE: carlton/2002-11-05: A C++ static data member
15588          should be a DW_TAG_member that is a declaration, but
15589          all versions of G++ as of this writing (so through at
15590          least 3.2.1) incorrectly generate DW_TAG_variable
15591          tags for them instead.  */
15592       dwarf2_add_field (fi, child_die, cu);
15593     }
15594   else if (child_die->tag == DW_TAG_subprogram)
15595     {
15596       /* Rust doesn't have member functions in the C++ sense.
15597          However, it does emit ordinary functions as children
15598          of a struct DIE.  */
15599       if (cu->language == language_rust)
15600         read_func_scope (child_die, cu);
15601       else
15602         {
15603           /* C++ member function.  */
15604           dwarf2_add_member_fn (fi, child_die, type, cu);
15605         }
15606     }
15607   else if (child_die->tag == DW_TAG_inheritance)
15608     {
15609       /* C++ base class field.  */
15610       dwarf2_add_field (fi, child_die, cu);
15611     }
15612   else if (type_can_define_types (child_die))
15613     dwarf2_add_type_defn (fi, child_die, cu);
15614   else if (child_die->tag == DW_TAG_template_type_param
15615            || child_die->tag == DW_TAG_template_value_param)
15616     {
15617       struct symbol *arg = new_symbol (child_die, NULL, cu);
15618
15619       if (arg != NULL)
15620         template_args->push_back (arg);
15621     }
15622   else if (child_die->tag == DW_TAG_variant)
15623     {
15624       /* In a variant we want to get the discriminant and also add a
15625          field for our sole member child.  */
15626       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15627
15628       for (die_info *variant_child = child_die->child;
15629            variant_child != NULL;
15630            variant_child = sibling_die (variant_child))
15631         {
15632           if (variant_child->tag == DW_TAG_member)
15633             {
15634               handle_struct_member_die (variant_child, type, fi,
15635                                         template_args, cu);
15636               /* Only handle the one.  */
15637               break;
15638             }
15639         }
15640
15641       /* We don't handle this but we might as well report it if we see
15642          it.  */
15643       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15644           complaint (_("DW_AT_discr_list is not supported yet"
15645                        " - DIE at %s [in module %s]"),
15646                      sect_offset_str (child_die->sect_off),
15647                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15648
15649       /* The first field was just added, so we can stash the
15650          discriminant there.  */
15651       gdb_assert (!fi->fields.empty ());
15652       if (discr == NULL)
15653         fi->fields.back ().variant.default_branch = true;
15654       else
15655         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15656     }
15657 }
15658
15659 /* Finish creating a structure or union type, including filling in
15660    its members and creating a symbol for it.  */
15661
15662 static void
15663 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15664 {
15665   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15666   struct die_info *child_die;
15667   struct type *type;
15668
15669   type = get_die_type (die, cu);
15670   if (type == NULL)
15671     type = read_structure_type (die, cu);
15672
15673   /* When reading a DW_TAG_variant_part, we need to notice when we
15674      read the discriminant member, so we can record it later in the
15675      discriminant_info.  */
15676   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15677   sect_offset discr_offset {};
15678   bool has_template_parameters = false;
15679
15680   if (is_variant_part)
15681     {
15682       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15683       if (discr == NULL)
15684         {
15685           /* Maybe it's a univariant form, an extension we support.
15686              In this case arrange not to check the offset.  */
15687           is_variant_part = false;
15688         }
15689       else if (discr->form_is_ref ())
15690         {
15691           struct dwarf2_cu *target_cu = cu;
15692           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15693
15694           discr_offset = target_die->sect_off;
15695         }
15696       else
15697         {
15698           complaint (_("DW_AT_discr does not have DIE reference form"
15699                        " - DIE at %s [in module %s]"),
15700                      sect_offset_str (die->sect_off),
15701                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15702           is_variant_part = false;
15703         }
15704     }
15705
15706   if (die->child != NULL && ! die_is_declaration (die, cu))
15707     {
15708       struct field_info fi;
15709       std::vector<struct symbol *> template_args;
15710
15711       child_die = die->child;
15712
15713       while (child_die && child_die->tag)
15714         {
15715           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15716
15717           if (is_variant_part && discr_offset == child_die->sect_off)
15718             fi.fields.back ().variant.is_discriminant = true;
15719
15720           child_die = sibling_die (child_die);
15721         }
15722
15723       /* Attach template arguments to type.  */
15724       if (!template_args.empty ())
15725         {
15726           has_template_parameters = true;
15727           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15728           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15729           TYPE_TEMPLATE_ARGUMENTS (type)
15730             = XOBNEWVEC (&objfile->objfile_obstack,
15731                          struct symbol *,
15732                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15733           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15734                   template_args.data (),
15735                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15736                    * sizeof (struct symbol *)));
15737         }
15738
15739       /* Attach fields and member functions to the type.  */
15740       if (fi.nfields)
15741         dwarf2_attach_fields_to_type (&fi, type, cu);
15742       if (!fi.fnfieldlists.empty ())
15743         {
15744           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15745
15746           /* Get the type which refers to the base class (possibly this
15747              class itself) which contains the vtable pointer for the current
15748              class from the DW_AT_containing_type attribute.  This use of
15749              DW_AT_containing_type is a GNU extension.  */
15750
15751           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15752             {
15753               struct type *t = die_containing_type (die, cu);
15754
15755               set_type_vptr_basetype (type, t);
15756               if (type == t)
15757                 {
15758                   int i;
15759
15760                   /* Our own class provides vtbl ptr.  */
15761                   for (i = TYPE_NFIELDS (t) - 1;
15762                        i >= TYPE_N_BASECLASSES (t);
15763                        --i)
15764                     {
15765                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15766
15767                       if (is_vtable_name (fieldname, cu))
15768                         {
15769                           set_type_vptr_fieldno (type, i);
15770                           break;
15771                         }
15772                     }
15773
15774                   /* Complain if virtual function table field not found.  */
15775                   if (i < TYPE_N_BASECLASSES (t))
15776                     complaint (_("virtual function table pointer "
15777                                  "not found when defining class '%s'"),
15778                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15779                 }
15780               else
15781                 {
15782                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15783                 }
15784             }
15785           else if (cu->producer
15786                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15787             {
15788               /* The IBM XLC compiler does not provide direct indication
15789                  of the containing type, but the vtable pointer is
15790                  always named __vfp.  */
15791
15792               int i;
15793
15794               for (i = TYPE_NFIELDS (type) - 1;
15795                    i >= TYPE_N_BASECLASSES (type);
15796                    --i)
15797                 {
15798                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15799                     {
15800                       set_type_vptr_fieldno (type, i);
15801                       set_type_vptr_basetype (type, type);
15802                       break;
15803                     }
15804                 }
15805             }
15806         }
15807
15808       /* Copy fi.typedef_field_list linked list elements content into the
15809          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15810       if (!fi.typedef_field_list.empty ())
15811         {
15812           int count = fi.typedef_field_list.size ();
15813
15814           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15815           TYPE_TYPEDEF_FIELD_ARRAY (type)
15816             = ((struct decl_field *)
15817                TYPE_ALLOC (type,
15818                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
15819           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
15820
15821           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
15822             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
15823         }
15824
15825       /* Copy fi.nested_types_list linked list elements content into the
15826          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15827       if (!fi.nested_types_list.empty () && cu->language != language_ada)
15828         {
15829           int count = fi.nested_types_list.size ();
15830
15831           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15832           TYPE_NESTED_TYPES_ARRAY (type)
15833             = ((struct decl_field *)
15834                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
15835           TYPE_NESTED_TYPES_COUNT (type) = count;
15836
15837           for (int i = 0; i < fi.nested_types_list.size (); ++i)
15838             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
15839         }
15840     }
15841
15842   quirk_gcc_member_function_pointer (type, objfile);
15843   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
15844     cu->rust_unions.push_back (type);
15845
15846   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
15847      snapshots) has been known to create a die giving a declaration
15848      for a class that has, as a child, a die giving a definition for a
15849      nested class.  So we have to process our children even if the
15850      current die is a declaration.  Normally, of course, a declaration
15851      won't have any children at all.  */
15852
15853   child_die = die->child;
15854
15855   while (child_die != NULL && child_die->tag)
15856     {
15857       if (child_die->tag == DW_TAG_member
15858           || child_die->tag == DW_TAG_variable
15859           || child_die->tag == DW_TAG_inheritance
15860           || child_die->tag == DW_TAG_template_value_param
15861           || child_die->tag == DW_TAG_template_type_param)
15862         {
15863           /* Do nothing.  */
15864         }
15865       else
15866         process_die (child_die, cu);
15867
15868       child_die = sibling_die (child_die);
15869     }
15870
15871   /* Do not consider external references.  According to the DWARF standard,
15872      these DIEs are identified by the fact that they have no byte_size
15873      attribute, and a declaration attribute.  */
15874   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
15875       || !die_is_declaration (die, cu))
15876     {
15877       struct symbol *sym = new_symbol (die, type, cu);
15878
15879       if (has_template_parameters)
15880         {
15881           struct symtab *symtab;
15882           if (sym != nullptr)
15883             symtab = symbol_symtab (sym);
15884           else if (cu->line_header != nullptr)
15885             {
15886               /* Any related symtab will do.  */
15887               symtab
15888                 = cu->line_header->file_names ()[0].symtab;
15889             }
15890           else
15891             {
15892               symtab = nullptr;
15893               complaint (_("could not find suitable "
15894                            "symtab for template parameter"
15895                            " - DIE at %s [in module %s]"),
15896                          sect_offset_str (die->sect_off),
15897                          objfile_name (objfile));
15898             }
15899
15900           if (symtab != nullptr)
15901             {
15902               /* Make sure that the symtab is set on the new symbols.
15903                  Even though they don't appear in this symtab directly,
15904                  other parts of gdb assume that symbols do, and this is
15905                  reasonably true.  */
15906               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
15907                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
15908             }
15909         }
15910     }
15911 }
15912
15913 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
15914    update TYPE using some information only available in DIE's children.  */
15915
15916 static void
15917 update_enumeration_type_from_children (struct die_info *die,
15918                                        struct type *type,
15919                                        struct dwarf2_cu *cu)
15920 {
15921   struct die_info *child_die;
15922   int unsigned_enum = 1;
15923   int flag_enum = 1;
15924   ULONGEST mask = 0;
15925
15926   auto_obstack obstack;
15927
15928   for (child_die = die->child;
15929        child_die != NULL && child_die->tag;
15930        child_die = sibling_die (child_die))
15931     {
15932       struct attribute *attr;
15933       LONGEST value;
15934       const gdb_byte *bytes;
15935       struct dwarf2_locexpr_baton *baton;
15936       const char *name;
15937
15938       if (child_die->tag != DW_TAG_enumerator)
15939         continue;
15940
15941       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
15942       if (attr == NULL)
15943         continue;
15944
15945       name = dwarf2_name (child_die, cu);
15946       if (name == NULL)
15947         name = "<anonymous enumerator>";
15948
15949       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
15950                                &value, &bytes, &baton);
15951       if (value < 0)
15952         {
15953           unsigned_enum = 0;
15954           flag_enum = 0;
15955         }
15956       else if ((mask & value) != 0)
15957         flag_enum = 0;
15958       else
15959         mask |= value;
15960
15961       /* If we already know that the enum type is neither unsigned, nor
15962          a flag type, no need to look at the rest of the enumerates.  */
15963       if (!unsigned_enum && !flag_enum)
15964         break;
15965     }
15966
15967   if (unsigned_enum)
15968     TYPE_UNSIGNED (type) = 1;
15969   if (flag_enum)
15970     TYPE_FLAG_ENUM (type) = 1;
15971 }
15972
15973 /* Given a DW_AT_enumeration_type die, set its type.  We do not
15974    complete the type's fields yet, or create any symbols.  */
15975
15976 static struct type *
15977 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
15978 {
15979   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15980   struct type *type;
15981   struct attribute *attr;
15982   const char *name;
15983
15984   /* If the definition of this type lives in .debug_types, read that type.
15985      Don't follow DW_AT_specification though, that will take us back up
15986      the chain and we want to go down.  */
15987   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15988   if (attr != nullptr)
15989     {
15990       type = get_DW_AT_signature_type (die, attr, cu);
15991
15992       /* The type's CU may not be the same as CU.
15993          Ensure TYPE is recorded with CU in die_type_hash.  */
15994       return set_die_type (die, type, cu);
15995     }
15996
15997   type = alloc_type (objfile);
15998
15999   TYPE_CODE (type) = TYPE_CODE_ENUM;
16000   name = dwarf2_full_name (NULL, die, cu);
16001   if (name != NULL)
16002     TYPE_NAME (type) = name;
16003
16004   attr = dwarf2_attr (die, DW_AT_type, cu);
16005   if (attr != NULL)
16006     {
16007       struct type *underlying_type = die_type (die, cu);
16008
16009       TYPE_TARGET_TYPE (type) = underlying_type;
16010     }
16011
16012   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16013   if (attr != nullptr)
16014     {
16015       TYPE_LENGTH (type) = DW_UNSND (attr);
16016     }
16017   else
16018     {
16019       TYPE_LENGTH (type) = 0;
16020     }
16021
16022   maybe_set_alignment (cu, die, type);
16023
16024   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16025      declared as private in the package spec, and then defined only
16026      inside the package body.  Such types are known as Taft Amendment
16027      Types.  When another package uses such a type, an incomplete DIE
16028      may be generated by the compiler.  */
16029   if (die_is_declaration (die, cu))
16030     TYPE_STUB (type) = 1;
16031
16032   /* Finish the creation of this type by using the enum's children.
16033      We must call this even when the underlying type has been provided
16034      so that we can determine if we're looking at a "flag" enum.  */
16035   update_enumeration_type_from_children (die, type, cu);
16036
16037   /* If this type has an underlying type that is not a stub, then we
16038      may use its attributes.  We always use the "unsigned" attribute
16039      in this situation, because ordinarily we guess whether the type
16040      is unsigned -- but the guess can be wrong and the underlying type
16041      can tell us the reality.  However, we defer to a local size
16042      attribute if one exists, because this lets the compiler override
16043      the underlying type if needed.  */
16044   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16045     {
16046       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16047       if (TYPE_LENGTH (type) == 0)
16048         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16049       if (TYPE_RAW_ALIGN (type) == 0
16050           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16051         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16052     }
16053
16054   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16055
16056   return set_die_type (die, type, cu);
16057 }
16058
16059 /* Given a pointer to a die which begins an enumeration, process all
16060    the dies that define the members of the enumeration, and create the
16061    symbol for the enumeration type.
16062
16063    NOTE: We reverse the order of the element list.  */
16064
16065 static void
16066 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16067 {
16068   struct type *this_type;
16069
16070   this_type = get_die_type (die, cu);
16071   if (this_type == NULL)
16072     this_type = read_enumeration_type (die, cu);
16073
16074   if (die->child != NULL)
16075     {
16076       struct die_info *child_die;
16077       struct symbol *sym;
16078       std::vector<struct field> fields;
16079       const char *name;
16080
16081       child_die = die->child;
16082       while (child_die && child_die->tag)
16083         {
16084           if (child_die->tag != DW_TAG_enumerator)
16085             {
16086               process_die (child_die, cu);
16087             }
16088           else
16089             {
16090               name = dwarf2_name (child_die, cu);
16091               if (name)
16092                 {
16093                   sym = new_symbol (child_die, this_type, cu);
16094
16095                   fields.emplace_back ();
16096                   struct field &field = fields.back ();
16097
16098                   FIELD_NAME (field) = sym->linkage_name ();
16099                   FIELD_TYPE (field) = NULL;
16100                   SET_FIELD_ENUMVAL (field, SYMBOL_VALUE (sym));
16101                   FIELD_BITSIZE (field) = 0;
16102                 }
16103             }
16104
16105           child_die = sibling_die (child_die);
16106         }
16107
16108       if (!fields.empty ())
16109         {
16110           TYPE_NFIELDS (this_type) = fields.size ();
16111           TYPE_FIELDS (this_type) = (struct field *)
16112             TYPE_ALLOC (this_type, sizeof (struct field) * fields.size ());
16113           memcpy (TYPE_FIELDS (this_type), fields.data (),
16114                   sizeof (struct field) * fields.size ());
16115         }
16116     }
16117
16118   /* If we are reading an enum from a .debug_types unit, and the enum
16119      is a declaration, and the enum is not the signatured type in the
16120      unit, then we do not want to add a symbol for it.  Adding a
16121      symbol would in some cases obscure the true definition of the
16122      enum, giving users an incomplete type when the definition is
16123      actually available.  Note that we do not want to do this for all
16124      enums which are just declarations, because C++0x allows forward
16125      enum declarations.  */
16126   if (cu->per_cu->is_debug_types
16127       && die_is_declaration (die, cu))
16128     {
16129       struct signatured_type *sig_type;
16130
16131       sig_type = (struct signatured_type *) cu->per_cu;
16132       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16133       if (sig_type->type_offset_in_section != die->sect_off)
16134         return;
16135     }
16136
16137   new_symbol (die, this_type, cu);
16138 }
16139
16140 /* Extract all information from a DW_TAG_array_type DIE and put it in
16141    the DIE's type field.  For now, this only handles one dimensional
16142    arrays.  */
16143
16144 static struct type *
16145 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16146 {
16147   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16148   struct die_info *child_die;
16149   struct type *type;
16150   struct type *element_type, *range_type, *index_type;
16151   struct attribute *attr;
16152   const char *name;
16153   struct dynamic_prop *byte_stride_prop = NULL;
16154   unsigned int bit_stride = 0;
16155
16156   element_type = die_type (die, cu);
16157
16158   /* The die_type call above may have already set the type for this DIE.  */
16159   type = get_die_type (die, cu);
16160   if (type)
16161     return type;
16162
16163   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16164   if (attr != NULL)
16165     {
16166       int stride_ok;
16167       struct type *prop_type
16168         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
16169
16170       byte_stride_prop
16171         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16172       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop,
16173                                         prop_type);
16174       if (!stride_ok)
16175         {
16176           complaint (_("unable to read array DW_AT_byte_stride "
16177                        " - DIE at %s [in module %s]"),
16178                      sect_offset_str (die->sect_off),
16179                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16180           /* Ignore this attribute.  We will likely not be able to print
16181              arrays of this type correctly, but there is little we can do
16182              to help if we cannot read the attribute's value.  */
16183           byte_stride_prop = NULL;
16184         }
16185     }
16186
16187   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16188   if (attr != NULL)
16189     bit_stride = DW_UNSND (attr);
16190
16191   /* Irix 6.2 native cc creates array types without children for
16192      arrays with unspecified length.  */
16193   if (die->child == NULL)
16194     {
16195       index_type = objfile_type (objfile)->builtin_int;
16196       range_type = create_static_range_type (NULL, index_type, 0, -1);
16197       type = create_array_type_with_stride (NULL, element_type, range_type,
16198                                             byte_stride_prop, bit_stride);
16199       return set_die_type (die, type, cu);
16200     }
16201
16202   std::vector<struct type *> range_types;
16203   child_die = die->child;
16204   while (child_die && child_die->tag)
16205     {
16206       if (child_die->tag == DW_TAG_subrange_type)
16207         {
16208           struct type *child_type = read_type_die (child_die, cu);
16209
16210           if (child_type != NULL)
16211             {
16212               /* The range type was succesfully read.  Save it for the
16213                  array type creation.  */
16214               range_types.push_back (child_type);
16215             }
16216         }
16217       child_die = sibling_die (child_die);
16218     }
16219
16220   /* Dwarf2 dimensions are output from left to right, create the
16221      necessary array types in backwards order.  */
16222
16223   type = element_type;
16224
16225   if (read_array_order (die, cu) == DW_ORD_col_major)
16226     {
16227       int i = 0;
16228
16229       while (i < range_types.size ())
16230         type = create_array_type_with_stride (NULL, type, range_types[i++],
16231                                               byte_stride_prop, bit_stride);
16232     }
16233   else
16234     {
16235       size_t ndim = range_types.size ();
16236       while (ndim-- > 0)
16237         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16238                                               byte_stride_prop, bit_stride);
16239     }
16240
16241   /* Understand Dwarf2 support for vector types (like they occur on
16242      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16243      array type.  This is not part of the Dwarf2/3 standard yet, but a
16244      custom vendor extension.  The main difference between a regular
16245      array and the vector variant is that vectors are passed by value
16246      to functions.  */
16247   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16248   if (attr != nullptr)
16249     make_vector_type (type);
16250
16251   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16252      implementation may choose to implement triple vectors using this
16253      attribute.  */
16254   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16255   if (attr != nullptr)
16256     {
16257       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16258         TYPE_LENGTH (type) = DW_UNSND (attr);
16259       else
16260         complaint (_("DW_AT_byte_size for array type smaller "
16261                      "than the total size of elements"));
16262     }
16263
16264   name = dwarf2_name (die, cu);
16265   if (name)
16266     TYPE_NAME (type) = name;
16267
16268   maybe_set_alignment (cu, die, type);
16269
16270   /* Install the type in the die.  */
16271   set_die_type (die, type, cu);
16272
16273   /* set_die_type should be already done.  */
16274   set_descriptive_type (type, die, cu);
16275
16276   return type;
16277 }
16278
16279 static enum dwarf_array_dim_ordering
16280 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16281 {
16282   struct attribute *attr;
16283
16284   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16285
16286   if (attr != nullptr)
16287     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16288
16289   /* GNU F77 is a special case, as at 08/2004 array type info is the
16290      opposite order to the dwarf2 specification, but data is still
16291      laid out as per normal fortran.
16292
16293      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16294      version checking.  */
16295
16296   if (cu->language == language_fortran
16297       && cu->producer && strstr (cu->producer, "GNU F77"))
16298     {
16299       return DW_ORD_row_major;
16300     }
16301
16302   switch (cu->language_defn->la_array_ordering)
16303     {
16304     case array_column_major:
16305       return DW_ORD_col_major;
16306     case array_row_major:
16307     default:
16308       return DW_ORD_row_major;
16309     };
16310 }
16311
16312 /* Extract all information from a DW_TAG_set_type DIE and put it in
16313    the DIE's type field.  */
16314
16315 static struct type *
16316 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16317 {
16318   struct type *domain_type, *set_type;
16319   struct attribute *attr;
16320
16321   domain_type = die_type (die, cu);
16322
16323   /* The die_type call above may have already set the type for this DIE.  */
16324   set_type = get_die_type (die, cu);
16325   if (set_type)
16326     return set_type;
16327
16328   set_type = create_set_type (NULL, domain_type);
16329
16330   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16331   if (attr != nullptr)
16332     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16333
16334   maybe_set_alignment (cu, die, set_type);
16335
16336   return set_die_type (die, set_type, cu);
16337 }
16338
16339 /* A helper for read_common_block that creates a locexpr baton.
16340    SYM is the symbol which we are marking as computed.
16341    COMMON_DIE is the DIE for the common block.
16342    COMMON_LOC is the location expression attribute for the common
16343    block itself.
16344    MEMBER_LOC is the location expression attribute for the particular
16345    member of the common block that we are processing.
16346    CU is the CU from which the above come.  */
16347
16348 static void
16349 mark_common_block_symbol_computed (struct symbol *sym,
16350                                    struct die_info *common_die,
16351                                    struct attribute *common_loc,
16352                                    struct attribute *member_loc,
16353                                    struct dwarf2_cu *cu)
16354 {
16355   struct dwarf2_per_objfile *dwarf2_per_objfile
16356     = cu->per_cu->dwarf2_per_objfile;
16357   struct objfile *objfile = dwarf2_per_objfile->objfile;
16358   struct dwarf2_locexpr_baton *baton;
16359   gdb_byte *ptr;
16360   unsigned int cu_off;
16361   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16362   LONGEST offset = 0;
16363
16364   gdb_assert (common_loc && member_loc);
16365   gdb_assert (common_loc->form_is_block ());
16366   gdb_assert (member_loc->form_is_block ()
16367               || member_loc->form_is_constant ());
16368
16369   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16370   baton->per_cu = cu->per_cu;
16371   gdb_assert (baton->per_cu);
16372
16373   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16374
16375   if (member_loc->form_is_constant ())
16376     {
16377       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16378       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16379     }
16380   else
16381     baton->size += DW_BLOCK (member_loc)->size;
16382
16383   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16384   baton->data = ptr;
16385
16386   *ptr++ = DW_OP_call4;
16387   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16388   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16389   ptr += 4;
16390
16391   if (member_loc->form_is_constant ())
16392     {
16393       *ptr++ = DW_OP_addr;
16394       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16395       ptr += cu->header.addr_size;
16396     }
16397   else
16398     {
16399       /* We have to copy the data here, because DW_OP_call4 will only
16400          use a DW_AT_location attribute.  */
16401       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16402       ptr += DW_BLOCK (member_loc)->size;
16403     }
16404
16405   *ptr++ = DW_OP_plus;
16406   gdb_assert (ptr - baton->data == baton->size);
16407
16408   SYMBOL_LOCATION_BATON (sym) = baton;
16409   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16410 }
16411
16412 /* Create appropriate locally-scoped variables for all the
16413    DW_TAG_common_block entries.  Also create a struct common_block
16414    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16415    is used to separate the common blocks name namespace from regular
16416    variable names.  */
16417
16418 static void
16419 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16420 {
16421   struct attribute *attr;
16422
16423   attr = dwarf2_attr (die, DW_AT_location, cu);
16424   if (attr != nullptr)
16425     {
16426       /* Support the .debug_loc offsets.  */
16427       if (attr->form_is_block ())
16428         {
16429           /* Ok.  */
16430         }
16431       else if (attr->form_is_section_offset ())
16432         {
16433           dwarf2_complex_location_expr_complaint ();
16434           attr = NULL;
16435         }
16436       else
16437         {
16438           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16439                                                  "common block member");
16440           attr = NULL;
16441         }
16442     }
16443
16444   if (die->child != NULL)
16445     {
16446       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16447       struct die_info *child_die;
16448       size_t n_entries = 0, size;
16449       struct common_block *common_block;
16450       struct symbol *sym;
16451
16452       for (child_die = die->child;
16453            child_die && child_die->tag;
16454            child_die = sibling_die (child_die))
16455         ++n_entries;
16456
16457       size = (sizeof (struct common_block)
16458               + (n_entries - 1) * sizeof (struct symbol *));
16459       common_block
16460         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16461                                                  size);
16462       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16463       common_block->n_entries = 0;
16464
16465       for (child_die = die->child;
16466            child_die && child_die->tag;
16467            child_die = sibling_die (child_die))
16468         {
16469           /* Create the symbol in the DW_TAG_common_block block in the current
16470              symbol scope.  */
16471           sym = new_symbol (child_die, NULL, cu);
16472           if (sym != NULL)
16473             {
16474               struct attribute *member_loc;
16475
16476               common_block->contents[common_block->n_entries++] = sym;
16477
16478               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16479                                         cu);
16480               if (member_loc)
16481                 {
16482                   /* GDB has handled this for a long time, but it is
16483                      not specified by DWARF.  It seems to have been
16484                      emitted by gfortran at least as recently as:
16485                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16486                   complaint (_("Variable in common block has "
16487                                "DW_AT_data_member_location "
16488                                "- DIE at %s [in module %s]"),
16489                                sect_offset_str (child_die->sect_off),
16490                              objfile_name (objfile));
16491
16492                   if (member_loc->form_is_section_offset ())
16493                     dwarf2_complex_location_expr_complaint ();
16494                   else if (member_loc->form_is_constant ()
16495                            || member_loc->form_is_block ())
16496                     {
16497                       if (attr != nullptr)
16498                         mark_common_block_symbol_computed (sym, die, attr,
16499                                                            member_loc, cu);
16500                     }
16501                   else
16502                     dwarf2_complex_location_expr_complaint ();
16503                 }
16504             }
16505         }
16506
16507       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16508       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16509     }
16510 }
16511
16512 /* Create a type for a C++ namespace.  */
16513
16514 static struct type *
16515 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16516 {
16517   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16518   const char *previous_prefix, *name;
16519   int is_anonymous;
16520   struct type *type;
16521
16522   /* For extensions, reuse the type of the original namespace.  */
16523   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16524     {
16525       struct die_info *ext_die;
16526       struct dwarf2_cu *ext_cu = cu;
16527
16528       ext_die = dwarf2_extension (die, &ext_cu);
16529       type = read_type_die (ext_die, ext_cu);
16530
16531       /* EXT_CU may not be the same as CU.
16532          Ensure TYPE is recorded with CU in die_type_hash.  */
16533       return set_die_type (die, type, cu);
16534     }
16535
16536   name = namespace_name (die, &is_anonymous, cu);
16537
16538   /* Now build the name of the current namespace.  */
16539
16540   previous_prefix = determine_prefix (die, cu);
16541   if (previous_prefix[0] != '\0')
16542     name = typename_concat (&objfile->objfile_obstack,
16543                             previous_prefix, name, 0, cu);
16544
16545   /* Create the type.  */
16546   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16547
16548   return set_die_type (die, type, cu);
16549 }
16550
16551 /* Read a namespace scope.  */
16552
16553 static void
16554 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16555 {
16556   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16557   int is_anonymous;
16558
16559   /* Add a symbol associated to this if we haven't seen the namespace
16560      before.  Also, add a using directive if it's an anonymous
16561      namespace.  */
16562
16563   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16564     {
16565       struct type *type;
16566
16567       type = read_type_die (die, cu);
16568       new_symbol (die, type, cu);
16569
16570       namespace_name (die, &is_anonymous, cu);
16571       if (is_anonymous)
16572         {
16573           const char *previous_prefix = determine_prefix (die, cu);
16574
16575           std::vector<const char *> excludes;
16576           add_using_directive (using_directives (cu),
16577                                previous_prefix, TYPE_NAME (type), NULL,
16578                                NULL, excludes, 0, &objfile->objfile_obstack);
16579         }
16580     }
16581
16582   if (die->child != NULL)
16583     {
16584       struct die_info *child_die = die->child;
16585
16586       while (child_die && child_die->tag)
16587         {
16588           process_die (child_die, cu);
16589           child_die = sibling_die (child_die);
16590         }
16591     }
16592 }
16593
16594 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16595    imported module.  Still we need that type as local Fortran "use ... only"
16596    declaration imports depend on the created type in determine_prefix.  */
16597
16598 static struct type *
16599 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16600 {
16601   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16602   const char *module_name;
16603   struct type *type;
16604
16605   module_name = dwarf2_name (die, cu);
16606   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16607
16608   return set_die_type (die, type, cu);
16609 }
16610
16611 /* Read a Fortran module.  */
16612
16613 static void
16614 read_module (struct die_info *die, struct dwarf2_cu *cu)
16615 {
16616   struct die_info *child_die = die->child;
16617   struct type *type;
16618
16619   type = read_type_die (die, cu);
16620   new_symbol (die, type, cu);
16621
16622   while (child_die && child_die->tag)
16623     {
16624       process_die (child_die, cu);
16625       child_die = sibling_die (child_die);
16626     }
16627 }
16628
16629 /* Return the name of the namespace represented by DIE.  Set
16630    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16631    namespace.  */
16632
16633 static const char *
16634 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16635 {
16636   struct die_info *current_die;
16637   const char *name = NULL;
16638
16639   /* Loop through the extensions until we find a name.  */
16640
16641   for (current_die = die;
16642        current_die != NULL;
16643        current_die = dwarf2_extension (die, &cu))
16644     {
16645       /* We don't use dwarf2_name here so that we can detect the absence
16646          of a name -> anonymous namespace.  */
16647       name = dwarf2_string_attr (die, DW_AT_name, cu);
16648
16649       if (name != NULL)
16650         break;
16651     }
16652
16653   /* Is it an anonymous namespace?  */
16654
16655   *is_anonymous = (name == NULL);
16656   if (*is_anonymous)
16657     name = CP_ANONYMOUS_NAMESPACE_STR;
16658
16659   return name;
16660 }
16661
16662 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16663    the user defined type vector.  */
16664
16665 static struct type *
16666 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16667 {
16668   struct gdbarch *gdbarch
16669     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16670   struct comp_unit_head *cu_header = &cu->header;
16671   struct type *type;
16672   struct attribute *attr_byte_size;
16673   struct attribute *attr_address_class;
16674   int byte_size, addr_class;
16675   struct type *target_type;
16676
16677   target_type = die_type (die, cu);
16678
16679   /* The die_type call above may have already set the type for this DIE.  */
16680   type = get_die_type (die, cu);
16681   if (type)
16682     return type;
16683
16684   type = lookup_pointer_type (target_type);
16685
16686   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16687   if (attr_byte_size)
16688     byte_size = DW_UNSND (attr_byte_size);
16689   else
16690     byte_size = cu_header->addr_size;
16691
16692   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16693   if (attr_address_class)
16694     addr_class = DW_UNSND (attr_address_class);
16695   else
16696     addr_class = DW_ADDR_none;
16697
16698   ULONGEST alignment = get_alignment (cu, die);
16699
16700   /* If the pointer size, alignment, or address class is different
16701      than the default, create a type variant marked as such and set
16702      the length accordingly.  */
16703   if (TYPE_LENGTH (type) != byte_size
16704       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16705           && alignment != TYPE_RAW_ALIGN (type))
16706       || addr_class != DW_ADDR_none)
16707     {
16708       if (gdbarch_address_class_type_flags_p (gdbarch))
16709         {
16710           int type_flags;
16711
16712           type_flags = gdbarch_address_class_type_flags
16713                          (gdbarch, byte_size, addr_class);
16714           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16715                       == 0);
16716           type = make_type_with_address_space (type, type_flags);
16717         }
16718       else if (TYPE_LENGTH (type) != byte_size)
16719         {
16720           complaint (_("invalid pointer size %d"), byte_size);
16721         }
16722       else if (TYPE_RAW_ALIGN (type) != alignment)
16723         {
16724           complaint (_("Invalid DW_AT_alignment"
16725                        " - DIE at %s [in module %s]"),
16726                      sect_offset_str (die->sect_off),
16727                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16728         }
16729       else
16730         {
16731           /* Should we also complain about unhandled address classes?  */
16732         }
16733     }
16734
16735   TYPE_LENGTH (type) = byte_size;
16736   set_type_align (type, alignment);
16737   return set_die_type (die, type, cu);
16738 }
16739
16740 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16741    the user defined type vector.  */
16742
16743 static struct type *
16744 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16745 {
16746   struct type *type;
16747   struct type *to_type;
16748   struct type *domain;
16749
16750   to_type = die_type (die, cu);
16751   domain = die_containing_type (die, cu);
16752
16753   /* The calls above may have already set the type for this DIE.  */
16754   type = get_die_type (die, cu);
16755   if (type)
16756     return type;
16757
16758   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16759     type = lookup_methodptr_type (to_type);
16760   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16761     {
16762       struct type *new_type
16763         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16764
16765       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16766                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16767                             TYPE_VARARGS (to_type));
16768       type = lookup_methodptr_type (new_type);
16769     }
16770   else
16771     type = lookup_memberptr_type (to_type, domain);
16772
16773   return set_die_type (die, type, cu);
16774 }
16775
16776 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16777    the user defined type vector.  */
16778
16779 static struct type *
16780 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16781                           enum type_code refcode)
16782 {
16783   struct comp_unit_head *cu_header = &cu->header;
16784   struct type *type, *target_type;
16785   struct attribute *attr;
16786
16787   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16788
16789   target_type = die_type (die, cu);
16790
16791   /* The die_type call above may have already set the type for this DIE.  */
16792   type = get_die_type (die, cu);
16793   if (type)
16794     return type;
16795
16796   type = lookup_reference_type (target_type, refcode);
16797   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16798   if (attr != nullptr)
16799     {
16800       TYPE_LENGTH (type) = DW_UNSND (attr);
16801     }
16802   else
16803     {
16804       TYPE_LENGTH (type) = cu_header->addr_size;
16805     }
16806   maybe_set_alignment (cu, die, type);
16807   return set_die_type (die, type, cu);
16808 }
16809
16810 /* Add the given cv-qualifiers to the element type of the array.  GCC
16811    outputs DWARF type qualifiers that apply to an array, not the
16812    element type.  But GDB relies on the array element type to carry
16813    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16814    specification.  */
16815
16816 static struct type *
16817 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16818                    struct type *base_type, int cnst, int voltl)
16819 {
16820   struct type *el_type, *inner_array;
16821
16822   base_type = copy_type (base_type);
16823   inner_array = base_type;
16824
16825   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16826     {
16827       TYPE_TARGET_TYPE (inner_array) =
16828         copy_type (TYPE_TARGET_TYPE (inner_array));
16829       inner_array = TYPE_TARGET_TYPE (inner_array);
16830     }
16831
16832   el_type = TYPE_TARGET_TYPE (inner_array);
16833   cnst |= TYPE_CONST (el_type);
16834   voltl |= TYPE_VOLATILE (el_type);
16835   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16836
16837   return set_die_type (die, base_type, cu);
16838 }
16839
16840 static struct type *
16841 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16842 {
16843   struct type *base_type, *cv_type;
16844
16845   base_type = die_type (die, cu);
16846
16847   /* The die_type call above may have already set the type for this DIE.  */
16848   cv_type = get_die_type (die, cu);
16849   if (cv_type)
16850     return cv_type;
16851
16852   /* In case the const qualifier is applied to an array type, the element type
16853      is so qualified, not the array type (section 6.7.3 of C99).  */
16854   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16855     return add_array_cv_type (die, cu, base_type, 1, 0);
16856
16857   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16858   return set_die_type (die, cv_type, cu);
16859 }
16860
16861 static struct type *
16862 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16863 {
16864   struct type *base_type, *cv_type;
16865
16866   base_type = die_type (die, cu);
16867
16868   /* The die_type call above may have already set the type for this DIE.  */
16869   cv_type = get_die_type (die, cu);
16870   if (cv_type)
16871     return cv_type;
16872
16873   /* In case the volatile qualifier is applied to an array type, the
16874      element type is so qualified, not the array type (section 6.7.3
16875      of C99).  */
16876   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16877     return add_array_cv_type (die, cu, base_type, 0, 1);
16878
16879   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
16880   return set_die_type (die, cv_type, cu);
16881 }
16882
16883 /* Handle DW_TAG_restrict_type.  */
16884
16885 static struct type *
16886 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
16887 {
16888   struct type *base_type, *cv_type;
16889
16890   base_type = die_type (die, cu);
16891
16892   /* The die_type call above may have already set the type for this DIE.  */
16893   cv_type = get_die_type (die, cu);
16894   if (cv_type)
16895     return cv_type;
16896
16897   cv_type = make_restrict_type (base_type);
16898   return set_die_type (die, cv_type, cu);
16899 }
16900
16901 /* Handle DW_TAG_atomic_type.  */
16902
16903 static struct type *
16904 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
16905 {
16906   struct type *base_type, *cv_type;
16907
16908   base_type = die_type (die, cu);
16909
16910   /* The die_type call above may have already set the type for this DIE.  */
16911   cv_type = get_die_type (die, cu);
16912   if (cv_type)
16913     return cv_type;
16914
16915   cv_type = make_atomic_type (base_type);
16916   return set_die_type (die, cv_type, cu);
16917 }
16918
16919 /* Extract all information from a DW_TAG_string_type DIE and add to
16920    the user defined type vector.  It isn't really a user defined type,
16921    but it behaves like one, with other DIE's using an AT_user_def_type
16922    attribute to reference it.  */
16923
16924 static struct type *
16925 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
16926 {
16927   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16928   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16929   struct type *type, *range_type, *index_type, *char_type;
16930   struct attribute *attr;
16931   struct dynamic_prop prop;
16932   bool length_is_constant = true;
16933   LONGEST length;
16934
16935   /* There are a couple of places where bit sizes might be made use of
16936      when parsing a DW_TAG_string_type, however, no producer that we know
16937      of make use of these.  Handling bit sizes that are a multiple of the
16938      byte size is easy enough, but what about other bit sizes?  Lets deal
16939      with that problem when we have to.  Warn about these attributes being
16940      unsupported, then parse the type and ignore them like we always
16941      have.  */
16942   if (dwarf2_attr (die, DW_AT_bit_size, cu) != nullptr
16943       || dwarf2_attr (die, DW_AT_string_length_bit_size, cu) != nullptr)
16944     {
16945       static bool warning_printed = false;
16946       if (!warning_printed)
16947         {
16948           warning (_("DW_AT_bit_size and DW_AT_string_length_bit_size not "
16949                      "currently supported on DW_TAG_string_type."));
16950           warning_printed = true;
16951         }
16952     }
16953
16954   attr = dwarf2_attr (die, DW_AT_string_length, cu);
16955   if (attr != nullptr && !attr->form_is_constant ())
16956     {
16957       /* The string length describes the location at which the length of
16958          the string can be found.  The size of the length field can be
16959          specified with one of the attributes below.  */
16960       struct type *prop_type;
16961       struct attribute *len
16962         = dwarf2_attr (die, DW_AT_string_length_byte_size, cu);
16963       if (len == nullptr)
16964         len = dwarf2_attr (die, DW_AT_byte_size, cu);
16965       if (len != nullptr && len->form_is_constant ())
16966         {
16967           /* Pass 0 as the default as we know this attribute is constant
16968              and the default value will not be returned.  */
16969           LONGEST sz = dwarf2_get_attr_constant_value (len, 0);
16970           prop_type = dwarf2_per_cu_int_type (cu->per_cu, sz, true);
16971         }
16972       else
16973         {
16974           /* If the size is not specified then we assume it is the size of
16975              an address on this target.  */
16976           prop_type = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, true);
16977         }
16978
16979       /* Convert the attribute into a dynamic property.  */
16980       if (!attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
16981         length = 1;
16982       else
16983         length_is_constant = false;
16984     }
16985   else if (attr != nullptr)
16986     {
16987       /* This DW_AT_string_length just contains the length with no
16988          indirection.  There's no need to create a dynamic property in this
16989          case.  Pass 0 for the default value as we know it will not be
16990          returned in this case.  */
16991       length = dwarf2_get_attr_constant_value (attr, 0);
16992     }
16993   else if ((attr = dwarf2_attr (die, DW_AT_byte_size, cu)) != nullptr)
16994     {
16995       /* We don't currently support non-constant byte sizes for strings.  */
16996       length = dwarf2_get_attr_constant_value (attr, 1);
16997     }
16998   else
16999     {
17000       /* Use 1 as a fallback length if we have nothing else.  */
17001       length = 1;
17002     }
17003
17004   index_type = objfile_type (objfile)->builtin_int;
17005   if (length_is_constant)
17006     range_type = create_static_range_type (NULL, index_type, 1, length);
17007   else
17008     {
17009       struct dynamic_prop low_bound;
17010
17011       low_bound.kind = PROP_CONST;
17012       low_bound.data.const_val = 1;
17013       range_type = create_range_type (NULL, index_type, &low_bound, &prop, 0);
17014     }
17015   char_type = language_string_char_type (cu->language_defn, gdbarch);
17016   type = create_string_type (NULL, char_type, range_type);
17017
17018   return set_die_type (die, type, cu);
17019 }
17020
17021 /* Assuming that DIE corresponds to a function, returns nonzero
17022    if the function is prototyped.  */
17023
17024 static int
17025 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17026 {
17027   struct attribute *attr;
17028
17029   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17030   if (attr && (DW_UNSND (attr) != 0))
17031     return 1;
17032
17033   /* The DWARF standard implies that the DW_AT_prototyped attribute
17034      is only meaningful for C, but the concept also extends to other
17035      languages that allow unprototyped functions (Eg: Objective C).
17036      For all other languages, assume that functions are always
17037      prototyped.  */
17038   if (cu->language != language_c
17039       && cu->language != language_objc
17040       && cu->language != language_opencl)
17041     return 1;
17042
17043   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17044      prototyped and unprototyped functions; default to prototyped,
17045      since that is more common in modern code (and RealView warns
17046      about unprototyped functions).  */
17047   if (producer_is_realview (cu->producer))
17048     return 1;
17049
17050   return 0;
17051 }
17052
17053 /* Handle DIES due to C code like:
17054
17055    struct foo
17056    {
17057    int (*funcp)(int a, long l);
17058    int b;
17059    };
17060
17061    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17062
17063 static struct type *
17064 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17065 {
17066   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17067   struct type *type;            /* Type that this function returns.  */
17068   struct type *ftype;           /* Function that returns above type.  */
17069   struct attribute *attr;
17070
17071   type = die_type (die, cu);
17072
17073   /* The die_type call above may have already set the type for this DIE.  */
17074   ftype = get_die_type (die, cu);
17075   if (ftype)
17076     return ftype;
17077
17078   ftype = lookup_function_type (type);
17079
17080   if (prototyped_function_p (die, cu))
17081     TYPE_PROTOTYPED (ftype) = 1;
17082
17083   /* Store the calling convention in the type if it's available in
17084      the subroutine die.  Otherwise set the calling convention to
17085      the default value DW_CC_normal.  */
17086   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17087   if (attr != nullptr
17088       && is_valid_DW_AT_calling_convention_for_subroutine (DW_UNSND (attr)))
17089     TYPE_CALLING_CONVENTION (ftype)
17090       = (enum dwarf_calling_convention) (DW_UNSND (attr));
17091   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17092     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17093   else
17094     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17095
17096   /* Record whether the function returns normally to its caller or not
17097      if the DWARF producer set that information.  */
17098   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17099   if (attr && (DW_UNSND (attr) != 0))
17100     TYPE_NO_RETURN (ftype) = 1;
17101
17102   /* We need to add the subroutine type to the die immediately so
17103      we don't infinitely recurse when dealing with parameters
17104      declared as the same subroutine type.  */
17105   set_die_type (die, ftype, cu);
17106
17107   if (die->child != NULL)
17108     {
17109       struct type *void_type = objfile_type (objfile)->builtin_void;
17110       struct die_info *child_die;
17111       int nparams, iparams;
17112
17113       /* Count the number of parameters.
17114          FIXME: GDB currently ignores vararg functions, but knows about
17115          vararg member functions.  */
17116       nparams = 0;
17117       child_die = die->child;
17118       while (child_die && child_die->tag)
17119         {
17120           if (child_die->tag == DW_TAG_formal_parameter)
17121             nparams++;
17122           else if (child_die->tag == DW_TAG_unspecified_parameters)
17123             TYPE_VARARGS (ftype) = 1;
17124           child_die = sibling_die (child_die);
17125         }
17126
17127       /* Allocate storage for parameters and fill them in.  */
17128       TYPE_NFIELDS (ftype) = nparams;
17129       TYPE_FIELDS (ftype) = (struct field *)
17130         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17131
17132       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17133          even if we error out during the parameters reading below.  */
17134       for (iparams = 0; iparams < nparams; iparams++)
17135         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17136
17137       iparams = 0;
17138       child_die = die->child;
17139       while (child_die && child_die->tag)
17140         {
17141           if (child_die->tag == DW_TAG_formal_parameter)
17142             {
17143               struct type *arg_type;
17144
17145               /* DWARF version 2 has no clean way to discern C++
17146                  static and non-static member functions.  G++ helps
17147                  GDB by marking the first parameter for non-static
17148                  member functions (which is the this pointer) as
17149                  artificial.  We pass this information to
17150                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17151
17152                  DWARF version 3 added DW_AT_object_pointer, which GCC
17153                  4.5 does not yet generate.  */
17154               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17155               if (attr != nullptr)
17156                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17157               else
17158                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17159               arg_type = die_type (child_die, cu);
17160
17161               /* RealView does not mark THIS as const, which the testsuite
17162                  expects.  GCC marks THIS as const in method definitions,
17163                  but not in the class specifications (GCC PR 43053).  */
17164               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17165                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17166                 {
17167                   int is_this = 0;
17168                   struct dwarf2_cu *arg_cu = cu;
17169                   const char *name = dwarf2_name (child_die, cu);
17170
17171                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17172                   if (attr != nullptr)
17173                     {
17174                       /* If the compiler emits this, use it.  */
17175                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17176                         is_this = 1;
17177                     }
17178                   else if (name && strcmp (name, "this") == 0)
17179                     /* Function definitions will have the argument names.  */
17180                     is_this = 1;
17181                   else if (name == NULL && iparams == 0)
17182                     /* Declarations may not have the names, so like
17183                        elsewhere in GDB, assume an artificial first
17184                        argument is "this".  */
17185                     is_this = 1;
17186
17187                   if (is_this)
17188                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17189                                              arg_type, 0);
17190                 }
17191
17192               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17193               iparams++;
17194             }
17195           child_die = sibling_die (child_die);
17196         }
17197     }
17198
17199   return ftype;
17200 }
17201
17202 static struct type *
17203 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17204 {
17205   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17206   const char *name = NULL;
17207   struct type *this_type, *target_type;
17208
17209   name = dwarf2_full_name (NULL, die, cu);
17210   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17211   TYPE_TARGET_STUB (this_type) = 1;
17212   set_die_type (die, this_type, cu);
17213   target_type = die_type (die, cu);
17214   if (target_type != this_type)
17215     TYPE_TARGET_TYPE (this_type) = target_type;
17216   else
17217     {
17218       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17219          spec and cause infinite loops in GDB.  */
17220       complaint (_("Self-referential DW_TAG_typedef "
17221                    "- DIE at %s [in module %s]"),
17222                  sect_offset_str (die->sect_off), objfile_name (objfile));
17223       TYPE_TARGET_TYPE (this_type) = NULL;
17224     }
17225   return this_type;
17226 }
17227
17228 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17229    (which may be different from NAME) to the architecture back-end to allow
17230    it to guess the correct format if necessary.  */
17231
17232 static struct type *
17233 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17234                         const char *name_hint, enum bfd_endian byte_order)
17235 {
17236   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17237   const struct floatformat **format;
17238   struct type *type;
17239
17240   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17241   if (format)
17242     type = init_float_type (objfile, bits, name, format, byte_order);
17243   else
17244     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17245
17246   return type;
17247 }
17248
17249 /* Allocate an integer type of size BITS and name NAME.  */
17250
17251 static struct type *
17252 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17253                           int bits, int unsigned_p, const char *name)
17254 {
17255   struct type *type;
17256
17257   /* Versions of Intel's C Compiler generate an integer type called "void"
17258      instead of using DW_TAG_unspecified_type.  This has been seen on
17259      at least versions 14, 17, and 18.  */
17260   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17261       && strcmp (name, "void") == 0)
17262     type = objfile_type (objfile)->builtin_void;
17263   else
17264     type = init_integer_type (objfile, bits, unsigned_p, name);
17265
17266   return type;
17267 }
17268
17269 /* Initialise and return a floating point type of size BITS suitable for
17270    use as a component of a complex number.  The NAME_HINT is passed through
17271    when initialising the floating point type and is the name of the complex
17272    type.
17273
17274    As DWARF doesn't currently provide an explicit name for the components
17275    of a complex number, but it can be helpful to have these components
17276    named, we try to select a suitable name based on the size of the
17277    component.  */
17278 static struct type *
17279 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
17280                                  struct objfile *objfile,
17281                                  int bits, const char *name_hint,
17282                                  enum bfd_endian byte_order)
17283 {
17284   gdbarch *gdbarch = get_objfile_arch (objfile);
17285   struct type *tt = nullptr;
17286
17287   /* Try to find a suitable floating point builtin type of size BITS.
17288      We're going to use the name of this type as the name for the complex
17289      target type that we are about to create.  */
17290   switch (cu->language)
17291     {
17292     case language_fortran:
17293       switch (bits)
17294         {
17295         case 32:
17296           tt = builtin_f_type (gdbarch)->builtin_real;
17297           break;
17298         case 64:
17299           tt = builtin_f_type (gdbarch)->builtin_real_s8;
17300           break;
17301         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17302         case 128:
17303           tt = builtin_f_type (gdbarch)->builtin_real_s16;
17304           break;
17305         }
17306       break;
17307     default:
17308       switch (bits)
17309         {
17310         case 32:
17311           tt = builtin_type (gdbarch)->builtin_float;
17312           break;
17313         case 64:
17314           tt = builtin_type (gdbarch)->builtin_double;
17315           break;
17316         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17317         case 128:
17318           tt = builtin_type (gdbarch)->builtin_long_double;
17319           break;
17320         }
17321       break;
17322     }
17323
17324   /* If the type we found doesn't match the size we were looking for, then
17325      pretend we didn't find a type at all, the complex target type we
17326      create will then be nameless.  */
17327   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
17328     tt = nullptr;
17329
17330   const char *name = (tt == nullptr) ? nullptr : TYPE_NAME (tt);
17331   return dwarf2_init_float_type (objfile, bits, name, name_hint, byte_order);
17332 }
17333
17334 /* Find a representation of a given base type and install
17335    it in the TYPE field of the die.  */
17336
17337 static struct type *
17338 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17339 {
17340   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17341   struct type *type;
17342   struct attribute *attr;
17343   int encoding = 0, bits = 0;
17344   const char *name;
17345   gdbarch *arch;
17346
17347   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17348   if (attr != nullptr)
17349     encoding = DW_UNSND (attr);
17350   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17351   if (attr != nullptr)
17352     bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17353   name = dwarf2_name (die, cu);
17354   if (!name)
17355     complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17356
17357   arch = get_objfile_arch (objfile);
17358   enum bfd_endian byte_order = gdbarch_byte_order (arch);
17359
17360   attr = dwarf2_attr (die, DW_AT_endianity, cu);
17361   if (attr)
17362     {
17363       int endianity = DW_UNSND (attr);
17364
17365       switch (endianity)
17366         {
17367         case DW_END_big:
17368           byte_order = BFD_ENDIAN_BIG;
17369           break;
17370         case DW_END_little:
17371           byte_order = BFD_ENDIAN_LITTLE;
17372           break;
17373         default:
17374           complaint (_("DW_AT_endianity has unrecognized value %d"), endianity);
17375           break;
17376         }
17377     }
17378
17379   switch (encoding)
17380     {
17381       case DW_ATE_address:
17382         /* Turn DW_ATE_address into a void * pointer.  */
17383         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17384         type = init_pointer_type (objfile, bits, name, type);
17385         break;
17386       case DW_ATE_boolean:
17387         type = init_boolean_type (objfile, bits, 1, name);
17388         break;
17389       case DW_ATE_complex_float:
17390         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name,
17391                                                 byte_order);
17392         type = init_complex_type (objfile, name, type);
17393         break;
17394       case DW_ATE_decimal_float:
17395         type = init_decfloat_type (objfile, bits, name);
17396         break;
17397       case DW_ATE_float:
17398         type = dwarf2_init_float_type (objfile, bits, name, name, byte_order);
17399         break;
17400       case DW_ATE_signed:
17401         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17402         break;
17403       case DW_ATE_unsigned:
17404         if (cu->language == language_fortran
17405             && name
17406             && startswith (name, "character("))
17407           type = init_character_type (objfile, bits, 1, name);
17408         else
17409           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17410         break;
17411       case DW_ATE_signed_char:
17412         if (cu->language == language_ada || cu->language == language_m2
17413             || cu->language == language_pascal
17414             || cu->language == language_fortran)
17415           type = init_character_type (objfile, bits, 0, name);
17416         else
17417           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17418         break;
17419       case DW_ATE_unsigned_char:
17420         if (cu->language == language_ada || cu->language == language_m2
17421             || cu->language == language_pascal
17422             || cu->language == language_fortran
17423             || cu->language == language_rust)
17424           type = init_character_type (objfile, bits, 1, name);
17425         else
17426           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17427         break;
17428       case DW_ATE_UTF:
17429         {
17430           if (bits == 16)
17431             type = builtin_type (arch)->builtin_char16;
17432           else if (bits == 32)
17433             type = builtin_type (arch)->builtin_char32;
17434           else
17435             {
17436               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17437                          bits);
17438               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17439             }
17440           return set_die_type (die, type, cu);
17441         }
17442         break;
17443
17444       default:
17445         complaint (_("unsupported DW_AT_encoding: '%s'"),
17446                    dwarf_type_encoding_name (encoding));
17447         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17448         break;
17449     }
17450
17451   if (name && strcmp (name, "char") == 0)
17452     TYPE_NOSIGN (type) = 1;
17453
17454   maybe_set_alignment (cu, die, type);
17455
17456   TYPE_ENDIANITY_NOT_DEFAULT (type) = gdbarch_byte_order (arch) != byte_order;
17457
17458   return set_die_type (die, type, cu);
17459 }
17460
17461 /* Parse dwarf attribute if it's a block, reference or constant and put the
17462    resulting value of the attribute into struct bound_prop.
17463    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17464
17465 static int
17466 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17467                       struct dwarf2_cu *cu, struct dynamic_prop *prop,
17468                       struct type *default_type)
17469 {
17470   struct dwarf2_property_baton *baton;
17471   struct obstack *obstack
17472     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17473
17474   gdb_assert (default_type != NULL);
17475
17476   if (attr == NULL || prop == NULL)
17477     return 0;
17478
17479   if (attr->form_is_block ())
17480     {
17481       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17482       baton->property_type = default_type;
17483       baton->locexpr.per_cu = cu->per_cu;
17484       baton->locexpr.size = DW_BLOCK (attr)->size;
17485       baton->locexpr.data = DW_BLOCK (attr)->data;
17486       switch (attr->name)
17487         {
17488         case DW_AT_string_length:
17489           baton->locexpr.is_reference = true;
17490           break;
17491         default:
17492           baton->locexpr.is_reference = false;
17493           break;
17494         }
17495       prop->data.baton = baton;
17496       prop->kind = PROP_LOCEXPR;
17497       gdb_assert (prop->data.baton != NULL);
17498     }
17499   else if (attr->form_is_ref ())
17500     {
17501       struct dwarf2_cu *target_cu = cu;
17502       struct die_info *target_die;
17503       struct attribute *target_attr;
17504
17505       target_die = follow_die_ref (die, attr, &target_cu);
17506       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17507       if (target_attr == NULL)
17508         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17509                                    target_cu);
17510       if (target_attr == NULL)
17511         return 0;
17512
17513       switch (target_attr->name)
17514         {
17515           case DW_AT_location:
17516             if (target_attr->form_is_section_offset ())
17517               {
17518                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17519                 baton->property_type = die_type (target_die, target_cu);
17520                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17521                 prop->data.baton = baton;
17522                 prop->kind = PROP_LOCLIST;
17523                 gdb_assert (prop->data.baton != NULL);
17524               }
17525             else if (target_attr->form_is_block ())
17526               {
17527                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17528                 baton->property_type = die_type (target_die, target_cu);
17529                 baton->locexpr.per_cu = cu->per_cu;
17530                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17531                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17532                 baton->locexpr.is_reference = true;
17533                 prop->data.baton = baton;
17534                 prop->kind = PROP_LOCEXPR;
17535                 gdb_assert (prop->data.baton != NULL);
17536               }
17537             else
17538               {
17539                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17540                                                        "dynamic property");
17541                 return 0;
17542               }
17543             break;
17544           case DW_AT_data_member_location:
17545             {
17546               LONGEST offset;
17547
17548               if (!handle_data_member_location (target_die, target_cu,
17549                                                 &offset))
17550                 return 0;
17551
17552               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17553               baton->property_type = read_type_die (target_die->parent,
17554                                                       target_cu);
17555               baton->offset_info.offset = offset;
17556               baton->offset_info.type = die_type (target_die, target_cu);
17557               prop->data.baton = baton;
17558               prop->kind = PROP_ADDR_OFFSET;
17559               break;
17560             }
17561         }
17562     }
17563   else if (attr->form_is_constant ())
17564     {
17565       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17566       prop->kind = PROP_CONST;
17567     }
17568   else
17569     {
17570       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17571                                              dwarf2_name (die, cu));
17572       return 0;
17573     }
17574
17575   return 1;
17576 }
17577
17578 /* Find an integer type SIZE_IN_BYTES bytes in size and return it.
17579    UNSIGNED_P controls if the integer is unsigned or not.  */
17580
17581 static struct type *
17582 dwarf2_per_cu_int_type (struct dwarf2_per_cu_data *per_cu,
17583                         int size_in_bytes, bool unsigned_p)
17584 {
17585   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
17586   struct type *int_type;
17587
17588   /* Helper macro to examine the various builtin types.  */
17589 #define TRY_TYPE(F)                                                     \
17590   int_type = (unsigned_p                                                \
17591               ? objfile_type (objfile)->builtin_unsigned_ ## F          \
17592               : objfile_type (objfile)->builtin_ ## F);                 \
17593   if (int_type != NULL && TYPE_LENGTH (int_type) == size_in_bytes)      \
17594     return int_type
17595
17596   TRY_TYPE (char);
17597   TRY_TYPE (short);
17598   TRY_TYPE (int);
17599   TRY_TYPE (long);
17600   TRY_TYPE (long_long);
17601
17602 #undef TRY_TYPE
17603
17604   gdb_assert_not_reached ("unable to find suitable integer type");
17605 }
17606
17607 /* Find an integer type the same size as the address size given in the
17608    compilation unit header for PER_CU.  UNSIGNED_P controls if the integer
17609    is unsigned or not.  */
17610
17611 static struct type *
17612 dwarf2_per_cu_addr_sized_int_type (struct dwarf2_per_cu_data *per_cu,
17613                                    bool unsigned_p)
17614 {
17615   int addr_size = dwarf2_per_cu_addr_size (per_cu);
17616   return dwarf2_per_cu_int_type (per_cu, addr_size, unsigned_p);
17617 }
17618
17619 /* Read the DW_AT_type attribute for a sub-range.  If this attribute is not
17620    present (which is valid) then compute the default type based on the
17621    compilation units address size.  */
17622
17623 static struct type *
17624 read_subrange_index_type (struct die_info *die, struct dwarf2_cu *cu)
17625 {
17626   struct type *index_type = die_type (die, cu);
17627
17628   /* Dwarf-2 specifications explicitly allows to create subrange types
17629      without specifying a base type.
17630      In that case, the base type must be set to the type of
17631      the lower bound, upper bound or count, in that order, if any of these
17632      three attributes references an object that has a type.
17633      If no base type is found, the Dwarf-2 specifications say that
17634      a signed integer type of size equal to the size of an address should
17635      be used.
17636      For the following C code: `extern char gdb_int [];'
17637      GCC produces an empty range DIE.
17638      FIXME: muller/2010-05-28: Possible references to object for low bound,
17639      high bound or count are not yet handled by this code.  */
17640   if (TYPE_CODE (index_type) == TYPE_CODE_VOID)
17641     index_type = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
17642
17643   return index_type;
17644 }
17645
17646 /* Read the given DW_AT_subrange DIE.  */
17647
17648 static struct type *
17649 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17650 {
17651   struct type *base_type, *orig_base_type;
17652   struct type *range_type;
17653   struct attribute *attr;
17654   struct dynamic_prop low, high;
17655   int low_default_is_valid;
17656   int high_bound_is_count = 0;
17657   const char *name;
17658   ULONGEST negative_mask;
17659
17660   orig_base_type = read_subrange_index_type (die, cu);
17661
17662   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17663      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17664      creating the range type, but we use the result of check_typedef
17665      when examining properties of the type.  */
17666   base_type = check_typedef (orig_base_type);
17667
17668   /* The die_type call above may have already set the type for this DIE.  */
17669   range_type = get_die_type (die, cu);
17670   if (range_type)
17671     return range_type;
17672
17673   low.kind = PROP_CONST;
17674   high.kind = PROP_CONST;
17675   high.data.const_val = 0;
17676
17677   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17678      omitting DW_AT_lower_bound.  */
17679   switch (cu->language)
17680     {
17681     case language_c:
17682     case language_cplus:
17683       low.data.const_val = 0;
17684       low_default_is_valid = 1;
17685       break;
17686     case language_fortran:
17687       low.data.const_val = 1;
17688       low_default_is_valid = 1;
17689       break;
17690     case language_d:
17691     case language_objc:
17692     case language_rust:
17693       low.data.const_val = 0;
17694       low_default_is_valid = (cu->header.version >= 4);
17695       break;
17696     case language_ada:
17697     case language_m2:
17698     case language_pascal:
17699       low.data.const_val = 1;
17700       low_default_is_valid = (cu->header.version >= 4);
17701       break;
17702     default:
17703       low.data.const_val = 0;
17704       low_default_is_valid = 0;
17705       break;
17706     }
17707
17708   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17709   if (attr != nullptr)
17710     attr_to_dynamic_prop (attr, die, cu, &low, base_type);
17711   else if (!low_default_is_valid)
17712     complaint (_("Missing DW_AT_lower_bound "
17713                                       "- DIE at %s [in module %s]"),
17714                sect_offset_str (die->sect_off),
17715                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17716
17717   struct attribute *attr_ub, *attr_count;
17718   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17719   if (!attr_to_dynamic_prop (attr, die, cu, &high, base_type))
17720     {
17721       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17722       if (attr_to_dynamic_prop (attr, die, cu, &high, base_type))
17723         {
17724           /* If bounds are constant do the final calculation here.  */
17725           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17726             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17727           else
17728             high_bound_is_count = 1;
17729         }
17730       else
17731         {
17732           if (attr_ub != NULL)
17733             complaint (_("Unresolved DW_AT_upper_bound "
17734                          "- DIE at %s [in module %s]"),
17735                        sect_offset_str (die->sect_off),
17736                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17737           if (attr_count != NULL)
17738             complaint (_("Unresolved DW_AT_count "
17739                          "- DIE at %s [in module %s]"),
17740                        sect_offset_str (die->sect_off),
17741                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17742         }
17743     }
17744
17745   LONGEST bias = 0;
17746   struct attribute *bias_attr = dwarf2_attr (die, DW_AT_GNU_bias, cu);
17747   if (bias_attr != nullptr && bias_attr->form_is_constant ())
17748     bias = dwarf2_get_attr_constant_value (bias_attr, 0);
17749
17750   /* Normally, the DWARF producers are expected to use a signed
17751      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17752      But this is unfortunately not always the case, as witnessed
17753      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17754      is used instead.  To work around that ambiguity, we treat
17755      the bounds as signed, and thus sign-extend their values, when
17756      the base type is signed.  */
17757   negative_mask =
17758     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17759   if (low.kind == PROP_CONST
17760       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17761     low.data.const_val |= negative_mask;
17762   if (high.kind == PROP_CONST
17763       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17764     high.data.const_val |= negative_mask;
17765
17766   /* Check for bit and byte strides.  */
17767   struct dynamic_prop byte_stride_prop;
17768   attribute *attr_byte_stride = dwarf2_attr (die, DW_AT_byte_stride, cu);
17769   if (attr_byte_stride != nullptr)
17770     {
17771       struct type *prop_type
17772         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
17773       attr_to_dynamic_prop (attr_byte_stride, die, cu, &byte_stride_prop,
17774                             prop_type);
17775     }
17776
17777   struct dynamic_prop bit_stride_prop;
17778   attribute *attr_bit_stride = dwarf2_attr (die, DW_AT_bit_stride, cu);
17779   if (attr_bit_stride != nullptr)
17780     {
17781       /* It only makes sense to have either a bit or byte stride.  */
17782       if (attr_byte_stride != nullptr)
17783         {
17784           complaint (_("Found DW_AT_bit_stride and DW_AT_byte_stride "
17785                        "- DIE at %s [in module %s]"),
17786                      sect_offset_str (die->sect_off),
17787                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17788           attr_bit_stride = nullptr;
17789         }
17790       else
17791         {
17792           struct type *prop_type
17793             = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
17794           attr_to_dynamic_prop (attr_bit_stride, die, cu, &bit_stride_prop,
17795                                 prop_type);
17796         }
17797     }
17798
17799   if (attr_byte_stride != nullptr
17800       || attr_bit_stride != nullptr)
17801     {
17802       bool byte_stride_p = (attr_byte_stride != nullptr);
17803       struct dynamic_prop *stride
17804         = byte_stride_p ? &byte_stride_prop : &bit_stride_prop;
17805
17806       range_type
17807         = create_range_type_with_stride (NULL, orig_base_type, &low,
17808                                          &high, bias, stride, byte_stride_p);
17809     }
17810   else
17811     range_type = create_range_type (NULL, orig_base_type, &low, &high, bias);
17812
17813   if (high_bound_is_count)
17814     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17815
17816   /* Ada expects an empty array on no boundary attributes.  */
17817   if (attr == NULL && cu->language != language_ada)
17818     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17819
17820   name = dwarf2_name (die, cu);
17821   if (name)
17822     TYPE_NAME (range_type) = name;
17823
17824   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17825   if (attr != nullptr)
17826     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17827
17828   maybe_set_alignment (cu, die, range_type);
17829
17830   set_die_type (die, range_type, cu);
17831
17832   /* set_die_type should be already done.  */
17833   set_descriptive_type (range_type, die, cu);
17834
17835   return range_type;
17836 }
17837
17838 static struct type *
17839 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17840 {
17841   struct type *type;
17842
17843   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17844                     NULL);
17845   TYPE_NAME (type) = dwarf2_name (die, cu);
17846
17847   /* In Ada, an unspecified type is typically used when the description
17848      of the type is deferred to a different unit.  When encountering
17849      such a type, we treat it as a stub, and try to resolve it later on,
17850      when needed.  */
17851   if (cu->language == language_ada)
17852     TYPE_STUB (type) = 1;
17853
17854   return set_die_type (die, type, cu);
17855 }
17856
17857 /* Read a single die and all its descendents.  Set the die's sibling
17858    field to NULL; set other fields in the die correctly, and set all
17859    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17860    location of the info_ptr after reading all of those dies.  PARENT
17861    is the parent of the die in question.  */
17862
17863 static struct die_info *
17864 read_die_and_children (const struct die_reader_specs *reader,
17865                        const gdb_byte *info_ptr,
17866                        const gdb_byte **new_info_ptr,
17867                        struct die_info *parent)
17868 {
17869   struct die_info *die;
17870   const gdb_byte *cur_ptr;
17871
17872   cur_ptr = read_full_die_1 (reader, &die, info_ptr, 0);
17873   if (die == NULL)
17874     {
17875       *new_info_ptr = cur_ptr;
17876       return NULL;
17877     }
17878   store_in_ref_table (die, reader->cu);
17879
17880   if (die->has_children)
17881     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17882   else
17883     {
17884       die->child = NULL;
17885       *new_info_ptr = cur_ptr;
17886     }
17887
17888   die->sibling = NULL;
17889   die->parent = parent;
17890   return die;
17891 }
17892
17893 /* Read a die, all of its descendents, and all of its siblings; set
17894    all of the fields of all of the dies correctly.  Arguments are as
17895    in read_die_and_children.  */
17896
17897 static struct die_info *
17898 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17899                          const gdb_byte *info_ptr,
17900                          const gdb_byte **new_info_ptr,
17901                          struct die_info *parent)
17902 {
17903   struct die_info *first_die, *last_sibling;
17904   const gdb_byte *cur_ptr;
17905
17906   cur_ptr = info_ptr;
17907   first_die = last_sibling = NULL;
17908
17909   while (1)
17910     {
17911       struct die_info *die
17912         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17913
17914       if (die == NULL)
17915         {
17916           *new_info_ptr = cur_ptr;
17917           return first_die;
17918         }
17919
17920       if (!first_die)
17921         first_die = die;
17922       else
17923         last_sibling->sibling = die;
17924
17925       last_sibling = die;
17926     }
17927 }
17928
17929 /* Read a die, all of its descendents, and all of its siblings; set
17930    all of the fields of all of the dies correctly.  Arguments are as
17931    in read_die_and_children.
17932    This the main entry point for reading a DIE and all its children.  */
17933
17934 static struct die_info *
17935 read_die_and_siblings (const struct die_reader_specs *reader,
17936                        const gdb_byte *info_ptr,
17937                        const gdb_byte **new_info_ptr,
17938                        struct die_info *parent)
17939 {
17940   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17941                                                   new_info_ptr, parent);
17942
17943   if (dwarf_die_debug)
17944     {
17945       fprintf_unfiltered (gdb_stdlog,
17946                           "Read die from %s@0x%x of %s:\n",
17947                           reader->die_section->get_name (),
17948                           (unsigned) (info_ptr - reader->die_section->buffer),
17949                           bfd_get_filename (reader->abfd));
17950       dump_die (die, dwarf_die_debug);
17951     }
17952
17953   return die;
17954 }
17955
17956 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17957    attributes.
17958    The caller is responsible for filling in the extra attributes
17959    and updating (*DIEP)->num_attrs.
17960    Set DIEP to point to a newly allocated die with its information,
17961    except for its child, sibling, and parent fields.  */
17962
17963 static const gdb_byte *
17964 read_full_die_1 (const struct die_reader_specs *reader,
17965                  struct die_info **diep, const gdb_byte *info_ptr,
17966                  int num_extra_attrs)
17967 {
17968   unsigned int abbrev_number, bytes_read, i;
17969   struct abbrev_info *abbrev;
17970   struct die_info *die;
17971   struct dwarf2_cu *cu = reader->cu;
17972   bfd *abfd = reader->abfd;
17973
17974   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17975   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17976   info_ptr += bytes_read;
17977   if (!abbrev_number)
17978     {
17979       *diep = NULL;
17980       return info_ptr;
17981     }
17982
17983   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17984   if (!abbrev)
17985     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17986            abbrev_number,
17987            bfd_get_filename (abfd));
17988
17989   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17990   die->sect_off = sect_off;
17991   die->tag = abbrev->tag;
17992   die->abbrev = abbrev_number;
17993   die->has_children = abbrev->has_children;
17994
17995   /* Make the result usable.
17996      The caller needs to update num_attrs after adding the extra
17997      attributes.  */
17998   die->num_attrs = abbrev->num_attrs;
17999
18000   std::vector<int> indexes_that_need_reprocess;
18001   for (i = 0; i < abbrev->num_attrs; ++i)
18002     {
18003       bool need_reprocess;
18004       info_ptr =
18005         read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18006                         info_ptr, &need_reprocess);
18007       if (need_reprocess)
18008         indexes_that_need_reprocess.push_back (i);
18009     }
18010
18011   struct attribute *attr = dwarf2_attr_no_follow (die, DW_AT_str_offsets_base);
18012   if (attr != nullptr)
18013     cu->str_offsets_base = DW_UNSND (attr);
18014
18015   auto maybe_addr_base = lookup_addr_base(die);
18016   if (maybe_addr_base.has_value ())
18017     cu->addr_base = *maybe_addr_base;
18018   for (int index : indexes_that_need_reprocess)
18019     read_attribute_reprocess (reader, &die->attrs[index]);
18020   *diep = die;
18021   return info_ptr;
18022 }
18023
18024 /* Read a die and all its attributes.
18025    Set DIEP to point to a newly allocated die with its information,
18026    except for its child, sibling, and parent fields.  */
18027
18028 static const gdb_byte *
18029 read_full_die (const struct die_reader_specs *reader,
18030                struct die_info **diep, const gdb_byte *info_ptr)
18031 {
18032   const gdb_byte *result;
18033
18034   result = read_full_die_1 (reader, diep, info_ptr, 0);
18035
18036   if (dwarf_die_debug)
18037     {
18038       fprintf_unfiltered (gdb_stdlog,
18039                           "Read die from %s@0x%x of %s:\n",
18040                           reader->die_section->get_name (),
18041                           (unsigned) (info_ptr - reader->die_section->buffer),
18042                           bfd_get_filename (reader->abfd));
18043       dump_die (*diep, dwarf_die_debug);
18044     }
18045
18046   return result;
18047 }
18048 \f
18049
18050 /* Returns nonzero if TAG represents a type that we might generate a partial
18051    symbol for.  */
18052
18053 static int
18054 is_type_tag_for_partial (int tag)
18055 {
18056   switch (tag)
18057     {
18058 #if 0
18059     /* Some types that would be reasonable to generate partial symbols for,
18060        that we don't at present.  */
18061     case DW_TAG_array_type:
18062     case DW_TAG_file_type:
18063     case DW_TAG_ptr_to_member_type:
18064     case DW_TAG_set_type:
18065     case DW_TAG_string_type:
18066     case DW_TAG_subroutine_type:
18067 #endif
18068     case DW_TAG_base_type:
18069     case DW_TAG_class_type:
18070     case DW_TAG_interface_type:
18071     case DW_TAG_enumeration_type:
18072     case DW_TAG_structure_type:
18073     case DW_TAG_subrange_type:
18074     case DW_TAG_typedef:
18075     case DW_TAG_union_type:
18076       return 1;
18077     default:
18078       return 0;
18079     }
18080 }
18081
18082 /* Load all DIEs that are interesting for partial symbols into memory.  */
18083
18084 static struct partial_die_info *
18085 load_partial_dies (const struct die_reader_specs *reader,
18086                    const gdb_byte *info_ptr, int building_psymtab)
18087 {
18088   struct dwarf2_cu *cu = reader->cu;
18089   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18090   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18091   unsigned int bytes_read;
18092   unsigned int load_all = 0;
18093   int nesting_level = 1;
18094
18095   parent_die = NULL;
18096   last_die = NULL;
18097
18098   gdb_assert (cu->per_cu != NULL);
18099   if (cu->per_cu->load_all_dies)
18100     load_all = 1;
18101
18102   cu->partial_dies
18103     = htab_create_alloc_ex (cu->header.length / 12,
18104                             partial_die_hash,
18105                             partial_die_eq,
18106                             NULL,
18107                             &cu->comp_unit_obstack,
18108                             hashtab_obstack_allocate,
18109                             dummy_obstack_deallocate);
18110
18111   while (1)
18112     {
18113       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18114
18115       /* A NULL abbrev means the end of a series of children.  */
18116       if (abbrev == NULL)
18117         {
18118           if (--nesting_level == 0)
18119             return first_die;
18120
18121           info_ptr += bytes_read;
18122           last_die = parent_die;
18123           parent_die = parent_die->die_parent;
18124           continue;
18125         }
18126
18127       /* Check for template arguments.  We never save these; if
18128          they're seen, we just mark the parent, and go on our way.  */
18129       if (parent_die != NULL
18130           && cu->language == language_cplus
18131           && (abbrev->tag == DW_TAG_template_type_param
18132               || abbrev->tag == DW_TAG_template_value_param))
18133         {
18134           parent_die->has_template_arguments = 1;
18135
18136           if (!load_all)
18137             {
18138               /* We don't need a partial DIE for the template argument.  */
18139               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18140               continue;
18141             }
18142         }
18143
18144       /* We only recurse into c++ subprograms looking for template arguments.
18145          Skip their other children.  */
18146       if (!load_all
18147           && cu->language == language_cplus
18148           && parent_die != NULL
18149           && parent_die->tag == DW_TAG_subprogram)
18150         {
18151           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18152           continue;
18153         }
18154
18155       /* Check whether this DIE is interesting enough to save.  Normally
18156          we would not be interested in members here, but there may be
18157          later variables referencing them via DW_AT_specification (for
18158          static members).  */
18159       if (!load_all
18160           && !is_type_tag_for_partial (abbrev->tag)
18161           && abbrev->tag != DW_TAG_constant
18162           && abbrev->tag != DW_TAG_enumerator
18163           && abbrev->tag != DW_TAG_subprogram
18164           && abbrev->tag != DW_TAG_inlined_subroutine
18165           && abbrev->tag != DW_TAG_lexical_block
18166           && abbrev->tag != DW_TAG_variable
18167           && abbrev->tag != DW_TAG_namespace
18168           && abbrev->tag != DW_TAG_module
18169           && abbrev->tag != DW_TAG_member
18170           && abbrev->tag != DW_TAG_imported_unit
18171           && abbrev->tag != DW_TAG_imported_declaration)
18172         {
18173           /* Otherwise we skip to the next sibling, if any.  */
18174           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18175           continue;
18176         }
18177
18178       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18179                                    abbrev);
18180
18181       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18182
18183       /* This two-pass algorithm for processing partial symbols has a
18184          high cost in cache pressure.  Thus, handle some simple cases
18185          here which cover the majority of C partial symbols.  DIEs
18186          which neither have specification tags in them, nor could have
18187          specification tags elsewhere pointing at them, can simply be
18188          processed and discarded.
18189
18190          This segment is also optional; scan_partial_symbols and
18191          add_partial_symbol will handle these DIEs if we chain
18192          them in normally.  When compilers which do not emit large
18193          quantities of duplicate debug information are more common,
18194          this code can probably be removed.  */
18195
18196       /* Any complete simple types at the top level (pretty much all
18197          of them, for a language without namespaces), can be processed
18198          directly.  */
18199       if (parent_die == NULL
18200           && pdi.has_specification == 0
18201           && pdi.is_declaration == 0
18202           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18203               || pdi.tag == DW_TAG_base_type
18204               || pdi.tag == DW_TAG_subrange_type))
18205         {
18206           if (building_psymtab && pdi.name != NULL)
18207             add_psymbol_to_list (pdi.name, false,
18208                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18209                                  psymbol_placement::STATIC,
18210                                  0, cu->language, objfile);
18211           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18212           continue;
18213         }
18214
18215       /* The exception for DW_TAG_typedef with has_children above is
18216          a workaround of GCC PR debug/47510.  In the case of this complaint
18217          type_name_or_error will error on such types later.
18218
18219          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18220          it could not find the child DIEs referenced later, this is checked
18221          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18222
18223       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18224         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18225                      "- DIE at %s [in module %s]"),
18226                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18227
18228       /* If we're at the second level, and we're an enumerator, and
18229          our parent has no specification (meaning possibly lives in a
18230          namespace elsewhere), then we can add the partial symbol now
18231          instead of queueing it.  */
18232       if (pdi.tag == DW_TAG_enumerator
18233           && parent_die != NULL
18234           && parent_die->die_parent == NULL
18235           && parent_die->tag == DW_TAG_enumeration_type
18236           && parent_die->has_specification == 0)
18237         {
18238           if (pdi.name == NULL)
18239             complaint (_("malformed enumerator DIE ignored"));
18240           else if (building_psymtab)
18241             add_psymbol_to_list (pdi.name, false,
18242                                  VAR_DOMAIN, LOC_CONST, -1,
18243                                  cu->language == language_cplus
18244                                  ? psymbol_placement::GLOBAL
18245                                  : psymbol_placement::STATIC,
18246                                  0, cu->language, objfile);
18247
18248           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18249           continue;
18250         }
18251
18252       struct partial_die_info *part_die
18253         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18254
18255       /* We'll save this DIE so link it in.  */
18256       part_die->die_parent = parent_die;
18257       part_die->die_sibling = NULL;
18258       part_die->die_child = NULL;
18259
18260       if (last_die && last_die == parent_die)
18261         last_die->die_child = part_die;
18262       else if (last_die)
18263         last_die->die_sibling = part_die;
18264
18265       last_die = part_die;
18266
18267       if (first_die == NULL)
18268         first_die = part_die;
18269
18270       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18271          find interesting need to be in the hash table, because we
18272          also have the parent/sibling/child chains; only those that we
18273          might refer to by offset later during partial symbol reading.
18274
18275          For now this means things that might have be the target of a
18276          DW_AT_specification, DW_AT_abstract_origin, or
18277          DW_AT_extension.  DW_AT_extension will refer only to
18278          namespaces; DW_AT_abstract_origin refers to functions (and
18279          many things under the function DIE, but we do not recurse
18280          into function DIEs during partial symbol reading) and
18281          possibly variables as well; DW_AT_specification refers to
18282          declarations.  Declarations ought to have the DW_AT_declaration
18283          flag.  It happens that GCC forgets to put it in sometimes, but
18284          only for functions, not for types.
18285
18286          Adding more things than necessary to the hash table is harmless
18287          except for the performance cost.  Adding too few will result in
18288          wasted time in find_partial_die, when we reread the compilation
18289          unit with load_all_dies set.  */
18290
18291       if (load_all
18292           || abbrev->tag == DW_TAG_constant
18293           || abbrev->tag == DW_TAG_subprogram
18294           || abbrev->tag == DW_TAG_variable
18295           || abbrev->tag == DW_TAG_namespace
18296           || part_die->is_declaration)
18297         {
18298           void **slot;
18299
18300           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18301                                            to_underlying (part_die->sect_off),
18302                                            INSERT);
18303           *slot = part_die;
18304         }
18305
18306       /* For some DIEs we want to follow their children (if any).  For C
18307          we have no reason to follow the children of structures; for other
18308          languages we have to, so that we can get at method physnames
18309          to infer fully qualified class names, for DW_AT_specification,
18310          and for C++ template arguments.  For C++, we also look one level
18311          inside functions to find template arguments (if the name of the
18312          function does not already contain the template arguments).
18313
18314          For Ada and Fortran, we need to scan the children of subprograms
18315          and lexical blocks as well because these languages allow the
18316          definition of nested entities that could be interesting for the
18317          debugger, such as nested subprograms for instance.  */
18318       if (last_die->has_children
18319           && (load_all
18320               || last_die->tag == DW_TAG_namespace
18321               || last_die->tag == DW_TAG_module
18322               || last_die->tag == DW_TAG_enumeration_type
18323               || (cu->language == language_cplus
18324                   && last_die->tag == DW_TAG_subprogram
18325                   && (last_die->name == NULL
18326                       || strchr (last_die->name, '<') == NULL))
18327               || (cu->language != language_c
18328                   && (last_die->tag == DW_TAG_class_type
18329                       || last_die->tag == DW_TAG_interface_type
18330                       || last_die->tag == DW_TAG_structure_type
18331                       || last_die->tag == DW_TAG_union_type))
18332               || ((cu->language == language_ada
18333                    || cu->language == language_fortran)
18334                   && (last_die->tag == DW_TAG_subprogram
18335                       || last_die->tag == DW_TAG_lexical_block))))
18336         {
18337           nesting_level++;
18338           parent_die = last_die;
18339           continue;
18340         }
18341
18342       /* Otherwise we skip to the next sibling, if any.  */
18343       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18344
18345       /* Back to the top, do it again.  */
18346     }
18347 }
18348
18349 partial_die_info::partial_die_info (sect_offset sect_off_,
18350                                     struct abbrev_info *abbrev)
18351   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18352 {
18353 }
18354
18355 /* Read a minimal amount of information into the minimal die structure.
18356    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18357
18358 const gdb_byte *
18359 partial_die_info::read (const struct die_reader_specs *reader,
18360                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18361 {
18362   struct dwarf2_cu *cu = reader->cu;
18363   struct dwarf2_per_objfile *dwarf2_per_objfile
18364     = cu->per_cu->dwarf2_per_objfile;
18365   unsigned int i;
18366   int has_low_pc_attr = 0;
18367   int has_high_pc_attr = 0;
18368   int high_pc_relative = 0;
18369
18370   std::vector<struct attribute> attr_vec (abbrev.num_attrs);
18371   for (i = 0; i < abbrev.num_attrs; ++i)
18372     {
18373       bool need_reprocess;
18374       info_ptr = read_attribute (reader, &attr_vec[i], &abbrev.attrs[i],
18375                                  info_ptr, &need_reprocess);
18376       /* String and address offsets that need to do the reprocessing have
18377          already been read at this point, so there is no need to wait until
18378          the loop terminates to do the reprocessing.  */
18379       if (need_reprocess)
18380         read_attribute_reprocess (reader, &attr_vec[i]);
18381       attribute &attr = attr_vec[i];
18382       /* Store the data if it is of an attribute we want to keep in a
18383          partial symbol table.  */
18384       switch (attr.name)
18385         {
18386         case DW_AT_name:
18387           switch (tag)
18388             {
18389             case DW_TAG_compile_unit:
18390             case DW_TAG_partial_unit:
18391             case DW_TAG_type_unit:
18392               /* Compilation units have a DW_AT_name that is a filename, not
18393                  a source language identifier.  */
18394             case DW_TAG_enumeration_type:
18395             case DW_TAG_enumerator:
18396               /* These tags always have simple identifiers already; no need
18397                  to canonicalize them.  */
18398               name = DW_STRING (&attr);
18399               break;
18400             default:
18401               {
18402                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18403
18404                 name
18405                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18406                                               &objfile->per_bfd->storage_obstack);
18407               }
18408               break;
18409             }
18410           break;
18411         case DW_AT_linkage_name:
18412         case DW_AT_MIPS_linkage_name:
18413           /* Note that both forms of linkage name might appear.  We
18414              assume they will be the same, and we only store the last
18415              one we see.  */
18416           linkage_name = DW_STRING (&attr);
18417           break;
18418         case DW_AT_low_pc:
18419           has_low_pc_attr = 1;
18420           lowpc = attr.value_as_address ();
18421           break;
18422         case DW_AT_high_pc:
18423           has_high_pc_attr = 1;
18424           highpc = attr.value_as_address ();
18425           if (cu->header.version >= 4 && attr.form_is_constant ())
18426                 high_pc_relative = 1;
18427           break;
18428         case DW_AT_location:
18429           /* Support the .debug_loc offsets.  */
18430           if (attr.form_is_block ())
18431             {
18432                d.locdesc = DW_BLOCK (&attr);
18433             }
18434           else if (attr.form_is_section_offset ())
18435             {
18436               dwarf2_complex_location_expr_complaint ();
18437             }
18438           else
18439             {
18440               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18441                                                      "partial symbol information");
18442             }
18443           break;
18444         case DW_AT_external:
18445           is_external = DW_UNSND (&attr);
18446           break;
18447         case DW_AT_declaration:
18448           is_declaration = DW_UNSND (&attr);
18449           break;
18450         case DW_AT_type:
18451           has_type = 1;
18452           break;
18453         case DW_AT_abstract_origin:
18454         case DW_AT_specification:
18455         case DW_AT_extension:
18456           has_specification = 1;
18457           spec_offset = dwarf2_get_ref_die_offset (&attr);
18458           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18459                                    || cu->per_cu->is_dwz);
18460           break;
18461         case DW_AT_sibling:
18462           /* Ignore absolute siblings, they might point outside of
18463              the current compile unit.  */
18464           if (attr.form == DW_FORM_ref_addr)
18465             complaint (_("ignoring absolute DW_AT_sibling"));
18466           else
18467             {
18468               const gdb_byte *buffer = reader->buffer;
18469               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18470               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18471
18472               if (sibling_ptr < info_ptr)
18473                 complaint (_("DW_AT_sibling points backwards"));
18474               else if (sibling_ptr > reader->buffer_end)
18475                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18476               else
18477                 sibling = sibling_ptr;
18478             }
18479           break;
18480         case DW_AT_byte_size:
18481           has_byte_size = 1;
18482           break;
18483         case DW_AT_const_value:
18484           has_const_value = 1;
18485           break;
18486         case DW_AT_calling_convention:
18487           /* DWARF doesn't provide a way to identify a program's source-level
18488              entry point.  DW_AT_calling_convention attributes are only meant
18489              to describe functions' calling conventions.
18490
18491              However, because it's a necessary piece of information in
18492              Fortran, and before DWARF 4 DW_CC_program was the only
18493              piece of debugging information whose definition refers to
18494              a 'main program' at all, several compilers marked Fortran
18495              main programs with DW_CC_program --- even when those
18496              functions use the standard calling conventions.
18497
18498              Although DWARF now specifies a way to provide this
18499              information, we support this practice for backward
18500              compatibility.  */
18501           if (DW_UNSND (&attr) == DW_CC_program
18502               && cu->language == language_fortran)
18503             main_subprogram = 1;
18504           break;
18505         case DW_AT_inline:
18506           if (DW_UNSND (&attr) == DW_INL_inlined
18507               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18508             may_be_inlined = 1;
18509           break;
18510
18511         case DW_AT_import:
18512           if (tag == DW_TAG_imported_unit)
18513             {
18514               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18515               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18516                                   || cu->per_cu->is_dwz);
18517             }
18518           break;
18519
18520         case DW_AT_main_subprogram:
18521           main_subprogram = DW_UNSND (&attr);
18522           break;
18523
18524         case DW_AT_ranges:
18525           {
18526             /* It would be nice to reuse dwarf2_get_pc_bounds here,
18527                but that requires a full DIE, so instead we just
18528                reimplement it.  */
18529             int need_ranges_base = tag != DW_TAG_compile_unit;
18530             unsigned int ranges_offset = (DW_UNSND (&attr)
18531                                           + (need_ranges_base
18532                                              ? cu->ranges_base
18533                                              : 0));
18534
18535             /* Value of the DW_AT_ranges attribute is the offset in the
18536                .debug_ranges section.  */
18537             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
18538                                     nullptr))
18539               has_pc_info = 1;
18540           }
18541           break;
18542
18543         default:
18544           break;
18545         }
18546     }
18547
18548   /* For Ada, if both the name and the linkage name appear, we prefer
18549      the latter.  This lets "catch exception" work better, regardless
18550      of the order in which the name and linkage name were emitted.
18551      Really, though, this is just a workaround for the fact that gdb
18552      doesn't store both the name and the linkage name.  */
18553   if (cu->language == language_ada && linkage_name != nullptr)
18554     name = linkage_name;
18555
18556   if (high_pc_relative)
18557     highpc += lowpc;
18558
18559   if (has_low_pc_attr && has_high_pc_attr)
18560     {
18561       /* When using the GNU linker, .gnu.linkonce. sections are used to
18562          eliminate duplicate copies of functions and vtables and such.
18563          The linker will arbitrarily choose one and discard the others.
18564          The AT_*_pc values for such functions refer to local labels in
18565          these sections.  If the section from that file was discarded, the
18566          labels are not in the output, so the relocs get a value of 0.
18567          If this is a discarded function, mark the pc bounds as invalid,
18568          so that GDB will ignore it.  */
18569       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18570         {
18571           struct objfile *objfile = dwarf2_per_objfile->objfile;
18572           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18573
18574           complaint (_("DW_AT_low_pc %s is zero "
18575                        "for DIE at %s [in module %s]"),
18576                      paddress (gdbarch, lowpc),
18577                      sect_offset_str (sect_off),
18578                      objfile_name (objfile));
18579         }
18580       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18581       else if (lowpc >= highpc)
18582         {
18583           struct objfile *objfile = dwarf2_per_objfile->objfile;
18584           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18585
18586           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18587                        "for DIE at %s [in module %s]"),
18588                      paddress (gdbarch, lowpc),
18589                      paddress (gdbarch, highpc),
18590                      sect_offset_str (sect_off),
18591                      objfile_name (objfile));
18592         }
18593       else
18594         has_pc_info = 1;
18595     }
18596
18597   return info_ptr;
18598 }
18599
18600 /* Find a cached partial DIE at OFFSET in CU.  */
18601
18602 struct partial_die_info *
18603 dwarf2_cu::find_partial_die (sect_offset sect_off)
18604 {
18605   struct partial_die_info *lookup_die = NULL;
18606   struct partial_die_info part_die (sect_off);
18607
18608   lookup_die = ((struct partial_die_info *)
18609                 htab_find_with_hash (partial_dies, &part_die,
18610                                      to_underlying (sect_off)));
18611
18612   return lookup_die;
18613 }
18614
18615 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18616    except in the case of .debug_types DIEs which do not reference
18617    outside their CU (they do however referencing other types via
18618    DW_FORM_ref_sig8).  */
18619
18620 static const struct cu_partial_die_info
18621 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18622 {
18623   struct dwarf2_per_objfile *dwarf2_per_objfile
18624     = cu->per_cu->dwarf2_per_objfile;
18625   struct objfile *objfile = dwarf2_per_objfile->objfile;
18626   struct dwarf2_per_cu_data *per_cu = NULL;
18627   struct partial_die_info *pd = NULL;
18628
18629   if (offset_in_dwz == cu->per_cu->is_dwz
18630       && offset_in_cu_p (&cu->header, sect_off))
18631     {
18632       pd = cu->find_partial_die (sect_off);
18633       if (pd != NULL)
18634         return { cu, pd };
18635       /* We missed recording what we needed.
18636          Load all dies and try again.  */
18637       per_cu = cu->per_cu;
18638     }
18639   else
18640     {
18641       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18642       if (cu->per_cu->is_debug_types)
18643         {
18644           error (_("Dwarf Error: Type Unit at offset %s contains"
18645                    " external reference to offset %s [in module %s].\n"),
18646                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18647                  bfd_get_filename (objfile->obfd));
18648         }
18649       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18650                                                  dwarf2_per_objfile);
18651
18652       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18653         load_partial_comp_unit (per_cu);
18654
18655       per_cu->cu->last_used = 0;
18656       pd = per_cu->cu->find_partial_die (sect_off);
18657     }
18658
18659   /* If we didn't find it, and not all dies have been loaded,
18660      load them all and try again.  */
18661
18662   if (pd == NULL && per_cu->load_all_dies == 0)
18663     {
18664       per_cu->load_all_dies = 1;
18665
18666       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18667          THIS_CU->cu may already be in use.  So we can't just free it and
18668          replace its DIEs with the ones we read in.  Instead, we leave those
18669          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18670          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18671          set.  */
18672       load_partial_comp_unit (per_cu);
18673
18674       pd = per_cu->cu->find_partial_die (sect_off);
18675     }
18676
18677   if (pd == NULL)
18678     internal_error (__FILE__, __LINE__,
18679                     _("could not find partial DIE %s "
18680                       "in cache [from module %s]\n"),
18681                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18682   return { per_cu->cu, pd };
18683 }
18684
18685 /* See if we can figure out if the class lives in a namespace.  We do
18686    this by looking for a member function; its demangled name will
18687    contain namespace info, if there is any.  */
18688
18689 static void
18690 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18691                                   struct dwarf2_cu *cu)
18692 {
18693   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18694      what template types look like, because the demangler
18695      frequently doesn't give the same name as the debug info.  We
18696      could fix this by only using the demangled name to get the
18697      prefix (but see comment in read_structure_type).  */
18698
18699   struct partial_die_info *real_pdi;
18700   struct partial_die_info *child_pdi;
18701
18702   /* If this DIE (this DIE's specification, if any) has a parent, then
18703      we should not do this.  We'll prepend the parent's fully qualified
18704      name when we create the partial symbol.  */
18705
18706   real_pdi = struct_pdi;
18707   while (real_pdi->has_specification)
18708     {
18709       auto res = find_partial_die (real_pdi->spec_offset,
18710                                    real_pdi->spec_is_dwz, cu);
18711       real_pdi = res.pdi;
18712       cu = res.cu;
18713     }
18714
18715   if (real_pdi->die_parent != NULL)
18716     return;
18717
18718   for (child_pdi = struct_pdi->die_child;
18719        child_pdi != NULL;
18720        child_pdi = child_pdi->die_sibling)
18721     {
18722       if (child_pdi->tag == DW_TAG_subprogram
18723           && child_pdi->linkage_name != NULL)
18724         {
18725           gdb::unique_xmalloc_ptr<char> actual_class_name
18726             (language_class_name_from_physname (cu->language_defn,
18727                                                 child_pdi->linkage_name));
18728           if (actual_class_name != NULL)
18729             {
18730               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18731               struct_pdi->name
18732                 = obstack_strdup (&objfile->per_bfd->storage_obstack,
18733                                   actual_class_name.get ());
18734             }
18735           break;
18736         }
18737     }
18738 }
18739
18740 void
18741 partial_die_info::fixup (struct dwarf2_cu *cu)
18742 {
18743   /* Once we've fixed up a die, there's no point in doing so again.
18744      This also avoids a memory leak if we were to call
18745      guess_partial_die_structure_name multiple times.  */
18746   if (fixup_called)
18747     return;
18748
18749   /* If we found a reference attribute and the DIE has no name, try
18750      to find a name in the referred to DIE.  */
18751
18752   if (name == NULL && has_specification)
18753     {
18754       struct partial_die_info *spec_die;
18755
18756       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
18757       spec_die = res.pdi;
18758       cu = res.cu;
18759
18760       spec_die->fixup (cu);
18761
18762       if (spec_die->name)
18763         {
18764           name = spec_die->name;
18765
18766           /* Copy DW_AT_external attribute if it is set.  */
18767           if (spec_die->is_external)
18768             is_external = spec_die->is_external;
18769         }
18770     }
18771
18772   /* Set default names for some unnamed DIEs.  */
18773
18774   if (name == NULL && tag == DW_TAG_namespace)
18775     name = CP_ANONYMOUS_NAMESPACE_STR;
18776
18777   /* If there is no parent die to provide a namespace, and there are
18778      children, see if we can determine the namespace from their linkage
18779      name.  */
18780   if (cu->language == language_cplus
18781       && !cu->per_cu->dwarf2_per_objfile->types.empty ()
18782       && die_parent == NULL
18783       && has_children
18784       && (tag == DW_TAG_class_type
18785           || tag == DW_TAG_structure_type
18786           || tag == DW_TAG_union_type))
18787     guess_partial_die_structure_name (this, cu);
18788
18789   /* GCC might emit a nameless struct or union that has a linkage
18790      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18791   if (name == NULL
18792       && (tag == DW_TAG_class_type
18793           || tag == DW_TAG_interface_type
18794           || tag == DW_TAG_structure_type
18795           || tag == DW_TAG_union_type)
18796       && linkage_name != NULL)
18797     {
18798       gdb::unique_xmalloc_ptr<char> demangled
18799         (gdb_demangle (linkage_name, DMGL_TYPES));
18800       if (demangled != nullptr)
18801         {
18802           const char *base;
18803
18804           /* Strip any leading namespaces/classes, keep only the base name.
18805              DW_AT_name for named DIEs does not contain the prefixes.  */
18806           base = strrchr (demangled.get (), ':');
18807           if (base && base > demangled.get () && base[-1] == ':')
18808             base++;
18809           else
18810             base = demangled.get ();
18811
18812           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18813           name = obstack_strdup (&objfile->per_bfd->storage_obstack, base);
18814         }
18815     }
18816
18817   fixup_called = 1;
18818 }
18819
18820 /* Process the attributes that had to be skipped in the first round. These
18821    attributes are the ones that need str_offsets_base or addr_base attributes.
18822    They could not have been processed in the first round, because at the time
18823    the values of str_offsets_base or addr_base may not have been known.  */
18824 void read_attribute_reprocess (const struct die_reader_specs *reader,
18825                                struct attribute *attr)
18826 {
18827   struct dwarf2_cu *cu = reader->cu;
18828   switch (attr->form)
18829     {
18830       case DW_FORM_addrx:
18831       case DW_FORM_GNU_addr_index:
18832         DW_ADDR (attr) = read_addr_index (cu, DW_UNSND (attr));
18833         break;
18834       case DW_FORM_strx:
18835       case DW_FORM_strx1:
18836       case DW_FORM_strx2:
18837       case DW_FORM_strx3:
18838       case DW_FORM_strx4:
18839       case DW_FORM_GNU_str_index:
18840         {
18841           unsigned int str_index = DW_UNSND (attr);
18842           if (reader->dwo_file != NULL)
18843             {
18844               DW_STRING (attr) = read_dwo_str_index (reader, str_index);
18845               DW_STRING_IS_CANONICAL (attr) = 0;
18846             }
18847           else
18848             {
18849               DW_STRING (attr) = read_stub_str_index (cu, str_index);
18850               DW_STRING_IS_CANONICAL (attr) = 0;
18851             }
18852           break;
18853         }
18854       default:
18855         gdb_assert_not_reached (_("Unexpected DWARF form."));
18856     }
18857 }
18858
18859 /* Read an attribute value described by an attribute form.  */
18860
18861 static const gdb_byte *
18862 read_attribute_value (const struct die_reader_specs *reader,
18863                       struct attribute *attr, unsigned form,
18864                       LONGEST implicit_const, const gdb_byte *info_ptr,
18865                       bool *need_reprocess)
18866 {
18867   struct dwarf2_cu *cu = reader->cu;
18868   struct dwarf2_per_objfile *dwarf2_per_objfile
18869     = cu->per_cu->dwarf2_per_objfile;
18870   struct objfile *objfile = dwarf2_per_objfile->objfile;
18871   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18872   bfd *abfd = reader->abfd;
18873   struct comp_unit_head *cu_header = &cu->header;
18874   unsigned int bytes_read;
18875   struct dwarf_block *blk;
18876   *need_reprocess = false;
18877
18878   attr->form = (enum dwarf_form) form;
18879   switch (form)
18880     {
18881     case DW_FORM_ref_addr:
18882       if (cu->header.version == 2)
18883         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18884       else
18885         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18886                                        &cu->header, &bytes_read);
18887       info_ptr += bytes_read;
18888       break;
18889     case DW_FORM_GNU_ref_alt:
18890       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18891       info_ptr += bytes_read;
18892       break;
18893     case DW_FORM_addr:
18894       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18895       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18896       info_ptr += bytes_read;
18897       break;
18898     case DW_FORM_block2:
18899       blk = dwarf_alloc_block (cu);
18900       blk->size = read_2_bytes (abfd, info_ptr);
18901       info_ptr += 2;
18902       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18903       info_ptr += blk->size;
18904       DW_BLOCK (attr) = blk;
18905       break;
18906     case DW_FORM_block4:
18907       blk = dwarf_alloc_block (cu);
18908       blk->size = read_4_bytes (abfd, info_ptr);
18909       info_ptr += 4;
18910       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18911       info_ptr += blk->size;
18912       DW_BLOCK (attr) = blk;
18913       break;
18914     case DW_FORM_data2:
18915       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18916       info_ptr += 2;
18917       break;
18918     case DW_FORM_data4:
18919       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18920       info_ptr += 4;
18921       break;
18922     case DW_FORM_data8:
18923       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18924       info_ptr += 8;
18925       break;
18926     case DW_FORM_data16:
18927       blk = dwarf_alloc_block (cu);
18928       blk->size = 16;
18929       blk->data = read_n_bytes (abfd, info_ptr, 16);
18930       info_ptr += 16;
18931       DW_BLOCK (attr) = blk;
18932       break;
18933     case DW_FORM_sec_offset:
18934       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18935       info_ptr += bytes_read;
18936       break;
18937     case DW_FORM_string:
18938       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18939       DW_STRING_IS_CANONICAL (attr) = 0;
18940       info_ptr += bytes_read;
18941       break;
18942     case DW_FORM_strp:
18943       if (!cu->per_cu->is_dwz)
18944         {
18945           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18946                                                    abfd, info_ptr, cu_header,
18947                                                    &bytes_read);
18948           DW_STRING_IS_CANONICAL (attr) = 0;
18949           info_ptr += bytes_read;
18950           break;
18951         }
18952       /* FALLTHROUGH */
18953     case DW_FORM_line_strp:
18954       if (!cu->per_cu->is_dwz)
18955         {
18956           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18957                                                         abfd, info_ptr,
18958                                                         cu_header, &bytes_read);
18959           DW_STRING_IS_CANONICAL (attr) = 0;
18960           info_ptr += bytes_read;
18961           break;
18962         }
18963       /* FALLTHROUGH */
18964     case DW_FORM_GNU_strp_alt:
18965       {
18966         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18967         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18968                                           &bytes_read);
18969
18970         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18971                                                           dwz, str_offset);
18972         DW_STRING_IS_CANONICAL (attr) = 0;
18973         info_ptr += bytes_read;
18974       }
18975       break;
18976     case DW_FORM_exprloc:
18977     case DW_FORM_block:
18978       blk = dwarf_alloc_block (cu);
18979       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18980       info_ptr += bytes_read;
18981       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18982       info_ptr += blk->size;
18983       DW_BLOCK (attr) = blk;
18984       break;
18985     case DW_FORM_block1:
18986       blk = dwarf_alloc_block (cu);
18987       blk->size = read_1_byte (abfd, info_ptr);
18988       info_ptr += 1;
18989       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18990       info_ptr += blk->size;
18991       DW_BLOCK (attr) = blk;
18992       break;
18993     case DW_FORM_data1:
18994       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18995       info_ptr += 1;
18996       break;
18997     case DW_FORM_flag:
18998       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18999       info_ptr += 1;
19000       break;
19001     case DW_FORM_flag_present:
19002       DW_UNSND (attr) = 1;
19003       break;
19004     case DW_FORM_sdata:
19005       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19006       info_ptr += bytes_read;
19007       break;
19008     case DW_FORM_udata:
19009     case DW_FORM_rnglistx:
19010       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19011       info_ptr += bytes_read;
19012       break;
19013     case DW_FORM_ref1:
19014       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19015                          + read_1_byte (abfd, info_ptr));
19016       info_ptr += 1;
19017       break;
19018     case DW_FORM_ref2:
19019       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19020                          + read_2_bytes (abfd, info_ptr));
19021       info_ptr += 2;
19022       break;
19023     case DW_FORM_ref4:
19024       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19025                          + read_4_bytes (abfd, info_ptr));
19026       info_ptr += 4;
19027       break;
19028     case DW_FORM_ref8:
19029       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19030                          + read_8_bytes (abfd, info_ptr));
19031       info_ptr += 8;
19032       break;
19033     case DW_FORM_ref_sig8:
19034       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19035       info_ptr += 8;
19036       break;
19037     case DW_FORM_ref_udata:
19038       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19039                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19040       info_ptr += bytes_read;
19041       break;
19042     case DW_FORM_indirect:
19043       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19044       info_ptr += bytes_read;
19045       if (form == DW_FORM_implicit_const)
19046         {
19047           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19048           info_ptr += bytes_read;
19049         }
19050       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19051                                        info_ptr, need_reprocess);
19052       break;
19053     case DW_FORM_implicit_const:
19054       DW_SND (attr) = implicit_const;
19055       break;
19056     case DW_FORM_addrx:
19057     case DW_FORM_GNU_addr_index:
19058       *need_reprocess = true;
19059       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19060       info_ptr += bytes_read;
19061       break;
19062     case DW_FORM_strx:
19063     case DW_FORM_strx1:
19064     case DW_FORM_strx2:
19065     case DW_FORM_strx3:
19066     case DW_FORM_strx4:
19067     case DW_FORM_GNU_str_index:
19068       {
19069         ULONGEST str_index;
19070         if (form == DW_FORM_strx1)
19071           {
19072             str_index = read_1_byte (abfd, info_ptr);
19073             info_ptr += 1;
19074           }
19075         else if (form == DW_FORM_strx2)
19076           {
19077             str_index = read_2_bytes (abfd, info_ptr);
19078             info_ptr += 2;
19079           }
19080         else if (form == DW_FORM_strx3)
19081           {
19082             str_index = read_3_bytes (abfd, info_ptr);
19083             info_ptr += 3;
19084           }
19085         else if (form == DW_FORM_strx4)
19086           {
19087             str_index = read_4_bytes (abfd, info_ptr);
19088             info_ptr += 4;
19089           }
19090         else
19091           {
19092             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19093             info_ptr += bytes_read;
19094           }
19095         *need_reprocess = true;
19096          DW_UNSND (attr) = str_index;
19097         }
19098       break;
19099     default:
19100       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19101              dwarf_form_name (form),
19102              bfd_get_filename (abfd));
19103     }
19104
19105   /* Super hack.  */
19106   if (cu->per_cu->is_dwz && attr->form_is_ref ())
19107     attr->form = DW_FORM_GNU_ref_alt;
19108
19109   /* We have seen instances where the compiler tried to emit a byte
19110      size attribute of -1 which ended up being encoded as an unsigned
19111      0xffffffff.  Although 0xffffffff is technically a valid size value,
19112      an object of this size seems pretty unlikely so we can relatively
19113      safely treat these cases as if the size attribute was invalid and
19114      treat them as zero by default.  */
19115   if (attr->name == DW_AT_byte_size
19116       && form == DW_FORM_data4
19117       && DW_UNSND (attr) >= 0xffffffff)
19118     {
19119       complaint
19120         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19121          hex_string (DW_UNSND (attr)));
19122       DW_UNSND (attr) = 0;
19123     }
19124
19125   return info_ptr;
19126 }
19127
19128 /* Read an attribute described by an abbreviated attribute.  */
19129
19130 static const gdb_byte *
19131 read_attribute (const struct die_reader_specs *reader,
19132                 struct attribute *attr, struct attr_abbrev *abbrev,
19133                 const gdb_byte *info_ptr, bool *need_reprocess)
19134 {
19135   attr->name = abbrev->name;
19136   return read_attribute_value (reader, attr, abbrev->form,
19137                                abbrev->implicit_const, info_ptr,
19138                                need_reprocess);
19139 }
19140
19141 static CORE_ADDR
19142 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19143               unsigned int *bytes_read)
19144 {
19145   struct comp_unit_head *cu_header = &cu->header;
19146   CORE_ADDR retval = 0;
19147
19148   if (cu_header->signed_addr_p)
19149     {
19150       switch (cu_header->addr_size)
19151         {
19152         case 2:
19153           retval = bfd_get_signed_16 (abfd, buf);
19154           break;
19155         case 4:
19156           retval = bfd_get_signed_32 (abfd, buf);
19157           break;
19158         case 8:
19159           retval = bfd_get_signed_64 (abfd, buf);
19160           break;
19161         default:
19162           internal_error (__FILE__, __LINE__,
19163                           _("read_address: bad switch, signed [in module %s]"),
19164                           bfd_get_filename (abfd));
19165         }
19166     }
19167   else
19168     {
19169       switch (cu_header->addr_size)
19170         {
19171         case 2:
19172           retval = bfd_get_16 (abfd, buf);
19173           break;
19174         case 4:
19175           retval = bfd_get_32 (abfd, buf);
19176           break;
19177         case 8:
19178           retval = bfd_get_64 (abfd, buf);
19179           break;
19180         default:
19181           internal_error (__FILE__, __LINE__,
19182                           _("read_address: bad switch, "
19183                             "unsigned [in module %s]"),
19184                           bfd_get_filename (abfd));
19185         }
19186     }
19187
19188   *bytes_read = cu_header->addr_size;
19189   return retval;
19190 }
19191
19192 /* Read the initial length from a section.  The (draft) DWARF 3
19193    specification allows the initial length to take up either 4 bytes
19194    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19195    bytes describe the length and all offsets will be 8 bytes in length
19196    instead of 4.
19197
19198    An older, non-standard 64-bit format is also handled by this
19199    function.  The older format in question stores the initial length
19200    as an 8-byte quantity without an escape value.  Lengths greater
19201    than 2^32 aren't very common which means that the initial 4 bytes
19202    is almost always zero.  Since a length value of zero doesn't make
19203    sense for the 32-bit format, this initial zero can be considered to
19204    be an escape value which indicates the presence of the older 64-bit
19205    format.  As written, the code can't detect (old format) lengths
19206    greater than 4GB.  If it becomes necessary to handle lengths
19207    somewhat larger than 4GB, we could allow other small values (such
19208    as the non-sensical values of 1, 2, and 3) to also be used as
19209    escape values indicating the presence of the old format.
19210
19211    The value returned via bytes_read should be used to increment the
19212    relevant pointer after calling read_initial_length().
19213
19214    [ Note:  read_initial_length() and read_offset() are based on the
19215      document entitled "DWARF Debugging Information Format", revision
19216      3, draft 8, dated November 19, 2001.  This document was obtained
19217      from:
19218
19219         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19220
19221      This document is only a draft and is subject to change.  (So beware.)
19222
19223      Details regarding the older, non-standard 64-bit format were
19224      determined empirically by examining 64-bit ELF files produced by
19225      the SGI toolchain on an IRIX 6.5 machine.
19226
19227      - Kevin, July 16, 2002
19228    ] */
19229
19230 static LONGEST
19231 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19232 {
19233   LONGEST length = bfd_get_32 (abfd, buf);
19234
19235   if (length == 0xffffffff)
19236     {
19237       length = bfd_get_64 (abfd, buf + 4);
19238       *bytes_read = 12;
19239     }
19240   else if (length == 0)
19241     {
19242       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19243       length = bfd_get_64 (abfd, buf);
19244       *bytes_read = 8;
19245     }
19246   else
19247     {
19248       *bytes_read = 4;
19249     }
19250
19251   return length;
19252 }
19253
19254 /* Cover function for read_initial_length.
19255    Returns the length of the object at BUF, and stores the size of the
19256    initial length in *BYTES_READ and stores the size that offsets will be in
19257    *OFFSET_SIZE.
19258    If the initial length size is not equivalent to that specified in
19259    CU_HEADER then issue a complaint.
19260    This is useful when reading non-comp-unit headers.  */
19261
19262 static LONGEST
19263 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19264                                         const struct comp_unit_head *cu_header,
19265                                         unsigned int *bytes_read,
19266                                         unsigned int *offset_size)
19267 {
19268   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19269
19270   gdb_assert (cu_header->initial_length_size == 4
19271               || cu_header->initial_length_size == 8
19272               || cu_header->initial_length_size == 12);
19273
19274   if (cu_header->initial_length_size != *bytes_read)
19275     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19276
19277   *offset_size = (*bytes_read == 4) ? 4 : 8;
19278   return length;
19279 }
19280
19281 /* Read an offset from the data stream.  The size of the offset is
19282    given by cu_header->offset_size.  */
19283
19284 static LONGEST
19285 read_offset (bfd *abfd, const gdb_byte *buf,
19286              const struct comp_unit_head *cu_header,
19287              unsigned int *bytes_read)
19288 {
19289   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19290
19291   *bytes_read = cu_header->offset_size;
19292   return offset;
19293 }
19294
19295 /* Read an offset from the data stream.  */
19296
19297 static LONGEST
19298 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19299 {
19300   LONGEST retval = 0;
19301
19302   switch (offset_size)
19303     {
19304     case 4:
19305       retval = bfd_get_32 (abfd, buf);
19306       break;
19307     case 8:
19308       retval = bfd_get_64 (abfd, buf);
19309       break;
19310     default:
19311       internal_error (__FILE__, __LINE__,
19312                       _("read_offset_1: bad switch [in module %s]"),
19313                       bfd_get_filename (abfd));
19314     }
19315
19316   return retval;
19317 }
19318
19319 static const gdb_byte *
19320 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19321 {
19322   /* If the size of a host char is 8 bits, we can return a pointer
19323      to the buffer, otherwise we have to copy the data to a buffer
19324      allocated on the temporary obstack.  */
19325   gdb_assert (HOST_CHAR_BIT == 8);
19326   return buf;
19327 }
19328
19329 static const char *
19330 read_direct_string (bfd *abfd, const gdb_byte *buf,
19331                     unsigned int *bytes_read_ptr)
19332 {
19333   /* If the size of a host char is 8 bits, we can return a pointer
19334      to the string, otherwise we have to copy the string to a buffer
19335      allocated on the temporary obstack.  */
19336   gdb_assert (HOST_CHAR_BIT == 8);
19337   if (*buf == '\0')
19338     {
19339       *bytes_read_ptr = 1;
19340       return NULL;
19341     }
19342   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19343   return (const char *) buf;
19344 }
19345
19346 /* Return pointer to string at section SECT offset STR_OFFSET with error
19347    reporting strings FORM_NAME and SECT_NAME.  */
19348
19349 static const char *
19350 read_indirect_string_at_offset_from (struct objfile *objfile,
19351                                      bfd *abfd, LONGEST str_offset,
19352                                      struct dwarf2_section_info *sect,
19353                                      const char *form_name,
19354                                      const char *sect_name)
19355 {
19356   sect->read (objfile);
19357   if (sect->buffer == NULL)
19358     error (_("%s used without %s section [in module %s]"),
19359            form_name, sect_name, bfd_get_filename (abfd));
19360   if (str_offset >= sect->size)
19361     error (_("%s pointing outside of %s section [in module %s]"),
19362            form_name, sect_name, bfd_get_filename (abfd));
19363   gdb_assert (HOST_CHAR_BIT == 8);
19364   if (sect->buffer[str_offset] == '\0')
19365     return NULL;
19366   return (const char *) (sect->buffer + str_offset);
19367 }
19368
19369 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19370
19371 static const char *
19372 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19373                                 bfd *abfd, LONGEST str_offset)
19374 {
19375   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19376                                               abfd, str_offset,
19377                                               &dwarf2_per_objfile->str,
19378                                               "DW_FORM_strp", ".debug_str");
19379 }
19380
19381 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19382
19383 static const char *
19384 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19385                                      bfd *abfd, LONGEST str_offset)
19386 {
19387   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19388                                               abfd, str_offset,
19389                                               &dwarf2_per_objfile->line_str,
19390                                               "DW_FORM_line_strp",
19391                                               ".debug_line_str");
19392 }
19393
19394 /* Read a string at offset STR_OFFSET in the .debug_str section from
19395    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19396    the string consists of a single NUL byte, return NULL; otherwise
19397    return a pointer to the string.  */
19398
19399 static const char *
19400 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19401                                LONGEST str_offset)
19402 {
19403   dwz->str.read (objfile);
19404
19405   if (dwz->str.buffer == NULL)
19406     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19407              "section [in module %s]"),
19408            bfd_get_filename (dwz->dwz_bfd.get ()));
19409   if (str_offset >= dwz->str.size)
19410     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19411              ".debug_str section [in module %s]"),
19412            bfd_get_filename (dwz->dwz_bfd.get ()));
19413   gdb_assert (HOST_CHAR_BIT == 8);
19414   if (dwz->str.buffer[str_offset] == '\0')
19415     return NULL;
19416   return (const char *) (dwz->str.buffer + str_offset);
19417 }
19418
19419 /* Return pointer to string at .debug_str offset as read from BUF.
19420    BUF is assumed to be in a compilation unit described by CU_HEADER.
19421    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19422
19423 static const char *
19424 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19425                       const gdb_byte *buf,
19426                       const struct comp_unit_head *cu_header,
19427                       unsigned int *bytes_read_ptr)
19428 {
19429   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19430
19431   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19432 }
19433
19434 /* Return pointer to string at .debug_line_str offset as read from BUF.
19435    BUF is assumed to be in a compilation unit described by CU_HEADER.
19436    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19437
19438 static const char *
19439 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19440                            bfd *abfd, const gdb_byte *buf,
19441                            const struct comp_unit_head *cu_header,
19442                            unsigned int *bytes_read_ptr)
19443 {
19444   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19445
19446   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19447                                               str_offset);
19448 }
19449
19450 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19451    ADDR_BASE is the DW_AT_addr_base (DW_AT_GNU_addr_base) attribute or zero.
19452    ADDR_SIZE is the size of addresses from the CU header.  */
19453
19454 static CORE_ADDR
19455 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19456                    unsigned int addr_index, gdb::optional<ULONGEST> addr_base,
19457                    int addr_size)
19458 {
19459   struct objfile *objfile = dwarf2_per_objfile->objfile;
19460   bfd *abfd = objfile->obfd;
19461   const gdb_byte *info_ptr;
19462   ULONGEST addr_base_or_zero = addr_base.has_value () ? *addr_base : 0;
19463
19464   dwarf2_per_objfile->addr.read (objfile);
19465   if (dwarf2_per_objfile->addr.buffer == NULL)
19466     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19467            objfile_name (objfile));
19468   if (addr_base_or_zero + addr_index * addr_size
19469       >= dwarf2_per_objfile->addr.size)
19470     error (_("DW_FORM_addr_index pointing outside of "
19471              ".debug_addr section [in module %s]"),
19472            objfile_name (objfile));
19473   info_ptr = (dwarf2_per_objfile->addr.buffer
19474               + addr_base_or_zero + addr_index * addr_size);
19475   if (addr_size == 4)
19476     return bfd_get_32 (abfd, info_ptr);
19477   else
19478     return bfd_get_64 (abfd, info_ptr);
19479 }
19480
19481 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19482
19483 static CORE_ADDR
19484 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19485 {
19486   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19487                             cu->addr_base, cu->header.addr_size);
19488 }
19489
19490 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19491
19492 static CORE_ADDR
19493 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19494                              unsigned int *bytes_read)
19495 {
19496   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19497   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19498
19499   return read_addr_index (cu, addr_index);
19500 }
19501
19502 /* Given an index in .debug_addr, fetch the value.
19503    NOTE: This can be called during dwarf expression evaluation,
19504    long after the debug information has been read, and thus per_cu->cu
19505    may no longer exist.  */
19506
19507 CORE_ADDR
19508 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19509                         unsigned int addr_index)
19510 {
19511   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19512   struct dwarf2_cu *cu = per_cu->cu;
19513   gdb::optional<ULONGEST> addr_base;
19514   int addr_size;
19515
19516   /* We need addr_base and addr_size.
19517      If we don't have PER_CU->cu, we have to get it.
19518      Nasty, but the alternative is storing the needed info in PER_CU,
19519      which at this point doesn't seem justified: it's not clear how frequently
19520      it would get used and it would increase the size of every PER_CU.
19521      Entry points like dwarf2_per_cu_addr_size do a similar thing
19522      so we're not in uncharted territory here.
19523      Alas we need to be a bit more complicated as addr_base is contained
19524      in the DIE.
19525
19526      We don't need to read the entire CU(/TU).
19527      We just need the header and top level die.
19528
19529      IWBN to use the aging mechanism to let us lazily later discard the CU.
19530      For now we skip this optimization.  */
19531
19532   if (cu != NULL)
19533     {
19534       addr_base = cu->addr_base;
19535       addr_size = cu->header.addr_size;
19536     }
19537   else
19538     {
19539       cutu_reader reader (per_cu, NULL, 0, 0, false);
19540       addr_base = reader.cu->addr_base;
19541       addr_size = reader.cu->header.addr_size;
19542     }
19543
19544   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19545                             addr_size);
19546 }
19547
19548 /* Given a DW_FORM_GNU_str_index value STR_INDEX, fetch the string.
19549    STR_SECTION, STR_OFFSETS_SECTION can be from a Fission stub or a
19550    DWO file.  */
19551
19552 static const char *
19553 read_str_index (struct dwarf2_cu *cu,
19554                 struct dwarf2_section_info *str_section,
19555                 struct dwarf2_section_info *str_offsets_section,
19556                 ULONGEST str_offsets_base, ULONGEST str_index)
19557 {
19558   struct dwarf2_per_objfile *dwarf2_per_objfile
19559     = cu->per_cu->dwarf2_per_objfile;
19560   struct objfile *objfile = dwarf2_per_objfile->objfile;
19561   const char *objf_name = objfile_name (objfile);
19562   bfd *abfd = objfile->obfd;
19563   const gdb_byte *info_ptr;
19564   ULONGEST str_offset;
19565   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
19566
19567   str_section->read (objfile);
19568   str_offsets_section->read (objfile);
19569   if (str_section->buffer == NULL)
19570     error (_("%s used without %s section"
19571              " in CU at offset %s [in module %s]"),
19572            form_name, str_section->get_name (),
19573            sect_offset_str (cu->header.sect_off), objf_name);
19574   if (str_offsets_section->buffer == NULL)
19575     error (_("%s used without %s section"
19576              " in CU at offset %s [in module %s]"),
19577            form_name, str_section->get_name (),
19578            sect_offset_str (cu->header.sect_off), objf_name);
19579   info_ptr = (str_offsets_section->buffer
19580               + str_offsets_base
19581               + str_index * cu->header.offset_size);
19582   if (cu->header.offset_size == 4)
19583     str_offset = bfd_get_32 (abfd, info_ptr);
19584   else
19585     str_offset = bfd_get_64 (abfd, info_ptr);
19586   if (str_offset >= str_section->size)
19587     error (_("Offset from %s pointing outside of"
19588              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19589            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19590   return (const char *) (str_section->buffer + str_offset);
19591 }
19592
19593 /* Given a DW_FORM_GNU_str_index from a DWO file, fetch the string.  */
19594
19595 static const char *
19596 read_dwo_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19597 {
19598   ULONGEST str_offsets_base = reader->cu->header.version >= 5
19599                               ? reader->cu->header.addr_size : 0;
19600   return read_str_index (reader->cu,
19601                          &reader->dwo_file->sections.str,
19602                          &reader->dwo_file->sections.str_offsets,
19603                          str_offsets_base, str_index);
19604 }
19605
19606 /* Given a DW_FORM_GNU_str_index from a Fission stub, fetch the string.  */
19607
19608 static const char *
19609 read_stub_str_index (struct dwarf2_cu *cu, ULONGEST str_index)
19610 {
19611   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19612   const char *objf_name = objfile_name (objfile);
19613   static const char form_name[] = "DW_FORM_GNU_str_index";
19614   static const char str_offsets_attr_name[] = "DW_AT_str_offsets";
19615
19616   if (!cu->str_offsets_base.has_value ())
19617     error (_("%s used in Fission stub without %s"
19618              " in CU at offset 0x%lx [in module %s]"),
19619            form_name, str_offsets_attr_name,
19620            (long) cu->header.offset_size, objf_name);
19621
19622   return read_str_index (cu,
19623                          &cu->per_cu->dwarf2_per_objfile->str,
19624                          &cu->per_cu->dwarf2_per_objfile->str_offsets,
19625                          *cu->str_offsets_base, str_index);
19626 }
19627
19628 /* Return the length of an LEB128 number in BUF.  */
19629
19630 static int
19631 leb128_size (const gdb_byte *buf)
19632 {
19633   const gdb_byte *begin = buf;
19634   gdb_byte byte;
19635
19636   while (1)
19637     {
19638       byte = *buf++;
19639       if ((byte & 128) == 0)
19640         return buf - begin;
19641     }
19642 }
19643
19644 static void
19645 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19646 {
19647   switch (lang)
19648     {
19649     case DW_LANG_C89:
19650     case DW_LANG_C99:
19651     case DW_LANG_C11:
19652     case DW_LANG_C:
19653     case DW_LANG_UPC:
19654       cu->language = language_c;
19655       break;
19656     case DW_LANG_Java:
19657     case DW_LANG_C_plus_plus:
19658     case DW_LANG_C_plus_plus_11:
19659     case DW_LANG_C_plus_plus_14:
19660       cu->language = language_cplus;
19661       break;
19662     case DW_LANG_D:
19663       cu->language = language_d;
19664       break;
19665     case DW_LANG_Fortran77:
19666     case DW_LANG_Fortran90:
19667     case DW_LANG_Fortran95:
19668     case DW_LANG_Fortran03:
19669     case DW_LANG_Fortran08:
19670       cu->language = language_fortran;
19671       break;
19672     case DW_LANG_Go:
19673       cu->language = language_go;
19674       break;
19675     case DW_LANG_Mips_Assembler:
19676       cu->language = language_asm;
19677       break;
19678     case DW_LANG_Ada83:
19679     case DW_LANG_Ada95:
19680       cu->language = language_ada;
19681       break;
19682     case DW_LANG_Modula2:
19683       cu->language = language_m2;
19684       break;
19685     case DW_LANG_Pascal83:
19686       cu->language = language_pascal;
19687       break;
19688     case DW_LANG_ObjC:
19689       cu->language = language_objc;
19690       break;
19691     case DW_LANG_Rust:
19692     case DW_LANG_Rust_old:
19693       cu->language = language_rust;
19694       break;
19695     case DW_LANG_Cobol74:
19696     case DW_LANG_Cobol85:
19697     default:
19698       cu->language = language_minimal;
19699       break;
19700     }
19701   cu->language_defn = language_def (cu->language);
19702 }
19703
19704 /* Return the named attribute or NULL if not there.  */
19705
19706 static struct attribute *
19707 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19708 {
19709   for (;;)
19710     {
19711       unsigned int i;
19712       struct attribute *spec = NULL;
19713
19714       for (i = 0; i < die->num_attrs; ++i)
19715         {
19716           if (die->attrs[i].name == name)
19717             return &die->attrs[i];
19718           if (die->attrs[i].name == DW_AT_specification
19719               || die->attrs[i].name == DW_AT_abstract_origin)
19720             spec = &die->attrs[i];
19721         }
19722
19723       if (!spec)
19724         break;
19725
19726       die = follow_die_ref (die, spec, &cu);
19727     }
19728
19729   return NULL;
19730 }
19731
19732 /* Return the named attribute or NULL if not there,
19733    but do not follow DW_AT_specification, etc.
19734    This is for use in contexts where we're reading .debug_types dies.
19735    Following DW_AT_specification, DW_AT_abstract_origin will take us
19736    back up the chain, and we want to go down.  */
19737
19738 static struct attribute *
19739 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19740 {
19741   unsigned int i;
19742
19743   for (i = 0; i < die->num_attrs; ++i)
19744     if (die->attrs[i].name == name)
19745       return &die->attrs[i];
19746
19747   return NULL;
19748 }
19749
19750 /* Return the string associated with a string-typed attribute, or NULL if it
19751    is either not found or is of an incorrect type.  */
19752
19753 static const char *
19754 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19755 {
19756   struct attribute *attr;
19757   const char *str = NULL;
19758
19759   attr = dwarf2_attr (die, name, cu);
19760
19761   if (attr != NULL)
19762     {
19763       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19764           || attr->form == DW_FORM_string
19765           || attr->form == DW_FORM_strx
19766           || attr->form == DW_FORM_strx1
19767           || attr->form == DW_FORM_strx2
19768           || attr->form == DW_FORM_strx3
19769           || attr->form == DW_FORM_strx4
19770           || attr->form == DW_FORM_GNU_str_index
19771           || attr->form == DW_FORM_GNU_strp_alt)
19772         str = DW_STRING (attr);
19773       else
19774         complaint (_("string type expected for attribute %s for "
19775                      "DIE at %s in module %s"),
19776                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19777                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19778     }
19779
19780   return str;
19781 }
19782
19783 /* Return the dwo name or NULL if not present. If present, it is in either
19784    DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.  */
19785 static const char *
19786 dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu)
19787 {
19788   const char *dwo_name = dwarf2_string_attr (die, DW_AT_GNU_dwo_name, cu);
19789   if (dwo_name == nullptr)
19790     dwo_name = dwarf2_string_attr (die, DW_AT_dwo_name, cu);
19791   return dwo_name;
19792 }
19793
19794 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19795    and holds a non-zero value.  This function should only be used for
19796    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19797
19798 static int
19799 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19800 {
19801   struct attribute *attr = dwarf2_attr (die, name, cu);
19802
19803   return (attr && DW_UNSND (attr));
19804 }
19805
19806 static int
19807 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19808 {
19809   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19810      which value is non-zero.  However, we have to be careful with
19811      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19812      (via dwarf2_flag_true_p) follows this attribute.  So we may
19813      end up accidently finding a declaration attribute that belongs
19814      to a different DIE referenced by the specification attribute,
19815      even though the given DIE does not have a declaration attribute.  */
19816   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19817           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19818 }
19819
19820 /* Return the die giving the specification for DIE, if there is
19821    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19822    containing the return value on output.  If there is no
19823    specification, but there is an abstract origin, that is
19824    returned.  */
19825
19826 static struct die_info *
19827 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19828 {
19829   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19830                                              *spec_cu);
19831
19832   if (spec_attr == NULL)
19833     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19834
19835   if (spec_attr == NULL)
19836     return NULL;
19837   else
19838     return follow_die_ref (die, spec_attr, spec_cu);
19839 }
19840
19841 /* Stub for free_line_header to match void * callback types.  */
19842
19843 static void
19844 free_line_header_voidp (void *arg)
19845 {
19846   struct line_header *lh = (struct line_header *) arg;
19847
19848   delete lh;
19849 }
19850
19851 void
19852 line_header::add_include_dir (const char *include_dir)
19853 {
19854   if (dwarf_line_debug >= 2)
19855     {
19856       size_t new_size;
19857       if (version >= 5)
19858         new_size = m_include_dirs.size ();
19859       else
19860         new_size = m_include_dirs.size () + 1;
19861       fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19862                           new_size, include_dir);
19863     }
19864   m_include_dirs.push_back (include_dir);
19865 }
19866
19867 void
19868 line_header::add_file_name (const char *name,
19869                             dir_index d_index,
19870                             unsigned int mod_time,
19871                             unsigned int length)
19872 {
19873   if (dwarf_line_debug >= 2)
19874     {
19875       size_t new_size;
19876       if (version >= 5)
19877         new_size = file_names_size ();
19878       else
19879         new_size = file_names_size () + 1;
19880       fprintf_unfiltered (gdb_stdlog, "Adding file %zu: %s\n",
19881                           new_size, name);
19882     }
19883   m_file_names.emplace_back (name, d_index, mod_time, length);
19884 }
19885
19886 /* A convenience function to find the proper .debug_line section for a CU.  */
19887
19888 static struct dwarf2_section_info *
19889 get_debug_line_section (struct dwarf2_cu *cu)
19890 {
19891   struct dwarf2_section_info *section;
19892   struct dwarf2_per_objfile *dwarf2_per_objfile
19893     = cu->per_cu->dwarf2_per_objfile;
19894
19895   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19896      DWO file.  */
19897   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19898     section = &cu->dwo_unit->dwo_file->sections.line;
19899   else if (cu->per_cu->is_dwz)
19900     {
19901       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19902
19903       section = &dwz->line;
19904     }
19905   else
19906     section = &dwarf2_per_objfile->line;
19907
19908   return section;
19909 }
19910
19911 /* Read directory or file name entry format, starting with byte of
19912    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19913    entries count and the entries themselves in the described entry
19914    format.  */
19915
19916 static void
19917 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19918                         bfd *abfd, const gdb_byte **bufp,
19919                         struct line_header *lh,
19920                         const struct comp_unit_head *cu_header,
19921                         void (*callback) (struct line_header *lh,
19922                                           const char *name,
19923                                           dir_index d_index,
19924                                           unsigned int mod_time,
19925                                           unsigned int length))
19926 {
19927   gdb_byte format_count, formati;
19928   ULONGEST data_count, datai;
19929   const gdb_byte *buf = *bufp;
19930   const gdb_byte *format_header_data;
19931   unsigned int bytes_read;
19932
19933   format_count = read_1_byte (abfd, buf);
19934   buf += 1;
19935   format_header_data = buf;
19936   for (formati = 0; formati < format_count; formati++)
19937     {
19938       read_unsigned_leb128 (abfd, buf, &bytes_read);
19939       buf += bytes_read;
19940       read_unsigned_leb128 (abfd, buf, &bytes_read);
19941       buf += bytes_read;
19942     }
19943
19944   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19945   buf += bytes_read;
19946   for (datai = 0; datai < data_count; datai++)
19947     {
19948       const gdb_byte *format = format_header_data;
19949       struct file_entry fe;
19950
19951       for (formati = 0; formati < format_count; formati++)
19952         {
19953           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19954           format += bytes_read;
19955
19956           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19957           format += bytes_read;
19958
19959           gdb::optional<const char *> string;
19960           gdb::optional<unsigned int> uint;
19961
19962           switch (form)
19963             {
19964             case DW_FORM_string:
19965               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19966               buf += bytes_read;
19967               break;
19968
19969             case DW_FORM_line_strp:
19970               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
19971                                                          abfd, buf,
19972                                                          cu_header,
19973                                                          &bytes_read));
19974               buf += bytes_read;
19975               break;
19976
19977             case DW_FORM_data1:
19978               uint.emplace (read_1_byte (abfd, buf));
19979               buf += 1;
19980               break;
19981
19982             case DW_FORM_data2:
19983               uint.emplace (read_2_bytes (abfd, buf));
19984               buf += 2;
19985               break;
19986
19987             case DW_FORM_data4:
19988               uint.emplace (read_4_bytes (abfd, buf));
19989               buf += 4;
19990               break;
19991
19992             case DW_FORM_data8:
19993               uint.emplace (read_8_bytes (abfd, buf));
19994               buf += 8;
19995               break;
19996
19997             case DW_FORM_data16:
19998               /*  This is used for MD5, but file_entry does not record MD5s. */
19999               buf += 16;
20000               break;
20001
20002             case DW_FORM_udata:
20003               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20004               buf += bytes_read;
20005               break;
20006
20007             case DW_FORM_block:
20008               /* It is valid only for DW_LNCT_timestamp which is ignored by
20009                  current GDB.  */
20010               break;
20011             }
20012
20013           switch (content_type)
20014             {
20015             case DW_LNCT_path:
20016               if (string.has_value ())
20017                 fe.name = *string;
20018               break;
20019             case DW_LNCT_directory_index:
20020               if (uint.has_value ())
20021                 fe.d_index = (dir_index) *uint;
20022               break;
20023             case DW_LNCT_timestamp:
20024               if (uint.has_value ())
20025                 fe.mod_time = *uint;
20026               break;
20027             case DW_LNCT_size:
20028               if (uint.has_value ())
20029                 fe.length = *uint;
20030               break;
20031             case DW_LNCT_MD5:
20032               break;
20033             default:
20034               complaint (_("Unknown format content type %s"),
20035                          pulongest (content_type));
20036             }
20037         }
20038
20039       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20040     }
20041
20042   *bufp = buf;
20043 }
20044
20045 /* Read the statement program header starting at OFFSET in
20046    .debug_line, or .debug_line.dwo.  Return a pointer
20047    to a struct line_header, allocated using xmalloc.
20048    Returns NULL if there is a problem reading the header, e.g., if it
20049    has a version we don't understand.
20050
20051    NOTE: the strings in the include directory and file name tables of
20052    the returned object point into the dwarf line section buffer,
20053    and must not be freed.  */
20054
20055 static line_header_up
20056 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20057 {
20058   const gdb_byte *line_ptr;
20059   unsigned int bytes_read, offset_size;
20060   int i;
20061   const char *cur_dir, *cur_file;
20062   struct dwarf2_section_info *section;
20063   bfd *abfd;
20064   struct dwarf2_per_objfile *dwarf2_per_objfile
20065     = cu->per_cu->dwarf2_per_objfile;
20066
20067   section = get_debug_line_section (cu);
20068   section->read (dwarf2_per_objfile->objfile);
20069   if (section->buffer == NULL)
20070     {
20071       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20072         complaint (_("missing .debug_line.dwo section"));
20073       else
20074         complaint (_("missing .debug_line section"));
20075       return 0;
20076     }
20077
20078   /* We can't do this until we know the section is non-empty.
20079      Only then do we know we have such a section.  */
20080   abfd = section->get_bfd_owner ();
20081
20082   /* Make sure that at least there's room for the total_length field.
20083      That could be 12 bytes long, but we're just going to fudge that.  */
20084   if (to_underlying (sect_off) + 4 >= section->size)
20085     {
20086       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20087       return 0;
20088     }
20089
20090   line_header_up lh (new line_header ());
20091
20092   lh->sect_off = sect_off;
20093   lh->offset_in_dwz = cu->per_cu->is_dwz;
20094
20095   line_ptr = section->buffer + to_underlying (sect_off);
20096
20097   /* Read in the header.  */
20098   lh->total_length =
20099     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20100                                             &bytes_read, &offset_size);
20101   line_ptr += bytes_read;
20102
20103   const gdb_byte *start_here = line_ptr;
20104
20105   if (line_ptr + lh->total_length > (section->buffer + section->size))
20106     {
20107       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20108       return 0;
20109     }
20110   lh->statement_program_end = start_here + lh->total_length;
20111   lh->version = read_2_bytes (abfd, line_ptr);
20112   line_ptr += 2;
20113   if (lh->version > 5)
20114     {
20115       /* This is a version we don't understand.  The format could have
20116          changed in ways we don't handle properly so just punt.  */
20117       complaint (_("unsupported version in .debug_line section"));
20118       return NULL;
20119     }
20120   if (lh->version >= 5)
20121     {
20122       gdb_byte segment_selector_size;
20123
20124       /* Skip address size.  */
20125       read_1_byte (abfd, line_ptr);
20126       line_ptr += 1;
20127
20128       segment_selector_size = read_1_byte (abfd, line_ptr);
20129       line_ptr += 1;
20130       if (segment_selector_size != 0)
20131         {
20132           complaint (_("unsupported segment selector size %u "
20133                        "in .debug_line section"),
20134                      segment_selector_size);
20135           return NULL;
20136         }
20137     }
20138   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20139   line_ptr += offset_size;
20140   lh->statement_program_start = line_ptr + lh->header_length;
20141   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20142   line_ptr += 1;
20143   if (lh->version >= 4)
20144     {
20145       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20146       line_ptr += 1;
20147     }
20148   else
20149     lh->maximum_ops_per_instruction = 1;
20150
20151   if (lh->maximum_ops_per_instruction == 0)
20152     {
20153       lh->maximum_ops_per_instruction = 1;
20154       complaint (_("invalid maximum_ops_per_instruction "
20155                    "in `.debug_line' section"));
20156     }
20157
20158   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20159   line_ptr += 1;
20160   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20161   line_ptr += 1;
20162   lh->line_range = read_1_byte (abfd, line_ptr);
20163   line_ptr += 1;
20164   lh->opcode_base = read_1_byte (abfd, line_ptr);
20165   line_ptr += 1;
20166   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20167
20168   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20169   for (i = 1; i < lh->opcode_base; ++i)
20170     {
20171       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20172       line_ptr += 1;
20173     }
20174
20175   if (lh->version >= 5)
20176     {
20177       /* Read directory table.  */
20178       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20179                               &cu->header,
20180                               [] (struct line_header *header, const char *name,
20181                                   dir_index d_index, unsigned int mod_time,
20182                                   unsigned int length)
20183         {
20184           header->add_include_dir (name);
20185         });
20186
20187       /* Read file name table.  */
20188       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20189                               &cu->header,
20190                               [] (struct line_header *header, const char *name,
20191                                   dir_index d_index, unsigned int mod_time,
20192                                   unsigned int length)
20193         {
20194           header->add_file_name (name, d_index, mod_time, length);
20195         });
20196     }
20197   else
20198     {
20199       /* Read directory table.  */
20200       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20201         {
20202           line_ptr += bytes_read;
20203           lh->add_include_dir (cur_dir);
20204         }
20205       line_ptr += bytes_read;
20206
20207       /* Read file name table.  */
20208       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20209         {
20210           unsigned int mod_time, length;
20211           dir_index d_index;
20212
20213           line_ptr += bytes_read;
20214           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20215           line_ptr += bytes_read;
20216           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20217           line_ptr += bytes_read;
20218           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20219           line_ptr += bytes_read;
20220
20221           lh->add_file_name (cur_file, d_index, mod_time, length);
20222         }
20223       line_ptr += bytes_read;
20224     }
20225
20226   if (line_ptr > (section->buffer + section->size))
20227     complaint (_("line number info header doesn't "
20228                  "fit in `.debug_line' section"));
20229
20230   return lh;
20231 }
20232
20233 /* Subroutine of dwarf_decode_lines to simplify it.
20234    Return the file name of the psymtab for the given file_entry.
20235    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20236    If space for the result is malloc'd, *NAME_HOLDER will be set.
20237    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20238
20239 static const char *
20240 psymtab_include_file_name (const struct line_header *lh, const file_entry &fe,
20241                            const dwarf2_psymtab *pst,
20242                            const char *comp_dir,
20243                            gdb::unique_xmalloc_ptr<char> *name_holder)
20244 {
20245   const char *include_name = fe.name;
20246   const char *include_name_to_compare = include_name;
20247   const char *pst_filename;
20248   int file_is_pst;
20249
20250   const char *dir_name = fe.include_dir (lh);
20251
20252   gdb::unique_xmalloc_ptr<char> hold_compare;
20253   if (!IS_ABSOLUTE_PATH (include_name)
20254       && (dir_name != NULL || comp_dir != NULL))
20255     {
20256       /* Avoid creating a duplicate psymtab for PST.
20257          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20258          Before we do the comparison, however, we need to account
20259          for DIR_NAME and COMP_DIR.
20260          First prepend dir_name (if non-NULL).  If we still don't
20261          have an absolute path prepend comp_dir (if non-NULL).
20262          However, the directory we record in the include-file's
20263          psymtab does not contain COMP_DIR (to match the
20264          corresponding symtab(s)).
20265
20266          Example:
20267
20268          bash$ cd /tmp
20269          bash$ gcc -g ./hello.c
20270          include_name = "hello.c"
20271          dir_name = "."
20272          DW_AT_comp_dir = comp_dir = "/tmp"
20273          DW_AT_name = "./hello.c"
20274
20275       */
20276
20277       if (dir_name != NULL)
20278         {
20279           name_holder->reset (concat (dir_name, SLASH_STRING,
20280                                       include_name, (char *) NULL));
20281           include_name = name_holder->get ();
20282           include_name_to_compare = include_name;
20283         }
20284       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20285         {
20286           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20287                                       include_name, (char *) NULL));
20288           include_name_to_compare = hold_compare.get ();
20289         }
20290     }
20291
20292   pst_filename = pst->filename;
20293   gdb::unique_xmalloc_ptr<char> copied_name;
20294   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20295     {
20296       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20297                                  pst_filename, (char *) NULL));
20298       pst_filename = copied_name.get ();
20299     }
20300
20301   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20302
20303   if (file_is_pst)
20304     return NULL;
20305   return include_name;
20306 }
20307
20308 /* State machine to track the state of the line number program.  */
20309
20310 class lnp_state_machine
20311 {
20312 public:
20313   /* Initialize a machine state for the start of a line number
20314      program.  */
20315   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20316                      bool record_lines_p);
20317
20318   file_entry *current_file ()
20319   {
20320     /* lh->file_names is 0-based, but the file name numbers in the
20321        statement program are 1-based.  */
20322     return m_line_header->file_name_at (m_file);
20323   }
20324
20325   /* Record the line in the state machine.  END_SEQUENCE is true if
20326      we're processing the end of a sequence.  */
20327   void record_line (bool end_sequence);
20328
20329   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20330      nop-out rest of the lines in this sequence.  */
20331   void check_line_address (struct dwarf2_cu *cu,
20332                            const gdb_byte *line_ptr,
20333                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20334
20335   void handle_set_discriminator (unsigned int discriminator)
20336   {
20337     m_discriminator = discriminator;
20338     m_line_has_non_zero_discriminator |= discriminator != 0;
20339   }
20340
20341   /* Handle DW_LNE_set_address.  */
20342   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20343   {
20344     m_op_index = 0;
20345     address += baseaddr;
20346     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20347   }
20348
20349   /* Handle DW_LNS_advance_pc.  */
20350   void handle_advance_pc (CORE_ADDR adjust);
20351
20352   /* Handle a special opcode.  */
20353   void handle_special_opcode (unsigned char op_code);
20354
20355   /* Handle DW_LNS_advance_line.  */
20356   void handle_advance_line (int line_delta)
20357   {
20358     advance_line (line_delta);
20359   }
20360
20361   /* Handle DW_LNS_set_file.  */
20362   void handle_set_file (file_name_index file);
20363
20364   /* Handle DW_LNS_negate_stmt.  */
20365   void handle_negate_stmt ()
20366   {
20367     m_is_stmt = !m_is_stmt;
20368   }
20369
20370   /* Handle DW_LNS_const_add_pc.  */
20371   void handle_const_add_pc ();
20372
20373   /* Handle DW_LNS_fixed_advance_pc.  */
20374   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20375   {
20376     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20377     m_op_index = 0;
20378   }
20379
20380   /* Handle DW_LNS_copy.  */
20381   void handle_copy ()
20382   {
20383     record_line (false);
20384     m_discriminator = 0;
20385   }
20386
20387   /* Handle DW_LNE_end_sequence.  */
20388   void handle_end_sequence ()
20389   {
20390     m_currently_recording_lines = true;
20391   }
20392
20393 private:
20394   /* Advance the line by LINE_DELTA.  */
20395   void advance_line (int line_delta)
20396   {
20397     m_line += line_delta;
20398
20399     if (line_delta != 0)
20400       m_line_has_non_zero_discriminator = m_discriminator != 0;
20401   }
20402
20403   struct dwarf2_cu *m_cu;
20404
20405   gdbarch *m_gdbarch;
20406
20407   /* True if we're recording lines.
20408      Otherwise we're building partial symtabs and are just interested in
20409      finding include files mentioned by the line number program.  */
20410   bool m_record_lines_p;
20411
20412   /* The line number header.  */
20413   line_header *m_line_header;
20414
20415   /* These are part of the standard DWARF line number state machine,
20416      and initialized according to the DWARF spec.  */
20417
20418   unsigned char m_op_index = 0;
20419   /* The line table index of the current file.  */
20420   file_name_index m_file = 1;
20421   unsigned int m_line = 1;
20422
20423   /* These are initialized in the constructor.  */
20424
20425   CORE_ADDR m_address;
20426   bool m_is_stmt;
20427   unsigned int m_discriminator;
20428
20429   /* Additional bits of state we need to track.  */
20430
20431   /* The last file that we called dwarf2_start_subfile for.
20432      This is only used for TLLs.  */
20433   unsigned int m_last_file = 0;
20434   /* The last file a line number was recorded for.  */
20435   struct subfile *m_last_subfile = NULL;
20436
20437   /* When true, record the lines we decode.  */
20438   bool m_currently_recording_lines = false;
20439
20440   /* The last line number that was recorded, used to coalesce
20441      consecutive entries for the same line.  This can happen, for
20442      example, when discriminators are present.  PR 17276.  */
20443   unsigned int m_last_line = 0;
20444   bool m_line_has_non_zero_discriminator = false;
20445 };
20446
20447 void
20448 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20449 {
20450   CORE_ADDR addr_adj = (((m_op_index + adjust)
20451                          / m_line_header->maximum_ops_per_instruction)
20452                         * m_line_header->minimum_instruction_length);
20453   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20454   m_op_index = ((m_op_index + adjust)
20455                 % m_line_header->maximum_ops_per_instruction);
20456 }
20457
20458 void
20459 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20460 {
20461   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20462   CORE_ADDR addr_adj = (((m_op_index
20463                           + (adj_opcode / m_line_header->line_range))
20464                          / m_line_header->maximum_ops_per_instruction)
20465                         * m_line_header->minimum_instruction_length);
20466   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20467   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20468                 % m_line_header->maximum_ops_per_instruction);
20469
20470   int line_delta = (m_line_header->line_base
20471                     + (adj_opcode % m_line_header->line_range));
20472   advance_line (line_delta);
20473   record_line (false);
20474   m_discriminator = 0;
20475 }
20476
20477 void
20478 lnp_state_machine::handle_set_file (file_name_index file)
20479 {
20480   m_file = file;
20481
20482   const file_entry *fe = current_file ();
20483   if (fe == NULL)
20484     dwarf2_debug_line_missing_file_complaint ();
20485   else if (m_record_lines_p)
20486     {
20487       const char *dir = fe->include_dir (m_line_header);
20488
20489       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20490       m_line_has_non_zero_discriminator = m_discriminator != 0;
20491       dwarf2_start_subfile (m_cu, fe->name, dir);
20492     }
20493 }
20494
20495 void
20496 lnp_state_machine::handle_const_add_pc ()
20497 {
20498   CORE_ADDR adjust
20499     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20500
20501   CORE_ADDR addr_adj
20502     = (((m_op_index + adjust)
20503         / m_line_header->maximum_ops_per_instruction)
20504        * m_line_header->minimum_instruction_length);
20505
20506   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20507   m_op_index = ((m_op_index + adjust)
20508                 % m_line_header->maximum_ops_per_instruction);
20509 }
20510
20511 /* Return non-zero if we should add LINE to the line number table.
20512    LINE is the line to add, LAST_LINE is the last line that was added,
20513    LAST_SUBFILE is the subfile for LAST_LINE.
20514    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20515    had a non-zero discriminator.
20516
20517    We have to be careful in the presence of discriminators.
20518    E.g., for this line:
20519
20520      for (i = 0; i < 100000; i++);
20521
20522    clang can emit four line number entries for that one line,
20523    each with a different discriminator.
20524    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20525
20526    However, we want gdb to coalesce all four entries into one.
20527    Otherwise the user could stepi into the middle of the line and
20528    gdb would get confused about whether the pc really was in the
20529    middle of the line.
20530
20531    Things are further complicated by the fact that two consecutive
20532    line number entries for the same line is a heuristic used by gcc
20533    to denote the end of the prologue.  So we can't just discard duplicate
20534    entries, we have to be selective about it.  The heuristic we use is
20535    that we only collapse consecutive entries for the same line if at least
20536    one of those entries has a non-zero discriminator.  PR 17276.
20537
20538    Note: Addresses in the line number state machine can never go backwards
20539    within one sequence, thus this coalescing is ok.  */
20540
20541 static int
20542 dwarf_record_line_p (struct dwarf2_cu *cu,
20543                      unsigned int line, unsigned int last_line,
20544                      int line_has_non_zero_discriminator,
20545                      struct subfile *last_subfile)
20546 {
20547   if (cu->get_builder ()->get_current_subfile () != last_subfile)
20548     return 1;
20549   if (line != last_line)
20550     return 1;
20551   /* Same line for the same file that we've seen already.
20552      As a last check, for pr 17276, only record the line if the line
20553      has never had a non-zero discriminator.  */
20554   if (!line_has_non_zero_discriminator)
20555     return 1;
20556   return 0;
20557 }
20558
20559 /* Use the CU's builder to record line number LINE beginning at
20560    address ADDRESS in the line table of subfile SUBFILE.  */
20561
20562 static void
20563 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20564                      unsigned int line, CORE_ADDR address,
20565                      struct dwarf2_cu *cu)
20566 {
20567   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20568
20569   if (dwarf_line_debug)
20570     {
20571       fprintf_unfiltered (gdb_stdlog,
20572                           "Recording line %u, file %s, address %s\n",
20573                           line, lbasename (subfile->name),
20574                           paddress (gdbarch, address));
20575     }
20576
20577   if (cu != nullptr)
20578     cu->get_builder ()->record_line (subfile, line, addr);
20579 }
20580
20581 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20582    Mark the end of a set of line number records.
20583    The arguments are the same as for dwarf_record_line_1.
20584    If SUBFILE is NULL the request is ignored.  */
20585
20586 static void
20587 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20588                    CORE_ADDR address, struct dwarf2_cu *cu)
20589 {
20590   if (subfile == NULL)
20591     return;
20592
20593   if (dwarf_line_debug)
20594     {
20595       fprintf_unfiltered (gdb_stdlog,
20596                           "Finishing current line, file %s, address %s\n",
20597                           lbasename (subfile->name),
20598                           paddress (gdbarch, address));
20599     }
20600
20601   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20602 }
20603
20604 void
20605 lnp_state_machine::record_line (bool end_sequence)
20606 {
20607   if (dwarf_line_debug)
20608     {
20609       fprintf_unfiltered (gdb_stdlog,
20610                           "Processing actual line %u: file %u,"
20611                           " address %s, is_stmt %u, discrim %u%s\n",
20612                           m_line, m_file,
20613                           paddress (m_gdbarch, m_address),
20614                           m_is_stmt, m_discriminator,
20615                           (end_sequence ? "\t(end sequence)" : ""));
20616     }
20617
20618   file_entry *fe = current_file ();
20619
20620   if (fe == NULL)
20621     dwarf2_debug_line_missing_file_complaint ();
20622   /* For now we ignore lines not starting on an instruction boundary.
20623      But not when processing end_sequence for compatibility with the
20624      previous version of the code.  */
20625   else if (m_op_index == 0 || end_sequence)
20626     {
20627       fe->included_p = 1;
20628       if (m_record_lines_p
20629           && (producer_is_codewarrior (m_cu) || m_is_stmt || end_sequence))
20630         {
20631           if (m_last_subfile != m_cu->get_builder ()->get_current_subfile ()
20632               || end_sequence)
20633             {
20634               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20635                                  m_currently_recording_lines ? m_cu : nullptr);
20636             }
20637
20638           if (!end_sequence)
20639             {
20640               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20641                                        m_line_has_non_zero_discriminator,
20642                                        m_last_subfile))
20643                 {
20644                   buildsym_compunit *builder = m_cu->get_builder ();
20645                   dwarf_record_line_1 (m_gdbarch,
20646                                        builder->get_current_subfile (),
20647                                        m_line, m_address,
20648                                        m_currently_recording_lines ? m_cu : nullptr);
20649                 }
20650               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20651               m_last_line = m_line;
20652             }
20653         }
20654     }
20655 }
20656
20657 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20658                                       line_header *lh, bool record_lines_p)
20659 {
20660   m_cu = cu;
20661   m_gdbarch = arch;
20662   m_record_lines_p = record_lines_p;
20663   m_line_header = lh;
20664
20665   m_currently_recording_lines = true;
20666
20667   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20668      was a line entry for it so that the backend has a chance to adjust it
20669      and also record it in case it needs it.  This is currently used by MIPS
20670      code, cf. `mips_adjust_dwarf2_line'.  */
20671   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20672   m_is_stmt = lh->default_is_stmt;
20673   m_discriminator = 0;
20674 }
20675
20676 void
20677 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20678                                        const gdb_byte *line_ptr,
20679                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20680 {
20681   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20682      the pc range of the CU.  However, we restrict the test to only ADDRESS
20683      values of zero to preserve GDB's previous behaviour which is to handle
20684      the specific case of a function being GC'd by the linker.  */
20685
20686   if (address == 0 && address < unrelocated_lowpc)
20687     {
20688       /* This line table is for a function which has been
20689          GCd by the linker.  Ignore it.  PR gdb/12528 */
20690
20691       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20692       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20693
20694       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20695                  line_offset, objfile_name (objfile));
20696       m_currently_recording_lines = false;
20697       /* Note: m_currently_recording_lines is left as false until we see
20698          DW_LNE_end_sequence.  */
20699     }
20700 }
20701
20702 /* Subroutine of dwarf_decode_lines to simplify it.
20703    Process the line number information in LH.
20704    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20705    program in order to set included_p for every referenced header.  */
20706
20707 static void
20708 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20709                       const int decode_for_pst_p, CORE_ADDR lowpc)
20710 {
20711   const gdb_byte *line_ptr, *extended_end;
20712   const gdb_byte *line_end;
20713   unsigned int bytes_read, extended_len;
20714   unsigned char op_code, extended_op;
20715   CORE_ADDR baseaddr;
20716   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20717   bfd *abfd = objfile->obfd;
20718   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20719   /* True if we're recording line info (as opposed to building partial
20720      symtabs and just interested in finding include files mentioned by
20721      the line number program).  */
20722   bool record_lines_p = !decode_for_pst_p;
20723
20724   baseaddr = objfile->text_section_offset ();
20725
20726   line_ptr = lh->statement_program_start;
20727   line_end = lh->statement_program_end;
20728
20729   /* Read the statement sequences until there's nothing left.  */
20730   while (line_ptr < line_end)
20731     {
20732       /* The DWARF line number program state machine.  Reset the state
20733          machine at the start of each sequence.  */
20734       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
20735       bool end_sequence = false;
20736
20737       if (record_lines_p)
20738         {
20739           /* Start a subfile for the current file of the state
20740              machine.  */
20741           const file_entry *fe = state_machine.current_file ();
20742
20743           if (fe != NULL)
20744             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
20745         }
20746
20747       /* Decode the table.  */
20748       while (line_ptr < line_end && !end_sequence)
20749         {
20750           op_code = read_1_byte (abfd, line_ptr);
20751           line_ptr += 1;
20752
20753           if (op_code >= lh->opcode_base)
20754             {
20755               /* Special opcode.  */
20756               state_machine.handle_special_opcode (op_code);
20757             }
20758           else switch (op_code)
20759             {
20760             case DW_LNS_extended_op:
20761               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20762                                                    &bytes_read);
20763               line_ptr += bytes_read;
20764               extended_end = line_ptr + extended_len;
20765               extended_op = read_1_byte (abfd, line_ptr);
20766               line_ptr += 1;
20767               switch (extended_op)
20768                 {
20769                 case DW_LNE_end_sequence:
20770                   state_machine.handle_end_sequence ();
20771                   end_sequence = true;
20772                   break;
20773                 case DW_LNE_set_address:
20774                   {
20775                     CORE_ADDR address
20776                       = read_address (abfd, line_ptr, cu, &bytes_read);
20777                     line_ptr += bytes_read;
20778
20779                     state_machine.check_line_address (cu, line_ptr,
20780                                                       lowpc - baseaddr, address);
20781                     state_machine.handle_set_address (baseaddr, address);
20782                   }
20783                   break;
20784                 case DW_LNE_define_file:
20785                   {
20786                     const char *cur_file;
20787                     unsigned int mod_time, length;
20788                     dir_index dindex;
20789
20790                     cur_file = read_direct_string (abfd, line_ptr,
20791                                                    &bytes_read);
20792                     line_ptr += bytes_read;
20793                     dindex = (dir_index)
20794                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20795                     line_ptr += bytes_read;
20796                     mod_time =
20797                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20798                     line_ptr += bytes_read;
20799                     length =
20800                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20801                     line_ptr += bytes_read;
20802                     lh->add_file_name (cur_file, dindex, mod_time, length);
20803                   }
20804                   break;
20805                 case DW_LNE_set_discriminator:
20806                   {
20807                     /* The discriminator is not interesting to the
20808                        debugger; just ignore it.  We still need to
20809                        check its value though:
20810                        if there are consecutive entries for the same
20811                        (non-prologue) line we want to coalesce them.
20812                        PR 17276.  */
20813                     unsigned int discr
20814                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20815                     line_ptr += bytes_read;
20816
20817                     state_machine.handle_set_discriminator (discr);
20818                   }
20819                   break;
20820                 default:
20821                   complaint (_("mangled .debug_line section"));
20822                   return;
20823                 }
20824               /* Make sure that we parsed the extended op correctly.  If e.g.
20825                  we expected a different address size than the producer used,
20826                  we may have read the wrong number of bytes.  */
20827               if (line_ptr != extended_end)
20828                 {
20829                   complaint (_("mangled .debug_line section"));
20830                   return;
20831                 }
20832               break;
20833             case DW_LNS_copy:
20834               state_machine.handle_copy ();
20835               break;
20836             case DW_LNS_advance_pc:
20837               {
20838                 CORE_ADDR adjust
20839                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20840                 line_ptr += bytes_read;
20841
20842                 state_machine.handle_advance_pc (adjust);
20843               }
20844               break;
20845             case DW_LNS_advance_line:
20846               {
20847                 int line_delta
20848                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20849                 line_ptr += bytes_read;
20850
20851                 state_machine.handle_advance_line (line_delta);
20852               }
20853               break;
20854             case DW_LNS_set_file:
20855               {
20856                 file_name_index file
20857                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20858                                                             &bytes_read);
20859                 line_ptr += bytes_read;
20860
20861                 state_machine.handle_set_file (file);
20862               }
20863               break;
20864             case DW_LNS_set_column:
20865               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20866               line_ptr += bytes_read;
20867               break;
20868             case DW_LNS_negate_stmt:
20869               state_machine.handle_negate_stmt ();
20870               break;
20871             case DW_LNS_set_basic_block:
20872               break;
20873             /* Add to the address register of the state machine the
20874                address increment value corresponding to special opcode
20875                255.  I.e., this value is scaled by the minimum
20876                instruction length since special opcode 255 would have
20877                scaled the increment.  */
20878             case DW_LNS_const_add_pc:
20879               state_machine.handle_const_add_pc ();
20880               break;
20881             case DW_LNS_fixed_advance_pc:
20882               {
20883                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20884                 line_ptr += 2;
20885
20886                 state_machine.handle_fixed_advance_pc (addr_adj);
20887               }
20888               break;
20889             default:
20890               {
20891                 /* Unknown standard opcode, ignore it.  */
20892                 int i;
20893
20894                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20895                   {
20896                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20897                     line_ptr += bytes_read;
20898                   }
20899               }
20900             }
20901         }
20902
20903       if (!end_sequence)
20904         dwarf2_debug_line_missing_end_sequence_complaint ();
20905
20906       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20907          in which case we still finish recording the last line).  */
20908       state_machine.record_line (true);
20909     }
20910 }
20911
20912 /* Decode the Line Number Program (LNP) for the given line_header
20913    structure and CU.  The actual information extracted and the type
20914    of structures created from the LNP depends on the value of PST.
20915
20916    1. If PST is NULL, then this procedure uses the data from the program
20917       to create all necessary symbol tables, and their linetables.
20918
20919    2. If PST is not NULL, this procedure reads the program to determine
20920       the list of files included by the unit represented by PST, and
20921       builds all the associated partial symbol tables.
20922
20923    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20924    It is used for relative paths in the line table.
20925    NOTE: When processing partial symtabs (pst != NULL),
20926    comp_dir == pst->dirname.
20927
20928    NOTE: It is important that psymtabs have the same file name (via strcmp)
20929    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20930    symtab we don't use it in the name of the psymtabs we create.
20931    E.g. expand_line_sal requires this when finding psymtabs to expand.
20932    A good testcase for this is mb-inline.exp.
20933
20934    LOWPC is the lowest address in CU (or 0 if not known).
20935
20936    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20937    for its PC<->lines mapping information.  Otherwise only the filename
20938    table is read in.  */
20939
20940 static void
20941 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20942                     struct dwarf2_cu *cu, dwarf2_psymtab *pst,
20943                     CORE_ADDR lowpc, int decode_mapping)
20944 {
20945   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20946   const int decode_for_pst_p = (pst != NULL);
20947
20948   if (decode_mapping)
20949     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20950
20951   if (decode_for_pst_p)
20952     {
20953       /* Now that we're done scanning the Line Header Program, we can
20954          create the psymtab of each included file.  */
20955       for (auto &file_entry : lh->file_names ())
20956         if (file_entry.included_p == 1)
20957           {
20958             gdb::unique_xmalloc_ptr<char> name_holder;
20959             const char *include_name =
20960               psymtab_include_file_name (lh, file_entry, pst,
20961                                          comp_dir, &name_holder);
20962             if (include_name != NULL)
20963               dwarf2_create_include_psymtab (include_name, pst, objfile);
20964           }
20965     }
20966   else
20967     {
20968       /* Make sure a symtab is created for every file, even files
20969          which contain only variables (i.e. no code with associated
20970          line numbers).  */
20971       buildsym_compunit *builder = cu->get_builder ();
20972       struct compunit_symtab *cust = builder->get_compunit_symtab ();
20973
20974       for (auto &fe : lh->file_names ())
20975         {
20976           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
20977           if (builder->get_current_subfile ()->symtab == NULL)
20978             {
20979               builder->get_current_subfile ()->symtab
20980                 = allocate_symtab (cust,
20981                                    builder->get_current_subfile ()->name);
20982             }
20983           fe.symtab = builder->get_current_subfile ()->symtab;
20984         }
20985     }
20986 }
20987
20988 /* Start a subfile for DWARF.  FILENAME is the name of the file and
20989    DIRNAME the name of the source directory which contains FILENAME
20990    or NULL if not known.
20991    This routine tries to keep line numbers from identical absolute and
20992    relative file names in a common subfile.
20993
20994    Using the `list' example from the GDB testsuite, which resides in
20995    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
20996    of /srcdir/list0.c yields the following debugging information for list0.c:
20997
20998    DW_AT_name:          /srcdir/list0.c
20999    DW_AT_comp_dir:      /compdir
21000    files.files[0].name: list0.h
21001    files.files[0].dir:  /srcdir
21002    files.files[1].name: list0.c
21003    files.files[1].dir:  /srcdir
21004
21005    The line number information for list0.c has to end up in a single
21006    subfile, so that `break /srcdir/list0.c:1' works as expected.
21007    start_subfile will ensure that this happens provided that we pass the
21008    concatenation of files.files[1].dir and files.files[1].name as the
21009    subfile's name.  */
21010
21011 static void
21012 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21013                       const char *dirname)
21014 {
21015   gdb::unique_xmalloc_ptr<char> copy;
21016
21017   /* In order not to lose the line information directory,
21018      we concatenate it to the filename when it makes sense.
21019      Note that the Dwarf3 standard says (speaking of filenames in line
21020      information): ``The directory index is ignored for file names
21021      that represent full path names''.  Thus ignoring dirname in the
21022      `else' branch below isn't an issue.  */
21023
21024   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21025     {
21026       copy.reset (concat (dirname, SLASH_STRING, filename, (char *) NULL));
21027       filename = copy.get ();
21028     }
21029
21030   cu->get_builder ()->start_subfile (filename);
21031 }
21032
21033 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21034    buildsym_compunit constructor.  */
21035
21036 struct compunit_symtab *
21037 dwarf2_cu::start_symtab (const char *name, const char *comp_dir,
21038                          CORE_ADDR low_pc)
21039 {
21040   gdb_assert (m_builder == nullptr);
21041
21042   m_builder.reset (new struct buildsym_compunit
21043                    (per_cu->dwarf2_per_objfile->objfile,
21044                     name, comp_dir, language, low_pc));
21045
21046   list_in_scope = get_builder ()->get_file_symbols ();
21047
21048   get_builder ()->record_debugformat ("DWARF 2");
21049   get_builder ()->record_producer (producer);
21050
21051   processing_has_namespace_info = false;
21052
21053   return get_builder ()->get_compunit_symtab ();
21054 }
21055
21056 static void
21057 var_decode_location (struct attribute *attr, struct symbol *sym,
21058                      struct dwarf2_cu *cu)
21059 {
21060   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21061   struct comp_unit_head *cu_header = &cu->header;
21062
21063   /* NOTE drow/2003-01-30: There used to be a comment and some special
21064      code here to turn a symbol with DW_AT_external and a
21065      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21066      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21067      with some versions of binutils) where shared libraries could have
21068      relocations against symbols in their debug information - the
21069      minimal symbol would have the right address, but the debug info
21070      would not.  It's no longer necessary, because we will explicitly
21071      apply relocations when we read in the debug information now.  */
21072
21073   /* A DW_AT_location attribute with no contents indicates that a
21074      variable has been optimized away.  */
21075   if (attr->form_is_block () && DW_BLOCK (attr)->size == 0)
21076     {
21077       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21078       return;
21079     }
21080
21081   /* Handle one degenerate form of location expression specially, to
21082      preserve GDB's previous behavior when section offsets are
21083      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
21084      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
21085
21086   if (attr->form_is_block ()
21087       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21088            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21089           || ((DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21090                || DW_BLOCK (attr)->data[0] == DW_OP_addrx)
21091               && (DW_BLOCK (attr)->size
21092                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21093     {
21094       unsigned int dummy;
21095
21096       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21097         SET_SYMBOL_VALUE_ADDRESS (sym,
21098                                   read_address (objfile->obfd,
21099                                                 DW_BLOCK (attr)->data + 1,
21100                                                 cu, &dummy));
21101       else
21102         SET_SYMBOL_VALUE_ADDRESS
21103           (sym, read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1,
21104                                              &dummy));
21105       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21106       fixup_symbol_section (sym, objfile);
21107       SET_SYMBOL_VALUE_ADDRESS
21108         (sym,
21109          SYMBOL_VALUE_ADDRESS (sym)
21110          + objfile->section_offsets[SYMBOL_SECTION (sym)]);
21111       return;
21112     }
21113
21114   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21115      expression evaluator, and use LOC_COMPUTED only when necessary
21116      (i.e. when the value of a register or memory location is
21117      referenced, or a thread-local block, etc.).  Then again, it might
21118      not be worthwhile.  I'm assuming that it isn't unless performance
21119      or memory numbers show me otherwise.  */
21120
21121   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21122
21123   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21124     cu->has_loclist = true;
21125 }
21126
21127 /* Given a pointer to a DWARF information entry, figure out if we need
21128    to make a symbol table entry for it, and if so, create a new entry
21129    and return a pointer to it.
21130    If TYPE is NULL, determine symbol type from the die, otherwise
21131    used the passed type.
21132    If SPACE is not NULL, use it to hold the new symbol.  If it is
21133    NULL, allocate a new symbol on the objfile's obstack.  */
21134
21135 static struct symbol *
21136 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21137             struct symbol *space)
21138 {
21139   struct dwarf2_per_objfile *dwarf2_per_objfile
21140     = cu->per_cu->dwarf2_per_objfile;
21141   struct objfile *objfile = dwarf2_per_objfile->objfile;
21142   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21143   struct symbol *sym = NULL;
21144   const char *name;
21145   struct attribute *attr = NULL;
21146   struct attribute *attr2 = NULL;
21147   CORE_ADDR baseaddr;
21148   struct pending **list_to_add = NULL;
21149
21150   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21151
21152   baseaddr = objfile->text_section_offset ();
21153
21154   name = dwarf2_name (die, cu);
21155   if (name)
21156     {
21157       const char *linkagename;
21158       int suppress_add = 0;
21159
21160       if (space)
21161         sym = space;
21162       else
21163         sym = allocate_symbol (objfile);
21164       OBJSTAT (objfile, n_syms++);
21165
21166       /* Cache this symbol's name and the name's demangled form (if any).  */
21167       sym->set_language (cu->language, &objfile->objfile_obstack);
21168       linkagename = dwarf2_physname (name, die, cu);
21169       sym->compute_and_set_names (linkagename, false, objfile->per_bfd);
21170
21171       /* Fortran does not have mangling standard and the mangling does differ
21172          between gfortran, iFort etc.  */
21173       if (cu->language == language_fortran
21174           && symbol_get_demangled_name (sym) == NULL)
21175         symbol_set_demangled_name (sym,
21176                                    dwarf2_full_name (name, die, cu),
21177                                    NULL);
21178
21179       /* Default assumptions.
21180          Use the passed type or decode it from the die.  */
21181       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21182       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21183       if (type != NULL)
21184         SYMBOL_TYPE (sym) = type;
21185       else
21186         SYMBOL_TYPE (sym) = die_type (die, cu);
21187       attr = dwarf2_attr (die,
21188                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21189                           cu);
21190       if (attr != nullptr)
21191         {
21192           SYMBOL_LINE (sym) = DW_UNSND (attr);
21193         }
21194
21195       attr = dwarf2_attr (die,
21196                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21197                           cu);
21198       if (attr != nullptr)
21199         {
21200           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21201           struct file_entry *fe;
21202
21203           if (cu->line_header != NULL)
21204             fe = cu->line_header->file_name_at (file_index);
21205           else
21206             fe = NULL;
21207
21208           if (fe == NULL)
21209             complaint (_("file index out of range"));
21210           else
21211             symbol_set_symtab (sym, fe->symtab);
21212         }
21213
21214       switch (die->tag)
21215         {
21216         case DW_TAG_label:
21217           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21218           if (attr != nullptr)
21219             {
21220               CORE_ADDR addr;
21221
21222               addr = attr->value_as_address ();
21223               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21224               SET_SYMBOL_VALUE_ADDRESS (sym, addr);
21225             }
21226           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21227           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21228           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21229           add_symbol_to_list (sym, cu->list_in_scope);
21230           break;
21231         case DW_TAG_subprogram:
21232           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21233              finish_block.  */
21234           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21235           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21236           if ((attr2 && (DW_UNSND (attr2) != 0))
21237               || cu->language == language_ada
21238               || cu->language == language_fortran)
21239             {
21240               /* Subprograms marked external are stored as a global symbol.
21241                  Ada and Fortran subprograms, whether marked external or
21242                  not, are always stored as a global symbol, because we want
21243                  to be able to access them globally.  For instance, we want
21244                  to be able to break on a nested subprogram without having
21245                  to specify the context.  */
21246               list_to_add = cu->get_builder ()->get_global_symbols ();
21247             }
21248           else
21249             {
21250               list_to_add = cu->list_in_scope;
21251             }
21252           break;
21253         case DW_TAG_inlined_subroutine:
21254           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21255              finish_block.  */
21256           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21257           SYMBOL_INLINED (sym) = 1;
21258           list_to_add = cu->list_in_scope;
21259           break;
21260         case DW_TAG_template_value_param:
21261           suppress_add = 1;
21262           /* Fall through.  */
21263         case DW_TAG_constant:
21264         case DW_TAG_variable:
21265         case DW_TAG_member:
21266           /* Compilation with minimal debug info may result in
21267              variables with missing type entries.  Change the
21268              misleading `void' type to something sensible.  */
21269           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21270             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21271
21272           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21273           /* In the case of DW_TAG_member, we should only be called for
21274              static const members.  */
21275           if (die->tag == DW_TAG_member)
21276             {
21277               /* dwarf2_add_field uses die_is_declaration,
21278                  so we do the same.  */
21279               gdb_assert (die_is_declaration (die, cu));
21280               gdb_assert (attr);
21281             }
21282           if (attr != nullptr)
21283             {
21284               dwarf2_const_value (attr, sym, cu);
21285               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21286               if (!suppress_add)
21287                 {
21288                   if (attr2 && (DW_UNSND (attr2) != 0))
21289                     list_to_add = cu->get_builder ()->get_global_symbols ();
21290                   else
21291                     list_to_add = cu->list_in_scope;
21292                 }
21293               break;
21294             }
21295           attr = dwarf2_attr (die, DW_AT_location, cu);
21296           if (attr != nullptr)
21297             {
21298               var_decode_location (attr, sym, cu);
21299               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21300
21301               /* Fortran explicitly imports any global symbols to the local
21302                  scope by DW_TAG_common_block.  */
21303               if (cu->language == language_fortran && die->parent
21304                   && die->parent->tag == DW_TAG_common_block)
21305                 attr2 = NULL;
21306
21307               if (SYMBOL_CLASS (sym) == LOC_STATIC
21308                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21309                   && !dwarf2_per_objfile->has_section_at_zero)
21310                 {
21311                   /* When a static variable is eliminated by the linker,
21312                      the corresponding debug information is not stripped
21313                      out, but the variable address is set to null;
21314                      do not add such variables into symbol table.  */
21315                 }
21316               else if (attr2 && (DW_UNSND (attr2) != 0))
21317                 {
21318                   if (SYMBOL_CLASS (sym) == LOC_STATIC
21319                       && (objfile->flags & OBJF_MAINLINE) == 0
21320                       && dwarf2_per_objfile->can_copy)
21321                     {
21322                       /* A global static variable might be subject to
21323                          copy relocation.  We first check for a local
21324                          minsym, though, because maybe the symbol was
21325                          marked hidden, in which case this would not
21326                          apply.  */
21327                       bound_minimal_symbol found
21328                         = (lookup_minimal_symbol_linkage
21329                            (sym->linkage_name (), objfile));
21330                       if (found.minsym != nullptr)
21331                         sym->maybe_copied = 1;
21332                     }
21333
21334                   /* A variable with DW_AT_external is never static,
21335                      but it may be block-scoped.  */
21336                   list_to_add
21337                     = ((cu->list_in_scope
21338                         == cu->get_builder ()->get_file_symbols ())
21339                        ? cu->get_builder ()->get_global_symbols ()
21340                        : cu->list_in_scope);
21341                 }
21342               else
21343                 list_to_add = cu->list_in_scope;
21344             }
21345           else
21346             {
21347               /* We do not know the address of this symbol.
21348                  If it is an external symbol and we have type information
21349                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21350                  The address of the variable will then be determined from
21351                  the minimal symbol table whenever the variable is
21352                  referenced.  */
21353               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21354
21355               /* Fortran explicitly imports any global symbols to the local
21356                  scope by DW_TAG_common_block.  */
21357               if (cu->language == language_fortran && die->parent
21358                   && die->parent->tag == DW_TAG_common_block)
21359                 {
21360                   /* SYMBOL_CLASS doesn't matter here because
21361                      read_common_block is going to reset it.  */
21362                   if (!suppress_add)
21363                     list_to_add = cu->list_in_scope;
21364                 }
21365               else if (attr2 && (DW_UNSND (attr2) != 0)
21366                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21367                 {
21368                   /* A variable with DW_AT_external is never static, but it
21369                      may be block-scoped.  */
21370                   list_to_add
21371                     = ((cu->list_in_scope
21372                         == cu->get_builder ()->get_file_symbols ())
21373                        ? cu->get_builder ()->get_global_symbols ()
21374                        : cu->list_in_scope);
21375
21376                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21377                 }
21378               else if (!die_is_declaration (die, cu))
21379                 {
21380                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21381                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21382                   if (!suppress_add)
21383                     list_to_add = cu->list_in_scope;
21384                 }
21385             }
21386           break;
21387         case DW_TAG_formal_parameter:
21388           {
21389             /* If we are inside a function, mark this as an argument.  If
21390                not, we might be looking at an argument to an inlined function
21391                when we do not have enough information to show inlined frames;
21392                pretend it's a local variable in that case so that the user can
21393                still see it.  */
21394             struct context_stack *curr
21395               = cu->get_builder ()->get_current_context_stack ();
21396             if (curr != nullptr && curr->name != nullptr)
21397               SYMBOL_IS_ARGUMENT (sym) = 1;
21398             attr = dwarf2_attr (die, DW_AT_location, cu);
21399             if (attr != nullptr)
21400               {
21401                 var_decode_location (attr, sym, cu);
21402               }
21403             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21404             if (attr != nullptr)
21405               {
21406                 dwarf2_const_value (attr, sym, cu);
21407               }
21408
21409             list_to_add = cu->list_in_scope;
21410           }
21411           break;
21412         case DW_TAG_unspecified_parameters:
21413           /* From varargs functions; gdb doesn't seem to have any
21414              interest in this information, so just ignore it for now.
21415              (FIXME?) */
21416           break;
21417         case DW_TAG_template_type_param:
21418           suppress_add = 1;
21419           /* Fall through.  */
21420         case DW_TAG_class_type:
21421         case DW_TAG_interface_type:
21422         case DW_TAG_structure_type:
21423         case DW_TAG_union_type:
21424         case DW_TAG_set_type:
21425         case DW_TAG_enumeration_type:
21426           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21427           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21428
21429           {
21430             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21431                really ever be static objects: otherwise, if you try
21432                to, say, break of a class's method and you're in a file
21433                which doesn't mention that class, it won't work unless
21434                the check for all static symbols in lookup_symbol_aux
21435                saves you.  See the OtherFileClass tests in
21436                gdb.c++/namespace.exp.  */
21437
21438             if (!suppress_add)
21439               {
21440                 buildsym_compunit *builder = cu->get_builder ();
21441                 list_to_add
21442                   = (cu->list_in_scope == builder->get_file_symbols ()
21443                      && cu->language == language_cplus
21444                      ? builder->get_global_symbols ()
21445                      : cu->list_in_scope);
21446
21447                 /* The semantics of C++ state that "struct foo {
21448                    ... }" also defines a typedef for "foo".  */
21449                 if (cu->language == language_cplus
21450                     || cu->language == language_ada
21451                     || cu->language == language_d
21452                     || cu->language == language_rust)
21453                   {
21454                     /* The symbol's name is already allocated along
21455                        with this objfile, so we don't need to
21456                        duplicate it for the type.  */
21457                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21458                       TYPE_NAME (SYMBOL_TYPE (sym)) = sym->search_name ();
21459                   }
21460               }
21461           }
21462           break;
21463         case DW_TAG_typedef:
21464           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21465           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21466           list_to_add = cu->list_in_scope;
21467           break;
21468         case DW_TAG_base_type:
21469         case DW_TAG_subrange_type:
21470           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21471           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21472           list_to_add = cu->list_in_scope;
21473           break;
21474         case DW_TAG_enumerator:
21475           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21476           if (attr != nullptr)
21477             {
21478               dwarf2_const_value (attr, sym, cu);
21479             }
21480           {
21481             /* NOTE: carlton/2003-11-10: See comment above in the
21482                DW_TAG_class_type, etc. block.  */
21483
21484             list_to_add
21485               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
21486                  && cu->language == language_cplus
21487                  ? cu->get_builder ()->get_global_symbols ()
21488                  : cu->list_in_scope);
21489           }
21490           break;
21491         case DW_TAG_imported_declaration:
21492         case DW_TAG_namespace:
21493           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21494           list_to_add = cu->get_builder ()->get_global_symbols ();
21495           break;
21496         case DW_TAG_module:
21497           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21498           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21499           list_to_add = cu->get_builder ()->get_global_symbols ();
21500           break;
21501         case DW_TAG_common_block:
21502           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21503           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21504           add_symbol_to_list (sym, cu->list_in_scope);
21505           break;
21506         default:
21507           /* Not a tag we recognize.  Hopefully we aren't processing
21508              trash data, but since we must specifically ignore things
21509              we don't recognize, there is nothing else we should do at
21510              this point.  */
21511           complaint (_("unsupported tag: '%s'"),
21512                      dwarf_tag_name (die->tag));
21513           break;
21514         }
21515
21516       if (suppress_add)
21517         {
21518           sym->hash_next = objfile->template_symbols;
21519           objfile->template_symbols = sym;
21520           list_to_add = NULL;
21521         }
21522
21523       if (list_to_add != NULL)
21524         add_symbol_to_list (sym, list_to_add);
21525
21526       /* For the benefit of old versions of GCC, check for anonymous
21527          namespaces based on the demangled name.  */
21528       if (!cu->processing_has_namespace_info
21529           && cu->language == language_cplus)
21530         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
21531     }
21532   return (sym);
21533 }
21534
21535 /* Given an attr with a DW_FORM_dataN value in host byte order,
21536    zero-extend it as appropriate for the symbol's type.  The DWARF
21537    standard (v4) is not entirely clear about the meaning of using
21538    DW_FORM_dataN for a constant with a signed type, where the type is
21539    wider than the data.  The conclusion of a discussion on the DWARF
21540    list was that this is unspecified.  We choose to always zero-extend
21541    because that is the interpretation long in use by GCC.  */
21542
21543 static gdb_byte *
21544 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21545                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21546 {
21547   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21548   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21549                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21550   LONGEST l = DW_UNSND (attr);
21551
21552   if (bits < sizeof (*value) * 8)
21553     {
21554       l &= ((LONGEST) 1 << bits) - 1;
21555       *value = l;
21556     }
21557   else if (bits == sizeof (*value) * 8)
21558     *value = l;
21559   else
21560     {
21561       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21562       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21563       return bytes;
21564     }
21565
21566   return NULL;
21567 }
21568
21569 /* Read a constant value from an attribute.  Either set *VALUE, or if
21570    the value does not fit in *VALUE, set *BYTES - either already
21571    allocated on the objfile obstack, or newly allocated on OBSTACK,
21572    or, set *BATON, if we translated the constant to a location
21573    expression.  */
21574
21575 static void
21576 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21577                          const char *name, struct obstack *obstack,
21578                          struct dwarf2_cu *cu,
21579                          LONGEST *value, const gdb_byte **bytes,
21580                          struct dwarf2_locexpr_baton **baton)
21581 {
21582   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21583   struct comp_unit_head *cu_header = &cu->header;
21584   struct dwarf_block *blk;
21585   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21586                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21587
21588   *value = 0;
21589   *bytes = NULL;
21590   *baton = NULL;
21591
21592   switch (attr->form)
21593     {
21594     case DW_FORM_addr:
21595     case DW_FORM_addrx:
21596     case DW_FORM_GNU_addr_index:
21597       {
21598         gdb_byte *data;
21599
21600         if (TYPE_LENGTH (type) != cu_header->addr_size)
21601           dwarf2_const_value_length_mismatch_complaint (name,
21602                                                         cu_header->addr_size,
21603                                                         TYPE_LENGTH (type));
21604         /* Symbols of this form are reasonably rare, so we just
21605            piggyback on the existing location code rather than writing
21606            a new implementation of symbol_computed_ops.  */
21607         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21608         (*baton)->per_cu = cu->per_cu;
21609         gdb_assert ((*baton)->per_cu);
21610
21611         (*baton)->size = 2 + cu_header->addr_size;
21612         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21613         (*baton)->data = data;
21614
21615         data[0] = DW_OP_addr;
21616         store_unsigned_integer (&data[1], cu_header->addr_size,
21617                                 byte_order, DW_ADDR (attr));
21618         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21619       }
21620       break;
21621     case DW_FORM_string:
21622     case DW_FORM_strp:
21623     case DW_FORM_strx:
21624     case DW_FORM_GNU_str_index:
21625     case DW_FORM_GNU_strp_alt:
21626       /* DW_STRING is already allocated on the objfile obstack, point
21627          directly to it.  */
21628       *bytes = (const gdb_byte *) DW_STRING (attr);
21629       break;
21630     case DW_FORM_block1:
21631     case DW_FORM_block2:
21632     case DW_FORM_block4:
21633     case DW_FORM_block:
21634     case DW_FORM_exprloc:
21635     case DW_FORM_data16:
21636       blk = DW_BLOCK (attr);
21637       if (TYPE_LENGTH (type) != blk->size)
21638         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21639                                                       TYPE_LENGTH (type));
21640       *bytes = blk->data;
21641       break;
21642
21643       /* The DW_AT_const_value attributes are supposed to carry the
21644          symbol's value "represented as it would be on the target
21645          architecture."  By the time we get here, it's already been
21646          converted to host endianness, so we just need to sign- or
21647          zero-extend it as appropriate.  */
21648     case DW_FORM_data1:
21649       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21650       break;
21651     case DW_FORM_data2:
21652       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21653       break;
21654     case DW_FORM_data4:
21655       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21656       break;
21657     case DW_FORM_data8:
21658       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21659       break;
21660
21661     case DW_FORM_sdata:
21662     case DW_FORM_implicit_const:
21663       *value = DW_SND (attr);
21664       break;
21665
21666     case DW_FORM_udata:
21667       *value = DW_UNSND (attr);
21668       break;
21669
21670     default:
21671       complaint (_("unsupported const value attribute form: '%s'"),
21672                  dwarf_form_name (attr->form));
21673       *value = 0;
21674       break;
21675     }
21676 }
21677
21678
21679 /* Copy constant value from an attribute to a symbol.  */
21680
21681 static void
21682 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21683                     struct dwarf2_cu *cu)
21684 {
21685   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21686   LONGEST value;
21687   const gdb_byte *bytes;
21688   struct dwarf2_locexpr_baton *baton;
21689
21690   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21691                            sym->print_name (),
21692                            &objfile->objfile_obstack, cu,
21693                            &value, &bytes, &baton);
21694
21695   if (baton != NULL)
21696     {
21697       SYMBOL_LOCATION_BATON (sym) = baton;
21698       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21699     }
21700   else if (bytes != NULL)
21701      {
21702       SYMBOL_VALUE_BYTES (sym) = bytes;
21703       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21704     }
21705   else
21706     {
21707       SYMBOL_VALUE (sym) = value;
21708       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21709     }
21710 }
21711
21712 /* Return the type of the die in question using its DW_AT_type attribute.  */
21713
21714 static struct type *
21715 die_type (struct die_info *die, struct dwarf2_cu *cu)
21716 {
21717   struct attribute *type_attr;
21718
21719   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21720   if (!type_attr)
21721     {
21722       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21723       /* A missing DW_AT_type represents a void type.  */
21724       return objfile_type (objfile)->builtin_void;
21725     }
21726
21727   return lookup_die_type (die, type_attr, cu);
21728 }
21729
21730 /* True iff CU's producer generates GNAT Ada auxiliary information
21731    that allows to find parallel types through that information instead
21732    of having to do expensive parallel lookups by type name.  */
21733
21734 static int
21735 need_gnat_info (struct dwarf2_cu *cu)
21736 {
21737   /* Assume that the Ada compiler was GNAT, which always produces
21738      the auxiliary information.  */
21739   return (cu->language == language_ada);
21740 }
21741
21742 /* Return the auxiliary type of the die in question using its
21743    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21744    attribute is not present.  */
21745
21746 static struct type *
21747 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21748 {
21749   struct attribute *type_attr;
21750
21751   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21752   if (!type_attr)
21753     return NULL;
21754
21755   return lookup_die_type (die, type_attr, cu);
21756 }
21757
21758 /* If DIE has a descriptive_type attribute, then set the TYPE's
21759    descriptive type accordingly.  */
21760
21761 static void
21762 set_descriptive_type (struct type *type, struct die_info *die,
21763                       struct dwarf2_cu *cu)
21764 {
21765   struct type *descriptive_type = die_descriptive_type (die, cu);
21766
21767   if (descriptive_type)
21768     {
21769       ALLOCATE_GNAT_AUX_TYPE (type);
21770       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21771     }
21772 }
21773
21774 /* Return the containing type of the die in question using its
21775    DW_AT_containing_type attribute.  */
21776
21777 static struct type *
21778 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21779 {
21780   struct attribute *type_attr;
21781   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21782
21783   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21784   if (!type_attr)
21785     error (_("Dwarf Error: Problem turning containing type into gdb type "
21786              "[in module %s]"), objfile_name (objfile));
21787
21788   return lookup_die_type (die, type_attr, cu);
21789 }
21790
21791 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21792
21793 static struct type *
21794 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21795 {
21796   struct dwarf2_per_objfile *dwarf2_per_objfile
21797     = cu->per_cu->dwarf2_per_objfile;
21798   struct objfile *objfile = dwarf2_per_objfile->objfile;
21799   char *saved;
21800
21801   std::string message
21802     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
21803                      objfile_name (objfile),
21804                      sect_offset_str (cu->header.sect_off),
21805                      sect_offset_str (die->sect_off));
21806   saved = obstack_strdup (&objfile->objfile_obstack, message);
21807
21808   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21809 }
21810
21811 /* Look up the type of DIE in CU using its type attribute ATTR.
21812    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21813    DW_AT_containing_type.
21814    If there is no type substitute an error marker.  */
21815
21816 static struct type *
21817 lookup_die_type (struct die_info *die, const struct attribute *attr,
21818                  struct dwarf2_cu *cu)
21819 {
21820   struct dwarf2_per_objfile *dwarf2_per_objfile
21821     = cu->per_cu->dwarf2_per_objfile;
21822   struct objfile *objfile = dwarf2_per_objfile->objfile;
21823   struct type *this_type;
21824
21825   gdb_assert (attr->name == DW_AT_type
21826               || attr->name == DW_AT_GNAT_descriptive_type
21827               || attr->name == DW_AT_containing_type);
21828
21829   /* First see if we have it cached.  */
21830
21831   if (attr->form == DW_FORM_GNU_ref_alt)
21832     {
21833       struct dwarf2_per_cu_data *per_cu;
21834       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21835
21836       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21837                                                  dwarf2_per_objfile);
21838       this_type = get_die_type_at_offset (sect_off, per_cu);
21839     }
21840   else if (attr->form_is_ref ())
21841     {
21842       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21843
21844       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21845     }
21846   else if (attr->form == DW_FORM_ref_sig8)
21847     {
21848       ULONGEST signature = DW_SIGNATURE (attr);
21849
21850       return get_signatured_type (die, signature, cu);
21851     }
21852   else
21853     {
21854       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21855                    " at %s [in module %s]"),
21856                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21857                  objfile_name (objfile));
21858       return build_error_marker_type (cu, die);
21859     }
21860
21861   /* If not cached we need to read it in.  */
21862
21863   if (this_type == NULL)
21864     {
21865       struct die_info *type_die = NULL;
21866       struct dwarf2_cu *type_cu = cu;
21867
21868       if (attr->form_is_ref ())
21869         type_die = follow_die_ref (die, attr, &type_cu);
21870       if (type_die == NULL)
21871         return build_error_marker_type (cu, die);
21872       /* If we find the type now, it's probably because the type came
21873          from an inter-CU reference and the type's CU got expanded before
21874          ours.  */
21875       this_type = read_type_die (type_die, type_cu);
21876     }
21877
21878   /* If we still don't have a type use an error marker.  */
21879
21880   if (this_type == NULL)
21881     return build_error_marker_type (cu, die);
21882
21883   return this_type;
21884 }
21885
21886 /* Return the type in DIE, CU.
21887    Returns NULL for invalid types.
21888
21889    This first does a lookup in die_type_hash,
21890    and only reads the die in if necessary.
21891
21892    NOTE: This can be called when reading in partial or full symbols.  */
21893
21894 static struct type *
21895 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21896 {
21897   struct type *this_type;
21898
21899   this_type = get_die_type (die, cu);
21900   if (this_type)
21901     return this_type;
21902
21903   return read_type_die_1 (die, cu);
21904 }
21905
21906 /* Read the type in DIE, CU.
21907    Returns NULL for invalid types.  */
21908
21909 static struct type *
21910 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21911 {
21912   struct type *this_type = NULL;
21913
21914   switch (die->tag)
21915     {
21916     case DW_TAG_class_type:
21917     case DW_TAG_interface_type:
21918     case DW_TAG_structure_type:
21919     case DW_TAG_union_type:
21920       this_type = read_structure_type (die, cu);
21921       break;
21922     case DW_TAG_enumeration_type:
21923       this_type = read_enumeration_type (die, cu);
21924       break;
21925     case DW_TAG_subprogram:
21926     case DW_TAG_subroutine_type:
21927     case DW_TAG_inlined_subroutine:
21928       this_type = read_subroutine_type (die, cu);
21929       break;
21930     case DW_TAG_array_type:
21931       this_type = read_array_type (die, cu);
21932       break;
21933     case DW_TAG_set_type:
21934       this_type = read_set_type (die, cu);
21935       break;
21936     case DW_TAG_pointer_type:
21937       this_type = read_tag_pointer_type (die, cu);
21938       break;
21939     case DW_TAG_ptr_to_member_type:
21940       this_type = read_tag_ptr_to_member_type (die, cu);
21941       break;
21942     case DW_TAG_reference_type:
21943       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21944       break;
21945     case DW_TAG_rvalue_reference_type:
21946       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21947       break;
21948     case DW_TAG_const_type:
21949       this_type = read_tag_const_type (die, cu);
21950       break;
21951     case DW_TAG_volatile_type:
21952       this_type = read_tag_volatile_type (die, cu);
21953       break;
21954     case DW_TAG_restrict_type:
21955       this_type = read_tag_restrict_type (die, cu);
21956       break;
21957     case DW_TAG_string_type:
21958       this_type = read_tag_string_type (die, cu);
21959       break;
21960     case DW_TAG_typedef:
21961       this_type = read_typedef (die, cu);
21962       break;
21963     case DW_TAG_subrange_type:
21964       this_type = read_subrange_type (die, cu);
21965       break;
21966     case DW_TAG_base_type:
21967       this_type = read_base_type (die, cu);
21968       break;
21969     case DW_TAG_unspecified_type:
21970       this_type = read_unspecified_type (die, cu);
21971       break;
21972     case DW_TAG_namespace:
21973       this_type = read_namespace_type (die, cu);
21974       break;
21975     case DW_TAG_module:
21976       this_type = read_module_type (die, cu);
21977       break;
21978     case DW_TAG_atomic_type:
21979       this_type = read_tag_atomic_type (die, cu);
21980       break;
21981     default:
21982       complaint (_("unexpected tag in read_type_die: '%s'"),
21983                  dwarf_tag_name (die->tag));
21984       break;
21985     }
21986
21987   return this_type;
21988 }
21989
21990 /* See if we can figure out if the class lives in a namespace.  We do
21991    this by looking for a member function; its demangled name will
21992    contain namespace info, if there is any.
21993    Return the computed name or NULL.
21994    Space for the result is allocated on the objfile's obstack.
21995    This is the full-die version of guess_partial_die_structure_name.
21996    In this case we know DIE has no useful parent.  */
21997
21998 static const char *
21999 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22000 {
22001   struct die_info *spec_die;
22002   struct dwarf2_cu *spec_cu;
22003   struct die_info *child;
22004   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22005
22006   spec_cu = cu;
22007   spec_die = die_specification (die, &spec_cu);
22008   if (spec_die != NULL)
22009     {
22010       die = spec_die;
22011       cu = spec_cu;
22012     }
22013
22014   for (child = die->child;
22015        child != NULL;
22016        child = child->sibling)
22017     {
22018       if (child->tag == DW_TAG_subprogram)
22019         {
22020           const char *linkage_name = dw2_linkage_name (child, cu);
22021
22022           if (linkage_name != NULL)
22023             {
22024               gdb::unique_xmalloc_ptr<char> actual_name
22025                 (language_class_name_from_physname (cu->language_defn,
22026                                                     linkage_name));
22027               const char *name = NULL;
22028
22029               if (actual_name != NULL)
22030                 {
22031                   const char *die_name = dwarf2_name (die, cu);
22032
22033                   if (die_name != NULL
22034                       && strcmp (die_name, actual_name.get ()) != 0)
22035                     {
22036                       /* Strip off the class name from the full name.
22037                          We want the prefix.  */
22038                       int die_name_len = strlen (die_name);
22039                       int actual_name_len = strlen (actual_name.get ());
22040                       const char *ptr = actual_name.get ();
22041
22042                       /* Test for '::' as a sanity check.  */
22043                       if (actual_name_len > die_name_len + 2
22044                           && ptr[actual_name_len - die_name_len - 1] == ':')
22045                         name = obstack_strndup (
22046                           &objfile->per_bfd->storage_obstack,
22047                           ptr, actual_name_len - die_name_len - 2);
22048                     }
22049                 }
22050               return name;
22051             }
22052         }
22053     }
22054
22055   return NULL;
22056 }
22057
22058 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22059    prefix part in such case.  See
22060    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22061
22062 static const char *
22063 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22064 {
22065   struct attribute *attr;
22066   const char *base;
22067
22068   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22069       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22070     return NULL;
22071
22072   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22073     return NULL;
22074
22075   attr = dw2_linkage_name_attr (die, cu);
22076   if (attr == NULL || DW_STRING (attr) == NULL)
22077     return NULL;
22078
22079   /* dwarf2_name had to be already called.  */
22080   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22081
22082   /* Strip the base name, keep any leading namespaces/classes.  */
22083   base = strrchr (DW_STRING (attr), ':');
22084   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22085     return "";
22086
22087   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22088   return obstack_strndup (&objfile->per_bfd->storage_obstack,
22089                           DW_STRING (attr),
22090                           &base[-1] - DW_STRING (attr));
22091 }
22092
22093 /* Return the name of the namespace/class that DIE is defined within,
22094    or "" if we can't tell.  The caller should not xfree the result.
22095
22096    For example, if we're within the method foo() in the following
22097    code:
22098
22099    namespace N {
22100      class C {
22101        void foo () {
22102        }
22103      };
22104    }
22105
22106    then determine_prefix on foo's die will return "N::C".  */
22107
22108 static const char *
22109 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22110 {
22111   struct dwarf2_per_objfile *dwarf2_per_objfile
22112     = cu->per_cu->dwarf2_per_objfile;
22113   struct die_info *parent, *spec_die;
22114   struct dwarf2_cu *spec_cu;
22115   struct type *parent_type;
22116   const char *retval;
22117
22118   if (cu->language != language_cplus
22119       && cu->language != language_fortran && cu->language != language_d
22120       && cu->language != language_rust)
22121     return "";
22122
22123   retval = anonymous_struct_prefix (die, cu);
22124   if (retval)
22125     return retval;
22126
22127   /* We have to be careful in the presence of DW_AT_specification.
22128      For example, with GCC 3.4, given the code
22129
22130      namespace N {
22131        void foo() {
22132          // Definition of N::foo.
22133        }
22134      }
22135
22136      then we'll have a tree of DIEs like this:
22137
22138      1: DW_TAG_compile_unit
22139        2: DW_TAG_namespace        // N
22140          3: DW_TAG_subprogram     // declaration of N::foo
22141        4: DW_TAG_subprogram       // definition of N::foo
22142             DW_AT_specification   // refers to die #3
22143
22144      Thus, when processing die #4, we have to pretend that we're in
22145      the context of its DW_AT_specification, namely the contex of die
22146      #3.  */
22147   spec_cu = cu;
22148   spec_die = die_specification (die, &spec_cu);
22149   if (spec_die == NULL)
22150     parent = die->parent;
22151   else
22152     {
22153       parent = spec_die->parent;
22154       cu = spec_cu;
22155     }
22156
22157   if (parent == NULL)
22158     return "";
22159   else if (parent->building_fullname)
22160     {
22161       const char *name;
22162       const char *parent_name;
22163
22164       /* It has been seen on RealView 2.2 built binaries,
22165          DW_TAG_template_type_param types actually _defined_ as
22166          children of the parent class:
22167
22168          enum E {};
22169          template class <class Enum> Class{};
22170          Class<enum E> class_e;
22171
22172          1: DW_TAG_class_type (Class)
22173            2: DW_TAG_enumeration_type (E)
22174              3: DW_TAG_enumerator (enum1:0)
22175              3: DW_TAG_enumerator (enum2:1)
22176              ...
22177            2: DW_TAG_template_type_param
22178               DW_AT_type  DW_FORM_ref_udata (E)
22179
22180          Besides being broken debug info, it can put GDB into an
22181          infinite loop.  Consider:
22182
22183          When we're building the full name for Class<E>, we'll start
22184          at Class, and go look over its template type parameters,
22185          finding E.  We'll then try to build the full name of E, and
22186          reach here.  We're now trying to build the full name of E,
22187          and look over the parent DIE for containing scope.  In the
22188          broken case, if we followed the parent DIE of E, we'd again
22189          find Class, and once again go look at its template type
22190          arguments, etc., etc.  Simply don't consider such parent die
22191          as source-level parent of this die (it can't be, the language
22192          doesn't allow it), and break the loop here.  */
22193       name = dwarf2_name (die, cu);
22194       parent_name = dwarf2_name (parent, cu);
22195       complaint (_("template param type '%s' defined within parent '%s'"),
22196                  name ? name : "<unknown>",
22197                  parent_name ? parent_name : "<unknown>");
22198       return "";
22199     }
22200   else
22201     switch (parent->tag)
22202       {
22203       case DW_TAG_namespace:
22204         parent_type = read_type_die (parent, cu);
22205         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22206            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22207            Work around this problem here.  */
22208         if (cu->language == language_cplus
22209             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22210           return "";
22211         /* We give a name to even anonymous namespaces.  */
22212         return TYPE_NAME (parent_type);
22213       case DW_TAG_class_type:
22214       case DW_TAG_interface_type:
22215       case DW_TAG_structure_type:
22216       case DW_TAG_union_type:
22217       case DW_TAG_module:
22218         parent_type = read_type_die (parent, cu);
22219         if (TYPE_NAME (parent_type) != NULL)
22220           return TYPE_NAME (parent_type);
22221         else
22222           /* An anonymous structure is only allowed non-static data
22223              members; no typedefs, no member functions, et cetera.
22224              So it does not need a prefix.  */
22225           return "";
22226       case DW_TAG_compile_unit:
22227       case DW_TAG_partial_unit:
22228         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22229         if (cu->language == language_cplus
22230             && !dwarf2_per_objfile->types.empty ()
22231             && die->child != NULL
22232             && (die->tag == DW_TAG_class_type
22233                 || die->tag == DW_TAG_structure_type
22234                 || die->tag == DW_TAG_union_type))
22235           {
22236             const char *name = guess_full_die_structure_name (die, cu);
22237             if (name != NULL)
22238               return name;
22239           }
22240         return "";
22241       case DW_TAG_subprogram:
22242         /* Nested subroutines in Fortran get a prefix with the name
22243            of the parent's subroutine.  */
22244         if (cu->language == language_fortran)
22245           {
22246             if ((die->tag ==  DW_TAG_subprogram)
22247                 && (dwarf2_name (parent, cu) != NULL))
22248               return dwarf2_name (parent, cu);
22249           }
22250         return determine_prefix (parent, cu);
22251       case DW_TAG_enumeration_type:
22252         parent_type = read_type_die (parent, cu);
22253         if (TYPE_DECLARED_CLASS (parent_type))
22254           {
22255             if (TYPE_NAME (parent_type) != NULL)
22256               return TYPE_NAME (parent_type);
22257             return "";
22258           }
22259         /* Fall through.  */
22260       default:
22261         return determine_prefix (parent, cu);
22262       }
22263 }
22264
22265 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22266    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22267    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22268    an obconcat, otherwise allocate storage for the result.  The CU argument is
22269    used to determine the language and hence, the appropriate separator.  */
22270
22271 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22272
22273 static char *
22274 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22275                  int physname, struct dwarf2_cu *cu)
22276 {
22277   const char *lead = "";
22278   const char *sep;
22279
22280   if (suffix == NULL || suffix[0] == '\0'
22281       || prefix == NULL || prefix[0] == '\0')
22282     sep = "";
22283   else if (cu->language == language_d)
22284     {
22285       /* For D, the 'main' function could be defined in any module, but it
22286          should never be prefixed.  */
22287       if (strcmp (suffix, "D main") == 0)
22288         {
22289           prefix = "";
22290           sep = "";
22291         }
22292       else
22293         sep = ".";
22294     }
22295   else if (cu->language == language_fortran && physname)
22296     {
22297       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22298          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22299
22300       lead = "__";
22301       sep = "_MOD_";
22302     }
22303   else
22304     sep = "::";
22305
22306   if (prefix == NULL)
22307     prefix = "";
22308   if (suffix == NULL)
22309     suffix = "";
22310
22311   if (obs == NULL)
22312     {
22313       char *retval
22314         = ((char *)
22315            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22316
22317       strcpy (retval, lead);
22318       strcat (retval, prefix);
22319       strcat (retval, sep);
22320       strcat (retval, suffix);
22321       return retval;
22322     }
22323   else
22324     {
22325       /* We have an obstack.  */
22326       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22327     }
22328 }
22329
22330 /* Return sibling of die, NULL if no sibling.  */
22331
22332 static struct die_info *
22333 sibling_die (struct die_info *die)
22334 {
22335   return die->sibling;
22336 }
22337
22338 /* Get name of a die, return NULL if not found.  */
22339
22340 static const char *
22341 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22342                           struct obstack *obstack)
22343 {
22344   if (name && cu->language == language_cplus)
22345     {
22346       std::string canon_name = cp_canonicalize_string (name);
22347
22348       if (!canon_name.empty ())
22349         {
22350           if (canon_name != name)
22351             name = obstack_strdup (obstack, canon_name);
22352         }
22353     }
22354
22355   return name;
22356 }
22357
22358 /* Get name of a die, return NULL if not found.
22359    Anonymous namespaces are converted to their magic string.  */
22360
22361 static const char *
22362 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22363 {
22364   struct attribute *attr;
22365   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22366
22367   attr = dwarf2_attr (die, DW_AT_name, cu);
22368   if ((!attr || !DW_STRING (attr))
22369       && die->tag != DW_TAG_namespace
22370       && die->tag != DW_TAG_class_type
22371       && die->tag != DW_TAG_interface_type
22372       && die->tag != DW_TAG_structure_type
22373       && die->tag != DW_TAG_union_type)
22374     return NULL;
22375
22376   switch (die->tag)
22377     {
22378     case DW_TAG_compile_unit:
22379     case DW_TAG_partial_unit:
22380       /* Compilation units have a DW_AT_name that is a filename, not
22381          a source language identifier.  */
22382     case DW_TAG_enumeration_type:
22383     case DW_TAG_enumerator:
22384       /* These tags always have simple identifiers already; no need
22385          to canonicalize them.  */
22386       return DW_STRING (attr);
22387
22388     case DW_TAG_namespace:
22389       if (attr != NULL && DW_STRING (attr) != NULL)
22390         return DW_STRING (attr);
22391       return CP_ANONYMOUS_NAMESPACE_STR;
22392
22393     case DW_TAG_class_type:
22394     case DW_TAG_interface_type:
22395     case DW_TAG_structure_type:
22396     case DW_TAG_union_type:
22397       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22398          structures or unions.  These were of the form "._%d" in GCC 4.1,
22399          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22400          and GCC 4.4.  We work around this problem by ignoring these.  */
22401       if (attr && DW_STRING (attr)
22402           && (startswith (DW_STRING (attr), "._")
22403               || startswith (DW_STRING (attr), "<anonymous")))
22404         return NULL;
22405
22406       /* GCC might emit a nameless typedef that has a linkage name.  See
22407          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22408       if (!attr || DW_STRING (attr) == NULL)
22409         {
22410           attr = dw2_linkage_name_attr (die, cu);
22411           if (attr == NULL || DW_STRING (attr) == NULL)
22412             return NULL;
22413
22414           /* Avoid demangling DW_STRING (attr) the second time on a second
22415              call for the same DIE.  */
22416           if (!DW_STRING_IS_CANONICAL (attr))
22417             {
22418               gdb::unique_xmalloc_ptr<char> demangled
22419                 (gdb_demangle (DW_STRING (attr), DMGL_TYPES));
22420
22421               const char *base;
22422
22423               /* FIXME: we already did this for the partial symbol... */
22424               DW_STRING (attr)
22425                 = obstack_strdup (&objfile->per_bfd->storage_obstack,
22426                                   demangled.get ());
22427               DW_STRING_IS_CANONICAL (attr) = 1;
22428
22429               /* Strip any leading namespaces/classes, keep only the base name.
22430                  DW_AT_name for named DIEs does not contain the prefixes.  */
22431               base = strrchr (DW_STRING (attr), ':');
22432               if (base && base > DW_STRING (attr) && base[-1] == ':')
22433                 return &base[1];
22434               else
22435                 return DW_STRING (attr);
22436             }
22437         }
22438       break;
22439
22440     default:
22441       break;
22442     }
22443
22444   if (!DW_STRING_IS_CANONICAL (attr))
22445     {
22446       DW_STRING (attr)
22447         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22448                                     &objfile->per_bfd->storage_obstack);
22449       DW_STRING_IS_CANONICAL (attr) = 1;
22450     }
22451   return DW_STRING (attr);
22452 }
22453
22454 /* Return the die that this die in an extension of, or NULL if there
22455    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22456    containing the return value on output.  */
22457
22458 static struct die_info *
22459 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22460 {
22461   struct attribute *attr;
22462
22463   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22464   if (attr == NULL)
22465     return NULL;
22466
22467   return follow_die_ref (die, attr, ext_cu);
22468 }
22469
22470 /* A convenience function that returns an "unknown" DWARF name,
22471    including the value of V.  STR is the name of the entity being
22472    printed, e.g., "TAG".  */
22473
22474 static const char *
22475 dwarf_unknown (const char *str, unsigned v)
22476 {
22477   char *cell = get_print_cell ();
22478   xsnprintf (cell, PRINT_CELL_SIZE, "DW_%s_<unknown: %u>", str, v);
22479   return cell;
22480 }
22481
22482 /* Convert a DIE tag into its string name.  */
22483
22484 static const char *
22485 dwarf_tag_name (unsigned tag)
22486 {
22487   const char *name = get_DW_TAG_name (tag);
22488
22489   if (name == NULL)
22490     return dwarf_unknown ("TAG", tag);
22491
22492   return name;
22493 }
22494
22495 /* Convert a DWARF attribute code into its string name.  */
22496
22497 static const char *
22498 dwarf_attr_name (unsigned attr)
22499 {
22500   const char *name;
22501
22502 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22503   if (attr == DW_AT_MIPS_fde)
22504     return "DW_AT_MIPS_fde";
22505 #else
22506   if (attr == DW_AT_HP_block_index)
22507     return "DW_AT_HP_block_index";
22508 #endif
22509
22510   name = get_DW_AT_name (attr);
22511
22512   if (name == NULL)
22513     return dwarf_unknown ("AT", attr);
22514
22515   return name;
22516 }
22517
22518 /* Convert a unit type to corresponding DW_UT name.  */
22519
22520 static const char *
22521 dwarf_unit_type_name (int unit_type) {
22522   switch (unit_type)
22523     {
22524       case 0x01:
22525         return "DW_UT_compile (0x01)";
22526       case 0x02:
22527         return "DW_UT_type (0x02)";
22528       case 0x03:
22529         return "DW_UT_partial (0x03)";
22530       case 0x04:
22531         return "DW_UT_skeleton (0x04)";
22532       case 0x05:
22533         return "DW_UT_split_compile (0x05)";
22534       case 0x06:
22535         return "DW_UT_split_type (0x06)";
22536       case 0x80:
22537         return "DW_UT_lo_user (0x80)";
22538       case 0xff:
22539         return "DW_UT_hi_user (0xff)";
22540       default:
22541         return nullptr;
22542     }
22543 }
22544
22545 /* Convert a DWARF value form code into its string name.  */
22546
22547 static const char *
22548 dwarf_form_name (unsigned form)
22549 {
22550   const char *name = get_DW_FORM_name (form);
22551
22552   if (name == NULL)
22553     return dwarf_unknown ("FORM", form);
22554
22555   return name;
22556 }
22557
22558 static const char *
22559 dwarf_bool_name (unsigned mybool)
22560 {
22561   if (mybool)
22562     return "TRUE";
22563   else
22564     return "FALSE";
22565 }
22566
22567 /* Convert a DWARF type code into its string name.  */
22568
22569 static const char *
22570 dwarf_type_encoding_name (unsigned enc)
22571 {
22572   const char *name = get_DW_ATE_name (enc);
22573
22574   if (name == NULL)
22575     return dwarf_unknown ("ATE", enc);
22576
22577   return name;
22578 }
22579
22580 static void
22581 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22582 {
22583   unsigned int i;
22584
22585   print_spaces (indent, f);
22586   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22587                       dwarf_tag_name (die->tag), die->abbrev,
22588                       sect_offset_str (die->sect_off));
22589
22590   if (die->parent != NULL)
22591     {
22592       print_spaces (indent, f);
22593       fprintf_unfiltered (f, "  parent at offset: %s\n",
22594                           sect_offset_str (die->parent->sect_off));
22595     }
22596
22597   print_spaces (indent, f);
22598   fprintf_unfiltered (f, "  has children: %s\n",
22599            dwarf_bool_name (die->child != NULL));
22600
22601   print_spaces (indent, f);
22602   fprintf_unfiltered (f, "  attributes:\n");
22603
22604   for (i = 0; i < die->num_attrs; ++i)
22605     {
22606       print_spaces (indent, f);
22607       fprintf_unfiltered (f, "    %s (%s) ",
22608                dwarf_attr_name (die->attrs[i].name),
22609                dwarf_form_name (die->attrs[i].form));
22610
22611       switch (die->attrs[i].form)
22612         {
22613         case DW_FORM_addr:
22614         case DW_FORM_addrx:
22615         case DW_FORM_GNU_addr_index:
22616           fprintf_unfiltered (f, "address: ");
22617           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22618           break;
22619         case DW_FORM_block2:
22620         case DW_FORM_block4:
22621         case DW_FORM_block:
22622         case DW_FORM_block1:
22623           fprintf_unfiltered (f, "block: size %s",
22624                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22625           break;
22626         case DW_FORM_exprloc:
22627           fprintf_unfiltered (f, "expression: size %s",
22628                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22629           break;
22630         case DW_FORM_data16:
22631           fprintf_unfiltered (f, "constant of 16 bytes");
22632           break;
22633         case DW_FORM_ref_addr:
22634           fprintf_unfiltered (f, "ref address: ");
22635           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22636           break;
22637         case DW_FORM_GNU_ref_alt:
22638           fprintf_unfiltered (f, "alt ref address: ");
22639           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22640           break;
22641         case DW_FORM_ref1:
22642         case DW_FORM_ref2:
22643         case DW_FORM_ref4:
22644         case DW_FORM_ref8:
22645         case DW_FORM_ref_udata:
22646           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22647                               (long) (DW_UNSND (&die->attrs[i])));
22648           break;
22649         case DW_FORM_data1:
22650         case DW_FORM_data2:
22651         case DW_FORM_data4:
22652         case DW_FORM_data8:
22653         case DW_FORM_udata:
22654         case DW_FORM_sdata:
22655           fprintf_unfiltered (f, "constant: %s",
22656                               pulongest (DW_UNSND (&die->attrs[i])));
22657           break;
22658         case DW_FORM_sec_offset:
22659           fprintf_unfiltered (f, "section offset: %s",
22660                               pulongest (DW_UNSND (&die->attrs[i])));
22661           break;
22662         case DW_FORM_ref_sig8:
22663           fprintf_unfiltered (f, "signature: %s",
22664                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22665           break;
22666         case DW_FORM_string:
22667         case DW_FORM_strp:
22668         case DW_FORM_line_strp:
22669         case DW_FORM_strx:
22670         case DW_FORM_GNU_str_index:
22671         case DW_FORM_GNU_strp_alt:
22672           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22673                    DW_STRING (&die->attrs[i])
22674                    ? DW_STRING (&die->attrs[i]) : "",
22675                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22676           break;
22677         case DW_FORM_flag:
22678           if (DW_UNSND (&die->attrs[i]))
22679             fprintf_unfiltered (f, "flag: TRUE");
22680           else
22681             fprintf_unfiltered (f, "flag: FALSE");
22682           break;
22683         case DW_FORM_flag_present:
22684           fprintf_unfiltered (f, "flag: TRUE");
22685           break;
22686         case DW_FORM_indirect:
22687           /* The reader will have reduced the indirect form to
22688              the "base form" so this form should not occur.  */
22689           fprintf_unfiltered (f,
22690                               "unexpected attribute form: DW_FORM_indirect");
22691           break;
22692         case DW_FORM_implicit_const:
22693           fprintf_unfiltered (f, "constant: %s",
22694                               plongest (DW_SND (&die->attrs[i])));
22695           break;
22696         default:
22697           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22698                    die->attrs[i].form);
22699           break;
22700         }
22701       fprintf_unfiltered (f, "\n");
22702     }
22703 }
22704
22705 static void
22706 dump_die_for_error (struct die_info *die)
22707 {
22708   dump_die_shallow (gdb_stderr, 0, die);
22709 }
22710
22711 static void
22712 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22713 {
22714   int indent = level * 4;
22715
22716   gdb_assert (die != NULL);
22717
22718   if (level >= max_level)
22719     return;
22720
22721   dump_die_shallow (f, indent, die);
22722
22723   if (die->child != NULL)
22724     {
22725       print_spaces (indent, f);
22726       fprintf_unfiltered (f, "  Children:");
22727       if (level + 1 < max_level)
22728         {
22729           fprintf_unfiltered (f, "\n");
22730           dump_die_1 (f, level + 1, max_level, die->child);
22731         }
22732       else
22733         {
22734           fprintf_unfiltered (f,
22735                               " [not printed, max nesting level reached]\n");
22736         }
22737     }
22738
22739   if (die->sibling != NULL && level > 0)
22740     {
22741       dump_die_1 (f, level, max_level, die->sibling);
22742     }
22743 }
22744
22745 /* This is called from the pdie macro in gdbinit.in.
22746    It's not static so gcc will keep a copy callable from gdb.  */
22747
22748 void
22749 dump_die (struct die_info *die, int max_level)
22750 {
22751   dump_die_1 (gdb_stdlog, 0, max_level, die);
22752 }
22753
22754 static void
22755 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22756 {
22757   void **slot;
22758
22759   slot = htab_find_slot_with_hash (cu->die_hash, die,
22760                                    to_underlying (die->sect_off),
22761                                    INSERT);
22762
22763   *slot = die;
22764 }
22765
22766 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22767    required kind.  */
22768
22769 static sect_offset
22770 dwarf2_get_ref_die_offset (const struct attribute *attr)
22771 {
22772   if (attr->form_is_ref ())
22773     return (sect_offset) DW_UNSND (attr);
22774
22775   complaint (_("unsupported die ref attribute form: '%s'"),
22776              dwarf_form_name (attr->form));
22777   return {};
22778 }
22779
22780 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22781  * the value held by the attribute is not constant.  */
22782
22783 static LONGEST
22784 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22785 {
22786   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22787     return DW_SND (attr);
22788   else if (attr->form == DW_FORM_udata
22789            || attr->form == DW_FORM_data1
22790            || attr->form == DW_FORM_data2
22791            || attr->form == DW_FORM_data4
22792            || attr->form == DW_FORM_data8)
22793     return DW_UNSND (attr);
22794   else
22795     {
22796       /* For DW_FORM_data16 see attribute::form_is_constant.  */
22797       complaint (_("Attribute value is not a constant (%s)"),
22798                  dwarf_form_name (attr->form));
22799       return default_value;
22800     }
22801 }
22802
22803 /* Follow reference or signature attribute ATTR of SRC_DIE.
22804    On entry *REF_CU is the CU of SRC_DIE.
22805    On exit *REF_CU is the CU of the result.  */
22806
22807 static struct die_info *
22808 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22809                        struct dwarf2_cu **ref_cu)
22810 {
22811   struct die_info *die;
22812
22813   if (attr->form_is_ref ())
22814     die = follow_die_ref (src_die, attr, ref_cu);
22815   else if (attr->form == DW_FORM_ref_sig8)
22816     die = follow_die_sig (src_die, attr, ref_cu);
22817   else
22818     {
22819       dump_die_for_error (src_die);
22820       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22821              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22822     }
22823
22824   return die;
22825 }
22826
22827 /* Follow reference OFFSET.
22828    On entry *REF_CU is the CU of the source die referencing OFFSET.
22829    On exit *REF_CU is the CU of the result.
22830    Returns NULL if OFFSET is invalid.  */
22831
22832 static struct die_info *
22833 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22834                    struct dwarf2_cu **ref_cu)
22835 {
22836   struct die_info temp_die;
22837   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22838   struct dwarf2_per_objfile *dwarf2_per_objfile
22839     = cu->per_cu->dwarf2_per_objfile;
22840
22841   gdb_assert (cu->per_cu != NULL);
22842
22843   target_cu = cu;
22844
22845   if (cu->per_cu->is_debug_types)
22846     {
22847       /* .debug_types CUs cannot reference anything outside their CU.
22848          If they need to, they have to reference a signatured type via
22849          DW_FORM_ref_sig8.  */
22850       if (!offset_in_cu_p (&cu->header, sect_off))
22851         return NULL;
22852     }
22853   else if (offset_in_dwz != cu->per_cu->is_dwz
22854            || !offset_in_cu_p (&cu->header, sect_off))
22855     {
22856       struct dwarf2_per_cu_data *per_cu;
22857
22858       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22859                                                  dwarf2_per_objfile);
22860
22861       /* If necessary, add it to the queue and load its DIEs.  */
22862       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22863         load_full_comp_unit (per_cu, false, cu->language);
22864
22865       target_cu = per_cu->cu;
22866     }
22867   else if (cu->dies == NULL)
22868     {
22869       /* We're loading full DIEs during partial symbol reading.  */
22870       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22871       load_full_comp_unit (cu->per_cu, false, language_minimal);
22872     }
22873
22874   *ref_cu = target_cu;
22875   temp_die.sect_off = sect_off;
22876
22877   if (target_cu != cu)
22878     target_cu->ancestor = cu;
22879
22880   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22881                                                   &temp_die,
22882                                                   to_underlying (sect_off));
22883 }
22884
22885 /* Follow reference attribute ATTR of SRC_DIE.
22886    On entry *REF_CU is the CU of SRC_DIE.
22887    On exit *REF_CU is the CU of the result.  */
22888
22889 static struct die_info *
22890 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22891                 struct dwarf2_cu **ref_cu)
22892 {
22893   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22894   struct dwarf2_cu *cu = *ref_cu;
22895   struct die_info *die;
22896
22897   die = follow_die_offset (sect_off,
22898                            (attr->form == DW_FORM_GNU_ref_alt
22899                             || cu->per_cu->is_dwz),
22900                            ref_cu);
22901   if (!die)
22902     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22903            "at %s [in module %s]"),
22904            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22905            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22906
22907   return die;
22908 }
22909
22910 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22911    Returned value is intended for DW_OP_call*.  Returned
22912    dwarf2_locexpr_baton->data has lifetime of
22913    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22914
22915 struct dwarf2_locexpr_baton
22916 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22917                                struct dwarf2_per_cu_data *per_cu,
22918                                CORE_ADDR (*get_frame_pc) (void *baton),
22919                                void *baton, bool resolve_abstract_p)
22920 {
22921   struct dwarf2_cu *cu;
22922   struct die_info *die;
22923   struct attribute *attr;
22924   struct dwarf2_locexpr_baton retval;
22925   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22926   struct objfile *objfile = dwarf2_per_objfile->objfile;
22927
22928   if (per_cu->cu == NULL)
22929     load_cu (per_cu, false);
22930   cu = per_cu->cu;
22931   if (cu == NULL)
22932     {
22933       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22934          Instead just throw an error, not much else we can do.  */
22935       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22936              sect_offset_str (sect_off), objfile_name (objfile));
22937     }
22938
22939   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22940   if (!die)
22941     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22942            sect_offset_str (sect_off), objfile_name (objfile));
22943
22944   attr = dwarf2_attr (die, DW_AT_location, cu);
22945   if (!attr && resolve_abstract_p
22946       && (dwarf2_per_objfile->abstract_to_concrete.find (die->sect_off)
22947           != dwarf2_per_objfile->abstract_to_concrete.end ()))
22948     {
22949       CORE_ADDR pc = (*get_frame_pc) (baton);
22950       CORE_ADDR baseaddr = objfile->text_section_offset ();
22951       struct gdbarch *gdbarch = get_objfile_arch (objfile);
22952
22953       for (const auto &cand_off
22954              : dwarf2_per_objfile->abstract_to_concrete[die->sect_off])
22955         {
22956           struct dwarf2_cu *cand_cu = cu;
22957           struct die_info *cand
22958             = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
22959           if (!cand
22960               || !cand->parent
22961               || cand->parent->tag != DW_TAG_subprogram)
22962             continue;
22963
22964           CORE_ADDR pc_low, pc_high;
22965           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
22966           if (pc_low == ((CORE_ADDR) -1))
22967             continue;
22968           pc_low = gdbarch_adjust_dwarf2_addr (gdbarch, pc_low + baseaddr);
22969           pc_high = gdbarch_adjust_dwarf2_addr (gdbarch, pc_high + baseaddr);
22970           if (!(pc_low <= pc && pc < pc_high))
22971             continue;
22972
22973           die = cand;
22974           attr = dwarf2_attr (die, DW_AT_location, cu);
22975           break;
22976         }
22977     }
22978
22979   if (!attr)
22980     {
22981       /* DWARF: "If there is no such attribute, then there is no effect.".
22982          DATA is ignored if SIZE is 0.  */
22983
22984       retval.data = NULL;
22985       retval.size = 0;
22986     }
22987   else if (attr->form_is_section_offset ())
22988     {
22989       struct dwarf2_loclist_baton loclist_baton;
22990       CORE_ADDR pc = (*get_frame_pc) (baton);
22991       size_t size;
22992
22993       fill_in_loclist_baton (cu, &loclist_baton, attr);
22994
22995       retval.data = dwarf2_find_location_expression (&loclist_baton,
22996                                                      &size, pc);
22997       retval.size = size;
22998     }
22999   else
23000     {
23001       if (!attr->form_is_block ())
23002         error (_("Dwarf Error: DIE at %s referenced in module %s "
23003                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23004                sect_offset_str (sect_off), objfile_name (objfile));
23005
23006       retval.data = DW_BLOCK (attr)->data;
23007       retval.size = DW_BLOCK (attr)->size;
23008     }
23009   retval.per_cu = cu->per_cu;
23010
23011   age_cached_comp_units (dwarf2_per_objfile);
23012
23013   return retval;
23014 }
23015
23016 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23017    offset.  */
23018
23019 struct dwarf2_locexpr_baton
23020 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23021                              struct dwarf2_per_cu_data *per_cu,
23022                              CORE_ADDR (*get_frame_pc) (void *baton),
23023                              void *baton)
23024 {
23025   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23026
23027   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23028 }
23029
23030 /* Write a constant of a given type as target-ordered bytes into
23031    OBSTACK.  */
23032
23033 static const gdb_byte *
23034 write_constant_as_bytes (struct obstack *obstack,
23035                          enum bfd_endian byte_order,
23036                          struct type *type,
23037                          ULONGEST value,
23038                          LONGEST *len)
23039 {
23040   gdb_byte *result;
23041
23042   *len = TYPE_LENGTH (type);
23043   result = (gdb_byte *) obstack_alloc (obstack, *len);
23044   store_unsigned_integer (result, *len, byte_order, value);
23045
23046   return result;
23047 }
23048
23049 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23050    pointer to the constant bytes and set LEN to the length of the
23051    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23052    does not have a DW_AT_const_value, return NULL.  */
23053
23054 const gdb_byte *
23055 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23056                              struct dwarf2_per_cu_data *per_cu,
23057                              struct obstack *obstack,
23058                              LONGEST *len)
23059 {
23060   struct dwarf2_cu *cu;
23061   struct die_info *die;
23062   struct attribute *attr;
23063   const gdb_byte *result = NULL;
23064   struct type *type;
23065   LONGEST value;
23066   enum bfd_endian byte_order;
23067   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23068
23069   if (per_cu->cu == NULL)
23070     load_cu (per_cu, false);
23071   cu = per_cu->cu;
23072   if (cu == NULL)
23073     {
23074       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23075          Instead just throw an error, not much else we can do.  */
23076       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23077              sect_offset_str (sect_off), objfile_name (objfile));
23078     }
23079
23080   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23081   if (!die)
23082     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23083            sect_offset_str (sect_off), objfile_name (objfile));
23084
23085   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23086   if (attr == NULL)
23087     return NULL;
23088
23089   byte_order = (bfd_big_endian (objfile->obfd)
23090                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23091
23092   switch (attr->form)
23093     {
23094     case DW_FORM_addr:
23095     case DW_FORM_addrx:
23096     case DW_FORM_GNU_addr_index:
23097       {
23098         gdb_byte *tem;
23099
23100         *len = cu->header.addr_size;
23101         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23102         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23103         result = tem;
23104       }
23105       break;
23106     case DW_FORM_string:
23107     case DW_FORM_strp:
23108     case DW_FORM_strx:
23109     case DW_FORM_GNU_str_index:
23110     case DW_FORM_GNU_strp_alt:
23111       /* DW_STRING is already allocated on the objfile obstack, point
23112          directly to it.  */
23113       result = (const gdb_byte *) DW_STRING (attr);
23114       *len = strlen (DW_STRING (attr));
23115       break;
23116     case DW_FORM_block1:
23117     case DW_FORM_block2:
23118     case DW_FORM_block4:
23119     case DW_FORM_block:
23120     case DW_FORM_exprloc:
23121     case DW_FORM_data16:
23122       result = DW_BLOCK (attr)->data;
23123       *len = DW_BLOCK (attr)->size;
23124       break;
23125
23126       /* The DW_AT_const_value attributes are supposed to carry the
23127          symbol's value "represented as it would be on the target
23128          architecture."  By the time we get here, it's already been
23129          converted to host endianness, so we just need to sign- or
23130          zero-extend it as appropriate.  */
23131     case DW_FORM_data1:
23132       type = die_type (die, cu);
23133       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23134       if (result == NULL)
23135         result = write_constant_as_bytes (obstack, byte_order,
23136                                           type, value, len);
23137       break;
23138     case DW_FORM_data2:
23139       type = die_type (die, cu);
23140       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23141       if (result == NULL)
23142         result = write_constant_as_bytes (obstack, byte_order,
23143                                           type, value, len);
23144       break;
23145     case DW_FORM_data4:
23146       type = die_type (die, cu);
23147       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23148       if (result == NULL)
23149         result = write_constant_as_bytes (obstack, byte_order,
23150                                           type, value, len);
23151       break;
23152     case DW_FORM_data8:
23153       type = die_type (die, cu);
23154       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23155       if (result == NULL)
23156         result = write_constant_as_bytes (obstack, byte_order,
23157                                           type, value, len);
23158       break;
23159
23160     case DW_FORM_sdata:
23161     case DW_FORM_implicit_const:
23162       type = die_type (die, cu);
23163       result = write_constant_as_bytes (obstack, byte_order,
23164                                         type, DW_SND (attr), len);
23165       break;
23166
23167     case DW_FORM_udata:
23168       type = die_type (die, cu);
23169       result = write_constant_as_bytes (obstack, byte_order,
23170                                         type, DW_UNSND (attr), len);
23171       break;
23172
23173     default:
23174       complaint (_("unsupported const value attribute form: '%s'"),
23175                  dwarf_form_name (attr->form));
23176       break;
23177     }
23178
23179   return result;
23180 }
23181
23182 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23183    valid type for this die is found.  */
23184
23185 struct type *
23186 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23187                                 struct dwarf2_per_cu_data *per_cu)
23188 {
23189   struct dwarf2_cu *cu;
23190   struct die_info *die;
23191
23192   if (per_cu->cu == NULL)
23193     load_cu (per_cu, false);
23194   cu = per_cu->cu;
23195   if (!cu)
23196     return NULL;
23197
23198   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23199   if (!die)
23200     return NULL;
23201
23202   return die_type (die, cu);
23203 }
23204
23205 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23206    PER_CU.  */
23207
23208 struct type *
23209 dwarf2_get_die_type (cu_offset die_offset,
23210                      struct dwarf2_per_cu_data *per_cu)
23211 {
23212   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23213   return get_die_type_at_offset (die_offset_sect, per_cu);
23214 }
23215
23216 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23217    On entry *REF_CU is the CU of SRC_DIE.
23218    On exit *REF_CU is the CU of the result.
23219    Returns NULL if the referenced DIE isn't found.  */
23220
23221 static struct die_info *
23222 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23223                   struct dwarf2_cu **ref_cu)
23224 {
23225   struct die_info temp_die;
23226   struct dwarf2_cu *sig_cu, *cu = *ref_cu;
23227   struct die_info *die;
23228
23229   /* While it might be nice to assert sig_type->type == NULL here,
23230      we can get here for DW_AT_imported_declaration where we need
23231      the DIE not the type.  */
23232
23233   /* If necessary, add it to the queue and load its DIEs.  */
23234
23235   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23236     read_signatured_type (sig_type);
23237
23238   sig_cu = sig_type->per_cu.cu;
23239   gdb_assert (sig_cu != NULL);
23240   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23241   temp_die.sect_off = sig_type->type_offset_in_section;
23242   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23243                                                  to_underlying (temp_die.sect_off));
23244   if (die)
23245     {
23246       struct dwarf2_per_objfile *dwarf2_per_objfile
23247         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23248
23249       /* For .gdb_index version 7 keep track of included TUs.
23250          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23251       if (dwarf2_per_objfile->index_table != NULL
23252           && dwarf2_per_objfile->index_table->version <= 7)
23253         {
23254           (*ref_cu)->per_cu->imported_symtabs_push (sig_cu->per_cu);
23255         }
23256
23257       *ref_cu = sig_cu;
23258       if (sig_cu != cu)
23259         sig_cu->ancestor = cu;
23260
23261       return die;
23262     }
23263
23264   return NULL;
23265 }
23266
23267 /* Follow signatured type referenced by ATTR in SRC_DIE.
23268    On entry *REF_CU is the CU of SRC_DIE.
23269    On exit *REF_CU is the CU of the result.
23270    The result is the DIE of the type.
23271    If the referenced type cannot be found an error is thrown.  */
23272
23273 static struct die_info *
23274 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23275                 struct dwarf2_cu **ref_cu)
23276 {
23277   ULONGEST signature = DW_SIGNATURE (attr);
23278   struct signatured_type *sig_type;
23279   struct die_info *die;
23280
23281   gdb_assert (attr->form == DW_FORM_ref_sig8);
23282
23283   sig_type = lookup_signatured_type (*ref_cu, signature);
23284   /* sig_type will be NULL if the signatured type is missing from
23285      the debug info.  */
23286   if (sig_type == NULL)
23287     {
23288       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23289                " from DIE at %s [in module %s]"),
23290              hex_string (signature), sect_offset_str (src_die->sect_off),
23291              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23292     }
23293
23294   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23295   if (die == NULL)
23296     {
23297       dump_die_for_error (src_die);
23298       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23299                " from DIE at %s [in module %s]"),
23300              hex_string (signature), sect_offset_str (src_die->sect_off),
23301              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23302     }
23303
23304   return die;
23305 }
23306
23307 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23308    reading in and processing the type unit if necessary.  */
23309
23310 static struct type *
23311 get_signatured_type (struct die_info *die, ULONGEST signature,
23312                      struct dwarf2_cu *cu)
23313 {
23314   struct dwarf2_per_objfile *dwarf2_per_objfile
23315     = cu->per_cu->dwarf2_per_objfile;
23316   struct signatured_type *sig_type;
23317   struct dwarf2_cu *type_cu;
23318   struct die_info *type_die;
23319   struct type *type;
23320
23321   sig_type = lookup_signatured_type (cu, signature);
23322   /* sig_type will be NULL if the signatured type is missing from
23323      the debug info.  */
23324   if (sig_type == NULL)
23325     {
23326       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23327                    " from DIE at %s [in module %s]"),
23328                  hex_string (signature), sect_offset_str (die->sect_off),
23329                  objfile_name (dwarf2_per_objfile->objfile));
23330       return build_error_marker_type (cu, die);
23331     }
23332
23333   /* If we already know the type we're done.  */
23334   if (sig_type->type != NULL)
23335     return sig_type->type;
23336
23337   type_cu = cu;
23338   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23339   if (type_die != NULL)
23340     {
23341       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23342          is created.  This is important, for example, because for c++ classes
23343          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23344       type = read_type_die (type_die, type_cu);
23345       if (type == NULL)
23346         {
23347           complaint (_("Dwarf Error: Cannot build signatured type %s"
23348                        " referenced from DIE at %s [in module %s]"),
23349                      hex_string (signature), sect_offset_str (die->sect_off),
23350                      objfile_name (dwarf2_per_objfile->objfile));
23351           type = build_error_marker_type (cu, die);
23352         }
23353     }
23354   else
23355     {
23356       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23357                    " from DIE at %s [in module %s]"),
23358                  hex_string (signature), sect_offset_str (die->sect_off),
23359                  objfile_name (dwarf2_per_objfile->objfile));
23360       type = build_error_marker_type (cu, die);
23361     }
23362   sig_type->type = type;
23363
23364   return type;
23365 }
23366
23367 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23368    reading in and processing the type unit if necessary.  */
23369
23370 static struct type *
23371 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23372                           struct dwarf2_cu *cu) /* ARI: editCase function */
23373 {
23374   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23375   if (attr->form_is_ref ())
23376     {
23377       struct dwarf2_cu *type_cu = cu;
23378       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23379
23380       return read_type_die (type_die, type_cu);
23381     }
23382   else if (attr->form == DW_FORM_ref_sig8)
23383     {
23384       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23385     }
23386   else
23387     {
23388       struct dwarf2_per_objfile *dwarf2_per_objfile
23389         = cu->per_cu->dwarf2_per_objfile;
23390
23391       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23392                    " at %s [in module %s]"),
23393                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23394                  objfile_name (dwarf2_per_objfile->objfile));
23395       return build_error_marker_type (cu, die);
23396     }
23397 }
23398
23399 /* Load the DIEs associated with type unit PER_CU into memory.  */
23400
23401 static void
23402 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23403 {
23404   struct signatured_type *sig_type;
23405
23406   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23407   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23408
23409   /* We have the per_cu, but we need the signatured_type.
23410      Fortunately this is an easy translation.  */
23411   gdb_assert (per_cu->is_debug_types);
23412   sig_type = (struct signatured_type *) per_cu;
23413
23414   gdb_assert (per_cu->cu == NULL);
23415
23416   read_signatured_type (sig_type);
23417
23418   gdb_assert (per_cu->cu != NULL);
23419 }
23420
23421 /* Read in a signatured type and build its CU and DIEs.
23422    If the type is a stub for the real type in a DWO file,
23423    read in the real type from the DWO file as well.  */
23424
23425 static void
23426 read_signatured_type (struct signatured_type *sig_type)
23427 {
23428   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23429
23430   gdb_assert (per_cu->is_debug_types);
23431   gdb_assert (per_cu->cu == NULL);
23432
23433   cutu_reader reader (per_cu, NULL, 0, 1, false);
23434
23435   if (!reader.dummy_p)
23436     {
23437       struct dwarf2_cu *cu = reader.cu;
23438       const gdb_byte *info_ptr = reader.info_ptr;
23439
23440       gdb_assert (cu->die_hash == NULL);
23441       cu->die_hash =
23442         htab_create_alloc_ex (cu->header.length / 12,
23443                               die_hash,
23444                               die_eq,
23445                               NULL,
23446                               &cu->comp_unit_obstack,
23447                               hashtab_obstack_allocate,
23448                               dummy_obstack_deallocate);
23449
23450       if (reader.comp_unit_die->has_children)
23451         reader.comp_unit_die->child
23452           = read_die_and_siblings (&reader, info_ptr, &info_ptr,
23453                                    reader.comp_unit_die);
23454       cu->dies = reader.comp_unit_die;
23455       /* comp_unit_die is not stored in die_hash, no need.  */
23456
23457       /* We try not to read any attributes in this function, because
23458          not all CUs needed for references have been loaded yet, and
23459          symbol table processing isn't initialized.  But we have to
23460          set the CU language, or we won't be able to build types
23461          correctly.  Similarly, if we do not read the producer, we can
23462          not apply producer-specific interpretation.  */
23463       prepare_one_comp_unit (cu, cu->dies, language_minimal);
23464     }
23465
23466   sig_type->per_cu.tu_read = 1;
23467 }
23468
23469 /* Decode simple location descriptions.
23470    Given a pointer to a dwarf block that defines a location, compute
23471    the location and return the value.
23472
23473    NOTE drow/2003-11-18: This function is called in two situations
23474    now: for the address of static or global variables (partial symbols
23475    only) and for offsets into structures which are expected to be
23476    (more or less) constant.  The partial symbol case should go away,
23477    and only the constant case should remain.  That will let this
23478    function complain more accurately.  A few special modes are allowed
23479    without complaint for global variables (for instance, global
23480    register values and thread-local values).
23481
23482    A location description containing no operations indicates that the
23483    object is optimized out.  The return value is 0 for that case.
23484    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23485    callers will only want a very basic result and this can become a
23486    complaint.
23487
23488    Note that stack[0] is unused except as a default error return.  */
23489
23490 static CORE_ADDR
23491 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23492 {
23493   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23494   size_t i;
23495   size_t size = blk->size;
23496   const gdb_byte *data = blk->data;
23497   CORE_ADDR stack[64];
23498   int stacki;
23499   unsigned int bytes_read, unsnd;
23500   gdb_byte op;
23501
23502   i = 0;
23503   stacki = 0;
23504   stack[stacki] = 0;
23505   stack[++stacki] = 0;
23506
23507   while (i < size)
23508     {
23509       op = data[i++];
23510       switch (op)
23511         {
23512         case DW_OP_lit0:
23513         case DW_OP_lit1:
23514         case DW_OP_lit2:
23515         case DW_OP_lit3:
23516         case DW_OP_lit4:
23517         case DW_OP_lit5:
23518         case DW_OP_lit6:
23519         case DW_OP_lit7:
23520         case DW_OP_lit8:
23521         case DW_OP_lit9:
23522         case DW_OP_lit10:
23523         case DW_OP_lit11:
23524         case DW_OP_lit12:
23525         case DW_OP_lit13:
23526         case DW_OP_lit14:
23527         case DW_OP_lit15:
23528         case DW_OP_lit16:
23529         case DW_OP_lit17:
23530         case DW_OP_lit18:
23531         case DW_OP_lit19:
23532         case DW_OP_lit20:
23533         case DW_OP_lit21:
23534         case DW_OP_lit22:
23535         case DW_OP_lit23:
23536         case DW_OP_lit24:
23537         case DW_OP_lit25:
23538         case DW_OP_lit26:
23539         case DW_OP_lit27:
23540         case DW_OP_lit28:
23541         case DW_OP_lit29:
23542         case DW_OP_lit30:
23543         case DW_OP_lit31:
23544           stack[++stacki] = op - DW_OP_lit0;
23545           break;
23546
23547         case DW_OP_reg0:
23548         case DW_OP_reg1:
23549         case DW_OP_reg2:
23550         case DW_OP_reg3:
23551         case DW_OP_reg4:
23552         case DW_OP_reg5:
23553         case DW_OP_reg6:
23554         case DW_OP_reg7:
23555         case DW_OP_reg8:
23556         case DW_OP_reg9:
23557         case DW_OP_reg10:
23558         case DW_OP_reg11:
23559         case DW_OP_reg12:
23560         case DW_OP_reg13:
23561         case DW_OP_reg14:
23562         case DW_OP_reg15:
23563         case DW_OP_reg16:
23564         case DW_OP_reg17:
23565         case DW_OP_reg18:
23566         case DW_OP_reg19:
23567         case DW_OP_reg20:
23568         case DW_OP_reg21:
23569         case DW_OP_reg22:
23570         case DW_OP_reg23:
23571         case DW_OP_reg24:
23572         case DW_OP_reg25:
23573         case DW_OP_reg26:
23574         case DW_OP_reg27:
23575         case DW_OP_reg28:
23576         case DW_OP_reg29:
23577         case DW_OP_reg30:
23578         case DW_OP_reg31:
23579           stack[++stacki] = op - DW_OP_reg0;
23580           if (i < size)
23581             dwarf2_complex_location_expr_complaint ();
23582           break;
23583
23584         case DW_OP_regx:
23585           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23586           i += bytes_read;
23587           stack[++stacki] = unsnd;
23588           if (i < size)
23589             dwarf2_complex_location_expr_complaint ();
23590           break;
23591
23592         case DW_OP_addr:
23593           stack[++stacki] = read_address (objfile->obfd, &data[i],
23594                                           cu, &bytes_read);
23595           i += bytes_read;
23596           break;
23597
23598         case DW_OP_const1u:
23599           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23600           i += 1;
23601           break;
23602
23603         case DW_OP_const1s:
23604           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23605           i += 1;
23606           break;
23607
23608         case DW_OP_const2u:
23609           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23610           i += 2;
23611           break;
23612
23613         case DW_OP_const2s:
23614           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23615           i += 2;
23616           break;
23617
23618         case DW_OP_const4u:
23619           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23620           i += 4;
23621           break;
23622
23623         case DW_OP_const4s:
23624           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23625           i += 4;
23626           break;
23627
23628         case DW_OP_const8u:
23629           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23630           i += 8;
23631           break;
23632
23633         case DW_OP_constu:
23634           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23635                                                   &bytes_read);
23636           i += bytes_read;
23637           break;
23638
23639         case DW_OP_consts:
23640           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23641           i += bytes_read;
23642           break;
23643
23644         case DW_OP_dup:
23645           stack[stacki + 1] = stack[stacki];
23646           stacki++;
23647           break;
23648
23649         case DW_OP_plus:
23650           stack[stacki - 1] += stack[stacki];
23651           stacki--;
23652           break;
23653
23654         case DW_OP_plus_uconst:
23655           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23656                                                  &bytes_read);
23657           i += bytes_read;
23658           break;
23659
23660         case DW_OP_minus:
23661           stack[stacki - 1] -= stack[stacki];
23662           stacki--;
23663           break;
23664
23665         case DW_OP_deref:
23666           /* If we're not the last op, then we definitely can't encode
23667              this using GDB's address_class enum.  This is valid for partial
23668              global symbols, although the variable's address will be bogus
23669              in the psymtab.  */
23670           if (i < size)
23671             dwarf2_complex_location_expr_complaint ();
23672           break;
23673
23674         case DW_OP_GNU_push_tls_address:
23675         case DW_OP_form_tls_address:
23676           /* The top of the stack has the offset from the beginning
23677              of the thread control block at which the variable is located.  */
23678           /* Nothing should follow this operator, so the top of stack would
23679              be returned.  */
23680           /* This is valid for partial global symbols, but the variable's
23681              address will be bogus in the psymtab.  Make it always at least
23682              non-zero to not look as a variable garbage collected by linker
23683              which have DW_OP_addr 0.  */
23684           if (i < size)
23685             dwarf2_complex_location_expr_complaint ();
23686           stack[stacki]++;
23687           break;
23688
23689         case DW_OP_GNU_uninit:
23690           break;
23691
23692         case DW_OP_addrx:
23693         case DW_OP_GNU_addr_index:
23694         case DW_OP_GNU_const_index:
23695           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23696                                                          &bytes_read);
23697           i += bytes_read;
23698           break;
23699
23700         default:
23701           {
23702             const char *name = get_DW_OP_name (op);
23703
23704             if (name)
23705               complaint (_("unsupported stack op: '%s'"),
23706                          name);
23707             else
23708               complaint (_("unsupported stack op: '%02x'"),
23709                          op);
23710           }
23711
23712           return (stack[stacki]);
23713         }
23714
23715       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23716          outside of the allocated space.  Also enforce minimum>0.  */
23717       if (stacki >= ARRAY_SIZE (stack) - 1)
23718         {
23719           complaint (_("location description stack overflow"));
23720           return 0;
23721         }
23722
23723       if (stacki <= 0)
23724         {
23725           complaint (_("location description stack underflow"));
23726           return 0;
23727         }
23728     }
23729   return (stack[stacki]);
23730 }
23731
23732 /* memory allocation interface */
23733
23734 static struct dwarf_block *
23735 dwarf_alloc_block (struct dwarf2_cu *cu)
23736 {
23737   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23738 }
23739
23740 static struct die_info *
23741 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23742 {
23743   struct die_info *die;
23744   size_t size = sizeof (struct die_info);
23745
23746   if (num_attrs > 1)
23747     size += (num_attrs - 1) * sizeof (struct attribute);
23748
23749   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23750   memset (die, 0, sizeof (struct die_info));
23751   return (die);
23752 }
23753
23754 \f
23755 /* Macro support.  */
23756
23757 char *
23758 line_header::file_file_name (int file)
23759 {
23760   /* Is the file number a valid index into the line header's file name
23761      table?  Remember that file numbers start with one, not zero.  */
23762   if (is_valid_file_index (file))
23763     {
23764       const file_entry *fe = file_name_at (file);
23765
23766       if (!IS_ABSOLUTE_PATH (fe->name))
23767         {
23768           const char *dir = fe->include_dir (this);
23769           if (dir != NULL)
23770             return concat (dir, SLASH_STRING, fe->name, (char *) NULL);
23771         }
23772       return xstrdup (fe->name);
23773     }
23774   else
23775     {
23776       /* The compiler produced a bogus file number.  We can at least
23777          record the macro definitions made in the file, even if we
23778          won't be able to find the file by name.  */
23779       char fake_name[80];
23780
23781       xsnprintf (fake_name, sizeof (fake_name),
23782                  "<bad macro file number %d>", file);
23783
23784       complaint (_("bad file number in macro information (%d)"),
23785                  file);
23786
23787       return xstrdup (fake_name);
23788     }
23789 }
23790
23791 char *
23792 line_header::file_full_name (int file, const char *comp_dir)
23793 {
23794   /* Is the file number a valid index into the line header's file name
23795      table?  Remember that file numbers start with one, not zero.  */
23796   if (is_valid_file_index (file))
23797     {
23798       char *relative = file_file_name (file);
23799
23800       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23801         return relative;
23802       return reconcat (relative, comp_dir, SLASH_STRING,
23803                        relative, (char *) NULL);
23804     }
23805   else
23806     return file_file_name (file);
23807 }
23808
23809
23810 static struct macro_source_file *
23811 macro_start_file (struct dwarf2_cu *cu,
23812                   int file, int line,
23813                   struct macro_source_file *current_file,
23814                   struct line_header *lh)
23815 {
23816   /* File name relative to the compilation directory of this source file.  */
23817   char *file_name = lh->file_file_name (file);
23818
23819   if (! current_file)
23820     {
23821       /* Note: We don't create a macro table for this compilation unit
23822          at all until we actually get a filename.  */
23823       struct macro_table *macro_table = cu->get_builder ()->get_macro_table ();
23824
23825       /* If we have no current file, then this must be the start_file
23826          directive for the compilation unit's main source file.  */
23827       current_file = macro_set_main (macro_table, file_name);
23828       macro_define_special (macro_table);
23829     }
23830   else
23831     current_file = macro_include (current_file, line, file_name);
23832
23833   xfree (file_name);
23834
23835   return current_file;
23836 }
23837
23838 static const char *
23839 consume_improper_spaces (const char *p, const char *body)
23840 {
23841   if (*p == ' ')
23842     {
23843       complaint (_("macro definition contains spaces "
23844                    "in formal argument list:\n`%s'"),
23845                  body);
23846
23847       while (*p == ' ')
23848         p++;
23849     }
23850
23851   return p;
23852 }
23853
23854
23855 static void
23856 parse_macro_definition (struct macro_source_file *file, int line,
23857                         const char *body)
23858 {
23859   const char *p;
23860
23861   /* The body string takes one of two forms.  For object-like macro
23862      definitions, it should be:
23863
23864         <macro name> " " <definition>
23865
23866      For function-like macro definitions, it should be:
23867
23868         <macro name> "() " <definition>
23869      or
23870         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23871
23872      Spaces may appear only where explicitly indicated, and in the
23873      <definition>.
23874
23875      The Dwarf 2 spec says that an object-like macro's name is always
23876      followed by a space, but versions of GCC around March 2002 omit
23877      the space when the macro's definition is the empty string.
23878
23879      The Dwarf 2 spec says that there should be no spaces between the
23880      formal arguments in a function-like macro's formal argument list,
23881      but versions of GCC around March 2002 include spaces after the
23882      commas.  */
23883
23884
23885   /* Find the extent of the macro name.  The macro name is terminated
23886      by either a space or null character (for an object-like macro) or
23887      an opening paren (for a function-like macro).  */
23888   for (p = body; *p; p++)
23889     if (*p == ' ' || *p == '(')
23890       break;
23891
23892   if (*p == ' ' || *p == '\0')
23893     {
23894       /* It's an object-like macro.  */
23895       int name_len = p - body;
23896       std::string name (body, name_len);
23897       const char *replacement;
23898
23899       if (*p == ' ')
23900         replacement = body + name_len + 1;
23901       else
23902         {
23903           dwarf2_macro_malformed_definition_complaint (body);
23904           replacement = body + name_len;
23905         }
23906
23907       macro_define_object (file, line, name.c_str (), replacement);
23908     }
23909   else if (*p == '(')
23910     {
23911       /* It's a function-like macro.  */
23912       std::string name (body, p - body);
23913       int argc = 0;
23914       int argv_size = 1;
23915       char **argv = XNEWVEC (char *, argv_size);
23916
23917       p++;
23918
23919       p = consume_improper_spaces (p, body);
23920
23921       /* Parse the formal argument list.  */
23922       while (*p && *p != ')')
23923         {
23924           /* Find the extent of the current argument name.  */
23925           const char *arg_start = p;
23926
23927           while (*p && *p != ',' && *p != ')' && *p != ' ')
23928             p++;
23929
23930           if (! *p || p == arg_start)
23931             dwarf2_macro_malformed_definition_complaint (body);
23932           else
23933             {
23934               /* Make sure argv has room for the new argument.  */
23935               if (argc >= argv_size)
23936                 {
23937                   argv_size *= 2;
23938                   argv = XRESIZEVEC (char *, argv, argv_size);
23939                 }
23940
23941               argv[argc++] = savestring (arg_start, p - arg_start);
23942             }
23943
23944           p = consume_improper_spaces (p, body);
23945
23946           /* Consume the comma, if present.  */
23947           if (*p == ',')
23948             {
23949               p++;
23950
23951               p = consume_improper_spaces (p, body);
23952             }
23953         }
23954
23955       if (*p == ')')
23956         {
23957           p++;
23958
23959           if (*p == ' ')
23960             /* Perfectly formed definition, no complaints.  */
23961             macro_define_function (file, line, name.c_str (),
23962                                    argc, (const char **) argv,
23963                                    p + 1);
23964           else if (*p == '\0')
23965             {
23966               /* Complain, but do define it.  */
23967               dwarf2_macro_malformed_definition_complaint (body);
23968               macro_define_function (file, line, name.c_str (),
23969                                      argc, (const char **) argv,
23970                                      p);
23971             }
23972           else
23973             /* Just complain.  */
23974             dwarf2_macro_malformed_definition_complaint (body);
23975         }
23976       else
23977         /* Just complain.  */
23978         dwarf2_macro_malformed_definition_complaint (body);
23979
23980       {
23981         int i;
23982
23983         for (i = 0; i < argc; i++)
23984           xfree (argv[i]);
23985       }
23986       xfree (argv);
23987     }
23988   else
23989     dwarf2_macro_malformed_definition_complaint (body);
23990 }
23991
23992 /* Skip some bytes from BYTES according to the form given in FORM.
23993    Returns the new pointer.  */
23994
23995 static const gdb_byte *
23996 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23997                  enum dwarf_form form,
23998                  unsigned int offset_size,
23999                  struct dwarf2_section_info *section)
24000 {
24001   unsigned int bytes_read;
24002
24003   switch (form)
24004     {
24005     case DW_FORM_data1:
24006     case DW_FORM_flag:
24007       ++bytes;
24008       break;
24009
24010     case DW_FORM_data2:
24011       bytes += 2;
24012       break;
24013
24014     case DW_FORM_data4:
24015       bytes += 4;
24016       break;
24017
24018     case DW_FORM_data8:
24019       bytes += 8;
24020       break;
24021
24022     case DW_FORM_data16:
24023       bytes += 16;
24024       break;
24025
24026     case DW_FORM_string:
24027       read_direct_string (abfd, bytes, &bytes_read);
24028       bytes += bytes_read;
24029       break;
24030
24031     case DW_FORM_sec_offset:
24032     case DW_FORM_strp:
24033     case DW_FORM_GNU_strp_alt:
24034       bytes += offset_size;
24035       break;
24036
24037     case DW_FORM_block:
24038       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24039       bytes += bytes_read;
24040       break;
24041
24042     case DW_FORM_block1:
24043       bytes += 1 + read_1_byte (abfd, bytes);
24044       break;
24045     case DW_FORM_block2:
24046       bytes += 2 + read_2_bytes (abfd, bytes);
24047       break;
24048     case DW_FORM_block4:
24049       bytes += 4 + read_4_bytes (abfd, bytes);
24050       break;
24051
24052     case DW_FORM_addrx:
24053     case DW_FORM_sdata:
24054     case DW_FORM_strx:
24055     case DW_FORM_udata:
24056     case DW_FORM_GNU_addr_index:
24057     case DW_FORM_GNU_str_index:
24058       bytes = gdb_skip_leb128 (bytes, buffer_end);
24059       if (bytes == NULL)
24060         {
24061           dwarf2_section_buffer_overflow_complaint (section);
24062           return NULL;
24063         }
24064       break;
24065
24066     case DW_FORM_implicit_const:
24067       break;
24068
24069     default:
24070       {
24071         complaint (_("invalid form 0x%x in `%s'"),
24072                    form, section->get_name ());
24073         return NULL;
24074       }
24075     }
24076
24077   return bytes;
24078 }
24079
24080 /* A helper for dwarf_decode_macros that handles skipping an unknown
24081    opcode.  Returns an updated pointer to the macro data buffer; or,
24082    on error, issues a complaint and returns NULL.  */
24083
24084 static const gdb_byte *
24085 skip_unknown_opcode (unsigned int opcode,
24086                      const gdb_byte **opcode_definitions,
24087                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24088                      bfd *abfd,
24089                      unsigned int offset_size,
24090                      struct dwarf2_section_info *section)
24091 {
24092   unsigned int bytes_read, i;
24093   unsigned long arg;
24094   const gdb_byte *defn;
24095
24096   if (opcode_definitions[opcode] == NULL)
24097     {
24098       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24099                  opcode);
24100       return NULL;
24101     }
24102
24103   defn = opcode_definitions[opcode];
24104   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24105   defn += bytes_read;
24106
24107   for (i = 0; i < arg; ++i)
24108     {
24109       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24110                                  (enum dwarf_form) defn[i], offset_size,
24111                                  section);
24112       if (mac_ptr == NULL)
24113         {
24114           /* skip_form_bytes already issued the complaint.  */
24115           return NULL;
24116         }
24117     }
24118
24119   return mac_ptr;
24120 }
24121
24122 /* A helper function which parses the header of a macro section.
24123    If the macro section is the extended (for now called "GNU") type,
24124    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24125    the header, or issues a complaint and returns NULL on error.  */
24126
24127 static const gdb_byte *
24128 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24129                           bfd *abfd,
24130                           const gdb_byte *mac_ptr,
24131                           unsigned int *offset_size,
24132                           int section_is_gnu)
24133 {
24134   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24135
24136   if (section_is_gnu)
24137     {
24138       unsigned int version, flags;
24139
24140       version = read_2_bytes (abfd, mac_ptr);
24141       if (version != 4 && version != 5)
24142         {
24143           complaint (_("unrecognized version `%d' in .debug_macro section"),
24144                      version);
24145           return NULL;
24146         }
24147       mac_ptr += 2;
24148
24149       flags = read_1_byte (abfd, mac_ptr);
24150       ++mac_ptr;
24151       *offset_size = (flags & 1) ? 8 : 4;
24152
24153       if ((flags & 2) != 0)
24154         /* We don't need the line table offset.  */
24155         mac_ptr += *offset_size;
24156
24157       /* Vendor opcode descriptions.  */
24158       if ((flags & 4) != 0)
24159         {
24160           unsigned int i, count;
24161
24162           count = read_1_byte (abfd, mac_ptr);
24163           ++mac_ptr;
24164           for (i = 0; i < count; ++i)
24165             {
24166               unsigned int opcode, bytes_read;
24167               unsigned long arg;
24168
24169               opcode = read_1_byte (abfd, mac_ptr);
24170               ++mac_ptr;
24171               opcode_definitions[opcode] = mac_ptr;
24172               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24173               mac_ptr += bytes_read;
24174               mac_ptr += arg;
24175             }
24176         }
24177     }
24178
24179   return mac_ptr;
24180 }
24181
24182 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24183    including DW_MACRO_import.  */
24184
24185 static void
24186 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24187                           bfd *abfd,
24188                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24189                           struct macro_source_file *current_file,
24190                           struct line_header *lh,
24191                           struct dwarf2_section_info *section,
24192                           int section_is_gnu, int section_is_dwz,
24193                           unsigned int offset_size,
24194                           htab_t include_hash)
24195 {
24196   struct dwarf2_per_objfile *dwarf2_per_objfile
24197     = cu->per_cu->dwarf2_per_objfile;
24198   struct objfile *objfile = dwarf2_per_objfile->objfile;
24199   enum dwarf_macro_record_type macinfo_type;
24200   int at_commandline;
24201   const gdb_byte *opcode_definitions[256];
24202
24203   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24204                                       &offset_size, section_is_gnu);
24205   if (mac_ptr == NULL)
24206     {
24207       /* We already issued a complaint.  */
24208       return;
24209     }
24210
24211   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24212      GDB is still reading the definitions from command line.  First
24213      DW_MACINFO_start_file will need to be ignored as it was already executed
24214      to create CURRENT_FILE for the main source holding also the command line
24215      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24216      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24217
24218   at_commandline = 1;
24219
24220   do
24221     {
24222       /* Do we at least have room for a macinfo type byte?  */
24223       if (mac_ptr >= mac_end)
24224         {
24225           dwarf2_section_buffer_overflow_complaint (section);
24226           break;
24227         }
24228
24229       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24230       mac_ptr++;
24231
24232       /* Note that we rely on the fact that the corresponding GNU and
24233          DWARF constants are the same.  */
24234       DIAGNOSTIC_PUSH
24235       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24236       switch (macinfo_type)
24237         {
24238           /* A zero macinfo type indicates the end of the macro
24239              information.  */
24240         case 0:
24241           break;
24242
24243         case DW_MACRO_define:
24244         case DW_MACRO_undef:
24245         case DW_MACRO_define_strp:
24246         case DW_MACRO_undef_strp:
24247         case DW_MACRO_define_sup:
24248         case DW_MACRO_undef_sup:
24249           {
24250             unsigned int bytes_read;
24251             int line;
24252             const char *body;
24253             int is_define;
24254
24255             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24256             mac_ptr += bytes_read;
24257
24258             if (macinfo_type == DW_MACRO_define
24259                 || macinfo_type == DW_MACRO_undef)
24260               {
24261                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24262                 mac_ptr += bytes_read;
24263               }
24264             else
24265               {
24266                 LONGEST str_offset;
24267
24268                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24269                 mac_ptr += offset_size;
24270
24271                 if (macinfo_type == DW_MACRO_define_sup
24272                     || macinfo_type == DW_MACRO_undef_sup
24273                     || section_is_dwz)
24274                   {
24275                     struct dwz_file *dwz
24276                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24277
24278                     body = read_indirect_string_from_dwz (objfile,
24279                                                           dwz, str_offset);
24280                   }
24281                 else
24282                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24283                                                          abfd, str_offset);
24284               }
24285
24286             is_define = (macinfo_type == DW_MACRO_define
24287                          || macinfo_type == DW_MACRO_define_strp
24288                          || macinfo_type == DW_MACRO_define_sup);
24289             if (! current_file)
24290               {
24291                 /* DWARF violation as no main source is present.  */
24292                 complaint (_("debug info with no main source gives macro %s "
24293                              "on line %d: %s"),
24294                            is_define ? _("definition") : _("undefinition"),
24295                            line, body);
24296                 break;
24297               }
24298             if ((line == 0 && !at_commandline)
24299                 || (line != 0 && at_commandline))
24300               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24301                          at_commandline ? _("command-line") : _("in-file"),
24302                          is_define ? _("definition") : _("undefinition"),
24303                          line == 0 ? _("zero") : _("non-zero"), line, body);
24304
24305             if (body == NULL)
24306               {
24307                 /* Fedora's rpm-build's "debugedit" binary
24308                    corrupted .debug_macro sections.
24309
24310                    For more info, see
24311                    https://bugzilla.redhat.com/show_bug.cgi?id=1708786 */
24312                 complaint (_("debug info gives %s invalid macro %s "
24313                              "without body (corrupted?) at line %d "
24314                              "on file %s"),
24315                            at_commandline ? _("command-line") : _("in-file"),
24316                            is_define ? _("definition") : _("undefinition"),
24317                            line, current_file->filename);
24318               }
24319             else if (is_define)
24320               parse_macro_definition (current_file, line, body);
24321             else
24322               {
24323                 gdb_assert (macinfo_type == DW_MACRO_undef
24324                             || macinfo_type == DW_MACRO_undef_strp
24325                             || macinfo_type == DW_MACRO_undef_sup);
24326                 macro_undef (current_file, line, body);
24327               }
24328           }
24329           break;
24330
24331         case DW_MACRO_start_file:
24332           {
24333             unsigned int bytes_read;
24334             int line, file;
24335
24336             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24337             mac_ptr += bytes_read;
24338             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24339             mac_ptr += bytes_read;
24340
24341             if ((line == 0 && !at_commandline)
24342                 || (line != 0 && at_commandline))
24343               complaint (_("debug info gives source %d included "
24344                            "from %s at %s line %d"),
24345                          file, at_commandline ? _("command-line") : _("file"),
24346                          line == 0 ? _("zero") : _("non-zero"), line);
24347
24348             if (at_commandline)
24349               {
24350                 /* This DW_MACRO_start_file was executed in the
24351                    pass one.  */
24352                 at_commandline = 0;
24353               }
24354             else
24355               current_file = macro_start_file (cu, file, line, current_file,
24356                                                lh);
24357           }
24358           break;
24359
24360         case DW_MACRO_end_file:
24361           if (! current_file)
24362             complaint (_("macro debug info has an unmatched "
24363                          "`close_file' directive"));
24364           else
24365             {
24366               current_file = current_file->included_by;
24367               if (! current_file)
24368                 {
24369                   enum dwarf_macro_record_type next_type;
24370
24371                   /* GCC circa March 2002 doesn't produce the zero
24372                      type byte marking the end of the compilation
24373                      unit.  Complain if it's not there, but exit no
24374                      matter what.  */
24375
24376                   /* Do we at least have room for a macinfo type byte?  */
24377                   if (mac_ptr >= mac_end)
24378                     {
24379                       dwarf2_section_buffer_overflow_complaint (section);
24380                       return;
24381                     }
24382
24383                   /* We don't increment mac_ptr here, so this is just
24384                      a look-ahead.  */
24385                   next_type
24386                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24387                                                                   mac_ptr);
24388                   if (next_type != 0)
24389                     complaint (_("no terminating 0-type entry for "
24390                                  "macros in `.debug_macinfo' section"));
24391
24392                   return;
24393                 }
24394             }
24395           break;
24396
24397         case DW_MACRO_import:
24398         case DW_MACRO_import_sup:
24399           {
24400             LONGEST offset;
24401             void **slot;
24402             bfd *include_bfd = abfd;
24403             struct dwarf2_section_info *include_section = section;
24404             const gdb_byte *include_mac_end = mac_end;
24405             int is_dwz = section_is_dwz;
24406             const gdb_byte *new_mac_ptr;
24407
24408             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24409             mac_ptr += offset_size;
24410
24411             if (macinfo_type == DW_MACRO_import_sup)
24412               {
24413                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24414
24415                 dwz->macro.read (objfile);
24416
24417                 include_section = &dwz->macro;
24418                 include_bfd = include_section->get_bfd_owner ();
24419                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24420                 is_dwz = 1;
24421               }
24422
24423             new_mac_ptr = include_section->buffer + offset;
24424             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24425
24426             if (*slot != NULL)
24427               {
24428                 /* This has actually happened; see
24429                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24430                 complaint (_("recursive DW_MACRO_import in "
24431                              ".debug_macro section"));
24432               }
24433             else
24434               {
24435                 *slot = (void *) new_mac_ptr;
24436
24437                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24438                                           include_mac_end, current_file, lh,
24439                                           section, section_is_gnu, is_dwz,
24440                                           offset_size, include_hash);
24441
24442                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24443               }
24444           }
24445           break;
24446
24447         case DW_MACINFO_vendor_ext:
24448           if (!section_is_gnu)
24449             {
24450               unsigned int bytes_read;
24451
24452               /* This reads the constant, but since we don't recognize
24453                  any vendor extensions, we ignore it.  */
24454               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24455               mac_ptr += bytes_read;
24456               read_direct_string (abfd, mac_ptr, &bytes_read);
24457               mac_ptr += bytes_read;
24458
24459               /* We don't recognize any vendor extensions.  */
24460               break;
24461             }
24462           /* FALLTHROUGH */
24463
24464         default:
24465           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24466                                          mac_ptr, mac_end, abfd, offset_size,
24467                                          section);
24468           if (mac_ptr == NULL)
24469             return;
24470           break;
24471         }
24472       DIAGNOSTIC_POP
24473     } while (macinfo_type != 0);
24474 }
24475
24476 static void
24477 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24478                      int section_is_gnu)
24479 {
24480   struct dwarf2_per_objfile *dwarf2_per_objfile
24481     = cu->per_cu->dwarf2_per_objfile;
24482   struct objfile *objfile = dwarf2_per_objfile->objfile;
24483   struct line_header *lh = cu->line_header;
24484   bfd *abfd;
24485   const gdb_byte *mac_ptr, *mac_end;
24486   struct macro_source_file *current_file = 0;
24487   enum dwarf_macro_record_type macinfo_type;
24488   unsigned int offset_size = cu->header.offset_size;
24489   const gdb_byte *opcode_definitions[256];
24490   void **slot;
24491   struct dwarf2_section_info *section;
24492   const char *section_name;
24493
24494   if (cu->dwo_unit != NULL)
24495     {
24496       if (section_is_gnu)
24497         {
24498           section = &cu->dwo_unit->dwo_file->sections.macro;
24499           section_name = ".debug_macro.dwo";
24500         }
24501       else
24502         {
24503           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24504           section_name = ".debug_macinfo.dwo";
24505         }
24506     }
24507   else
24508     {
24509       if (section_is_gnu)
24510         {
24511           section = &dwarf2_per_objfile->macro;
24512           section_name = ".debug_macro";
24513         }
24514       else
24515         {
24516           section = &dwarf2_per_objfile->macinfo;
24517           section_name = ".debug_macinfo";
24518         }
24519     }
24520
24521   section->read (objfile);
24522   if (section->buffer == NULL)
24523     {
24524       complaint (_("missing %s section"), section_name);
24525       return;
24526     }
24527   abfd = section->get_bfd_owner ();
24528
24529   /* First pass: Find the name of the base filename.
24530      This filename is needed in order to process all macros whose definition
24531      (or undefinition) comes from the command line.  These macros are defined
24532      before the first DW_MACINFO_start_file entry, and yet still need to be
24533      associated to the base file.
24534
24535      To determine the base file name, we scan the macro definitions until we
24536      reach the first DW_MACINFO_start_file entry.  We then initialize
24537      CURRENT_FILE accordingly so that any macro definition found before the
24538      first DW_MACINFO_start_file can still be associated to the base file.  */
24539
24540   mac_ptr = section->buffer + offset;
24541   mac_end = section->buffer + section->size;
24542
24543   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24544                                       &offset_size, section_is_gnu);
24545   if (mac_ptr == NULL)
24546     {
24547       /* We already issued a complaint.  */
24548       return;
24549     }
24550
24551   do
24552     {
24553       /* Do we at least have room for a macinfo type byte?  */
24554       if (mac_ptr >= mac_end)
24555         {
24556           /* Complaint is printed during the second pass as GDB will probably
24557              stop the first pass earlier upon finding
24558              DW_MACINFO_start_file.  */
24559           break;
24560         }
24561
24562       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24563       mac_ptr++;
24564
24565       /* Note that we rely on the fact that the corresponding GNU and
24566          DWARF constants are the same.  */
24567       DIAGNOSTIC_PUSH
24568       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24569       switch (macinfo_type)
24570         {
24571           /* A zero macinfo type indicates the end of the macro
24572              information.  */
24573         case 0:
24574           break;
24575
24576         case DW_MACRO_define:
24577         case DW_MACRO_undef:
24578           /* Only skip the data by MAC_PTR.  */
24579           {
24580             unsigned int bytes_read;
24581
24582             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24583             mac_ptr += bytes_read;
24584             read_direct_string (abfd, mac_ptr, &bytes_read);
24585             mac_ptr += bytes_read;
24586           }
24587           break;
24588
24589         case DW_MACRO_start_file:
24590           {
24591             unsigned int bytes_read;
24592             int line, file;
24593
24594             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24595             mac_ptr += bytes_read;
24596             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24597             mac_ptr += bytes_read;
24598
24599             current_file = macro_start_file (cu, file, line, current_file, lh);
24600           }
24601           break;
24602
24603         case DW_MACRO_end_file:
24604           /* No data to skip by MAC_PTR.  */
24605           break;
24606
24607         case DW_MACRO_define_strp:
24608         case DW_MACRO_undef_strp:
24609         case DW_MACRO_define_sup:
24610         case DW_MACRO_undef_sup:
24611           {
24612             unsigned int bytes_read;
24613
24614             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24615             mac_ptr += bytes_read;
24616             mac_ptr += offset_size;
24617           }
24618           break;
24619
24620         case DW_MACRO_import:
24621         case DW_MACRO_import_sup:
24622           /* Note that, according to the spec, a transparent include
24623              chain cannot call DW_MACRO_start_file.  So, we can just
24624              skip this opcode.  */
24625           mac_ptr += offset_size;
24626           break;
24627
24628         case DW_MACINFO_vendor_ext:
24629           /* Only skip the data by MAC_PTR.  */
24630           if (!section_is_gnu)
24631             {
24632               unsigned int bytes_read;
24633
24634               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24635               mac_ptr += bytes_read;
24636               read_direct_string (abfd, mac_ptr, &bytes_read);
24637               mac_ptr += bytes_read;
24638             }
24639           /* FALLTHROUGH */
24640
24641         default:
24642           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24643                                          mac_ptr, mac_end, abfd, offset_size,
24644                                          section);
24645           if (mac_ptr == NULL)
24646             return;
24647           break;
24648         }
24649       DIAGNOSTIC_POP
24650     } while (macinfo_type != 0 && current_file == NULL);
24651
24652   /* Second pass: Process all entries.
24653
24654      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24655      command-line macro definitions/undefinitions.  This flag is unset when we
24656      reach the first DW_MACINFO_start_file entry.  */
24657
24658   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24659                                            htab_eq_pointer,
24660                                            NULL, xcalloc, xfree));
24661   mac_ptr = section->buffer + offset;
24662   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24663   *slot = (void *) mac_ptr;
24664   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24665                             current_file, lh, section,
24666                             section_is_gnu, 0, offset_size,
24667                             include_hash.get ());
24668 }
24669
24670 /* Return the .debug_loc section to use for CU.
24671    For DWO files use .debug_loc.dwo.  */
24672
24673 static struct dwarf2_section_info *
24674 cu_debug_loc_section (struct dwarf2_cu *cu)
24675 {
24676   struct dwarf2_per_objfile *dwarf2_per_objfile
24677     = cu->per_cu->dwarf2_per_objfile;
24678
24679   if (cu->dwo_unit)
24680     {
24681       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24682
24683       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24684     }
24685   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24686                                   : &dwarf2_per_objfile->loc);
24687 }
24688
24689 /* A helper function that fills in a dwarf2_loclist_baton.  */
24690
24691 static void
24692 fill_in_loclist_baton (struct dwarf2_cu *cu,
24693                        struct dwarf2_loclist_baton *baton,
24694                        const struct attribute *attr)
24695 {
24696   struct dwarf2_per_objfile *dwarf2_per_objfile
24697     = cu->per_cu->dwarf2_per_objfile;
24698   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24699
24700   section->read (dwarf2_per_objfile->objfile);
24701
24702   baton->per_cu = cu->per_cu;
24703   gdb_assert (baton->per_cu);
24704   /* We don't know how long the location list is, but make sure we
24705      don't run off the edge of the section.  */
24706   baton->size = section->size - DW_UNSND (attr);
24707   baton->data = section->buffer + DW_UNSND (attr);
24708   baton->base_address = cu->base_address;
24709   baton->from_dwo = cu->dwo_unit != NULL;
24710 }
24711
24712 static void
24713 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24714                              struct dwarf2_cu *cu, int is_block)
24715 {
24716   struct dwarf2_per_objfile *dwarf2_per_objfile
24717     = cu->per_cu->dwarf2_per_objfile;
24718   struct objfile *objfile = dwarf2_per_objfile->objfile;
24719   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24720
24721   if (attr->form_is_section_offset ()
24722       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24723          the section.  If so, fall through to the complaint in the
24724          other branch.  */
24725       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24726     {
24727       struct dwarf2_loclist_baton *baton;
24728
24729       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24730
24731       fill_in_loclist_baton (cu, baton, attr);
24732
24733       if (cu->base_known == 0)
24734         complaint (_("Location list used without "
24735                      "specifying the CU base address."));
24736
24737       SYMBOL_ACLASS_INDEX (sym) = (is_block
24738                                    ? dwarf2_loclist_block_index
24739                                    : dwarf2_loclist_index);
24740       SYMBOL_LOCATION_BATON (sym) = baton;
24741     }
24742   else
24743     {
24744       struct dwarf2_locexpr_baton *baton;
24745
24746       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24747       baton->per_cu = cu->per_cu;
24748       gdb_assert (baton->per_cu);
24749
24750       if (attr->form_is_block ())
24751         {
24752           /* Note that we're just copying the block's data pointer
24753              here, not the actual data.  We're still pointing into the
24754              info_buffer for SYM's objfile; right now we never release
24755              that buffer, but when we do clean up properly this may
24756              need to change.  */
24757           baton->size = DW_BLOCK (attr)->size;
24758           baton->data = DW_BLOCK (attr)->data;
24759         }
24760       else
24761         {
24762           dwarf2_invalid_attrib_class_complaint ("location description",
24763                                                  sym->natural_name ());
24764           baton->size = 0;
24765         }
24766
24767       SYMBOL_ACLASS_INDEX (sym) = (is_block
24768                                    ? dwarf2_locexpr_block_index
24769                                    : dwarf2_locexpr_index);
24770       SYMBOL_LOCATION_BATON (sym) = baton;
24771     }
24772 }
24773
24774 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24775    came from a separate debuginfo file, then the master objfile is
24776    returned.  */
24777
24778 struct objfile *
24779 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24780 {
24781   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24782
24783   /* Return the master objfile, so that we can report and look up the
24784      correct file containing this variable.  */
24785   if (objfile->separate_debug_objfile_backlink)
24786     objfile = objfile->separate_debug_objfile_backlink;
24787
24788   return objfile;
24789 }
24790
24791 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24792    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24793    CU_HEADERP first.  */
24794
24795 static const struct comp_unit_head *
24796 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24797                        struct dwarf2_per_cu_data *per_cu)
24798 {
24799   const gdb_byte *info_ptr;
24800
24801   if (per_cu->cu)
24802     return &per_cu->cu->header;
24803
24804   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24805
24806   memset (cu_headerp, 0, sizeof (*cu_headerp));
24807   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24808                        rcuh_kind::COMPILE);
24809
24810   return cu_headerp;
24811 }
24812
24813 /* Return the address size given in the compilation unit header for CU.  */
24814
24815 int
24816 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24817 {
24818   struct comp_unit_head cu_header_local;
24819   const struct comp_unit_head *cu_headerp;
24820
24821   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24822
24823   return cu_headerp->addr_size;
24824 }
24825
24826 /* Return the offset size given in the compilation unit header for CU.  */
24827
24828 int
24829 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24830 {
24831   struct comp_unit_head cu_header_local;
24832   const struct comp_unit_head *cu_headerp;
24833
24834   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24835
24836   return cu_headerp->offset_size;
24837 }
24838
24839 /* See its dwarf2loc.h declaration.  */
24840
24841 int
24842 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24843 {
24844   struct comp_unit_head cu_header_local;
24845   const struct comp_unit_head *cu_headerp;
24846
24847   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24848
24849   if (cu_headerp->version == 2)
24850     return cu_headerp->addr_size;
24851   else
24852     return cu_headerp->offset_size;
24853 }
24854
24855 /* Return the text offset of the CU.  The returned offset comes from
24856    this CU's objfile.  If this objfile came from a separate debuginfo
24857    file, then the offset may be different from the corresponding
24858    offset in the parent objfile.  */
24859
24860 CORE_ADDR
24861 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24862 {
24863   return per_cu->dwarf2_per_objfile->objfile->text_section_offset ();
24864 }
24865
24866 /* Return a type that is a generic pointer type, the size of which matches
24867    the address size given in the compilation unit header for PER_CU.  */
24868 static struct type *
24869 dwarf2_per_cu_addr_type (struct dwarf2_per_cu_data *per_cu)
24870 {
24871   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24872   struct type *void_type = objfile_type (objfile)->builtin_void;
24873   struct type *addr_type = lookup_pointer_type (void_type);
24874   int addr_size = dwarf2_per_cu_addr_size (per_cu);
24875
24876   if (TYPE_LENGTH (addr_type) == addr_size)
24877     return addr_type;
24878
24879   addr_type
24880     = dwarf2_per_cu_addr_sized_int_type (per_cu, TYPE_UNSIGNED (addr_type));
24881   return addr_type;
24882 }
24883
24884 /* Return DWARF version number of PER_CU.  */
24885
24886 short
24887 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24888 {
24889   return per_cu->dwarf_version;
24890 }
24891
24892 /* Locate the .debug_info compilation unit from CU's objfile which contains
24893    the DIE at OFFSET.  Raises an error on failure.  */
24894
24895 static struct dwarf2_per_cu_data *
24896 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24897                                   unsigned int offset_in_dwz,
24898                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24899 {
24900   struct dwarf2_per_cu_data *this_cu;
24901   int low, high;
24902
24903   low = 0;
24904   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24905   while (high > low)
24906     {
24907       struct dwarf2_per_cu_data *mid_cu;
24908       int mid = low + (high - low) / 2;
24909
24910       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24911       if (mid_cu->is_dwz > offset_in_dwz
24912           || (mid_cu->is_dwz == offset_in_dwz
24913               && mid_cu->sect_off + mid_cu->length >= sect_off))
24914         high = mid;
24915       else
24916         low = mid + 1;
24917     }
24918   gdb_assert (low == high);
24919   this_cu = dwarf2_per_objfile->all_comp_units[low];
24920   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
24921     {
24922       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24923         error (_("Dwarf Error: could not find partial DIE containing "
24924                "offset %s [in module %s]"),
24925                sect_offset_str (sect_off),
24926                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24927
24928       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24929                   <= sect_off);
24930       return dwarf2_per_objfile->all_comp_units[low-1];
24931     }
24932   else
24933     {
24934       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24935           && sect_off >= this_cu->sect_off + this_cu->length)
24936         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24937       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24938       return this_cu;
24939     }
24940 }
24941
24942 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24943
24944 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24945   : per_cu (per_cu_),
24946     mark (false),
24947     has_loclist (false),
24948     checked_producer (false),
24949     producer_is_gxx_lt_4_6 (false),
24950     producer_is_gcc_lt_4_3 (false),
24951     producer_is_icc (false),
24952     producer_is_icc_lt_14 (false),
24953     producer_is_codewarrior (false),
24954     processing_has_namespace_info (false)
24955 {
24956   per_cu->cu = this;
24957 }
24958
24959 /* Destroy a dwarf2_cu.  */
24960
24961 dwarf2_cu::~dwarf2_cu ()
24962 {
24963   per_cu->cu = NULL;
24964 }
24965
24966 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24967
24968 static void
24969 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24970                        enum language pretend_language)
24971 {
24972   struct attribute *attr;
24973
24974   /* Set the language we're debugging.  */
24975   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24976   if (attr != nullptr)
24977     set_cu_language (DW_UNSND (attr), cu);
24978   else
24979     {
24980       cu->language = pretend_language;
24981       cu->language_defn = language_def (cu->language);
24982     }
24983
24984   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24985 }
24986
24987 /* Increase the age counter on each cached compilation unit, and free
24988    any that are too old.  */
24989
24990 static void
24991 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
24992 {
24993   struct dwarf2_per_cu_data *per_cu, **last_chain;
24994
24995   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24996   per_cu = dwarf2_per_objfile->read_in_chain;
24997   while (per_cu != NULL)
24998     {
24999       per_cu->cu->last_used ++;
25000       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25001         dwarf2_mark (per_cu->cu);
25002       per_cu = per_cu->cu->read_in_chain;
25003     }
25004
25005   per_cu = dwarf2_per_objfile->read_in_chain;
25006   last_chain = &dwarf2_per_objfile->read_in_chain;
25007   while (per_cu != NULL)
25008     {
25009       struct dwarf2_per_cu_data *next_cu;
25010
25011       next_cu = per_cu->cu->read_in_chain;
25012
25013       if (!per_cu->cu->mark)
25014         {
25015           delete per_cu->cu;
25016           *last_chain = next_cu;
25017         }
25018       else
25019         last_chain = &per_cu->cu->read_in_chain;
25020
25021       per_cu = next_cu;
25022     }
25023 }
25024
25025 /* Remove a single compilation unit from the cache.  */
25026
25027 static void
25028 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25029 {
25030   struct dwarf2_per_cu_data *per_cu, **last_chain;
25031   struct dwarf2_per_objfile *dwarf2_per_objfile
25032     = target_per_cu->dwarf2_per_objfile;
25033
25034   per_cu = dwarf2_per_objfile->read_in_chain;
25035   last_chain = &dwarf2_per_objfile->read_in_chain;
25036   while (per_cu != NULL)
25037     {
25038       struct dwarf2_per_cu_data *next_cu;
25039
25040       next_cu = per_cu->cu->read_in_chain;
25041
25042       if (per_cu == target_per_cu)
25043         {
25044           delete per_cu->cu;
25045           per_cu->cu = NULL;
25046           *last_chain = next_cu;
25047           break;
25048         }
25049       else
25050         last_chain = &per_cu->cu->read_in_chain;
25051
25052       per_cu = next_cu;
25053     }
25054 }
25055
25056 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25057    We store these in a hash table separate from the DIEs, and preserve them
25058    when the DIEs are flushed out of cache.
25059
25060    The CU "per_cu" pointer is needed because offset alone is not enough to
25061    uniquely identify the type.  A file may have multiple .debug_types sections,
25062    or the type may come from a DWO file.  Furthermore, while it's more logical
25063    to use per_cu->section+offset, with Fission the section with the data is in
25064    the DWO file but we don't know that section at the point we need it.
25065    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25066    because we can enter the lookup routine, get_die_type_at_offset, from
25067    outside this file, and thus won't necessarily have PER_CU->cu.
25068    Fortunately, PER_CU is stable for the life of the objfile.  */
25069
25070 struct dwarf2_per_cu_offset_and_type
25071 {
25072   const struct dwarf2_per_cu_data *per_cu;
25073   sect_offset sect_off;
25074   struct type *type;
25075 };
25076
25077 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25078
25079 static hashval_t
25080 per_cu_offset_and_type_hash (const void *item)
25081 {
25082   const struct dwarf2_per_cu_offset_and_type *ofs
25083     = (const struct dwarf2_per_cu_offset_and_type *) item;
25084
25085   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25086 }
25087
25088 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25089
25090 static int
25091 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25092 {
25093   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25094     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25095   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25096     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25097
25098   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25099           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25100 }
25101
25102 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25103    table if necessary.  For convenience, return TYPE.
25104
25105    The DIEs reading must have careful ordering to:
25106     * Not cause infinite loops trying to read in DIEs as a prerequisite for
25107       reading current DIE.
25108     * Not trying to dereference contents of still incompletely read in types
25109       while reading in other DIEs.
25110     * Enable referencing still incompletely read in types just by a pointer to
25111       the type without accessing its fields.
25112
25113    Therefore caller should follow these rules:
25114      * Try to fetch any prerequisite types we may need to build this DIE type
25115        before building the type and calling set_die_type.
25116      * After building type call set_die_type for current DIE as soon as
25117        possible before fetching more types to complete the current type.
25118      * Make the type as complete as possible before fetching more types.  */
25119
25120 static struct type *
25121 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25122 {
25123   struct dwarf2_per_objfile *dwarf2_per_objfile
25124     = cu->per_cu->dwarf2_per_objfile;
25125   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25126   struct objfile *objfile = dwarf2_per_objfile->objfile;
25127   struct attribute *attr;
25128   struct dynamic_prop prop;
25129
25130   /* For Ada types, make sure that the gnat-specific data is always
25131      initialized (if not already set).  There are a few types where
25132      we should not be doing so, because the type-specific area is
25133      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25134      where the type-specific area is used to store the floatformat).
25135      But this is not a problem, because the gnat-specific information
25136      is actually not needed for these types.  */
25137   if (need_gnat_info (cu)
25138       && TYPE_CODE (type) != TYPE_CODE_FUNC
25139       && TYPE_CODE (type) != TYPE_CODE_FLT
25140       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25141       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25142       && TYPE_CODE (type) != TYPE_CODE_METHOD
25143       && !HAVE_GNAT_AUX_INFO (type))
25144     INIT_GNAT_SPECIFIC (type);
25145
25146   /* Read DW_AT_allocated and set in type.  */
25147   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25148   if (attr != NULL && attr->form_is_block ())
25149     {
25150       struct type *prop_type
25151         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
25152       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
25153         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25154     }
25155   else if (attr != NULL)
25156     {
25157       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25158                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25159                  sect_offset_str (die->sect_off));
25160     }
25161
25162   /* Read DW_AT_associated and set in type.  */
25163   attr = dwarf2_attr (die, DW_AT_associated, cu);
25164   if (attr != NULL && attr->form_is_block ())
25165     {
25166       struct type *prop_type
25167         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
25168       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
25169         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25170     }
25171   else if (attr != NULL)
25172     {
25173       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25174                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25175                  sect_offset_str (die->sect_off));
25176     }
25177
25178   /* Read DW_AT_data_location and set in type.  */
25179   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25180   if (attr_to_dynamic_prop (attr, die, cu, &prop,
25181                             dwarf2_per_cu_addr_type (cu->per_cu)))
25182     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25183
25184   if (dwarf2_per_objfile->die_type_hash == NULL)
25185     dwarf2_per_objfile->die_type_hash
25186       = htab_up (htab_create_alloc (127,
25187                                     per_cu_offset_and_type_hash,
25188                                     per_cu_offset_and_type_eq,
25189                                     NULL, xcalloc, xfree));
25190
25191   ofs.per_cu = cu->per_cu;
25192   ofs.sect_off = die->sect_off;
25193   ofs.type = type;
25194   slot = (struct dwarf2_per_cu_offset_and_type **)
25195     htab_find_slot (dwarf2_per_objfile->die_type_hash.get (), &ofs, INSERT);
25196   if (*slot)
25197     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25198                sect_offset_str (die->sect_off));
25199   *slot = XOBNEW (&objfile->objfile_obstack,
25200                   struct dwarf2_per_cu_offset_and_type);
25201   **slot = ofs;
25202   return type;
25203 }
25204
25205 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25206    or return NULL if the die does not have a saved type.  */
25207
25208 static struct type *
25209 get_die_type_at_offset (sect_offset sect_off,
25210                         struct dwarf2_per_cu_data *per_cu)
25211 {
25212   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25213   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25214
25215   if (dwarf2_per_objfile->die_type_hash == NULL)
25216     return NULL;
25217
25218   ofs.per_cu = per_cu;
25219   ofs.sect_off = sect_off;
25220   slot = ((struct dwarf2_per_cu_offset_and_type *)
25221           htab_find (dwarf2_per_objfile->die_type_hash.get (), &ofs));
25222   if (slot)
25223     return slot->type;
25224   else
25225     return NULL;
25226 }
25227
25228 /* Look up the type for DIE in CU in die_type_hash,
25229    or return NULL if DIE does not have a saved type.  */
25230
25231 static struct type *
25232 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25233 {
25234   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25235 }
25236
25237 /* Add a dependence relationship from CU to REF_PER_CU.  */
25238
25239 static void
25240 dwarf2_add_dependence (struct dwarf2_cu *cu,
25241                        struct dwarf2_per_cu_data *ref_per_cu)
25242 {
25243   void **slot;
25244
25245   if (cu->dependencies == NULL)
25246     cu->dependencies
25247       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25248                               NULL, &cu->comp_unit_obstack,
25249                               hashtab_obstack_allocate,
25250                               dummy_obstack_deallocate);
25251
25252   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25253   if (*slot == NULL)
25254     *slot = ref_per_cu;
25255 }
25256
25257 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25258    Set the mark field in every compilation unit in the
25259    cache that we must keep because we are keeping CU.  */
25260
25261 static int
25262 dwarf2_mark_helper (void **slot, void *data)
25263 {
25264   struct dwarf2_per_cu_data *per_cu;
25265
25266   per_cu = (struct dwarf2_per_cu_data *) *slot;
25267
25268   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25269      reading of the chain.  As such dependencies remain valid it is not much
25270      useful to track and undo them during QUIT cleanups.  */
25271   if (per_cu->cu == NULL)
25272     return 1;
25273
25274   if (per_cu->cu->mark)
25275     return 1;
25276   per_cu->cu->mark = true;
25277
25278   if (per_cu->cu->dependencies != NULL)
25279     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25280
25281   return 1;
25282 }
25283
25284 /* Set the mark field in CU and in every other compilation unit in the
25285    cache that we must keep because we are keeping CU.  */
25286
25287 static void
25288 dwarf2_mark (struct dwarf2_cu *cu)
25289 {
25290   if (cu->mark)
25291     return;
25292   cu->mark = true;
25293   if (cu->dependencies != NULL)
25294     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25295 }
25296
25297 static void
25298 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25299 {
25300   while (per_cu)
25301     {
25302       per_cu->cu->mark = false;
25303       per_cu = per_cu->cu->read_in_chain;
25304     }
25305 }
25306
25307 /* Trivial hash function for partial_die_info: the hash value of a DIE
25308    is its offset in .debug_info for this objfile.  */
25309
25310 static hashval_t
25311 partial_die_hash (const void *item)
25312 {
25313   const struct partial_die_info *part_die
25314     = (const struct partial_die_info *) item;
25315
25316   return to_underlying (part_die->sect_off);
25317 }
25318
25319 /* Trivial comparison function for partial_die_info structures: two DIEs
25320    are equal if they have the same offset.  */
25321
25322 static int
25323 partial_die_eq (const void *item_lhs, const void *item_rhs)
25324 {
25325   const struct partial_die_info *part_die_lhs
25326     = (const struct partial_die_info *) item_lhs;
25327   const struct partial_die_info *part_die_rhs
25328     = (const struct partial_die_info *) item_rhs;
25329
25330   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25331 }
25332
25333 struct cmd_list_element *set_dwarf_cmdlist;
25334 struct cmd_list_element *show_dwarf_cmdlist;
25335
25336 static void
25337 set_dwarf_cmd (const char *args, int from_tty)
25338 {
25339   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25340              gdb_stdout);
25341 }
25342
25343 static void
25344 show_dwarf_cmd (const char *args, int from_tty)
25345 {
25346   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25347 }
25348
25349 static void
25350 show_check_physname (struct ui_file *file, int from_tty,
25351                      struct cmd_list_element *c, const char *value)
25352 {
25353   fprintf_filtered (file,
25354                     _("Whether to check \"physname\" is %s.\n"),
25355                     value);
25356 }
25357
25358 void _initialize_dwarf2_read ();
25359 void
25360 _initialize_dwarf2_read ()
25361 {
25362   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25363 Set DWARF specific variables.\n\
25364 Configure DWARF variables such as the cache size."),
25365                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25366                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25367
25368   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25369 Show DWARF specific variables.\n\
25370 Show DWARF variables such as the cache size."),
25371                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25372                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25373
25374   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25375                             &dwarf_max_cache_age, _("\
25376 Set the upper bound on the age of cached DWARF compilation units."), _("\
25377 Show the upper bound on the age of cached DWARF compilation units."), _("\
25378 A higher limit means that cached compilation units will be stored\n\
25379 in memory longer, and more total memory will be used.  Zero disables\n\
25380 caching, which can slow down startup."),
25381                             NULL,
25382                             show_dwarf_max_cache_age,
25383                             &set_dwarf_cmdlist,
25384                             &show_dwarf_cmdlist);
25385
25386   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25387 Set debugging of the DWARF reader."), _("\
25388 Show debugging of the DWARF reader."), _("\
25389 When enabled (non-zero), debugging messages are printed during DWARF\n\
25390 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25391 information.  A value greater than 1 provides more verbose information."),
25392                             NULL,
25393                             NULL,
25394                             &setdebuglist, &showdebuglist);
25395
25396   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25397 Set debugging of the DWARF DIE reader."), _("\
25398 Show debugging of the DWARF DIE reader."), _("\
25399 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25400 The value is the maximum depth to print."),
25401                              NULL,
25402                              NULL,
25403                              &setdebuglist, &showdebuglist);
25404
25405   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25406 Set debugging of the dwarf line reader."), _("\
25407 Show debugging of the dwarf line reader."), _("\
25408 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25409 A value of 1 (one) provides basic information.\n\
25410 A value greater than 1 provides more verbose information."),
25411                              NULL,
25412                              NULL,
25413                              &setdebuglist, &showdebuglist);
25414
25415   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25416 Set cross-checking of \"physname\" code against demangler."), _("\
25417 Show cross-checking of \"physname\" code against demangler."), _("\
25418 When enabled, GDB's internal \"physname\" code is checked against\n\
25419 the demangler."),
25420                            NULL, show_check_physname,
25421                            &setdebuglist, &showdebuglist);
25422
25423   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25424                            no_class, &use_deprecated_index_sections, _("\
25425 Set whether to use deprecated gdb_index sections."), _("\
25426 Show whether to use deprecated gdb_index sections."), _("\
25427 When enabled, deprecated .gdb_index sections are used anyway.\n\
25428 Normally they are ignored either because of a missing feature or\n\
25429 performance issue.\n\
25430 Warning: This option must be enabled before gdb reads the file."),
25431                            NULL,
25432                            NULL,
25433                            &setlist, &showlist);
25434
25435   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25436                                                         &dwarf2_locexpr_funcs);
25437   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25438                                                         &dwarf2_loclist_funcs);
25439
25440   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25441                                         &dwarf2_block_frame_base_locexpr_funcs);
25442   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25443                                         &dwarf2_block_frame_base_loclist_funcs);
25444
25445 #if GDB_SELF_TEST
25446   selftests::register_test ("dw2_expand_symtabs_matching",
25447                             selftests::dw2_expand_symtabs_matching::run_test);
25448 #endif
25449 }
This page took 1.432935 seconds and 4 git commands to generate.