]> Git Repo - binutils.git/blob - gdb/dwarf2/read.c
Change dwarf2_per_objfile::quick_file_names_table to htab_up
[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  private:
1078   /* The include_directories table.  Note these are observing
1079      pointers.  The memory is owned by debug_line_buffer.  */
1080   std::vector<const char *> m_include_dirs;
1081
1082   /* The file_names table. This is private because the meaning of indexes
1083      differs among DWARF versions (The first valid index is 1 in DWARF 4 and
1084      before, and is 0 in DWARF 5 and later).  So the client should use
1085      file_name_at method for access.  */
1086   std::vector<file_entry> m_file_names;
1087 };
1088
1089 typedef std::unique_ptr<line_header> line_header_up;
1090
1091 const char *
1092 file_entry::include_dir (const line_header *lh) const
1093 {
1094   return lh->include_dir_at (d_index);
1095 }
1096
1097 /* When we construct a partial symbol table entry we only
1098    need this much information.  */
1099 struct partial_die_info : public allocate_on_obstack
1100   {
1101     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1102
1103     /* Disable assign but still keep copy ctor, which is needed
1104        load_partial_dies.   */
1105     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1106
1107     /* Adjust the partial die before generating a symbol for it.  This
1108        function may set the is_external flag or change the DIE's
1109        name.  */
1110     void fixup (struct dwarf2_cu *cu);
1111
1112     /* Read a minimal amount of information into the minimal die
1113        structure.  */
1114     const gdb_byte *read (const struct die_reader_specs *reader,
1115                           const struct abbrev_info &abbrev,
1116                           const gdb_byte *info_ptr);
1117
1118     /* Offset of this DIE.  */
1119     const sect_offset sect_off;
1120
1121     /* DWARF-2 tag for this DIE.  */
1122     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1123
1124     /* Assorted flags describing the data found in this DIE.  */
1125     const unsigned int has_children : 1;
1126
1127     unsigned int is_external : 1;
1128     unsigned int is_declaration : 1;
1129     unsigned int has_type : 1;
1130     unsigned int has_specification : 1;
1131     unsigned int has_pc_info : 1;
1132     unsigned int may_be_inlined : 1;
1133
1134     /* This DIE has been marked DW_AT_main_subprogram.  */
1135     unsigned int main_subprogram : 1;
1136
1137     /* Flag set if the SCOPE field of this structure has been
1138        computed.  */
1139     unsigned int scope_set : 1;
1140
1141     /* Flag set if the DIE has a byte_size attribute.  */
1142     unsigned int has_byte_size : 1;
1143
1144     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1145     unsigned int has_const_value : 1;
1146
1147     /* Flag set if any of the DIE's children are template arguments.  */
1148     unsigned int has_template_arguments : 1;
1149
1150     /* Flag set if fixup has been called on this die.  */
1151     unsigned int fixup_called : 1;
1152
1153     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1154     unsigned int is_dwz : 1;
1155
1156     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1157     unsigned int spec_is_dwz : 1;
1158
1159     /* The name of this DIE.  Normally the value of DW_AT_name, but
1160        sometimes a default name for unnamed DIEs.  */
1161     const char *name = nullptr;
1162
1163     /* The linkage name, if present.  */
1164     const char *linkage_name = nullptr;
1165
1166     /* The scope to prepend to our children.  This is generally
1167        allocated on the comp_unit_obstack, so will disappear
1168        when this compilation unit leaves the cache.  */
1169     const char *scope = nullptr;
1170
1171     /* Some data associated with the partial DIE.  The tag determines
1172        which field is live.  */
1173     union
1174     {
1175       /* The location description associated with this DIE, if any.  */
1176       struct dwarf_block *locdesc;
1177       /* The offset of an import, for DW_TAG_imported_unit.  */
1178       sect_offset sect_off;
1179     } d {};
1180
1181     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1182     CORE_ADDR lowpc = 0;
1183     CORE_ADDR highpc = 0;
1184
1185     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1186        DW_AT_sibling, if any.  */
1187     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1188        could return DW_AT_sibling values to its caller load_partial_dies.  */
1189     const gdb_byte *sibling = nullptr;
1190
1191     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1192        DW_AT_specification (or DW_AT_abstract_origin or
1193        DW_AT_extension).  */
1194     sect_offset spec_offset {};
1195
1196     /* Pointers to this DIE's parent, first child, and next sibling,
1197        if any.  */
1198     struct partial_die_info *die_parent = nullptr;
1199     struct partial_die_info *die_child = nullptr;
1200     struct partial_die_info *die_sibling = nullptr;
1201
1202     friend struct partial_die_info *
1203     dwarf2_cu::find_partial_die (sect_offset sect_off);
1204
1205   private:
1206     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1207     partial_die_info (sect_offset sect_off)
1208       : partial_die_info (sect_off, DW_TAG_padding, 0)
1209     {
1210     }
1211
1212     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1213                       int has_children_)
1214       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1215     {
1216       is_external = 0;
1217       is_declaration = 0;
1218       has_type = 0;
1219       has_specification = 0;
1220       has_pc_info = 0;
1221       may_be_inlined = 0;
1222       main_subprogram = 0;
1223       scope_set = 0;
1224       has_byte_size = 0;
1225       has_const_value = 0;
1226       has_template_arguments = 0;
1227       fixup_called = 0;
1228       is_dwz = 0;
1229       spec_is_dwz = 0;
1230     }
1231   };
1232
1233 /* This data structure holds a complete die structure.  */
1234 struct die_info
1235   {
1236     /* DWARF-2 tag for this DIE.  */
1237     ENUM_BITFIELD(dwarf_tag) tag : 16;
1238
1239     /* Number of attributes */
1240     unsigned char num_attrs;
1241
1242     /* True if we're presently building the full type name for the
1243        type derived from this DIE.  */
1244     unsigned char building_fullname : 1;
1245
1246     /* True if this die is in process.  PR 16581.  */
1247     unsigned char in_process : 1;
1248
1249     /* True if this DIE has children.  */
1250     unsigned char has_children : 1;
1251
1252     /* Abbrev number */
1253     unsigned int abbrev;
1254
1255     /* Offset in .debug_info or .debug_types section.  */
1256     sect_offset sect_off;
1257
1258     /* The dies in a compilation unit form an n-ary tree.  PARENT
1259        points to this die's parent; CHILD points to the first child of
1260        this node; and all the children of a given node are chained
1261        together via their SIBLING fields.  */
1262     struct die_info *child;     /* Its first child, if any.  */
1263     struct die_info *sibling;   /* Its next sibling, if any.  */
1264     struct die_info *parent;    /* Its parent, if any.  */
1265
1266     /* An array of attributes, with NUM_ATTRS elements.  There may be
1267        zero, but it's not common and zero-sized arrays are not
1268        sufficiently portable C.  */
1269     struct attribute attrs[1];
1270   };
1271
1272 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1273    but this would require a corresponding change in unpack_field_as_long
1274    and friends.  */
1275 static int bits_per_byte = 8;
1276
1277 /* When reading a variant or variant part, we track a bit more
1278    information about the field, and store it in an object of this
1279    type.  */
1280
1281 struct variant_field
1282 {
1283   /* If we see a DW_TAG_variant, then this will be the discriminant
1284      value.  */
1285   ULONGEST discriminant_value;
1286   /* If we see a DW_TAG_variant, then this will be set if this is the
1287      default branch.  */
1288   bool default_branch;
1289   /* While reading a DW_TAG_variant_part, this will be set if this
1290      field is the discriminant.  */
1291   bool is_discriminant;
1292 };
1293
1294 struct nextfield
1295 {
1296   int accessibility = 0;
1297   int virtuality = 0;
1298   /* Extra information to describe a variant or variant part.  */
1299   struct variant_field variant {};
1300   struct field field {};
1301 };
1302
1303 struct fnfieldlist
1304 {
1305   const char *name = nullptr;
1306   std::vector<struct fn_field> fnfields;
1307 };
1308
1309 /* The routines that read and process dies for a C struct or C++ class
1310    pass lists of data member fields and lists of member function fields
1311    in an instance of a field_info structure, as defined below.  */
1312 struct field_info
1313   {
1314     /* List of data member and baseclasses fields.  */
1315     std::vector<struct nextfield> fields;
1316     std::vector<struct nextfield> baseclasses;
1317
1318     /* Number of fields (including baseclasses).  */
1319     int nfields = 0;
1320
1321     /* Set if the accessibility of one of the fields is not public.  */
1322     int non_public_fields = 0;
1323
1324     /* Member function fieldlist array, contains name of possibly overloaded
1325        member function, number of overloaded member functions and a pointer
1326        to the head of the member function field chain.  */
1327     std::vector<struct fnfieldlist> fnfieldlists;
1328
1329     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1330        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1331     std::vector<struct decl_field> typedef_field_list;
1332
1333     /* Nested types defined by this class and the number of elements in this
1334        list.  */
1335     std::vector<struct decl_field> nested_types_list;
1336   };
1337
1338 /* Loaded secondary compilation units are kept in memory until they
1339    have not been referenced for the processing of this many
1340    compilation units.  Set this to zero to disable caching.  Cache
1341    sizes of up to at least twenty will improve startup time for
1342    typical inter-CU-reference binaries, at an obvious memory cost.  */
1343 static int dwarf_max_cache_age = 5;
1344 static void
1345 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1346                           struct cmd_list_element *c, const char *value)
1347 {
1348   fprintf_filtered (file, _("The upper bound on the age of cached "
1349                             "DWARF compilation units is %s.\n"),
1350                     value);
1351 }
1352 \f
1353 /* local function prototypes */
1354
1355 static void dwarf2_find_base_address (struct die_info *die,
1356                                       struct dwarf2_cu *cu);
1357
1358 static dwarf2_psymtab *create_partial_symtab
1359   (struct dwarf2_per_cu_data *per_cu, const char *name);
1360
1361 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1362                                         const gdb_byte *info_ptr,
1363                                         struct die_info *type_unit_die);
1364
1365 static void dwarf2_build_psymtabs_hard
1366   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1367
1368 static void scan_partial_symbols (struct partial_die_info *,
1369                                   CORE_ADDR *, CORE_ADDR *,
1370                                   int, struct dwarf2_cu *);
1371
1372 static void add_partial_symbol (struct partial_die_info *,
1373                                 struct dwarf2_cu *);
1374
1375 static void add_partial_namespace (struct partial_die_info *pdi,
1376                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1377                                    int set_addrmap, struct dwarf2_cu *cu);
1378
1379 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1380                                 CORE_ADDR *highpc, int set_addrmap,
1381                                 struct dwarf2_cu *cu);
1382
1383 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1384                                      struct dwarf2_cu *cu);
1385
1386 static void add_partial_subprogram (struct partial_die_info *pdi,
1387                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1388                                     int need_pc, struct dwarf2_cu *cu);
1389
1390 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1391
1392 static struct partial_die_info *load_partial_dies
1393   (const struct die_reader_specs *, const gdb_byte *, int);
1394
1395 /* A pair of partial_die_info and compilation unit.  */
1396 struct cu_partial_die_info
1397 {
1398   /* The compilation unit of the partial_die_info.  */
1399   struct dwarf2_cu *cu;
1400   /* A partial_die_info.  */
1401   struct partial_die_info *pdi;
1402
1403   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1404     : cu (cu),
1405       pdi (pdi)
1406   { /* Nothing.  */ }
1407
1408 private:
1409   cu_partial_die_info () = delete;
1410 };
1411
1412 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1413                                                           struct dwarf2_cu *);
1414
1415 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1416                                        struct attribute *, struct attr_abbrev *,
1417                                        const gdb_byte *, bool *need_reprocess);
1418
1419 static void read_attribute_reprocess (const struct die_reader_specs *reader,
1420                                       struct attribute *attr);
1421
1422 static CORE_ADDR read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index);
1423
1424 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1425                                unsigned int *);
1426
1427 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1428
1429 static LONGEST read_checked_initial_length_and_offset
1430   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1431    unsigned int *, unsigned int *);
1432
1433 static LONGEST read_offset (bfd *, const gdb_byte *,
1434                             const struct comp_unit_head *,
1435                             unsigned int *);
1436
1437 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1438
1439 static sect_offset read_abbrev_offset
1440   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1441    struct dwarf2_section_info *, sect_offset);
1442
1443 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1444
1445 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1446
1447 static const char *read_indirect_string
1448   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1449    const struct comp_unit_head *, unsigned int *);
1450
1451 static const char *read_indirect_line_string
1452   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1453    const struct comp_unit_head *, unsigned int *);
1454
1455 static const char *read_indirect_string_at_offset
1456   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1457    LONGEST str_offset);
1458
1459 static const char *read_indirect_string_from_dwz
1460   (struct objfile *objfile, struct dwz_file *, LONGEST);
1461
1462 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1463                                               const gdb_byte *,
1464                                               unsigned int *);
1465
1466 static const char *read_dwo_str_index (const struct die_reader_specs *reader,
1467                                        ULONGEST str_index);
1468
1469 static const char *read_stub_str_index (struct dwarf2_cu *cu,
1470                                         ULONGEST str_index);
1471
1472 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1473
1474 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1475                                       struct dwarf2_cu *);
1476
1477 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1478                                                 unsigned int);
1479
1480 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1481                                        struct dwarf2_cu *cu);
1482
1483 static const char *dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu);
1484
1485 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1486                                struct dwarf2_cu *cu);
1487
1488 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1489
1490 static struct die_info *die_specification (struct die_info *die,
1491                                            struct dwarf2_cu **);
1492
1493 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1494                                                 struct dwarf2_cu *cu);
1495
1496 static void dwarf_decode_lines (struct line_header *, const char *,
1497                                 struct dwarf2_cu *, dwarf2_psymtab *,
1498                                 CORE_ADDR, int decode_mapping);
1499
1500 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1501                                   const char *);
1502
1503 static struct symbol *new_symbol (struct die_info *, struct type *,
1504                                   struct dwarf2_cu *, struct symbol * = NULL);
1505
1506 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1507                                 struct dwarf2_cu *);
1508
1509 static void dwarf2_const_value_attr (const struct attribute *attr,
1510                                      struct type *type,
1511                                      const char *name,
1512                                      struct obstack *obstack,
1513                                      struct dwarf2_cu *cu, LONGEST *value,
1514                                      const gdb_byte **bytes,
1515                                      struct dwarf2_locexpr_baton **baton);
1516
1517 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1518
1519 static int need_gnat_info (struct dwarf2_cu *);
1520
1521 static struct type *die_descriptive_type (struct die_info *,
1522                                           struct dwarf2_cu *);
1523
1524 static void set_descriptive_type (struct type *, struct die_info *,
1525                                   struct dwarf2_cu *);
1526
1527 static struct type *die_containing_type (struct die_info *,
1528                                          struct dwarf2_cu *);
1529
1530 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1531                                      struct dwarf2_cu *);
1532
1533 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1534
1535 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1536
1537 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1538
1539 static char *typename_concat (struct obstack *obs, const char *prefix,
1540                               const char *suffix, int physname,
1541                               struct dwarf2_cu *cu);
1542
1543 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1544
1545 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1546
1547 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1548
1549 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1550
1551 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1552
1553 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1554
1555 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1556                                struct dwarf2_cu *, dwarf2_psymtab *);
1557
1558 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1559    values.  Keep the items ordered with increasing constraints compliance.  */
1560 enum pc_bounds_kind
1561 {
1562   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1563   PC_BOUNDS_NOT_PRESENT,
1564
1565   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1566      were present but they do not form a valid range of PC addresses.  */
1567   PC_BOUNDS_INVALID,
1568
1569   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1570   PC_BOUNDS_RANGES,
1571
1572   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1573   PC_BOUNDS_HIGH_LOW,
1574 };
1575
1576 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1577                                                  CORE_ADDR *, CORE_ADDR *,
1578                                                  struct dwarf2_cu *,
1579                                                  dwarf2_psymtab *);
1580
1581 static void get_scope_pc_bounds (struct die_info *,
1582                                  CORE_ADDR *, CORE_ADDR *,
1583                                  struct dwarf2_cu *);
1584
1585 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1586                                         CORE_ADDR, struct dwarf2_cu *);
1587
1588 static void dwarf2_add_field (struct field_info *, struct die_info *,
1589                               struct dwarf2_cu *);
1590
1591 static void dwarf2_attach_fields_to_type (struct field_info *,
1592                                           struct type *, struct dwarf2_cu *);
1593
1594 static void dwarf2_add_member_fn (struct field_info *,
1595                                   struct die_info *, struct type *,
1596                                   struct dwarf2_cu *);
1597
1598 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1599                                              struct type *,
1600                                              struct dwarf2_cu *);
1601
1602 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1603
1604 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1605
1606 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1607
1608 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1609
1610 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1611
1612 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1613
1614 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1615
1616 static struct type *read_module_type (struct die_info *die,
1617                                       struct dwarf2_cu *cu);
1618
1619 static const char *namespace_name (struct die_info *die,
1620                                    int *is_anonymous, struct dwarf2_cu *);
1621
1622 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1623
1624 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1625
1626 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1627                                                        struct dwarf2_cu *);
1628
1629 static struct die_info *read_die_and_siblings_1
1630   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1631    struct die_info *);
1632
1633 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1634                                                const gdb_byte *info_ptr,
1635                                                const gdb_byte **new_info_ptr,
1636                                                struct die_info *parent);
1637
1638 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1639                                         struct die_info **, const gdb_byte *,
1640                                         int);
1641
1642 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1643                                       struct die_info **, const gdb_byte *);
1644
1645 static void process_die (struct die_info *, struct dwarf2_cu *);
1646
1647 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1648                                              struct obstack *);
1649
1650 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1651
1652 static const char *dwarf2_full_name (const char *name,
1653                                      struct die_info *die,
1654                                      struct dwarf2_cu *cu);
1655
1656 static const char *dwarf2_physname (const char *name, struct die_info *die,
1657                                     struct dwarf2_cu *cu);
1658
1659 static struct die_info *dwarf2_extension (struct die_info *die,
1660                                           struct dwarf2_cu **);
1661
1662 static const char *dwarf_tag_name (unsigned int);
1663
1664 static const char *dwarf_attr_name (unsigned int);
1665
1666 static const char *dwarf_unit_type_name (int unit_type);
1667
1668 static const char *dwarf_form_name (unsigned int);
1669
1670 static const char *dwarf_bool_name (unsigned int);
1671
1672 static const char *dwarf_type_encoding_name (unsigned int);
1673
1674 static struct die_info *sibling_die (struct die_info *);
1675
1676 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1677
1678 static void dump_die_for_error (struct die_info *);
1679
1680 static void dump_die_1 (struct ui_file *, int level, int max_level,
1681                         struct die_info *);
1682
1683 /*static*/ void dump_die (struct die_info *, int max_level);
1684
1685 static void store_in_ref_table (struct die_info *,
1686                                 struct dwarf2_cu *);
1687
1688 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1689
1690 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1691
1692 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1693                                                const struct attribute *,
1694                                                struct dwarf2_cu **);
1695
1696 static struct die_info *follow_die_ref (struct die_info *,
1697                                         const struct attribute *,
1698                                         struct dwarf2_cu **);
1699
1700 static struct die_info *follow_die_sig (struct die_info *,
1701                                         const struct attribute *,
1702                                         struct dwarf2_cu **);
1703
1704 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1705                                          struct dwarf2_cu *);
1706
1707 static struct type *get_DW_AT_signature_type (struct die_info *,
1708                                               const struct attribute *,
1709                                               struct dwarf2_cu *);
1710
1711 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1712
1713 static void read_signatured_type (struct signatured_type *);
1714
1715 static int attr_to_dynamic_prop (const struct attribute *attr,
1716                                  struct die_info *die, struct dwarf2_cu *cu,
1717                                  struct dynamic_prop *prop, struct type *type);
1718
1719 /* memory allocation interface */
1720
1721 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1722
1723 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1724
1725 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1726
1727 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1728                                    struct dwarf2_loclist_baton *baton,
1729                                    const struct attribute *attr);
1730
1731 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1732                                          struct symbol *sym,
1733                                          struct dwarf2_cu *cu,
1734                                          int is_block);
1735
1736 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1737                                      const gdb_byte *info_ptr,
1738                                      struct abbrev_info *abbrev);
1739
1740 static hashval_t partial_die_hash (const void *item);
1741
1742 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1743
1744 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1745   (sect_offset sect_off, unsigned int offset_in_dwz,
1746    struct dwarf2_per_objfile *dwarf2_per_objfile);
1747
1748 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1749                                    struct die_info *comp_unit_die,
1750                                    enum language pretend_language);
1751
1752 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1753
1754 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1755
1756 static struct type *set_die_type (struct die_info *, struct type *,
1757                                   struct dwarf2_cu *);
1758
1759 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1760
1761 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1762
1763 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1764                                  enum language);
1765
1766 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1767                                     enum language);
1768
1769 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1770                                     enum language);
1771
1772 static void dwarf2_add_dependence (struct dwarf2_cu *,
1773                                    struct dwarf2_per_cu_data *);
1774
1775 static void dwarf2_mark (struct dwarf2_cu *);
1776
1777 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1778
1779 static struct type *get_die_type_at_offset (sect_offset,
1780                                             struct dwarf2_per_cu_data *);
1781
1782 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1783
1784 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1785                              enum language pretend_language);
1786
1787 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1788
1789 static struct type *dwarf2_per_cu_addr_type (struct dwarf2_per_cu_data *per_cu);
1790 static struct type *dwarf2_per_cu_addr_sized_int_type
1791         (struct dwarf2_per_cu_data *per_cu, bool unsigned_p);
1792 static struct type *dwarf2_per_cu_int_type
1793         (struct dwarf2_per_cu_data *per_cu, int size_in_bytes,
1794          bool unsigned_p);
1795
1796 /* Class, the destructor of which frees all allocated queue entries.  This
1797    will only have work to do if an error was thrown while processing the
1798    dwarf.  If no error was thrown then the queue entries should have all
1799    been processed, and freed, as we went along.  */
1800
1801 class dwarf2_queue_guard
1802 {
1803 public:
1804   explicit dwarf2_queue_guard (dwarf2_per_objfile *per_objfile)
1805     : m_per_objfile (per_objfile)
1806   {
1807   }
1808
1809   /* Free any entries remaining on the queue.  There should only be
1810      entries left if we hit an error while processing the dwarf.  */
1811   ~dwarf2_queue_guard ()
1812   {
1813     /* Ensure that no memory is allocated by the queue.  */
1814     std::queue<dwarf2_queue_item> empty;
1815     std::swap (m_per_objfile->queue, empty);
1816   }
1817
1818   DISABLE_COPY_AND_ASSIGN (dwarf2_queue_guard);
1819
1820 private:
1821   dwarf2_per_objfile *m_per_objfile;
1822 };
1823
1824 dwarf2_queue_item::~dwarf2_queue_item ()
1825 {
1826   /* Anything still marked queued is likely to be in an
1827      inconsistent state, so discard it.  */
1828   if (per_cu->queued)
1829     {
1830       if (per_cu->cu != NULL)
1831         free_one_cached_comp_unit (per_cu);
1832       per_cu->queued = 0;
1833     }
1834 }
1835
1836 /* The return type of find_file_and_directory.  Note, the enclosed
1837    string pointers are only valid while this object is valid.  */
1838
1839 struct file_and_directory
1840 {
1841   /* The filename.  This is never NULL.  */
1842   const char *name;
1843
1844   /* The compilation directory.  NULL if not known.  If we needed to
1845      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1846      points directly to the DW_AT_comp_dir string attribute owned by
1847      the obstack that owns the DIE.  */
1848   const char *comp_dir;
1849
1850   /* If we needed to build a new string for comp_dir, this is what
1851      owns the storage.  */
1852   std::string comp_dir_storage;
1853 };
1854
1855 static file_and_directory find_file_and_directory (struct die_info *die,
1856                                                    struct dwarf2_cu *cu);
1857
1858 static char *file_full_name (int file, struct line_header *lh,
1859                              const char *comp_dir);
1860
1861 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1862 enum class rcuh_kind { COMPILE, TYPE };
1863
1864 static const gdb_byte *read_and_check_comp_unit_head
1865   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1866    struct comp_unit_head *header,
1867    struct dwarf2_section_info *section,
1868    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1869    rcuh_kind section_kind);
1870
1871 static htab_up allocate_signatured_type_table (struct objfile *objfile);
1872
1873 static htab_up allocate_dwo_unit_table (struct objfile *objfile);
1874
1875 static struct dwo_unit *lookup_dwo_unit_in_dwp
1876   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1877    struct dwp_file *dwp_file, const char *comp_dir,
1878    ULONGEST signature, int is_debug_types);
1879
1880 static struct dwp_file *get_dwp_file
1881   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1882
1883 static struct dwo_unit *lookup_dwo_comp_unit
1884   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1885
1886 static struct dwo_unit *lookup_dwo_type_unit
1887   (struct signatured_type *, const char *, const char *);
1888
1889 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1890
1891 /* A unique pointer to a dwo_file.  */
1892
1893 typedef std::unique_ptr<struct dwo_file> dwo_file_up;
1894
1895 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1896
1897 static void check_producer (struct dwarf2_cu *cu);
1898
1899 static void free_line_header_voidp (void *arg);
1900 \f
1901 /* Various complaints about symbol reading that don't abort the process.  */
1902
1903 static void
1904 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1905 {
1906   complaint (_("statement list doesn't fit in .debug_line section"));
1907 }
1908
1909 static void
1910 dwarf2_debug_line_missing_file_complaint (void)
1911 {
1912   complaint (_(".debug_line section has line data without a file"));
1913 }
1914
1915 static void
1916 dwarf2_debug_line_missing_end_sequence_complaint (void)
1917 {
1918   complaint (_(".debug_line section has line "
1919                "program sequence without an end"));
1920 }
1921
1922 static void
1923 dwarf2_complex_location_expr_complaint (void)
1924 {
1925   complaint (_("location expression too complex"));
1926 }
1927
1928 static void
1929 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1930                                               int arg3)
1931 {
1932   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
1933              arg1, arg2, arg3);
1934 }
1935
1936 static void
1937 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1938 {
1939   complaint (_("debug info runs off end of %s section"
1940                " [in module %s]"),
1941              section->get_name (),
1942              section->get_file_name ());
1943 }
1944
1945 static void
1946 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1947 {
1948   complaint (_("macro debug info contains a "
1949                "malformed macro definition:\n`%s'"),
1950              arg1);
1951 }
1952
1953 static void
1954 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1955 {
1956   complaint (_("invalid attribute class or form for '%s' in '%s'"),
1957              arg1, arg2);
1958 }
1959
1960 /* Hash function for line_header_hash.  */
1961
1962 static hashval_t
1963 line_header_hash (const struct line_header *ofs)
1964 {
1965   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
1966 }
1967
1968 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
1969
1970 static hashval_t
1971 line_header_hash_voidp (const void *item)
1972 {
1973   const struct line_header *ofs = (const struct line_header *) item;
1974
1975   return line_header_hash (ofs);
1976 }
1977
1978 /* Equality function for line_header_hash.  */
1979
1980 static int
1981 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
1982 {
1983   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
1984   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
1985
1986   return (ofs_lhs->sect_off == ofs_rhs->sect_off
1987           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
1988 }
1989
1990 \f
1991
1992 /* See declaration.  */
1993
1994 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
1995                                         const dwarf2_debug_sections *names,
1996                                         bool can_copy_)
1997   : objfile (objfile_),
1998     can_copy (can_copy_)
1999 {
2000   if (names == NULL)
2001     names = &dwarf2_elf_names;
2002
2003   bfd *obfd = objfile->obfd;
2004
2005   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2006     locate_sections (obfd, sec, *names);
2007 }
2008
2009 dwarf2_per_objfile::~dwarf2_per_objfile ()
2010 {
2011   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2012   free_cached_comp_units ();
2013
2014   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2015     per_cu->imported_symtabs_free ();
2016
2017   for (signatured_type *sig_type : all_type_units)
2018     sig_type->per_cu.imported_symtabs_free ();
2019
2020   /* Everything else should be on the objfile obstack.  */
2021 }
2022
2023 /* See declaration.  */
2024
2025 void
2026 dwarf2_per_objfile::free_cached_comp_units ()
2027 {
2028   dwarf2_per_cu_data *per_cu = read_in_chain;
2029   dwarf2_per_cu_data **last_chain = &read_in_chain;
2030   while (per_cu != NULL)
2031     {
2032       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2033
2034       delete per_cu->cu;
2035       *last_chain = next_cu;
2036       per_cu = next_cu;
2037     }
2038 }
2039
2040 /* A helper class that calls free_cached_comp_units on
2041    destruction.  */
2042
2043 class free_cached_comp_units
2044 {
2045 public:
2046
2047   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2048     : m_per_objfile (per_objfile)
2049   {
2050   }
2051
2052   ~free_cached_comp_units ()
2053   {
2054     m_per_objfile->free_cached_comp_units ();
2055   }
2056
2057   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2058
2059 private:
2060
2061   dwarf2_per_objfile *m_per_objfile;
2062 };
2063
2064 /* Try to locate the sections we need for DWARF 2 debugging
2065    information and return true if we have enough to do something.
2066    NAMES points to the dwarf2 section names, or is NULL if the standard
2067    ELF names are used.  CAN_COPY is true for formats where symbol
2068    interposition is possible and so symbol values must follow copy
2069    relocation rules.  */
2070
2071 int
2072 dwarf2_has_info (struct objfile *objfile,
2073                  const struct dwarf2_debug_sections *names,
2074                  bool can_copy)
2075 {
2076   if (objfile->flags & OBJF_READNEVER)
2077     return 0;
2078
2079   struct dwarf2_per_objfile *dwarf2_per_objfile
2080     = get_dwarf2_per_objfile (objfile);
2081
2082   if (dwarf2_per_objfile == NULL)
2083     dwarf2_per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile,
2084                                                           names,
2085                                                           can_copy);
2086
2087   return (!dwarf2_per_objfile->info.is_virtual
2088           && dwarf2_per_objfile->info.s.section != NULL
2089           && !dwarf2_per_objfile->abbrev.is_virtual
2090           && dwarf2_per_objfile->abbrev.s.section != NULL);
2091 }
2092
2093 /* When loading sections, we look either for uncompressed section or for
2094    compressed section names.  */
2095
2096 static int
2097 section_is_p (const char *section_name,
2098               const struct dwarf2_section_names *names)
2099 {
2100   if (names->normal != NULL
2101       && strcmp (section_name, names->normal) == 0)
2102     return 1;
2103   if (names->compressed != NULL
2104       && strcmp (section_name, names->compressed) == 0)
2105     return 1;
2106   return 0;
2107 }
2108
2109 /* See declaration.  */
2110
2111 void
2112 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2113                                      const dwarf2_debug_sections &names)
2114 {
2115   flagword aflag = bfd_section_flags (sectp);
2116
2117   if ((aflag & SEC_HAS_CONTENTS) == 0)
2118     {
2119     }
2120   else if (elf_section_data (sectp)->this_hdr.sh_size
2121            > bfd_get_file_size (abfd))
2122     {
2123       bfd_size_type size = elf_section_data (sectp)->this_hdr.sh_size;
2124       warning (_("Discarding section %s which has a section size (%s"
2125                  ") larger than the file size [in module %s]"),
2126                bfd_section_name (sectp), phex_nz (size, sizeof (size)),
2127                bfd_get_filename (abfd));
2128     }
2129   else if (section_is_p (sectp->name, &names.info))
2130     {
2131       this->info.s.section = sectp;
2132       this->info.size = bfd_section_size (sectp);
2133     }
2134   else if (section_is_p (sectp->name, &names.abbrev))
2135     {
2136       this->abbrev.s.section = sectp;
2137       this->abbrev.size = bfd_section_size (sectp);
2138     }
2139   else if (section_is_p (sectp->name, &names.line))
2140     {
2141       this->line.s.section = sectp;
2142       this->line.size = bfd_section_size (sectp);
2143     }
2144   else if (section_is_p (sectp->name, &names.loc))
2145     {
2146       this->loc.s.section = sectp;
2147       this->loc.size = bfd_section_size (sectp);
2148     }
2149   else if (section_is_p (sectp->name, &names.loclists))
2150     {
2151       this->loclists.s.section = sectp;
2152       this->loclists.size = bfd_section_size (sectp);
2153     }
2154   else if (section_is_p (sectp->name, &names.macinfo))
2155     {
2156       this->macinfo.s.section = sectp;
2157       this->macinfo.size = bfd_section_size (sectp);
2158     }
2159   else if (section_is_p (sectp->name, &names.macro))
2160     {
2161       this->macro.s.section = sectp;
2162       this->macro.size = bfd_section_size (sectp);
2163     }
2164   else if (section_is_p (sectp->name, &names.str))
2165     {
2166       this->str.s.section = sectp;
2167       this->str.size = bfd_section_size (sectp);
2168     }
2169   else if (section_is_p (sectp->name, &names.str_offsets))
2170     {
2171       this->str_offsets.s.section = sectp;
2172       this->str_offsets.size = bfd_section_size (sectp);
2173     }
2174   else if (section_is_p (sectp->name, &names.line_str))
2175     {
2176       this->line_str.s.section = sectp;
2177       this->line_str.size = bfd_section_size (sectp);
2178     }
2179   else if (section_is_p (sectp->name, &names.addr))
2180     {
2181       this->addr.s.section = sectp;
2182       this->addr.size = bfd_section_size (sectp);
2183     }
2184   else if (section_is_p (sectp->name, &names.frame))
2185     {
2186       this->frame.s.section = sectp;
2187       this->frame.size = bfd_section_size (sectp);
2188     }
2189   else if (section_is_p (sectp->name, &names.eh_frame))
2190     {
2191       this->eh_frame.s.section = sectp;
2192       this->eh_frame.size = bfd_section_size (sectp);
2193     }
2194   else if (section_is_p (sectp->name, &names.ranges))
2195     {
2196       this->ranges.s.section = sectp;
2197       this->ranges.size = bfd_section_size (sectp);
2198     }
2199   else if (section_is_p (sectp->name, &names.rnglists))
2200     {
2201       this->rnglists.s.section = sectp;
2202       this->rnglists.size = bfd_section_size (sectp);
2203     }
2204   else if (section_is_p (sectp->name, &names.types))
2205     {
2206       struct dwarf2_section_info type_section;
2207
2208       memset (&type_section, 0, sizeof (type_section));
2209       type_section.s.section = sectp;
2210       type_section.size = bfd_section_size (sectp);
2211
2212       this->types.push_back (type_section);
2213     }
2214   else if (section_is_p (sectp->name, &names.gdb_index))
2215     {
2216       this->gdb_index.s.section = sectp;
2217       this->gdb_index.size = bfd_section_size (sectp);
2218     }
2219   else if (section_is_p (sectp->name, &names.debug_names))
2220     {
2221       this->debug_names.s.section = sectp;
2222       this->debug_names.size = bfd_section_size (sectp);
2223     }
2224   else if (section_is_p (sectp->name, &names.debug_aranges))
2225     {
2226       this->debug_aranges.s.section = sectp;
2227       this->debug_aranges.size = bfd_section_size (sectp);
2228     }
2229
2230   if ((bfd_section_flags (sectp) & (SEC_LOAD | SEC_ALLOC))
2231       && bfd_section_vma (sectp) == 0)
2232     this->has_section_at_zero = true;
2233 }
2234
2235 /* A helper function that returns the size of a section in a safe way.
2236    If you are positive that the section has been read before using the
2237    size, then it is safe to refer to the dwarf2_section_info object's
2238    "size" field directly.  In other cases, you must call this
2239    function, because for compressed sections the size field is not set
2240    correctly until the section has been read.  */
2241
2242 static bfd_size_type
2243 dwarf2_section_size (struct objfile *objfile,
2244                      struct dwarf2_section_info *info)
2245 {
2246   if (!info->readin)
2247     info->read (objfile);
2248   return info->size;
2249 }
2250
2251 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2252    SECTION_NAME.  */
2253
2254 void
2255 dwarf2_get_section_info (struct objfile *objfile,
2256                          enum dwarf2_section_enum sect,
2257                          asection **sectp, const gdb_byte **bufp,
2258                          bfd_size_type *sizep)
2259 {
2260   struct dwarf2_per_objfile *data = dwarf2_objfile_data_key.get (objfile);
2261   struct dwarf2_section_info *info;
2262
2263   /* We may see an objfile without any DWARF, in which case we just
2264      return nothing.  */
2265   if (data == NULL)
2266     {
2267       *sectp = NULL;
2268       *bufp = NULL;
2269       *sizep = 0;
2270       return;
2271     }
2272   switch (sect)
2273     {
2274     case DWARF2_DEBUG_FRAME:
2275       info = &data->frame;
2276       break;
2277     case DWARF2_EH_FRAME:
2278       info = &data->eh_frame;
2279       break;
2280     default:
2281       gdb_assert_not_reached ("unexpected section");
2282     }
2283
2284   info->read (objfile);
2285
2286   *sectp = info->get_bfd_section ();
2287   *bufp = info->buffer;
2288   *sizep = info->size;
2289 }
2290
2291 /* A helper function to find the sections for a .dwz file.  */
2292
2293 static void
2294 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2295 {
2296   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2297
2298   /* Note that we only support the standard ELF names, because .dwz
2299      is ELF-only (at the time of writing).  */
2300   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2301     {
2302       dwz_file->abbrev.s.section = sectp;
2303       dwz_file->abbrev.size = bfd_section_size (sectp);
2304     }
2305   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2306     {
2307       dwz_file->info.s.section = sectp;
2308       dwz_file->info.size = bfd_section_size (sectp);
2309     }
2310   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2311     {
2312       dwz_file->str.s.section = sectp;
2313       dwz_file->str.size = bfd_section_size (sectp);
2314     }
2315   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2316     {
2317       dwz_file->line.s.section = sectp;
2318       dwz_file->line.size = bfd_section_size (sectp);
2319     }
2320   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2321     {
2322       dwz_file->macro.s.section = sectp;
2323       dwz_file->macro.size = bfd_section_size (sectp);
2324     }
2325   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2326     {
2327       dwz_file->gdb_index.s.section = sectp;
2328       dwz_file->gdb_index.size = bfd_section_size (sectp);
2329     }
2330   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2331     {
2332       dwz_file->debug_names.s.section = sectp;
2333       dwz_file->debug_names.size = bfd_section_size (sectp);
2334     }
2335 }
2336
2337 /* See dwarf2read.h.  */
2338
2339 struct dwz_file *
2340 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2341 {
2342   const char *filename;
2343   bfd_size_type buildid_len_arg;
2344   size_t buildid_len;
2345   bfd_byte *buildid;
2346
2347   if (dwarf2_per_objfile->dwz_file != NULL)
2348     return dwarf2_per_objfile->dwz_file.get ();
2349
2350   bfd_set_error (bfd_error_no_error);
2351   gdb::unique_xmalloc_ptr<char> data
2352     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2353                                   &buildid_len_arg, &buildid));
2354   if (data == NULL)
2355     {
2356       if (bfd_get_error () == bfd_error_no_error)
2357         return NULL;
2358       error (_("could not read '.gnu_debugaltlink' section: %s"),
2359              bfd_errmsg (bfd_get_error ()));
2360     }
2361
2362   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2363
2364   buildid_len = (size_t) buildid_len_arg;
2365
2366   filename = data.get ();
2367
2368   std::string abs_storage;
2369   if (!IS_ABSOLUTE_PATH (filename))
2370     {
2371       gdb::unique_xmalloc_ptr<char> abs
2372         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2373
2374       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2375       filename = abs_storage.c_str ();
2376     }
2377
2378   /* First try the file name given in the section.  If that doesn't
2379      work, try to use the build-id instead.  */
2380   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2381   if (dwz_bfd != NULL)
2382     {
2383       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2384         dwz_bfd.reset (nullptr);
2385     }
2386
2387   if (dwz_bfd == NULL)
2388     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2389
2390   if (dwz_bfd == NULL)
2391     error (_("could not find '.gnu_debugaltlink' file for %s"),
2392            objfile_name (dwarf2_per_objfile->objfile));
2393
2394   std::unique_ptr<struct dwz_file> result
2395     (new struct dwz_file (std::move (dwz_bfd)));
2396
2397   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2398                          result.get ());
2399
2400   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2401                             result->dwz_bfd.get ());
2402   dwarf2_per_objfile->dwz_file = std::move (result);
2403   return dwarf2_per_objfile->dwz_file.get ();
2404 }
2405 \f
2406 /* DWARF quick_symbols_functions support.  */
2407
2408 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2409    unique line tables, so we maintain a separate table of all .debug_line
2410    derived entries to support the sharing.
2411    All the quick functions need is the list of file names.  We discard the
2412    line_header when we're done and don't need to record it here.  */
2413 struct quick_file_names
2414 {
2415   /* The data used to construct the hash key.  */
2416   struct stmt_list_hash hash;
2417
2418   /* The number of entries in file_names, real_names.  */
2419   unsigned int num_file_names;
2420
2421   /* The file names from the line table, after being run through
2422      file_full_name.  */
2423   const char **file_names;
2424
2425   /* The file names from the line table after being run through
2426      gdb_realpath.  These are computed lazily.  */
2427   const char **real_names;
2428 };
2429
2430 /* When using the index (and thus not using psymtabs), each CU has an
2431    object of this type.  This is used to hold information needed by
2432    the various "quick" methods.  */
2433 struct dwarf2_per_cu_quick_data
2434 {
2435   /* The file table.  This can be NULL if there was no file table
2436      or it's currently not read in.
2437      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2438   struct quick_file_names *file_names;
2439
2440   /* The corresponding symbol table.  This is NULL if symbols for this
2441      CU have not yet been read.  */
2442   struct compunit_symtab *compunit_symtab;
2443
2444   /* A temporary mark bit used when iterating over all CUs in
2445      expand_symtabs_matching.  */
2446   unsigned int mark : 1;
2447
2448   /* True if we've tried to read the file table and found there isn't one.
2449      There will be no point in trying to read it again next time.  */
2450   unsigned int no_file_data : 1;
2451 };
2452
2453 /* Utility hash function for a stmt_list_hash.  */
2454
2455 static hashval_t
2456 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2457 {
2458   hashval_t v = 0;
2459
2460   if (stmt_list_hash->dwo_unit != NULL)
2461     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2462   v += to_underlying (stmt_list_hash->line_sect_off);
2463   return v;
2464 }
2465
2466 /* Utility equality function for a stmt_list_hash.  */
2467
2468 static int
2469 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2470                     const struct stmt_list_hash *rhs)
2471 {
2472   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2473     return 0;
2474   if (lhs->dwo_unit != NULL
2475       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2476     return 0;
2477
2478   return lhs->line_sect_off == rhs->line_sect_off;
2479 }
2480
2481 /* Hash function for a quick_file_names.  */
2482
2483 static hashval_t
2484 hash_file_name_entry (const void *e)
2485 {
2486   const struct quick_file_names *file_data
2487     = (const struct quick_file_names *) e;
2488
2489   return hash_stmt_list_entry (&file_data->hash);
2490 }
2491
2492 /* Equality function for a quick_file_names.  */
2493
2494 static int
2495 eq_file_name_entry (const void *a, const void *b)
2496 {
2497   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2498   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2499
2500   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2501 }
2502
2503 /* Delete function for a quick_file_names.  */
2504
2505 static void
2506 delete_file_name_entry (void *e)
2507 {
2508   struct quick_file_names *file_data = (struct quick_file_names *) e;
2509   int i;
2510
2511   for (i = 0; i < file_data->num_file_names; ++i)
2512     {
2513       xfree ((void*) file_data->file_names[i]);
2514       if (file_data->real_names)
2515         xfree ((void*) file_data->real_names[i]);
2516     }
2517
2518   /* The space for the struct itself lives on objfile_obstack,
2519      so we don't free it here.  */
2520 }
2521
2522 /* Create a quick_file_names hash table.  */
2523
2524 static htab_up
2525 create_quick_file_names_table (unsigned int nr_initial_entries)
2526 {
2527   return htab_up (htab_create_alloc (nr_initial_entries,
2528                                      hash_file_name_entry, eq_file_name_entry,
2529                                      delete_file_name_entry, xcalloc, xfree));
2530 }
2531
2532 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2533    have to be created afterwards.  You should call age_cached_comp_units after
2534    processing PER_CU->CU.  dw2_setup must have been already called.  */
2535
2536 static void
2537 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2538 {
2539   if (per_cu->is_debug_types)
2540     load_full_type_unit (per_cu);
2541   else
2542     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2543
2544   if (per_cu->cu == NULL)
2545     return;  /* Dummy CU.  */
2546
2547   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2548 }
2549
2550 /* Read in the symbols for PER_CU.  */
2551
2552 static void
2553 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2554 {
2555   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2556
2557   /* Skip type_unit_groups, reading the type units they contain
2558      is handled elsewhere.  */
2559   if (IS_TYPE_UNIT_GROUP (per_cu))
2560     return;
2561
2562   /* The destructor of dwarf2_queue_guard frees any entries left on
2563      the queue.  After this point we're guaranteed to leave this function
2564      with the dwarf queue empty.  */
2565   dwarf2_queue_guard q_guard (dwarf2_per_objfile);
2566
2567   if (dwarf2_per_objfile->using_index
2568       ? per_cu->v.quick->compunit_symtab == NULL
2569       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2570     {
2571       queue_comp_unit (per_cu, language_minimal);
2572       load_cu (per_cu, skip_partial);
2573
2574       /* If we just loaded a CU from a DWO, and we're working with an index
2575          that may badly handle TUs, load all the TUs in that DWO as well.
2576          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2577       if (!per_cu->is_debug_types
2578           && per_cu->cu != NULL
2579           && per_cu->cu->dwo_unit != NULL
2580           && dwarf2_per_objfile->index_table != NULL
2581           && dwarf2_per_objfile->index_table->version <= 7
2582           /* DWP files aren't supported yet.  */
2583           && get_dwp_file (dwarf2_per_objfile) == NULL)
2584         queue_and_load_all_dwo_tus (per_cu);
2585     }
2586
2587   process_queue (dwarf2_per_objfile);
2588
2589   /* Age the cache, releasing compilation units that have not
2590      been used recently.  */
2591   age_cached_comp_units (dwarf2_per_objfile);
2592 }
2593
2594 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2595    the objfile from which this CU came.  Returns the resulting symbol
2596    table.  */
2597
2598 static struct compunit_symtab *
2599 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2600 {
2601   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2602
2603   gdb_assert (dwarf2_per_objfile->using_index);
2604   if (!per_cu->v.quick->compunit_symtab)
2605     {
2606       free_cached_comp_units freer (dwarf2_per_objfile);
2607       scoped_restore decrementer = increment_reading_symtab ();
2608       dw2_do_instantiate_symtab (per_cu, skip_partial);
2609       process_cu_includes (dwarf2_per_objfile);
2610     }
2611
2612   return per_cu->v.quick->compunit_symtab;
2613 }
2614
2615 /* See declaration.  */
2616
2617 dwarf2_per_cu_data *
2618 dwarf2_per_objfile::get_cutu (int index)
2619 {
2620   if (index >= this->all_comp_units.size ())
2621     {
2622       index -= this->all_comp_units.size ();
2623       gdb_assert (index < this->all_type_units.size ());
2624       return &this->all_type_units[index]->per_cu;
2625     }
2626
2627   return this->all_comp_units[index];
2628 }
2629
2630 /* See declaration.  */
2631
2632 dwarf2_per_cu_data *
2633 dwarf2_per_objfile::get_cu (int index)
2634 {
2635   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2636
2637   return this->all_comp_units[index];
2638 }
2639
2640 /* See declaration.  */
2641
2642 signatured_type *
2643 dwarf2_per_objfile::get_tu (int index)
2644 {
2645   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2646
2647   return this->all_type_units[index];
2648 }
2649
2650 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2651    objfile_obstack, and constructed with the specified field
2652    values.  */
2653
2654 static dwarf2_per_cu_data *
2655 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2656                           struct dwarf2_section_info *section,
2657                           int is_dwz,
2658                           sect_offset sect_off, ULONGEST length)
2659 {
2660   struct objfile *objfile = dwarf2_per_objfile->objfile;
2661   dwarf2_per_cu_data *the_cu
2662     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2663                      struct dwarf2_per_cu_data);
2664   the_cu->sect_off = sect_off;
2665   the_cu->length = length;
2666   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2667   the_cu->section = section;
2668   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2669                                    struct dwarf2_per_cu_quick_data);
2670   the_cu->is_dwz = is_dwz;
2671   return the_cu;
2672 }
2673
2674 /* A helper for create_cus_from_index that handles a given list of
2675    CUs.  */
2676
2677 static void
2678 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2679                             const gdb_byte *cu_list, offset_type n_elements,
2680                             struct dwarf2_section_info *section,
2681                             int is_dwz)
2682 {
2683   for (offset_type i = 0; i < n_elements; i += 2)
2684     {
2685       gdb_static_assert (sizeof (ULONGEST) >= 8);
2686
2687       sect_offset sect_off
2688         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2689       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2690       cu_list += 2 * 8;
2691
2692       dwarf2_per_cu_data *per_cu
2693         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2694                                      sect_off, length);
2695       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2696     }
2697 }
2698
2699 /* Read the CU list from the mapped index, and use it to create all
2700    the CU objects for this objfile.  */
2701
2702 static void
2703 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
2704                        const gdb_byte *cu_list, offset_type cu_list_elements,
2705                        const gdb_byte *dwz_list, offset_type dwz_elements)
2706 {
2707   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
2708   dwarf2_per_objfile->all_comp_units.reserve
2709     ((cu_list_elements + dwz_elements) / 2);
2710
2711   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
2712                               &dwarf2_per_objfile->info, 0);
2713
2714   if (dwz_elements == 0)
2715     return;
2716
2717   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
2718   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
2719                               &dwz->info, 1);
2720 }
2721
2722 /* Create the signatured type hash table from the index.  */
2723
2724 static void
2725 create_signatured_type_table_from_index
2726   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2727    struct dwarf2_section_info *section,
2728    const gdb_byte *bytes,
2729    offset_type elements)
2730 {
2731   struct objfile *objfile = dwarf2_per_objfile->objfile;
2732
2733   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
2734   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
2735
2736   htab_up sig_types_hash = allocate_signatured_type_table (objfile);
2737
2738   for (offset_type i = 0; i < elements; i += 3)
2739     {
2740       struct signatured_type *sig_type;
2741       ULONGEST signature;
2742       void **slot;
2743       cu_offset type_offset_in_tu;
2744
2745       gdb_static_assert (sizeof (ULONGEST) >= 8);
2746       sect_offset sect_off
2747         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2748       type_offset_in_tu
2749         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
2750                                                 BFD_ENDIAN_LITTLE);
2751       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2752       bytes += 3 * 8;
2753
2754       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2755                                  struct signatured_type);
2756       sig_type->signature = signature;
2757       sig_type->type_offset_in_tu = type_offset_in_tu;
2758       sig_type->per_cu.is_debug_types = 1;
2759       sig_type->per_cu.section = section;
2760       sig_type->per_cu.sect_off = sect_off;
2761       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
2762       sig_type->per_cu.v.quick
2763         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2764                           struct dwarf2_per_cu_quick_data);
2765
2766       slot = htab_find_slot (sig_types_hash.get (), sig_type, INSERT);
2767       *slot = sig_type;
2768
2769       dwarf2_per_objfile->all_type_units.push_back (sig_type);
2770     }
2771
2772   dwarf2_per_objfile->signatured_types = std::move (sig_types_hash);
2773 }
2774
2775 /* Create the signatured type hash table from .debug_names.  */
2776
2777 static void
2778 create_signatured_type_table_from_debug_names
2779   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2780    const mapped_debug_names &map,
2781    struct dwarf2_section_info *section,
2782    struct dwarf2_section_info *abbrev_section)
2783 {
2784   struct objfile *objfile = dwarf2_per_objfile->objfile;
2785
2786   section->read (objfile);
2787   abbrev_section->read (objfile);
2788
2789   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
2790   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
2791
2792   htab_up sig_types_hash = allocate_signatured_type_table (objfile);
2793
2794   for (uint32_t i = 0; i < map.tu_count; ++i)
2795     {
2796       struct signatured_type *sig_type;
2797       void **slot;
2798
2799       sect_offset sect_off
2800         = (sect_offset) (extract_unsigned_integer
2801                          (map.tu_table_reordered + i * map.offset_size,
2802                           map.offset_size,
2803                           map.dwarf5_byte_order));
2804
2805       comp_unit_head cu_header;
2806       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
2807                                      abbrev_section,
2808                                      section->buffer + to_underlying (sect_off),
2809                                      rcuh_kind::TYPE);
2810
2811       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2812                                  struct signatured_type);
2813       sig_type->signature = cu_header.signature;
2814       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
2815       sig_type->per_cu.is_debug_types = 1;
2816       sig_type->per_cu.section = section;
2817       sig_type->per_cu.sect_off = sect_off;
2818       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
2819       sig_type->per_cu.v.quick
2820         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2821                           struct dwarf2_per_cu_quick_data);
2822
2823       slot = htab_find_slot (sig_types_hash.get (), sig_type, INSERT);
2824       *slot = sig_type;
2825
2826       dwarf2_per_objfile->all_type_units.push_back (sig_type);
2827     }
2828
2829   dwarf2_per_objfile->signatured_types = std::move (sig_types_hash);
2830 }
2831
2832 /* Read the address map data from the mapped index, and use it to
2833    populate the objfile's psymtabs_addrmap.  */
2834
2835 static void
2836 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
2837                            struct mapped_index *index)
2838 {
2839   struct objfile *objfile = dwarf2_per_objfile->objfile;
2840   struct gdbarch *gdbarch = get_objfile_arch (objfile);
2841   const gdb_byte *iter, *end;
2842   struct addrmap *mutable_map;
2843   CORE_ADDR baseaddr;
2844
2845   auto_obstack temp_obstack;
2846
2847   mutable_map = addrmap_create_mutable (&temp_obstack);
2848
2849   iter = index->address_table.data ();
2850   end = iter + index->address_table.size ();
2851
2852   baseaddr = objfile->text_section_offset ();
2853
2854   while (iter < end)
2855     {
2856       ULONGEST hi, lo, cu_index;
2857       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2858       iter += 8;
2859       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2860       iter += 8;
2861       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2862       iter += 4;
2863
2864       if (lo > hi)
2865         {
2866           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
2867                      hex_string (lo), hex_string (hi));
2868           continue;
2869         }
2870
2871       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
2872         {
2873           complaint (_(".gdb_index address table has invalid CU number %u"),
2874                      (unsigned) cu_index);
2875           continue;
2876         }
2877
2878       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
2879       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
2880       addrmap_set_empty (mutable_map, lo, hi - 1,
2881                          dwarf2_per_objfile->get_cu (cu_index));
2882     }
2883
2884   objfile->partial_symtabs->psymtabs_addrmap
2885     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
2886 }
2887
2888 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
2889    populate the objfile's psymtabs_addrmap.  */
2890
2891 static void
2892 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
2893                              struct dwarf2_section_info *section)
2894 {
2895   struct objfile *objfile = dwarf2_per_objfile->objfile;
2896   bfd *abfd = objfile->obfd;
2897   struct gdbarch *gdbarch = get_objfile_arch (objfile);
2898   const CORE_ADDR baseaddr = objfile->text_section_offset ();
2899
2900   auto_obstack temp_obstack;
2901   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
2902
2903   std::unordered_map<sect_offset,
2904                      dwarf2_per_cu_data *,
2905                      gdb::hash_enum<sect_offset>>
2906     debug_info_offset_to_per_cu;
2907   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
2908     {
2909       const auto insertpair
2910         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
2911       if (!insertpair.second)
2912         {
2913           warning (_("Section .debug_aranges in %s has duplicate "
2914                      "debug_info_offset %s, ignoring .debug_aranges."),
2915                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
2916           return;
2917         }
2918     }
2919
2920   section->read (objfile);
2921
2922   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
2923
2924   const gdb_byte *addr = section->buffer;
2925
2926   while (addr < section->buffer + section->size)
2927     {
2928       const gdb_byte *const entry_addr = addr;
2929       unsigned int bytes_read;
2930
2931       const LONGEST entry_length = read_initial_length (abfd, addr,
2932                                                         &bytes_read);
2933       addr += bytes_read;
2934
2935       const gdb_byte *const entry_end = addr + entry_length;
2936       const bool dwarf5_is_dwarf64 = bytes_read != 4;
2937       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
2938       if (addr + entry_length > section->buffer + section->size)
2939         {
2940           warning (_("Section .debug_aranges in %s entry at offset %s "
2941                      "length %s exceeds section length %s, "
2942                      "ignoring .debug_aranges."),
2943                    objfile_name (objfile),
2944                    plongest (entry_addr - section->buffer),
2945                    plongest (bytes_read + entry_length),
2946                    pulongest (section->size));
2947           return;
2948         }
2949
2950       /* The version number.  */
2951       const uint16_t version = read_2_bytes (abfd, addr);
2952       addr += 2;
2953       if (version != 2)
2954         {
2955           warning (_("Section .debug_aranges in %s entry at offset %s "
2956                      "has unsupported version %d, ignoring .debug_aranges."),
2957                    objfile_name (objfile),
2958                    plongest (entry_addr - section->buffer), version);
2959           return;
2960         }
2961
2962       const uint64_t debug_info_offset
2963         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
2964       addr += offset_size;
2965       const auto per_cu_it
2966         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
2967       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
2968         {
2969           warning (_("Section .debug_aranges in %s entry at offset %s "
2970                      "debug_info_offset %s does not exists, "
2971                      "ignoring .debug_aranges."),
2972                    objfile_name (objfile),
2973                    plongest (entry_addr - section->buffer),
2974                    pulongest (debug_info_offset));
2975           return;
2976         }
2977       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
2978
2979       const uint8_t address_size = *addr++;
2980       if (address_size < 1 || address_size > 8)
2981         {
2982           warning (_("Section .debug_aranges in %s entry at offset %s "
2983                      "address_size %u is invalid, ignoring .debug_aranges."),
2984                    objfile_name (objfile),
2985                    plongest (entry_addr - section->buffer), address_size);
2986           return;
2987         }
2988
2989       const uint8_t segment_selector_size = *addr++;
2990       if (segment_selector_size != 0)
2991         {
2992           warning (_("Section .debug_aranges in %s entry at offset %s "
2993                      "segment_selector_size %u is not supported, "
2994                      "ignoring .debug_aranges."),
2995                    objfile_name (objfile),
2996                    plongest (entry_addr - section->buffer),
2997                    segment_selector_size);
2998           return;
2999         }
3000
3001       /* Must pad to an alignment boundary that is twice the address
3002          size.  It is undocumented by the DWARF standard but GCC does
3003          use it.  */
3004       for (size_t padding = ((-(addr - section->buffer))
3005                              & (2 * address_size - 1));
3006            padding > 0; padding--)
3007         if (*addr++ != 0)
3008           {
3009             warning (_("Section .debug_aranges in %s entry at offset %s "
3010                        "padding is not zero, ignoring .debug_aranges."),
3011                      objfile_name (objfile),
3012                      plongest (entry_addr - section->buffer));
3013             return;
3014           }
3015
3016       for (;;)
3017         {
3018           if (addr + 2 * address_size > entry_end)
3019             {
3020               warning (_("Section .debug_aranges in %s entry at offset %s "
3021                          "address list is not properly terminated, "
3022                          "ignoring .debug_aranges."),
3023                        objfile_name (objfile),
3024                        plongest (entry_addr - section->buffer));
3025               return;
3026             }
3027           ULONGEST start = extract_unsigned_integer (addr, address_size,
3028                                                      dwarf5_byte_order);
3029           addr += address_size;
3030           ULONGEST length = extract_unsigned_integer (addr, address_size,
3031                                                       dwarf5_byte_order);
3032           addr += address_size;
3033           if (start == 0 && length == 0)
3034             break;
3035           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3036             {
3037               /* Symbol was eliminated due to a COMDAT group.  */
3038               continue;
3039             }
3040           ULONGEST end = start + length;
3041           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
3042                    - baseaddr);
3043           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3044                  - baseaddr);
3045           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3046         }
3047     }
3048
3049   objfile->partial_symtabs->psymtabs_addrmap
3050     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3051 }
3052
3053 /* Find a slot in the mapped index INDEX for the object named NAME.
3054    If NAME is found, set *VEC_OUT to point to the CU vector in the
3055    constant pool and return true.  If NAME cannot be found, return
3056    false.  */
3057
3058 static bool
3059 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3060                           offset_type **vec_out)
3061 {
3062   offset_type hash;
3063   offset_type slot, step;
3064   int (*cmp) (const char *, const char *);
3065
3066   gdb::unique_xmalloc_ptr<char> without_params;
3067   if (current_language->la_language == language_cplus
3068       || current_language->la_language == language_fortran
3069       || current_language->la_language == language_d)
3070     {
3071       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3072          not contain any.  */
3073
3074       if (strchr (name, '(') != NULL)
3075         {
3076           without_params = cp_remove_params (name);
3077
3078           if (without_params != NULL)
3079             name = without_params.get ();
3080         }
3081     }
3082
3083   /* Index version 4 did not support case insensitive searches.  But the
3084      indices for case insensitive languages are built in lowercase, therefore
3085      simulate our NAME being searched is also lowercased.  */
3086   hash = mapped_index_string_hash ((index->version == 4
3087                                     && case_sensitivity == case_sensitive_off
3088                                     ? 5 : index->version),
3089                                    name);
3090
3091   slot = hash & (index->symbol_table.size () - 1);
3092   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3093   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3094
3095   for (;;)
3096     {
3097       const char *str;
3098
3099       const auto &bucket = index->symbol_table[slot];
3100       if (bucket.name == 0 && bucket.vec == 0)
3101         return false;
3102
3103       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3104       if (!cmp (name, str))
3105         {
3106           *vec_out = (offset_type *) (index->constant_pool
3107                                       + MAYBE_SWAP (bucket.vec));
3108           return true;
3109         }
3110
3111       slot = (slot + step) & (index->symbol_table.size () - 1);
3112     }
3113 }
3114
3115 /* A helper function that reads the .gdb_index from BUFFER and fills
3116    in MAP.  FILENAME is the name of the file containing the data;
3117    it is used for error reporting.  DEPRECATED_OK is true if it is
3118    ok to use deprecated sections.
3119
3120    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3121    out parameters that are filled in with information about the CU and
3122    TU lists in the section.
3123
3124    Returns true if all went well, false otherwise.  */
3125
3126 static bool
3127 read_gdb_index_from_buffer (struct objfile *objfile,
3128                             const char *filename,
3129                             bool deprecated_ok,
3130                             gdb::array_view<const gdb_byte> buffer,
3131                             struct mapped_index *map,
3132                             const gdb_byte **cu_list,
3133                             offset_type *cu_list_elements,
3134                             const gdb_byte **types_list,
3135                             offset_type *types_list_elements)
3136 {
3137   const gdb_byte *addr = &buffer[0];
3138
3139   /* Version check.  */
3140   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3141   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3142      causes the index to behave very poorly for certain requests.  Version 3
3143      contained incomplete addrmap.  So, it seems better to just ignore such
3144      indices.  */
3145   if (version < 4)
3146     {
3147       static int warning_printed = 0;
3148       if (!warning_printed)
3149         {
3150           warning (_("Skipping obsolete .gdb_index section in %s."),
3151                    filename);
3152           warning_printed = 1;
3153         }
3154       return 0;
3155     }
3156   /* Index version 4 uses a different hash function than index version
3157      5 and later.
3158
3159      Versions earlier than 6 did not emit psymbols for inlined
3160      functions.  Using these files will cause GDB not to be able to
3161      set breakpoints on inlined functions by name, so we ignore these
3162      indices unless the user has done
3163      "set use-deprecated-index-sections on".  */
3164   if (version < 6 && !deprecated_ok)
3165     {
3166       static int warning_printed = 0;
3167       if (!warning_printed)
3168         {
3169           warning (_("\
3170 Skipping deprecated .gdb_index section in %s.\n\
3171 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3172 to use the section anyway."),
3173                    filename);
3174           warning_printed = 1;
3175         }
3176       return 0;
3177     }
3178   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3179      of the TU (for symbols coming from TUs),
3180      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3181      Plus gold-generated indices can have duplicate entries for global symbols,
3182      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3183      These are just performance bugs, and we can't distinguish gdb-generated
3184      indices from gold-generated ones, so issue no warning here.  */
3185
3186   /* Indexes with higher version than the one supported by GDB may be no
3187      longer backward compatible.  */
3188   if (version > 8)
3189     return 0;
3190
3191   map->version = version;
3192
3193   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3194
3195   int i = 0;
3196   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3197   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3198                        / 8);
3199   ++i;
3200
3201   *types_list = addr + MAYBE_SWAP (metadata[i]);
3202   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3203                            - MAYBE_SWAP (metadata[i]))
3204                           / 8);
3205   ++i;
3206
3207   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3208   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3209   map->address_table
3210     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3211   ++i;
3212
3213   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3214   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3215   map->symbol_table
3216     = gdb::array_view<mapped_index::symbol_table_slot>
3217        ((mapped_index::symbol_table_slot *) symbol_table,
3218         (mapped_index::symbol_table_slot *) symbol_table_end);
3219
3220   ++i;
3221   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3222
3223   return 1;
3224 }
3225
3226 /* Callback types for dwarf2_read_gdb_index.  */
3227
3228 typedef gdb::function_view
3229     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
3230     get_gdb_index_contents_ftype;
3231 typedef gdb::function_view
3232     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3233     get_gdb_index_contents_dwz_ftype;
3234
3235 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3236    elements of all the CUs and return 1.  Otherwise, return 0.  */
3237
3238 static int
3239 dwarf2_read_gdb_index
3240   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3241    get_gdb_index_contents_ftype get_gdb_index_contents,
3242    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3243 {
3244   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3245   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3246   struct dwz_file *dwz;
3247   struct objfile *objfile = dwarf2_per_objfile->objfile;
3248
3249   gdb::array_view<const gdb_byte> main_index_contents
3250     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3251
3252   if (main_index_contents.empty ())
3253     return 0;
3254
3255   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3256   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3257                                    use_deprecated_index_sections,
3258                                    main_index_contents, map.get (), &cu_list,
3259                                    &cu_list_elements, &types_list,
3260                                    &types_list_elements))
3261     return 0;
3262
3263   /* Don't use the index if it's empty.  */
3264   if (map->symbol_table.empty ())
3265     return 0;
3266
3267   /* If there is a .dwz file, read it so we can get its CU list as
3268      well.  */
3269   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3270   if (dwz != NULL)
3271     {
3272       struct mapped_index dwz_map;
3273       const gdb_byte *dwz_types_ignore;
3274       offset_type dwz_types_elements_ignore;
3275
3276       gdb::array_view<const gdb_byte> dwz_index_content
3277         = get_gdb_index_contents_dwz (objfile, dwz);
3278
3279       if (dwz_index_content.empty ())
3280         return 0;
3281
3282       if (!read_gdb_index_from_buffer (objfile,
3283                                        bfd_get_filename (dwz->dwz_bfd.get ()),
3284                                        1, dwz_index_content, &dwz_map,
3285                                        &dwz_list, &dwz_list_elements,
3286                                        &dwz_types_ignore,
3287                                        &dwz_types_elements_ignore))
3288         {
3289           warning (_("could not read '.gdb_index' section from %s; skipping"),
3290                    bfd_get_filename (dwz->dwz_bfd.get ()));
3291           return 0;
3292         }
3293     }
3294
3295   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3296                          dwz_list, dwz_list_elements);
3297
3298   if (types_list_elements)
3299     {
3300       /* We can only handle a single .debug_types when we have an
3301          index.  */
3302       if (dwarf2_per_objfile->types.size () != 1)
3303         return 0;
3304
3305       dwarf2_section_info *section = &dwarf2_per_objfile->types[0];
3306
3307       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3308                                                types_list, types_list_elements);
3309     }
3310
3311   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3312
3313   dwarf2_per_objfile->index_table = std::move (map);
3314   dwarf2_per_objfile->using_index = 1;
3315   dwarf2_per_objfile->quick_file_names_table =
3316     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3317
3318   return 1;
3319 }
3320
3321 /* die_reader_func for dw2_get_file_names.  */
3322
3323 static void
3324 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3325                            const gdb_byte *info_ptr,
3326                            struct die_info *comp_unit_die)
3327 {
3328   struct dwarf2_cu *cu = reader->cu;
3329   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3330   struct dwarf2_per_objfile *dwarf2_per_objfile
3331     = cu->per_cu->dwarf2_per_objfile;
3332   struct objfile *objfile = dwarf2_per_objfile->objfile;
3333   struct dwarf2_per_cu_data *lh_cu;
3334   struct attribute *attr;
3335   void **slot;
3336   struct quick_file_names *qfn;
3337
3338   gdb_assert (! this_cu->is_debug_types);
3339
3340   /* Our callers never want to match partial units -- instead they
3341      will match the enclosing full CU.  */
3342   if (comp_unit_die->tag == DW_TAG_partial_unit)
3343     {
3344       this_cu->v.quick->no_file_data = 1;
3345       return;
3346     }
3347
3348   lh_cu = this_cu;
3349   slot = NULL;
3350
3351   line_header_up lh;
3352   sect_offset line_offset {};
3353
3354   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3355   if (attr != nullptr)
3356     {
3357       struct quick_file_names find_entry;
3358
3359       line_offset = (sect_offset) DW_UNSND (attr);
3360
3361       /* We may have already read in this line header (TU line header sharing).
3362          If we have we're done.  */
3363       find_entry.hash.dwo_unit = cu->dwo_unit;
3364       find_entry.hash.line_sect_off = line_offset;
3365       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table.get (),
3366                              &find_entry, INSERT);
3367       if (*slot != NULL)
3368         {
3369           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3370           return;
3371         }
3372
3373       lh = dwarf_decode_line_header (line_offset, cu);
3374     }
3375   if (lh == NULL)
3376     {
3377       lh_cu->v.quick->no_file_data = 1;
3378       return;
3379     }
3380
3381   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3382   qfn->hash.dwo_unit = cu->dwo_unit;
3383   qfn->hash.line_sect_off = line_offset;
3384   gdb_assert (slot != NULL);
3385   *slot = qfn;
3386
3387   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3388
3389   int offset = 0;
3390   if (strcmp (fnd.name, "<unknown>") != 0)
3391     ++offset;
3392
3393   qfn->num_file_names = offset + lh->file_names_size ();
3394   qfn->file_names =
3395     XOBNEWVEC (&objfile->objfile_obstack, const char *, qfn->num_file_names);
3396   if (offset != 0)
3397     qfn->file_names[0] = xstrdup (fnd.name);
3398   for (int i = 0; i < lh->file_names_size (); ++i)
3399     qfn->file_names[i + offset] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3400   qfn->real_names = NULL;
3401
3402   lh_cu->v.quick->file_names = qfn;
3403 }
3404
3405 /* A helper for the "quick" functions which attempts to read the line
3406    table for THIS_CU.  */
3407
3408 static struct quick_file_names *
3409 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3410 {
3411   /* This should never be called for TUs.  */
3412   gdb_assert (! this_cu->is_debug_types);
3413   /* Nor type unit groups.  */
3414   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3415
3416   if (this_cu->v.quick->file_names != NULL)
3417     return this_cu->v.quick->file_names;
3418   /* If we know there is no line data, no point in looking again.  */
3419   if (this_cu->v.quick->no_file_data)
3420     return NULL;
3421
3422   cutu_reader reader (this_cu);
3423   if (!reader.dummy_p)
3424     dw2_get_file_names_reader (&reader, reader.info_ptr, reader.comp_unit_die);
3425
3426   if (this_cu->v.quick->no_file_data)
3427     return NULL;
3428   return this_cu->v.quick->file_names;
3429 }
3430
3431 /* A helper for the "quick" functions which computes and caches the
3432    real path for a given file name from the line table.  */
3433
3434 static const char *
3435 dw2_get_real_path (struct objfile *objfile,
3436                    struct quick_file_names *qfn, int index)
3437 {
3438   if (qfn->real_names == NULL)
3439     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3440                                       qfn->num_file_names, const char *);
3441
3442   if (qfn->real_names[index] == NULL)
3443     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3444
3445   return qfn->real_names[index];
3446 }
3447
3448 static struct symtab *
3449 dw2_find_last_source_symtab (struct objfile *objfile)
3450 {
3451   struct dwarf2_per_objfile *dwarf2_per_objfile
3452     = get_dwarf2_per_objfile (objfile);
3453   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3454   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3455
3456   if (cust == NULL)
3457     return NULL;
3458
3459   return compunit_primary_filetab (cust);
3460 }
3461
3462 /* Traversal function for dw2_forget_cached_source_info.  */
3463
3464 static int
3465 dw2_free_cached_file_names (void **slot, void *info)
3466 {
3467   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3468
3469   if (file_data->real_names)
3470     {
3471       int i;
3472
3473       for (i = 0; i < file_data->num_file_names; ++i)
3474         {
3475           xfree ((void*) file_data->real_names[i]);
3476           file_data->real_names[i] = NULL;
3477         }
3478     }
3479
3480   return 1;
3481 }
3482
3483 static void
3484 dw2_forget_cached_source_info (struct objfile *objfile)
3485 {
3486   struct dwarf2_per_objfile *dwarf2_per_objfile
3487     = get_dwarf2_per_objfile (objfile);
3488
3489   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table.get (),
3490                           dw2_free_cached_file_names, NULL);
3491 }
3492
3493 /* Helper function for dw2_map_symtabs_matching_filename that expands
3494    the symtabs and calls the iterator.  */
3495
3496 static int
3497 dw2_map_expand_apply (struct objfile *objfile,
3498                       struct dwarf2_per_cu_data *per_cu,
3499                       const char *name, const char *real_path,
3500                       gdb::function_view<bool (symtab *)> callback)
3501 {
3502   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3503
3504   /* Don't visit already-expanded CUs.  */
3505   if (per_cu->v.quick->compunit_symtab)
3506     return 0;
3507
3508   /* This may expand more than one symtab, and we want to iterate over
3509      all of them.  */
3510   dw2_instantiate_symtab (per_cu, false);
3511
3512   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3513                                     last_made, callback);
3514 }
3515
3516 /* Implementation of the map_symtabs_matching_filename method.  */
3517
3518 static bool
3519 dw2_map_symtabs_matching_filename
3520   (struct objfile *objfile, const char *name, const char *real_path,
3521    gdb::function_view<bool (symtab *)> callback)
3522 {
3523   const char *name_basename = lbasename (name);
3524   struct dwarf2_per_objfile *dwarf2_per_objfile
3525     = get_dwarf2_per_objfile (objfile);
3526
3527   /* The rule is CUs specify all the files, including those used by
3528      any TU, so there's no need to scan TUs here.  */
3529
3530   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3531     {
3532       /* We only need to look at symtabs not already expanded.  */
3533       if (per_cu->v.quick->compunit_symtab)
3534         continue;
3535
3536       quick_file_names *file_data = dw2_get_file_names (per_cu);
3537       if (file_data == NULL)
3538         continue;
3539
3540       for (int j = 0; j < file_data->num_file_names; ++j)
3541         {
3542           const char *this_name = file_data->file_names[j];
3543           const char *this_real_name;
3544
3545           if (compare_filenames_for_search (this_name, name))
3546             {
3547               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3548                                         callback))
3549                 return true;
3550               continue;
3551             }
3552
3553           /* Before we invoke realpath, which can get expensive when many
3554              files are involved, do a quick comparison of the basenames.  */
3555           if (! basenames_may_differ
3556               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3557             continue;
3558
3559           this_real_name = dw2_get_real_path (objfile, file_data, j);
3560           if (compare_filenames_for_search (this_real_name, name))
3561             {
3562               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3563                                         callback))
3564                 return true;
3565               continue;
3566             }
3567
3568           if (real_path != NULL)
3569             {
3570               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3571               gdb_assert (IS_ABSOLUTE_PATH (name));
3572               if (this_real_name != NULL
3573                   && FILENAME_CMP (real_path, this_real_name) == 0)
3574                 {
3575                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3576                                             callback))
3577                     return true;
3578                   continue;
3579                 }
3580             }
3581         }
3582     }
3583
3584   return false;
3585 }
3586
3587 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3588
3589 struct dw2_symtab_iterator
3590 {
3591   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3592   struct dwarf2_per_objfile *dwarf2_per_objfile;
3593   /* If set, only look for symbols that match that block.  Valid values are
3594      GLOBAL_BLOCK and STATIC_BLOCK.  */
3595   gdb::optional<block_enum> block_index;
3596   /* The kind of symbol we're looking for.  */
3597   domain_enum domain;
3598   /* The list of CUs from the index entry of the symbol,
3599      or NULL if not found.  */
3600   offset_type *vec;
3601   /* The next element in VEC to look at.  */
3602   int next;
3603   /* The number of elements in VEC, or zero if there is no match.  */
3604   int length;
3605   /* Have we seen a global version of the symbol?
3606      If so we can ignore all further global instances.
3607      This is to work around gold/15646, inefficient gold-generated
3608      indices.  */
3609   int global_seen;
3610 };
3611
3612 /* Initialize the index symtab iterator ITER.  */
3613
3614 static void
3615 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3616                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3617                       gdb::optional<block_enum> block_index,
3618                       domain_enum domain,
3619                       const char *name)
3620 {
3621   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3622   iter->block_index = block_index;
3623   iter->domain = domain;
3624   iter->next = 0;
3625   iter->global_seen = 0;
3626
3627   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3628
3629   /* index is NULL if OBJF_READNOW.  */
3630   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3631     iter->length = MAYBE_SWAP (*iter->vec);
3632   else
3633     {
3634       iter->vec = NULL;
3635       iter->length = 0;
3636     }
3637 }
3638
3639 /* Return the next matching CU or NULL if there are no more.  */
3640
3641 static struct dwarf2_per_cu_data *
3642 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3643 {
3644   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3645
3646   for ( ; iter->next < iter->length; ++iter->next)
3647     {
3648       offset_type cu_index_and_attrs =
3649         MAYBE_SWAP (iter->vec[iter->next + 1]);
3650       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3651       gdb_index_symbol_kind symbol_kind =
3652         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3653       /* Only check the symbol attributes if they're present.
3654          Indices prior to version 7 don't record them,
3655          and indices >= 7 may elide them for certain symbols
3656          (gold does this).  */
3657       int attrs_valid =
3658         (dwarf2_per_objfile->index_table->version >= 7
3659          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3660
3661       /* Don't crash on bad data.  */
3662       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3663                        + dwarf2_per_objfile->all_type_units.size ()))
3664         {
3665           complaint (_(".gdb_index entry has bad CU index"
3666                        " [in module %s]"),
3667                      objfile_name (dwarf2_per_objfile->objfile));
3668           continue;
3669         }
3670
3671       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3672
3673       /* Skip if already read in.  */
3674       if (per_cu->v.quick->compunit_symtab)
3675         continue;
3676
3677       /* Check static vs global.  */
3678       if (attrs_valid)
3679         {
3680           bool is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3681
3682           if (iter->block_index.has_value ())
3683             {
3684               bool want_static = *iter->block_index == STATIC_BLOCK;
3685
3686               if (is_static != want_static)
3687                 continue;
3688             }
3689
3690           /* Work around gold/15646.  */
3691           if (!is_static && iter->global_seen)
3692             continue;
3693           if (!is_static)
3694             iter->global_seen = 1;
3695         }
3696
3697       /* Only check the symbol's kind if it has one.  */
3698       if (attrs_valid)
3699         {
3700           switch (iter->domain)
3701             {
3702             case VAR_DOMAIN:
3703               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3704                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3705                   /* Some types are also in VAR_DOMAIN.  */
3706                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3707                 continue;
3708               break;
3709             case STRUCT_DOMAIN:
3710               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3711                 continue;
3712               break;
3713             case LABEL_DOMAIN:
3714               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3715                 continue;
3716               break;
3717             case MODULE_DOMAIN:
3718               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3719                 continue;
3720               break;
3721             default:
3722               break;
3723             }
3724         }
3725
3726       ++iter->next;
3727       return per_cu;
3728     }
3729
3730   return NULL;
3731 }
3732
3733 static struct compunit_symtab *
3734 dw2_lookup_symbol (struct objfile *objfile, block_enum block_index,
3735                    const char *name, domain_enum domain)
3736 {
3737   struct compunit_symtab *stab_best = NULL;
3738   struct dwarf2_per_objfile *dwarf2_per_objfile
3739     = get_dwarf2_per_objfile (objfile);
3740
3741   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3742
3743   struct dw2_symtab_iterator iter;
3744   struct dwarf2_per_cu_data *per_cu;
3745
3746   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, block_index, domain, name);
3747
3748   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3749     {
3750       struct symbol *sym, *with_opaque = NULL;
3751       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
3752       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3753       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3754
3755       sym = block_find_symbol (block, name, domain,
3756                                block_find_non_opaque_type_preferred,
3757                                &with_opaque);
3758
3759       /* Some caution must be observed with overloaded functions
3760          and methods, since the index will not contain any overload
3761          information (but NAME might contain it).  */
3762
3763       if (sym != NULL
3764           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3765         return stab;
3766       if (with_opaque != NULL
3767           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3768         stab_best = stab;
3769
3770       /* Keep looking through other CUs.  */
3771     }
3772
3773   return stab_best;
3774 }
3775
3776 static void
3777 dw2_print_stats (struct objfile *objfile)
3778 {
3779   struct dwarf2_per_objfile *dwarf2_per_objfile
3780     = get_dwarf2_per_objfile (objfile);
3781   int total = (dwarf2_per_objfile->all_comp_units.size ()
3782                + dwarf2_per_objfile->all_type_units.size ());
3783   int count = 0;
3784
3785   for (int i = 0; i < total; ++i)
3786     {
3787       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
3788
3789       if (!per_cu->v.quick->compunit_symtab)
3790         ++count;
3791     }
3792   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3793   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3794 }
3795
3796 /* This dumps minimal information about the index.
3797    It is called via "mt print objfiles".
3798    One use is to verify .gdb_index has been loaded by the
3799    gdb.dwarf2/gdb-index.exp testcase.  */
3800
3801 static void
3802 dw2_dump (struct objfile *objfile)
3803 {
3804   struct dwarf2_per_objfile *dwarf2_per_objfile
3805     = get_dwarf2_per_objfile (objfile);
3806
3807   gdb_assert (dwarf2_per_objfile->using_index);
3808   printf_filtered (".gdb_index:");
3809   if (dwarf2_per_objfile->index_table != NULL)
3810     {
3811       printf_filtered (" version %d\n",
3812                        dwarf2_per_objfile->index_table->version);
3813     }
3814   else
3815     printf_filtered (" faked for \"readnow\"\n");
3816   printf_filtered ("\n");
3817 }
3818
3819 static void
3820 dw2_expand_symtabs_for_function (struct objfile *objfile,
3821                                  const char *func_name)
3822 {
3823   struct dwarf2_per_objfile *dwarf2_per_objfile
3824     = get_dwarf2_per_objfile (objfile);
3825
3826   struct dw2_symtab_iterator iter;
3827   struct dwarf2_per_cu_data *per_cu;
3828
3829   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, {}, VAR_DOMAIN, func_name);
3830
3831   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3832     dw2_instantiate_symtab (per_cu, false);
3833
3834 }
3835
3836 static void
3837 dw2_expand_all_symtabs (struct objfile *objfile)
3838 {
3839   struct dwarf2_per_objfile *dwarf2_per_objfile
3840     = get_dwarf2_per_objfile (objfile);
3841   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
3842                      + dwarf2_per_objfile->all_type_units.size ());
3843
3844   for (int i = 0; i < total_units; ++i)
3845     {
3846       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
3847
3848       /* We don't want to directly expand a partial CU, because if we
3849          read it with the wrong language, then assertion failures can
3850          be triggered later on.  See PR symtab/23010.  So, tell
3851          dw2_instantiate_symtab to skip partial CUs -- any important
3852          partial CU will be read via DW_TAG_imported_unit anyway.  */
3853       dw2_instantiate_symtab (per_cu, true);
3854     }
3855 }
3856
3857 static void
3858 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3859                                   const char *fullname)
3860 {
3861   struct dwarf2_per_objfile *dwarf2_per_objfile
3862     = get_dwarf2_per_objfile (objfile);
3863
3864   /* We don't need to consider type units here.
3865      This is only called for examining code, e.g. expand_line_sal.
3866      There can be an order of magnitude (or more) more type units
3867      than comp units, and we avoid them if we can.  */
3868
3869   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3870     {
3871       /* We only need to look at symtabs not already expanded.  */
3872       if (per_cu->v.quick->compunit_symtab)
3873         continue;
3874
3875       quick_file_names *file_data = dw2_get_file_names (per_cu);
3876       if (file_data == NULL)
3877         continue;
3878
3879       for (int j = 0; j < file_data->num_file_names; ++j)
3880         {
3881           const char *this_fullname = file_data->file_names[j];
3882
3883           if (filename_cmp (this_fullname, fullname) == 0)
3884             {
3885               dw2_instantiate_symtab (per_cu, false);
3886               break;
3887             }
3888         }
3889     }
3890 }
3891
3892 static void
3893 dw2_map_matching_symbols
3894   (struct objfile *objfile,
3895    const lookup_name_info &name, domain_enum domain,
3896    int global,
3897    gdb::function_view<symbol_found_callback_ftype> callback,
3898    symbol_compare_ftype *ordered_compare)
3899 {
3900   /* Currently unimplemented; used for Ada.  The function can be called if the
3901      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3902      does not look for non-Ada symbols this function should just return.  */
3903 }
3904
3905 /* Starting from a search name, return the string that finds the upper
3906    bound of all strings that start with SEARCH_NAME in a sorted name
3907    list.  Returns the empty string to indicate that the upper bound is
3908    the end of the list.  */
3909
3910 static std::string
3911 make_sort_after_prefix_name (const char *search_name)
3912 {
3913   /* When looking to complete "func", we find the upper bound of all
3914      symbols that start with "func" by looking for where we'd insert
3915      the closest string that would follow "func" in lexicographical
3916      order.  Usually, that's "func"-with-last-character-incremented,
3917      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
3918      will be UTF-8 multi-byte sequences, but we can't be certain.
3919      Especially mind the 0xff character, which is a valid character in
3920      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
3921      rule out compilers allowing it in identifiers.  Note that
3922      conveniently, strcmp/strcasecmp are specified to compare
3923      characters interpreted as unsigned char.  So what we do is treat
3924      the whole string as a base 256 number composed of a sequence of
3925      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
3926      to 0, and carries 1 to the following more-significant position.
3927      If the very first character in SEARCH_NAME ends up incremented
3928      and carries/overflows, then the upper bound is the end of the
3929      list.  The string after the empty string is also the empty
3930      string.
3931
3932      Some examples of this operation:
3933
3934        SEARCH_NAME  => "+1" RESULT
3935
3936        "abc"              => "abd"
3937        "ab\xff"           => "ac"
3938        "\xff" "a" "\xff"  => "\xff" "b"
3939        "\xff"             => ""
3940        "\xff\xff"         => ""
3941        ""                 => ""
3942
3943      Then, with these symbols for example:
3944
3945       func
3946       func1
3947       fund
3948
3949      completing "func" looks for symbols between "func" and
3950      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
3951      which finds "func" and "func1", but not "fund".
3952
3953      And with:
3954
3955       funcÿ     (Latin1 'ÿ' [0xff])
3956       funcÿ1
3957       fund
3958
3959      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
3960      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
3961
3962      And with:
3963
3964       ÿÿ        (Latin1 'ÿ' [0xff])
3965       ÿÿ1
3966
3967      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
3968      the end of the list.
3969   */
3970   std::string after = search_name;
3971   while (!after.empty () && (unsigned char) after.back () == 0xff)
3972     after.pop_back ();
3973   if (!after.empty ())
3974     after.back () = (unsigned char) after.back () + 1;
3975   return after;
3976 }
3977
3978 /* See declaration.  */
3979
3980 std::pair<std::vector<name_component>::const_iterator,
3981           std::vector<name_component>::const_iterator>
3982 mapped_index_base::find_name_components_bounds
3983   (const lookup_name_info &lookup_name_without_params, language lang) const
3984 {
3985   auto *name_cmp
3986     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3987
3988   const char *lang_name
3989     = lookup_name_without_params.language_lookup_name (lang).c_str ();
3990
3991   /* Comparison function object for lower_bound that matches against a
3992      given symbol name.  */
3993   auto lookup_compare_lower = [&] (const name_component &elem,
3994                                    const char *name)
3995     {
3996       const char *elem_qualified = this->symbol_name_at (elem.idx);
3997       const char *elem_name = elem_qualified + elem.name_offset;
3998       return name_cmp (elem_name, name) < 0;
3999     };
4000
4001   /* Comparison function object for upper_bound that matches against a
4002      given symbol name.  */
4003   auto lookup_compare_upper = [&] (const char *name,
4004                                    const name_component &elem)
4005     {
4006       const char *elem_qualified = this->symbol_name_at (elem.idx);
4007       const char *elem_name = elem_qualified + elem.name_offset;
4008       return name_cmp (name, elem_name) < 0;
4009     };
4010
4011   auto begin = this->name_components.begin ();
4012   auto end = this->name_components.end ();
4013
4014   /* Find the lower bound.  */
4015   auto lower = [&] ()
4016     {
4017       if (lookup_name_without_params.completion_mode () && lang_name[0] == '\0')
4018         return begin;
4019       else
4020         return std::lower_bound (begin, end, lang_name, lookup_compare_lower);
4021     } ();
4022
4023   /* Find the upper bound.  */
4024   auto upper = [&] ()
4025     {
4026       if (lookup_name_without_params.completion_mode ())
4027         {
4028           /* In completion mode, we want UPPER to point past all
4029              symbols names that have the same prefix.  I.e., with
4030              these symbols, and completing "func":
4031
4032               function        << lower bound
4033               function1
4034               other_function  << upper bound
4035
4036              We find the upper bound by looking for the insertion
4037              point of "func"-with-last-character-incremented,
4038              i.e. "fund".  */
4039           std::string after = make_sort_after_prefix_name (lang_name);
4040           if (after.empty ())
4041             return end;
4042           return std::lower_bound (lower, end, after.c_str (),
4043                                    lookup_compare_lower);
4044         }
4045       else
4046         return std::upper_bound (lower, end, lang_name, lookup_compare_upper);
4047     } ();
4048
4049   return {lower, upper};
4050 }
4051
4052 /* See declaration.  */
4053
4054 void
4055 mapped_index_base::build_name_components ()
4056 {
4057   if (!this->name_components.empty ())
4058     return;
4059
4060   this->name_components_casing = case_sensitivity;
4061   auto *name_cmp
4062     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4063
4064   /* The code below only knows how to break apart components of C++
4065      symbol names (and other languages that use '::' as
4066      namespace/module separator) and Ada symbol names.  */
4067   auto count = this->symbol_name_count ();
4068   for (offset_type idx = 0; idx < count; idx++)
4069     {
4070       if (this->symbol_name_slot_invalid (idx))
4071         continue;
4072
4073       const char *name = this->symbol_name_at (idx);
4074
4075       /* Add each name component to the name component table.  */
4076       unsigned int previous_len = 0;
4077
4078       if (strstr (name, "::") != nullptr)
4079         {
4080           for (unsigned int current_len = cp_find_first_component (name);
4081                name[current_len] != '\0';
4082                current_len += cp_find_first_component (name + current_len))
4083             {
4084               gdb_assert (name[current_len] == ':');
4085               this->name_components.push_back ({previous_len, idx});
4086               /* Skip the '::'.  */
4087               current_len += 2;
4088               previous_len = current_len;
4089             }
4090         }
4091       else
4092         {
4093           /* Handle the Ada encoded (aka mangled) form here.  */
4094           for (const char *iter = strstr (name, "__");
4095                iter != nullptr;
4096                iter = strstr (iter, "__"))
4097             {
4098               this->name_components.push_back ({previous_len, idx});
4099               iter += 2;
4100               previous_len = iter - name;
4101             }
4102         }
4103
4104       this->name_components.push_back ({previous_len, idx});
4105     }
4106
4107   /* Sort name_components elements by name.  */
4108   auto name_comp_compare = [&] (const name_component &left,
4109                                 const name_component &right)
4110     {
4111       const char *left_qualified = this->symbol_name_at (left.idx);
4112       const char *right_qualified = this->symbol_name_at (right.idx);
4113
4114       const char *left_name = left_qualified + left.name_offset;
4115       const char *right_name = right_qualified + right.name_offset;
4116
4117       return name_cmp (left_name, right_name) < 0;
4118     };
4119
4120   std::sort (this->name_components.begin (),
4121              this->name_components.end (),
4122              name_comp_compare);
4123 }
4124
4125 /* Helper for dw2_expand_symtabs_matching that works with a
4126    mapped_index_base instead of the containing objfile.  This is split
4127    to a separate function in order to be able to unit test the
4128    name_components matching using a mock mapped_index_base.  For each
4129    symbol name that matches, calls MATCH_CALLBACK, passing it the
4130    symbol's index in the mapped_index_base symbol table.  */
4131
4132 static void
4133 dw2_expand_symtabs_matching_symbol
4134   (mapped_index_base &index,
4135    const lookup_name_info &lookup_name_in,
4136    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4137    enum search_domain kind,
4138    gdb::function_view<bool (offset_type)> match_callback)
4139 {
4140   lookup_name_info lookup_name_without_params
4141     = lookup_name_in.make_ignore_params ();
4142
4143   /* Build the symbol name component sorted vector, if we haven't
4144      yet.  */
4145   index.build_name_components ();
4146
4147   /* The same symbol may appear more than once in the range though.
4148      E.g., if we're looking for symbols that complete "w", and we have
4149      a symbol named "w1::w2", we'll find the two name components for
4150      that same symbol in the range.  To be sure we only call the
4151      callback once per symbol, we first collect the symbol name
4152      indexes that matched in a temporary vector and ignore
4153      duplicates.  */
4154   std::vector<offset_type> matches;
4155
4156   struct name_and_matcher
4157   {
4158     symbol_name_matcher_ftype *matcher;
4159     const std::string &name;
4160
4161     bool operator== (const name_and_matcher &other) const
4162     {
4163       return matcher == other.matcher && name == other.name;
4164     }
4165   };
4166
4167   /* A vector holding all the different symbol name matchers, for all
4168      languages.  */
4169   std::vector<name_and_matcher> matchers;
4170
4171   for (int i = 0; i < nr_languages; i++)
4172     {
4173       enum language lang_e = (enum language) i;
4174
4175       const language_defn *lang = language_def (lang_e);
4176       symbol_name_matcher_ftype *name_matcher
4177         = get_symbol_name_matcher (lang, lookup_name_without_params);
4178
4179       name_and_matcher key {
4180          name_matcher,
4181          lookup_name_without_params.language_lookup_name (lang_e)
4182       };
4183
4184       /* Don't insert the same comparison routine more than once.
4185          Note that we do this linear walk.  This is not a problem in
4186          practice because the number of supported languages is
4187          low.  */
4188       if (std::find (matchers.begin (), matchers.end (), key)
4189           != matchers.end ())
4190         continue;
4191       matchers.push_back (std::move (key));
4192
4193       auto bounds
4194         = index.find_name_components_bounds (lookup_name_without_params,
4195                                              lang_e);
4196
4197       /* Now for each symbol name in range, check to see if we have a name
4198          match, and if so, call the MATCH_CALLBACK callback.  */
4199
4200       for (; bounds.first != bounds.second; ++bounds.first)
4201         {
4202           const char *qualified = index.symbol_name_at (bounds.first->idx);
4203
4204           if (!name_matcher (qualified, lookup_name_without_params, NULL)
4205               || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4206             continue;
4207
4208           matches.push_back (bounds.first->idx);
4209         }
4210     }
4211
4212   std::sort (matches.begin (), matches.end ());
4213
4214   /* Finally call the callback, once per match.  */
4215   ULONGEST prev = -1;
4216   for (offset_type idx : matches)
4217     {
4218       if (prev != idx)
4219         {
4220           if (!match_callback (idx))
4221             break;
4222           prev = idx;
4223         }
4224     }
4225
4226   /* Above we use a type wider than idx's for 'prev', since 0 and
4227      (offset_type)-1 are both possible values.  */
4228   static_assert (sizeof (prev) > sizeof (offset_type), "");
4229 }
4230
4231 #if GDB_SELF_TEST
4232
4233 namespace selftests { namespace dw2_expand_symtabs_matching {
4234
4235 /* A mock .gdb_index/.debug_names-like name index table, enough to
4236    exercise dw2_expand_symtabs_matching_symbol, which works with the
4237    mapped_index_base interface.  Builds an index from the symbol list
4238    passed as parameter to the constructor.  */
4239 class mock_mapped_index : public mapped_index_base
4240 {
4241 public:
4242   mock_mapped_index (gdb::array_view<const char *> symbols)
4243     : m_symbol_table (symbols)
4244   {}
4245
4246   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4247
4248   /* Return the number of names in the symbol table.  */
4249   size_t symbol_name_count () const override
4250   {
4251     return m_symbol_table.size ();
4252   }
4253
4254   /* Get the name of the symbol at IDX in the symbol table.  */
4255   const char *symbol_name_at (offset_type idx) const override
4256   {
4257     return m_symbol_table[idx];
4258   }
4259
4260 private:
4261   gdb::array_view<const char *> m_symbol_table;
4262 };
4263
4264 /* Convenience function that converts a NULL pointer to a "<null>"
4265    string, to pass to print routines.  */
4266
4267 static const char *
4268 string_or_null (const char *str)
4269 {
4270   return str != NULL ? str : "<null>";
4271 }
4272
4273 /* Check if a lookup_name_info built from
4274    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4275    index.  EXPECTED_LIST is the list of expected matches, in expected
4276    matching order.  If no match expected, then an empty list is
4277    specified.  Returns true on success.  On failure prints a warning
4278    indicating the file:line that failed, and returns false.  */
4279
4280 static bool
4281 check_match (const char *file, int line,
4282              mock_mapped_index &mock_index,
4283              const char *name, symbol_name_match_type match_type,
4284              bool completion_mode,
4285              std::initializer_list<const char *> expected_list)
4286 {
4287   lookup_name_info lookup_name (name, match_type, completion_mode);
4288
4289   bool matched = true;
4290
4291   auto mismatch = [&] (const char *expected_str,
4292                        const char *got)
4293   {
4294     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4295                "expected=\"%s\", got=\"%s\"\n"),
4296              file, line,
4297              (match_type == symbol_name_match_type::FULL
4298               ? "FULL" : "WILD"),
4299              name, string_or_null (expected_str), string_or_null (got));
4300     matched = false;
4301   };
4302
4303   auto expected_it = expected_list.begin ();
4304   auto expected_end = expected_list.end ();
4305
4306   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4307                                       NULL, ALL_DOMAIN,
4308                                       [&] (offset_type idx)
4309   {
4310     const char *matched_name = mock_index.symbol_name_at (idx);
4311     const char *expected_str
4312       = expected_it == expected_end ? NULL : *expected_it++;
4313
4314     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4315       mismatch (expected_str, matched_name);
4316     return true;
4317   });
4318
4319   const char *expected_str
4320   = expected_it == expected_end ? NULL : *expected_it++;
4321   if (expected_str != NULL)
4322     mismatch (expected_str, NULL);
4323
4324   return matched;
4325 }
4326
4327 /* The symbols added to the mock mapped_index for testing (in
4328    canonical form).  */
4329 static const char *test_symbols[] = {
4330   "function",
4331   "std::bar",
4332   "std::zfunction",
4333   "std::zfunction2",
4334   "w1::w2",
4335   "ns::foo<char*>",
4336   "ns::foo<int>",
4337   "ns::foo<long>",
4338   "ns2::tmpl<int>::foo2",
4339   "(anonymous namespace)::A::B::C",
4340
4341   /* These are used to check that the increment-last-char in the
4342      matching algorithm for completion doesn't match "t1_fund" when
4343      completing "t1_func".  */
4344   "t1_func",
4345   "t1_func1",
4346   "t1_fund",
4347   "t1_fund1",
4348
4349   /* A UTF-8 name with multi-byte sequences to make sure that
4350      cp-name-parser understands this as a single identifier ("função"
4351      is "function" in PT).  */
4352   u8"u8função",
4353
4354   /* \377 (0xff) is Latin1 'ÿ'.  */
4355   "yfunc\377",
4356
4357   /* \377 (0xff) is Latin1 'ÿ'.  */
4358   "\377",
4359   "\377\377123",
4360
4361   /* A name with all sorts of complications.  Starts with "z" to make
4362      it easier for the completion tests below.  */
4363 #define Z_SYM_NAME \
4364   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4365     "::tuple<(anonymous namespace)::ui*, " \
4366     "std::default_delete<(anonymous namespace)::ui>, void>"
4367
4368   Z_SYM_NAME
4369 };
4370
4371 /* Returns true if the mapped_index_base::find_name_component_bounds
4372    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4373    in completion mode.  */
4374
4375 static bool
4376 check_find_bounds_finds (mapped_index_base &index,
4377                          const char *search_name,
4378                          gdb::array_view<const char *> expected_syms)
4379 {
4380   lookup_name_info lookup_name (search_name,
4381                                 symbol_name_match_type::FULL, true);
4382
4383   auto bounds = index.find_name_components_bounds (lookup_name,
4384                                                    language_cplus);
4385
4386   size_t distance = std::distance (bounds.first, bounds.second);
4387   if (distance != expected_syms.size ())
4388     return false;
4389
4390   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4391     {
4392       auto nc_elem = bounds.first + exp_elem;
4393       const char *qualified = index.symbol_name_at (nc_elem->idx);
4394       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4395         return false;
4396     }
4397
4398   return true;
4399 }
4400
4401 /* Test the lower-level mapped_index::find_name_component_bounds
4402    method.  */
4403
4404 static void
4405 test_mapped_index_find_name_component_bounds ()
4406 {
4407   mock_mapped_index mock_index (test_symbols);
4408
4409   mock_index.build_name_components ();
4410
4411   /* Test the lower-level mapped_index::find_name_component_bounds
4412      method in completion mode.  */
4413   {
4414     static const char *expected_syms[] = {
4415       "t1_func",
4416       "t1_func1",
4417     };
4418
4419     SELF_CHECK (check_find_bounds_finds (mock_index,
4420                                          "t1_func", expected_syms));
4421   }
4422
4423   /* Check that the increment-last-char in the name matching algorithm
4424      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4425   {
4426     static const char *expected_syms1[] = {
4427       "\377",
4428       "\377\377123",
4429     };
4430     SELF_CHECK (check_find_bounds_finds (mock_index,
4431                                          "\377", expected_syms1));
4432
4433     static const char *expected_syms2[] = {
4434       "\377\377123",
4435     };
4436     SELF_CHECK (check_find_bounds_finds (mock_index,
4437                                          "\377\377", expected_syms2));
4438   }
4439 }
4440
4441 /* Test dw2_expand_symtabs_matching_symbol.  */
4442
4443 static void
4444 test_dw2_expand_symtabs_matching_symbol ()
4445 {
4446   mock_mapped_index mock_index (test_symbols);
4447
4448   /* We let all tests run until the end even if some fails, for debug
4449      convenience.  */
4450   bool any_mismatch = false;
4451
4452   /* Create the expected symbols list (an initializer_list).  Needed
4453      because lists have commas, and we need to pass them to CHECK,
4454      which is a macro.  */
4455 #define EXPECT(...) { __VA_ARGS__ }
4456
4457   /* Wrapper for check_match that passes down the current
4458      __FILE__/__LINE__.  */
4459 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4460   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4461                                 mock_index,                             \
4462                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4463                                 EXPECTED_LIST)
4464
4465   /* Identity checks.  */
4466   for (const char *sym : test_symbols)
4467     {
4468       /* Should be able to match all existing symbols.  */
4469       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4470                    EXPECT (sym));
4471
4472       /* Should be able to match all existing symbols with
4473          parameters.  */
4474       std::string with_params = std::string (sym) + "(int)";
4475       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4476                    EXPECT (sym));
4477
4478       /* Should be able to match all existing symbols with
4479          parameters and qualifiers.  */
4480       with_params = std::string (sym) + " ( int ) const";
4481       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4482                    EXPECT (sym));
4483
4484       /* This should really find sym, but cp-name-parser.y doesn't
4485          know about lvalue/rvalue qualifiers yet.  */
4486       with_params = std::string (sym) + " ( int ) &&";
4487       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4488                    {});
4489     }
4490
4491   /* Check that the name matching algorithm for completion doesn't get
4492      confused with Latin1 'ÿ' / 0xff.  */
4493   {
4494     static const char str[] = "\377";
4495     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4496                  EXPECT ("\377", "\377\377123"));
4497   }
4498
4499   /* Check that the increment-last-char in the matching algorithm for
4500      completion doesn't match "t1_fund" when completing "t1_func".  */
4501   {
4502     static const char str[] = "t1_func";
4503     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4504                  EXPECT ("t1_func", "t1_func1"));
4505   }
4506
4507   /* Check that completion mode works at each prefix of the expected
4508      symbol name.  */
4509   {
4510     static const char str[] = "function(int)";
4511     size_t len = strlen (str);
4512     std::string lookup;
4513
4514     for (size_t i = 1; i < len; i++)
4515       {
4516         lookup.assign (str, i);
4517         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4518                      EXPECT ("function"));
4519       }
4520   }
4521
4522   /* While "w" is a prefix of both components, the match function
4523      should still only be called once.  */
4524   {
4525     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4526                  EXPECT ("w1::w2"));
4527     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4528                  EXPECT ("w1::w2"));
4529   }
4530
4531   /* Same, with a "complicated" symbol.  */
4532   {
4533     static const char str[] = Z_SYM_NAME;
4534     size_t len = strlen (str);
4535     std::string lookup;
4536
4537     for (size_t i = 1; i < len; i++)
4538       {
4539         lookup.assign (str, i);
4540         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4541                      EXPECT (Z_SYM_NAME));
4542       }
4543   }
4544
4545   /* In FULL mode, an incomplete symbol doesn't match.  */
4546   {
4547     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4548                  {});
4549   }
4550
4551   /* A complete symbol with parameters matches any overload, since the
4552      index has no overload info.  */
4553   {
4554     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4555                  EXPECT ("std::zfunction", "std::zfunction2"));
4556     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4557                  EXPECT ("std::zfunction", "std::zfunction2"));
4558     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4559                  EXPECT ("std::zfunction", "std::zfunction2"));
4560   }
4561
4562   /* Check that whitespace is ignored appropriately.  A symbol with a
4563      template argument list. */
4564   {
4565     static const char expected[] = "ns::foo<int>";
4566     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4567                  EXPECT (expected));
4568     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4569                  EXPECT (expected));
4570   }
4571
4572   /* Check that whitespace is ignored appropriately.  A symbol with a
4573      template argument list that includes a pointer.  */
4574   {
4575     static const char expected[] = "ns::foo<char*>";
4576     /* Try both completion and non-completion modes.  */
4577     static const bool completion_mode[2] = {false, true};
4578     for (size_t i = 0; i < 2; i++)
4579       {
4580         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4581                      completion_mode[i], EXPECT (expected));
4582         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4583                      completion_mode[i], EXPECT (expected));
4584
4585         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4586                      completion_mode[i], EXPECT (expected));
4587         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4588                      completion_mode[i], EXPECT (expected));
4589       }
4590   }
4591
4592   {
4593     /* Check method qualifiers are ignored.  */
4594     static const char expected[] = "ns::foo<char*>";
4595     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4596                  symbol_name_match_type::FULL, true, EXPECT (expected));
4597     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4598                  symbol_name_match_type::FULL, true, EXPECT (expected));
4599     CHECK_MATCH ("foo < char * >  ( int ) const",
4600                  symbol_name_match_type::WILD, true, EXPECT (expected));
4601     CHECK_MATCH ("foo < char * >  ( int ) &&",
4602                  symbol_name_match_type::WILD, true, EXPECT (expected));
4603   }
4604
4605   /* Test lookup names that don't match anything.  */
4606   {
4607     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4608                  {});
4609
4610     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4611                  {});
4612   }
4613
4614   /* Some wild matching tests, exercising "(anonymous namespace)",
4615      which should not be confused with a parameter list.  */
4616   {
4617     static const char *syms[] = {
4618       "A::B::C",
4619       "B::C",
4620       "C",
4621       "A :: B :: C ( int )",
4622       "B :: C ( int )",
4623       "C ( int )",
4624     };
4625
4626     for (const char *s : syms)
4627       {
4628         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4629                      EXPECT ("(anonymous namespace)::A::B::C"));
4630       }
4631   }
4632
4633   {
4634     static const char expected[] = "ns2::tmpl<int>::foo2";
4635     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4636                  EXPECT (expected));
4637     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4638                  EXPECT (expected));
4639   }
4640
4641   SELF_CHECK (!any_mismatch);
4642
4643 #undef EXPECT
4644 #undef CHECK_MATCH
4645 }
4646
4647 static void
4648 run_test ()
4649 {
4650   test_mapped_index_find_name_component_bounds ();
4651   test_dw2_expand_symtabs_matching_symbol ();
4652 }
4653
4654 }} // namespace selftests::dw2_expand_symtabs_matching
4655
4656 #endif /* GDB_SELF_TEST */
4657
4658 /* If FILE_MATCHER is NULL or if PER_CU has
4659    dwarf2_per_cu_quick_data::MARK set (see
4660    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4661    EXPANSION_NOTIFY on it.  */
4662
4663 static void
4664 dw2_expand_symtabs_matching_one
4665   (struct dwarf2_per_cu_data *per_cu,
4666    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4667    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4668 {
4669   if (file_matcher == NULL || per_cu->v.quick->mark)
4670     {
4671       bool symtab_was_null
4672         = (per_cu->v.quick->compunit_symtab == NULL);
4673
4674       dw2_instantiate_symtab (per_cu, false);
4675
4676       if (expansion_notify != NULL
4677           && symtab_was_null
4678           && per_cu->v.quick->compunit_symtab != NULL)
4679         expansion_notify (per_cu->v.quick->compunit_symtab);
4680     }
4681 }
4682
4683 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4684    matched, to expand corresponding CUs that were marked.  IDX is the
4685    index of the symbol name that matched.  */
4686
4687 static void
4688 dw2_expand_marked_cus
4689   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
4690    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4691    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4692    search_domain kind)
4693 {
4694   offset_type *vec, vec_len, vec_idx;
4695   bool global_seen = false;
4696   mapped_index &index = *dwarf2_per_objfile->index_table;
4697
4698   vec = (offset_type *) (index.constant_pool
4699                          + MAYBE_SWAP (index.symbol_table[idx].vec));
4700   vec_len = MAYBE_SWAP (vec[0]);
4701   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4702     {
4703       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4704       /* This value is only valid for index versions >= 7.  */
4705       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4706       gdb_index_symbol_kind symbol_kind =
4707         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4708       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4709       /* Only check the symbol attributes if they're present.
4710          Indices prior to version 7 don't record them,
4711          and indices >= 7 may elide them for certain symbols
4712          (gold does this).  */
4713       int attrs_valid =
4714         (index.version >= 7
4715          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4716
4717       /* Work around gold/15646.  */
4718       if (attrs_valid)
4719         {
4720           if (!is_static && global_seen)
4721             continue;
4722           if (!is_static)
4723             global_seen = true;
4724         }
4725
4726       /* Only check the symbol's kind if it has one.  */
4727       if (attrs_valid)
4728         {
4729           switch (kind)
4730             {
4731             case VARIABLES_DOMAIN:
4732               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4733                 continue;
4734               break;
4735             case FUNCTIONS_DOMAIN:
4736               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4737                 continue;
4738               break;
4739             case TYPES_DOMAIN:
4740               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4741                 continue;
4742               break;
4743             case MODULES_DOMAIN:
4744               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4745                 continue;
4746               break;
4747             default:
4748               break;
4749             }
4750         }
4751
4752       /* Don't crash on bad data.  */
4753       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
4754                        + dwarf2_per_objfile->all_type_units.size ()))
4755         {
4756           complaint (_(".gdb_index entry has bad CU index"
4757                        " [in module %s]"),
4758                        objfile_name (dwarf2_per_objfile->objfile));
4759           continue;
4760         }
4761
4762       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
4763       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
4764                                        expansion_notify);
4765     }
4766 }
4767
4768 /* If FILE_MATCHER is non-NULL, set all the
4769    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
4770    that match FILE_MATCHER.  */
4771
4772 static void
4773 dw_expand_symtabs_matching_file_matcher
4774   (struct dwarf2_per_objfile *dwarf2_per_objfile,
4775    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
4776 {
4777   if (file_matcher == NULL)
4778     return;
4779
4780   objfile *const objfile = dwarf2_per_objfile->objfile;
4781
4782   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4783                                             htab_eq_pointer,
4784                                             NULL, xcalloc, xfree));
4785   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4786                                                 htab_eq_pointer,
4787                                                 NULL, xcalloc, xfree));
4788
4789   /* The rule is CUs specify all the files, including those used by
4790      any TU, so there's no need to scan TUs here.  */
4791
4792   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4793     {
4794       QUIT;
4795
4796       per_cu->v.quick->mark = 0;
4797
4798       /* We only need to look at symtabs not already expanded.  */
4799       if (per_cu->v.quick->compunit_symtab)
4800         continue;
4801
4802       quick_file_names *file_data = dw2_get_file_names (per_cu);
4803       if (file_data == NULL)
4804         continue;
4805
4806       if (htab_find (visited_not_found.get (), file_data) != NULL)
4807         continue;
4808       else if (htab_find (visited_found.get (), file_data) != NULL)
4809         {
4810           per_cu->v.quick->mark = 1;
4811           continue;
4812         }
4813
4814       for (int j = 0; j < file_data->num_file_names; ++j)
4815         {
4816           const char *this_real_name;
4817
4818           if (file_matcher (file_data->file_names[j], false))
4819             {
4820               per_cu->v.quick->mark = 1;
4821               break;
4822             }
4823
4824           /* Before we invoke realpath, which can get expensive when many
4825              files are involved, do a quick comparison of the basenames.  */
4826           if (!basenames_may_differ
4827               && !file_matcher (lbasename (file_data->file_names[j]),
4828                                 true))
4829             continue;
4830
4831           this_real_name = dw2_get_real_path (objfile, file_data, j);
4832           if (file_matcher (this_real_name, false))
4833             {
4834               per_cu->v.quick->mark = 1;
4835               break;
4836             }
4837         }
4838
4839       void **slot = htab_find_slot (per_cu->v.quick->mark
4840                                     ? visited_found.get ()
4841                                     : visited_not_found.get (),
4842                                     file_data, INSERT);
4843       *slot = file_data;
4844     }
4845 }
4846
4847 static void
4848 dw2_expand_symtabs_matching
4849   (struct objfile *objfile,
4850    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4851    const lookup_name_info &lookup_name,
4852    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4853    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4854    enum search_domain kind)
4855 {
4856   struct dwarf2_per_objfile *dwarf2_per_objfile
4857     = get_dwarf2_per_objfile (objfile);
4858
4859   /* index_table is NULL if OBJF_READNOW.  */
4860   if (!dwarf2_per_objfile->index_table)
4861     return;
4862
4863   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
4864
4865   mapped_index &index = *dwarf2_per_objfile->index_table;
4866
4867   dw2_expand_symtabs_matching_symbol (index, lookup_name,
4868                                       symbol_matcher,
4869                                       kind, [&] (offset_type idx)
4870     {
4871       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
4872                              expansion_notify, kind);
4873       return true;
4874     });
4875 }
4876
4877 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4878    symtab.  */
4879
4880 static struct compunit_symtab *
4881 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4882                                           CORE_ADDR pc)
4883 {
4884   int i;
4885
4886   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4887       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4888     return cust;
4889
4890   if (cust->includes == NULL)
4891     return NULL;
4892
4893   for (i = 0; cust->includes[i]; ++i)
4894     {
4895       struct compunit_symtab *s = cust->includes[i];
4896
4897       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4898       if (s != NULL)
4899         return s;
4900     }
4901
4902   return NULL;
4903 }
4904
4905 static struct compunit_symtab *
4906 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4907                                   struct bound_minimal_symbol msymbol,
4908                                   CORE_ADDR pc,
4909                                   struct obj_section *section,
4910                                   int warn_if_readin)
4911 {
4912   struct dwarf2_per_cu_data *data;
4913   struct compunit_symtab *result;
4914
4915   if (!objfile->partial_symtabs->psymtabs_addrmap)
4916     return NULL;
4917
4918   CORE_ADDR baseaddr = objfile->text_section_offset ();
4919   data = (struct dwarf2_per_cu_data *) addrmap_find
4920     (objfile->partial_symtabs->psymtabs_addrmap, pc - baseaddr);
4921   if (!data)
4922     return NULL;
4923
4924   if (warn_if_readin && data->v.quick->compunit_symtab)
4925     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4926              paddress (get_objfile_arch (objfile), pc));
4927
4928   result
4929     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
4930                                                                         false),
4931                                                 pc);
4932   gdb_assert (result != NULL);
4933   return result;
4934 }
4935
4936 static void
4937 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4938                           void *data, int need_fullname)
4939 {
4940   struct dwarf2_per_objfile *dwarf2_per_objfile
4941     = get_dwarf2_per_objfile (objfile);
4942
4943   if (!dwarf2_per_objfile->filenames_cache)
4944     {
4945       dwarf2_per_objfile->filenames_cache.emplace ();
4946
4947       htab_up visited (htab_create_alloc (10,
4948                                           htab_hash_pointer, htab_eq_pointer,
4949                                           NULL, xcalloc, xfree));
4950
4951       /* The rule is CUs specify all the files, including those used
4952          by any TU, so there's no need to scan TUs here.  We can
4953          ignore file names coming from already-expanded CUs.  */
4954
4955       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4956         {
4957           if (per_cu->v.quick->compunit_symtab)
4958             {
4959               void **slot = htab_find_slot (visited.get (),
4960                                             per_cu->v.quick->file_names,
4961                                             INSERT);
4962
4963               *slot = per_cu->v.quick->file_names;
4964             }
4965         }
4966
4967       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4968         {
4969           /* We only need to look at symtabs not already expanded.  */
4970           if (per_cu->v.quick->compunit_symtab)
4971             continue;
4972
4973           quick_file_names *file_data = dw2_get_file_names (per_cu);
4974           if (file_data == NULL)
4975             continue;
4976
4977           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
4978           if (*slot)
4979             {
4980               /* Already visited.  */
4981               continue;
4982             }
4983           *slot = file_data;
4984
4985           for (int j = 0; j < file_data->num_file_names; ++j)
4986             {
4987               const char *filename = file_data->file_names[j];
4988               dwarf2_per_objfile->filenames_cache->seen (filename);
4989             }
4990         }
4991     }
4992
4993   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4994     {
4995       gdb::unique_xmalloc_ptr<char> this_real_name;
4996
4997       if (need_fullname)
4998         this_real_name = gdb_realpath (filename);
4999       (*fun) (filename, this_real_name.get (), data);
5000     });
5001 }
5002
5003 static int
5004 dw2_has_symbols (struct objfile *objfile)
5005 {
5006   return 1;
5007 }
5008
5009 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5010 {
5011   dw2_has_symbols,
5012   dw2_find_last_source_symtab,
5013   dw2_forget_cached_source_info,
5014   dw2_map_symtabs_matching_filename,
5015   dw2_lookup_symbol,
5016   dw2_print_stats,
5017   dw2_dump,
5018   dw2_expand_symtabs_for_function,
5019   dw2_expand_all_symtabs,
5020   dw2_expand_symtabs_with_fullname,
5021   dw2_map_matching_symbols,
5022   dw2_expand_symtabs_matching,
5023   dw2_find_pc_sect_compunit_symtab,
5024   NULL,
5025   dw2_map_symbol_filenames
5026 };
5027
5028 /* DWARF-5 debug_names reader.  */
5029
5030 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5031 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5032
5033 /* A helper function that reads the .debug_names section in SECTION
5034    and fills in MAP.  FILENAME is the name of the file containing the
5035    section; it is used for error reporting.
5036
5037    Returns true if all went well, false otherwise.  */
5038
5039 static bool
5040 read_debug_names_from_section (struct objfile *objfile,
5041                                const char *filename,
5042                                struct dwarf2_section_info *section,
5043                                mapped_debug_names &map)
5044 {
5045   if (section->empty ())
5046     return false;
5047
5048   /* Older elfutils strip versions could keep the section in the main
5049      executable while splitting it for the separate debug info file.  */
5050   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5051     return false;
5052
5053   section->read (objfile);
5054
5055   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5056
5057   const gdb_byte *addr = section->buffer;
5058
5059   bfd *const abfd = section->get_bfd_owner ();
5060
5061   unsigned int bytes_read;
5062   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5063   addr += bytes_read;
5064
5065   map.dwarf5_is_dwarf64 = bytes_read != 4;
5066   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5067   if (bytes_read + length != section->size)
5068     {
5069       /* There may be multiple per-CU indices.  */
5070       warning (_("Section .debug_names in %s length %s does not match "
5071                  "section length %s, ignoring .debug_names."),
5072                filename, plongest (bytes_read + length),
5073                pulongest (section->size));
5074       return false;
5075     }
5076
5077   /* The version number.  */
5078   uint16_t version = read_2_bytes (abfd, addr);
5079   addr += 2;
5080   if (version != 5)
5081     {
5082       warning (_("Section .debug_names in %s has unsupported version %d, "
5083                  "ignoring .debug_names."),
5084                filename, version);
5085       return false;
5086     }
5087
5088   /* Padding.  */
5089   uint16_t padding = read_2_bytes (abfd, addr);
5090   addr += 2;
5091   if (padding != 0)
5092     {
5093       warning (_("Section .debug_names in %s has unsupported padding %d, "
5094                  "ignoring .debug_names."),
5095                filename, padding);
5096       return false;
5097     }
5098
5099   /* comp_unit_count - The number of CUs in the CU list.  */
5100   map.cu_count = read_4_bytes (abfd, addr);
5101   addr += 4;
5102
5103   /* local_type_unit_count - The number of TUs in the local TU
5104      list.  */
5105   map.tu_count = read_4_bytes (abfd, addr);
5106   addr += 4;
5107
5108   /* foreign_type_unit_count - The number of TUs in the foreign TU
5109      list.  */
5110   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5111   addr += 4;
5112   if (foreign_tu_count != 0)
5113     {
5114       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5115                  "ignoring .debug_names."),
5116                filename, static_cast<unsigned long> (foreign_tu_count));
5117       return false;
5118     }
5119
5120   /* bucket_count - The number of hash buckets in the hash lookup
5121      table.  */
5122   map.bucket_count = read_4_bytes (abfd, addr);
5123   addr += 4;
5124
5125   /* name_count - The number of unique names in the index.  */
5126   map.name_count = read_4_bytes (abfd, addr);
5127   addr += 4;
5128
5129   /* abbrev_table_size - The size in bytes of the abbreviations
5130      table.  */
5131   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5132   addr += 4;
5133
5134   /* augmentation_string_size - The size in bytes of the augmentation
5135      string.  This value is rounded up to a multiple of 4.  */
5136   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5137   addr += 4;
5138   map.augmentation_is_gdb = ((augmentation_string_size
5139                               == sizeof (dwarf5_augmentation))
5140                              && memcmp (addr, dwarf5_augmentation,
5141                                         sizeof (dwarf5_augmentation)) == 0);
5142   augmentation_string_size += (-augmentation_string_size) & 3;
5143   addr += augmentation_string_size;
5144
5145   /* List of CUs */
5146   map.cu_table_reordered = addr;
5147   addr += map.cu_count * map.offset_size;
5148
5149   /* List of Local TUs */
5150   map.tu_table_reordered = addr;
5151   addr += map.tu_count * map.offset_size;
5152
5153   /* Hash Lookup Table */
5154   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5155   addr += map.bucket_count * 4;
5156   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5157   addr += map.name_count * 4;
5158
5159   /* Name Table */
5160   map.name_table_string_offs_reordered = addr;
5161   addr += map.name_count * map.offset_size;
5162   map.name_table_entry_offs_reordered = addr;
5163   addr += map.name_count * map.offset_size;
5164
5165   const gdb_byte *abbrev_table_start = addr;
5166   for (;;)
5167     {
5168       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5169       addr += bytes_read;
5170       if (index_num == 0)
5171         break;
5172
5173       const auto insertpair
5174         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5175       if (!insertpair.second)
5176         {
5177           warning (_("Section .debug_names in %s has duplicate index %s, "
5178                      "ignoring .debug_names."),
5179                    filename, pulongest (index_num));
5180           return false;
5181         }
5182       mapped_debug_names::index_val &indexval = insertpair.first->second;
5183       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5184       addr += bytes_read;
5185
5186       for (;;)
5187         {
5188           mapped_debug_names::index_val::attr attr;
5189           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5190           addr += bytes_read;
5191           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5192           addr += bytes_read;
5193           if (attr.form == DW_FORM_implicit_const)
5194             {
5195               attr.implicit_const = read_signed_leb128 (abfd, addr,
5196                                                         &bytes_read);
5197               addr += bytes_read;
5198             }
5199           if (attr.dw_idx == 0 && attr.form == 0)
5200             break;
5201           indexval.attr_vec.push_back (std::move (attr));
5202         }
5203     }
5204   if (addr != abbrev_table_start + abbrev_table_size)
5205     {
5206       warning (_("Section .debug_names in %s has abbreviation_table "
5207                  "of size %s vs. written as %u, ignoring .debug_names."),
5208                filename, plongest (addr - abbrev_table_start),
5209                abbrev_table_size);
5210       return false;
5211     }
5212   map.entry_pool = addr;
5213
5214   return true;
5215 }
5216
5217 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5218    list.  */
5219
5220 static void
5221 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5222                                   const mapped_debug_names &map,
5223                                   dwarf2_section_info &section,
5224                                   bool is_dwz)
5225 {
5226   sect_offset sect_off_prev;
5227   for (uint32_t i = 0; i <= map.cu_count; ++i)
5228     {
5229       sect_offset sect_off_next;
5230       if (i < map.cu_count)
5231         {
5232           sect_off_next
5233             = (sect_offset) (extract_unsigned_integer
5234                              (map.cu_table_reordered + i * map.offset_size,
5235                               map.offset_size,
5236                               map.dwarf5_byte_order));
5237         }
5238       else
5239         sect_off_next = (sect_offset) section.size;
5240       if (i >= 1)
5241         {
5242           const ULONGEST length = sect_off_next - sect_off_prev;
5243           dwarf2_per_cu_data *per_cu
5244             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5245                                          sect_off_prev, length);
5246           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5247         }
5248       sect_off_prev = sect_off_next;
5249     }
5250 }
5251
5252 /* Read the CU list from the mapped index, and use it to create all
5253    the CU objects for this dwarf2_per_objfile.  */
5254
5255 static void
5256 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5257                              const mapped_debug_names &map,
5258                              const mapped_debug_names &dwz_map)
5259 {
5260   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5261   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5262
5263   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5264                                     dwarf2_per_objfile->info,
5265                                     false /* is_dwz */);
5266
5267   if (dwz_map.cu_count == 0)
5268     return;
5269
5270   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5271   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5272                                     true /* is_dwz */);
5273 }
5274
5275 /* Read .debug_names.  If everything went ok, initialize the "quick"
5276    elements of all the CUs and return true.  Otherwise, return false.  */
5277
5278 static bool
5279 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5280 {
5281   std::unique_ptr<mapped_debug_names> map
5282     (new mapped_debug_names (dwarf2_per_objfile));
5283   mapped_debug_names dwz_map (dwarf2_per_objfile);
5284   struct objfile *objfile = dwarf2_per_objfile->objfile;
5285
5286   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5287                                       &dwarf2_per_objfile->debug_names,
5288                                       *map))
5289     return false;
5290
5291   /* Don't use the index if it's empty.  */
5292   if (map->name_count == 0)
5293     return false;
5294
5295   /* If there is a .dwz file, read it so we can get its CU list as
5296      well.  */
5297   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5298   if (dwz != NULL)
5299     {
5300       if (!read_debug_names_from_section (objfile,
5301                                           bfd_get_filename (dwz->dwz_bfd.get ()),
5302                                           &dwz->debug_names, dwz_map))
5303         {
5304           warning (_("could not read '.debug_names' section from %s; skipping"),
5305                    bfd_get_filename (dwz->dwz_bfd.get ()));
5306           return false;
5307         }
5308     }
5309
5310   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5311
5312   if (map->tu_count != 0)
5313     {
5314       /* We can only handle a single .debug_types when we have an
5315          index.  */
5316       if (dwarf2_per_objfile->types.size () != 1)
5317         return false;
5318
5319       dwarf2_section_info *section = &dwarf2_per_objfile->types[0];
5320
5321       create_signatured_type_table_from_debug_names
5322         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5323     }
5324
5325   create_addrmap_from_aranges (dwarf2_per_objfile,
5326                                &dwarf2_per_objfile->debug_aranges);
5327
5328   dwarf2_per_objfile->debug_names_table = std::move (map);
5329   dwarf2_per_objfile->using_index = 1;
5330   dwarf2_per_objfile->quick_file_names_table =
5331     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5332
5333   return true;
5334 }
5335
5336 /* Type used to manage iterating over all CUs looking for a symbol for
5337    .debug_names.  */
5338
5339 class dw2_debug_names_iterator
5340 {
5341 public:
5342   dw2_debug_names_iterator (const mapped_debug_names &map,
5343                             gdb::optional<block_enum> block_index,
5344                             domain_enum domain,
5345                             const char *name)
5346     : m_map (map), m_block_index (block_index), m_domain (domain),
5347       m_addr (find_vec_in_debug_names (map, name))
5348   {}
5349
5350   dw2_debug_names_iterator (const mapped_debug_names &map,
5351                             search_domain search, uint32_t namei)
5352     : m_map (map),
5353       m_search (search),
5354       m_addr (find_vec_in_debug_names (map, namei))
5355   {}
5356
5357   dw2_debug_names_iterator (const mapped_debug_names &map,
5358                             block_enum block_index, domain_enum domain,
5359                             uint32_t namei)
5360     : m_map (map), m_block_index (block_index), m_domain (domain),
5361       m_addr (find_vec_in_debug_names (map, namei))
5362   {}
5363
5364   /* Return the next matching CU or NULL if there are no more.  */
5365   dwarf2_per_cu_data *next ();
5366
5367 private:
5368   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5369                                                   const char *name);
5370   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5371                                                   uint32_t namei);
5372
5373   /* The internalized form of .debug_names.  */
5374   const mapped_debug_names &m_map;
5375
5376   /* If set, only look for symbols that match that block.  Valid values are
5377      GLOBAL_BLOCK and STATIC_BLOCK.  */
5378   const gdb::optional<block_enum> m_block_index;
5379
5380   /* The kind of symbol we're looking for.  */
5381   const domain_enum m_domain = UNDEF_DOMAIN;
5382   const search_domain m_search = ALL_DOMAIN;
5383
5384   /* The list of CUs from the index entry of the symbol, or NULL if
5385      not found.  */
5386   const gdb_byte *m_addr;
5387 };
5388
5389 const char *
5390 mapped_debug_names::namei_to_name (uint32_t namei) const
5391 {
5392   const ULONGEST namei_string_offs
5393     = extract_unsigned_integer ((name_table_string_offs_reordered
5394                                  + namei * offset_size),
5395                                 offset_size,
5396                                 dwarf5_byte_order);
5397   return read_indirect_string_at_offset
5398     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5399 }
5400
5401 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5402    found, return pointer to its pool data.  If NAME cannot be found,
5403    return NULL.  */
5404
5405 const gdb_byte *
5406 dw2_debug_names_iterator::find_vec_in_debug_names
5407   (const mapped_debug_names &map, const char *name)
5408 {
5409   int (*cmp) (const char *, const char *);
5410
5411   gdb::unique_xmalloc_ptr<char> without_params;
5412   if (current_language->la_language == language_cplus
5413       || current_language->la_language == language_fortran
5414       || current_language->la_language == language_d)
5415     {
5416       /* NAME is already canonical.  Drop any qualifiers as
5417          .debug_names does not contain any.  */
5418
5419       if (strchr (name, '(') != NULL)
5420         {
5421           without_params = cp_remove_params (name);
5422           if (without_params != NULL)
5423             name = without_params.get ();
5424         }
5425     }
5426
5427   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5428
5429   const uint32_t full_hash = dwarf5_djb_hash (name);
5430   uint32_t namei
5431     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5432                                 (map.bucket_table_reordered
5433                                  + (full_hash % map.bucket_count)), 4,
5434                                 map.dwarf5_byte_order);
5435   if (namei == 0)
5436     return NULL;
5437   --namei;
5438   if (namei >= map.name_count)
5439     {
5440       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5441                    "[in module %s]"),
5442                  namei, map.name_count,
5443                  objfile_name (map.dwarf2_per_objfile->objfile));
5444       return NULL;
5445     }
5446
5447   for (;;)
5448     {
5449       const uint32_t namei_full_hash
5450         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5451                                     (map.hash_table_reordered + namei), 4,
5452                                     map.dwarf5_byte_order);
5453       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5454         return NULL;
5455
5456       if (full_hash == namei_full_hash)
5457         {
5458           const char *const namei_string = map.namei_to_name (namei);
5459
5460 #if 0 /* An expensive sanity check.  */
5461           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5462             {
5463               complaint (_("Wrong .debug_names hash for string at index %u "
5464                            "[in module %s]"),
5465                          namei, objfile_name (dwarf2_per_objfile->objfile));
5466               return NULL;
5467             }
5468 #endif
5469
5470           if (cmp (namei_string, name) == 0)
5471             {
5472               const ULONGEST namei_entry_offs
5473                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5474                                              + namei * map.offset_size),
5475                                             map.offset_size, map.dwarf5_byte_order);
5476               return map.entry_pool + namei_entry_offs;
5477             }
5478         }
5479
5480       ++namei;
5481       if (namei >= map.name_count)
5482         return NULL;
5483     }
5484 }
5485
5486 const gdb_byte *
5487 dw2_debug_names_iterator::find_vec_in_debug_names
5488   (const mapped_debug_names &map, uint32_t namei)
5489 {
5490   if (namei >= map.name_count)
5491     {
5492       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5493                    "[in module %s]"),
5494                  namei, map.name_count,
5495                  objfile_name (map.dwarf2_per_objfile->objfile));
5496       return NULL;
5497     }
5498
5499   const ULONGEST namei_entry_offs
5500     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5501                                  + namei * map.offset_size),
5502                                 map.offset_size, map.dwarf5_byte_order);
5503   return map.entry_pool + namei_entry_offs;
5504 }
5505
5506 /* See dw2_debug_names_iterator.  */
5507
5508 dwarf2_per_cu_data *
5509 dw2_debug_names_iterator::next ()
5510 {
5511   if (m_addr == NULL)
5512     return NULL;
5513
5514   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5515   struct objfile *objfile = dwarf2_per_objfile->objfile;
5516   bfd *const abfd = objfile->obfd;
5517
5518  again:
5519
5520   unsigned int bytes_read;
5521   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5522   m_addr += bytes_read;
5523   if (abbrev == 0)
5524     return NULL;
5525
5526   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5527   if (indexval_it == m_map.abbrev_map.cend ())
5528     {
5529       complaint (_("Wrong .debug_names undefined abbrev code %s "
5530                    "[in module %s]"),
5531                  pulongest (abbrev), objfile_name (objfile));
5532       return NULL;
5533     }
5534   const mapped_debug_names::index_val &indexval = indexval_it->second;
5535   enum class symbol_linkage {
5536     unknown,
5537     static_,
5538     extern_,
5539   } symbol_linkage_ = symbol_linkage::unknown;
5540   dwarf2_per_cu_data *per_cu = NULL;
5541   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5542     {
5543       ULONGEST ull;
5544       switch (attr.form)
5545         {
5546         case DW_FORM_implicit_const:
5547           ull = attr.implicit_const;
5548           break;
5549         case DW_FORM_flag_present:
5550           ull = 1;
5551           break;
5552         case DW_FORM_udata:
5553           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5554           m_addr += bytes_read;
5555           break;
5556         default:
5557           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5558                      dwarf_form_name (attr.form),
5559                      objfile_name (objfile));
5560           return NULL;
5561         }
5562       switch (attr.dw_idx)
5563         {
5564         case DW_IDX_compile_unit:
5565           /* Don't crash on bad data.  */
5566           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5567             {
5568               complaint (_(".debug_names entry has bad CU index %s"
5569                            " [in module %s]"),
5570                          pulongest (ull),
5571                          objfile_name (dwarf2_per_objfile->objfile));
5572               continue;
5573             }
5574           per_cu = dwarf2_per_objfile->get_cutu (ull);
5575           break;
5576         case DW_IDX_type_unit:
5577           /* Don't crash on bad data.  */
5578           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5579             {
5580               complaint (_(".debug_names entry has bad TU index %s"
5581                            " [in module %s]"),
5582                          pulongest (ull),
5583                          objfile_name (dwarf2_per_objfile->objfile));
5584               continue;
5585             }
5586           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5587           break;
5588         case DW_IDX_GNU_internal:
5589           if (!m_map.augmentation_is_gdb)
5590             break;
5591           symbol_linkage_ = symbol_linkage::static_;
5592           break;
5593         case DW_IDX_GNU_external:
5594           if (!m_map.augmentation_is_gdb)
5595             break;
5596           symbol_linkage_ = symbol_linkage::extern_;
5597           break;
5598         }
5599     }
5600
5601   /* Skip if already read in.  */
5602   if (per_cu->v.quick->compunit_symtab)
5603     goto again;
5604
5605   /* Check static vs global.  */
5606   if (symbol_linkage_ != symbol_linkage::unknown && m_block_index.has_value ())
5607     {
5608         const bool want_static = *m_block_index == STATIC_BLOCK;
5609         const bool symbol_is_static =
5610           symbol_linkage_ == symbol_linkage::static_;
5611         if (want_static != symbol_is_static)
5612           goto again;
5613     }
5614
5615   /* Match dw2_symtab_iter_next, symbol_kind
5616      and debug_names::psymbol_tag.  */
5617   switch (m_domain)
5618     {
5619     case VAR_DOMAIN:
5620       switch (indexval.dwarf_tag)
5621         {
5622         case DW_TAG_variable:
5623         case DW_TAG_subprogram:
5624         /* Some types are also in VAR_DOMAIN.  */
5625         case DW_TAG_typedef:
5626         case DW_TAG_structure_type:
5627           break;
5628         default:
5629           goto again;
5630         }
5631       break;
5632     case STRUCT_DOMAIN:
5633       switch (indexval.dwarf_tag)
5634         {
5635         case DW_TAG_typedef:
5636         case DW_TAG_structure_type:
5637           break;
5638         default:
5639           goto again;
5640         }
5641       break;
5642     case LABEL_DOMAIN:
5643       switch (indexval.dwarf_tag)
5644         {
5645         case 0:
5646         case DW_TAG_variable:
5647           break;
5648         default:
5649           goto again;
5650         }
5651       break;
5652     case MODULE_DOMAIN:
5653       switch (indexval.dwarf_tag)
5654         {
5655         case DW_TAG_module:
5656           break;
5657         default:
5658           goto again;
5659         }
5660       break;
5661     default:
5662       break;
5663     }
5664
5665   /* Match dw2_expand_symtabs_matching, symbol_kind and
5666      debug_names::psymbol_tag.  */
5667   switch (m_search)
5668     {
5669     case VARIABLES_DOMAIN:
5670       switch (indexval.dwarf_tag)
5671         {
5672         case DW_TAG_variable:
5673           break;
5674         default:
5675           goto again;
5676         }
5677       break;
5678     case FUNCTIONS_DOMAIN:
5679       switch (indexval.dwarf_tag)
5680         {
5681         case DW_TAG_subprogram:
5682           break;
5683         default:
5684           goto again;
5685         }
5686       break;
5687     case TYPES_DOMAIN:
5688       switch (indexval.dwarf_tag)
5689         {
5690         case DW_TAG_typedef:
5691         case DW_TAG_structure_type:
5692           break;
5693         default:
5694           goto again;
5695         }
5696       break;
5697     case MODULES_DOMAIN:
5698       switch (indexval.dwarf_tag)
5699         {
5700         case DW_TAG_module:
5701           break;
5702         default:
5703           goto again;
5704         }
5705     default:
5706       break;
5707     }
5708
5709   return per_cu;
5710 }
5711
5712 static struct compunit_symtab *
5713 dw2_debug_names_lookup_symbol (struct objfile *objfile, block_enum block_index,
5714                                const char *name, domain_enum domain)
5715 {
5716   struct dwarf2_per_objfile *dwarf2_per_objfile
5717     = get_dwarf2_per_objfile (objfile);
5718
5719   const auto &mapp = dwarf2_per_objfile->debug_names_table;
5720   if (!mapp)
5721     {
5722       /* index is NULL if OBJF_READNOW.  */
5723       return NULL;
5724     }
5725   const auto &map = *mapp;
5726
5727   dw2_debug_names_iterator iter (map, block_index, domain, name);
5728
5729   struct compunit_symtab *stab_best = NULL;
5730   struct dwarf2_per_cu_data *per_cu;
5731   while ((per_cu = iter.next ()) != NULL)
5732     {
5733       struct symbol *sym, *with_opaque = NULL;
5734       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
5735       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
5736       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
5737
5738       sym = block_find_symbol (block, name, domain,
5739                                block_find_non_opaque_type_preferred,
5740                                &with_opaque);
5741
5742       /* Some caution must be observed with overloaded functions and
5743          methods, since the index will not contain any overload
5744          information (but NAME might contain it).  */
5745
5746       if (sym != NULL
5747           && strcmp_iw (sym->search_name (), name) == 0)
5748         return stab;
5749       if (with_opaque != NULL
5750           && strcmp_iw (with_opaque->search_name (), name) == 0)
5751         stab_best = stab;
5752
5753       /* Keep looking through other CUs.  */
5754     }
5755
5756   return stab_best;
5757 }
5758
5759 /* This dumps minimal information about .debug_names.  It is called
5760    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
5761    uses this to verify that .debug_names has been loaded.  */
5762
5763 static void
5764 dw2_debug_names_dump (struct objfile *objfile)
5765 {
5766   struct dwarf2_per_objfile *dwarf2_per_objfile
5767     = get_dwarf2_per_objfile (objfile);
5768
5769   gdb_assert (dwarf2_per_objfile->using_index);
5770   printf_filtered (".debug_names:");
5771   if (dwarf2_per_objfile->debug_names_table)
5772     printf_filtered (" exists\n");
5773   else
5774     printf_filtered (" faked for \"readnow\"\n");
5775   printf_filtered ("\n");
5776 }
5777
5778 static void
5779 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
5780                                              const char *func_name)
5781 {
5782   struct dwarf2_per_objfile *dwarf2_per_objfile
5783     = get_dwarf2_per_objfile (objfile);
5784
5785   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
5786   if (dwarf2_per_objfile->debug_names_table)
5787     {
5788       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5789
5790       dw2_debug_names_iterator iter (map, {}, VAR_DOMAIN, func_name);
5791
5792       struct dwarf2_per_cu_data *per_cu;
5793       while ((per_cu = iter.next ()) != NULL)
5794         dw2_instantiate_symtab (per_cu, false);
5795     }
5796 }
5797
5798 static void
5799 dw2_debug_names_map_matching_symbols
5800   (struct objfile *objfile,
5801    const lookup_name_info &name, domain_enum domain,
5802    int global,
5803    gdb::function_view<symbol_found_callback_ftype> callback,
5804    symbol_compare_ftype *ordered_compare)
5805 {
5806   struct dwarf2_per_objfile *dwarf2_per_objfile
5807     = get_dwarf2_per_objfile (objfile);
5808
5809   /* debug_names_table is NULL if OBJF_READNOW.  */
5810   if (!dwarf2_per_objfile->debug_names_table)
5811     return;
5812
5813   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5814   const block_enum block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5815
5816   const char *match_name = name.ada ().lookup_name ().c_str ();
5817   auto matcher = [&] (const char *symname)
5818     {
5819       if (ordered_compare == nullptr)
5820         return true;
5821       return ordered_compare (symname, match_name) == 0;
5822     };
5823
5824   dw2_expand_symtabs_matching_symbol (map, name, matcher, ALL_DOMAIN,
5825                                       [&] (offset_type namei)
5826     {
5827       /* The name was matched, now expand corresponding CUs that were
5828          marked.  */
5829       dw2_debug_names_iterator iter (map, block_kind, domain, namei);
5830
5831       struct dwarf2_per_cu_data *per_cu;
5832       while ((per_cu = iter.next ()) != NULL)
5833         dw2_expand_symtabs_matching_one (per_cu, nullptr, nullptr);
5834       return true;
5835     });
5836
5837   /* It's a shame we couldn't do this inside the
5838      dw2_expand_symtabs_matching_symbol callback, but that skips CUs
5839      that have already been expanded.  Instead, this loop matches what
5840      the psymtab code does.  */
5841   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5842     {
5843       struct compunit_symtab *cust = per_cu->v.quick->compunit_symtab;
5844       if (cust != nullptr)
5845         {
5846           const struct block *block
5847             = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cust), block_kind);
5848           if (!iterate_over_symbols_terminated (block, name,
5849                                                 domain, callback))
5850             break;
5851         }
5852     }
5853 }
5854
5855 static void
5856 dw2_debug_names_expand_symtabs_matching
5857   (struct objfile *objfile,
5858    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5859    const lookup_name_info &lookup_name,
5860    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5861    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5862    enum search_domain kind)
5863 {
5864   struct dwarf2_per_objfile *dwarf2_per_objfile
5865     = get_dwarf2_per_objfile (objfile);
5866
5867   /* debug_names_table is NULL if OBJF_READNOW.  */
5868   if (!dwarf2_per_objfile->debug_names_table)
5869     return;
5870
5871   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5872
5873   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5874
5875   dw2_expand_symtabs_matching_symbol (map, lookup_name,
5876                                       symbol_matcher,
5877                                       kind, [&] (offset_type namei)
5878     {
5879       /* The name was matched, now expand corresponding CUs that were
5880          marked.  */
5881       dw2_debug_names_iterator iter (map, kind, namei);
5882
5883       struct dwarf2_per_cu_data *per_cu;
5884       while ((per_cu = iter.next ()) != NULL)
5885         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5886                                          expansion_notify);
5887       return true;
5888     });
5889 }
5890
5891 const struct quick_symbol_functions dwarf2_debug_names_functions =
5892 {
5893   dw2_has_symbols,
5894   dw2_find_last_source_symtab,
5895   dw2_forget_cached_source_info,
5896   dw2_map_symtabs_matching_filename,
5897   dw2_debug_names_lookup_symbol,
5898   dw2_print_stats,
5899   dw2_debug_names_dump,
5900   dw2_debug_names_expand_symtabs_for_function,
5901   dw2_expand_all_symtabs,
5902   dw2_expand_symtabs_with_fullname,
5903   dw2_debug_names_map_matching_symbols,
5904   dw2_debug_names_expand_symtabs_matching,
5905   dw2_find_pc_sect_compunit_symtab,
5906   NULL,
5907   dw2_map_symbol_filenames
5908 };
5909
5910 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
5911    to either a dwarf2_per_objfile or dwz_file object.  */
5912
5913 template <typename T>
5914 static gdb::array_view<const gdb_byte>
5915 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
5916 {
5917   dwarf2_section_info *section = &section_owner->gdb_index;
5918
5919   if (section->empty ())
5920     return {};
5921
5922   /* Older elfutils strip versions could keep the section in the main
5923      executable while splitting it for the separate debug info file.  */
5924   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5925     return {};
5926
5927   section->read (obj);
5928
5929   /* dwarf2_section_info::size is a bfd_size_type, while
5930      gdb::array_view works with size_t.  On 32-bit hosts, with
5931      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
5932      is 32-bit.  So we need an explicit narrowing conversion here.
5933      This is fine, because it's impossible to allocate or mmap an
5934      array/buffer larger than what size_t can represent.  */
5935   return gdb::make_array_view (section->buffer, section->size);
5936 }
5937
5938 /* Lookup the index cache for the contents of the index associated to
5939    DWARF2_OBJ.  */
5940
5941 static gdb::array_view<const gdb_byte>
5942 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_objfile *dwarf2_obj)
5943 {
5944   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
5945   if (build_id == nullptr)
5946     return {};
5947
5948   return global_index_cache.lookup_gdb_index (build_id,
5949                                               &dwarf2_obj->index_cache_res);
5950 }
5951
5952 /* Same as the above, but for DWZ.  */
5953
5954 static gdb::array_view<const gdb_byte>
5955 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
5956 {
5957   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
5958   if (build_id == nullptr)
5959     return {};
5960
5961   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
5962 }
5963
5964 /* See symfile.h.  */
5965
5966 bool
5967 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
5968 {
5969   struct dwarf2_per_objfile *dwarf2_per_objfile
5970     = get_dwarf2_per_objfile (objfile);
5971
5972   /* If we're about to read full symbols, don't bother with the
5973      indices.  In this case we also don't care if some other debug
5974      format is making psymtabs, because they are all about to be
5975      expanded anyway.  */
5976   if ((objfile->flags & OBJF_READNOW))
5977     {
5978       dwarf2_per_objfile->using_index = 1;
5979       create_all_comp_units (dwarf2_per_objfile);
5980       create_all_type_units (dwarf2_per_objfile);
5981       dwarf2_per_objfile->quick_file_names_table
5982         = create_quick_file_names_table
5983             (dwarf2_per_objfile->all_comp_units.size ());
5984
5985       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
5986                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
5987         {
5988           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
5989
5990           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5991                                             struct dwarf2_per_cu_quick_data);
5992         }
5993
5994       /* Return 1 so that gdb sees the "quick" functions.  However,
5995          these functions will be no-ops because we will have expanded
5996          all symtabs.  */
5997       *index_kind = dw_index_kind::GDB_INDEX;
5998       return true;
5999     }
6000
6001   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6002     {
6003       *index_kind = dw_index_kind::DEBUG_NAMES;
6004       return true;
6005     }
6006
6007   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6008                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
6009                              get_gdb_index_contents_from_section<dwz_file>))
6010     {
6011       *index_kind = dw_index_kind::GDB_INDEX;
6012       return true;
6013     }
6014
6015   /* ... otherwise, try to find the index in the index cache.  */
6016   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6017                              get_gdb_index_contents_from_cache,
6018                              get_gdb_index_contents_from_cache_dwz))
6019     {
6020       global_index_cache.hit ();
6021       *index_kind = dw_index_kind::GDB_INDEX;
6022       return true;
6023     }
6024
6025   global_index_cache.miss ();
6026   return false;
6027 }
6028
6029 \f
6030
6031 /* Build a partial symbol table.  */
6032
6033 void
6034 dwarf2_build_psymtabs (struct objfile *objfile)
6035 {
6036   struct dwarf2_per_objfile *dwarf2_per_objfile
6037     = get_dwarf2_per_objfile (objfile);
6038
6039   init_psymbol_list (objfile, 1024);
6040
6041   try
6042     {
6043       /* This isn't really ideal: all the data we allocate on the
6044          objfile's obstack is still uselessly kept around.  However,
6045          freeing it seems unsafe.  */
6046       psymtab_discarder psymtabs (objfile);
6047       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6048       psymtabs.keep ();
6049
6050       /* (maybe) store an index in the cache.  */
6051       global_index_cache.store (dwarf2_per_objfile);
6052     }
6053   catch (const gdb_exception_error &except)
6054     {
6055       exception_print (gdb_stderr, except);
6056     }
6057 }
6058
6059 /* Return the total length of the CU described by HEADER.  */
6060
6061 static unsigned int
6062 get_cu_length (const struct comp_unit_head *header)
6063 {
6064   return header->initial_length_size + header->length;
6065 }
6066
6067 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6068
6069 static inline bool
6070 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6071 {
6072   sect_offset bottom = cu_header->sect_off;
6073   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6074
6075   return sect_off >= bottom && sect_off < top;
6076 }
6077
6078 /* Find the base address of the compilation unit for range lists and
6079    location lists.  It will normally be specified by DW_AT_low_pc.
6080    In DWARF-3 draft 4, the base address could be overridden by
6081    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6082    compilation units with discontinuous ranges.  */
6083
6084 static void
6085 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6086 {
6087   struct attribute *attr;
6088
6089   cu->base_known = 0;
6090   cu->base_address = 0;
6091
6092   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6093   if (attr != nullptr)
6094     {
6095       cu->base_address = attr->value_as_address ();
6096       cu->base_known = 1;
6097     }
6098   else
6099     {
6100       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6101       if (attr != nullptr)
6102         {
6103           cu->base_address = attr->value_as_address ();
6104           cu->base_known = 1;
6105         }
6106     }
6107 }
6108
6109 /* Read in the comp unit header information from the debug_info at info_ptr.
6110    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6111    NOTE: This leaves members offset, first_die_offset to be filled in
6112    by the caller.  */
6113
6114 static const gdb_byte *
6115 read_comp_unit_head (struct comp_unit_head *cu_header,
6116                      const gdb_byte *info_ptr,
6117                      struct dwarf2_section_info *section,
6118                      rcuh_kind section_kind)
6119 {
6120   int signed_addr;
6121   unsigned int bytes_read;
6122   const char *filename = section->get_file_name ();
6123   bfd *abfd = section->get_bfd_owner ();
6124
6125   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6126   cu_header->initial_length_size = bytes_read;
6127   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6128   info_ptr += bytes_read;
6129   cu_header->version = read_2_bytes (abfd, info_ptr);
6130   if (cu_header->version < 2 || cu_header->version > 5)
6131     error (_("Dwarf Error: wrong version in compilation unit header "
6132            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6133            cu_header->version, filename);
6134   info_ptr += 2;
6135   if (cu_header->version < 5)
6136     switch (section_kind)
6137       {
6138       case rcuh_kind::COMPILE:
6139         cu_header->unit_type = DW_UT_compile;
6140         break;
6141       case rcuh_kind::TYPE:
6142         cu_header->unit_type = DW_UT_type;
6143         break;
6144       default:
6145         internal_error (__FILE__, __LINE__,
6146                         _("read_comp_unit_head: invalid section_kind"));
6147       }
6148   else
6149     {
6150       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6151                                                  (read_1_byte (abfd, info_ptr));
6152       info_ptr += 1;
6153       switch (cu_header->unit_type)
6154         {
6155         case DW_UT_compile:
6156         case DW_UT_partial:
6157         case DW_UT_skeleton:
6158         case DW_UT_split_compile:
6159           if (section_kind != rcuh_kind::COMPILE)
6160             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6161                    "(is %s, should be %s) [in module %s]"),
6162                    dwarf_unit_type_name (cu_header->unit_type),
6163                    dwarf_unit_type_name (DW_UT_type), filename);
6164           break;
6165         case DW_UT_type:
6166         case DW_UT_split_type:
6167           section_kind = rcuh_kind::TYPE;
6168           break;
6169         default:
6170           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6171                  "(is %#04x, should be one of: %s, %s, %s, %s or %s) "
6172                  "[in module %s]"), cu_header->unit_type,
6173                  dwarf_unit_type_name (DW_UT_compile),
6174                  dwarf_unit_type_name (DW_UT_skeleton),
6175                  dwarf_unit_type_name (DW_UT_split_compile),
6176                  dwarf_unit_type_name (DW_UT_type),
6177                  dwarf_unit_type_name (DW_UT_split_type), filename);
6178         }
6179
6180       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6181       info_ptr += 1;
6182     }
6183   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6184                                                           cu_header,
6185                                                           &bytes_read);
6186   info_ptr += bytes_read;
6187   if (cu_header->version < 5)
6188     {
6189       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6190       info_ptr += 1;
6191     }
6192   signed_addr = bfd_get_sign_extend_vma (abfd);
6193   if (signed_addr < 0)
6194     internal_error (__FILE__, __LINE__,
6195                     _("read_comp_unit_head: dwarf from non elf file"));
6196   cu_header->signed_addr_p = signed_addr;
6197
6198   bool header_has_signature = section_kind == rcuh_kind::TYPE
6199     || cu_header->unit_type == DW_UT_skeleton
6200     || cu_header->unit_type == DW_UT_split_compile;
6201
6202   if (header_has_signature)
6203     {
6204       cu_header->signature = read_8_bytes (abfd, info_ptr);
6205       info_ptr += 8;
6206     }
6207
6208   if (section_kind == rcuh_kind::TYPE)
6209     {
6210       LONGEST type_offset;
6211       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6212       info_ptr += bytes_read;
6213       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6214       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6215         error (_("Dwarf Error: Too big type_offset in compilation unit "
6216                "header (is %s) [in module %s]"), plongest (type_offset),
6217                filename);
6218     }
6219
6220   return info_ptr;
6221 }
6222
6223 /* Helper function that returns the proper abbrev section for
6224    THIS_CU.  */
6225
6226 static struct dwarf2_section_info *
6227 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6228 {
6229   struct dwarf2_section_info *abbrev;
6230   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6231
6232   if (this_cu->is_dwz)
6233     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6234   else
6235     abbrev = &dwarf2_per_objfile->abbrev;
6236
6237   return abbrev;
6238 }
6239
6240 /* Subroutine of read_and_check_comp_unit_head and
6241    read_and_check_type_unit_head to simplify them.
6242    Perform various error checking on the header.  */
6243
6244 static void
6245 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6246                             struct comp_unit_head *header,
6247                             struct dwarf2_section_info *section,
6248                             struct dwarf2_section_info *abbrev_section)
6249 {
6250   const char *filename = section->get_file_name ();
6251
6252   if (to_underlying (header->abbrev_sect_off)
6253       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6254     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6255            "(offset %s + 6) [in module %s]"),
6256            sect_offset_str (header->abbrev_sect_off),
6257            sect_offset_str (header->sect_off),
6258            filename);
6259
6260   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6261      avoid potential 32-bit overflow.  */
6262   if (((ULONGEST) header->sect_off + get_cu_length (header))
6263       > section->size)
6264     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6265            "(offset %s + 0) [in module %s]"),
6266            header->length, sect_offset_str (header->sect_off),
6267            filename);
6268 }
6269
6270 /* Read in a CU/TU header and perform some basic error checking.
6271    The contents of the header are stored in HEADER.
6272    The result is a pointer to the start of the first DIE.  */
6273
6274 static const gdb_byte *
6275 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6276                                struct comp_unit_head *header,
6277                                struct dwarf2_section_info *section,
6278                                struct dwarf2_section_info *abbrev_section,
6279                                const gdb_byte *info_ptr,
6280                                rcuh_kind section_kind)
6281 {
6282   const gdb_byte *beg_of_comp_unit = info_ptr;
6283
6284   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6285
6286   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6287
6288   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6289
6290   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6291                               abbrev_section);
6292
6293   return info_ptr;
6294 }
6295
6296 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6297
6298 static sect_offset
6299 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6300                     struct dwarf2_section_info *section,
6301                     sect_offset sect_off)
6302 {
6303   bfd *abfd = section->get_bfd_owner ();
6304   const gdb_byte *info_ptr;
6305   unsigned int initial_length_size, offset_size;
6306   uint16_t version;
6307
6308   section->read (dwarf2_per_objfile->objfile);
6309   info_ptr = section->buffer + to_underlying (sect_off);
6310   read_initial_length (abfd, info_ptr, &initial_length_size);
6311   offset_size = initial_length_size == 4 ? 4 : 8;
6312   info_ptr += initial_length_size;
6313
6314   version = read_2_bytes (abfd, info_ptr);
6315   info_ptr += 2;
6316   if (version >= 5)
6317     {
6318       /* Skip unit type and address size.  */
6319       info_ptr += 2;
6320     }
6321
6322   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6323 }
6324
6325 /* Allocate a new partial symtab for file named NAME and mark this new
6326    partial symtab as being an include of PST.  */
6327
6328 static void
6329 dwarf2_create_include_psymtab (const char *name, dwarf2_psymtab *pst,
6330                                struct objfile *objfile)
6331 {
6332   dwarf2_psymtab *subpst = new dwarf2_psymtab (name, objfile);
6333
6334   if (!IS_ABSOLUTE_PATH (subpst->filename))
6335     {
6336       /* It shares objfile->objfile_obstack.  */
6337       subpst->dirname = pst->dirname;
6338     }
6339
6340   subpst->dependencies = objfile->partial_symtabs->allocate_dependencies (1);
6341   subpst->dependencies[0] = pst;
6342   subpst->number_of_dependencies = 1;
6343
6344   /* No private part is necessary for include psymtabs.  This property
6345      can be used to differentiate between such include psymtabs and
6346      the regular ones.  */
6347   subpst->per_cu_data = nullptr;
6348 }
6349
6350 /* Read the Line Number Program data and extract the list of files
6351    included by the source file represented by PST.  Build an include
6352    partial symtab for each of these included files.  */
6353
6354 static void
6355 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6356                                struct die_info *die,
6357                                dwarf2_psymtab *pst)
6358 {
6359   line_header_up lh;
6360   struct attribute *attr;
6361
6362   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6363   if (attr != nullptr)
6364     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6365   if (lh == NULL)
6366     return;  /* No linetable, so no includes.  */
6367
6368   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6369      that we pass in the raw text_low here; that is ok because we're
6370      only decoding the line table to make include partial symtabs, and
6371      so the addresses aren't really used.  */
6372   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6373                       pst->raw_text_low (), 1);
6374 }
6375
6376 static hashval_t
6377 hash_signatured_type (const void *item)
6378 {
6379   const struct signatured_type *sig_type
6380     = (const struct signatured_type *) item;
6381
6382   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6383   return sig_type->signature;
6384 }
6385
6386 static int
6387 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6388 {
6389   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6390   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6391
6392   return lhs->signature == rhs->signature;
6393 }
6394
6395 /* Allocate a hash table for signatured types.  */
6396
6397 static htab_up
6398 allocate_signatured_type_table (struct objfile *objfile)
6399 {
6400   return htab_up (htab_create_alloc (41,
6401                                      hash_signatured_type,
6402                                      eq_signatured_type,
6403                                      NULL, xcalloc, xfree));
6404 }
6405
6406 /* A helper function to add a signatured type CU to a table.  */
6407
6408 static int
6409 add_signatured_type_cu_to_table (void **slot, void *datum)
6410 {
6411   struct signatured_type *sigt = (struct signatured_type *) *slot;
6412   std::vector<signatured_type *> *all_type_units
6413     = (std::vector<signatured_type *> *) datum;
6414
6415   all_type_units->push_back (sigt);
6416
6417   return 1;
6418 }
6419
6420 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6421    and fill them into TYPES_HTAB.  It will process only type units,
6422    therefore DW_UT_type.  */
6423
6424 static void
6425 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6426                               struct dwo_file *dwo_file,
6427                               dwarf2_section_info *section, htab_up &types_htab,
6428                               rcuh_kind section_kind)
6429 {
6430   struct objfile *objfile = dwarf2_per_objfile->objfile;
6431   struct dwarf2_section_info *abbrev_section;
6432   bfd *abfd;
6433   const gdb_byte *info_ptr, *end_ptr;
6434
6435   abbrev_section = (dwo_file != NULL
6436                     ? &dwo_file->sections.abbrev
6437                     : &dwarf2_per_objfile->abbrev);
6438
6439   if (dwarf_read_debug)
6440     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6441                         section->get_name (),
6442                         abbrev_section->get_file_name ());
6443
6444   section->read (objfile);
6445   info_ptr = section->buffer;
6446
6447   if (info_ptr == NULL)
6448     return;
6449
6450   /* We can't set abfd until now because the section may be empty or
6451      not present, in which case the bfd is unknown.  */
6452   abfd = section->get_bfd_owner ();
6453
6454   /* We don't use cutu_reader here because we don't need to read
6455      any dies: the signature is in the header.  */
6456
6457   end_ptr = info_ptr + section->size;
6458   while (info_ptr < end_ptr)
6459     {
6460       struct signatured_type *sig_type;
6461       struct dwo_unit *dwo_tu;
6462       void **slot;
6463       const gdb_byte *ptr = info_ptr;
6464       struct comp_unit_head header;
6465       unsigned int length;
6466
6467       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6468
6469       /* Initialize it due to a false compiler warning.  */
6470       header.signature = -1;
6471       header.type_cu_offset_in_tu = (cu_offset) -1;
6472
6473       /* We need to read the type's signature in order to build the hash
6474          table, but we don't need anything else just yet.  */
6475
6476       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6477                                            abbrev_section, ptr, section_kind);
6478
6479       length = get_cu_length (&header);
6480
6481       /* Skip dummy type units.  */
6482       if (ptr >= info_ptr + length
6483           || peek_abbrev_code (abfd, ptr) == 0
6484           || header.unit_type != DW_UT_type)
6485         {
6486           info_ptr += length;
6487           continue;
6488         }
6489
6490       if (types_htab == NULL)
6491         {
6492           if (dwo_file)
6493             types_htab = allocate_dwo_unit_table (objfile);
6494           else
6495             types_htab = allocate_signatured_type_table (objfile);
6496         }
6497
6498       if (dwo_file)
6499         {
6500           sig_type = NULL;
6501           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6502                                    struct dwo_unit);
6503           dwo_tu->dwo_file = dwo_file;
6504           dwo_tu->signature = header.signature;
6505           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6506           dwo_tu->section = section;
6507           dwo_tu->sect_off = sect_off;
6508           dwo_tu->length = length;
6509         }
6510       else
6511         {
6512           /* N.B.: type_offset is not usable if this type uses a DWO file.
6513              The real type_offset is in the DWO file.  */
6514           dwo_tu = NULL;
6515           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6516                                      struct signatured_type);
6517           sig_type->signature = header.signature;
6518           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6519           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6520           sig_type->per_cu.is_debug_types = 1;
6521           sig_type->per_cu.section = section;
6522           sig_type->per_cu.sect_off = sect_off;
6523           sig_type->per_cu.length = length;
6524         }
6525
6526       slot = htab_find_slot (types_htab.get (),
6527                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6528                              INSERT);
6529       gdb_assert (slot != NULL);
6530       if (*slot != NULL)
6531         {
6532           sect_offset dup_sect_off;
6533
6534           if (dwo_file)
6535             {
6536               const struct dwo_unit *dup_tu
6537                 = (const struct dwo_unit *) *slot;
6538
6539               dup_sect_off = dup_tu->sect_off;
6540             }
6541           else
6542             {
6543               const struct signatured_type *dup_tu
6544                 = (const struct signatured_type *) *slot;
6545
6546               dup_sect_off = dup_tu->per_cu.sect_off;
6547             }
6548
6549           complaint (_("debug type entry at offset %s is duplicate to"
6550                        " the entry at offset %s, signature %s"),
6551                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6552                      hex_string (header.signature));
6553         }
6554       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6555
6556       if (dwarf_read_debug > 1)
6557         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6558                             sect_offset_str (sect_off),
6559                             hex_string (header.signature));
6560
6561       info_ptr += length;
6562     }
6563 }
6564
6565 /* Create the hash table of all entries in the .debug_types
6566    (or .debug_types.dwo) section(s).
6567    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6568    otherwise it is NULL.
6569
6570    The result is a pointer to the hash table or NULL if there are no types.
6571
6572    Note: This function processes DWO files only, not DWP files.  */
6573
6574 static void
6575 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6576                                struct dwo_file *dwo_file,
6577                                gdb::array_view<dwarf2_section_info> type_sections,
6578                                htab_up &types_htab)
6579 {
6580   for (dwarf2_section_info &section : type_sections)
6581     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, &section,
6582                                   types_htab, rcuh_kind::TYPE);
6583 }
6584
6585 /* Create the hash table of all entries in the .debug_types section,
6586    and initialize all_type_units.
6587    The result is zero if there is an error (e.g. missing .debug_types section),
6588    otherwise non-zero.  */
6589
6590 static int
6591 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6592 {
6593   htab_up types_htab;
6594
6595   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6596                                 &dwarf2_per_objfile->info, types_htab,
6597                                 rcuh_kind::COMPILE);
6598   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6599                                  dwarf2_per_objfile->types, types_htab);
6600   if (types_htab == NULL)
6601     {
6602       dwarf2_per_objfile->signatured_types = NULL;
6603       return 0;
6604     }
6605
6606   dwarf2_per_objfile->signatured_types = std::move (types_htab);
6607
6608   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6609   dwarf2_per_objfile->all_type_units.reserve
6610     (htab_elements (dwarf2_per_objfile->signatured_types.get ()));
6611
6612   htab_traverse_noresize (dwarf2_per_objfile->signatured_types.get (),
6613                           add_signatured_type_cu_to_table,
6614                           &dwarf2_per_objfile->all_type_units);
6615
6616   return 1;
6617 }
6618
6619 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6620    If SLOT is non-NULL, it is the entry to use in the hash table.
6621    Otherwise we find one.  */
6622
6623 static struct signatured_type *
6624 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6625                void **slot)
6626 {
6627   struct objfile *objfile = dwarf2_per_objfile->objfile;
6628
6629   if (dwarf2_per_objfile->all_type_units.size ()
6630       == dwarf2_per_objfile->all_type_units.capacity ())
6631     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6632
6633   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6634                                               struct signatured_type);
6635
6636   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6637   sig_type->signature = sig;
6638   sig_type->per_cu.is_debug_types = 1;
6639   if (dwarf2_per_objfile->using_index)
6640     {
6641       sig_type->per_cu.v.quick =
6642         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6643                         struct dwarf2_per_cu_quick_data);
6644     }
6645
6646   if (slot == NULL)
6647     {
6648       slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6649                              sig_type, INSERT);
6650     }
6651   gdb_assert (*slot == NULL);
6652   *slot = sig_type;
6653   /* The rest of sig_type must be filled in by the caller.  */
6654   return sig_type;
6655 }
6656
6657 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6658    Fill in SIG_ENTRY with DWO_ENTRY.  */
6659
6660 static void
6661 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6662                                   struct signatured_type *sig_entry,
6663                                   struct dwo_unit *dwo_entry)
6664 {
6665   /* Make sure we're not clobbering something we don't expect to.  */
6666   gdb_assert (! sig_entry->per_cu.queued);
6667   gdb_assert (sig_entry->per_cu.cu == NULL);
6668   if (dwarf2_per_objfile->using_index)
6669     {
6670       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6671       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6672     }
6673   else
6674       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6675   gdb_assert (sig_entry->signature == dwo_entry->signature);
6676   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6677   gdb_assert (sig_entry->type_unit_group == NULL);
6678   gdb_assert (sig_entry->dwo_unit == NULL);
6679
6680   sig_entry->per_cu.section = dwo_entry->section;
6681   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6682   sig_entry->per_cu.length = dwo_entry->length;
6683   sig_entry->per_cu.reading_dwo_directly = 1;
6684   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6685   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6686   sig_entry->dwo_unit = dwo_entry;
6687 }
6688
6689 /* Subroutine of lookup_signatured_type.
6690    If we haven't read the TU yet, create the signatured_type data structure
6691    for a TU to be read in directly from a DWO file, bypassing the stub.
6692    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6693    using .gdb_index, then when reading a CU we want to stay in the DWO file
6694    containing that CU.  Otherwise we could end up reading several other DWO
6695    files (due to comdat folding) to process the transitive closure of all the
6696    mentioned TUs, and that can be slow.  The current DWO file will have every
6697    type signature that it needs.
6698    We only do this for .gdb_index because in the psymtab case we already have
6699    to read all the DWOs to build the type unit groups.  */
6700
6701 static struct signatured_type *
6702 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6703 {
6704   struct dwarf2_per_objfile *dwarf2_per_objfile
6705     = cu->per_cu->dwarf2_per_objfile;
6706   struct objfile *objfile = dwarf2_per_objfile->objfile;
6707   struct dwo_file *dwo_file;
6708   struct dwo_unit find_dwo_entry, *dwo_entry;
6709   struct signatured_type find_sig_entry, *sig_entry;
6710   void **slot;
6711
6712   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6713
6714   /* If TU skeletons have been removed then we may not have read in any
6715      TUs yet.  */
6716   if (dwarf2_per_objfile->signatured_types == NULL)
6717     {
6718       dwarf2_per_objfile->signatured_types
6719         = allocate_signatured_type_table (objfile);
6720     }
6721
6722   /* We only ever need to read in one copy of a signatured type.
6723      Use the global signatured_types array to do our own comdat-folding
6724      of types.  If this is the first time we're reading this TU, and
6725      the TU has an entry in .gdb_index, replace the recorded data from
6726      .gdb_index with this TU.  */
6727
6728   find_sig_entry.signature = sig;
6729   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6730                          &find_sig_entry, INSERT);
6731   sig_entry = (struct signatured_type *) *slot;
6732
6733   /* We can get here with the TU already read, *or* in the process of being
6734      read.  Don't reassign the global entry to point to this DWO if that's
6735      the case.  Also note that if the TU is already being read, it may not
6736      have come from a DWO, the program may be a mix of Fission-compiled
6737      code and non-Fission-compiled code.  */
6738
6739   /* Have we already tried to read this TU?
6740      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6741      needn't exist in the global table yet).  */
6742   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6743     return sig_entry;
6744
6745   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6746      dwo_unit of the TU itself.  */
6747   dwo_file = cu->dwo_unit->dwo_file;
6748
6749   /* Ok, this is the first time we're reading this TU.  */
6750   if (dwo_file->tus == NULL)
6751     return NULL;
6752   find_dwo_entry.signature = sig;
6753   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
6754                                              &find_dwo_entry);
6755   if (dwo_entry == NULL)
6756     return NULL;
6757
6758   /* If the global table doesn't have an entry for this TU, add one.  */
6759   if (sig_entry == NULL)
6760     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6761
6762   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6763   sig_entry->per_cu.tu_read = 1;
6764   return sig_entry;
6765 }
6766
6767 /* Subroutine of lookup_signatured_type.
6768    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6769    then try the DWP file.  If the TU stub (skeleton) has been removed then
6770    it won't be in .gdb_index.  */
6771
6772 static struct signatured_type *
6773 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6774 {
6775   struct dwarf2_per_objfile *dwarf2_per_objfile
6776     = cu->per_cu->dwarf2_per_objfile;
6777   struct objfile *objfile = dwarf2_per_objfile->objfile;
6778   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6779   struct dwo_unit *dwo_entry;
6780   struct signatured_type find_sig_entry, *sig_entry;
6781   void **slot;
6782
6783   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6784   gdb_assert (dwp_file != NULL);
6785
6786   /* If TU skeletons have been removed then we may not have read in any
6787      TUs yet.  */
6788   if (dwarf2_per_objfile->signatured_types == NULL)
6789     {
6790       dwarf2_per_objfile->signatured_types
6791         = allocate_signatured_type_table (objfile);
6792     }
6793
6794   find_sig_entry.signature = sig;
6795   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6796                          &find_sig_entry, INSERT);
6797   sig_entry = (struct signatured_type *) *slot;
6798
6799   /* Have we already tried to read this TU?
6800      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6801      needn't exist in the global table yet).  */
6802   if (sig_entry != NULL)
6803     return sig_entry;
6804
6805   if (dwp_file->tus == NULL)
6806     return NULL;
6807   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
6808                                       sig, 1 /* is_debug_types */);
6809   if (dwo_entry == NULL)
6810     return NULL;
6811
6812   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6813   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6814
6815   return sig_entry;
6816 }
6817
6818 /* Lookup a signature based type for DW_FORM_ref_sig8.
6819    Returns NULL if signature SIG is not present in the table.
6820    It is up to the caller to complain about this.  */
6821
6822 static struct signatured_type *
6823 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6824 {
6825   struct dwarf2_per_objfile *dwarf2_per_objfile
6826     = cu->per_cu->dwarf2_per_objfile;
6827
6828   if (cu->dwo_unit
6829       && dwarf2_per_objfile->using_index)
6830     {
6831       /* We're in a DWO/DWP file, and we're using .gdb_index.
6832          These cases require special processing.  */
6833       if (get_dwp_file (dwarf2_per_objfile) == NULL)
6834         return lookup_dwo_signatured_type (cu, sig);
6835       else
6836         return lookup_dwp_signatured_type (cu, sig);
6837     }
6838   else
6839     {
6840       struct signatured_type find_entry, *entry;
6841
6842       if (dwarf2_per_objfile->signatured_types == NULL)
6843         return NULL;
6844       find_entry.signature = sig;
6845       entry = ((struct signatured_type *)
6846                htab_find (dwarf2_per_objfile->signatured_types.get (),
6847                           &find_entry));
6848       return entry;
6849     }
6850 }
6851
6852 /* Return the address base of the compile unit, which, if exists, is stored
6853    either at the attribute DW_AT_GNU_addr_base, or DW_AT_addr_base.  */
6854 static gdb::optional<ULONGEST>
6855 lookup_addr_base (struct die_info *comp_unit_die)
6856 {
6857   struct attribute *attr;
6858   attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_addr_base);
6859   if (attr == nullptr)
6860     attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_GNU_addr_base);
6861   if (attr == nullptr)
6862     return gdb::optional<ULONGEST> ();
6863   return DW_UNSND (attr);
6864 }
6865
6866 /* Return range lists base of the compile unit, which, if exists, is stored
6867    either at the attribute DW_AT_rnglists_base or DW_AT_GNU_ranges_base.  */
6868 static ULONGEST
6869 lookup_ranges_base (struct die_info *comp_unit_die)
6870 {
6871   struct attribute *attr;
6872   attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_rnglists_base);
6873   if (attr == nullptr)
6874     attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_GNU_ranges_base);
6875   if (attr == nullptr)
6876     return 0;
6877   return DW_UNSND (attr);
6878 }
6879
6880 /* Low level DIE reading support.  */
6881
6882 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6883
6884 static void
6885 init_cu_die_reader (struct die_reader_specs *reader,
6886                     struct dwarf2_cu *cu,
6887                     struct dwarf2_section_info *section,
6888                     struct dwo_file *dwo_file,
6889                     struct abbrev_table *abbrev_table)
6890 {
6891   gdb_assert (section->readin && section->buffer != NULL);
6892   reader->abfd = section->get_bfd_owner ();
6893   reader->cu = cu;
6894   reader->dwo_file = dwo_file;
6895   reader->die_section = section;
6896   reader->buffer = section->buffer;
6897   reader->buffer_end = section->buffer + section->size;
6898   reader->abbrev_table = abbrev_table;
6899 }
6900
6901 /* Subroutine of cutu_reader to simplify it.
6902    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6903    There's just a lot of work to do, and cutu_reader is big enough
6904    already.
6905
6906    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6907    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6908    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6909    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6910    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6911    STUB_COMP_DIR may be non-NULL.
6912    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE
6913    are filled in with the info of the DIE from the DWO file.
6914    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
6915    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
6916    kept around for at least as long as *RESULT_READER.
6917
6918    The result is non-zero if a valid (non-dummy) DIE was found.  */
6919
6920 static int
6921 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
6922                         struct dwo_unit *dwo_unit,
6923                         struct die_info *stub_comp_unit_die,
6924                         const char *stub_comp_dir,
6925                         struct die_reader_specs *result_reader,
6926                         const gdb_byte **result_info_ptr,
6927                         struct die_info **result_comp_unit_die,
6928                         abbrev_table_up *result_dwo_abbrev_table)
6929 {
6930   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6931   struct objfile *objfile = dwarf2_per_objfile->objfile;
6932   struct dwarf2_cu *cu = this_cu->cu;
6933   bfd *abfd;
6934   const gdb_byte *begin_info_ptr, *info_ptr;
6935   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6936   int i,num_extra_attrs;
6937   struct dwarf2_section_info *dwo_abbrev_section;
6938   struct die_info *comp_unit_die;
6939
6940   /* At most one of these may be provided.  */
6941   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6942
6943   /* These attributes aren't processed until later:
6944      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6945      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6946      referenced later.  However, these attributes are found in the stub
6947      which we won't have later.  In order to not impose this complication
6948      on the rest of the code, we read them here and copy them to the
6949      DWO CU/TU die.  */
6950
6951   stmt_list = NULL;
6952   low_pc = NULL;
6953   high_pc = NULL;
6954   ranges = NULL;
6955   comp_dir = NULL;
6956
6957   if (stub_comp_unit_die != NULL)
6958     {
6959       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6960          DWO file.  */
6961       if (! this_cu->is_debug_types)
6962         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6963       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6964       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6965       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6966       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6967
6968       cu->addr_base = lookup_addr_base (stub_comp_unit_die);
6969
6970       /* There should be a DW_AT_rnglists_base (DW_AT_GNU_ranges_base) attribute
6971          here (if needed). We need the value before we can process
6972          DW_AT_ranges.  */
6973       cu->ranges_base = lookup_ranges_base (stub_comp_unit_die);
6974     }
6975   else if (stub_comp_dir != NULL)
6976     {
6977       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6978       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
6979       comp_dir->name = DW_AT_comp_dir;
6980       comp_dir->form = DW_FORM_string;
6981       DW_STRING_IS_CANONICAL (comp_dir) = 0;
6982       DW_STRING (comp_dir) = stub_comp_dir;
6983     }
6984
6985   /* Set up for reading the DWO CU/TU.  */
6986   cu->dwo_unit = dwo_unit;
6987   dwarf2_section_info *section = dwo_unit->section;
6988   section->read (objfile);
6989   abfd = section->get_bfd_owner ();
6990   begin_info_ptr = info_ptr = (section->buffer
6991                                + to_underlying (dwo_unit->sect_off));
6992   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
6993
6994   if (this_cu->is_debug_types)
6995     {
6996       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
6997
6998       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
6999                                                 &cu->header, section,
7000                                                 dwo_abbrev_section,
7001                                                 info_ptr, rcuh_kind::TYPE);
7002       /* This is not an assert because it can be caused by bad debug info.  */
7003       if (sig_type->signature != cu->header.signature)
7004         {
7005           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7006                    " TU at offset %s [in module %s]"),
7007                  hex_string (sig_type->signature),
7008                  hex_string (cu->header.signature),
7009                  sect_offset_str (dwo_unit->sect_off),
7010                  bfd_get_filename (abfd));
7011         }
7012       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7013       /* For DWOs coming from DWP files, we don't know the CU length
7014          nor the type's offset in the TU until now.  */
7015       dwo_unit->length = get_cu_length (&cu->header);
7016       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7017
7018       /* Establish the type offset that can be used to lookup the type.
7019          For DWO files, we don't know it until now.  */
7020       sig_type->type_offset_in_section
7021         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7022     }
7023   else
7024     {
7025       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7026                                                 &cu->header, section,
7027                                                 dwo_abbrev_section,
7028                                                 info_ptr, rcuh_kind::COMPILE);
7029       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7030       /* For DWOs coming from DWP files, we don't know the CU length
7031          until now.  */
7032       dwo_unit->length = get_cu_length (&cu->header);
7033     }
7034
7035   *result_dwo_abbrev_table
7036     = abbrev_table::read (objfile, dwo_abbrev_section,
7037                           cu->header.abbrev_sect_off);
7038   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7039                       result_dwo_abbrev_table->get ());
7040
7041   /* Read in the die, but leave space to copy over the attributes
7042      from the stub.  This has the benefit of simplifying the rest of
7043      the code - all the work to maintain the illusion of a single
7044      DW_TAG_{compile,type}_unit DIE is done here.  */
7045   num_extra_attrs = ((stmt_list != NULL)
7046                      + (low_pc != NULL)
7047                      + (high_pc != NULL)
7048                      + (ranges != NULL)
7049                      + (comp_dir != NULL));
7050   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7051                               num_extra_attrs);
7052
7053   /* Copy over the attributes from the stub to the DIE we just read in.  */
7054   comp_unit_die = *result_comp_unit_die;
7055   i = comp_unit_die->num_attrs;
7056   if (stmt_list != NULL)
7057     comp_unit_die->attrs[i++] = *stmt_list;
7058   if (low_pc != NULL)
7059     comp_unit_die->attrs[i++] = *low_pc;
7060   if (high_pc != NULL)
7061     comp_unit_die->attrs[i++] = *high_pc;
7062   if (ranges != NULL)
7063     comp_unit_die->attrs[i++] = *ranges;
7064   if (comp_dir != NULL)
7065     comp_unit_die->attrs[i++] = *comp_dir;
7066   comp_unit_die->num_attrs += num_extra_attrs;
7067
7068   if (dwarf_die_debug)
7069     {
7070       fprintf_unfiltered (gdb_stdlog,
7071                           "Read die from %s@0x%x of %s:\n",
7072                           section->get_name (),
7073                           (unsigned) (begin_info_ptr - section->buffer),
7074                           bfd_get_filename (abfd));
7075       dump_die (comp_unit_die, dwarf_die_debug);
7076     }
7077
7078   /* Skip dummy compilation units.  */
7079   if (info_ptr >= begin_info_ptr + dwo_unit->length
7080       || peek_abbrev_code (abfd, info_ptr) == 0)
7081     return 0;
7082
7083   *result_info_ptr = info_ptr;
7084   return 1;
7085 }
7086
7087 /* Return the signature of the compile unit, if found. In DWARF 4 and before,
7088    the signature is in the DW_AT_GNU_dwo_id attribute. In DWARF 5 and later, the
7089    signature is part of the header.  */
7090 static gdb::optional<ULONGEST>
7091 lookup_dwo_id (struct dwarf2_cu *cu, struct die_info* comp_unit_die)
7092 {
7093   if (cu->header.version >= 5)
7094     return cu->header.signature;
7095   struct attribute *attr;
7096   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7097   if (attr == nullptr)
7098     return gdb::optional<ULONGEST> ();
7099   return DW_UNSND (attr);
7100 }
7101
7102 /* Subroutine of cutu_reader to simplify it.
7103    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7104    Returns NULL if the specified DWO unit cannot be found.  */
7105
7106 static struct dwo_unit *
7107 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7108                  struct die_info *comp_unit_die,
7109                  const char *dwo_name)
7110 {
7111   struct dwarf2_cu *cu = this_cu->cu;
7112   struct dwo_unit *dwo_unit;
7113   const char *comp_dir;
7114
7115   gdb_assert (cu != NULL);
7116
7117   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7118   dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
7119   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7120
7121   if (this_cu->is_debug_types)
7122     {
7123       struct signatured_type *sig_type;
7124
7125       /* Since this_cu is the first member of struct signatured_type,
7126          we can go from a pointer to one to a pointer to the other.  */
7127       sig_type = (struct signatured_type *) this_cu;
7128       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7129     }
7130   else
7131     {
7132       gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
7133       if (!signature.has_value ())
7134         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7135                  " [in module %s]"),
7136                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7137       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7138                                        *signature);
7139     }
7140
7141   return dwo_unit;
7142 }
7143
7144 /* Subroutine of cutu_reader to simplify it.
7145    See it for a description of the parameters.
7146    Read a TU directly from a DWO file, bypassing the stub.  */
7147
7148 void
7149 cutu_reader::init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7150                                         int use_existing_cu, int keep)
7151 {
7152   struct signatured_type *sig_type;
7153   struct die_reader_specs reader;
7154
7155   /* Verify we can do the following downcast, and that we have the
7156      data we need.  */
7157   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7158   sig_type = (struct signatured_type *) this_cu;
7159   gdb_assert (sig_type->dwo_unit != NULL);
7160
7161   if (use_existing_cu && this_cu->cu != NULL)
7162     {
7163       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7164       /* There's no need to do the rereading_dwo_cu handling that
7165          cutu_reader does since we don't read the stub.  */
7166     }
7167   else
7168     {
7169       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7170       gdb_assert (this_cu->cu == NULL);
7171       m_new_cu.reset (new dwarf2_cu (this_cu));
7172     }
7173
7174   /* A future optimization, if needed, would be to use an existing
7175      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7176      could share abbrev tables.  */
7177
7178   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7179                               NULL /* stub_comp_unit_die */,
7180                               sig_type->dwo_unit->dwo_file->comp_dir,
7181                               &reader, &info_ptr,
7182                               &comp_unit_die,
7183                               &m_dwo_abbrev_table) == 0)
7184     {
7185       /* Dummy die.  */
7186       dummy_p = true;
7187     }
7188 }
7189
7190 /* Initialize a CU (or TU) and read its DIEs.
7191    If the CU defers to a DWO file, read the DWO file as well.
7192
7193    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7194    Otherwise the table specified in the comp unit header is read in and used.
7195    This is an optimization for when we already have the abbrev table.
7196
7197    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7198    Otherwise, a new CU is allocated with xmalloc.
7199
7200    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7201    read_in_chain.  Otherwise the dwarf2_cu data is freed at the
7202    end.  */
7203
7204 cutu_reader::cutu_reader (struct dwarf2_per_cu_data *this_cu,
7205                           struct abbrev_table *abbrev_table,
7206                           int use_existing_cu, int keep,
7207                           bool skip_partial)
7208   : die_reader_specs {},
7209     m_this_cu (this_cu),
7210     m_keep (keep)
7211 {
7212   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7213   struct objfile *objfile = dwarf2_per_objfile->objfile;
7214   struct dwarf2_section_info *section = this_cu->section;
7215   bfd *abfd = section->get_bfd_owner ();
7216   struct dwarf2_cu *cu;
7217   const gdb_byte *begin_info_ptr;
7218   struct signatured_type *sig_type = NULL;
7219   struct dwarf2_section_info *abbrev_section;
7220   /* Non-zero if CU currently points to a DWO file and we need to
7221      reread it.  When this happens we need to reread the skeleton die
7222      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7223   int rereading_dwo_cu = 0;
7224
7225   if (dwarf_die_debug)
7226     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7227                         this_cu->is_debug_types ? "type" : "comp",
7228                         sect_offset_str (this_cu->sect_off));
7229
7230   if (use_existing_cu)
7231     gdb_assert (keep);
7232
7233   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7234      file (instead of going through the stub), short-circuit all of this.  */
7235   if (this_cu->reading_dwo_directly)
7236     {
7237       /* Narrow down the scope of possibilities to have to understand.  */
7238       gdb_assert (this_cu->is_debug_types);
7239       gdb_assert (abbrev_table == NULL);
7240       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep);
7241       return;
7242     }
7243
7244   /* This is cheap if the section is already read in.  */
7245   section->read (objfile);
7246
7247   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7248
7249   abbrev_section = get_abbrev_section_for_cu (this_cu);
7250
7251   if (use_existing_cu && this_cu->cu != NULL)
7252     {
7253       cu = this_cu->cu;
7254       /* If this CU is from a DWO file we need to start over, we need to
7255          refetch the attributes from the skeleton CU.
7256          This could be optimized by retrieving those attributes from when we
7257          were here the first time: the previous comp_unit_die was stored in
7258          comp_unit_obstack.  But there's no data yet that we need this
7259          optimization.  */
7260       if (cu->dwo_unit != NULL)
7261         rereading_dwo_cu = 1;
7262     }
7263   else
7264     {
7265       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7266       gdb_assert (this_cu->cu == NULL);
7267       m_new_cu.reset (new dwarf2_cu (this_cu));
7268       cu = m_new_cu.get ();
7269     }
7270
7271   /* Get the header.  */
7272   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7273     {
7274       /* We already have the header, there's no need to read it in again.  */
7275       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7276     }
7277   else
7278     {
7279       if (this_cu->is_debug_types)
7280         {
7281           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7282                                                     &cu->header, section,
7283                                                     abbrev_section, info_ptr,
7284                                                     rcuh_kind::TYPE);
7285
7286           /* Since per_cu is the first member of struct signatured_type,
7287              we can go from a pointer to one to a pointer to the other.  */
7288           sig_type = (struct signatured_type *) this_cu;
7289           gdb_assert (sig_type->signature == cu->header.signature);
7290           gdb_assert (sig_type->type_offset_in_tu
7291                       == cu->header.type_cu_offset_in_tu);
7292           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7293
7294           /* LENGTH has not been set yet for type units if we're
7295              using .gdb_index.  */
7296           this_cu->length = get_cu_length (&cu->header);
7297
7298           /* Establish the type offset that can be used to lookup the type.  */
7299           sig_type->type_offset_in_section =
7300             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7301
7302           this_cu->dwarf_version = cu->header.version;
7303         }
7304       else
7305         {
7306           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7307                                                     &cu->header, section,
7308                                                     abbrev_section,
7309                                                     info_ptr,
7310                                                     rcuh_kind::COMPILE);
7311
7312           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7313           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7314           this_cu->dwarf_version = cu->header.version;
7315         }
7316     }
7317
7318   /* Skip dummy compilation units.  */
7319   if (info_ptr >= begin_info_ptr + this_cu->length
7320       || peek_abbrev_code (abfd, info_ptr) == 0)
7321     {
7322       dummy_p = true;
7323       return;
7324     }
7325
7326   /* If we don't have them yet, read the abbrevs for this compilation unit.
7327      And if we need to read them now, make sure they're freed when we're
7328      done.  */
7329   if (abbrev_table != NULL)
7330     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7331   else
7332     {
7333       m_abbrev_table_holder
7334         = abbrev_table::read (objfile, abbrev_section,
7335                               cu->header.abbrev_sect_off);
7336       abbrev_table = m_abbrev_table_holder.get ();
7337     }
7338
7339   /* Read the top level CU/TU die.  */
7340   init_cu_die_reader (this, cu, section, NULL, abbrev_table);
7341   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
7342
7343   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7344     {
7345       dummy_p = true;
7346       return;
7347     }
7348
7349   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7350      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7351      table from the DWO file and pass the ownership over to us.  It will be
7352      referenced from READER, so we must make sure to free it after we're done
7353      with READER.
7354
7355      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7356      DWO CU, that this test will fail (the attribute will not be present).  */
7357   const char *dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
7358   if (dwo_name != nullptr)
7359     {
7360       struct dwo_unit *dwo_unit;
7361       struct die_info *dwo_comp_unit_die;
7362
7363       if (comp_unit_die->has_children)
7364         {
7365           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7366                        " has children (offset %s) [in module %s]"),
7367                      sect_offset_str (this_cu->sect_off),
7368                      bfd_get_filename (abfd));
7369         }
7370       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die, dwo_name);
7371       if (dwo_unit != NULL)
7372         {
7373           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7374                                       comp_unit_die, NULL,
7375                                       this, &info_ptr,
7376                                       &dwo_comp_unit_die,
7377                                       &m_dwo_abbrev_table) == 0)
7378             {
7379               /* Dummy die.  */
7380               dummy_p = true;
7381               return;
7382             }
7383           comp_unit_die = dwo_comp_unit_die;
7384         }
7385       else
7386         {
7387           /* Yikes, we couldn't find the rest of the DIE, we only have
7388              the stub.  A complaint has already been logged.  There's
7389              not much more we can do except pass on the stub DIE to
7390              die_reader_func.  We don't want to throw an error on bad
7391              debug info.  */
7392         }
7393     }
7394 }
7395
7396 cutu_reader::~cutu_reader ()
7397 {
7398   /* Done, clean up.  */
7399   if (m_new_cu != NULL && m_keep && !dummy_p)
7400     {
7401       struct dwarf2_per_objfile *dwarf2_per_objfile
7402         = m_this_cu->dwarf2_per_objfile;
7403       /* Link this CU into read_in_chain.  */
7404       m_this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7405       dwarf2_per_objfile->read_in_chain = m_this_cu;
7406       /* The chain owns it now.  */
7407       m_new_cu.release ();
7408     }
7409 }
7410
7411 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name (DW_AT_dwo_name)
7412    if present. DWO_FILE, if non-NULL, is the DWO file to read (the caller is
7413    assumed to have already done the lookup to find the DWO file).
7414
7415    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7416    THIS_CU->is_debug_types, but nothing else.
7417
7418    We fill in THIS_CU->length.
7419
7420    THIS_CU->cu is always freed when done.
7421    This is done in order to not leave THIS_CU->cu in a state where we have
7422    to care whether it refers to the "main" CU or the DWO CU.
7423
7424    When parent_cu is passed, it is used to provide a default value for
7425    str_offsets_base and addr_base from the parent.  */
7426
7427 cutu_reader::cutu_reader (struct dwarf2_per_cu_data *this_cu,
7428                           struct dwarf2_cu *parent_cu,
7429                           struct dwo_file *dwo_file)
7430   : die_reader_specs {},
7431     m_this_cu (this_cu)
7432 {
7433   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7434   struct objfile *objfile = dwarf2_per_objfile->objfile;
7435   struct dwarf2_section_info *section = this_cu->section;
7436   bfd *abfd = section->get_bfd_owner ();
7437   struct dwarf2_section_info *abbrev_section;
7438   const gdb_byte *begin_info_ptr, *info_ptr;
7439
7440   if (dwarf_die_debug)
7441     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7442                         this_cu->is_debug_types ? "type" : "comp",
7443                         sect_offset_str (this_cu->sect_off));
7444
7445   gdb_assert (this_cu->cu == NULL);
7446
7447   abbrev_section = (dwo_file != NULL
7448                     ? &dwo_file->sections.abbrev
7449                     : get_abbrev_section_for_cu (this_cu));
7450
7451   /* This is cheap if the section is already read in.  */
7452   section->read (objfile);
7453
7454   m_new_cu.reset (new dwarf2_cu (this_cu));
7455
7456   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7457   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7458                                             &m_new_cu->header, section,
7459                                             abbrev_section, info_ptr,
7460                                             (this_cu->is_debug_types
7461                                              ? rcuh_kind::TYPE
7462                                              : rcuh_kind::COMPILE));
7463
7464   if (parent_cu != nullptr)
7465     {
7466       m_new_cu->str_offsets_base = parent_cu->str_offsets_base;
7467       m_new_cu->addr_base = parent_cu->addr_base;
7468     }
7469   this_cu->length = get_cu_length (&m_new_cu->header);
7470
7471   /* Skip dummy compilation units.  */
7472   if (info_ptr >= begin_info_ptr + this_cu->length
7473       || peek_abbrev_code (abfd, info_ptr) == 0)
7474     {
7475       dummy_p = true;
7476       return;
7477     }
7478
7479   m_abbrev_table_holder
7480     = abbrev_table::read (objfile, abbrev_section,
7481                           m_new_cu->header.abbrev_sect_off);
7482
7483   init_cu_die_reader (this, m_new_cu.get (), section, dwo_file,
7484                       m_abbrev_table_holder.get ());
7485   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
7486 }
7487
7488 \f
7489 /* Type Unit Groups.
7490
7491    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7492    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7493    so that all types coming from the same compilation (.o file) are grouped
7494    together.  A future step could be to put the types in the same symtab as
7495    the CU the types ultimately came from.  */
7496
7497 static hashval_t
7498 hash_type_unit_group (const void *item)
7499 {
7500   const struct type_unit_group *tu_group
7501     = (const struct type_unit_group *) item;
7502
7503   return hash_stmt_list_entry (&tu_group->hash);
7504 }
7505
7506 static int
7507 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7508 {
7509   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7510   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7511
7512   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7513 }
7514
7515 /* Allocate a hash table for type unit groups.  */
7516
7517 static htab_up
7518 allocate_type_unit_groups_table (struct objfile *objfile)
7519 {
7520   return htab_up (htab_create_alloc (3,
7521                                      hash_type_unit_group,
7522                                      eq_type_unit_group,
7523                                      NULL, xcalloc, xfree));
7524 }
7525
7526 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7527    partial symtabs.  We combine several TUs per psymtab to not let the size
7528    of any one psymtab grow too big.  */
7529 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7530 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7531
7532 /* Helper routine for get_type_unit_group.
7533    Create the type_unit_group object used to hold one or more TUs.  */
7534
7535 static struct type_unit_group *
7536 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7537 {
7538   struct dwarf2_per_objfile *dwarf2_per_objfile
7539     = cu->per_cu->dwarf2_per_objfile;
7540   struct objfile *objfile = dwarf2_per_objfile->objfile;
7541   struct dwarf2_per_cu_data *per_cu;
7542   struct type_unit_group *tu_group;
7543
7544   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7545                              struct type_unit_group);
7546   per_cu = &tu_group->per_cu;
7547   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7548
7549   if (dwarf2_per_objfile->using_index)
7550     {
7551       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7552                                         struct dwarf2_per_cu_quick_data);
7553     }
7554   else
7555     {
7556       unsigned int line_offset = to_underlying (line_offset_struct);
7557       dwarf2_psymtab *pst;
7558       std::string name;
7559
7560       /* Give the symtab a useful name for debug purposes.  */
7561       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7562         name = string_printf ("<type_units_%d>",
7563                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7564       else
7565         name = string_printf ("<type_units_at_0x%x>", line_offset);
7566
7567       pst = create_partial_symtab (per_cu, name.c_str ());
7568       pst->anonymous = true;
7569     }
7570
7571   tu_group->hash.dwo_unit = cu->dwo_unit;
7572   tu_group->hash.line_sect_off = line_offset_struct;
7573
7574   return tu_group;
7575 }
7576
7577 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7578    STMT_LIST is a DW_AT_stmt_list attribute.  */
7579
7580 static struct type_unit_group *
7581 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7582 {
7583   struct dwarf2_per_objfile *dwarf2_per_objfile
7584     = cu->per_cu->dwarf2_per_objfile;
7585   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7586   struct type_unit_group *tu_group;
7587   void **slot;
7588   unsigned int line_offset;
7589   struct type_unit_group type_unit_group_for_lookup;
7590
7591   if (dwarf2_per_objfile->type_unit_groups == NULL)
7592     {
7593       dwarf2_per_objfile->type_unit_groups =
7594         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7595     }
7596
7597   /* Do we need to create a new group, or can we use an existing one?  */
7598
7599   if (stmt_list)
7600     {
7601       line_offset = DW_UNSND (stmt_list);
7602       ++tu_stats->nr_symtab_sharers;
7603     }
7604   else
7605     {
7606       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7607          We can do various things here like create one group per TU or
7608          spread them over multiple groups to split up the expansion work.
7609          To avoid worst case scenarios (too many groups or too large groups)
7610          we, umm, group them in bunches.  */
7611       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7612                      | (tu_stats->nr_stmt_less_type_units
7613                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7614       ++tu_stats->nr_stmt_less_type_units;
7615     }
7616
7617   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7618   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7619   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups.get (),
7620                          &type_unit_group_for_lookup, INSERT);
7621   if (*slot != NULL)
7622     {
7623       tu_group = (struct type_unit_group *) *slot;
7624       gdb_assert (tu_group != NULL);
7625     }
7626   else
7627     {
7628       sect_offset line_offset_struct = (sect_offset) line_offset;
7629       tu_group = create_type_unit_group (cu, line_offset_struct);
7630       *slot = tu_group;
7631       ++tu_stats->nr_symtabs;
7632     }
7633
7634   return tu_group;
7635 }
7636 \f
7637 /* Partial symbol tables.  */
7638
7639 /* Create a psymtab named NAME and assign it to PER_CU.
7640
7641    The caller must fill in the following details:
7642    dirname, textlow, texthigh.  */
7643
7644 static dwarf2_psymtab *
7645 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7646 {
7647   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7648   dwarf2_psymtab *pst;
7649
7650   pst = new dwarf2_psymtab (name, objfile, 0);
7651
7652   pst->psymtabs_addrmap_supported = true;
7653
7654   /* This is the glue that links PST into GDB's symbol API.  */
7655   pst->per_cu_data = per_cu;
7656   per_cu->v.psymtab = pst;
7657
7658   return pst;
7659 }
7660
7661 /* DIE reader function for process_psymtab_comp_unit.  */
7662
7663 static void
7664 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7665                                   const gdb_byte *info_ptr,
7666                                   struct die_info *comp_unit_die,
7667                                   int want_partial_unit,
7668                                   enum language pretend_language)
7669 {
7670   struct dwarf2_cu *cu = reader->cu;
7671   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7672   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7673   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7674   CORE_ADDR baseaddr;
7675   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7676   dwarf2_psymtab *pst;
7677   enum pc_bounds_kind cu_bounds_kind;
7678   const char *filename;
7679
7680   if (comp_unit_die->tag == DW_TAG_partial_unit && !want_partial_unit)
7681     return;
7682
7683   gdb_assert (! per_cu->is_debug_types);
7684
7685   prepare_one_comp_unit (cu, comp_unit_die, pretend_language);
7686
7687   /* Allocate a new partial symbol table structure.  */
7688   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7689   if (filename == NULL)
7690     filename = "";
7691
7692   pst = create_partial_symtab (per_cu, filename);
7693
7694   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7695   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7696
7697   baseaddr = objfile->text_section_offset ();
7698
7699   dwarf2_find_base_address (comp_unit_die, cu);
7700
7701   /* Possibly set the default values of LOWPC and HIGHPC from
7702      `DW_AT_ranges'.  */
7703   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7704                                          &best_highpc, cu, pst);
7705   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7706     {
7707       CORE_ADDR low
7708         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
7709            - baseaddr);
7710       CORE_ADDR high
7711         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
7712            - baseaddr - 1);
7713       /* Store the contiguous range if it is not empty; it can be
7714          empty for CUs with no code.  */
7715       addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
7716                          low, high, pst);
7717     }
7718
7719   /* Check if comp unit has_children.
7720      If so, read the rest of the partial symbols from this comp unit.
7721      If not, there's no more debug_info for this comp unit.  */
7722   if (comp_unit_die->has_children)
7723     {
7724       struct partial_die_info *first_die;
7725       CORE_ADDR lowpc, highpc;
7726
7727       lowpc = ((CORE_ADDR) -1);
7728       highpc = ((CORE_ADDR) 0);
7729
7730       first_die = load_partial_dies (reader, info_ptr, 1);
7731
7732       scan_partial_symbols (first_die, &lowpc, &highpc,
7733                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7734
7735       /* If we didn't find a lowpc, set it to highpc to avoid
7736          complaints from `maint check'.  */
7737       if (lowpc == ((CORE_ADDR) -1))
7738         lowpc = highpc;
7739
7740       /* If the compilation unit didn't have an explicit address range,
7741          then use the information extracted from its child dies.  */
7742       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7743         {
7744           best_lowpc = lowpc;
7745           best_highpc = highpc;
7746         }
7747     }
7748   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
7749                                                  best_lowpc + baseaddr)
7750                      - baseaddr);
7751   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
7752                                                   best_highpc + baseaddr)
7753                       - baseaddr);
7754
7755   end_psymtab_common (objfile, pst);
7756
7757   if (!cu->per_cu->imported_symtabs_empty ())
7758     {
7759       int i;
7760       int len = cu->per_cu->imported_symtabs_size ();
7761
7762       /* Fill in 'dependencies' here; we fill in 'users' in a
7763          post-pass.  */
7764       pst->number_of_dependencies = len;
7765       pst->dependencies
7766         = objfile->partial_symtabs->allocate_dependencies (len);
7767       for (i = 0; i < len; ++i)
7768         {
7769           pst->dependencies[i]
7770             = cu->per_cu->imported_symtabs->at (i)->v.psymtab;
7771         }
7772
7773       cu->per_cu->imported_symtabs_free ();
7774     }
7775
7776   /* Get the list of files included in the current compilation unit,
7777      and build a psymtab for each of them.  */
7778   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7779
7780   if (dwarf_read_debug)
7781     fprintf_unfiltered (gdb_stdlog,
7782                         "Psymtab for %s unit @%s: %s - %s"
7783                         ", %d global, %d static syms\n",
7784                         per_cu->is_debug_types ? "type" : "comp",
7785                         sect_offset_str (per_cu->sect_off),
7786                         paddress (gdbarch, pst->text_low (objfile)),
7787                         paddress (gdbarch, pst->text_high (objfile)),
7788                         pst->n_global_syms, pst->n_static_syms);
7789 }
7790
7791 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7792    Process compilation unit THIS_CU for a psymtab.  */
7793
7794 static void
7795 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
7796                            int want_partial_unit,
7797                            enum language pretend_language)
7798 {
7799   /* If this compilation unit was already read in, free the
7800      cached copy in order to read it in again.  This is
7801      necessary because we skipped some symbols when we first
7802      read in the compilation unit (see load_partial_dies).
7803      This problem could be avoided, but the benefit is unclear.  */
7804   if (this_cu->cu != NULL)
7805     free_one_cached_comp_unit (this_cu);
7806
7807   cutu_reader reader (this_cu, NULL, 0, 0, false);
7808
7809   if (reader.dummy_p)
7810     {
7811       /* Nothing.  */
7812     }
7813   else if (this_cu->is_debug_types)
7814     build_type_psymtabs_reader (&reader, reader.info_ptr,
7815                                 reader.comp_unit_die);
7816   else
7817     process_psymtab_comp_unit_reader (&reader, reader.info_ptr,
7818                                       reader.comp_unit_die,
7819                                       want_partial_unit,
7820                                       pretend_language);
7821
7822   /* Age out any secondary CUs.  */
7823   age_cached_comp_units (this_cu->dwarf2_per_objfile);
7824 }
7825
7826 /* Reader function for build_type_psymtabs.  */
7827
7828 static void
7829 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7830                             const gdb_byte *info_ptr,
7831                             struct die_info *type_unit_die)
7832 {
7833   struct dwarf2_per_objfile *dwarf2_per_objfile
7834     = reader->cu->per_cu->dwarf2_per_objfile;
7835   struct objfile *objfile = dwarf2_per_objfile->objfile;
7836   struct dwarf2_cu *cu = reader->cu;
7837   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7838   struct signatured_type *sig_type;
7839   struct type_unit_group *tu_group;
7840   struct attribute *attr;
7841   struct partial_die_info *first_die;
7842   CORE_ADDR lowpc, highpc;
7843   dwarf2_psymtab *pst;
7844
7845   gdb_assert (per_cu->is_debug_types);
7846   sig_type = (struct signatured_type *) per_cu;
7847
7848   if (! type_unit_die->has_children)
7849     return;
7850
7851   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
7852   tu_group = get_type_unit_group (cu, attr);
7853
7854   if (tu_group->tus == nullptr)
7855     tu_group->tus = new std::vector<signatured_type *>;
7856   tu_group->tus->push_back (sig_type);
7857
7858   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7859   pst = create_partial_symtab (per_cu, "");
7860   pst->anonymous = true;
7861
7862   first_die = load_partial_dies (reader, info_ptr, 1);
7863
7864   lowpc = (CORE_ADDR) -1;
7865   highpc = (CORE_ADDR) 0;
7866   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7867
7868   end_psymtab_common (objfile, pst);
7869 }
7870
7871 /* Struct used to sort TUs by their abbreviation table offset.  */
7872
7873 struct tu_abbrev_offset
7874 {
7875   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
7876   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
7877   {}
7878
7879   signatured_type *sig_type;
7880   sect_offset abbrev_offset;
7881 };
7882
7883 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
7884
7885 static bool
7886 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
7887                           const struct tu_abbrev_offset &b)
7888 {
7889   return a.abbrev_offset < b.abbrev_offset;
7890 }
7891
7892 /* Efficiently read all the type units.
7893    This does the bulk of the work for build_type_psymtabs.
7894
7895    The efficiency is because we sort TUs by the abbrev table they use and
7896    only read each abbrev table once.  In one program there are 200K TUs
7897    sharing 8K abbrev tables.
7898
7899    The main purpose of this function is to support building the
7900    dwarf2_per_objfile->type_unit_groups table.
7901    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7902    can collapse the search space by grouping them by stmt_list.
7903    The savings can be significant, in the same program from above the 200K TUs
7904    share 8K stmt_list tables.
7905
7906    FUNC is expected to call get_type_unit_group, which will create the
7907    struct type_unit_group if necessary and add it to
7908    dwarf2_per_objfile->type_unit_groups.  */
7909
7910 static void
7911 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
7912 {
7913   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7914   abbrev_table_up abbrev_table;
7915   sect_offset abbrev_offset;
7916
7917   /* It's up to the caller to not call us multiple times.  */
7918   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
7919
7920   if (dwarf2_per_objfile->all_type_units.empty ())
7921     return;
7922
7923   /* TUs typically share abbrev tables, and there can be way more TUs than
7924      abbrev tables.  Sort by abbrev table to reduce the number of times we
7925      read each abbrev table in.
7926      Alternatives are to punt or to maintain a cache of abbrev tables.
7927      This is simpler and efficient enough for now.
7928
7929      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7930      symtab to use).  Typically TUs with the same abbrev offset have the same
7931      stmt_list value too so in practice this should work well.
7932
7933      The basic algorithm here is:
7934
7935       sort TUs by abbrev table
7936       for each TU with same abbrev table:
7937         read abbrev table if first user
7938         read TU top level DIE
7939           [IWBN if DWO skeletons had DW_AT_stmt_list]
7940         call FUNC  */
7941
7942   if (dwarf_read_debug)
7943     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
7944
7945   /* Sort in a separate table to maintain the order of all_type_units
7946      for .gdb_index: TU indices directly index all_type_units.  */
7947   std::vector<tu_abbrev_offset> sorted_by_abbrev;
7948   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
7949
7950   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
7951     sorted_by_abbrev.emplace_back
7952       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
7953                                      sig_type->per_cu.section,
7954                                      sig_type->per_cu.sect_off));
7955
7956   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
7957              sort_tu_by_abbrev_offset);
7958
7959   abbrev_offset = (sect_offset) ~(unsigned) 0;
7960
7961   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
7962     {
7963       /* Switch to the next abbrev table if necessary.  */
7964       if (abbrev_table == NULL
7965           || tu.abbrev_offset != abbrev_offset)
7966         {
7967           abbrev_offset = tu.abbrev_offset;
7968           abbrev_table =
7969             abbrev_table::read (dwarf2_per_objfile->objfile,
7970                                 &dwarf2_per_objfile->abbrev,
7971                                 abbrev_offset);
7972           ++tu_stats->nr_uniq_abbrev_tables;
7973         }
7974
7975       cutu_reader reader (&tu.sig_type->per_cu, abbrev_table.get (),
7976                           0, 0, false);
7977       if (!reader.dummy_p)
7978         build_type_psymtabs_reader (&reader, reader.info_ptr,
7979                                     reader.comp_unit_die);
7980     }
7981 }
7982
7983 /* Print collected type unit statistics.  */
7984
7985 static void
7986 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
7987 {
7988   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7989
7990   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
7991   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
7992                       dwarf2_per_objfile->all_type_units.size ());
7993   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
7994                       tu_stats->nr_uniq_abbrev_tables);
7995   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
7996                       tu_stats->nr_symtabs);
7997   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
7998                       tu_stats->nr_symtab_sharers);
7999   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8000                       tu_stats->nr_stmt_less_type_units);
8001   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8002                       tu_stats->nr_all_type_units_reallocs);
8003 }
8004
8005 /* Traversal function for build_type_psymtabs.  */
8006
8007 static int
8008 build_type_psymtab_dependencies (void **slot, void *info)
8009 {
8010   struct dwarf2_per_objfile *dwarf2_per_objfile
8011     = (struct dwarf2_per_objfile *) info;
8012   struct objfile *objfile = dwarf2_per_objfile->objfile;
8013   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8014   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8015   dwarf2_psymtab *pst = per_cu->v.psymtab;
8016   int len = (tu_group->tus == nullptr) ? 0 : tu_group->tus->size ();
8017   int i;
8018
8019   gdb_assert (len > 0);
8020   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8021
8022   pst->number_of_dependencies = len;
8023   pst->dependencies = objfile->partial_symtabs->allocate_dependencies (len);
8024   for (i = 0; i < len; ++i)
8025     {
8026       struct signatured_type *iter = tu_group->tus->at (i);
8027       gdb_assert (iter->per_cu.is_debug_types);
8028       pst->dependencies[i] = iter->per_cu.v.psymtab;
8029       iter->type_unit_group = tu_group;
8030     }
8031
8032   delete tu_group->tus;
8033   tu_group->tus = nullptr;
8034
8035   return 1;
8036 }
8037
8038 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8039    Build partial symbol tables for the .debug_types comp-units.  */
8040
8041 static void
8042 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8043 {
8044   if (! create_all_type_units (dwarf2_per_objfile))
8045     return;
8046
8047   build_type_psymtabs_1 (dwarf2_per_objfile);
8048 }
8049
8050 /* Traversal function for process_skeletonless_type_unit.
8051    Read a TU in a DWO file and build partial symbols for it.  */
8052
8053 static int
8054 process_skeletonless_type_unit (void **slot, void *info)
8055 {
8056   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8057   struct dwarf2_per_objfile *dwarf2_per_objfile
8058     = (struct dwarf2_per_objfile *) info;
8059   struct signatured_type find_entry, *entry;
8060
8061   /* If this TU doesn't exist in the global table, add it and read it in.  */
8062
8063   if (dwarf2_per_objfile->signatured_types == NULL)
8064     {
8065       dwarf2_per_objfile->signatured_types
8066         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8067     }
8068
8069   find_entry.signature = dwo_unit->signature;
8070   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
8071                          &find_entry, INSERT);
8072   /* If we've already seen this type there's nothing to do.  What's happening
8073      is we're doing our own version of comdat-folding here.  */
8074   if (*slot != NULL)
8075     return 1;
8076
8077   /* This does the job that create_all_type_units would have done for
8078      this TU.  */
8079   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8080   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8081   *slot = entry;
8082
8083   /* This does the job that build_type_psymtabs_1 would have done.  */
8084   cutu_reader reader (&entry->per_cu, NULL, 0, 0, false);
8085   if (!reader.dummy_p)
8086     build_type_psymtabs_reader (&reader, reader.info_ptr,
8087                                 reader.comp_unit_die);
8088
8089   return 1;
8090 }
8091
8092 /* Traversal function for process_skeletonless_type_units.  */
8093
8094 static int
8095 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8096 {
8097   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8098
8099   if (dwo_file->tus != NULL)
8100     htab_traverse_noresize (dwo_file->tus.get (),
8101                             process_skeletonless_type_unit, info);
8102
8103   return 1;
8104 }
8105
8106 /* Scan all TUs of DWO files, verifying we've processed them.
8107    This is needed in case a TU was emitted without its skeleton.
8108    Note: This can't be done until we know what all the DWO files are.  */
8109
8110 static void
8111 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8112 {
8113   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8114   if (get_dwp_file (dwarf2_per_objfile) == NULL
8115       && dwarf2_per_objfile->dwo_files != NULL)
8116     {
8117       htab_traverse_noresize (dwarf2_per_objfile->dwo_files.get (),
8118                               process_dwo_file_for_skeletonless_type_units,
8119                               dwarf2_per_objfile);
8120     }
8121 }
8122
8123 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8124
8125 static void
8126 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8127 {
8128   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8129     {
8130       dwarf2_psymtab *pst = per_cu->v.psymtab;
8131
8132       if (pst == NULL)
8133         continue;
8134
8135       for (int j = 0; j < pst->number_of_dependencies; ++j)
8136         {
8137           /* Set the 'user' field only if it is not already set.  */
8138           if (pst->dependencies[j]->user == NULL)
8139             pst->dependencies[j]->user = pst;
8140         }
8141     }
8142 }
8143
8144 /* Build the partial symbol table by doing a quick pass through the
8145    .debug_info and .debug_abbrev sections.  */
8146
8147 static void
8148 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8149 {
8150   struct objfile *objfile = dwarf2_per_objfile->objfile;
8151
8152   if (dwarf_read_debug)
8153     {
8154       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8155                           objfile_name (objfile));
8156     }
8157
8158   dwarf2_per_objfile->reading_partial_symbols = 1;
8159
8160   dwarf2_per_objfile->info.read (objfile);
8161
8162   /* Any cached compilation units will be linked by the per-objfile
8163      read_in_chain.  Make sure to free them when we're done.  */
8164   free_cached_comp_units freer (dwarf2_per_objfile);
8165
8166   build_type_psymtabs (dwarf2_per_objfile);
8167
8168   create_all_comp_units (dwarf2_per_objfile);
8169
8170   /* Create a temporary address map on a temporary obstack.  We later
8171      copy this to the final obstack.  */
8172   auto_obstack temp_obstack;
8173
8174   scoped_restore save_psymtabs_addrmap
8175     = make_scoped_restore (&objfile->partial_symtabs->psymtabs_addrmap,
8176                            addrmap_create_mutable (&temp_obstack));
8177
8178   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8179     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8180
8181   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8182   process_skeletonless_type_units (dwarf2_per_objfile);
8183
8184   /* Now that all TUs have been processed we can fill in the dependencies.  */
8185   if (dwarf2_per_objfile->type_unit_groups != NULL)
8186     {
8187       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups.get (),
8188                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8189     }
8190
8191   if (dwarf_read_debug)
8192     print_tu_stats (dwarf2_per_objfile);
8193
8194   set_partial_user (dwarf2_per_objfile);
8195
8196   objfile->partial_symtabs->psymtabs_addrmap
8197     = addrmap_create_fixed (objfile->partial_symtabs->psymtabs_addrmap,
8198                             objfile->partial_symtabs->obstack ());
8199   /* At this point we want to keep the address map.  */
8200   save_psymtabs_addrmap.release ();
8201
8202   if (dwarf_read_debug)
8203     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8204                         objfile_name (objfile));
8205 }
8206
8207 /* Load the partial DIEs for a secondary CU into memory.
8208    This is also used when rereading a primary CU with load_all_dies.  */
8209
8210 static void
8211 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8212 {
8213   cutu_reader reader (this_cu, NULL, 1, 1, false);
8214
8215   if (!reader.dummy_p)
8216     {
8217       prepare_one_comp_unit (reader.cu, reader.comp_unit_die,
8218                              language_minimal);
8219
8220       /* Check if comp unit has_children.
8221          If so, read the rest of the partial symbols from this comp unit.
8222          If not, there's no more debug_info for this comp unit.  */
8223       if (reader.comp_unit_die->has_children)
8224         load_partial_dies (&reader, reader.info_ptr, 0);
8225     }
8226 }
8227
8228 static void
8229 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8230                               struct dwarf2_section_info *section,
8231                               struct dwarf2_section_info *abbrev_section,
8232                               unsigned int is_dwz)
8233 {
8234   const gdb_byte *info_ptr;
8235   struct objfile *objfile = dwarf2_per_objfile->objfile;
8236
8237   if (dwarf_read_debug)
8238     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8239                         section->get_name (),
8240                         section->get_file_name ());
8241
8242   section->read (objfile);
8243
8244   info_ptr = section->buffer;
8245
8246   while (info_ptr < section->buffer + section->size)
8247     {
8248       struct dwarf2_per_cu_data *this_cu;
8249
8250       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8251
8252       comp_unit_head cu_header;
8253       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8254                                      abbrev_section, info_ptr,
8255                                      rcuh_kind::COMPILE);
8256
8257       /* Save the compilation unit for later lookup.  */
8258       if (cu_header.unit_type != DW_UT_type)
8259         {
8260           this_cu = XOBNEW (&objfile->objfile_obstack,
8261                             struct dwarf2_per_cu_data);
8262           memset (this_cu, 0, sizeof (*this_cu));
8263         }
8264       else
8265         {
8266           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8267                                   struct signatured_type);
8268           memset (sig_type, 0, sizeof (*sig_type));
8269           sig_type->signature = cu_header.signature;
8270           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8271           this_cu = &sig_type->per_cu;
8272         }
8273       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8274       this_cu->sect_off = sect_off;
8275       this_cu->length = cu_header.length + cu_header.initial_length_size;
8276       this_cu->is_dwz = is_dwz;
8277       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8278       this_cu->section = section;
8279
8280       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8281
8282       info_ptr = info_ptr + this_cu->length;
8283     }
8284 }
8285
8286 /* Create a list of all compilation units in OBJFILE.
8287    This is only done for -readnow and building partial symtabs.  */
8288
8289 static void
8290 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8291 {
8292   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8293   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8294                                 &dwarf2_per_objfile->abbrev, 0);
8295
8296   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8297   if (dwz != NULL)
8298     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8299                                   1);
8300 }
8301
8302 /* Process all loaded DIEs for compilation unit CU, starting at
8303    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8304    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8305    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8306    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8307
8308 static void
8309 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8310                       CORE_ADDR *highpc, int set_addrmap,
8311                       struct dwarf2_cu *cu)
8312 {
8313   struct partial_die_info *pdi;
8314
8315   /* Now, march along the PDI's, descending into ones which have
8316      interesting children but skipping the children of the other ones,
8317      until we reach the end of the compilation unit.  */
8318
8319   pdi = first_die;
8320
8321   while (pdi != NULL)
8322     {
8323       pdi->fixup (cu);
8324
8325       /* Anonymous namespaces or modules have no name but have interesting
8326          children, so we need to look at them.  Ditto for anonymous
8327          enums.  */
8328
8329       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8330           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8331           || pdi->tag == DW_TAG_imported_unit
8332           || pdi->tag == DW_TAG_inlined_subroutine)
8333         {
8334           switch (pdi->tag)
8335             {
8336             case DW_TAG_subprogram:
8337             case DW_TAG_inlined_subroutine:
8338               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8339               break;
8340             case DW_TAG_constant:
8341             case DW_TAG_variable:
8342             case DW_TAG_typedef:
8343             case DW_TAG_union_type:
8344               if (!pdi->is_declaration)
8345                 {
8346                   add_partial_symbol (pdi, cu);
8347                 }
8348               break;
8349             case DW_TAG_class_type:
8350             case DW_TAG_interface_type:
8351             case DW_TAG_structure_type:
8352               if (!pdi->is_declaration)
8353                 {
8354                   add_partial_symbol (pdi, cu);
8355                 }
8356               if ((cu->language == language_rust
8357                    || cu->language == language_cplus) && pdi->has_children)
8358                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8359                                       set_addrmap, cu);
8360               break;
8361             case DW_TAG_enumeration_type:
8362               if (!pdi->is_declaration)
8363                 add_partial_enumeration (pdi, cu);
8364               break;
8365             case DW_TAG_base_type:
8366             case DW_TAG_subrange_type:
8367               /* File scope base type definitions are added to the partial
8368                  symbol table.  */
8369               add_partial_symbol (pdi, cu);
8370               break;
8371             case DW_TAG_namespace:
8372               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8373               break;
8374             case DW_TAG_module:
8375               if (!pdi->is_declaration)
8376                 add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8377               break;
8378             case DW_TAG_imported_unit:
8379               {
8380                 struct dwarf2_per_cu_data *per_cu;
8381
8382                 /* For now we don't handle imported units in type units.  */
8383                 if (cu->per_cu->is_debug_types)
8384                   {
8385                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8386                              " supported in type units [in module %s]"),
8387                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8388                   }
8389
8390                 per_cu = dwarf2_find_containing_comp_unit
8391                            (pdi->d.sect_off, pdi->is_dwz,
8392                             cu->per_cu->dwarf2_per_objfile);
8393
8394                 /* Go read the partial unit, if needed.  */
8395                 if (per_cu->v.psymtab == NULL)
8396                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8397
8398                 cu->per_cu->imported_symtabs_push (per_cu);
8399               }
8400               break;
8401             case DW_TAG_imported_declaration:
8402               add_partial_symbol (pdi, cu);
8403               break;
8404             default:
8405               break;
8406             }
8407         }
8408
8409       /* If the die has a sibling, skip to the sibling.  */
8410
8411       pdi = pdi->die_sibling;
8412     }
8413 }
8414
8415 /* Functions used to compute the fully scoped name of a partial DIE.
8416
8417    Normally, this is simple.  For C++, the parent DIE's fully scoped
8418    name is concatenated with "::" and the partial DIE's name.
8419    Enumerators are an exception; they use the scope of their parent
8420    enumeration type, i.e. the name of the enumeration type is not
8421    prepended to the enumerator.
8422
8423    There are two complexities.  One is DW_AT_specification; in this
8424    case "parent" means the parent of the target of the specification,
8425    instead of the direct parent of the DIE.  The other is compilers
8426    which do not emit DW_TAG_namespace; in this case we try to guess
8427    the fully qualified name of structure types from their members'
8428    linkage names.  This must be done using the DIE's children rather
8429    than the children of any DW_AT_specification target.  We only need
8430    to do this for structures at the top level, i.e. if the target of
8431    any DW_AT_specification (if any; otherwise the DIE itself) does not
8432    have a parent.  */
8433
8434 /* Compute the scope prefix associated with PDI's parent, in
8435    compilation unit CU.  The result will be allocated on CU's
8436    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8437    field.  NULL is returned if no prefix is necessary.  */
8438 static const char *
8439 partial_die_parent_scope (struct partial_die_info *pdi,
8440                           struct dwarf2_cu *cu)
8441 {
8442   const char *grandparent_scope;
8443   struct partial_die_info *parent, *real_pdi;
8444
8445   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8446      then this means the parent of the specification DIE.  */
8447
8448   real_pdi = pdi;
8449   while (real_pdi->has_specification)
8450     {
8451       auto res = find_partial_die (real_pdi->spec_offset,
8452                                    real_pdi->spec_is_dwz, cu);
8453       real_pdi = res.pdi;
8454       cu = res.cu;
8455     }
8456
8457   parent = real_pdi->die_parent;
8458   if (parent == NULL)
8459     return NULL;
8460
8461   if (parent->scope_set)
8462     return parent->scope;
8463
8464   parent->fixup (cu);
8465
8466   grandparent_scope = partial_die_parent_scope (parent, cu);
8467
8468   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8469      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8470      Work around this problem here.  */
8471   if (cu->language == language_cplus
8472       && parent->tag == DW_TAG_namespace
8473       && strcmp (parent->name, "::") == 0
8474       && grandparent_scope == NULL)
8475     {
8476       parent->scope = NULL;
8477       parent->scope_set = 1;
8478       return NULL;
8479     }
8480
8481   /* Nested subroutines in Fortran get a prefix.  */
8482   if (pdi->tag == DW_TAG_enumerator)
8483     /* Enumerators should not get the name of the enumeration as a prefix.  */
8484     parent->scope = grandparent_scope;
8485   else if (parent->tag == DW_TAG_namespace
8486       || parent->tag == DW_TAG_module
8487       || parent->tag == DW_TAG_structure_type
8488       || parent->tag == DW_TAG_class_type
8489       || parent->tag == DW_TAG_interface_type
8490       || parent->tag == DW_TAG_union_type
8491       || parent->tag == DW_TAG_enumeration_type
8492       || (cu->language == language_fortran
8493           && parent->tag == DW_TAG_subprogram
8494           && pdi->tag == DW_TAG_subprogram))
8495     {
8496       if (grandparent_scope == NULL)
8497         parent->scope = parent->name;
8498       else
8499         parent->scope = typename_concat (&cu->comp_unit_obstack,
8500                                          grandparent_scope,
8501                                          parent->name, 0, cu);
8502     }
8503   else
8504     {
8505       /* FIXME drow/2004-04-01: What should we be doing with
8506          function-local names?  For partial symbols, we should probably be
8507          ignoring them.  */
8508       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
8509                  dwarf_tag_name (parent->tag),
8510                  sect_offset_str (pdi->sect_off));
8511       parent->scope = grandparent_scope;
8512     }
8513
8514   parent->scope_set = 1;
8515   return parent->scope;
8516 }
8517
8518 /* Return the fully scoped name associated with PDI, from compilation unit
8519    CU.  The result will be allocated with malloc.  */
8520
8521 static gdb::unique_xmalloc_ptr<char>
8522 partial_die_full_name (struct partial_die_info *pdi,
8523                        struct dwarf2_cu *cu)
8524 {
8525   const char *parent_scope;
8526
8527   /* If this is a template instantiation, we can not work out the
8528      template arguments from partial DIEs.  So, unfortunately, we have
8529      to go through the full DIEs.  At least any work we do building
8530      types here will be reused if full symbols are loaded later.  */
8531   if (pdi->has_template_arguments)
8532     {
8533       pdi->fixup (cu);
8534
8535       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8536         {
8537           struct die_info *die;
8538           struct attribute attr;
8539           struct dwarf2_cu *ref_cu = cu;
8540
8541           /* DW_FORM_ref_addr is using section offset.  */
8542           attr.name = (enum dwarf_attribute) 0;
8543           attr.form = DW_FORM_ref_addr;
8544           attr.u.unsnd = to_underlying (pdi->sect_off);
8545           die = follow_die_ref (NULL, &attr, &ref_cu);
8546
8547           return make_unique_xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8548         }
8549     }
8550
8551   parent_scope = partial_die_parent_scope (pdi, cu);
8552   if (parent_scope == NULL)
8553     return NULL;
8554   else
8555     return gdb::unique_xmalloc_ptr<char> (typename_concat (NULL, parent_scope,
8556                                                            pdi->name, 0, cu));
8557 }
8558
8559 static void
8560 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8561 {
8562   struct dwarf2_per_objfile *dwarf2_per_objfile
8563     = cu->per_cu->dwarf2_per_objfile;
8564   struct objfile *objfile = dwarf2_per_objfile->objfile;
8565   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8566   CORE_ADDR addr = 0;
8567   const char *actual_name = NULL;
8568   CORE_ADDR baseaddr;
8569
8570   baseaddr = objfile->text_section_offset ();
8571
8572   gdb::unique_xmalloc_ptr<char> built_actual_name
8573     = partial_die_full_name (pdi, cu);
8574   if (built_actual_name != NULL)
8575     actual_name = built_actual_name.get ();
8576
8577   if (actual_name == NULL)
8578     actual_name = pdi->name;
8579
8580   switch (pdi->tag)
8581     {
8582     case DW_TAG_inlined_subroutine:
8583     case DW_TAG_subprogram:
8584       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8585               - baseaddr);
8586       if (pdi->is_external
8587           || cu->language == language_ada
8588           || (cu->language == language_fortran
8589               && pdi->die_parent != NULL
8590               && pdi->die_parent->tag == DW_TAG_subprogram))
8591         {
8592           /* Normally, only "external" DIEs are part of the global scope.
8593              But in Ada and Fortran, we want to be able to access nested
8594              procedures globally.  So all Ada and Fortran subprograms are
8595              stored in the global scope.  */
8596           add_psymbol_to_list (actual_name,
8597                                built_actual_name != NULL,
8598                                VAR_DOMAIN, LOC_BLOCK,
8599                                SECT_OFF_TEXT (objfile),
8600                                psymbol_placement::GLOBAL,
8601                                addr,
8602                                cu->language, objfile);
8603         }
8604       else
8605         {
8606           add_psymbol_to_list (actual_name,
8607                                built_actual_name != NULL,
8608                                VAR_DOMAIN, LOC_BLOCK,
8609                                SECT_OFF_TEXT (objfile),
8610                                psymbol_placement::STATIC,
8611                                addr, cu->language, objfile);
8612         }
8613
8614       if (pdi->main_subprogram && actual_name != NULL)
8615         set_objfile_main_name (objfile, actual_name, cu->language);
8616       break;
8617     case DW_TAG_constant:
8618       add_psymbol_to_list (actual_name,
8619                            built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8620                            -1, (pdi->is_external
8621                                 ? psymbol_placement::GLOBAL
8622                                 : psymbol_placement::STATIC),
8623                            0, cu->language, objfile);
8624       break;
8625     case DW_TAG_variable:
8626       if (pdi->d.locdesc)
8627         addr = decode_locdesc (pdi->d.locdesc, cu);
8628
8629       if (pdi->d.locdesc
8630           && addr == 0
8631           && !dwarf2_per_objfile->has_section_at_zero)
8632         {
8633           /* A global or static variable may also have been stripped
8634              out by the linker if unused, in which case its address
8635              will be nullified; do not add such variables into partial
8636              symbol table then.  */
8637         }
8638       else if (pdi->is_external)
8639         {
8640           /* Global Variable.
8641              Don't enter into the minimal symbol tables as there is
8642              a minimal symbol table entry from the ELF symbols already.
8643              Enter into partial symbol table if it has a location
8644              descriptor or a type.
8645              If the location descriptor is missing, new_symbol will create
8646              a LOC_UNRESOLVED symbol, the address of the variable will then
8647              be determined from the minimal symbol table whenever the variable
8648              is referenced.
8649              The address for the partial symbol table entry is not
8650              used by GDB, but it comes in handy for debugging partial symbol
8651              table building.  */
8652
8653           if (pdi->d.locdesc || pdi->has_type)
8654             add_psymbol_to_list (actual_name,
8655                                  built_actual_name != NULL,
8656                                  VAR_DOMAIN, LOC_STATIC,
8657                                  SECT_OFF_TEXT (objfile),
8658                                  psymbol_placement::GLOBAL,
8659                                  addr, cu->language, objfile);
8660         }
8661       else
8662         {
8663           int has_loc = pdi->d.locdesc != NULL;
8664
8665           /* Static Variable.  Skip symbols whose value we cannot know (those
8666              without location descriptors or constant values).  */
8667           if (!has_loc && !pdi->has_const_value)
8668             return;
8669
8670           add_psymbol_to_list (actual_name,
8671                                built_actual_name != NULL,
8672                                VAR_DOMAIN, LOC_STATIC,
8673                                SECT_OFF_TEXT (objfile),
8674                                psymbol_placement::STATIC,
8675                                has_loc ? addr : 0,
8676                                cu->language, objfile);
8677         }
8678       break;
8679     case DW_TAG_typedef:
8680     case DW_TAG_base_type:
8681     case DW_TAG_subrange_type:
8682       add_psymbol_to_list (actual_name,
8683                            built_actual_name != NULL,
8684                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8685                            psymbol_placement::STATIC,
8686                            0, cu->language, objfile);
8687       break;
8688     case DW_TAG_imported_declaration:
8689     case DW_TAG_namespace:
8690       add_psymbol_to_list (actual_name,
8691                            built_actual_name != NULL,
8692                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8693                            psymbol_placement::GLOBAL,
8694                            0, cu->language, objfile);
8695       break;
8696     case DW_TAG_module:
8697       /* With Fortran 77 there might be a "BLOCK DATA" module
8698          available without any name.  If so, we skip the module as it
8699          doesn't bring any value.  */
8700       if (actual_name != nullptr)
8701         add_psymbol_to_list (actual_name,
8702                              built_actual_name != NULL,
8703                              MODULE_DOMAIN, LOC_TYPEDEF, -1,
8704                              psymbol_placement::GLOBAL,
8705                              0, cu->language, objfile);
8706       break;
8707     case DW_TAG_class_type:
8708     case DW_TAG_interface_type:
8709     case DW_TAG_structure_type:
8710     case DW_TAG_union_type:
8711     case DW_TAG_enumeration_type:
8712       /* Skip external references.  The DWARF standard says in the section
8713          about "Structure, Union, and Class Type Entries": "An incomplete
8714          structure, union or class type is represented by a structure,
8715          union or class entry that does not have a byte size attribute
8716          and that has a DW_AT_declaration attribute."  */
8717       if (!pdi->has_byte_size && pdi->is_declaration)
8718         return;
8719
8720       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8721          static vs. global.  */
8722       add_psymbol_to_list (actual_name,
8723                            built_actual_name != NULL,
8724                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
8725                            cu->language == language_cplus
8726                            ? psymbol_placement::GLOBAL
8727                            : psymbol_placement::STATIC,
8728                            0, cu->language, objfile);
8729
8730       break;
8731     case DW_TAG_enumerator:
8732       add_psymbol_to_list (actual_name,
8733                            built_actual_name != NULL,
8734                            VAR_DOMAIN, LOC_CONST, -1,
8735                            cu->language == language_cplus
8736                            ? psymbol_placement::GLOBAL
8737                            : psymbol_placement::STATIC,
8738                            0, cu->language, objfile);
8739       break;
8740     default:
8741       break;
8742     }
8743 }
8744
8745 /* Read a partial die corresponding to a namespace; also, add a symbol
8746    corresponding to that namespace to the symbol table.  NAMESPACE is
8747    the name of the enclosing namespace.  */
8748
8749 static void
8750 add_partial_namespace (struct partial_die_info *pdi,
8751                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8752                        int set_addrmap, struct dwarf2_cu *cu)
8753 {
8754   /* Add a symbol for the namespace.  */
8755
8756   add_partial_symbol (pdi, cu);
8757
8758   /* Now scan partial symbols in that namespace.  */
8759
8760   if (pdi->has_children)
8761     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8762 }
8763
8764 /* Read a partial die corresponding to a Fortran module.  */
8765
8766 static void
8767 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8768                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8769 {
8770   /* Add a symbol for the namespace.  */
8771
8772   add_partial_symbol (pdi, cu);
8773
8774   /* Now scan partial symbols in that module.  */
8775
8776   if (pdi->has_children)
8777     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8778 }
8779
8780 /* Read a partial die corresponding to a subprogram or an inlined
8781    subprogram and create a partial symbol for that subprogram.
8782    When the CU language allows it, this routine also defines a partial
8783    symbol for each nested subprogram that this subprogram contains.
8784    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
8785    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
8786
8787    PDI may also be a lexical block, in which case we simply search
8788    recursively for subprograms defined inside that lexical block.
8789    Again, this is only performed when the CU language allows this
8790    type of definitions.  */
8791
8792 static void
8793 add_partial_subprogram (struct partial_die_info *pdi,
8794                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
8795                         int set_addrmap, struct dwarf2_cu *cu)
8796 {
8797   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
8798     {
8799       if (pdi->has_pc_info)
8800         {
8801           if (pdi->lowpc < *lowpc)
8802             *lowpc = pdi->lowpc;
8803           if (pdi->highpc > *highpc)
8804             *highpc = pdi->highpc;
8805           if (set_addrmap)
8806             {
8807               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8808               struct gdbarch *gdbarch = get_objfile_arch (objfile);
8809               CORE_ADDR baseaddr;
8810               CORE_ADDR this_highpc;
8811               CORE_ADDR this_lowpc;
8812
8813               baseaddr = objfile->text_section_offset ();
8814               this_lowpc
8815                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8816                                                pdi->lowpc + baseaddr)
8817                    - baseaddr);
8818               this_highpc
8819                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8820                                                pdi->highpc + baseaddr)
8821                    - baseaddr);
8822               addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
8823                                  this_lowpc, this_highpc - 1,
8824                                  cu->per_cu->v.psymtab);
8825             }
8826         }
8827
8828       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8829         {
8830           if (!pdi->is_declaration)
8831             /* Ignore subprogram DIEs that do not have a name, they are
8832                illegal.  Do not emit a complaint at this point, we will
8833                do so when we convert this psymtab into a symtab.  */
8834             if (pdi->name)
8835               add_partial_symbol (pdi, cu);
8836         }
8837     }
8838
8839   if (! pdi->has_children)
8840     return;
8841
8842   if (cu->language == language_ada || cu->language == language_fortran)
8843     {
8844       pdi = pdi->die_child;
8845       while (pdi != NULL)
8846         {
8847           pdi->fixup (cu);
8848           if (pdi->tag == DW_TAG_subprogram
8849               || pdi->tag == DW_TAG_inlined_subroutine
8850               || pdi->tag == DW_TAG_lexical_block)
8851             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8852           pdi = pdi->die_sibling;
8853         }
8854     }
8855 }
8856
8857 /* Read a partial die corresponding to an enumeration type.  */
8858
8859 static void
8860 add_partial_enumeration (struct partial_die_info *enum_pdi,
8861                          struct dwarf2_cu *cu)
8862 {
8863   struct partial_die_info *pdi;
8864
8865   if (enum_pdi->name != NULL)
8866     add_partial_symbol (enum_pdi, cu);
8867
8868   pdi = enum_pdi->die_child;
8869   while (pdi)
8870     {
8871       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
8872         complaint (_("malformed enumerator DIE ignored"));
8873       else
8874         add_partial_symbol (pdi, cu);
8875       pdi = pdi->die_sibling;
8876     }
8877 }
8878
8879 /* Return the initial uleb128 in the die at INFO_PTR.  */
8880
8881 static unsigned int
8882 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8883 {
8884   unsigned int bytes_read;
8885
8886   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8887 }
8888
8889 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
8890    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
8891
8892    Return the corresponding abbrev, or NULL if the number is zero (indicating
8893    an empty DIE).  In either case *BYTES_READ will be set to the length of
8894    the initial number.  */
8895
8896 static struct abbrev_info *
8897 peek_die_abbrev (const die_reader_specs &reader,
8898                  const gdb_byte *info_ptr, unsigned int *bytes_read)
8899 {
8900   dwarf2_cu *cu = reader.cu;
8901   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
8902   unsigned int abbrev_number
8903     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8904
8905   if (abbrev_number == 0)
8906     return NULL;
8907
8908   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
8909   if (!abbrev)
8910     {
8911       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8912                " at offset %s [in module %s]"),
8913              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8914              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
8915     }
8916
8917   return abbrev;
8918 }
8919
8920 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8921    Returns a pointer to the end of a series of DIEs, terminated by an empty
8922    DIE.  Any children of the skipped DIEs will also be skipped.  */
8923
8924 static const gdb_byte *
8925 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8926 {
8927   while (1)
8928     {
8929       unsigned int bytes_read;
8930       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
8931
8932       if (abbrev == NULL)
8933         return info_ptr + bytes_read;
8934       else
8935         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8936     }
8937 }
8938
8939 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8940    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8941    abbrev corresponding to that skipped uleb128 should be passed in
8942    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8943    children.  */
8944
8945 static const gdb_byte *
8946 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8947               struct abbrev_info *abbrev)
8948 {
8949   unsigned int bytes_read;
8950   struct attribute attr;
8951   bfd *abfd = reader->abfd;
8952   struct dwarf2_cu *cu = reader->cu;
8953   const gdb_byte *buffer = reader->buffer;
8954   const gdb_byte *buffer_end = reader->buffer_end;
8955   unsigned int form, i;
8956
8957   for (i = 0; i < abbrev->num_attrs; i++)
8958     {
8959       /* The only abbrev we care about is DW_AT_sibling.  */
8960       if (abbrev->attrs[i].name == DW_AT_sibling)
8961         {
8962           bool ignored;
8963           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr,
8964                           &ignored);
8965           if (attr.form == DW_FORM_ref_addr)
8966             complaint (_("ignoring absolute DW_AT_sibling"));
8967           else
8968             {
8969               sect_offset off = dwarf2_get_ref_die_offset (&attr);
8970               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8971
8972               if (sibling_ptr < info_ptr)
8973                 complaint (_("DW_AT_sibling points backwards"));
8974               else if (sibling_ptr > reader->buffer_end)
8975                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
8976               else
8977                 return sibling_ptr;
8978             }
8979         }
8980
8981       /* If it isn't DW_AT_sibling, skip this attribute.  */
8982       form = abbrev->attrs[i].form;
8983     skip_attribute:
8984       switch (form)
8985         {
8986         case DW_FORM_ref_addr:
8987           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8988              and later it is offset sized.  */
8989           if (cu->header.version == 2)
8990             info_ptr += cu->header.addr_size;
8991           else
8992             info_ptr += cu->header.offset_size;
8993           break;
8994         case DW_FORM_GNU_ref_alt:
8995           info_ptr += cu->header.offset_size;
8996           break;
8997         case DW_FORM_addr:
8998           info_ptr += cu->header.addr_size;
8999           break;
9000         case DW_FORM_data1:
9001         case DW_FORM_ref1:
9002         case DW_FORM_flag:
9003         case DW_FORM_strx1:
9004           info_ptr += 1;
9005           break;
9006         case DW_FORM_flag_present:
9007         case DW_FORM_implicit_const:
9008           break;
9009         case DW_FORM_data2:
9010         case DW_FORM_ref2:
9011         case DW_FORM_strx2:
9012           info_ptr += 2;
9013           break;
9014         case DW_FORM_strx3:
9015           info_ptr += 3;
9016           break;
9017         case DW_FORM_data4:
9018         case DW_FORM_ref4:
9019         case DW_FORM_strx4:
9020           info_ptr += 4;
9021           break;
9022         case DW_FORM_data8:
9023         case DW_FORM_ref8:
9024         case DW_FORM_ref_sig8:
9025           info_ptr += 8;
9026           break;
9027         case DW_FORM_data16:
9028           info_ptr += 16;
9029           break;
9030         case DW_FORM_string:
9031           read_direct_string (abfd, info_ptr, &bytes_read);
9032           info_ptr += bytes_read;
9033           break;
9034         case DW_FORM_sec_offset:
9035         case DW_FORM_strp:
9036         case DW_FORM_GNU_strp_alt:
9037           info_ptr += cu->header.offset_size;
9038           break;
9039         case DW_FORM_exprloc:
9040         case DW_FORM_block:
9041           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9042           info_ptr += bytes_read;
9043           break;
9044         case DW_FORM_block1:
9045           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9046           break;
9047         case DW_FORM_block2:
9048           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9049           break;
9050         case DW_FORM_block4:
9051           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9052           break;
9053         case DW_FORM_addrx:
9054         case DW_FORM_strx:
9055         case DW_FORM_sdata:
9056         case DW_FORM_udata:
9057         case DW_FORM_ref_udata:
9058         case DW_FORM_GNU_addr_index:
9059         case DW_FORM_GNU_str_index:
9060         case DW_FORM_rnglistx:
9061           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9062           break;
9063         case DW_FORM_indirect:
9064           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9065           info_ptr += bytes_read;
9066           /* We need to continue parsing from here, so just go back to
9067              the top.  */
9068           goto skip_attribute;
9069
9070         default:
9071           error (_("Dwarf Error: Cannot handle %s "
9072                    "in DWARF reader [in module %s]"),
9073                  dwarf_form_name (form),
9074                  bfd_get_filename (abfd));
9075         }
9076     }
9077
9078   if (abbrev->has_children)
9079     return skip_children (reader, info_ptr);
9080   else
9081     return info_ptr;
9082 }
9083
9084 /* Locate ORIG_PDI's sibling.
9085    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9086
9087 static const gdb_byte *
9088 locate_pdi_sibling (const struct die_reader_specs *reader,
9089                     struct partial_die_info *orig_pdi,
9090                     const gdb_byte *info_ptr)
9091 {
9092   /* Do we know the sibling already?  */
9093
9094   if (orig_pdi->sibling)
9095     return orig_pdi->sibling;
9096
9097   /* Are there any children to deal with?  */
9098
9099   if (!orig_pdi->has_children)
9100     return info_ptr;
9101
9102   /* Skip the children the long way.  */
9103
9104   return skip_children (reader, info_ptr);
9105 }
9106
9107 /* Expand this partial symbol table into a full symbol table.  SELF is
9108    not NULL.  */
9109
9110 void
9111 dwarf2_psymtab::read_symtab (struct objfile *objfile)
9112 {
9113   struct dwarf2_per_objfile *dwarf2_per_objfile
9114     = get_dwarf2_per_objfile (objfile);
9115
9116   gdb_assert (!readin);
9117   /* If this psymtab is constructed from a debug-only objfile, the
9118      has_section_at_zero flag will not necessarily be correct.  We
9119      can get the correct value for this flag by looking at the data
9120      associated with the (presumably stripped) associated objfile.  */
9121   if (objfile->separate_debug_objfile_backlink)
9122     {
9123       struct dwarf2_per_objfile *dpo_backlink
9124         = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9125
9126       dwarf2_per_objfile->has_section_at_zero
9127         = dpo_backlink->has_section_at_zero;
9128     }
9129
9130   dwarf2_per_objfile->reading_partial_symbols = 0;
9131
9132   expand_psymtab (objfile);
9133
9134   process_cu_includes (dwarf2_per_objfile);
9135 }
9136 \f
9137 /* Reading in full CUs.  */
9138
9139 /* Add PER_CU to the queue.  */
9140
9141 static void
9142 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9143                  enum language pretend_language)
9144 {
9145   per_cu->queued = 1;
9146   per_cu->dwarf2_per_objfile->queue.emplace (per_cu, pretend_language);
9147 }
9148
9149 /* If PER_CU is not yet queued, add it to the queue.
9150    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9151    dependency.
9152    The result is non-zero if PER_CU was queued, otherwise the result is zero
9153    meaning either PER_CU is already queued or it is already loaded.
9154
9155    N.B. There is an invariant here that if a CU is queued then it is loaded.
9156    The caller is required to load PER_CU if we return non-zero.  */
9157
9158 static int
9159 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9160                        struct dwarf2_per_cu_data *per_cu,
9161                        enum language pretend_language)
9162 {
9163   /* We may arrive here during partial symbol reading, if we need full
9164      DIEs to process an unusual case (e.g. template arguments).  Do
9165      not queue PER_CU, just tell our caller to load its DIEs.  */
9166   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9167     {
9168       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9169         return 1;
9170       return 0;
9171     }
9172
9173   /* Mark the dependence relation so that we don't flush PER_CU
9174      too early.  */
9175   if (dependent_cu != NULL)
9176     dwarf2_add_dependence (dependent_cu, per_cu);
9177
9178   /* If it's already on the queue, we have nothing to do.  */
9179   if (per_cu->queued)
9180     return 0;
9181
9182   /* If the compilation unit is already loaded, just mark it as
9183      used.  */
9184   if (per_cu->cu != NULL)
9185     {
9186       per_cu->cu->last_used = 0;
9187       return 0;
9188     }
9189
9190   /* Add it to the queue.  */
9191   queue_comp_unit (per_cu, pretend_language);
9192
9193   return 1;
9194 }
9195
9196 /* Process the queue.  */
9197
9198 static void
9199 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9200 {
9201   if (dwarf_read_debug)
9202     {
9203       fprintf_unfiltered (gdb_stdlog,
9204                           "Expanding one or more symtabs of objfile %s ...\n",
9205                           objfile_name (dwarf2_per_objfile->objfile));
9206     }
9207
9208   /* The queue starts out with one item, but following a DIE reference
9209      may load a new CU, adding it to the end of the queue.  */
9210   while (!dwarf2_per_objfile->queue.empty ())
9211     {
9212       dwarf2_queue_item &item = dwarf2_per_objfile->queue.front ();
9213
9214       if ((dwarf2_per_objfile->using_index
9215            ? !item.per_cu->v.quick->compunit_symtab
9216            : (item.per_cu->v.psymtab && !item.per_cu->v.psymtab->readin))
9217           /* Skip dummy CUs.  */
9218           && item.per_cu->cu != NULL)
9219         {
9220           struct dwarf2_per_cu_data *per_cu = item.per_cu;
9221           unsigned int debug_print_threshold;
9222           char buf[100];
9223
9224           if (per_cu->is_debug_types)
9225             {
9226               struct signatured_type *sig_type =
9227                 (struct signatured_type *) per_cu;
9228
9229               sprintf (buf, "TU %s at offset %s",
9230                        hex_string (sig_type->signature),
9231                        sect_offset_str (per_cu->sect_off));
9232               /* There can be 100s of TUs.
9233                  Only print them in verbose mode.  */
9234               debug_print_threshold = 2;
9235             }
9236           else
9237             {
9238               sprintf (buf, "CU at offset %s",
9239                        sect_offset_str (per_cu->sect_off));
9240               debug_print_threshold = 1;
9241             }
9242
9243           if (dwarf_read_debug >= debug_print_threshold)
9244             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9245
9246           if (per_cu->is_debug_types)
9247             process_full_type_unit (per_cu, item.pretend_language);
9248           else
9249             process_full_comp_unit (per_cu, item.pretend_language);
9250
9251           if (dwarf_read_debug >= debug_print_threshold)
9252             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9253         }
9254
9255       item.per_cu->queued = 0;
9256       dwarf2_per_objfile->queue.pop ();
9257     }
9258
9259   if (dwarf_read_debug)
9260     {
9261       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9262                           objfile_name (dwarf2_per_objfile->objfile));
9263     }
9264 }
9265
9266 /* Read in full symbols for PST, and anything it depends on.  */
9267
9268 void
9269 dwarf2_psymtab::expand_psymtab (struct objfile *objfile)
9270 {
9271   struct dwarf2_per_cu_data *per_cu;
9272
9273   if (readin)
9274     return;
9275
9276   read_dependencies (objfile);
9277
9278   per_cu = per_cu_data;
9279
9280   if (per_cu == NULL)
9281     {
9282       /* It's an include file, no symbols to read for it.
9283          Everything is in the parent symtab.  */
9284       readin = true;
9285       return;
9286     }
9287
9288   dw2_do_instantiate_symtab (per_cu, false);
9289 }
9290
9291 /* Trivial hash function for die_info: the hash value of a DIE
9292    is its offset in .debug_info for this objfile.  */
9293
9294 static hashval_t
9295 die_hash (const void *item)
9296 {
9297   const struct die_info *die = (const struct die_info *) item;
9298
9299   return to_underlying (die->sect_off);
9300 }
9301
9302 /* Trivial comparison function for die_info structures: two DIEs
9303    are equal if they have the same offset.  */
9304
9305 static int
9306 die_eq (const void *item_lhs, const void *item_rhs)
9307 {
9308   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9309   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9310
9311   return die_lhs->sect_off == die_rhs->sect_off;
9312 }
9313
9314 /* Load the DIEs associated with PER_CU into memory.  */
9315
9316 static void
9317 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9318                      bool skip_partial,
9319                      enum language pretend_language)
9320 {
9321   gdb_assert (! this_cu->is_debug_types);
9322
9323   cutu_reader reader (this_cu, NULL, 1, 1, skip_partial);
9324   if (reader.dummy_p)
9325     return;
9326
9327   struct dwarf2_cu *cu = reader.cu;
9328   const gdb_byte *info_ptr = reader.info_ptr;
9329
9330   gdb_assert (cu->die_hash == NULL);
9331   cu->die_hash =
9332     htab_create_alloc_ex (cu->header.length / 12,
9333                           die_hash,
9334                           die_eq,
9335                           NULL,
9336                           &cu->comp_unit_obstack,
9337                           hashtab_obstack_allocate,
9338                           dummy_obstack_deallocate);
9339
9340   if (reader.comp_unit_die->has_children)
9341     reader.comp_unit_die->child
9342       = read_die_and_siblings (&reader, reader.info_ptr,
9343                                &info_ptr, reader.comp_unit_die);
9344   cu->dies = reader.comp_unit_die;
9345   /* comp_unit_die is not stored in die_hash, no need.  */
9346
9347   /* We try not to read any attributes in this function, because not
9348      all CUs needed for references have been loaded yet, and symbol
9349      table processing isn't initialized.  But we have to set the CU language,
9350      or we won't be able to build types correctly.
9351      Similarly, if we do not read the producer, we can not apply
9352      producer-specific interpretation.  */
9353   prepare_one_comp_unit (cu, cu->dies, pretend_language);
9354 }
9355
9356 /* Add a DIE to the delayed physname list.  */
9357
9358 static void
9359 add_to_method_list (struct type *type, int fnfield_index, int index,
9360                     const char *name, struct die_info *die,
9361                     struct dwarf2_cu *cu)
9362 {
9363   struct delayed_method_info mi;
9364   mi.type = type;
9365   mi.fnfield_index = fnfield_index;
9366   mi.index = index;
9367   mi.name = name;
9368   mi.die = die;
9369   cu->method_list.push_back (mi);
9370 }
9371
9372 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9373    "const" / "volatile".  If so, decrements LEN by the length of the
9374    modifier and return true.  Otherwise return false.  */
9375
9376 template<size_t N>
9377 static bool
9378 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9379 {
9380   size_t mod_len = sizeof (mod) - 1;
9381   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9382     {
9383       len -= mod_len;
9384       return true;
9385     }
9386   return false;
9387 }
9388
9389 /* Compute the physnames of any methods on the CU's method list.
9390
9391    The computation of method physnames is delayed in order to avoid the
9392    (bad) condition that one of the method's formal parameters is of an as yet
9393    incomplete type.  */
9394
9395 static void
9396 compute_delayed_physnames (struct dwarf2_cu *cu)
9397 {
9398   /* Only C++ delays computing physnames.  */
9399   if (cu->method_list.empty ())
9400     return;
9401   gdb_assert (cu->language == language_cplus);
9402
9403   for (const delayed_method_info &mi : cu->method_list)
9404     {
9405       const char *physname;
9406       struct fn_fieldlist *fn_flp
9407         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9408       physname = dwarf2_physname (mi.name, mi.die, cu);
9409       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9410         = physname ? physname : "";
9411
9412       /* Since there's no tag to indicate whether a method is a
9413          const/volatile overload, extract that information out of the
9414          demangled name.  */
9415       if (physname != NULL)
9416         {
9417           size_t len = strlen (physname);
9418
9419           while (1)
9420             {
9421               if (physname[len] == ')') /* shortcut */
9422                 break;
9423               else if (check_modifier (physname, len, " const"))
9424                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9425               else if (check_modifier (physname, len, " volatile"))
9426                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9427               else
9428                 break;
9429             }
9430         }
9431     }
9432
9433   /* The list is no longer needed.  */
9434   cu->method_list.clear ();
9435 }
9436
9437 /* Go objects should be embedded in a DW_TAG_module DIE,
9438    and it's not clear if/how imported objects will appear.
9439    To keep Go support simple until that's worked out,
9440    go back through what we've read and create something usable.
9441    We could do this while processing each DIE, and feels kinda cleaner,
9442    but that way is more invasive.
9443    This is to, for example, allow the user to type "p var" or "b main"
9444    without having to specify the package name, and allow lookups
9445    of module.object to work in contexts that use the expression
9446    parser.  */
9447
9448 static void
9449 fixup_go_packaging (struct dwarf2_cu *cu)
9450 {
9451   gdb::unique_xmalloc_ptr<char> package_name;
9452   struct pending *list;
9453   int i;
9454
9455   for (list = *cu->get_builder ()->get_global_symbols ();
9456        list != NULL;
9457        list = list->next)
9458     {
9459       for (i = 0; i < list->nsyms; ++i)
9460         {
9461           struct symbol *sym = list->symbol[i];
9462
9463           if (sym->language () == language_go
9464               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9465             {
9466               gdb::unique_xmalloc_ptr<char> this_package_name
9467                 (go_symbol_package_name (sym));
9468
9469               if (this_package_name == NULL)
9470                 continue;
9471               if (package_name == NULL)
9472                 package_name = std::move (this_package_name);
9473               else
9474                 {
9475                   struct objfile *objfile
9476                     = cu->per_cu->dwarf2_per_objfile->objfile;
9477                   if (strcmp (package_name.get (), this_package_name.get ()) != 0)
9478                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9479                                (symbol_symtab (sym) != NULL
9480                                 ? symtab_to_filename_for_display
9481                                     (symbol_symtab (sym))
9482                                 : objfile_name (objfile)),
9483                                this_package_name.get (), package_name.get ());
9484                 }
9485             }
9486         }
9487     }
9488
9489   if (package_name != NULL)
9490     {
9491       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9492       const char *saved_package_name
9493         = obstack_strdup (&objfile->per_bfd->storage_obstack, package_name.get ());
9494       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9495                                      saved_package_name);
9496       struct symbol *sym;
9497
9498       sym = allocate_symbol (objfile);
9499       sym->set_language (language_go, &objfile->objfile_obstack);
9500       sym->compute_and_set_names (saved_package_name, false, objfile->per_bfd);
9501       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9502          e.g., "main" finds the "main" module and not C's main().  */
9503       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9504       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9505       SYMBOL_TYPE (sym) = type;
9506
9507       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
9508     }
9509 }
9510
9511 /* Allocate a fully-qualified name consisting of the two parts on the
9512    obstack.  */
9513
9514 static const char *
9515 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9516 {
9517   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9518 }
9519
9520 /* A helper that allocates a struct discriminant_info to attach to a
9521    union type.  */
9522
9523 static struct discriminant_info *
9524 alloc_discriminant_info (struct type *type, int discriminant_index,
9525                          int default_index)
9526 {
9527   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9528   gdb_assert (discriminant_index == -1
9529               || (discriminant_index >= 0
9530                   && discriminant_index < TYPE_NFIELDS (type)));
9531   gdb_assert (default_index == -1
9532               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9533
9534   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9535
9536   struct discriminant_info *disc
9537     = ((struct discriminant_info *)
9538        TYPE_ZALLOC (type,
9539                     offsetof (struct discriminant_info, discriminants)
9540                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9541   disc->default_index = default_index;
9542   disc->discriminant_index = discriminant_index;
9543
9544   struct dynamic_prop prop;
9545   prop.kind = PROP_UNDEFINED;
9546   prop.data.baton = disc;
9547
9548   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9549
9550   return disc;
9551 }
9552
9553 /* Some versions of rustc emitted enums in an unusual way.
9554
9555    Ordinary enums were emitted as unions.  The first element of each
9556    structure in the union was named "RUST$ENUM$DISR".  This element
9557    held the discriminant.
9558
9559    These versions of Rust also implemented the "non-zero"
9560    optimization.  When the enum had two values, and one is empty and
9561    the other holds a pointer that cannot be zero, the pointer is used
9562    as the discriminant, with a zero value meaning the empty variant.
9563    Here, the union's first member is of the form
9564    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9565    where the fieldnos are the indices of the fields that should be
9566    traversed in order to find the field (which may be several fields deep)
9567    and the variantname is the name of the variant of the case when the
9568    field is zero.
9569
9570    This function recognizes whether TYPE is of one of these forms,
9571    and, if so, smashes it to be a variant type.  */
9572
9573 static void
9574 quirk_rust_enum (struct type *type, struct objfile *objfile)
9575 {
9576   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9577
9578   /* We don't need to deal with empty enums.  */
9579   if (TYPE_NFIELDS (type) == 0)
9580     return;
9581
9582 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9583   if (TYPE_NFIELDS (type) == 1
9584       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9585     {
9586       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9587
9588       /* Decode the field name to find the offset of the
9589          discriminant.  */
9590       ULONGEST bit_offset = 0;
9591       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9592       while (name[0] >= '0' && name[0] <= '9')
9593         {
9594           char *tail;
9595           unsigned long index = strtoul (name, &tail, 10);
9596           name = tail;
9597           if (*name != '$'
9598               || index >= TYPE_NFIELDS (field_type)
9599               || (TYPE_FIELD_LOC_KIND (field_type, index)
9600                   != FIELD_LOC_KIND_BITPOS))
9601             {
9602               complaint (_("Could not parse Rust enum encoding string \"%s\""
9603                            "[in module %s]"),
9604                          TYPE_FIELD_NAME (type, 0),
9605                          objfile_name (objfile));
9606               return;
9607             }
9608           ++name;
9609
9610           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9611           field_type = TYPE_FIELD_TYPE (field_type, index);
9612         }
9613
9614       /* Make a union to hold the variants.  */
9615       struct type *union_type = alloc_type (objfile);
9616       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9617       TYPE_NFIELDS (union_type) = 3;
9618       TYPE_FIELDS (union_type)
9619         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9620       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9621       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9622
9623       /* Put the discriminant must at index 0.  */
9624       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9625       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9626       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9627       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9628
9629       /* The order of fields doesn't really matter, so put the real
9630          field at index 1 and the data-less field at index 2.  */
9631       struct discriminant_info *disc
9632         = alloc_discriminant_info (union_type, 0, 1);
9633       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9634       TYPE_FIELD_NAME (union_type, 1)
9635         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9636       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9637         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9638                               TYPE_FIELD_NAME (union_type, 1));
9639
9640       const char *dataless_name
9641         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9642                               name);
9643       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9644                                               dataless_name);
9645       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9646       /* NAME points into the original discriminant name, which
9647          already has the correct lifetime.  */
9648       TYPE_FIELD_NAME (union_type, 2) = name;
9649       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9650       disc->discriminants[2] = 0;
9651
9652       /* Smash this type to be a structure type.  We have to do this
9653          because the type has already been recorded.  */
9654       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9655       TYPE_NFIELDS (type) = 1;
9656       TYPE_FIELDS (type)
9657         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9658
9659       /* Install the variant part.  */
9660       TYPE_FIELD_TYPE (type, 0) = union_type;
9661       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9662       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9663     }
9664   /* A union with a single anonymous field is probably an old-style
9665      univariant enum.  */
9666   else if (TYPE_NFIELDS (type) == 1 && streq (TYPE_FIELD_NAME (type, 0), ""))
9667     {
9668       /* Smash this type to be a structure type.  We have to do this
9669          because the type has already been recorded.  */
9670       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9671
9672       /* Make a union to hold the variants.  */
9673       struct type *union_type = alloc_type (objfile);
9674       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9675       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9676       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9677       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9678       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9679
9680       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9681       const char *variant_name
9682         = rust_last_path_segment (TYPE_NAME (field_type));
9683       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9684       TYPE_NAME (field_type)
9685         = rust_fully_qualify (&objfile->objfile_obstack,
9686                               TYPE_NAME (type), variant_name);
9687
9688       /* Install the union in the outer struct type.  */
9689       TYPE_NFIELDS (type) = 1;
9690       TYPE_FIELDS (type)
9691         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9692       TYPE_FIELD_TYPE (type, 0) = union_type;
9693       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9694       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9695
9696       alloc_discriminant_info (union_type, -1, 0);
9697     }
9698   else
9699     {
9700       struct type *disr_type = nullptr;
9701       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9702         {
9703           disr_type = TYPE_FIELD_TYPE (type, i);
9704
9705           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9706             {
9707               /* All fields of a true enum will be structs.  */
9708               return;
9709             }
9710           else if (TYPE_NFIELDS (disr_type) == 0)
9711             {
9712               /* Could be data-less variant, so keep going.  */
9713               disr_type = nullptr;
9714             }
9715           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9716                            "RUST$ENUM$DISR") != 0)
9717             {
9718               /* Not a Rust enum.  */
9719               return;
9720             }
9721           else
9722             {
9723               /* Found one.  */
9724               break;
9725             }
9726         }
9727
9728       /* If we got here without a discriminant, then it's probably
9729          just a union.  */
9730       if (disr_type == nullptr)
9731         return;
9732
9733       /* Smash this type to be a structure type.  We have to do this
9734          because the type has already been recorded.  */
9735       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9736
9737       /* Make a union to hold the variants.  */
9738       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
9739       struct type *union_type = alloc_type (objfile);
9740       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9741       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
9742       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9743       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9744       TYPE_FIELDS (union_type)
9745         = (struct field *) TYPE_ZALLOC (union_type,
9746                                         (TYPE_NFIELDS (union_type)
9747                                          * sizeof (struct field)));
9748
9749       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
9750               TYPE_NFIELDS (type) * sizeof (struct field));
9751
9752       /* Install the discriminant at index 0 in the union.  */
9753       TYPE_FIELD (union_type, 0) = *disr_field;
9754       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9755       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9756
9757       /* Install the union in the outer struct type.  */
9758       TYPE_FIELD_TYPE (type, 0) = union_type;
9759       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9760       TYPE_NFIELDS (type) = 1;
9761
9762       /* Set the size and offset of the union type.  */
9763       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9764
9765       /* We need a way to find the correct discriminant given a
9766          variant name.  For convenience we build a map here.  */
9767       struct type *enum_type = FIELD_TYPE (*disr_field);
9768       std::unordered_map<std::string, ULONGEST> discriminant_map;
9769       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
9770         {
9771           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
9772             {
9773               const char *name
9774                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
9775               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
9776             }
9777         }
9778
9779       int n_fields = TYPE_NFIELDS (union_type);
9780       struct discriminant_info *disc
9781         = alloc_discriminant_info (union_type, 0, -1);
9782       /* Skip the discriminant here.  */
9783       for (int i = 1; i < n_fields; ++i)
9784         {
9785           /* Find the final word in the name of this variant's type.
9786              That name can be used to look up the correct
9787              discriminant.  */
9788           const char *variant_name
9789             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
9790                                                                   i)));
9791
9792           auto iter = discriminant_map.find (variant_name);
9793           if (iter != discriminant_map.end ())
9794             disc->discriminants[i] = iter->second;
9795
9796           /* Remove the discriminant field, if it exists.  */
9797           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
9798           if (TYPE_NFIELDS (sub_type) > 0)
9799             {
9800               --TYPE_NFIELDS (sub_type);
9801               ++TYPE_FIELDS (sub_type);
9802             }
9803           TYPE_FIELD_NAME (union_type, i) = variant_name;
9804           TYPE_NAME (sub_type)
9805             = rust_fully_qualify (&objfile->objfile_obstack,
9806                                   TYPE_NAME (type), variant_name);
9807         }
9808     }
9809 }
9810
9811 /* Rewrite some Rust unions to be structures with variants parts.  */
9812
9813 static void
9814 rust_union_quirks (struct dwarf2_cu *cu)
9815 {
9816   gdb_assert (cu->language == language_rust);
9817   for (type *type_ : cu->rust_unions)
9818     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
9819   /* We don't need this any more.  */
9820   cu->rust_unions.clear ();
9821 }
9822
9823 /* Return the symtab for PER_CU.  This works properly regardless of
9824    whether we're using the index or psymtabs.  */
9825
9826 static struct compunit_symtab *
9827 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
9828 {
9829   return (per_cu->dwarf2_per_objfile->using_index
9830           ? per_cu->v.quick->compunit_symtab
9831           : per_cu->v.psymtab->compunit_symtab);
9832 }
9833
9834 /* A helper function for computing the list of all symbol tables
9835    included by PER_CU.  */
9836
9837 static void
9838 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
9839                                 htab_t all_children, htab_t all_type_symtabs,
9840                                 struct dwarf2_per_cu_data *per_cu,
9841                                 struct compunit_symtab *immediate_parent)
9842 {
9843   void **slot;
9844   struct compunit_symtab *cust;
9845
9846   slot = htab_find_slot (all_children, per_cu, INSERT);
9847   if (*slot != NULL)
9848     {
9849       /* This inclusion and its children have been processed.  */
9850       return;
9851     }
9852
9853   *slot = per_cu;
9854   /* Only add a CU if it has a symbol table.  */
9855   cust = get_compunit_symtab (per_cu);
9856   if (cust != NULL)
9857     {
9858       /* If this is a type unit only add its symbol table if we haven't
9859          seen it yet (type unit per_cu's can share symtabs).  */
9860       if (per_cu->is_debug_types)
9861         {
9862           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9863           if (*slot == NULL)
9864             {
9865               *slot = cust;
9866               result->push_back (cust);
9867               if (cust->user == NULL)
9868                 cust->user = immediate_parent;
9869             }
9870         }
9871       else
9872         {
9873           result->push_back (cust);
9874           if (cust->user == NULL)
9875             cust->user = immediate_parent;
9876         }
9877     }
9878
9879   if (!per_cu->imported_symtabs_empty ())
9880     for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9881       {
9882         recursively_compute_inclusions (result, all_children,
9883                                         all_type_symtabs, ptr, cust);
9884       }
9885 }
9886
9887 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9888    PER_CU.  */
9889
9890 static void
9891 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
9892 {
9893   gdb_assert (! per_cu->is_debug_types);
9894
9895   if (!per_cu->imported_symtabs_empty ())
9896     {
9897       int len;
9898       std::vector<compunit_symtab *> result_symtabs;
9899       htab_t all_children, all_type_symtabs;
9900       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
9901
9902       /* If we don't have a symtab, we can just skip this case.  */
9903       if (cust == NULL)
9904         return;
9905
9906       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9907                                         NULL, xcalloc, xfree);
9908       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9909                                             NULL, xcalloc, xfree);
9910
9911       for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9912         {
9913           recursively_compute_inclusions (&result_symtabs, all_children,
9914                                           all_type_symtabs, ptr, cust);
9915         }
9916
9917       /* Now we have a transitive closure of all the included symtabs.  */
9918       len = result_symtabs.size ();
9919       cust->includes
9920         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
9921                      struct compunit_symtab *, len + 1);
9922       memcpy (cust->includes, result_symtabs.data (),
9923               len * sizeof (compunit_symtab *));
9924       cust->includes[len] = NULL;
9925
9926       htab_delete (all_children);
9927       htab_delete (all_type_symtabs);
9928     }
9929 }
9930
9931 /* Compute the 'includes' field for the symtabs of all the CUs we just
9932    read.  */
9933
9934 static void
9935 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
9936 {
9937   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
9938     {
9939       if (! iter->is_debug_types)
9940         compute_compunit_symtab_includes (iter);
9941     }
9942
9943   dwarf2_per_objfile->just_read_cus.clear ();
9944 }
9945
9946 /* Generate full symbol information for PER_CU, whose DIEs have
9947    already been loaded into memory.  */
9948
9949 static void
9950 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
9951                         enum language pretend_language)
9952 {
9953   struct dwarf2_cu *cu = per_cu->cu;
9954   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
9955   struct objfile *objfile = dwarf2_per_objfile->objfile;
9956   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9957   CORE_ADDR lowpc, highpc;
9958   struct compunit_symtab *cust;
9959   CORE_ADDR baseaddr;
9960   struct block *static_block;
9961   CORE_ADDR addr;
9962
9963   baseaddr = objfile->text_section_offset ();
9964
9965   /* Clear the list here in case something was left over.  */
9966   cu->method_list.clear ();
9967
9968   cu->language = pretend_language;
9969   cu->language_defn = language_def (cu->language);
9970
9971   /* Do line number decoding in read_file_scope () */
9972   process_die (cu->dies, cu);
9973
9974   /* For now fudge the Go package.  */
9975   if (cu->language == language_go)
9976     fixup_go_packaging (cu);
9977
9978   /* Now that we have processed all the DIEs in the CU, all the types
9979      should be complete, and it should now be safe to compute all of the
9980      physnames.  */
9981   compute_delayed_physnames (cu);
9982
9983   if (cu->language == language_rust)
9984     rust_union_quirks (cu);
9985
9986   /* Some compilers don't define a DW_AT_high_pc attribute for the
9987      compilation unit.  If the DW_AT_high_pc is missing, synthesize
9988      it, by scanning the DIE's below the compilation unit.  */
9989   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
9990
9991   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
9992   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
9993
9994   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
9995      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
9996      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
9997      addrmap to help ensure it has an accurate map of pc values belonging to
9998      this comp unit.  */
9999   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10000
10001   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
10002                                                     SECT_OFF_TEXT (objfile),
10003                                                     0);
10004
10005   if (cust != NULL)
10006     {
10007       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10008
10009       /* Set symtab language to language from DW_AT_language.  If the
10010          compilation is from a C file generated by language preprocessors, do
10011          not set the language if it was already deduced by start_subfile.  */
10012       if (!(cu->language == language_c
10013             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10014         COMPUNIT_FILETABS (cust)->language = cu->language;
10015
10016       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10017          produce DW_AT_location with location lists but it can be possibly
10018          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10019          there were bugs in prologue debug info, fixed later in GCC-4.5
10020          by "unwind info for epilogues" patch (which is not directly related).
10021
10022          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10023          needed, it would be wrong due to missing DW_AT_producer there.
10024
10025          Still one can confuse GDB by using non-standard GCC compilation
10026          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10027          */
10028       if (cu->has_loclist && gcc_4_minor >= 5)
10029         cust->locations_valid = 1;
10030
10031       if (gcc_4_minor >= 5)
10032         cust->epilogue_unwind_valid = 1;
10033
10034       cust->call_site_htab = cu->call_site_htab;
10035     }
10036
10037   if (dwarf2_per_objfile->using_index)
10038     per_cu->v.quick->compunit_symtab = cust;
10039   else
10040     {
10041       dwarf2_psymtab *pst = per_cu->v.psymtab;
10042       pst->compunit_symtab = cust;
10043       pst->readin = true;
10044     }
10045
10046   /* Push it for inclusion processing later.  */
10047   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10048
10049   /* Not needed any more.  */
10050   cu->reset_builder ();
10051 }
10052
10053 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10054    already been loaded into memory.  */
10055
10056 static void
10057 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10058                         enum language pretend_language)
10059 {
10060   struct dwarf2_cu *cu = per_cu->cu;
10061   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10062   struct objfile *objfile = dwarf2_per_objfile->objfile;
10063   struct compunit_symtab *cust;
10064   struct signatured_type *sig_type;
10065
10066   gdb_assert (per_cu->is_debug_types);
10067   sig_type = (struct signatured_type *) per_cu;
10068
10069   /* Clear the list here in case something was left over.  */
10070   cu->method_list.clear ();
10071
10072   cu->language = pretend_language;
10073   cu->language_defn = language_def (cu->language);
10074
10075   /* The symbol tables are set up in read_type_unit_scope.  */
10076   process_die (cu->dies, cu);
10077
10078   /* For now fudge the Go package.  */
10079   if (cu->language == language_go)
10080     fixup_go_packaging (cu);
10081
10082   /* Now that we have processed all the DIEs in the CU, all the types
10083      should be complete, and it should now be safe to compute all of the
10084      physnames.  */
10085   compute_delayed_physnames (cu);
10086
10087   if (cu->language == language_rust)
10088     rust_union_quirks (cu);
10089
10090   /* TUs share symbol tables.
10091      If this is the first TU to use this symtab, complete the construction
10092      of it with end_expandable_symtab.  Otherwise, complete the addition of
10093      this TU's symbols to the existing symtab.  */
10094   if (sig_type->type_unit_group->compunit_symtab == NULL)
10095     {
10096       buildsym_compunit *builder = cu->get_builder ();
10097       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10098       sig_type->type_unit_group->compunit_symtab = cust;
10099
10100       if (cust != NULL)
10101         {
10102           /* Set symtab language to language from DW_AT_language.  If the
10103              compilation is from a C file generated by language preprocessors,
10104              do not set the language if it was already deduced by
10105              start_subfile.  */
10106           if (!(cu->language == language_c
10107                 && COMPUNIT_FILETABS (cust)->language != language_c))
10108             COMPUNIT_FILETABS (cust)->language = cu->language;
10109         }
10110     }
10111   else
10112     {
10113       cu->get_builder ()->augment_type_symtab ();
10114       cust = sig_type->type_unit_group->compunit_symtab;
10115     }
10116
10117   if (dwarf2_per_objfile->using_index)
10118     per_cu->v.quick->compunit_symtab = cust;
10119   else
10120     {
10121       dwarf2_psymtab *pst = per_cu->v.psymtab;
10122       pst->compunit_symtab = cust;
10123       pst->readin = true;
10124     }
10125
10126   /* Not needed any more.  */
10127   cu->reset_builder ();
10128 }
10129
10130 /* Process an imported unit DIE.  */
10131
10132 static void
10133 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10134 {
10135   struct attribute *attr;
10136
10137   /* For now we don't handle imported units in type units.  */
10138   if (cu->per_cu->is_debug_types)
10139     {
10140       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10141                " supported in type units [in module %s]"),
10142              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10143     }
10144
10145   attr = dwarf2_attr (die, DW_AT_import, cu);
10146   if (attr != NULL)
10147     {
10148       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10149       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10150       dwarf2_per_cu_data *per_cu
10151         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10152                                             cu->per_cu->dwarf2_per_objfile);
10153
10154       /* If necessary, add it to the queue and load its DIEs.  */
10155       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10156         load_full_comp_unit (per_cu, false, cu->language);
10157
10158       cu->per_cu->imported_symtabs_push (per_cu);
10159     }
10160 }
10161
10162 /* RAII object that represents a process_die scope: i.e.,
10163    starts/finishes processing a DIE.  */
10164 class process_die_scope
10165 {
10166 public:
10167   process_die_scope (die_info *die, dwarf2_cu *cu)
10168     : m_die (die), m_cu (cu)
10169   {
10170     /* We should only be processing DIEs not already in process.  */
10171     gdb_assert (!m_die->in_process);
10172     m_die->in_process = true;
10173   }
10174
10175   ~process_die_scope ()
10176   {
10177     m_die->in_process = false;
10178
10179     /* If we're done processing the DIE for the CU that owns the line
10180        header, we don't need the line header anymore.  */
10181     if (m_cu->line_header_die_owner == m_die)
10182       {
10183         delete m_cu->line_header;
10184         m_cu->line_header = NULL;
10185         m_cu->line_header_die_owner = NULL;
10186       }
10187   }
10188
10189 private:
10190   die_info *m_die;
10191   dwarf2_cu *m_cu;
10192 };
10193
10194 /* Process a die and its children.  */
10195
10196 static void
10197 process_die (struct die_info *die, struct dwarf2_cu *cu)
10198 {
10199   process_die_scope scope (die, cu);
10200
10201   switch (die->tag)
10202     {
10203     case DW_TAG_padding:
10204       break;
10205     case DW_TAG_compile_unit:
10206     case DW_TAG_partial_unit:
10207       read_file_scope (die, cu);
10208       break;
10209     case DW_TAG_type_unit:
10210       read_type_unit_scope (die, cu);
10211       break;
10212     case DW_TAG_subprogram:
10213       /* Nested subprograms in Fortran get a prefix.  */
10214       if (cu->language == language_fortran
10215           && die->parent != NULL
10216           && die->parent->tag == DW_TAG_subprogram)
10217         cu->processing_has_namespace_info = true;
10218       /* Fall through.  */
10219     case DW_TAG_inlined_subroutine:
10220       read_func_scope (die, cu);
10221       break;
10222     case DW_TAG_lexical_block:
10223     case DW_TAG_try_block:
10224     case DW_TAG_catch_block:
10225       read_lexical_block_scope (die, cu);
10226       break;
10227     case DW_TAG_call_site:
10228     case DW_TAG_GNU_call_site:
10229       read_call_site_scope (die, cu);
10230       break;
10231     case DW_TAG_class_type:
10232     case DW_TAG_interface_type:
10233     case DW_TAG_structure_type:
10234     case DW_TAG_union_type:
10235       process_structure_scope (die, cu);
10236       break;
10237     case DW_TAG_enumeration_type:
10238       process_enumeration_scope (die, cu);
10239       break;
10240
10241     /* These dies have a type, but processing them does not create
10242        a symbol or recurse to process the children.  Therefore we can
10243        read them on-demand through read_type_die.  */
10244     case DW_TAG_subroutine_type:
10245     case DW_TAG_set_type:
10246     case DW_TAG_array_type:
10247     case DW_TAG_pointer_type:
10248     case DW_TAG_ptr_to_member_type:
10249     case DW_TAG_reference_type:
10250     case DW_TAG_rvalue_reference_type:
10251     case DW_TAG_string_type:
10252       break;
10253
10254     case DW_TAG_base_type:
10255     case DW_TAG_subrange_type:
10256     case DW_TAG_typedef:
10257       /* Add a typedef symbol for the type definition, if it has a
10258          DW_AT_name.  */
10259       new_symbol (die, read_type_die (die, cu), cu);
10260       break;
10261     case DW_TAG_common_block:
10262       read_common_block (die, cu);
10263       break;
10264     case DW_TAG_common_inclusion:
10265       break;
10266     case DW_TAG_namespace:
10267       cu->processing_has_namespace_info = true;
10268       read_namespace (die, cu);
10269       break;
10270     case DW_TAG_module:
10271       cu->processing_has_namespace_info = true;
10272       read_module (die, cu);
10273       break;
10274     case DW_TAG_imported_declaration:
10275       cu->processing_has_namespace_info = true;
10276       if (read_namespace_alias (die, cu))
10277         break;
10278       /* The declaration is not a global namespace alias.  */
10279       /* Fall through.  */
10280     case DW_TAG_imported_module:
10281       cu->processing_has_namespace_info = true;
10282       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10283                                  || cu->language != language_fortran))
10284         complaint (_("Tag '%s' has unexpected children"),
10285                    dwarf_tag_name (die->tag));
10286       read_import_statement (die, cu);
10287       break;
10288
10289     case DW_TAG_imported_unit:
10290       process_imported_unit_die (die, cu);
10291       break;
10292
10293     case DW_TAG_variable:
10294       read_variable (die, cu);
10295       break;
10296
10297     default:
10298       new_symbol (die, NULL, cu);
10299       break;
10300     }
10301 }
10302 \f
10303 /* DWARF name computation.  */
10304
10305 /* A helper function for dwarf2_compute_name which determines whether DIE
10306    needs to have the name of the scope prepended to the name listed in the
10307    die.  */
10308
10309 static int
10310 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10311 {
10312   struct attribute *attr;
10313
10314   switch (die->tag)
10315     {
10316     case DW_TAG_namespace:
10317     case DW_TAG_typedef:
10318     case DW_TAG_class_type:
10319     case DW_TAG_interface_type:
10320     case DW_TAG_structure_type:
10321     case DW_TAG_union_type:
10322     case DW_TAG_enumeration_type:
10323     case DW_TAG_enumerator:
10324     case DW_TAG_subprogram:
10325     case DW_TAG_inlined_subroutine:
10326     case DW_TAG_member:
10327     case DW_TAG_imported_declaration:
10328       return 1;
10329
10330     case DW_TAG_variable:
10331     case DW_TAG_constant:
10332       /* We only need to prefix "globally" visible variables.  These include
10333          any variable marked with DW_AT_external or any variable that
10334          lives in a namespace.  [Variables in anonymous namespaces
10335          require prefixing, but they are not DW_AT_external.]  */
10336
10337       if (dwarf2_attr (die, DW_AT_specification, cu))
10338         {
10339           struct dwarf2_cu *spec_cu = cu;
10340
10341           return die_needs_namespace (die_specification (die, &spec_cu),
10342                                       spec_cu);
10343         }
10344
10345       attr = dwarf2_attr (die, DW_AT_external, cu);
10346       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10347           && die->parent->tag != DW_TAG_module)
10348         return 0;
10349       /* A variable in a lexical block of some kind does not need a
10350          namespace, even though in C++ such variables may be external
10351          and have a mangled name.  */
10352       if (die->parent->tag ==  DW_TAG_lexical_block
10353           || die->parent->tag ==  DW_TAG_try_block
10354           || die->parent->tag ==  DW_TAG_catch_block
10355           || die->parent->tag == DW_TAG_subprogram)
10356         return 0;
10357       return 1;
10358
10359     default:
10360       return 0;
10361     }
10362 }
10363
10364 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10365    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10366    defined for the given DIE.  */
10367
10368 static struct attribute *
10369 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10370 {
10371   struct attribute *attr;
10372
10373   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10374   if (attr == NULL)
10375     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10376
10377   return attr;
10378 }
10379
10380 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10381    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10382    defined for the given DIE.  */
10383
10384 static const char *
10385 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10386 {
10387   const char *linkage_name;
10388
10389   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10390   if (linkage_name == NULL)
10391     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10392
10393   return linkage_name;
10394 }
10395
10396 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10397    compute the physname for the object, which include a method's:
10398    - formal parameters (C++),
10399    - receiver type (Go),
10400
10401    The term "physname" is a bit confusing.
10402    For C++, for example, it is the demangled name.
10403    For Go, for example, it's the mangled name.
10404
10405    For Ada, return the DIE's linkage name rather than the fully qualified
10406    name.  PHYSNAME is ignored..
10407
10408    The result is allocated on the objfile_obstack and canonicalized.  */
10409
10410 static const char *
10411 dwarf2_compute_name (const char *name,
10412                      struct die_info *die, struct dwarf2_cu *cu,
10413                      int physname)
10414 {
10415   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10416
10417   if (name == NULL)
10418     name = dwarf2_name (die, cu);
10419
10420   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10421      but otherwise compute it by typename_concat inside GDB.
10422      FIXME: Actually this is not really true, or at least not always true.
10423      It's all very confusing.  compute_and_set_names doesn't try to demangle
10424      Fortran names because there is no mangling standard.  So new_symbol
10425      will set the demangled name to the result of dwarf2_full_name, and it is
10426      the demangled name that GDB uses if it exists.  */
10427   if (cu->language == language_ada
10428       || (cu->language == language_fortran && physname))
10429     {
10430       /* For Ada unit, we prefer the linkage name over the name, as
10431          the former contains the exported name, which the user expects
10432          to be able to reference.  Ideally, we want the user to be able
10433          to reference this entity using either natural or linkage name,
10434          but we haven't started looking at this enhancement yet.  */
10435       const char *linkage_name = dw2_linkage_name (die, cu);
10436
10437       if (linkage_name != NULL)
10438         return linkage_name;
10439     }
10440
10441   /* These are the only languages we know how to qualify names in.  */
10442   if (name != NULL
10443       && (cu->language == language_cplus
10444           || cu->language == language_fortran || cu->language == language_d
10445           || cu->language == language_rust))
10446     {
10447       if (die_needs_namespace (die, cu))
10448         {
10449           const char *prefix;
10450           const char *canonical_name = NULL;
10451
10452           string_file buf;
10453
10454           prefix = determine_prefix (die, cu);
10455           if (*prefix != '\0')
10456             {
10457               gdb::unique_xmalloc_ptr<char> prefixed_name
10458                 (typename_concat (NULL, prefix, name, physname, cu));
10459
10460               buf.puts (prefixed_name.get ());
10461             }
10462           else
10463             buf.puts (name);
10464
10465           /* Template parameters may be specified in the DIE's DW_AT_name, or
10466              as children with DW_TAG_template_type_param or
10467              DW_TAG_value_type_param.  If the latter, add them to the name
10468              here.  If the name already has template parameters, then
10469              skip this step; some versions of GCC emit both, and
10470              it is more efficient to use the pre-computed name.
10471
10472              Something to keep in mind about this process: it is very
10473              unlikely, or in some cases downright impossible, to produce
10474              something that will match the mangled name of a function.
10475              If the definition of the function has the same debug info,
10476              we should be able to match up with it anyway.  But fallbacks
10477              using the minimal symbol, for instance to find a method
10478              implemented in a stripped copy of libstdc++, will not work.
10479              If we do not have debug info for the definition, we will have to
10480              match them up some other way.
10481
10482              When we do name matching there is a related problem with function
10483              templates; two instantiated function templates are allowed to
10484              differ only by their return types, which we do not add here.  */
10485
10486           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10487             {
10488               struct attribute *attr;
10489               struct die_info *child;
10490               int first = 1;
10491
10492               die->building_fullname = 1;
10493
10494               for (child = die->child; child != NULL; child = child->sibling)
10495                 {
10496                   struct type *type;
10497                   LONGEST value;
10498                   const gdb_byte *bytes;
10499                   struct dwarf2_locexpr_baton *baton;
10500                   struct value *v;
10501
10502                   if (child->tag != DW_TAG_template_type_param
10503                       && child->tag != DW_TAG_template_value_param)
10504                     continue;
10505
10506                   if (first)
10507                     {
10508                       buf.puts ("<");
10509                       first = 0;
10510                     }
10511                   else
10512                     buf.puts (", ");
10513
10514                   attr = dwarf2_attr (child, DW_AT_type, cu);
10515                   if (attr == NULL)
10516                     {
10517                       complaint (_("template parameter missing DW_AT_type"));
10518                       buf.puts ("UNKNOWN_TYPE");
10519                       continue;
10520                     }
10521                   type = die_type (child, cu);
10522
10523                   if (child->tag == DW_TAG_template_type_param)
10524                     {
10525                       c_print_type (type, "", &buf, -1, 0, cu->language,
10526                                     &type_print_raw_options);
10527                       continue;
10528                     }
10529
10530                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10531                   if (attr == NULL)
10532                     {
10533                       complaint (_("template parameter missing "
10534                                    "DW_AT_const_value"));
10535                       buf.puts ("UNKNOWN_VALUE");
10536                       continue;
10537                     }
10538
10539                   dwarf2_const_value_attr (attr, type, name,
10540                                            &cu->comp_unit_obstack, cu,
10541                                            &value, &bytes, &baton);
10542
10543                   if (TYPE_NOSIGN (type))
10544                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10545                        changed, this can use value_print instead.  */
10546                     c_printchar (value, type, &buf);
10547                   else
10548                     {
10549                       struct value_print_options opts;
10550
10551                       if (baton != NULL)
10552                         v = dwarf2_evaluate_loc_desc (type, NULL,
10553                                                       baton->data,
10554                                                       baton->size,
10555                                                       baton->per_cu);
10556                       else if (bytes != NULL)
10557                         {
10558                           v = allocate_value (type);
10559                           memcpy (value_contents_writeable (v), bytes,
10560                                   TYPE_LENGTH (type));
10561                         }
10562                       else
10563                         v = value_from_longest (type, value);
10564
10565                       /* Specify decimal so that we do not depend on
10566                          the radix.  */
10567                       get_formatted_print_options (&opts, 'd');
10568                       opts.raw = 1;
10569                       value_print (v, &buf, &opts);
10570                       release_value (v);
10571                     }
10572                 }
10573
10574               die->building_fullname = 0;
10575
10576               if (!first)
10577                 {
10578                   /* Close the argument list, with a space if necessary
10579                      (nested templates).  */
10580                   if (!buf.empty () && buf.string ().back () == '>')
10581                     buf.puts (" >");
10582                   else
10583                     buf.puts (">");
10584                 }
10585             }
10586
10587           /* For C++ methods, append formal parameter type
10588              information, if PHYSNAME.  */
10589
10590           if (physname && die->tag == DW_TAG_subprogram
10591               && cu->language == language_cplus)
10592             {
10593               struct type *type = read_type_die (die, cu);
10594
10595               c_type_print_args (type, &buf, 1, cu->language,
10596                                  &type_print_raw_options);
10597
10598               if (cu->language == language_cplus)
10599                 {
10600                   /* Assume that an artificial first parameter is
10601                      "this", but do not crash if it is not.  RealView
10602                      marks unnamed (and thus unused) parameters as
10603                      artificial; there is no way to differentiate
10604                      the two cases.  */
10605                   if (TYPE_NFIELDS (type) > 0
10606                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10607                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10608                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10609                                                                         0))))
10610                     buf.puts (" const");
10611                 }
10612             }
10613
10614           const std::string &intermediate_name = buf.string ();
10615
10616           if (cu->language == language_cplus)
10617             canonical_name
10618               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10619                                           &objfile->per_bfd->storage_obstack);
10620
10621           /* If we only computed INTERMEDIATE_NAME, or if
10622              INTERMEDIATE_NAME is already canonical, then we need to
10623              copy it to the appropriate obstack.  */
10624           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10625             name = obstack_strdup (&objfile->per_bfd->storage_obstack,
10626                                    intermediate_name);
10627           else
10628             name = canonical_name;
10629         }
10630     }
10631
10632   return name;
10633 }
10634
10635 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10636    If scope qualifiers are appropriate they will be added.  The result
10637    will be allocated on the storage_obstack, or NULL if the DIE does
10638    not have a name.  NAME may either be from a previous call to
10639    dwarf2_name or NULL.
10640
10641    The output string will be canonicalized (if C++).  */
10642
10643 static const char *
10644 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10645 {
10646   return dwarf2_compute_name (name, die, cu, 0);
10647 }
10648
10649 /* Construct a physname for the given DIE in CU.  NAME may either be
10650    from a previous call to dwarf2_name or NULL.  The result will be
10651    allocated on the objfile_objstack or NULL if the DIE does not have a
10652    name.
10653
10654    The output string will be canonicalized (if C++).  */
10655
10656 static const char *
10657 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10658 {
10659   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10660   const char *retval, *mangled = NULL, *canon = NULL;
10661   int need_copy = 1;
10662
10663   /* In this case dwarf2_compute_name is just a shortcut not building anything
10664      on its own.  */
10665   if (!die_needs_namespace (die, cu))
10666     return dwarf2_compute_name (name, die, cu, 1);
10667
10668   mangled = dw2_linkage_name (die, cu);
10669
10670   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10671      See https://github.com/rust-lang/rust/issues/32925.  */
10672   if (cu->language == language_rust && mangled != NULL
10673       && strchr (mangled, '{') != NULL)
10674     mangled = NULL;
10675
10676   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10677      has computed.  */
10678   gdb::unique_xmalloc_ptr<char> demangled;
10679   if (mangled != NULL)
10680     {
10681
10682       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10683         {
10684           /* Do nothing (do not demangle the symbol name).  */
10685         }
10686       else if (cu->language == language_go)
10687         {
10688           /* This is a lie, but we already lie to the caller new_symbol.
10689              new_symbol assumes we return the mangled name.
10690              This just undoes that lie until things are cleaned up.  */
10691         }
10692       else
10693         {
10694           /* Use DMGL_RET_DROP for C++ template functions to suppress
10695              their return type.  It is easier for GDB users to search
10696              for such functions as `name(params)' than `long name(params)'.
10697              In such case the minimal symbol names do not match the full
10698              symbol names but for template functions there is never a need
10699              to look up their definition from their declaration so
10700              the only disadvantage remains the minimal symbol variant
10701              `long name(params)' does not have the proper inferior type.  */
10702           demangled.reset (gdb_demangle (mangled,
10703                                          (DMGL_PARAMS | DMGL_ANSI
10704                                           | DMGL_RET_DROP)));
10705         }
10706       if (demangled)
10707         canon = demangled.get ();
10708       else
10709         {
10710           canon = mangled;
10711           need_copy = 0;
10712         }
10713     }
10714
10715   if (canon == NULL || check_physname)
10716     {
10717       const char *physname = dwarf2_compute_name (name, die, cu, 1);
10718
10719       if (canon != NULL && strcmp (physname, canon) != 0)
10720         {
10721           /* It may not mean a bug in GDB.  The compiler could also
10722              compute DW_AT_linkage_name incorrectly.  But in such case
10723              GDB would need to be bug-to-bug compatible.  */
10724
10725           complaint (_("Computed physname <%s> does not match demangled <%s> "
10726                        "(from linkage <%s>) - DIE at %s [in module %s]"),
10727                      physname, canon, mangled, sect_offset_str (die->sect_off),
10728                      objfile_name (objfile));
10729
10730           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
10731              is available here - over computed PHYSNAME.  It is safer
10732              against both buggy GDB and buggy compilers.  */
10733
10734           retval = canon;
10735         }
10736       else
10737         {
10738           retval = physname;
10739           need_copy = 0;
10740         }
10741     }
10742   else
10743     retval = canon;
10744
10745   if (need_copy)
10746     retval = obstack_strdup (&objfile->per_bfd->storage_obstack, retval);
10747
10748   return retval;
10749 }
10750
10751 /* Inspect DIE in CU for a namespace alias.  If one exists, record
10752    a new symbol for it.
10753
10754    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
10755
10756 static int
10757 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
10758 {
10759   struct attribute *attr;
10760
10761   /* If the die does not have a name, this is not a namespace
10762      alias.  */
10763   attr = dwarf2_attr (die, DW_AT_name, cu);
10764   if (attr != NULL)
10765     {
10766       int num;
10767       struct die_info *d = die;
10768       struct dwarf2_cu *imported_cu = cu;
10769
10770       /* If the compiler has nested DW_AT_imported_declaration DIEs,
10771          keep inspecting DIEs until we hit the underlying import.  */
10772 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
10773       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
10774         {
10775           attr = dwarf2_attr (d, DW_AT_import, cu);
10776           if (attr == NULL)
10777             break;
10778
10779           d = follow_die_ref (d, attr, &imported_cu);
10780           if (d->tag != DW_TAG_imported_declaration)
10781             break;
10782         }
10783
10784       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10785         {
10786           complaint (_("DIE at %s has too many recursively imported "
10787                        "declarations"), sect_offset_str (d->sect_off));
10788           return 0;
10789         }
10790
10791       if (attr != NULL)
10792         {
10793           struct type *type;
10794           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10795
10796           type = get_die_type_at_offset (sect_off, cu->per_cu);
10797           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
10798             {
10799               /* This declaration is a global namespace alias.  Add
10800                  a symbol for it whose type is the aliased namespace.  */
10801               new_symbol (die, type, cu);
10802               return 1;
10803             }
10804         }
10805     }
10806
10807   return 0;
10808 }
10809
10810 /* Return the using directives repository (global or local?) to use in the
10811    current context for CU.
10812
10813    For Ada, imported declarations can materialize renamings, which *may* be
10814    global.  However it is impossible (for now?) in DWARF to distinguish
10815    "external" imported declarations and "static" ones.  As all imported
10816    declarations seem to be static in all other languages, make them all CU-wide
10817    global only in Ada.  */
10818
10819 static struct using_direct **
10820 using_directives (struct dwarf2_cu *cu)
10821 {
10822   if (cu->language == language_ada
10823       && cu->get_builder ()->outermost_context_p ())
10824     return cu->get_builder ()->get_global_using_directives ();
10825   else
10826     return cu->get_builder ()->get_local_using_directives ();
10827 }
10828
10829 /* Read the import statement specified by the given die and record it.  */
10830
10831 static void
10832 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10833 {
10834   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10835   struct attribute *import_attr;
10836   struct die_info *imported_die, *child_die;
10837   struct dwarf2_cu *imported_cu;
10838   const char *imported_name;
10839   const char *imported_name_prefix;
10840   const char *canonical_name;
10841   const char *import_alias;
10842   const char *imported_declaration = NULL;
10843   const char *import_prefix;
10844   std::vector<const char *> excludes;
10845
10846   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10847   if (import_attr == NULL)
10848     {
10849       complaint (_("Tag '%s' has no DW_AT_import"),
10850                  dwarf_tag_name (die->tag));
10851       return;
10852     }
10853
10854   imported_cu = cu;
10855   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10856   imported_name = dwarf2_name (imported_die, imported_cu);
10857   if (imported_name == NULL)
10858     {
10859       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10860
10861         The import in the following code:
10862         namespace A
10863           {
10864             typedef int B;
10865           }
10866
10867         int main ()
10868           {
10869             using A::B;
10870             B b;
10871             return b;
10872           }
10873
10874         ...
10875          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10876             <52>   DW_AT_decl_file   : 1
10877             <53>   DW_AT_decl_line   : 6
10878             <54>   DW_AT_import      : <0x75>
10879          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10880             <59>   DW_AT_name        : B
10881             <5b>   DW_AT_decl_file   : 1
10882             <5c>   DW_AT_decl_line   : 2
10883             <5d>   DW_AT_type        : <0x6e>
10884         ...
10885          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10886             <76>   DW_AT_byte_size   : 4
10887             <77>   DW_AT_encoding    : 5        (signed)
10888
10889         imports the wrong die ( 0x75 instead of 0x58 ).
10890         This case will be ignored until the gcc bug is fixed.  */
10891       return;
10892     }
10893
10894   /* Figure out the local name after import.  */
10895   import_alias = dwarf2_name (die, cu);
10896
10897   /* Figure out where the statement is being imported to.  */
10898   import_prefix = determine_prefix (die, cu);
10899
10900   /* Figure out what the scope of the imported die is and prepend it
10901      to the name of the imported die.  */
10902   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10903
10904   if (imported_die->tag != DW_TAG_namespace
10905       && imported_die->tag != DW_TAG_module)
10906     {
10907       imported_declaration = imported_name;
10908       canonical_name = imported_name_prefix;
10909     }
10910   else if (strlen (imported_name_prefix) > 0)
10911     canonical_name = obconcat (&objfile->objfile_obstack,
10912                                imported_name_prefix,
10913                                (cu->language == language_d ? "." : "::"),
10914                                imported_name, (char *) NULL);
10915   else
10916     canonical_name = imported_name;
10917
10918   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
10919     for (child_die = die->child; child_die && child_die->tag;
10920          child_die = sibling_die (child_die))
10921       {
10922         /* DWARF-4: A Fortran use statement with a “rename list” may be
10923            represented by an imported module entry with an import attribute
10924            referring to the module and owned entries corresponding to those
10925            entities that are renamed as part of being imported.  */
10926
10927         if (child_die->tag != DW_TAG_imported_declaration)
10928           {
10929             complaint (_("child DW_TAG_imported_declaration expected "
10930                          "- DIE at %s [in module %s]"),
10931                        sect_offset_str (child_die->sect_off),
10932                        objfile_name (objfile));
10933             continue;
10934           }
10935
10936         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10937         if (import_attr == NULL)
10938           {
10939             complaint (_("Tag '%s' has no DW_AT_import"),
10940                        dwarf_tag_name (child_die->tag));
10941             continue;
10942           }
10943
10944         imported_cu = cu;
10945         imported_die = follow_die_ref_or_sig (child_die, import_attr,
10946                                               &imported_cu);
10947         imported_name = dwarf2_name (imported_die, imported_cu);
10948         if (imported_name == NULL)
10949           {
10950             complaint (_("child DW_TAG_imported_declaration has unknown "
10951                          "imported name - DIE at %s [in module %s]"),
10952                        sect_offset_str (child_die->sect_off),
10953                        objfile_name (objfile));
10954             continue;
10955           }
10956
10957         excludes.push_back (imported_name);
10958
10959         process_die (child_die, cu);
10960       }
10961
10962   add_using_directive (using_directives (cu),
10963                        import_prefix,
10964                        canonical_name,
10965                        import_alias,
10966                        imported_declaration,
10967                        excludes,
10968                        0,
10969                        &objfile->objfile_obstack);
10970 }
10971
10972 /* ICC<14 does not output the required DW_AT_declaration on incomplete
10973    types, but gives them a size of zero.  Starting with version 14,
10974    ICC is compatible with GCC.  */
10975
10976 static bool
10977 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
10978 {
10979   if (!cu->checked_producer)
10980     check_producer (cu);
10981
10982   return cu->producer_is_icc_lt_14;
10983 }
10984
10985 /* ICC generates a DW_AT_type for C void functions.  This was observed on
10986    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
10987    which says that void functions should not have a DW_AT_type.  */
10988
10989 static bool
10990 producer_is_icc (struct dwarf2_cu *cu)
10991 {
10992   if (!cu->checked_producer)
10993     check_producer (cu);
10994
10995   return cu->producer_is_icc;
10996 }
10997
10998 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
10999    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11000    this, it was first present in GCC release 4.3.0.  */
11001
11002 static bool
11003 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11004 {
11005   if (!cu->checked_producer)
11006     check_producer (cu);
11007
11008   return cu->producer_is_gcc_lt_4_3;
11009 }
11010
11011 static file_and_directory
11012 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11013 {
11014   file_and_directory res;
11015
11016   /* Find the filename.  Do not use dwarf2_name here, since the filename
11017      is not a source language identifier.  */
11018   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11019   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11020
11021   if (res.comp_dir == NULL
11022       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11023       && IS_ABSOLUTE_PATH (res.name))
11024     {
11025       res.comp_dir_storage = ldirname (res.name);
11026       if (!res.comp_dir_storage.empty ())
11027         res.comp_dir = res.comp_dir_storage.c_str ();
11028     }
11029   if (res.comp_dir != NULL)
11030     {
11031       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11032          directory, get rid of it.  */
11033       const char *cp = strchr (res.comp_dir, ':');
11034
11035       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11036         res.comp_dir = cp + 1;
11037     }
11038
11039   if (res.name == NULL)
11040     res.name = "<unknown>";
11041
11042   return res;
11043 }
11044
11045 /* Handle DW_AT_stmt_list for a compilation unit.
11046    DIE is the DW_TAG_compile_unit die for CU.
11047    COMP_DIR is the compilation directory.  LOWPC is passed to
11048    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11049
11050 static void
11051 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11052                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11053 {
11054   struct dwarf2_per_objfile *dwarf2_per_objfile
11055     = cu->per_cu->dwarf2_per_objfile;
11056   struct attribute *attr;
11057   struct line_header line_header_local;
11058   hashval_t line_header_local_hash;
11059   void **slot;
11060   int decode_mapping;
11061
11062   gdb_assert (! cu->per_cu->is_debug_types);
11063
11064   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11065   if (attr == NULL)
11066     return;
11067
11068   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11069
11070   /* The line header hash table is only created if needed (it exists to
11071      prevent redundant reading of the line table for partial_units).
11072      If we're given a partial_unit, we'll need it.  If we're given a
11073      compile_unit, then use the line header hash table if it's already
11074      created, but don't create one just yet.  */
11075
11076   if (dwarf2_per_objfile->line_header_hash == NULL
11077       && die->tag == DW_TAG_partial_unit)
11078     {
11079       dwarf2_per_objfile->line_header_hash
11080         .reset (htab_create_alloc (127, line_header_hash_voidp,
11081                                    line_header_eq_voidp,
11082                                    free_line_header_voidp,
11083                                    xcalloc, xfree));
11084     }
11085
11086   line_header_local.sect_off = line_offset;
11087   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11088   line_header_local_hash = line_header_hash (&line_header_local);
11089   if (dwarf2_per_objfile->line_header_hash != NULL)
11090     {
11091       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash.get (),
11092                                        &line_header_local,
11093                                        line_header_local_hash, NO_INSERT);
11094
11095       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11096          is not present in *SLOT (since if there is something in *SLOT then
11097          it will be for a partial_unit).  */
11098       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11099         {
11100           gdb_assert (*slot != NULL);
11101           cu->line_header = (struct line_header *) *slot;
11102           return;
11103         }
11104     }
11105
11106   /* dwarf_decode_line_header does not yet provide sufficient information.
11107      We always have to call also dwarf_decode_lines for it.  */
11108   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11109   if (lh == NULL)
11110     return;
11111
11112   cu->line_header = lh.release ();
11113   cu->line_header_die_owner = die;
11114
11115   if (dwarf2_per_objfile->line_header_hash == NULL)
11116     slot = NULL;
11117   else
11118     {
11119       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash.get (),
11120                                        &line_header_local,
11121                                        line_header_local_hash, INSERT);
11122       gdb_assert (slot != NULL);
11123     }
11124   if (slot != NULL && *slot == NULL)
11125     {
11126       /* This newly decoded line number information unit will be owned
11127          by line_header_hash hash table.  */
11128       *slot = cu->line_header;
11129       cu->line_header_die_owner = NULL;
11130     }
11131   else
11132     {
11133       /* We cannot free any current entry in (*slot) as that struct line_header
11134          may be already used by multiple CUs.  Create only temporary decoded
11135          line_header for this CU - it may happen at most once for each line
11136          number information unit.  And if we're not using line_header_hash
11137          then this is what we want as well.  */
11138       gdb_assert (die->tag != DW_TAG_partial_unit);
11139     }
11140   decode_mapping = (die->tag != DW_TAG_partial_unit);
11141   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11142                       decode_mapping);
11143
11144 }
11145
11146 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11147
11148 static void
11149 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11150 {
11151   struct dwarf2_per_objfile *dwarf2_per_objfile
11152     = cu->per_cu->dwarf2_per_objfile;
11153   struct objfile *objfile = dwarf2_per_objfile->objfile;
11154   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11155   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11156   CORE_ADDR highpc = ((CORE_ADDR) 0);
11157   struct attribute *attr;
11158   struct die_info *child_die;
11159   CORE_ADDR baseaddr;
11160
11161   prepare_one_comp_unit (cu, die, cu->language);
11162   baseaddr = objfile->text_section_offset ();
11163
11164   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11165
11166   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11167      from finish_block.  */
11168   if (lowpc == ((CORE_ADDR) -1))
11169     lowpc = highpc;
11170   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11171
11172   file_and_directory fnd = find_file_and_directory (die, cu);
11173
11174   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11175      standardised yet.  As a workaround for the language detection we fall
11176      back to the DW_AT_producer string.  */
11177   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11178     cu->language = language_opencl;
11179
11180   /* Similar hack for Go.  */
11181   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11182     set_cu_language (DW_LANG_Go, cu);
11183
11184   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
11185
11186   /* Decode line number information if present.  We do this before
11187      processing child DIEs, so that the line header table is available
11188      for DW_AT_decl_file.  */
11189   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11190
11191   /* Process all dies in compilation unit.  */
11192   if (die->child != NULL)
11193     {
11194       child_die = die->child;
11195       while (child_die && child_die->tag)
11196         {
11197           process_die (child_die, cu);
11198           child_die = sibling_die (child_die);
11199         }
11200     }
11201
11202   /* Decode macro information, if present.  Dwarf 2 macro information
11203      refers to information in the line number info statement program
11204      header, so we can only read it if we've read the header
11205      successfully.  */
11206   attr = dwarf2_attr (die, DW_AT_macros, cu);
11207   if (attr == NULL)
11208     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11209   if (attr && cu->line_header)
11210     {
11211       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11212         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11213
11214       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11215     }
11216   else
11217     {
11218       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11219       if (attr && cu->line_header)
11220         {
11221           unsigned int macro_offset = DW_UNSND (attr);
11222
11223           dwarf_decode_macros (cu, macro_offset, 0);
11224         }
11225     }
11226 }
11227
11228 void
11229 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
11230 {
11231   struct type_unit_group *tu_group;
11232   int first_time;
11233   struct attribute *attr;
11234   unsigned int i;
11235   struct signatured_type *sig_type;
11236
11237   gdb_assert (per_cu->is_debug_types);
11238   sig_type = (struct signatured_type *) per_cu;
11239
11240   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
11241
11242   /* If we're using .gdb_index (includes -readnow) then
11243      per_cu->type_unit_group may not have been set up yet.  */
11244   if (sig_type->type_unit_group == NULL)
11245     sig_type->type_unit_group = get_type_unit_group (this, attr);
11246   tu_group = sig_type->type_unit_group;
11247
11248   /* If we've already processed this stmt_list there's no real need to
11249      do it again, we could fake it and just recreate the part we need
11250      (file name,index -> symtab mapping).  If data shows this optimization
11251      is useful we can do it then.  */
11252   first_time = tu_group->compunit_symtab == NULL;
11253
11254   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11255      debug info.  */
11256   line_header_up lh;
11257   if (attr != NULL)
11258     {
11259       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11260       lh = dwarf_decode_line_header (line_offset, this);
11261     }
11262   if (lh == NULL)
11263     {
11264       if (first_time)
11265         start_symtab ("", NULL, 0);
11266       else
11267         {
11268           gdb_assert (tu_group->symtabs == NULL);
11269           gdb_assert (m_builder == nullptr);
11270           struct compunit_symtab *cust = tu_group->compunit_symtab;
11271           m_builder.reset (new struct buildsym_compunit
11272                            (COMPUNIT_OBJFILE (cust), "",
11273                             COMPUNIT_DIRNAME (cust),
11274                             compunit_language (cust),
11275                             0, cust));
11276         }
11277       return;
11278     }
11279
11280   line_header = lh.release ();
11281   line_header_die_owner = die;
11282
11283   if (first_time)
11284     {
11285       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
11286
11287       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11288          still initializing it, and our caller (a few levels up)
11289          process_full_type_unit still needs to know if this is the first
11290          time.  */
11291
11292       tu_group->num_symtabs = line_header->file_names_size ();
11293       tu_group->symtabs = XNEWVEC (struct symtab *,
11294                                    line_header->file_names_size ());
11295
11296       auto &file_names = line_header->file_names ();
11297       for (i = 0; i < file_names.size (); ++i)
11298         {
11299           file_entry &fe = file_names[i];
11300           dwarf2_start_subfile (this, fe.name,
11301                                 fe.include_dir (line_header));
11302           buildsym_compunit *b = get_builder ();
11303           if (b->get_current_subfile ()->symtab == NULL)
11304             {
11305               /* NOTE: start_subfile will recognize when it's been
11306                  passed a file it has already seen.  So we can't
11307                  assume there's a simple mapping from
11308                  cu->line_header->file_names to subfiles, plus
11309                  cu->line_header->file_names may contain dups.  */
11310               b->get_current_subfile ()->symtab
11311                 = allocate_symtab (cust, b->get_current_subfile ()->name);
11312             }
11313
11314           fe.symtab = b->get_current_subfile ()->symtab;
11315           tu_group->symtabs[i] = fe.symtab;
11316         }
11317     }
11318   else
11319     {
11320       gdb_assert (m_builder == nullptr);
11321       struct compunit_symtab *cust = tu_group->compunit_symtab;
11322       m_builder.reset (new struct buildsym_compunit
11323                        (COMPUNIT_OBJFILE (cust), "",
11324                         COMPUNIT_DIRNAME (cust),
11325                         compunit_language (cust),
11326                         0, cust));
11327
11328       auto &file_names = line_header->file_names ();
11329       for (i = 0; i < file_names.size (); ++i)
11330         {
11331           file_entry &fe = file_names[i];
11332           fe.symtab = tu_group->symtabs[i];
11333         }
11334     }
11335
11336   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11337      so they don't have a "real" (so to speak) symtab anyway.
11338      There is later code that will assign the main symtab to all symbols
11339      that don't have one.  We need to handle the case of a symbol with a
11340      missing symtab (DW_AT_decl_file) anyway.  */
11341 }
11342
11343 /* Process DW_TAG_type_unit.
11344    For TUs we want to skip the first top level sibling if it's not the
11345    actual type being defined by this TU.  In this case the first top
11346    level sibling is there to provide context only.  */
11347
11348 static void
11349 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11350 {
11351   struct die_info *child_die;
11352
11353   prepare_one_comp_unit (cu, die, language_minimal);
11354
11355   /* Initialize (or reinitialize) the machinery for building symtabs.
11356      We do this before processing child DIEs, so that the line header table
11357      is available for DW_AT_decl_file.  */
11358   cu->setup_type_unit_groups (die);
11359
11360   if (die->child != NULL)
11361     {
11362       child_die = die->child;
11363       while (child_die && child_die->tag)
11364         {
11365           process_die (child_die, cu);
11366           child_die = sibling_die (child_die);
11367         }
11368     }
11369 }
11370 \f
11371 /* DWO/DWP files.
11372
11373    http://gcc.gnu.org/wiki/DebugFission
11374    http://gcc.gnu.org/wiki/DebugFissionDWP
11375
11376    To simplify handling of both DWO files ("object" files with the DWARF info)
11377    and DWP files (a file with the DWOs packaged up into one file), we treat
11378    DWP files as having a collection of virtual DWO files.  */
11379
11380 static hashval_t
11381 hash_dwo_file (const void *item)
11382 {
11383   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11384   hashval_t hash;
11385
11386   hash = htab_hash_string (dwo_file->dwo_name);
11387   if (dwo_file->comp_dir != NULL)
11388     hash += htab_hash_string (dwo_file->comp_dir);
11389   return hash;
11390 }
11391
11392 static int
11393 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11394 {
11395   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11396   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11397
11398   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11399     return 0;
11400   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11401     return lhs->comp_dir == rhs->comp_dir;
11402   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11403 }
11404
11405 /* Allocate a hash table for DWO files.  */
11406
11407 static htab_up
11408 allocate_dwo_file_hash_table (struct objfile *objfile)
11409 {
11410   auto delete_dwo_file = [] (void *item)
11411     {
11412       struct dwo_file *dwo_file = (struct dwo_file *) item;
11413
11414       delete dwo_file;
11415     };
11416
11417   return htab_up (htab_create_alloc (41,
11418                                      hash_dwo_file,
11419                                      eq_dwo_file,
11420                                      delete_dwo_file,
11421                                      xcalloc, xfree));
11422 }
11423
11424 /* Lookup DWO file DWO_NAME.  */
11425
11426 static void **
11427 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11428                       const char *dwo_name,
11429                       const char *comp_dir)
11430 {
11431   struct dwo_file find_entry;
11432   void **slot;
11433
11434   if (dwarf2_per_objfile->dwo_files == NULL)
11435     dwarf2_per_objfile->dwo_files
11436       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11437
11438   find_entry.dwo_name = dwo_name;
11439   find_entry.comp_dir = comp_dir;
11440   slot = htab_find_slot (dwarf2_per_objfile->dwo_files.get (), &find_entry,
11441                          INSERT);
11442
11443   return slot;
11444 }
11445
11446 static hashval_t
11447 hash_dwo_unit (const void *item)
11448 {
11449   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11450
11451   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11452   return dwo_unit->signature;
11453 }
11454
11455 static int
11456 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11457 {
11458   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11459   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11460
11461   /* The signature is assumed to be unique within the DWO file.
11462      So while object file CU dwo_id's always have the value zero,
11463      that's OK, assuming each object file DWO file has only one CU,
11464      and that's the rule for now.  */
11465   return lhs->signature == rhs->signature;
11466 }
11467
11468 /* Allocate a hash table for DWO CUs,TUs.
11469    There is one of these tables for each of CUs,TUs for each DWO file.  */
11470
11471 static htab_up
11472 allocate_dwo_unit_table (struct objfile *objfile)
11473 {
11474   /* Start out with a pretty small number.
11475      Generally DWO files contain only one CU and maybe some TUs.  */
11476   return htab_up (htab_create_alloc (3,
11477                                      hash_dwo_unit,
11478                                      eq_dwo_unit,
11479                                      NULL, xcalloc, xfree));
11480 }
11481
11482 /* die_reader_func for create_dwo_cu.  */
11483
11484 static void
11485 create_dwo_cu_reader (const struct die_reader_specs *reader,
11486                       const gdb_byte *info_ptr,
11487                       struct die_info *comp_unit_die,
11488                       struct dwo_file *dwo_file,
11489                       struct dwo_unit *dwo_unit)
11490 {
11491   struct dwarf2_cu *cu = reader->cu;
11492   sect_offset sect_off = cu->per_cu->sect_off;
11493   struct dwarf2_section_info *section = cu->per_cu->section;
11494
11495   gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
11496   if (!signature.has_value ())
11497     {
11498       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11499                    " its dwo_id [in module %s]"),
11500                  sect_offset_str (sect_off), dwo_file->dwo_name);
11501       return;
11502     }
11503
11504   dwo_unit->dwo_file = dwo_file;
11505   dwo_unit->signature = *signature;
11506   dwo_unit->section = section;
11507   dwo_unit->sect_off = sect_off;
11508   dwo_unit->length = cu->per_cu->length;
11509
11510   if (dwarf_read_debug)
11511     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11512                         sect_offset_str (sect_off),
11513                         hex_string (dwo_unit->signature));
11514 }
11515
11516 /* Create the dwo_units for the CUs in a DWO_FILE.
11517    Note: This function processes DWO files only, not DWP files.  */
11518
11519 static void
11520 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11521                        dwarf2_cu *cu, struct dwo_file &dwo_file,
11522                        dwarf2_section_info &section, htab_up &cus_htab)
11523 {
11524   struct objfile *objfile = dwarf2_per_objfile->objfile;
11525   const gdb_byte *info_ptr, *end_ptr;
11526
11527   section.read (objfile);
11528   info_ptr = section.buffer;
11529
11530   if (info_ptr == NULL)
11531     return;
11532
11533   if (dwarf_read_debug)
11534     {
11535       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11536                           section.get_name (),
11537                           section.get_file_name ());
11538     }
11539
11540   end_ptr = info_ptr + section.size;
11541   while (info_ptr < end_ptr)
11542     {
11543       struct dwarf2_per_cu_data per_cu;
11544       struct dwo_unit read_unit {};
11545       struct dwo_unit *dwo_unit;
11546       void **slot;
11547       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11548
11549       memset (&per_cu, 0, sizeof (per_cu));
11550       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11551       per_cu.is_debug_types = 0;
11552       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11553       per_cu.section = &section;
11554
11555       cutu_reader reader (&per_cu, cu, &dwo_file);
11556       if (!reader.dummy_p)
11557         create_dwo_cu_reader (&reader, reader.info_ptr, reader.comp_unit_die,
11558                               &dwo_file, &read_unit);
11559       info_ptr += per_cu.length;
11560
11561       // If the unit could not be parsed, skip it.
11562       if (read_unit.dwo_file == NULL)
11563         continue;
11564
11565       if (cus_htab == NULL)
11566         cus_htab = allocate_dwo_unit_table (objfile);
11567
11568       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11569       *dwo_unit = read_unit;
11570       slot = htab_find_slot (cus_htab.get (), dwo_unit, INSERT);
11571       gdb_assert (slot != NULL);
11572       if (*slot != NULL)
11573         {
11574           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11575           sect_offset dup_sect_off = dup_cu->sect_off;
11576
11577           complaint (_("debug cu entry at offset %s is duplicate to"
11578                        " the entry at offset %s, signature %s"),
11579                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11580                      hex_string (dwo_unit->signature));
11581         }
11582       *slot = (void *)dwo_unit;
11583     }
11584 }
11585
11586 /* DWP file .debug_{cu,tu}_index section format:
11587    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11588
11589    DWP Version 1:
11590
11591    Both index sections have the same format, and serve to map a 64-bit
11592    signature to a set of section numbers.  Each section begins with a header,
11593    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11594    indexes, and a pool of 32-bit section numbers.  The index sections will be
11595    aligned at 8-byte boundaries in the file.
11596
11597    The index section header consists of:
11598
11599     V, 32 bit version number
11600     -, 32 bits unused
11601     N, 32 bit number of compilation units or type units in the index
11602     M, 32 bit number of slots in the hash table
11603
11604    Numbers are recorded using the byte order of the application binary.
11605
11606    The hash table begins at offset 16 in the section, and consists of an array
11607    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11608    order of the application binary).  Unused slots in the hash table are 0.
11609    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11610
11611    The parallel table begins immediately after the hash table
11612    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11613    array of 32-bit indexes (using the byte order of the application binary),
11614    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11615    table contains a 32-bit index into the pool of section numbers.  For unused
11616    hash table slots, the corresponding entry in the parallel table will be 0.
11617
11618    The pool of section numbers begins immediately following the hash table
11619    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11620    section numbers consists of an array of 32-bit words (using the byte order
11621    of the application binary).  Each item in the array is indexed starting
11622    from 0.  The hash table entry provides the index of the first section
11623    number in the set.  Additional section numbers in the set follow, and the
11624    set is terminated by a 0 entry (section number 0 is not used in ELF).
11625
11626    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11627    section must be the first entry in the set, and the .debug_abbrev.dwo must
11628    be the second entry. Other members of the set may follow in any order.
11629
11630    ---
11631
11632    DWP Version 2:
11633
11634    DWP Version 2 combines all the .debug_info, etc. sections into one,
11635    and the entries in the index tables are now offsets into these sections.
11636    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11637    section.
11638
11639    Index Section Contents:
11640     Header
11641     Hash Table of Signatures   dwp_hash_table.hash_table
11642     Parallel Table of Indices  dwp_hash_table.unit_table
11643     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11644     Table of Section Sizes     dwp_hash_table.v2.sizes
11645
11646    The index section header consists of:
11647
11648     V, 32 bit version number
11649     L, 32 bit number of columns in the table of section offsets
11650     N, 32 bit number of compilation units or type units in the index
11651     M, 32 bit number of slots in the hash table
11652
11653    Numbers are recorded using the byte order of the application binary.
11654
11655    The hash table has the same format as version 1.
11656    The parallel table of indices has the same format as version 1,
11657    except that the entries are origin-1 indices into the table of sections
11658    offsets and the table of section sizes.
11659
11660    The table of offsets begins immediately following the parallel table
11661    (at offset 16 + 12 * M from the beginning of the section).  The table is
11662    a two-dimensional array of 32-bit words (using the byte order of the
11663    application binary), with L columns and N+1 rows, in row-major order.
11664    Each row in the array is indexed starting from 0.  The first row provides
11665    a key to the remaining rows: each column in this row provides an identifier
11666    for a debug section, and the offsets in the same column of subsequent rows
11667    refer to that section.  The section identifiers are:
11668
11669     DW_SECT_INFO         1  .debug_info.dwo
11670     DW_SECT_TYPES        2  .debug_types.dwo
11671     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11672     DW_SECT_LINE         4  .debug_line.dwo
11673     DW_SECT_LOC          5  .debug_loc.dwo
11674     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11675     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11676     DW_SECT_MACRO        8  .debug_macro.dwo
11677
11678    The offsets provided by the CU and TU index sections are the base offsets
11679    for the contributions made by each CU or TU to the corresponding section
11680    in the package file.  Each CU and TU header contains an abbrev_offset
11681    field, used to find the abbreviations table for that CU or TU within the
11682    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11683    be interpreted as relative to the base offset given in the index section.
11684    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11685    should be interpreted as relative to the base offset for .debug_line.dwo,
11686    and offsets into other debug sections obtained from DWARF attributes should
11687    also be interpreted as relative to the corresponding base offset.
11688
11689    The table of sizes begins immediately following the table of offsets.
11690    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11691    with L columns and N rows, in row-major order.  Each row in the array is
11692    indexed starting from 1 (row 0 is shared by the two tables).
11693
11694    ---
11695
11696    Hash table lookup is handled the same in version 1 and 2:
11697
11698    We assume that N and M will not exceed 2^32 - 1.
11699    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11700
11701    Given a 64-bit compilation unit signature or a type signature S, an entry
11702    in the hash table is located as follows:
11703
11704    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11705       the low-order k bits all set to 1.
11706
11707    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11708
11709    3) If the hash table entry at index H matches the signature, use that
11710       entry.  If the hash table entry at index H is unused (all zeroes),
11711       terminate the search: the signature is not present in the table.
11712
11713    4) Let H = (H + H') modulo M. Repeat at Step 3.
11714
11715    Because M > N and H' and M are relatively prime, the search is guaranteed
11716    to stop at an unused slot or find the match.  */
11717
11718 /* Create a hash table to map DWO IDs to their CU/TU entry in
11719    .debug_{info,types}.dwo in DWP_FILE.
11720    Returns NULL if there isn't one.
11721    Note: This function processes DWP files only, not DWO files.  */
11722
11723 static struct dwp_hash_table *
11724 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11725                        struct dwp_file *dwp_file, int is_debug_types)
11726 {
11727   struct objfile *objfile = dwarf2_per_objfile->objfile;
11728   bfd *dbfd = dwp_file->dbfd.get ();
11729   const gdb_byte *index_ptr, *index_end;
11730   struct dwarf2_section_info *index;
11731   uint32_t version, nr_columns, nr_units, nr_slots;
11732   struct dwp_hash_table *htab;
11733
11734   if (is_debug_types)
11735     index = &dwp_file->sections.tu_index;
11736   else
11737     index = &dwp_file->sections.cu_index;
11738
11739   if (index->empty ())
11740     return NULL;
11741   index->read (objfile);
11742
11743   index_ptr = index->buffer;
11744   index_end = index_ptr + index->size;
11745
11746   version = read_4_bytes (dbfd, index_ptr);
11747   index_ptr += 4;
11748   if (version == 2)
11749     nr_columns = read_4_bytes (dbfd, index_ptr);
11750   else
11751     nr_columns = 0;
11752   index_ptr += 4;
11753   nr_units = read_4_bytes (dbfd, index_ptr);
11754   index_ptr += 4;
11755   nr_slots = read_4_bytes (dbfd, index_ptr);
11756   index_ptr += 4;
11757
11758   if (version != 1 && version != 2)
11759     {
11760       error (_("Dwarf Error: unsupported DWP file version (%s)"
11761                " [in module %s]"),
11762              pulongest (version), dwp_file->name);
11763     }
11764   if (nr_slots != (nr_slots & -nr_slots))
11765     {
11766       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
11767                " is not power of 2 [in module %s]"),
11768              pulongest (nr_slots), dwp_file->name);
11769     }
11770
11771   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
11772   htab->version = version;
11773   htab->nr_columns = nr_columns;
11774   htab->nr_units = nr_units;
11775   htab->nr_slots = nr_slots;
11776   htab->hash_table = index_ptr;
11777   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
11778
11779   /* Exit early if the table is empty.  */
11780   if (nr_slots == 0 || nr_units == 0
11781       || (version == 2 && nr_columns == 0))
11782     {
11783       /* All must be zero.  */
11784       if (nr_slots != 0 || nr_units != 0
11785           || (version == 2 && nr_columns != 0))
11786         {
11787           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
11788                        " all zero [in modules %s]"),
11789                      dwp_file->name);
11790         }
11791       return htab;
11792     }
11793
11794   if (version == 1)
11795     {
11796       htab->section_pool.v1.indices =
11797         htab->unit_table + sizeof (uint32_t) * nr_slots;
11798       /* It's harder to decide whether the section is too small in v1.
11799          V1 is deprecated anyway so we punt.  */
11800     }
11801   else
11802     {
11803       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11804       int *ids = htab->section_pool.v2.section_ids;
11805       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
11806       /* Reverse map for error checking.  */
11807       int ids_seen[DW_SECT_MAX + 1];
11808       int i;
11809
11810       if (nr_columns < 2)
11811         {
11812           error (_("Dwarf Error: bad DWP hash table, too few columns"
11813                    " in section table [in module %s]"),
11814                  dwp_file->name);
11815         }
11816       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11817         {
11818           error (_("Dwarf Error: bad DWP hash table, too many columns"
11819                    " in section table [in module %s]"),
11820                  dwp_file->name);
11821         }
11822       memset (ids, 255, sizeof_ids);
11823       memset (ids_seen, 255, sizeof (ids_seen));
11824       for (i = 0; i < nr_columns; ++i)
11825         {
11826           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11827
11828           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11829             {
11830               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11831                        " in section table [in module %s]"),
11832                      id, dwp_file->name);
11833             }
11834           if (ids_seen[id] != -1)
11835             {
11836               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11837                        " id %d in section table [in module %s]"),
11838                      id, dwp_file->name);
11839             }
11840           ids_seen[id] = i;
11841           ids[i] = id;
11842         }
11843       /* Must have exactly one info or types section.  */
11844       if (((ids_seen[DW_SECT_INFO] != -1)
11845            + (ids_seen[DW_SECT_TYPES] != -1))
11846           != 1)
11847         {
11848           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11849                    " DWO info/types section [in module %s]"),
11850                  dwp_file->name);
11851         }
11852       /* Must have an abbrev section.  */
11853       if (ids_seen[DW_SECT_ABBREV] == -1)
11854         {
11855           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11856                    " section [in module %s]"),
11857                  dwp_file->name);
11858         }
11859       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11860       htab->section_pool.v2.sizes =
11861         htab->section_pool.v2.offsets + (sizeof (uint32_t)
11862                                          * nr_units * nr_columns);
11863       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11864                                           * nr_units * nr_columns))
11865           > index_end)
11866         {
11867           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11868                    " [in module %s]"),
11869                  dwp_file->name);
11870         }
11871     }
11872
11873   return htab;
11874 }
11875
11876 /* Update SECTIONS with the data from SECTP.
11877
11878    This function is like the other "locate" section routines that are
11879    passed to bfd_map_over_sections, but in this context the sections to
11880    read comes from the DWP V1 hash table, not the full ELF section table.
11881
11882    The result is non-zero for success, or zero if an error was found.  */
11883
11884 static int
11885 locate_v1_virtual_dwo_sections (asection *sectp,
11886                                 struct virtual_v1_dwo_sections *sections)
11887 {
11888   const struct dwop_section_names *names = &dwop_section_names;
11889
11890   if (section_is_p (sectp->name, &names->abbrev_dwo))
11891     {
11892       /* There can be only one.  */
11893       if (sections->abbrev.s.section != NULL)
11894         return 0;
11895       sections->abbrev.s.section = sectp;
11896       sections->abbrev.size = bfd_section_size (sectp);
11897     }
11898   else if (section_is_p (sectp->name, &names->info_dwo)
11899            || section_is_p (sectp->name, &names->types_dwo))
11900     {
11901       /* There can be only one.  */
11902       if (sections->info_or_types.s.section != NULL)
11903         return 0;
11904       sections->info_or_types.s.section = sectp;
11905       sections->info_or_types.size = bfd_section_size (sectp);
11906     }
11907   else if (section_is_p (sectp->name, &names->line_dwo))
11908     {
11909       /* There can be only one.  */
11910       if (sections->line.s.section != NULL)
11911         return 0;
11912       sections->line.s.section = sectp;
11913       sections->line.size = bfd_section_size (sectp);
11914     }
11915   else if (section_is_p (sectp->name, &names->loc_dwo))
11916     {
11917       /* There can be only one.  */
11918       if (sections->loc.s.section != NULL)
11919         return 0;
11920       sections->loc.s.section = sectp;
11921       sections->loc.size = bfd_section_size (sectp);
11922     }
11923   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11924     {
11925       /* There can be only one.  */
11926       if (sections->macinfo.s.section != NULL)
11927         return 0;
11928       sections->macinfo.s.section = sectp;
11929       sections->macinfo.size = bfd_section_size (sectp);
11930     }
11931   else if (section_is_p (sectp->name, &names->macro_dwo))
11932     {
11933       /* There can be only one.  */
11934       if (sections->macro.s.section != NULL)
11935         return 0;
11936       sections->macro.s.section = sectp;
11937       sections->macro.size = bfd_section_size (sectp);
11938     }
11939   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11940     {
11941       /* There can be only one.  */
11942       if (sections->str_offsets.s.section != NULL)
11943         return 0;
11944       sections->str_offsets.s.section = sectp;
11945       sections->str_offsets.size = bfd_section_size (sectp);
11946     }
11947   else
11948     {
11949       /* No other kind of section is valid.  */
11950       return 0;
11951     }
11952
11953   return 1;
11954 }
11955
11956 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11957    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11958    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11959    This is for DWP version 1 files.  */
11960
11961 static struct dwo_unit *
11962 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
11963                            struct dwp_file *dwp_file,
11964                            uint32_t unit_index,
11965                            const char *comp_dir,
11966                            ULONGEST signature, int is_debug_types)
11967 {
11968   struct objfile *objfile = dwarf2_per_objfile->objfile;
11969   const struct dwp_hash_table *dwp_htab =
11970     is_debug_types ? dwp_file->tus : dwp_file->cus;
11971   bfd *dbfd = dwp_file->dbfd.get ();
11972   const char *kind = is_debug_types ? "TU" : "CU";
11973   struct dwo_file *dwo_file;
11974   struct dwo_unit *dwo_unit;
11975   struct virtual_v1_dwo_sections sections;
11976   void **dwo_file_slot;
11977   int i;
11978
11979   gdb_assert (dwp_file->version == 1);
11980
11981   if (dwarf_read_debug)
11982     {
11983       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
11984                           kind,
11985                           pulongest (unit_index), hex_string (signature),
11986                           dwp_file->name);
11987     }
11988
11989   /* Fetch the sections of this DWO unit.
11990      Put a limit on the number of sections we look for so that bad data
11991      doesn't cause us to loop forever.  */
11992
11993 #define MAX_NR_V1_DWO_SECTIONS \
11994   (1 /* .debug_info or .debug_types */ \
11995    + 1 /* .debug_abbrev */ \
11996    + 1 /* .debug_line */ \
11997    + 1 /* .debug_loc */ \
11998    + 1 /* .debug_str_offsets */ \
11999    + 1 /* .debug_macro or .debug_macinfo */ \
12000    + 1 /* trailing zero */)
12001
12002   memset (&sections, 0, sizeof (sections));
12003
12004   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12005     {
12006       asection *sectp;
12007       uint32_t section_nr =
12008         read_4_bytes (dbfd,
12009                       dwp_htab->section_pool.v1.indices
12010                       + (unit_index + i) * sizeof (uint32_t));
12011
12012       if (section_nr == 0)
12013         break;
12014       if (section_nr >= dwp_file->num_sections)
12015         {
12016           error (_("Dwarf Error: bad DWP hash table, section number too large"
12017                    " [in module %s]"),
12018                  dwp_file->name);
12019         }
12020
12021       sectp = dwp_file->elf_sections[section_nr];
12022       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12023         {
12024           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12025                    " [in module %s]"),
12026                  dwp_file->name);
12027         }
12028     }
12029
12030   if (i < 2
12031       || sections.info_or_types.empty ()
12032       || sections.abbrev.empty ())
12033     {
12034       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12035                " [in module %s]"),
12036              dwp_file->name);
12037     }
12038   if (i == MAX_NR_V1_DWO_SECTIONS)
12039     {
12040       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12041                " [in module %s]"),
12042              dwp_file->name);
12043     }
12044
12045   /* It's easier for the rest of the code if we fake a struct dwo_file and
12046      have dwo_unit "live" in that.  At least for now.
12047
12048      The DWP file can be made up of a random collection of CUs and TUs.
12049      However, for each CU + set of TUs that came from the same original DWO
12050      file, we can combine them back into a virtual DWO file to save space
12051      (fewer struct dwo_file objects to allocate).  Remember that for really
12052      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12053
12054   std::string virtual_dwo_name =
12055     string_printf ("virtual-dwo/%d-%d-%d-%d",
12056                    sections.abbrev.get_id (),
12057                    sections.line.get_id (),
12058                    sections.loc.get_id (),
12059                    sections.str_offsets.get_id ());
12060   /* Can we use an existing virtual DWO file?  */
12061   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12062                                         virtual_dwo_name.c_str (),
12063                                         comp_dir);
12064   /* Create one if necessary.  */
12065   if (*dwo_file_slot == NULL)
12066     {
12067       if (dwarf_read_debug)
12068         {
12069           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12070                               virtual_dwo_name.c_str ());
12071         }
12072       dwo_file = new struct dwo_file;
12073       dwo_file->dwo_name = obstack_strdup (&objfile->objfile_obstack,
12074                                            virtual_dwo_name);
12075       dwo_file->comp_dir = comp_dir;
12076       dwo_file->sections.abbrev = sections.abbrev;
12077       dwo_file->sections.line = sections.line;
12078       dwo_file->sections.loc = sections.loc;
12079       dwo_file->sections.macinfo = sections.macinfo;
12080       dwo_file->sections.macro = sections.macro;
12081       dwo_file->sections.str_offsets = sections.str_offsets;
12082       /* The "str" section is global to the entire DWP file.  */
12083       dwo_file->sections.str = dwp_file->sections.str;
12084       /* The info or types section is assigned below to dwo_unit,
12085          there's no need to record it in dwo_file.
12086          Also, we can't simply record type sections in dwo_file because
12087          we record a pointer into the vector in dwo_unit.  As we collect more
12088          types we'll grow the vector and eventually have to reallocate space
12089          for it, invalidating all copies of pointers into the previous
12090          contents.  */
12091       *dwo_file_slot = dwo_file;
12092     }
12093   else
12094     {
12095       if (dwarf_read_debug)
12096         {
12097           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12098                               virtual_dwo_name.c_str ());
12099         }
12100       dwo_file = (struct dwo_file *) *dwo_file_slot;
12101     }
12102
12103   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12104   dwo_unit->dwo_file = dwo_file;
12105   dwo_unit->signature = signature;
12106   dwo_unit->section =
12107     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12108   *dwo_unit->section = sections.info_or_types;
12109   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12110
12111   return dwo_unit;
12112 }
12113
12114 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12115    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12116    piece within that section used by a TU/CU, return a virtual section
12117    of just that piece.  */
12118
12119 static struct dwarf2_section_info
12120 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12121                        struct dwarf2_section_info *section,
12122                        bfd_size_type offset, bfd_size_type size)
12123 {
12124   struct dwarf2_section_info result;
12125   asection *sectp;
12126
12127   gdb_assert (section != NULL);
12128   gdb_assert (!section->is_virtual);
12129
12130   memset (&result, 0, sizeof (result));
12131   result.s.containing_section = section;
12132   result.is_virtual = true;
12133
12134   if (size == 0)
12135     return result;
12136
12137   sectp = section->get_bfd_section ();
12138
12139   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12140      bounds of the real section.  This is a pretty-rare event, so just
12141      flag an error (easier) instead of a warning and trying to cope.  */
12142   if (sectp == NULL
12143       || offset + size > bfd_section_size (sectp))
12144     {
12145       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12146                " in section %s [in module %s]"),
12147              sectp ? bfd_section_name (sectp) : "<unknown>",
12148              objfile_name (dwarf2_per_objfile->objfile));
12149     }
12150
12151   result.virtual_offset = offset;
12152   result.size = size;
12153   return result;
12154 }
12155
12156 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12157    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12158    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12159    This is for DWP version 2 files.  */
12160
12161 static struct dwo_unit *
12162 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12163                            struct dwp_file *dwp_file,
12164                            uint32_t unit_index,
12165                            const char *comp_dir,
12166                            ULONGEST signature, int is_debug_types)
12167 {
12168   struct objfile *objfile = dwarf2_per_objfile->objfile;
12169   const struct dwp_hash_table *dwp_htab =
12170     is_debug_types ? dwp_file->tus : dwp_file->cus;
12171   bfd *dbfd = dwp_file->dbfd.get ();
12172   const char *kind = is_debug_types ? "TU" : "CU";
12173   struct dwo_file *dwo_file;
12174   struct dwo_unit *dwo_unit;
12175   struct virtual_v2_dwo_sections sections;
12176   void **dwo_file_slot;
12177   int i;
12178
12179   gdb_assert (dwp_file->version == 2);
12180
12181   if (dwarf_read_debug)
12182     {
12183       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12184                           kind,
12185                           pulongest (unit_index), hex_string (signature),
12186                           dwp_file->name);
12187     }
12188
12189   /* Fetch the section offsets of this DWO unit.  */
12190
12191   memset (&sections, 0, sizeof (sections));
12192
12193   for (i = 0; i < dwp_htab->nr_columns; ++i)
12194     {
12195       uint32_t offset = read_4_bytes (dbfd,
12196                                       dwp_htab->section_pool.v2.offsets
12197                                       + (((unit_index - 1) * dwp_htab->nr_columns
12198                                           + i)
12199                                          * sizeof (uint32_t)));
12200       uint32_t size = read_4_bytes (dbfd,
12201                                     dwp_htab->section_pool.v2.sizes
12202                                     + (((unit_index - 1) * dwp_htab->nr_columns
12203                                         + i)
12204                                        * sizeof (uint32_t)));
12205
12206       switch (dwp_htab->section_pool.v2.section_ids[i])
12207         {
12208         case DW_SECT_INFO:
12209         case DW_SECT_TYPES:
12210           sections.info_or_types_offset = offset;
12211           sections.info_or_types_size = size;
12212           break;
12213         case DW_SECT_ABBREV:
12214           sections.abbrev_offset = offset;
12215           sections.abbrev_size = size;
12216           break;
12217         case DW_SECT_LINE:
12218           sections.line_offset = offset;
12219           sections.line_size = size;
12220           break;
12221         case DW_SECT_LOC:
12222           sections.loc_offset = offset;
12223           sections.loc_size = size;
12224           break;
12225         case DW_SECT_STR_OFFSETS:
12226           sections.str_offsets_offset = offset;
12227           sections.str_offsets_size = size;
12228           break;
12229         case DW_SECT_MACINFO:
12230           sections.macinfo_offset = offset;
12231           sections.macinfo_size = size;
12232           break;
12233         case DW_SECT_MACRO:
12234           sections.macro_offset = offset;
12235           sections.macro_size = size;
12236           break;
12237         }
12238     }
12239
12240   /* It's easier for the rest of the code if we fake a struct dwo_file and
12241      have dwo_unit "live" in that.  At least for now.
12242
12243      The DWP file can be made up of a random collection of CUs and TUs.
12244      However, for each CU + set of TUs that came from the same original DWO
12245      file, we can combine them back into a virtual DWO file to save space
12246      (fewer struct dwo_file objects to allocate).  Remember that for really
12247      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12248
12249   std::string virtual_dwo_name =
12250     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12251                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12252                    (long) (sections.line_size ? sections.line_offset : 0),
12253                    (long) (sections.loc_size ? sections.loc_offset : 0),
12254                    (long) (sections.str_offsets_size
12255                            ? sections.str_offsets_offset : 0));
12256   /* Can we use an existing virtual DWO file?  */
12257   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12258                                         virtual_dwo_name.c_str (),
12259                                         comp_dir);
12260   /* Create one if necessary.  */
12261   if (*dwo_file_slot == NULL)
12262     {
12263       if (dwarf_read_debug)
12264         {
12265           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12266                               virtual_dwo_name.c_str ());
12267         }
12268       dwo_file = new struct dwo_file;
12269       dwo_file->dwo_name = obstack_strdup (&objfile->objfile_obstack,
12270                                            virtual_dwo_name);
12271       dwo_file->comp_dir = comp_dir;
12272       dwo_file->sections.abbrev =
12273         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12274                                sections.abbrev_offset, sections.abbrev_size);
12275       dwo_file->sections.line =
12276         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12277                                sections.line_offset, sections.line_size);
12278       dwo_file->sections.loc =
12279         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12280                                sections.loc_offset, sections.loc_size);
12281       dwo_file->sections.macinfo =
12282         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12283                                sections.macinfo_offset, sections.macinfo_size);
12284       dwo_file->sections.macro =
12285         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12286                                sections.macro_offset, sections.macro_size);
12287       dwo_file->sections.str_offsets =
12288         create_dwp_v2_section (dwarf2_per_objfile,
12289                                &dwp_file->sections.str_offsets,
12290                                sections.str_offsets_offset,
12291                                sections.str_offsets_size);
12292       /* The "str" section is global to the entire DWP file.  */
12293       dwo_file->sections.str = dwp_file->sections.str;
12294       /* The info or types section is assigned below to dwo_unit,
12295          there's no need to record it in dwo_file.
12296          Also, we can't simply record type sections in dwo_file because
12297          we record a pointer into the vector in dwo_unit.  As we collect more
12298          types we'll grow the vector and eventually have to reallocate space
12299          for it, invalidating all copies of pointers into the previous
12300          contents.  */
12301       *dwo_file_slot = dwo_file;
12302     }
12303   else
12304     {
12305       if (dwarf_read_debug)
12306         {
12307           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12308                               virtual_dwo_name.c_str ());
12309         }
12310       dwo_file = (struct dwo_file *) *dwo_file_slot;
12311     }
12312
12313   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12314   dwo_unit->dwo_file = dwo_file;
12315   dwo_unit->signature = signature;
12316   dwo_unit->section =
12317     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12318   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12319                                               is_debug_types
12320                                               ? &dwp_file->sections.types
12321                                               : &dwp_file->sections.info,
12322                                               sections.info_or_types_offset,
12323                                               sections.info_or_types_size);
12324   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12325
12326   return dwo_unit;
12327 }
12328
12329 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12330    Returns NULL if the signature isn't found.  */
12331
12332 static struct dwo_unit *
12333 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12334                         struct dwp_file *dwp_file, const char *comp_dir,
12335                         ULONGEST signature, int is_debug_types)
12336 {
12337   const struct dwp_hash_table *dwp_htab =
12338     is_debug_types ? dwp_file->tus : dwp_file->cus;
12339   bfd *dbfd = dwp_file->dbfd.get ();
12340   uint32_t mask = dwp_htab->nr_slots - 1;
12341   uint32_t hash = signature & mask;
12342   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12343   unsigned int i;
12344   void **slot;
12345   struct dwo_unit find_dwo_cu;
12346
12347   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12348   find_dwo_cu.signature = signature;
12349   slot = htab_find_slot (is_debug_types
12350                          ? dwp_file->loaded_tus.get ()
12351                          : dwp_file->loaded_cus.get (),
12352                          &find_dwo_cu, INSERT);
12353
12354   if (*slot != NULL)
12355     return (struct dwo_unit *) *slot;
12356
12357   /* Use a for loop so that we don't loop forever on bad debug info.  */
12358   for (i = 0; i < dwp_htab->nr_slots; ++i)
12359     {
12360       ULONGEST signature_in_table;
12361
12362       signature_in_table =
12363         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12364       if (signature_in_table == signature)
12365         {
12366           uint32_t unit_index =
12367             read_4_bytes (dbfd,
12368                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12369
12370           if (dwp_file->version == 1)
12371             {
12372               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12373                                                  dwp_file, unit_index,
12374                                                  comp_dir, signature,
12375                                                  is_debug_types);
12376             }
12377           else
12378             {
12379               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12380                                                  dwp_file, unit_index,
12381                                                  comp_dir, signature,
12382                                                  is_debug_types);
12383             }
12384           return (struct dwo_unit *) *slot;
12385         }
12386       if (signature_in_table == 0)
12387         return NULL;
12388       hash = (hash + hash2) & mask;
12389     }
12390
12391   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12392            " [in module %s]"),
12393          dwp_file->name);
12394 }
12395
12396 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12397    Open the file specified by FILE_NAME and hand it off to BFD for
12398    preliminary analysis.  Return a newly initialized bfd *, which
12399    includes a canonicalized copy of FILE_NAME.
12400    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12401    SEARCH_CWD is true if the current directory is to be searched.
12402    It will be searched before debug-file-directory.
12403    If successful, the file is added to the bfd include table of the
12404    objfile's bfd (see gdb_bfd_record_inclusion).
12405    If unable to find/open the file, return NULL.
12406    NOTE: This function is derived from symfile_bfd_open.  */
12407
12408 static gdb_bfd_ref_ptr
12409 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12410                     const char *file_name, int is_dwp, int search_cwd)
12411 {
12412   int desc;
12413   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12414      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12415      to debug_file_directory.  */
12416   const char *search_path;
12417   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12418
12419   gdb::unique_xmalloc_ptr<char> search_path_holder;
12420   if (search_cwd)
12421     {
12422       if (*debug_file_directory != '\0')
12423         {
12424           search_path_holder.reset (concat (".", dirname_separator_string,
12425                                             debug_file_directory,
12426                                             (char *) NULL));
12427           search_path = search_path_holder.get ();
12428         }
12429       else
12430         search_path = ".";
12431     }
12432   else
12433     search_path = debug_file_directory;
12434
12435   openp_flags flags = OPF_RETURN_REALPATH;
12436   if (is_dwp)
12437     flags |= OPF_SEARCH_IN_PATH;
12438
12439   gdb::unique_xmalloc_ptr<char> absolute_name;
12440   desc = openp (search_path, flags, file_name,
12441                 O_RDONLY | O_BINARY, &absolute_name);
12442   if (desc < 0)
12443     return NULL;
12444
12445   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12446                                          gnutarget, desc));
12447   if (sym_bfd == NULL)
12448     return NULL;
12449   bfd_set_cacheable (sym_bfd.get (), 1);
12450
12451   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12452     return NULL;
12453
12454   /* Success.  Record the bfd as having been included by the objfile's bfd.
12455      This is important because things like demangled_names_hash lives in the
12456      objfile's per_bfd space and may have references to things like symbol
12457      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12458   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12459
12460   return sym_bfd;
12461 }
12462
12463 /* Try to open DWO file FILE_NAME.
12464    COMP_DIR is the DW_AT_comp_dir attribute.
12465    The result is the bfd handle of the file.
12466    If there is a problem finding or opening the file, return NULL.
12467    Upon success, the canonicalized path of the file is stored in the bfd,
12468    same as symfile_bfd_open.  */
12469
12470 static gdb_bfd_ref_ptr
12471 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12472                const char *file_name, const char *comp_dir)
12473 {
12474   if (IS_ABSOLUTE_PATH (file_name))
12475     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12476                                0 /*is_dwp*/, 0 /*search_cwd*/);
12477
12478   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12479
12480   if (comp_dir != NULL)
12481     {
12482       gdb::unique_xmalloc_ptr<char> path_to_try
12483         (concat (comp_dir, SLASH_STRING, file_name, (char *) NULL));
12484
12485       /* NOTE: If comp_dir is a relative path, this will also try the
12486          search path, which seems useful.  */
12487       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12488                                                 path_to_try.get (),
12489                                                 0 /*is_dwp*/,
12490                                                 1 /*search_cwd*/));
12491       if (abfd != NULL)
12492         return abfd;
12493     }
12494
12495   /* That didn't work, try debug-file-directory, which, despite its name,
12496      is a list of paths.  */
12497
12498   if (*debug_file_directory == '\0')
12499     return NULL;
12500
12501   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12502                              0 /*is_dwp*/, 1 /*search_cwd*/);
12503 }
12504
12505 /* This function is mapped across the sections and remembers the offset and
12506    size of each of the DWO debugging sections we are interested in.  */
12507
12508 static void
12509 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12510 {
12511   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12512   const struct dwop_section_names *names = &dwop_section_names;
12513
12514   if (section_is_p (sectp->name, &names->abbrev_dwo))
12515     {
12516       dwo_sections->abbrev.s.section = sectp;
12517       dwo_sections->abbrev.size = bfd_section_size (sectp);
12518     }
12519   else if (section_is_p (sectp->name, &names->info_dwo))
12520     {
12521       dwo_sections->info.s.section = sectp;
12522       dwo_sections->info.size = bfd_section_size (sectp);
12523     }
12524   else if (section_is_p (sectp->name, &names->line_dwo))
12525     {
12526       dwo_sections->line.s.section = sectp;
12527       dwo_sections->line.size = bfd_section_size (sectp);
12528     }
12529   else if (section_is_p (sectp->name, &names->loc_dwo))
12530     {
12531       dwo_sections->loc.s.section = sectp;
12532       dwo_sections->loc.size = bfd_section_size (sectp);
12533     }
12534   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12535     {
12536       dwo_sections->macinfo.s.section = sectp;
12537       dwo_sections->macinfo.size = bfd_section_size (sectp);
12538     }
12539   else if (section_is_p (sectp->name, &names->macro_dwo))
12540     {
12541       dwo_sections->macro.s.section = sectp;
12542       dwo_sections->macro.size = bfd_section_size (sectp);
12543     }
12544   else if (section_is_p (sectp->name, &names->str_dwo))
12545     {
12546       dwo_sections->str.s.section = sectp;
12547       dwo_sections->str.size = bfd_section_size (sectp);
12548     }
12549   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12550     {
12551       dwo_sections->str_offsets.s.section = sectp;
12552       dwo_sections->str_offsets.size = bfd_section_size (sectp);
12553     }
12554   else if (section_is_p (sectp->name, &names->types_dwo))
12555     {
12556       struct dwarf2_section_info type_section;
12557
12558       memset (&type_section, 0, sizeof (type_section));
12559       type_section.s.section = sectp;
12560       type_section.size = bfd_section_size (sectp);
12561       dwo_sections->types.push_back (type_section);
12562     }
12563 }
12564
12565 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12566    by PER_CU.  This is for the non-DWP case.
12567    The result is NULL if DWO_NAME can't be found.  */
12568
12569 static struct dwo_file *
12570 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12571                         const char *dwo_name, const char *comp_dir)
12572 {
12573   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12574
12575   gdb_bfd_ref_ptr dbfd = open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir);
12576   if (dbfd == NULL)
12577     {
12578       if (dwarf_read_debug)
12579         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12580       return NULL;
12581     }
12582
12583   dwo_file_up dwo_file (new struct dwo_file);
12584   dwo_file->dwo_name = dwo_name;
12585   dwo_file->comp_dir = comp_dir;
12586   dwo_file->dbfd = std::move (dbfd);
12587
12588   bfd_map_over_sections (dwo_file->dbfd.get (), dwarf2_locate_dwo_sections,
12589                          &dwo_file->sections);
12590
12591   create_cus_hash_table (dwarf2_per_objfile, per_cu->cu, *dwo_file,
12592                          dwo_file->sections.info, dwo_file->cus);
12593
12594   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12595                                  dwo_file->sections.types, dwo_file->tus);
12596
12597   if (dwarf_read_debug)
12598     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12599
12600   return dwo_file.release ();
12601 }
12602
12603 /* This function is mapped across the sections and remembers the offset and
12604    size of each of the DWP debugging sections common to version 1 and 2 that
12605    we are interested in.  */
12606
12607 static void
12608 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12609                                    void *dwp_file_ptr)
12610 {
12611   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12612   const struct dwop_section_names *names = &dwop_section_names;
12613   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12614
12615   /* Record the ELF section number for later lookup: this is what the
12616      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12617   gdb_assert (elf_section_nr < dwp_file->num_sections);
12618   dwp_file->elf_sections[elf_section_nr] = sectp;
12619
12620   /* Look for specific sections that we need.  */
12621   if (section_is_p (sectp->name, &names->str_dwo))
12622     {
12623       dwp_file->sections.str.s.section = sectp;
12624       dwp_file->sections.str.size = bfd_section_size (sectp);
12625     }
12626   else if (section_is_p (sectp->name, &names->cu_index))
12627     {
12628       dwp_file->sections.cu_index.s.section = sectp;
12629       dwp_file->sections.cu_index.size = bfd_section_size (sectp);
12630     }
12631   else if (section_is_p (sectp->name, &names->tu_index))
12632     {
12633       dwp_file->sections.tu_index.s.section = sectp;
12634       dwp_file->sections.tu_index.size = bfd_section_size (sectp);
12635     }
12636 }
12637
12638 /* This function is mapped across the sections and remembers the offset and
12639    size of each of the DWP version 2 debugging sections that we are interested
12640    in.  This is split into a separate function because we don't know if we
12641    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12642
12643 static void
12644 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12645 {
12646   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12647   const struct dwop_section_names *names = &dwop_section_names;
12648   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12649
12650   /* Record the ELF section number for later lookup: this is what the
12651      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12652   gdb_assert (elf_section_nr < dwp_file->num_sections);
12653   dwp_file->elf_sections[elf_section_nr] = sectp;
12654
12655   /* Look for specific sections that we need.  */
12656   if (section_is_p (sectp->name, &names->abbrev_dwo))
12657     {
12658       dwp_file->sections.abbrev.s.section = sectp;
12659       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
12660     }
12661   else if (section_is_p (sectp->name, &names->info_dwo))
12662     {
12663       dwp_file->sections.info.s.section = sectp;
12664       dwp_file->sections.info.size = bfd_section_size (sectp);
12665     }
12666   else if (section_is_p (sectp->name, &names->line_dwo))
12667     {
12668       dwp_file->sections.line.s.section = sectp;
12669       dwp_file->sections.line.size = bfd_section_size (sectp);
12670     }
12671   else if (section_is_p (sectp->name, &names->loc_dwo))
12672     {
12673       dwp_file->sections.loc.s.section = sectp;
12674       dwp_file->sections.loc.size = bfd_section_size (sectp);
12675     }
12676   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12677     {
12678       dwp_file->sections.macinfo.s.section = sectp;
12679       dwp_file->sections.macinfo.size = bfd_section_size (sectp);
12680     }
12681   else if (section_is_p (sectp->name, &names->macro_dwo))
12682     {
12683       dwp_file->sections.macro.s.section = sectp;
12684       dwp_file->sections.macro.size = bfd_section_size (sectp);
12685     }
12686   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12687     {
12688       dwp_file->sections.str_offsets.s.section = sectp;
12689       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
12690     }
12691   else if (section_is_p (sectp->name, &names->types_dwo))
12692     {
12693       dwp_file->sections.types.s.section = sectp;
12694       dwp_file->sections.types.size = bfd_section_size (sectp);
12695     }
12696 }
12697
12698 /* Hash function for dwp_file loaded CUs/TUs.  */
12699
12700 static hashval_t
12701 hash_dwp_loaded_cutus (const void *item)
12702 {
12703   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12704
12705   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
12706   return dwo_unit->signature;
12707 }
12708
12709 /* Equality function for dwp_file loaded CUs/TUs.  */
12710
12711 static int
12712 eq_dwp_loaded_cutus (const void *a, const void *b)
12713 {
12714   const struct dwo_unit *dua = (const struct dwo_unit *) a;
12715   const struct dwo_unit *dub = (const struct dwo_unit *) b;
12716
12717   return dua->signature == dub->signature;
12718 }
12719
12720 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
12721
12722 static htab_up
12723 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
12724 {
12725   return htab_up (htab_create_alloc (3,
12726                                      hash_dwp_loaded_cutus,
12727                                      eq_dwp_loaded_cutus,
12728                                      NULL, xcalloc, xfree));
12729 }
12730
12731 /* Try to open DWP file FILE_NAME.
12732    The result is the bfd handle of the file.
12733    If there is a problem finding or opening the file, return NULL.
12734    Upon success, the canonicalized path of the file is stored in the bfd,
12735    same as symfile_bfd_open.  */
12736
12737 static gdb_bfd_ref_ptr
12738 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12739                const char *file_name)
12740 {
12741   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
12742                                             1 /*is_dwp*/,
12743                                             1 /*search_cwd*/));
12744   if (abfd != NULL)
12745     return abfd;
12746
12747   /* Work around upstream bug 15652.
12748      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
12749      [Whether that's a "bug" is debatable, but it is getting in our way.]
12750      We have no real idea where the dwp file is, because gdb's realpath-ing
12751      of the executable's path may have discarded the needed info.
12752      [IWBN if the dwp file name was recorded in the executable, akin to
12753      .gnu_debuglink, but that doesn't exist yet.]
12754      Strip the directory from FILE_NAME and search again.  */
12755   if (*debug_file_directory != '\0')
12756     {
12757       /* Don't implicitly search the current directory here.
12758          If the user wants to search "." to handle this case,
12759          it must be added to debug-file-directory.  */
12760       return try_open_dwop_file (dwarf2_per_objfile,
12761                                  lbasename (file_name), 1 /*is_dwp*/,
12762                                  0 /*search_cwd*/);
12763     }
12764
12765   return NULL;
12766 }
12767
12768 /* Initialize the use of the DWP file for the current objfile.
12769    By convention the name of the DWP file is ${objfile}.dwp.
12770    The result is NULL if it can't be found.  */
12771
12772 static std::unique_ptr<struct dwp_file>
12773 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
12774 {
12775   struct objfile *objfile = dwarf2_per_objfile->objfile;
12776
12777   /* Try to find first .dwp for the binary file before any symbolic links
12778      resolving.  */
12779
12780   /* If the objfile is a debug file, find the name of the real binary
12781      file and get the name of dwp file from there.  */
12782   std::string dwp_name;
12783   if (objfile->separate_debug_objfile_backlink != NULL)
12784     {
12785       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
12786       const char *backlink_basename = lbasename (backlink->original_name);
12787
12788       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
12789     }
12790   else
12791     dwp_name = objfile->original_name;
12792
12793   dwp_name += ".dwp";
12794
12795   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
12796   if (dbfd == NULL
12797       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
12798     {
12799       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
12800       dwp_name = objfile_name (objfile);
12801       dwp_name += ".dwp";
12802       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
12803     }
12804
12805   if (dbfd == NULL)
12806     {
12807       if (dwarf_read_debug)
12808         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
12809       return std::unique_ptr<dwp_file> ();
12810     }
12811
12812   const char *name = bfd_get_filename (dbfd.get ());
12813   std::unique_ptr<struct dwp_file> dwp_file
12814     (new struct dwp_file (name, std::move (dbfd)));
12815
12816   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
12817   dwp_file->elf_sections =
12818     OBSTACK_CALLOC (&objfile->objfile_obstack,
12819                     dwp_file->num_sections, asection *);
12820
12821   bfd_map_over_sections (dwp_file->dbfd.get (),
12822                          dwarf2_locate_common_dwp_sections,
12823                          dwp_file.get ());
12824
12825   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
12826                                          0);
12827
12828   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
12829                                          1);
12830
12831   /* The DWP file version is stored in the hash table.  Oh well.  */
12832   if (dwp_file->cus && dwp_file->tus
12833       && dwp_file->cus->version != dwp_file->tus->version)
12834     {
12835       /* Technically speaking, we should try to limp along, but this is
12836          pretty bizarre.  We use pulongest here because that's the established
12837          portability solution (e.g, we cannot use %u for uint32_t).  */
12838       error (_("Dwarf Error: DWP file CU version %s doesn't match"
12839                " TU version %s [in DWP file %s]"),
12840              pulongest (dwp_file->cus->version),
12841              pulongest (dwp_file->tus->version), dwp_name.c_str ());
12842     }
12843
12844   if (dwp_file->cus)
12845     dwp_file->version = dwp_file->cus->version;
12846   else if (dwp_file->tus)
12847     dwp_file->version = dwp_file->tus->version;
12848   else
12849     dwp_file->version = 2;
12850
12851   if (dwp_file->version == 2)
12852     bfd_map_over_sections (dwp_file->dbfd.get (),
12853                            dwarf2_locate_v2_dwp_sections,
12854                            dwp_file.get ());
12855
12856   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
12857   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
12858
12859   if (dwarf_read_debug)
12860     {
12861       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
12862       fprintf_unfiltered (gdb_stdlog,
12863                           "    %s CUs, %s TUs\n",
12864                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
12865                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
12866     }
12867
12868   return dwp_file;
12869 }
12870
12871 /* Wrapper around open_and_init_dwp_file, only open it once.  */
12872
12873 static struct dwp_file *
12874 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
12875 {
12876   if (! dwarf2_per_objfile->dwp_checked)
12877     {
12878       dwarf2_per_objfile->dwp_file
12879         = open_and_init_dwp_file (dwarf2_per_objfile);
12880       dwarf2_per_objfile->dwp_checked = 1;
12881     }
12882   return dwarf2_per_objfile->dwp_file.get ();
12883 }
12884
12885 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
12886    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
12887    or in the DWP file for the objfile, referenced by THIS_UNIT.
12888    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
12889    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
12890
12891    This is called, for example, when wanting to read a variable with a
12892    complex location.  Therefore we don't want to do file i/o for every call.
12893    Therefore we don't want to look for a DWO file on every call.
12894    Therefore we first see if we've already seen SIGNATURE in a DWP file,
12895    then we check if we've already seen DWO_NAME, and only THEN do we check
12896    for a DWO file.
12897
12898    The result is a pointer to the dwo_unit object or NULL if we didn't find it
12899    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
12900
12901 static struct dwo_unit *
12902 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
12903                  const char *dwo_name, const char *comp_dir,
12904                  ULONGEST signature, int is_debug_types)
12905 {
12906   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
12907   struct objfile *objfile = dwarf2_per_objfile->objfile;
12908   const char *kind = is_debug_types ? "TU" : "CU";
12909   void **dwo_file_slot;
12910   struct dwo_file *dwo_file;
12911   struct dwp_file *dwp_file;
12912
12913   /* First see if there's a DWP file.
12914      If we have a DWP file but didn't find the DWO inside it, don't
12915      look for the original DWO file.  It makes gdb behave differently
12916      depending on whether one is debugging in the build tree.  */
12917
12918   dwp_file = get_dwp_file (dwarf2_per_objfile);
12919   if (dwp_file != NULL)
12920     {
12921       const struct dwp_hash_table *dwp_htab =
12922         is_debug_types ? dwp_file->tus : dwp_file->cus;
12923
12924       if (dwp_htab != NULL)
12925         {
12926           struct dwo_unit *dwo_cutu =
12927             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
12928                                     signature, is_debug_types);
12929
12930           if (dwo_cutu != NULL)
12931             {
12932               if (dwarf_read_debug)
12933                 {
12934                   fprintf_unfiltered (gdb_stdlog,
12935                                       "Virtual DWO %s %s found: @%s\n",
12936                                       kind, hex_string (signature),
12937                                       host_address_to_string (dwo_cutu));
12938                 }
12939               return dwo_cutu;
12940             }
12941         }
12942     }
12943   else
12944     {
12945       /* No DWP file, look for the DWO file.  */
12946
12947       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12948                                             dwo_name, comp_dir);
12949       if (*dwo_file_slot == NULL)
12950         {
12951           /* Read in the file and build a table of the CUs/TUs it contains.  */
12952           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
12953         }
12954       /* NOTE: This will be NULL if unable to open the file.  */
12955       dwo_file = (struct dwo_file *) *dwo_file_slot;
12956
12957       if (dwo_file != NULL)
12958         {
12959           struct dwo_unit *dwo_cutu = NULL;
12960
12961           if (is_debug_types && dwo_file->tus)
12962             {
12963               struct dwo_unit find_dwo_cutu;
12964
12965               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12966               find_dwo_cutu.signature = signature;
12967               dwo_cutu
12968                 = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
12969                                                  &find_dwo_cutu);
12970             }
12971           else if (!is_debug_types && dwo_file->cus)
12972             {
12973               struct dwo_unit find_dwo_cutu;
12974
12975               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12976               find_dwo_cutu.signature = signature;
12977               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus.get (),
12978                                                        &find_dwo_cutu);
12979             }
12980
12981           if (dwo_cutu != NULL)
12982             {
12983               if (dwarf_read_debug)
12984                 {
12985                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
12986                                       kind, dwo_name, hex_string (signature),
12987                                       host_address_to_string (dwo_cutu));
12988                 }
12989               return dwo_cutu;
12990             }
12991         }
12992     }
12993
12994   /* We didn't find it.  This could mean a dwo_id mismatch, or
12995      someone deleted the DWO/DWP file, or the search path isn't set up
12996      correctly to find the file.  */
12997
12998   if (dwarf_read_debug)
12999     {
13000       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13001                           kind, dwo_name, hex_string (signature));
13002     }
13003
13004   /* This is a warning and not a complaint because it can be caused by
13005      pilot error (e.g., user accidentally deleting the DWO).  */
13006   {
13007     /* Print the name of the DWP file if we looked there, helps the user
13008        better diagnose the problem.  */
13009     std::string dwp_text;
13010
13011     if (dwp_file != NULL)
13012       dwp_text = string_printf (" [in DWP file %s]",
13013                                 lbasename (dwp_file->name));
13014
13015     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13016                " [in module %s]"),
13017              kind, dwo_name, hex_string (signature),
13018              dwp_text.c_str (),
13019              this_unit->is_debug_types ? "TU" : "CU",
13020              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13021   }
13022   return NULL;
13023 }
13024
13025 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13026    See lookup_dwo_cutu_unit for details.  */
13027
13028 static struct dwo_unit *
13029 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13030                       const char *dwo_name, const char *comp_dir,
13031                       ULONGEST signature)
13032 {
13033   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13034 }
13035
13036 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13037    See lookup_dwo_cutu_unit for details.  */
13038
13039 static struct dwo_unit *
13040 lookup_dwo_type_unit (struct signatured_type *this_tu,
13041                       const char *dwo_name, const char *comp_dir)
13042 {
13043   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13044 }
13045
13046 /* Traversal function for queue_and_load_all_dwo_tus.  */
13047
13048 static int
13049 queue_and_load_dwo_tu (void **slot, void *info)
13050 {
13051   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13052   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13053   ULONGEST signature = dwo_unit->signature;
13054   struct signatured_type *sig_type =
13055     lookup_dwo_signatured_type (per_cu->cu, signature);
13056
13057   if (sig_type != NULL)
13058     {
13059       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13060
13061       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13062          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13063          while processing PER_CU.  */
13064       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13065         load_full_type_unit (sig_cu);
13066       per_cu->imported_symtabs_push (sig_cu);
13067     }
13068
13069   return 1;
13070 }
13071
13072 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13073    The DWO may have the only definition of the type, though it may not be
13074    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13075    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13076
13077 static void
13078 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13079 {
13080   struct dwo_unit *dwo_unit;
13081   struct dwo_file *dwo_file;
13082
13083   gdb_assert (!per_cu->is_debug_types);
13084   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13085   gdb_assert (per_cu->cu != NULL);
13086
13087   dwo_unit = per_cu->cu->dwo_unit;
13088   gdb_assert (dwo_unit != NULL);
13089
13090   dwo_file = dwo_unit->dwo_file;
13091   if (dwo_file->tus != NULL)
13092     htab_traverse_noresize (dwo_file->tus.get (), queue_and_load_dwo_tu,
13093                             per_cu);
13094 }
13095
13096 /* Read in various DIEs.  */
13097
13098 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13099    Inherit only the children of the DW_AT_abstract_origin DIE not being
13100    already referenced by DW_AT_abstract_origin from the children of the
13101    current DIE.  */
13102
13103 static void
13104 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13105 {
13106   struct die_info *child_die;
13107   sect_offset *offsetp;
13108   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13109   struct die_info *origin_die;
13110   /* Iterator of the ORIGIN_DIE children.  */
13111   struct die_info *origin_child_die;
13112   struct attribute *attr;
13113   struct dwarf2_cu *origin_cu;
13114   struct pending **origin_previous_list_in_scope;
13115
13116   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13117   if (!attr)
13118     return;
13119
13120   /* Note that following die references may follow to a die in a
13121      different cu.  */
13122
13123   origin_cu = cu;
13124   origin_die = follow_die_ref (die, attr, &origin_cu);
13125
13126   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13127      symbols in.  */
13128   origin_previous_list_in_scope = origin_cu->list_in_scope;
13129   origin_cu->list_in_scope = cu->list_in_scope;
13130
13131   if (die->tag != origin_die->tag
13132       && !(die->tag == DW_TAG_inlined_subroutine
13133            && origin_die->tag == DW_TAG_subprogram))
13134     complaint (_("DIE %s and its abstract origin %s have different tags"),
13135                sect_offset_str (die->sect_off),
13136                sect_offset_str (origin_die->sect_off));
13137
13138   std::vector<sect_offset> offsets;
13139
13140   for (child_die = die->child;
13141        child_die && child_die->tag;
13142        child_die = sibling_die (child_die))
13143     {
13144       struct die_info *child_origin_die;
13145       struct dwarf2_cu *child_origin_cu;
13146
13147       /* We are trying to process concrete instance entries:
13148          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13149          it's not relevant to our analysis here. i.e. detecting DIEs that are
13150          present in the abstract instance but not referenced in the concrete
13151          one.  */
13152       if (child_die->tag == DW_TAG_call_site
13153           || child_die->tag == DW_TAG_GNU_call_site)
13154         continue;
13155
13156       /* For each CHILD_DIE, find the corresponding child of
13157          ORIGIN_DIE.  If there is more than one layer of
13158          DW_AT_abstract_origin, follow them all; there shouldn't be,
13159          but GCC versions at least through 4.4 generate this (GCC PR
13160          40573).  */
13161       child_origin_die = child_die;
13162       child_origin_cu = cu;
13163       while (1)
13164         {
13165           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13166                               child_origin_cu);
13167           if (attr == NULL)
13168             break;
13169           child_origin_die = follow_die_ref (child_origin_die, attr,
13170                                              &child_origin_cu);
13171         }
13172
13173       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13174          counterpart may exist.  */
13175       if (child_origin_die != child_die)
13176         {
13177           if (child_die->tag != child_origin_die->tag
13178               && !(child_die->tag == DW_TAG_inlined_subroutine
13179                    && child_origin_die->tag == DW_TAG_subprogram))
13180             complaint (_("Child DIE %s and its abstract origin %s have "
13181                          "different tags"),
13182                        sect_offset_str (child_die->sect_off),
13183                        sect_offset_str (child_origin_die->sect_off));
13184           if (child_origin_die->parent != origin_die)
13185             complaint (_("Child DIE %s and its abstract origin %s have "
13186                          "different parents"),
13187                        sect_offset_str (child_die->sect_off),
13188                        sect_offset_str (child_origin_die->sect_off));
13189           else
13190             offsets.push_back (child_origin_die->sect_off);
13191         }
13192     }
13193   std::sort (offsets.begin (), offsets.end ());
13194   sect_offset *offsets_end = offsets.data () + offsets.size ();
13195   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13196     if (offsetp[-1] == *offsetp)
13197       complaint (_("Multiple children of DIE %s refer "
13198                    "to DIE %s as their abstract origin"),
13199                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13200
13201   offsetp = offsets.data ();
13202   origin_child_die = origin_die->child;
13203   while (origin_child_die && origin_child_die->tag)
13204     {
13205       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13206       while (offsetp < offsets_end
13207              && *offsetp < origin_child_die->sect_off)
13208         offsetp++;
13209       if (offsetp >= offsets_end
13210           || *offsetp > origin_child_die->sect_off)
13211         {
13212           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13213              Check whether we're already processing ORIGIN_CHILD_DIE.
13214              This can happen with mutually referenced abstract_origins.
13215              PR 16581.  */
13216           if (!origin_child_die->in_process)
13217             process_die (origin_child_die, origin_cu);
13218         }
13219       origin_child_die = sibling_die (origin_child_die);
13220     }
13221   origin_cu->list_in_scope = origin_previous_list_in_scope;
13222
13223   if (cu != origin_cu)
13224     compute_delayed_physnames (origin_cu);
13225 }
13226
13227 static void
13228 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13229 {
13230   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13231   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13232   struct context_stack *newobj;
13233   CORE_ADDR lowpc;
13234   CORE_ADDR highpc;
13235   struct die_info *child_die;
13236   struct attribute *attr, *call_line, *call_file;
13237   const char *name;
13238   CORE_ADDR baseaddr;
13239   struct block *block;
13240   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13241   std::vector<struct symbol *> template_args;
13242   struct template_symbol *templ_func = NULL;
13243
13244   if (inlined_func)
13245     {
13246       /* If we do not have call site information, we can't show the
13247          caller of this inlined function.  That's too confusing, so
13248          only use the scope for local variables.  */
13249       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13250       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13251       if (call_line == NULL || call_file == NULL)
13252         {
13253           read_lexical_block_scope (die, cu);
13254           return;
13255         }
13256     }
13257
13258   baseaddr = objfile->text_section_offset ();
13259
13260   name = dwarf2_name (die, cu);
13261
13262   /* Ignore functions with missing or empty names.  These are actually
13263      illegal according to the DWARF standard.  */
13264   if (name == NULL)
13265     {
13266       complaint (_("missing name for subprogram DIE at %s"),
13267                  sect_offset_str (die->sect_off));
13268       return;
13269     }
13270
13271   /* Ignore functions with missing or invalid low and high pc attributes.  */
13272   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13273       <= PC_BOUNDS_INVALID)
13274     {
13275       attr = dwarf2_attr (die, DW_AT_external, cu);
13276       if (!attr || !DW_UNSND (attr))
13277         complaint (_("cannot get low and high bounds "
13278                      "for subprogram DIE at %s"),
13279                    sect_offset_str (die->sect_off));
13280       return;
13281     }
13282
13283   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13284   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13285
13286   /* If we have any template arguments, then we must allocate a
13287      different sort of symbol.  */
13288   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13289     {
13290       if (child_die->tag == DW_TAG_template_type_param
13291           || child_die->tag == DW_TAG_template_value_param)
13292         {
13293           templ_func = allocate_template_symbol (objfile);
13294           templ_func->subclass = SYMBOL_TEMPLATE;
13295           break;
13296         }
13297     }
13298
13299   newobj = cu->get_builder ()->push_context (0, lowpc);
13300   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13301                              (struct symbol *) templ_func);
13302
13303   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
13304     set_objfile_main_name (objfile, newobj->name->linkage_name (),
13305                            cu->language);
13306
13307   /* If there is a location expression for DW_AT_frame_base, record
13308      it.  */
13309   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13310   if (attr != nullptr)
13311     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13312
13313   /* If there is a location for the static link, record it.  */
13314   newobj->static_link = NULL;
13315   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13316   if (attr != nullptr)
13317     {
13318       newobj->static_link
13319         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13320       attr_to_dynamic_prop (attr, die, cu, newobj->static_link,
13321                             dwarf2_per_cu_addr_type (cu->per_cu));
13322     }
13323
13324   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13325
13326   if (die->child != NULL)
13327     {
13328       child_die = die->child;
13329       while (child_die && child_die->tag)
13330         {
13331           if (child_die->tag == DW_TAG_template_type_param
13332               || child_die->tag == DW_TAG_template_value_param)
13333             {
13334               struct symbol *arg = new_symbol (child_die, NULL, cu);
13335
13336               if (arg != NULL)
13337                 template_args.push_back (arg);
13338             }
13339           else
13340             process_die (child_die, cu);
13341           child_die = sibling_die (child_die);
13342         }
13343     }
13344
13345   inherit_abstract_dies (die, cu);
13346
13347   /* If we have a DW_AT_specification, we might need to import using
13348      directives from the context of the specification DIE.  See the
13349      comment in determine_prefix.  */
13350   if (cu->language == language_cplus
13351       && dwarf2_attr (die, DW_AT_specification, cu))
13352     {
13353       struct dwarf2_cu *spec_cu = cu;
13354       struct die_info *spec_die = die_specification (die, &spec_cu);
13355
13356       while (spec_die)
13357         {
13358           child_die = spec_die->child;
13359           while (child_die && child_die->tag)
13360             {
13361               if (child_die->tag == DW_TAG_imported_module)
13362                 process_die (child_die, spec_cu);
13363               child_die = sibling_die (child_die);
13364             }
13365
13366           /* In some cases, GCC generates specification DIEs that
13367              themselves contain DW_AT_specification attributes.  */
13368           spec_die = die_specification (spec_die, &spec_cu);
13369         }
13370     }
13371
13372   struct context_stack cstk = cu->get_builder ()->pop_context ();
13373   /* Make a block for the local symbols within.  */
13374   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13375                                      cstk.static_link, lowpc, highpc);
13376
13377   /* For C++, set the block's scope.  */
13378   if ((cu->language == language_cplus
13379        || cu->language == language_fortran
13380        || cu->language == language_d
13381        || cu->language == language_rust)
13382       && cu->processing_has_namespace_info)
13383     block_set_scope (block, determine_prefix (die, cu),
13384                      &objfile->objfile_obstack);
13385
13386   /* If we have address ranges, record them.  */
13387   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13388
13389   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13390
13391   /* Attach template arguments to function.  */
13392   if (!template_args.empty ())
13393     {
13394       gdb_assert (templ_func != NULL);
13395
13396       templ_func->n_template_arguments = template_args.size ();
13397       templ_func->template_arguments
13398         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13399                      templ_func->n_template_arguments);
13400       memcpy (templ_func->template_arguments,
13401               template_args.data (),
13402               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13403
13404       /* Make sure that the symtab is set on the new symbols.  Even
13405          though they don't appear in this symtab directly, other parts
13406          of gdb assume that symbols do, and this is reasonably
13407          true.  */
13408       for (symbol *sym : template_args)
13409         symbol_set_symtab (sym, symbol_symtab (templ_func));
13410     }
13411
13412   /* In C++, we can have functions nested inside functions (e.g., when
13413      a function declares a class that has methods).  This means that
13414      when we finish processing a function scope, we may need to go
13415      back to building a containing block's symbol lists.  */
13416   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13417   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13418
13419   /* If we've finished processing a top-level function, subsequent
13420      symbols go in the file symbol list.  */
13421   if (cu->get_builder ()->outermost_context_p ())
13422     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13423 }
13424
13425 /* Process all the DIES contained within a lexical block scope.  Start
13426    a new scope, process the dies, and then close the scope.  */
13427
13428 static void
13429 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13430 {
13431   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13432   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13433   CORE_ADDR lowpc, highpc;
13434   struct die_info *child_die;
13435   CORE_ADDR baseaddr;
13436
13437   baseaddr = objfile->text_section_offset ();
13438
13439   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13440   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13441      as multiple lexical blocks?  Handling children in a sane way would
13442      be nasty.  Might be easier to properly extend generic blocks to
13443      describe ranges.  */
13444   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13445     {
13446     case PC_BOUNDS_NOT_PRESENT:
13447       /* DW_TAG_lexical_block has no attributes, process its children as if
13448          there was no wrapping by that DW_TAG_lexical_block.
13449          GCC does no longer produces such DWARF since GCC r224161.  */
13450       for (child_die = die->child;
13451            child_die != NULL && child_die->tag;
13452            child_die = sibling_die (child_die))
13453         process_die (child_die, cu);
13454       return;
13455     case PC_BOUNDS_INVALID:
13456       return;
13457     }
13458   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13459   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13460
13461   cu->get_builder ()->push_context (0, lowpc);
13462   if (die->child != NULL)
13463     {
13464       child_die = die->child;
13465       while (child_die && child_die->tag)
13466         {
13467           process_die (child_die, cu);
13468           child_die = sibling_die (child_die);
13469         }
13470     }
13471   inherit_abstract_dies (die, cu);
13472   struct context_stack cstk = cu->get_builder ()->pop_context ();
13473
13474   if (*cu->get_builder ()->get_local_symbols () != NULL
13475       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13476     {
13477       struct block *block
13478         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13479                                      cstk.start_addr, highpc);
13480
13481       /* Note that recording ranges after traversing children, as we
13482          do here, means that recording a parent's ranges entails
13483          walking across all its children's ranges as they appear in
13484          the address map, which is quadratic behavior.
13485
13486          It would be nicer to record the parent's ranges before
13487          traversing its children, simply overriding whatever you find
13488          there.  But since we don't even decide whether to create a
13489          block until after we've traversed its children, that's hard
13490          to do.  */
13491       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13492     }
13493   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13494   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13495 }
13496
13497 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13498
13499 static void
13500 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13501 {
13502   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13503   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13504   CORE_ADDR pc, baseaddr;
13505   struct attribute *attr;
13506   struct call_site *call_site, call_site_local;
13507   void **slot;
13508   int nparams;
13509   struct die_info *child_die;
13510
13511   baseaddr = objfile->text_section_offset ();
13512
13513   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13514   if (attr == NULL)
13515     {
13516       /* This was a pre-DWARF-5 GNU extension alias
13517          for DW_AT_call_return_pc.  */
13518       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13519     }
13520   if (!attr)
13521     {
13522       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13523                    "DIE %s [in module %s]"),
13524                  sect_offset_str (die->sect_off), objfile_name (objfile));
13525       return;
13526     }
13527   pc = attr->value_as_address () + baseaddr;
13528   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13529
13530   if (cu->call_site_htab == NULL)
13531     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13532                                                NULL, &objfile->objfile_obstack,
13533                                                hashtab_obstack_allocate, NULL);
13534   call_site_local.pc = pc;
13535   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13536   if (*slot != NULL)
13537     {
13538       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13539                    "DIE %s [in module %s]"),
13540                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13541                  objfile_name (objfile));
13542       return;
13543     }
13544
13545   /* Count parameters at the caller.  */
13546
13547   nparams = 0;
13548   for (child_die = die->child; child_die && child_die->tag;
13549        child_die = sibling_die (child_die))
13550     {
13551       if (child_die->tag != DW_TAG_call_site_parameter
13552           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13553         {
13554           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13555                        "DW_TAG_call_site child DIE %s [in module %s]"),
13556                      child_die->tag, sect_offset_str (child_die->sect_off),
13557                      objfile_name (objfile));
13558           continue;
13559         }
13560
13561       nparams++;
13562     }
13563
13564   call_site
13565     = ((struct call_site *)
13566        obstack_alloc (&objfile->objfile_obstack,
13567                       sizeof (*call_site)
13568                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13569   *slot = call_site;
13570   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13571   call_site->pc = pc;
13572
13573   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13574       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13575     {
13576       struct die_info *func_die;
13577
13578       /* Skip also over DW_TAG_inlined_subroutine.  */
13579       for (func_die = die->parent;
13580            func_die && func_die->tag != DW_TAG_subprogram
13581            && func_die->tag != DW_TAG_subroutine_type;
13582            func_die = func_die->parent);
13583
13584       /* DW_AT_call_all_calls is a superset
13585          of DW_AT_call_all_tail_calls.  */
13586       if (func_die
13587           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13588           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13589           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13590           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13591         {
13592           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13593              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13594              both the initial caller containing the real return address PC and
13595              the final callee containing the current PC of a chain of tail
13596              calls do not need to have the tail call list complete.  But any
13597              function candidate for a virtual tail call frame searched via
13598              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13599              determined unambiguously.  */
13600         }
13601       else
13602         {
13603           struct type *func_type = NULL;
13604
13605           if (func_die)
13606             func_type = get_die_type (func_die, cu);
13607           if (func_type != NULL)
13608             {
13609               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13610
13611               /* Enlist this call site to the function.  */
13612               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13613               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13614             }
13615           else
13616             complaint (_("Cannot find function owning DW_TAG_call_site "
13617                          "DIE %s [in module %s]"),
13618                        sect_offset_str (die->sect_off), objfile_name (objfile));
13619         }
13620     }
13621
13622   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13623   if (attr == NULL)
13624     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13625   if (attr == NULL)
13626     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13627   if (attr == NULL)
13628     {
13629       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13630       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13631     }
13632   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13633   if (!attr || (attr->form_is_block () && DW_BLOCK (attr)->size == 0))
13634     /* Keep NULL DWARF_BLOCK.  */;
13635   else if (attr->form_is_block ())
13636     {
13637       struct dwarf2_locexpr_baton *dlbaton;
13638
13639       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13640       dlbaton->data = DW_BLOCK (attr)->data;
13641       dlbaton->size = DW_BLOCK (attr)->size;
13642       dlbaton->per_cu = cu->per_cu;
13643
13644       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13645     }
13646   else if (attr->form_is_ref ())
13647     {
13648       struct dwarf2_cu *target_cu = cu;
13649       struct die_info *target_die;
13650
13651       target_die = follow_die_ref (die, attr, &target_cu);
13652       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13653       if (die_is_declaration (target_die, target_cu))
13654         {
13655           const char *target_physname;
13656
13657           /* Prefer the mangled name; otherwise compute the demangled one.  */
13658           target_physname = dw2_linkage_name (target_die, target_cu);
13659           if (target_physname == NULL)
13660             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13661           if (target_physname == NULL)
13662             complaint (_("DW_AT_call_target target DIE has invalid "
13663                          "physname, for referencing DIE %s [in module %s]"),
13664                        sect_offset_str (die->sect_off), objfile_name (objfile));
13665           else
13666             SET_FIELD_PHYSNAME (call_site->target, target_physname);
13667         }
13668       else
13669         {
13670           CORE_ADDR lowpc;
13671
13672           /* DW_AT_entry_pc should be preferred.  */
13673           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13674               <= PC_BOUNDS_INVALID)
13675             complaint (_("DW_AT_call_target target DIE has invalid "
13676                          "low pc, for referencing DIE %s [in module %s]"),
13677                        sect_offset_str (die->sect_off), objfile_name (objfile));
13678           else
13679             {
13680               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13681               SET_FIELD_PHYSADDR (call_site->target, lowpc);
13682             }
13683         }
13684     }
13685   else
13686     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
13687                  "block nor reference, for DIE %s [in module %s]"),
13688                sect_offset_str (die->sect_off), objfile_name (objfile));
13689
13690   call_site->per_cu = cu->per_cu;
13691
13692   for (child_die = die->child;
13693        child_die && child_die->tag;
13694        child_die = sibling_die (child_die))
13695     {
13696       struct call_site_parameter *parameter;
13697       struct attribute *loc, *origin;
13698
13699       if (child_die->tag != DW_TAG_call_site_parameter
13700           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13701         {
13702           /* Already printed the complaint above.  */
13703           continue;
13704         }
13705
13706       gdb_assert (call_site->parameter_count < nparams);
13707       parameter = &call_site->parameter[call_site->parameter_count];
13708
13709       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
13710          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
13711          register is contained in DW_AT_call_value.  */
13712
13713       loc = dwarf2_attr (child_die, DW_AT_location, cu);
13714       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
13715       if (origin == NULL)
13716         {
13717           /* This was a pre-DWARF-5 GNU extension alias
13718              for DW_AT_call_parameter.  */
13719           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
13720         }
13721       if (loc == NULL && origin != NULL && origin->form_is_ref ())
13722         {
13723           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
13724
13725           sect_offset sect_off
13726             = (sect_offset) dwarf2_get_ref_die_offset (origin);
13727           if (!offset_in_cu_p (&cu->header, sect_off))
13728             {
13729               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
13730                  binding can be done only inside one CU.  Such referenced DIE
13731                  therefore cannot be even moved to DW_TAG_partial_unit.  */
13732               complaint (_("DW_AT_call_parameter offset is not in CU for "
13733                            "DW_TAG_call_site child DIE %s [in module %s]"),
13734                          sect_offset_str (child_die->sect_off),
13735                          objfile_name (objfile));
13736               continue;
13737             }
13738           parameter->u.param_cu_off
13739             = (cu_offset) (sect_off - cu->header.sect_off);
13740         }
13741       else if (loc == NULL || origin != NULL || !loc->form_is_block ())
13742         {
13743           complaint (_("No DW_FORM_block* DW_AT_location for "
13744                        "DW_TAG_call_site child DIE %s [in module %s]"),
13745                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
13746           continue;
13747         }
13748       else
13749         {
13750           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
13751             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
13752           if (parameter->u.dwarf_reg != -1)
13753             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
13754           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
13755                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
13756                                              &parameter->u.fb_offset))
13757             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
13758           else
13759             {
13760               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
13761                            "for DW_FORM_block* DW_AT_location is supported for "
13762                            "DW_TAG_call_site child DIE %s "
13763                            "[in module %s]"),
13764                          sect_offset_str (child_die->sect_off),
13765                          objfile_name (objfile));
13766               continue;
13767             }
13768         }
13769
13770       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
13771       if (attr == NULL)
13772         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
13773       if (attr == NULL || !attr->form_is_block ())
13774         {
13775           complaint (_("No DW_FORM_block* DW_AT_call_value for "
13776                        "DW_TAG_call_site child DIE %s [in module %s]"),
13777                      sect_offset_str (child_die->sect_off),
13778                      objfile_name (objfile));
13779           continue;
13780         }
13781       parameter->value = DW_BLOCK (attr)->data;
13782       parameter->value_size = DW_BLOCK (attr)->size;
13783
13784       /* Parameters are not pre-cleared by memset above.  */
13785       parameter->data_value = NULL;
13786       parameter->data_value_size = 0;
13787       call_site->parameter_count++;
13788
13789       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
13790       if (attr == NULL)
13791         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
13792       if (attr != nullptr)
13793         {
13794           if (!attr->form_is_block ())
13795             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
13796                          "DW_TAG_call_site child DIE %s [in module %s]"),
13797                        sect_offset_str (child_die->sect_off),
13798                        objfile_name (objfile));
13799           else
13800             {
13801               parameter->data_value = DW_BLOCK (attr)->data;
13802               parameter->data_value_size = DW_BLOCK (attr)->size;
13803             }
13804         }
13805     }
13806 }
13807
13808 /* Helper function for read_variable.  If DIE represents a virtual
13809    table, then return the type of the concrete object that is
13810    associated with the virtual table.  Otherwise, return NULL.  */
13811
13812 static struct type *
13813 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13814 {
13815   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
13816   if (attr == NULL)
13817     return NULL;
13818
13819   /* Find the type DIE.  */
13820   struct die_info *type_die = NULL;
13821   struct dwarf2_cu *type_cu = cu;
13822
13823   if (attr->form_is_ref ())
13824     type_die = follow_die_ref (die, attr, &type_cu);
13825   if (type_die == NULL)
13826     return NULL;
13827
13828   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
13829     return NULL;
13830   return die_containing_type (type_die, type_cu);
13831 }
13832
13833 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
13834
13835 static void
13836 read_variable (struct die_info *die, struct dwarf2_cu *cu)
13837 {
13838   struct rust_vtable_symbol *storage = NULL;
13839
13840   if (cu->language == language_rust)
13841     {
13842       struct type *containing_type = rust_containing_type (die, cu);
13843
13844       if (containing_type != NULL)
13845         {
13846           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13847
13848           storage = new (&objfile->objfile_obstack) rust_vtable_symbol ();
13849           initialize_objfile_symbol (storage);
13850           storage->concrete_type = containing_type;
13851           storage->subclass = SYMBOL_RUST_VTABLE;
13852         }
13853     }
13854
13855   struct symbol *res = new_symbol (die, NULL, cu, storage);
13856   struct attribute *abstract_origin
13857     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13858   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
13859   if (res == NULL && loc && abstract_origin)
13860     {
13861       /* We have a variable without a name, but with a location and an abstract
13862          origin.  This may be a concrete instance of an abstract variable
13863          referenced from an DW_OP_GNU_variable_value, so save it to find it back
13864          later.  */
13865       struct dwarf2_cu *origin_cu = cu;
13866       struct die_info *origin_die
13867         = follow_die_ref (die, abstract_origin, &origin_cu);
13868       dwarf2_per_objfile *dpo = cu->per_cu->dwarf2_per_objfile;
13869       dpo->abstract_to_concrete[origin_die->sect_off].push_back (die->sect_off);
13870     }
13871 }
13872
13873 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
13874    reading .debug_rnglists.
13875    Callback's type should be:
13876     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13877    Return true if the attributes are present and valid, otherwise,
13878    return false.  */
13879
13880 template <typename Callback>
13881 static bool
13882 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
13883                          Callback &&callback)
13884 {
13885   struct dwarf2_per_objfile *dwarf2_per_objfile
13886     = cu->per_cu->dwarf2_per_objfile;
13887   struct objfile *objfile = dwarf2_per_objfile->objfile;
13888   bfd *obfd = objfile->obfd;
13889   /* Base address selection entry.  */
13890   CORE_ADDR base;
13891   int found_base;
13892   const gdb_byte *buffer;
13893   CORE_ADDR baseaddr;
13894   bool overflow = false;
13895
13896   found_base = cu->base_known;
13897   base = cu->base_address;
13898
13899   dwarf2_per_objfile->rnglists.read (objfile);
13900   if (offset >= dwarf2_per_objfile->rnglists.size)
13901     {
13902       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
13903                  offset);
13904       return false;
13905     }
13906   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
13907
13908   baseaddr = objfile->text_section_offset ();
13909
13910   while (1)
13911     {
13912       /* Initialize it due to a false compiler warning.  */
13913       CORE_ADDR range_beginning = 0, range_end = 0;
13914       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
13915                                  + dwarf2_per_objfile->rnglists.size);
13916       unsigned int bytes_read;
13917
13918       if (buffer == buf_end)
13919         {
13920           overflow = true;
13921           break;
13922         }
13923       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
13924       switch (rlet)
13925         {
13926         case DW_RLE_end_of_list:
13927           break;
13928         case DW_RLE_base_address:
13929           if (buffer + cu->header.addr_size > buf_end)
13930             {
13931               overflow = true;
13932               break;
13933             }
13934           base = read_address (obfd, buffer, cu, &bytes_read);
13935           found_base = 1;
13936           buffer += bytes_read;
13937           break;
13938         case DW_RLE_start_length:
13939           if (buffer + cu->header.addr_size > buf_end)
13940             {
13941               overflow = true;
13942               break;
13943             }
13944           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13945           buffer += bytes_read;
13946           range_end = (range_beginning
13947                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13948           buffer += bytes_read;
13949           if (buffer > buf_end)
13950             {
13951               overflow = true;
13952               break;
13953             }
13954           break;
13955         case DW_RLE_offset_pair:
13956           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13957           buffer += bytes_read;
13958           if (buffer > buf_end)
13959             {
13960               overflow = true;
13961               break;
13962             }
13963           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13964           buffer += bytes_read;
13965           if (buffer > buf_end)
13966             {
13967               overflow = true;
13968               break;
13969             }
13970           break;
13971         case DW_RLE_start_end:
13972           if (buffer + 2 * cu->header.addr_size > buf_end)
13973             {
13974               overflow = true;
13975               break;
13976             }
13977           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13978           buffer += bytes_read;
13979           range_end = read_address (obfd, buffer, cu, &bytes_read);
13980           buffer += bytes_read;
13981           break;
13982         default:
13983           complaint (_("Invalid .debug_rnglists data (no base address)"));
13984           return false;
13985         }
13986       if (rlet == DW_RLE_end_of_list || overflow)
13987         break;
13988       if (rlet == DW_RLE_base_address)
13989         continue;
13990
13991       if (!found_base)
13992         {
13993           /* We have no valid base address for the ranges
13994              data.  */
13995           complaint (_("Invalid .debug_rnglists data (no base address)"));
13996           return false;
13997         }
13998
13999       if (range_beginning > range_end)
14000         {
14001           /* Inverted range entries are invalid.  */
14002           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14003           return false;
14004         }
14005
14006       /* Empty range entries have no effect.  */
14007       if (range_beginning == range_end)
14008         continue;
14009
14010       range_beginning += base;
14011       range_end += base;
14012
14013       /* A not-uncommon case of bad debug info.
14014          Don't pollute the addrmap with bad data.  */
14015       if (range_beginning + baseaddr == 0
14016           && !dwarf2_per_objfile->has_section_at_zero)
14017         {
14018           complaint (_(".debug_rnglists entry has start address of zero"
14019                        " [in module %s]"), objfile_name (objfile));
14020           continue;
14021         }
14022
14023       callback (range_beginning, range_end);
14024     }
14025
14026   if (overflow)
14027     {
14028       complaint (_("Offset %d is not terminated "
14029                    "for DW_AT_ranges attribute"),
14030                  offset);
14031       return false;
14032     }
14033
14034   return true;
14035 }
14036
14037 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14038    Callback's type should be:
14039     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14040    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14041
14042 template <typename Callback>
14043 static int
14044 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14045                        Callback &&callback)
14046 {
14047   struct dwarf2_per_objfile *dwarf2_per_objfile
14048       = cu->per_cu->dwarf2_per_objfile;
14049   struct objfile *objfile = dwarf2_per_objfile->objfile;
14050   struct comp_unit_head *cu_header = &cu->header;
14051   bfd *obfd = objfile->obfd;
14052   unsigned int addr_size = cu_header->addr_size;
14053   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14054   /* Base address selection entry.  */
14055   CORE_ADDR base;
14056   int found_base;
14057   unsigned int dummy;
14058   const gdb_byte *buffer;
14059   CORE_ADDR baseaddr;
14060
14061   if (cu_header->version >= 5)
14062     return dwarf2_rnglists_process (offset, cu, callback);
14063
14064   found_base = cu->base_known;
14065   base = cu->base_address;
14066
14067   dwarf2_per_objfile->ranges.read (objfile);
14068   if (offset >= dwarf2_per_objfile->ranges.size)
14069     {
14070       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14071                  offset);
14072       return 0;
14073     }
14074   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14075
14076   baseaddr = objfile->text_section_offset ();
14077
14078   while (1)
14079     {
14080       CORE_ADDR range_beginning, range_end;
14081
14082       range_beginning = read_address (obfd, buffer, cu, &dummy);
14083       buffer += addr_size;
14084       range_end = read_address (obfd, buffer, cu, &dummy);
14085       buffer += addr_size;
14086       offset += 2 * addr_size;
14087
14088       /* An end of list marker is a pair of zero addresses.  */
14089       if (range_beginning == 0 && range_end == 0)
14090         /* Found the end of list entry.  */
14091         break;
14092
14093       /* Each base address selection entry is a pair of 2 values.
14094          The first is the largest possible address, the second is
14095          the base address.  Check for a base address here.  */
14096       if ((range_beginning & mask) == mask)
14097         {
14098           /* If we found the largest possible address, then we already
14099              have the base address in range_end.  */
14100           base = range_end;
14101           found_base = 1;
14102           continue;
14103         }
14104
14105       if (!found_base)
14106         {
14107           /* We have no valid base address for the ranges
14108              data.  */
14109           complaint (_("Invalid .debug_ranges data (no base address)"));
14110           return 0;
14111         }
14112
14113       if (range_beginning > range_end)
14114         {
14115           /* Inverted range entries are invalid.  */
14116           complaint (_("Invalid .debug_ranges data (inverted range)"));
14117           return 0;
14118         }
14119
14120       /* Empty range entries have no effect.  */
14121       if (range_beginning == range_end)
14122         continue;
14123
14124       range_beginning += base;
14125       range_end += base;
14126
14127       /* A not-uncommon case of bad debug info.
14128          Don't pollute the addrmap with bad data.  */
14129       if (range_beginning + baseaddr == 0
14130           && !dwarf2_per_objfile->has_section_at_zero)
14131         {
14132           complaint (_(".debug_ranges entry has start address of zero"
14133                        " [in module %s]"), objfile_name (objfile));
14134           continue;
14135         }
14136
14137       callback (range_beginning, range_end);
14138     }
14139
14140   return 1;
14141 }
14142
14143 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14144    Return 1 if the attributes are present and valid, otherwise, return 0.
14145    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14146
14147 static int
14148 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14149                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14150                     dwarf2_psymtab *ranges_pst)
14151 {
14152   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14153   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14154   const CORE_ADDR baseaddr = objfile->text_section_offset ();
14155   int low_set = 0;
14156   CORE_ADDR low = 0;
14157   CORE_ADDR high = 0;
14158   int retval;
14159
14160   retval = dwarf2_ranges_process (offset, cu,
14161     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14162     {
14163       if (ranges_pst != NULL)
14164         {
14165           CORE_ADDR lowpc;
14166           CORE_ADDR highpc;
14167
14168           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14169                                                range_beginning + baseaddr)
14170                    - baseaddr);
14171           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14172                                                 range_end + baseaddr)
14173                     - baseaddr);
14174           addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
14175                              lowpc, highpc - 1, ranges_pst);
14176         }
14177
14178       /* FIXME: This is recording everything as a low-high
14179          segment of consecutive addresses.  We should have a
14180          data structure for discontiguous block ranges
14181          instead.  */
14182       if (! low_set)
14183         {
14184           low = range_beginning;
14185           high = range_end;
14186           low_set = 1;
14187         }
14188       else
14189         {
14190           if (range_beginning < low)
14191             low = range_beginning;
14192           if (range_end > high)
14193             high = range_end;
14194         }
14195     });
14196   if (!retval)
14197     return 0;
14198
14199   if (! low_set)
14200     /* If the first entry is an end-of-list marker, the range
14201        describes an empty scope, i.e. no instructions.  */
14202     return 0;
14203
14204   if (low_return)
14205     *low_return = low;
14206   if (high_return)
14207     *high_return = high;
14208   return 1;
14209 }
14210
14211 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14212    definition for the return value.  *LOWPC and *HIGHPC are set iff
14213    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14214
14215 static enum pc_bounds_kind
14216 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14217                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14218                       dwarf2_psymtab *pst)
14219 {
14220   struct dwarf2_per_objfile *dwarf2_per_objfile
14221     = cu->per_cu->dwarf2_per_objfile;
14222   struct attribute *attr;
14223   struct attribute *attr_high;
14224   CORE_ADDR low = 0;
14225   CORE_ADDR high = 0;
14226   enum pc_bounds_kind ret;
14227
14228   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14229   if (attr_high)
14230     {
14231       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14232       if (attr != nullptr)
14233         {
14234           low = attr->value_as_address ();
14235           high = attr_high->value_as_address ();
14236           if (cu->header.version >= 4 && attr_high->form_is_constant ())
14237             high += low;
14238         }
14239       else
14240         /* Found high w/o low attribute.  */
14241         return PC_BOUNDS_INVALID;
14242
14243       /* Found consecutive range of addresses.  */
14244       ret = PC_BOUNDS_HIGH_LOW;
14245     }
14246   else
14247     {
14248       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14249       if (attr != NULL)
14250         {
14251           /* DW_AT_rnglists_base does not apply to DIEs from the DWO skeleton.
14252              We take advantage of the fact that DW_AT_ranges does not appear
14253              in DW_TAG_compile_unit of DWO files.  */
14254           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14255           unsigned int ranges_offset = (DW_UNSND (attr)
14256                                         + (need_ranges_base
14257                                            ? cu->ranges_base
14258                                            : 0));
14259
14260           /* Value of the DW_AT_ranges attribute is the offset in the
14261              .debug_ranges section.  */
14262           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14263             return PC_BOUNDS_INVALID;
14264           /* Found discontinuous range of addresses.  */
14265           ret = PC_BOUNDS_RANGES;
14266         }
14267       else
14268         return PC_BOUNDS_NOT_PRESENT;
14269     }
14270
14271   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14272   if (high <= low)
14273     return PC_BOUNDS_INVALID;
14274
14275   /* When using the GNU linker, .gnu.linkonce. sections are used to
14276      eliminate duplicate copies of functions and vtables and such.
14277      The linker will arbitrarily choose one and discard the others.
14278      The AT_*_pc values for such functions refer to local labels in
14279      these sections.  If the section from that file was discarded, the
14280      labels are not in the output, so the relocs get a value of 0.
14281      If this is a discarded function, mark the pc bounds as invalid,
14282      so that GDB will ignore it.  */
14283   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14284     return PC_BOUNDS_INVALID;
14285
14286   *lowpc = low;
14287   if (highpc)
14288     *highpc = high;
14289   return ret;
14290 }
14291
14292 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14293    its low and high PC addresses.  Do nothing if these addresses could not
14294    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14295    and HIGHPC to the high address if greater than HIGHPC.  */
14296
14297 static void
14298 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14299                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14300                                  struct dwarf2_cu *cu)
14301 {
14302   CORE_ADDR low, high;
14303   struct die_info *child = die->child;
14304
14305   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14306     {
14307       *lowpc = std::min (*lowpc, low);
14308       *highpc = std::max (*highpc, high);
14309     }
14310
14311   /* If the language does not allow nested subprograms (either inside
14312      subprograms or lexical blocks), we're done.  */
14313   if (cu->language != language_ada)
14314     return;
14315
14316   /* Check all the children of the given DIE.  If it contains nested
14317      subprograms, then check their pc bounds.  Likewise, we need to
14318      check lexical blocks as well, as they may also contain subprogram
14319      definitions.  */
14320   while (child && child->tag)
14321     {
14322       if (child->tag == DW_TAG_subprogram
14323           || child->tag == DW_TAG_lexical_block)
14324         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14325       child = sibling_die (child);
14326     }
14327 }
14328
14329 /* Get the low and high pc's represented by the scope DIE, and store
14330    them in *LOWPC and *HIGHPC.  If the correct values can't be
14331    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14332
14333 static void
14334 get_scope_pc_bounds (struct die_info *die,
14335                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14336                      struct dwarf2_cu *cu)
14337 {
14338   CORE_ADDR best_low = (CORE_ADDR) -1;
14339   CORE_ADDR best_high = (CORE_ADDR) 0;
14340   CORE_ADDR current_low, current_high;
14341
14342   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14343       >= PC_BOUNDS_RANGES)
14344     {
14345       best_low = current_low;
14346       best_high = current_high;
14347     }
14348   else
14349     {
14350       struct die_info *child = die->child;
14351
14352       while (child && child->tag)
14353         {
14354           switch (child->tag) {
14355           case DW_TAG_subprogram:
14356             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14357             break;
14358           case DW_TAG_namespace:
14359           case DW_TAG_module:
14360             /* FIXME: carlton/2004-01-16: Should we do this for
14361                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14362                that current GCC's always emit the DIEs corresponding
14363                to definitions of methods of classes as children of a
14364                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14365                the DIEs giving the declarations, which could be
14366                anywhere).  But I don't see any reason why the
14367                standards says that they have to be there.  */
14368             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14369
14370             if (current_low != ((CORE_ADDR) -1))
14371               {
14372                 best_low = std::min (best_low, current_low);
14373                 best_high = std::max (best_high, current_high);
14374               }
14375             break;
14376           default:
14377             /* Ignore.  */
14378             break;
14379           }
14380
14381           child = sibling_die (child);
14382         }
14383     }
14384
14385   *lowpc = best_low;
14386   *highpc = best_high;
14387 }
14388
14389 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14390    in DIE.  */
14391
14392 static void
14393 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14394                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14395 {
14396   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14397   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14398   struct attribute *attr;
14399   struct attribute *attr_high;
14400
14401   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14402   if (attr_high)
14403     {
14404       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14405       if (attr != nullptr)
14406         {
14407           CORE_ADDR low = attr->value_as_address ();
14408           CORE_ADDR high = attr_high->value_as_address ();
14409
14410           if (cu->header.version >= 4 && attr_high->form_is_constant ())
14411             high += low;
14412
14413           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14414           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14415           cu->get_builder ()->record_block_range (block, low, high - 1);
14416         }
14417     }
14418
14419   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14420   if (attr != nullptr)
14421     {
14422       /* DW_AT_rnglists_base does not apply to DIEs from the DWO skeleton.
14423          We take advantage of the fact that DW_AT_ranges does not appear
14424          in DW_TAG_compile_unit of DWO files.  */
14425       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14426
14427       /* The value of the DW_AT_ranges attribute is the offset of the
14428          address range list in the .debug_ranges section.  */
14429       unsigned long offset = (DW_UNSND (attr)
14430                               + (need_ranges_base ? cu->ranges_base : 0));
14431
14432       std::vector<blockrange> blockvec;
14433       dwarf2_ranges_process (offset, cu,
14434         [&] (CORE_ADDR start, CORE_ADDR end)
14435         {
14436           start += baseaddr;
14437           end += baseaddr;
14438           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14439           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14440           cu->get_builder ()->record_block_range (block, start, end - 1);
14441           blockvec.emplace_back (start, end);
14442         });
14443
14444       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14445     }
14446 }
14447
14448 /* Check whether the producer field indicates either of GCC < 4.6, or the
14449    Intel C/C++ compiler, and cache the result in CU.  */
14450
14451 static void
14452 check_producer (struct dwarf2_cu *cu)
14453 {
14454   int major, minor;
14455
14456   if (cu->producer == NULL)
14457     {
14458       /* For unknown compilers expect their behavior is DWARF version
14459          compliant.
14460
14461          GCC started to support .debug_types sections by -gdwarf-4 since
14462          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14463          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14464          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14465          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14466     }
14467   else if (producer_is_gcc (cu->producer, &major, &minor))
14468     {
14469       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14470       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14471     }
14472   else if (producer_is_icc (cu->producer, &major, &minor))
14473     {
14474       cu->producer_is_icc = true;
14475       cu->producer_is_icc_lt_14 = major < 14;
14476     }
14477   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14478     cu->producer_is_codewarrior = true;
14479   else
14480     {
14481       /* For other non-GCC compilers, expect their behavior is DWARF version
14482          compliant.  */
14483     }
14484
14485   cu->checked_producer = true;
14486 }
14487
14488 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14489    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14490    during 4.6.0 experimental.  */
14491
14492 static bool
14493 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14494 {
14495   if (!cu->checked_producer)
14496     check_producer (cu);
14497
14498   return cu->producer_is_gxx_lt_4_6;
14499 }
14500
14501
14502 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14503    with incorrect is_stmt attributes.  */
14504
14505 static bool
14506 producer_is_codewarrior (struct dwarf2_cu *cu)
14507 {
14508   if (!cu->checked_producer)
14509     check_producer (cu);
14510
14511   return cu->producer_is_codewarrior;
14512 }
14513
14514 /* Return the default accessibility type if it is not overridden by
14515    DW_AT_accessibility.  */
14516
14517 static enum dwarf_access_attribute
14518 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14519 {
14520   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14521     {
14522       /* The default DWARF 2 accessibility for members is public, the default
14523          accessibility for inheritance is private.  */
14524
14525       if (die->tag != DW_TAG_inheritance)
14526         return DW_ACCESS_public;
14527       else
14528         return DW_ACCESS_private;
14529     }
14530   else
14531     {
14532       /* DWARF 3+ defines the default accessibility a different way.  The same
14533          rules apply now for DW_TAG_inheritance as for the members and it only
14534          depends on the container kind.  */
14535
14536       if (die->parent->tag == DW_TAG_class_type)
14537         return DW_ACCESS_private;
14538       else
14539         return DW_ACCESS_public;
14540     }
14541 }
14542
14543 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14544    offset.  If the attribute was not found return 0, otherwise return
14545    1.  If it was found but could not properly be handled, set *OFFSET
14546    to 0.  */
14547
14548 static int
14549 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14550                              LONGEST *offset)
14551 {
14552   struct attribute *attr;
14553
14554   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14555   if (attr != NULL)
14556     {
14557       *offset = 0;
14558
14559       /* Note that we do not check for a section offset first here.
14560          This is because DW_AT_data_member_location is new in DWARF 4,
14561          so if we see it, we can assume that a constant form is really
14562          a constant and not a section offset.  */
14563       if (attr->form_is_constant ())
14564         *offset = dwarf2_get_attr_constant_value (attr, 0);
14565       else if (attr->form_is_section_offset ())
14566         dwarf2_complex_location_expr_complaint ();
14567       else if (attr->form_is_block ())
14568         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14569       else
14570         dwarf2_complex_location_expr_complaint ();
14571
14572       return 1;
14573     }
14574
14575   return 0;
14576 }
14577
14578 /* Add an aggregate field to the field list.  */
14579
14580 static void
14581 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14582                   struct dwarf2_cu *cu)
14583 {
14584   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14585   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14586   struct nextfield *new_field;
14587   struct attribute *attr;
14588   struct field *fp;
14589   const char *fieldname = "";
14590
14591   if (die->tag == DW_TAG_inheritance)
14592     {
14593       fip->baseclasses.emplace_back ();
14594       new_field = &fip->baseclasses.back ();
14595     }
14596   else
14597     {
14598       fip->fields.emplace_back ();
14599       new_field = &fip->fields.back ();
14600     }
14601
14602   fip->nfields++;
14603
14604   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14605   if (attr != nullptr)
14606     new_field->accessibility = DW_UNSND (attr);
14607   else
14608     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14609   if (new_field->accessibility != DW_ACCESS_public)
14610     fip->non_public_fields = 1;
14611
14612   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14613   if (attr != nullptr)
14614     new_field->virtuality = DW_UNSND (attr);
14615   else
14616     new_field->virtuality = DW_VIRTUALITY_none;
14617
14618   fp = &new_field->field;
14619
14620   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14621     {
14622       LONGEST offset;
14623
14624       /* Data member other than a C++ static data member.  */
14625
14626       /* Get type of field.  */
14627       fp->type = die_type (die, cu);
14628
14629       SET_FIELD_BITPOS (*fp, 0);
14630
14631       /* Get bit size of field (zero if none).  */
14632       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14633       if (attr != nullptr)
14634         {
14635           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14636         }
14637       else
14638         {
14639           FIELD_BITSIZE (*fp) = 0;
14640         }
14641
14642       /* Get bit offset of field.  */
14643       if (handle_data_member_location (die, cu, &offset))
14644         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14645       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14646       if (attr != nullptr)
14647         {
14648           if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
14649             {
14650               /* For big endian bits, the DW_AT_bit_offset gives the
14651                  additional bit offset from the MSB of the containing
14652                  anonymous object to the MSB of the field.  We don't
14653                  have to do anything special since we don't need to
14654                  know the size of the anonymous object.  */
14655               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14656             }
14657           else
14658             {
14659               /* For little endian bits, compute the bit offset to the
14660                  MSB of the anonymous object, subtract off the number of
14661                  bits from the MSB of the field to the MSB of the
14662                  object, and then subtract off the number of bits of
14663                  the field itself.  The result is the bit offset of
14664                  the LSB of the field.  */
14665               int anonymous_size;
14666               int bit_offset = DW_UNSND (attr);
14667
14668               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14669               if (attr != nullptr)
14670                 {
14671                   /* The size of the anonymous object containing
14672                      the bit field is explicit, so use the
14673                      indicated size (in bytes).  */
14674                   anonymous_size = DW_UNSND (attr);
14675                 }
14676               else
14677                 {
14678                   /* The size of the anonymous object containing
14679                      the bit field must be inferred from the type
14680                      attribute of the data member containing the
14681                      bit field.  */
14682                   anonymous_size = TYPE_LENGTH (fp->type);
14683                 }
14684               SET_FIELD_BITPOS (*fp,
14685                                 (FIELD_BITPOS (*fp)
14686                                  + anonymous_size * bits_per_byte
14687                                  - bit_offset - FIELD_BITSIZE (*fp)));
14688             }
14689         }
14690       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14691       if (attr != NULL)
14692         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14693                                 + dwarf2_get_attr_constant_value (attr, 0)));
14694
14695       /* Get name of field.  */
14696       fieldname = dwarf2_name (die, cu);
14697       if (fieldname == NULL)
14698         fieldname = "";
14699
14700       /* The name is already allocated along with this objfile, so we don't
14701          need to duplicate it for the type.  */
14702       fp->name = fieldname;
14703
14704       /* Change accessibility for artificial fields (e.g. virtual table
14705          pointer or virtual base class pointer) to private.  */
14706       if (dwarf2_attr (die, DW_AT_artificial, cu))
14707         {
14708           FIELD_ARTIFICIAL (*fp) = 1;
14709           new_field->accessibility = DW_ACCESS_private;
14710           fip->non_public_fields = 1;
14711         }
14712     }
14713   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
14714     {
14715       /* C++ static member.  */
14716
14717       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
14718          is a declaration, but all versions of G++ as of this writing
14719          (so through at least 3.2.1) incorrectly generate
14720          DW_TAG_variable tags.  */
14721
14722       const char *physname;
14723
14724       /* Get name of field.  */
14725       fieldname = dwarf2_name (die, cu);
14726       if (fieldname == NULL)
14727         return;
14728
14729       attr = dwarf2_attr (die, DW_AT_const_value, cu);
14730       if (attr
14731           /* Only create a symbol if this is an external value.
14732              new_symbol checks this and puts the value in the global symbol
14733              table, which we want.  If it is not external, new_symbol
14734              will try to put the value in cu->list_in_scope which is wrong.  */
14735           && dwarf2_flag_true_p (die, DW_AT_external, cu))
14736         {
14737           /* A static const member, not much different than an enum as far as
14738              we're concerned, except that we can support more types.  */
14739           new_symbol (die, NULL, cu);
14740         }
14741
14742       /* Get physical name.  */
14743       physname = dwarf2_physname (fieldname, die, cu);
14744
14745       /* The name is already allocated along with this objfile, so we don't
14746          need to duplicate it for the type.  */
14747       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
14748       FIELD_TYPE (*fp) = die_type (die, cu);
14749       FIELD_NAME (*fp) = fieldname;
14750     }
14751   else if (die->tag == DW_TAG_inheritance)
14752     {
14753       LONGEST offset;
14754
14755       /* C++ base class field.  */
14756       if (handle_data_member_location (die, cu, &offset))
14757         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14758       FIELD_BITSIZE (*fp) = 0;
14759       FIELD_TYPE (*fp) = die_type (die, cu);
14760       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
14761     }
14762   else if (die->tag == DW_TAG_variant_part)
14763     {
14764       /* process_structure_scope will treat this DIE as a union.  */
14765       process_structure_scope (die, cu);
14766
14767       /* The variant part is relative to the start of the enclosing
14768          structure.  */
14769       SET_FIELD_BITPOS (*fp, 0);
14770       fp->type = get_die_type (die, cu);
14771       fp->artificial = 1;
14772       fp->name = "<<variant>>";
14773
14774       /* Normally a DW_TAG_variant_part won't have a size, but our
14775          representation requires one, so set it to the maximum of the
14776          child sizes, being sure to account for the offset at which
14777          each child is seen.  */
14778       if (TYPE_LENGTH (fp->type) == 0)
14779         {
14780           unsigned max = 0;
14781           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
14782             {
14783               unsigned len = ((TYPE_FIELD_BITPOS (fp->type, i) + 7) / 8
14784                               + TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)));
14785               if (len > max)
14786                 max = len;
14787             }
14788           TYPE_LENGTH (fp->type) = max;
14789         }
14790     }
14791   else
14792     gdb_assert_not_reached ("missing case in dwarf2_add_field");
14793 }
14794
14795 /* Can the type given by DIE define another type?  */
14796
14797 static bool
14798 type_can_define_types (const struct die_info *die)
14799 {
14800   switch (die->tag)
14801     {
14802     case DW_TAG_typedef:
14803     case DW_TAG_class_type:
14804     case DW_TAG_structure_type:
14805     case DW_TAG_union_type:
14806     case DW_TAG_enumeration_type:
14807       return true;
14808
14809     default:
14810       return false;
14811     }
14812 }
14813
14814 /* Add a type definition defined in the scope of the FIP's class.  */
14815
14816 static void
14817 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
14818                       struct dwarf2_cu *cu)
14819 {
14820   struct decl_field fp;
14821   memset (&fp, 0, sizeof (fp));
14822
14823   gdb_assert (type_can_define_types (die));
14824
14825   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
14826   fp.name = dwarf2_name (die, cu);
14827   fp.type = read_type_die (die, cu);
14828
14829   /* Save accessibility.  */
14830   enum dwarf_access_attribute accessibility;
14831   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14832   if (attr != NULL)
14833     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14834   else
14835     accessibility = dwarf2_default_access_attribute (die, cu);
14836   switch (accessibility)
14837     {
14838     case DW_ACCESS_public:
14839       /* The assumed value if neither private nor protected.  */
14840       break;
14841     case DW_ACCESS_private:
14842       fp.is_private = 1;
14843       break;
14844     case DW_ACCESS_protected:
14845       fp.is_protected = 1;
14846       break;
14847     default:
14848       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
14849     }
14850
14851   if (die->tag == DW_TAG_typedef)
14852     fip->typedef_field_list.push_back (fp);
14853   else
14854     fip->nested_types_list.push_back (fp);
14855 }
14856
14857 /* Create the vector of fields, and attach it to the type.  */
14858
14859 static void
14860 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
14861                               struct dwarf2_cu *cu)
14862 {
14863   int nfields = fip->nfields;
14864
14865   /* Record the field count, allocate space for the array of fields,
14866      and create blank accessibility bitfields if necessary.  */
14867   TYPE_NFIELDS (type) = nfields;
14868   TYPE_FIELDS (type) = (struct field *)
14869     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
14870
14871   if (fip->non_public_fields && cu->language != language_ada)
14872     {
14873       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14874
14875       TYPE_FIELD_PRIVATE_BITS (type) =
14876         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14877       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
14878
14879       TYPE_FIELD_PROTECTED_BITS (type) =
14880         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14881       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
14882
14883       TYPE_FIELD_IGNORE_BITS (type) =
14884         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14885       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
14886     }
14887
14888   /* If the type has baseclasses, allocate and clear a bit vector for
14889      TYPE_FIELD_VIRTUAL_BITS.  */
14890   if (!fip->baseclasses.empty () && cu->language != language_ada)
14891     {
14892       int num_bytes = B_BYTES (fip->baseclasses.size ());
14893       unsigned char *pointer;
14894
14895       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14896       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
14897       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
14898       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
14899       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
14900     }
14901
14902   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
14903     {
14904       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
14905
14906       for (int index = 0; index < nfields; ++index)
14907         {
14908           struct nextfield &field = fip->fields[index];
14909
14910           if (field.variant.is_discriminant)
14911             di->discriminant_index = index;
14912           else if (field.variant.default_branch)
14913             di->default_index = index;
14914           else
14915             di->discriminants[index] = field.variant.discriminant_value;
14916         }
14917     }
14918
14919   /* Copy the saved-up fields into the field vector.  */
14920   for (int i = 0; i < nfields; ++i)
14921     {
14922       struct nextfield &field
14923         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
14924            : fip->fields[i - fip->baseclasses.size ()]);
14925
14926       TYPE_FIELD (type, i) = field.field;
14927       switch (field.accessibility)
14928         {
14929         case DW_ACCESS_private:
14930           if (cu->language != language_ada)
14931             SET_TYPE_FIELD_PRIVATE (type, i);
14932           break;
14933
14934         case DW_ACCESS_protected:
14935           if (cu->language != language_ada)
14936             SET_TYPE_FIELD_PROTECTED (type, i);
14937           break;
14938
14939         case DW_ACCESS_public:
14940           break;
14941
14942         default:
14943           /* Unknown accessibility.  Complain and treat it as public.  */
14944           {
14945             complaint (_("unsupported accessibility %d"),
14946                        field.accessibility);
14947           }
14948           break;
14949         }
14950       if (i < fip->baseclasses.size ())
14951         {
14952           switch (field.virtuality)
14953             {
14954             case DW_VIRTUALITY_virtual:
14955             case DW_VIRTUALITY_pure_virtual:
14956               if (cu->language == language_ada)
14957                 error (_("unexpected virtuality in component of Ada type"));
14958               SET_TYPE_FIELD_VIRTUAL (type, i);
14959               break;
14960             }
14961         }
14962     }
14963 }
14964
14965 /* Return true if this member function is a constructor, false
14966    otherwise.  */
14967
14968 static int
14969 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
14970 {
14971   const char *fieldname;
14972   const char *type_name;
14973   int len;
14974
14975   if (die->parent == NULL)
14976     return 0;
14977
14978   if (die->parent->tag != DW_TAG_structure_type
14979       && die->parent->tag != DW_TAG_union_type
14980       && die->parent->tag != DW_TAG_class_type)
14981     return 0;
14982
14983   fieldname = dwarf2_name (die, cu);
14984   type_name = dwarf2_name (die->parent, cu);
14985   if (fieldname == NULL || type_name == NULL)
14986     return 0;
14987
14988   len = strlen (fieldname);
14989   return (strncmp (fieldname, type_name, len) == 0
14990           && (type_name[len] == '\0' || type_name[len] == '<'));
14991 }
14992
14993 /* Check if the given VALUE is a recognized enum
14994    dwarf_defaulted_attribute constant according to DWARF5 spec,
14995    Table 7.24.  */
14996
14997 static bool
14998 is_valid_DW_AT_defaulted (ULONGEST value)
14999 {
15000   switch (value)
15001     {
15002     case DW_DEFAULTED_no:
15003     case DW_DEFAULTED_in_class:
15004     case DW_DEFAULTED_out_of_class:
15005       return true;
15006     }
15007
15008   complaint (_("unrecognized DW_AT_defaulted value (%s)"), pulongest (value));
15009   return false;
15010 }
15011
15012 /* Add a member function to the proper fieldlist.  */
15013
15014 static void
15015 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15016                       struct type *type, struct dwarf2_cu *cu)
15017 {
15018   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15019   struct attribute *attr;
15020   int i;
15021   struct fnfieldlist *flp = nullptr;
15022   struct fn_field *fnp;
15023   const char *fieldname;
15024   struct type *this_type;
15025   enum dwarf_access_attribute accessibility;
15026
15027   if (cu->language == language_ada)
15028     error (_("unexpected member function in Ada type"));
15029
15030   /* Get name of member function.  */
15031   fieldname = dwarf2_name (die, cu);
15032   if (fieldname == NULL)
15033     return;
15034
15035   /* Look up member function name in fieldlist.  */
15036   for (i = 0; i < fip->fnfieldlists.size (); i++)
15037     {
15038       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15039         {
15040           flp = &fip->fnfieldlists[i];
15041           break;
15042         }
15043     }
15044
15045   /* Create a new fnfieldlist if necessary.  */
15046   if (flp == nullptr)
15047     {
15048       fip->fnfieldlists.emplace_back ();
15049       flp = &fip->fnfieldlists.back ();
15050       flp->name = fieldname;
15051       i = fip->fnfieldlists.size () - 1;
15052     }
15053
15054   /* Create a new member function field and add it to the vector of
15055      fnfieldlists.  */
15056   flp->fnfields.emplace_back ();
15057   fnp = &flp->fnfields.back ();
15058
15059   /* Delay processing of the physname until later.  */
15060   if (cu->language == language_cplus)
15061     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15062                         die, cu);
15063   else
15064     {
15065       const char *physname = dwarf2_physname (fieldname, die, cu);
15066       fnp->physname = physname ? physname : "";
15067     }
15068
15069   fnp->type = alloc_type (objfile);
15070   this_type = read_type_die (die, cu);
15071   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15072     {
15073       int nparams = TYPE_NFIELDS (this_type);
15074
15075       /* TYPE is the domain of this method, and THIS_TYPE is the type
15076            of the method itself (TYPE_CODE_METHOD).  */
15077       smash_to_method_type (fnp->type, type,
15078                             TYPE_TARGET_TYPE (this_type),
15079                             TYPE_FIELDS (this_type),
15080                             TYPE_NFIELDS (this_type),
15081                             TYPE_VARARGS (this_type));
15082
15083       /* Handle static member functions.
15084          Dwarf2 has no clean way to discern C++ static and non-static
15085          member functions.  G++ helps GDB by marking the first
15086          parameter for non-static member functions (which is the this
15087          pointer) as artificial.  We obtain this information from
15088          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15089       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15090         fnp->voffset = VOFFSET_STATIC;
15091     }
15092   else
15093     complaint (_("member function type missing for '%s'"),
15094                dwarf2_full_name (fieldname, die, cu));
15095
15096   /* Get fcontext from DW_AT_containing_type if present.  */
15097   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15098     fnp->fcontext = die_containing_type (die, cu);
15099
15100   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15101      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15102
15103   /* Get accessibility.  */
15104   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15105   if (attr != nullptr)
15106     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15107   else
15108     accessibility = dwarf2_default_access_attribute (die, cu);
15109   switch (accessibility)
15110     {
15111     case DW_ACCESS_private:
15112       fnp->is_private = 1;
15113       break;
15114     case DW_ACCESS_protected:
15115       fnp->is_protected = 1;
15116       break;
15117     }
15118
15119   /* Check for artificial methods.  */
15120   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15121   if (attr && DW_UNSND (attr) != 0)
15122     fnp->is_artificial = 1;
15123
15124   /* Check for defaulted methods.  */
15125   attr = dwarf2_attr (die, DW_AT_defaulted, cu);
15126   if (attr != nullptr && is_valid_DW_AT_defaulted (DW_UNSND (attr)))
15127     fnp->defaulted = (enum dwarf_defaulted_attribute) DW_UNSND (attr);
15128
15129   /* Check for deleted methods.  */
15130   attr = dwarf2_attr (die, DW_AT_deleted, cu);
15131   if (attr != nullptr && DW_UNSND (attr) != 0)
15132     fnp->is_deleted = 1;
15133
15134   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15135
15136   /* Get index in virtual function table if it is a virtual member
15137      function.  For older versions of GCC, this is an offset in the
15138      appropriate virtual table, as specified by DW_AT_containing_type.
15139      For everyone else, it is an expression to be evaluated relative
15140      to the object address.  */
15141
15142   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15143   if (attr != nullptr)
15144     {
15145       if (attr->form_is_block () && DW_BLOCK (attr)->size > 0)
15146         {
15147           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15148             {
15149               /* Old-style GCC.  */
15150               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15151             }
15152           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15153                    || (DW_BLOCK (attr)->size > 1
15154                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15155                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15156             {
15157               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15158               if ((fnp->voffset % cu->header.addr_size) != 0)
15159                 dwarf2_complex_location_expr_complaint ();
15160               else
15161                 fnp->voffset /= cu->header.addr_size;
15162               fnp->voffset += 2;
15163             }
15164           else
15165             dwarf2_complex_location_expr_complaint ();
15166
15167           if (!fnp->fcontext)
15168             {
15169               /* If there is no `this' field and no DW_AT_containing_type,
15170                  we cannot actually find a base class context for the
15171                  vtable!  */
15172               if (TYPE_NFIELDS (this_type) == 0
15173                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15174                 {
15175                   complaint (_("cannot determine context for virtual member "
15176                                "function \"%s\" (offset %s)"),
15177                              fieldname, sect_offset_str (die->sect_off));
15178                 }
15179               else
15180                 {
15181                   fnp->fcontext
15182                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15183                 }
15184             }
15185         }
15186       else if (attr->form_is_section_offset ())
15187         {
15188           dwarf2_complex_location_expr_complaint ();
15189         }
15190       else
15191         {
15192           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15193                                                  fieldname);
15194         }
15195     }
15196   else
15197     {
15198       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15199       if (attr && DW_UNSND (attr))
15200         {
15201           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15202           complaint (_("Member function \"%s\" (offset %s) is virtual "
15203                        "but the vtable offset is not specified"),
15204                      fieldname, sect_offset_str (die->sect_off));
15205           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15206           TYPE_CPLUS_DYNAMIC (type) = 1;
15207         }
15208     }
15209 }
15210
15211 /* Create the vector of member function fields, and attach it to the type.  */
15212
15213 static void
15214 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15215                                  struct dwarf2_cu *cu)
15216 {
15217   if (cu->language == language_ada)
15218     error (_("unexpected member functions in Ada type"));
15219
15220   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15221   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15222     TYPE_ALLOC (type,
15223                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15224
15225   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15226     {
15227       struct fnfieldlist &nf = fip->fnfieldlists[i];
15228       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15229
15230       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15231       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15232       fn_flp->fn_fields = (struct fn_field *)
15233         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15234
15235       for (int k = 0; k < nf.fnfields.size (); ++k)
15236         fn_flp->fn_fields[k] = nf.fnfields[k];
15237     }
15238
15239   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15240 }
15241
15242 /* Returns non-zero if NAME is the name of a vtable member in CU's
15243    language, zero otherwise.  */
15244 static int
15245 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15246 {
15247   static const char vptr[] = "_vptr";
15248
15249   /* Look for the C++ form of the vtable.  */
15250   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15251     return 1;
15252
15253   return 0;
15254 }
15255
15256 /* GCC outputs unnamed structures that are really pointers to member
15257    functions, with the ABI-specified layout.  If TYPE describes
15258    such a structure, smash it into a member function type.
15259
15260    GCC shouldn't do this; it should just output pointer to member DIEs.
15261    This is GCC PR debug/28767.  */
15262
15263 static void
15264 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15265 {
15266   struct type *pfn_type, *self_type, *new_type;
15267
15268   /* Check for a structure with no name and two children.  */
15269   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15270     return;
15271
15272   /* Check for __pfn and __delta members.  */
15273   if (TYPE_FIELD_NAME (type, 0) == NULL
15274       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15275       || TYPE_FIELD_NAME (type, 1) == NULL
15276       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15277     return;
15278
15279   /* Find the type of the method.  */
15280   pfn_type = TYPE_FIELD_TYPE (type, 0);
15281   if (pfn_type == NULL
15282       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15283       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15284     return;
15285
15286   /* Look for the "this" argument.  */
15287   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15288   if (TYPE_NFIELDS (pfn_type) == 0
15289       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15290       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15291     return;
15292
15293   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15294   new_type = alloc_type (objfile);
15295   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15296                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15297                         TYPE_VARARGS (pfn_type));
15298   smash_to_methodptr_type (type, new_type);
15299 }
15300
15301 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15302    appropriate error checking and issuing complaints if there is a
15303    problem.  */
15304
15305 static ULONGEST
15306 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15307 {
15308   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15309
15310   if (attr == nullptr)
15311     return 0;
15312
15313   if (!attr->form_is_constant ())
15314     {
15315       complaint (_("DW_AT_alignment must have constant form"
15316                    " - DIE at %s [in module %s]"),
15317                  sect_offset_str (die->sect_off),
15318                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15319       return 0;
15320     }
15321
15322   ULONGEST align;
15323   if (attr->form == DW_FORM_sdata)
15324     {
15325       LONGEST val = DW_SND (attr);
15326       if (val < 0)
15327         {
15328           complaint (_("DW_AT_alignment value must not be negative"
15329                        " - DIE at %s [in module %s]"),
15330                      sect_offset_str (die->sect_off),
15331                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15332           return 0;
15333         }
15334       align = val;
15335     }
15336   else
15337     align = DW_UNSND (attr);
15338
15339   if (align == 0)
15340     {
15341       complaint (_("DW_AT_alignment value must not be zero"
15342                    " - DIE at %s [in module %s]"),
15343                  sect_offset_str (die->sect_off),
15344                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15345       return 0;
15346     }
15347   if ((align & (align - 1)) != 0)
15348     {
15349       complaint (_("DW_AT_alignment value must be a power of 2"
15350                    " - DIE at %s [in module %s]"),
15351                  sect_offset_str (die->sect_off),
15352                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15353       return 0;
15354     }
15355
15356   return align;
15357 }
15358
15359 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15360    the alignment for TYPE.  */
15361
15362 static void
15363 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15364                      struct type *type)
15365 {
15366   if (!set_type_align (type, get_alignment (cu, die)))
15367     complaint (_("DW_AT_alignment value too large"
15368                  " - DIE at %s [in module %s]"),
15369                sect_offset_str (die->sect_off),
15370                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15371 }
15372
15373 /* Check if the given VALUE is a valid enum dwarf_calling_convention
15374    constant for a type, according to DWARF5 spec, Table 5.5.  */
15375
15376 static bool
15377 is_valid_DW_AT_calling_convention_for_type (ULONGEST value)
15378 {
15379   switch (value)
15380     {
15381     case DW_CC_normal:
15382     case DW_CC_pass_by_reference:
15383     case DW_CC_pass_by_value:
15384       return true;
15385
15386     default:
15387       complaint (_("unrecognized DW_AT_calling_convention value "
15388                    "(%s) for a type"), pulongest (value));
15389       return false;
15390     }
15391 }
15392
15393 /* Check if the given VALUE is a valid enum dwarf_calling_convention
15394    constant for a subroutine, according to DWARF5 spec, Table 3.3, and
15395    also according to GNU-specific values (see include/dwarf2.h).  */
15396
15397 static bool
15398 is_valid_DW_AT_calling_convention_for_subroutine (ULONGEST value)
15399 {
15400   switch (value)
15401     {
15402     case DW_CC_normal:
15403     case DW_CC_program:
15404     case DW_CC_nocall:
15405       return true;
15406
15407     case DW_CC_GNU_renesas_sh:
15408     case DW_CC_GNU_borland_fastcall_i386:
15409     case DW_CC_GDB_IBM_OpenCL:
15410       return true;
15411
15412     default:
15413       complaint (_("unrecognized DW_AT_calling_convention value "
15414                    "(%s) for a subroutine"), pulongest (value));
15415       return false;
15416     }
15417 }
15418
15419 /* Called when we find the DIE that starts a structure or union scope
15420    (definition) to create a type for the structure or union.  Fill in
15421    the type's name and general properties; the members will not be
15422    processed until process_structure_scope.  A symbol table entry for
15423    the type will also not be done until process_structure_scope (assuming
15424    the type has a name).
15425
15426    NOTE: we need to call these functions regardless of whether or not the
15427    DIE has a DW_AT_name attribute, since it might be an anonymous
15428    structure or union.  This gets the type entered into our set of
15429    user defined types.  */
15430
15431 static struct type *
15432 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15433 {
15434   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15435   struct type *type;
15436   struct attribute *attr;
15437   const char *name;
15438
15439   /* If the definition of this type lives in .debug_types, read that type.
15440      Don't follow DW_AT_specification though, that will take us back up
15441      the chain and we want to go down.  */
15442   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15443   if (attr != nullptr)
15444     {
15445       type = get_DW_AT_signature_type (die, attr, cu);
15446
15447       /* The type's CU may not be the same as CU.
15448          Ensure TYPE is recorded with CU in die_type_hash.  */
15449       return set_die_type (die, type, cu);
15450     }
15451
15452   type = alloc_type (objfile);
15453   INIT_CPLUS_SPECIFIC (type);
15454
15455   name = dwarf2_name (die, cu);
15456   if (name != NULL)
15457     {
15458       if (cu->language == language_cplus
15459           || cu->language == language_d
15460           || cu->language == language_rust)
15461         {
15462           const char *full_name = dwarf2_full_name (name, die, cu);
15463
15464           /* dwarf2_full_name might have already finished building the DIE's
15465              type.  If so, there is no need to continue.  */
15466           if (get_die_type (die, cu) != NULL)
15467             return get_die_type (die, cu);
15468
15469           TYPE_NAME (type) = full_name;
15470         }
15471       else
15472         {
15473           /* The name is already allocated along with this objfile, so
15474              we don't need to duplicate it for the type.  */
15475           TYPE_NAME (type) = name;
15476         }
15477     }
15478
15479   if (die->tag == DW_TAG_structure_type)
15480     {
15481       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15482     }
15483   else if (die->tag == DW_TAG_union_type)
15484     {
15485       TYPE_CODE (type) = TYPE_CODE_UNION;
15486     }
15487   else if (die->tag == DW_TAG_variant_part)
15488     {
15489       TYPE_CODE (type) = TYPE_CODE_UNION;
15490       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15491     }
15492   else
15493     {
15494       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15495     }
15496
15497   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15498     TYPE_DECLARED_CLASS (type) = 1;
15499
15500   /* Store the calling convention in the type if it's available in
15501      the die.  Otherwise the calling convention remains set to
15502      the default value DW_CC_normal.  */
15503   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15504   if (attr != nullptr
15505       && is_valid_DW_AT_calling_convention_for_type (DW_UNSND (attr)))
15506     {
15507       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15508       TYPE_CPLUS_CALLING_CONVENTION (type)
15509         = (enum dwarf_calling_convention) (DW_UNSND (attr));
15510     }
15511
15512   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15513   if (attr != nullptr)
15514     {
15515       if (attr->form_is_constant ())
15516         TYPE_LENGTH (type) = DW_UNSND (attr);
15517       else
15518         {
15519           /* For the moment, dynamic type sizes are not supported
15520              by GDB's struct type.  The actual size is determined
15521              on-demand when resolving the type of a given object,
15522              so set the type's length to zero for now.  Otherwise,
15523              we record an expression as the length, and that expression
15524              could lead to a very large value, which could eventually
15525              lead to us trying to allocate that much memory when creating
15526              a value of that type.  */
15527           TYPE_LENGTH (type) = 0;
15528         }
15529     }
15530   else
15531     {
15532       TYPE_LENGTH (type) = 0;
15533     }
15534
15535   maybe_set_alignment (cu, die, type);
15536
15537   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15538     {
15539       /* ICC<14 does not output the required DW_AT_declaration on
15540          incomplete types, but gives them a size of zero.  */
15541       TYPE_STUB (type) = 1;
15542     }
15543   else
15544     TYPE_STUB_SUPPORTED (type) = 1;
15545
15546   if (die_is_declaration (die, cu))
15547     TYPE_STUB (type) = 1;
15548   else if (attr == NULL && die->child == NULL
15549            && producer_is_realview (cu->producer))
15550     /* RealView does not output the required DW_AT_declaration
15551        on incomplete types.  */
15552     TYPE_STUB (type) = 1;
15553
15554   /* We need to add the type field to the die immediately so we don't
15555      infinitely recurse when dealing with pointers to the structure
15556      type within the structure itself.  */
15557   set_die_type (die, type, cu);
15558
15559   /* set_die_type should be already done.  */
15560   set_descriptive_type (type, die, cu);
15561
15562   return type;
15563 }
15564
15565 /* A helper for process_structure_scope that handles a single member
15566    DIE.  */
15567
15568 static void
15569 handle_struct_member_die (struct die_info *child_die, struct type *type,
15570                           struct field_info *fi,
15571                           std::vector<struct symbol *> *template_args,
15572                           struct dwarf2_cu *cu)
15573 {
15574   if (child_die->tag == DW_TAG_member
15575       || child_die->tag == DW_TAG_variable
15576       || child_die->tag == DW_TAG_variant_part)
15577     {
15578       /* NOTE: carlton/2002-11-05: A C++ static data member
15579          should be a DW_TAG_member that is a declaration, but
15580          all versions of G++ as of this writing (so through at
15581          least 3.2.1) incorrectly generate DW_TAG_variable
15582          tags for them instead.  */
15583       dwarf2_add_field (fi, child_die, cu);
15584     }
15585   else if (child_die->tag == DW_TAG_subprogram)
15586     {
15587       /* Rust doesn't have member functions in the C++ sense.
15588          However, it does emit ordinary functions as children
15589          of a struct DIE.  */
15590       if (cu->language == language_rust)
15591         read_func_scope (child_die, cu);
15592       else
15593         {
15594           /* C++ member function.  */
15595           dwarf2_add_member_fn (fi, child_die, type, cu);
15596         }
15597     }
15598   else if (child_die->tag == DW_TAG_inheritance)
15599     {
15600       /* C++ base class field.  */
15601       dwarf2_add_field (fi, child_die, cu);
15602     }
15603   else if (type_can_define_types (child_die))
15604     dwarf2_add_type_defn (fi, child_die, cu);
15605   else if (child_die->tag == DW_TAG_template_type_param
15606            || child_die->tag == DW_TAG_template_value_param)
15607     {
15608       struct symbol *arg = new_symbol (child_die, NULL, cu);
15609
15610       if (arg != NULL)
15611         template_args->push_back (arg);
15612     }
15613   else if (child_die->tag == DW_TAG_variant)
15614     {
15615       /* In a variant we want to get the discriminant and also add a
15616          field for our sole member child.  */
15617       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15618
15619       for (die_info *variant_child = child_die->child;
15620            variant_child != NULL;
15621            variant_child = sibling_die (variant_child))
15622         {
15623           if (variant_child->tag == DW_TAG_member)
15624             {
15625               handle_struct_member_die (variant_child, type, fi,
15626                                         template_args, cu);
15627               /* Only handle the one.  */
15628               break;
15629             }
15630         }
15631
15632       /* We don't handle this but we might as well report it if we see
15633          it.  */
15634       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15635           complaint (_("DW_AT_discr_list is not supported yet"
15636                        " - DIE at %s [in module %s]"),
15637                      sect_offset_str (child_die->sect_off),
15638                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15639
15640       /* The first field was just added, so we can stash the
15641          discriminant there.  */
15642       gdb_assert (!fi->fields.empty ());
15643       if (discr == NULL)
15644         fi->fields.back ().variant.default_branch = true;
15645       else
15646         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15647     }
15648 }
15649
15650 /* Finish creating a structure or union type, including filling in
15651    its members and creating a symbol for it.  */
15652
15653 static void
15654 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15655 {
15656   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15657   struct die_info *child_die;
15658   struct type *type;
15659
15660   type = get_die_type (die, cu);
15661   if (type == NULL)
15662     type = read_structure_type (die, cu);
15663
15664   /* When reading a DW_TAG_variant_part, we need to notice when we
15665      read the discriminant member, so we can record it later in the
15666      discriminant_info.  */
15667   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15668   sect_offset discr_offset {};
15669   bool has_template_parameters = false;
15670
15671   if (is_variant_part)
15672     {
15673       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15674       if (discr == NULL)
15675         {
15676           /* Maybe it's a univariant form, an extension we support.
15677              In this case arrange not to check the offset.  */
15678           is_variant_part = false;
15679         }
15680       else if (discr->form_is_ref ())
15681         {
15682           struct dwarf2_cu *target_cu = cu;
15683           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15684
15685           discr_offset = target_die->sect_off;
15686         }
15687       else
15688         {
15689           complaint (_("DW_AT_discr does not have DIE reference form"
15690                        " - DIE at %s [in module %s]"),
15691                      sect_offset_str (die->sect_off),
15692                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15693           is_variant_part = false;
15694         }
15695     }
15696
15697   if (die->child != NULL && ! die_is_declaration (die, cu))
15698     {
15699       struct field_info fi;
15700       std::vector<struct symbol *> template_args;
15701
15702       child_die = die->child;
15703
15704       while (child_die && child_die->tag)
15705         {
15706           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15707
15708           if (is_variant_part && discr_offset == child_die->sect_off)
15709             fi.fields.back ().variant.is_discriminant = true;
15710
15711           child_die = sibling_die (child_die);
15712         }
15713
15714       /* Attach template arguments to type.  */
15715       if (!template_args.empty ())
15716         {
15717           has_template_parameters = true;
15718           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15719           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15720           TYPE_TEMPLATE_ARGUMENTS (type)
15721             = XOBNEWVEC (&objfile->objfile_obstack,
15722                          struct symbol *,
15723                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15724           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15725                   template_args.data (),
15726                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15727                    * sizeof (struct symbol *)));
15728         }
15729
15730       /* Attach fields and member functions to the type.  */
15731       if (fi.nfields)
15732         dwarf2_attach_fields_to_type (&fi, type, cu);
15733       if (!fi.fnfieldlists.empty ())
15734         {
15735           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15736
15737           /* Get the type which refers to the base class (possibly this
15738              class itself) which contains the vtable pointer for the current
15739              class from the DW_AT_containing_type attribute.  This use of
15740              DW_AT_containing_type is a GNU extension.  */
15741
15742           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15743             {
15744               struct type *t = die_containing_type (die, cu);
15745
15746               set_type_vptr_basetype (type, t);
15747               if (type == t)
15748                 {
15749                   int i;
15750
15751                   /* Our own class provides vtbl ptr.  */
15752                   for (i = TYPE_NFIELDS (t) - 1;
15753                        i >= TYPE_N_BASECLASSES (t);
15754                        --i)
15755                     {
15756                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15757
15758                       if (is_vtable_name (fieldname, cu))
15759                         {
15760                           set_type_vptr_fieldno (type, i);
15761                           break;
15762                         }
15763                     }
15764
15765                   /* Complain if virtual function table field not found.  */
15766                   if (i < TYPE_N_BASECLASSES (t))
15767                     complaint (_("virtual function table pointer "
15768                                  "not found when defining class '%s'"),
15769                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15770                 }
15771               else
15772                 {
15773                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15774                 }
15775             }
15776           else if (cu->producer
15777                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15778             {
15779               /* The IBM XLC compiler does not provide direct indication
15780                  of the containing type, but the vtable pointer is
15781                  always named __vfp.  */
15782
15783               int i;
15784
15785               for (i = TYPE_NFIELDS (type) - 1;
15786                    i >= TYPE_N_BASECLASSES (type);
15787                    --i)
15788                 {
15789                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15790                     {
15791                       set_type_vptr_fieldno (type, i);
15792                       set_type_vptr_basetype (type, type);
15793                       break;
15794                     }
15795                 }
15796             }
15797         }
15798
15799       /* Copy fi.typedef_field_list linked list elements content into the
15800          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15801       if (!fi.typedef_field_list.empty ())
15802         {
15803           int count = fi.typedef_field_list.size ();
15804
15805           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15806           TYPE_TYPEDEF_FIELD_ARRAY (type)
15807             = ((struct decl_field *)
15808                TYPE_ALLOC (type,
15809                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
15810           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
15811
15812           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
15813             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
15814         }
15815
15816       /* Copy fi.nested_types_list linked list elements content into the
15817          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15818       if (!fi.nested_types_list.empty () && cu->language != language_ada)
15819         {
15820           int count = fi.nested_types_list.size ();
15821
15822           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15823           TYPE_NESTED_TYPES_ARRAY (type)
15824             = ((struct decl_field *)
15825                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
15826           TYPE_NESTED_TYPES_COUNT (type) = count;
15827
15828           for (int i = 0; i < fi.nested_types_list.size (); ++i)
15829             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
15830         }
15831     }
15832
15833   quirk_gcc_member_function_pointer (type, objfile);
15834   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
15835     cu->rust_unions.push_back (type);
15836
15837   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
15838      snapshots) has been known to create a die giving a declaration
15839      for a class that has, as a child, a die giving a definition for a
15840      nested class.  So we have to process our children even if the
15841      current die is a declaration.  Normally, of course, a declaration
15842      won't have any children at all.  */
15843
15844   child_die = die->child;
15845
15846   while (child_die != NULL && child_die->tag)
15847     {
15848       if (child_die->tag == DW_TAG_member
15849           || child_die->tag == DW_TAG_variable
15850           || child_die->tag == DW_TAG_inheritance
15851           || child_die->tag == DW_TAG_template_value_param
15852           || child_die->tag == DW_TAG_template_type_param)
15853         {
15854           /* Do nothing.  */
15855         }
15856       else
15857         process_die (child_die, cu);
15858
15859       child_die = sibling_die (child_die);
15860     }
15861
15862   /* Do not consider external references.  According to the DWARF standard,
15863      these DIEs are identified by the fact that they have no byte_size
15864      attribute, and a declaration attribute.  */
15865   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
15866       || !die_is_declaration (die, cu))
15867     {
15868       struct symbol *sym = new_symbol (die, type, cu);
15869
15870       if (has_template_parameters)
15871         {
15872           struct symtab *symtab;
15873           if (sym != nullptr)
15874             symtab = symbol_symtab (sym);
15875           else if (cu->line_header != nullptr)
15876             {
15877               /* Any related symtab will do.  */
15878               symtab
15879                 = cu->line_header->file_names ()[0].symtab;
15880             }
15881           else
15882             {
15883               symtab = nullptr;
15884               complaint (_("could not find suitable "
15885                            "symtab for template parameter"
15886                            " - DIE at %s [in module %s]"),
15887                          sect_offset_str (die->sect_off),
15888                          objfile_name (objfile));
15889             }
15890
15891           if (symtab != nullptr)
15892             {
15893               /* Make sure that the symtab is set on the new symbols.
15894                  Even though they don't appear in this symtab directly,
15895                  other parts of gdb assume that symbols do, and this is
15896                  reasonably true.  */
15897               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
15898                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
15899             }
15900         }
15901     }
15902 }
15903
15904 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
15905    update TYPE using some information only available in DIE's children.  */
15906
15907 static void
15908 update_enumeration_type_from_children (struct die_info *die,
15909                                        struct type *type,
15910                                        struct dwarf2_cu *cu)
15911 {
15912   struct die_info *child_die;
15913   int unsigned_enum = 1;
15914   int flag_enum = 1;
15915   ULONGEST mask = 0;
15916
15917   auto_obstack obstack;
15918
15919   for (child_die = die->child;
15920        child_die != NULL && child_die->tag;
15921        child_die = sibling_die (child_die))
15922     {
15923       struct attribute *attr;
15924       LONGEST value;
15925       const gdb_byte *bytes;
15926       struct dwarf2_locexpr_baton *baton;
15927       const char *name;
15928
15929       if (child_die->tag != DW_TAG_enumerator)
15930         continue;
15931
15932       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
15933       if (attr == NULL)
15934         continue;
15935
15936       name = dwarf2_name (child_die, cu);
15937       if (name == NULL)
15938         name = "<anonymous enumerator>";
15939
15940       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
15941                                &value, &bytes, &baton);
15942       if (value < 0)
15943         {
15944           unsigned_enum = 0;
15945           flag_enum = 0;
15946         }
15947       else if ((mask & value) != 0)
15948         flag_enum = 0;
15949       else
15950         mask |= value;
15951
15952       /* If we already know that the enum type is neither unsigned, nor
15953          a flag type, no need to look at the rest of the enumerates.  */
15954       if (!unsigned_enum && !flag_enum)
15955         break;
15956     }
15957
15958   if (unsigned_enum)
15959     TYPE_UNSIGNED (type) = 1;
15960   if (flag_enum)
15961     TYPE_FLAG_ENUM (type) = 1;
15962 }
15963
15964 /* Given a DW_AT_enumeration_type die, set its type.  We do not
15965    complete the type's fields yet, or create any symbols.  */
15966
15967 static struct type *
15968 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
15969 {
15970   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15971   struct type *type;
15972   struct attribute *attr;
15973   const char *name;
15974
15975   /* If the definition of this type lives in .debug_types, read that type.
15976      Don't follow DW_AT_specification though, that will take us back up
15977      the chain and we want to go down.  */
15978   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15979   if (attr != nullptr)
15980     {
15981       type = get_DW_AT_signature_type (die, attr, cu);
15982
15983       /* The type's CU may not be the same as CU.
15984          Ensure TYPE is recorded with CU in die_type_hash.  */
15985       return set_die_type (die, type, cu);
15986     }
15987
15988   type = alloc_type (objfile);
15989
15990   TYPE_CODE (type) = TYPE_CODE_ENUM;
15991   name = dwarf2_full_name (NULL, die, cu);
15992   if (name != NULL)
15993     TYPE_NAME (type) = name;
15994
15995   attr = dwarf2_attr (die, DW_AT_type, cu);
15996   if (attr != NULL)
15997     {
15998       struct type *underlying_type = die_type (die, cu);
15999
16000       TYPE_TARGET_TYPE (type) = underlying_type;
16001     }
16002
16003   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16004   if (attr != nullptr)
16005     {
16006       TYPE_LENGTH (type) = DW_UNSND (attr);
16007     }
16008   else
16009     {
16010       TYPE_LENGTH (type) = 0;
16011     }
16012
16013   maybe_set_alignment (cu, die, type);
16014
16015   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16016      declared as private in the package spec, and then defined only
16017      inside the package body.  Such types are known as Taft Amendment
16018      Types.  When another package uses such a type, an incomplete DIE
16019      may be generated by the compiler.  */
16020   if (die_is_declaration (die, cu))
16021     TYPE_STUB (type) = 1;
16022
16023   /* Finish the creation of this type by using the enum's children.
16024      We must call this even when the underlying type has been provided
16025      so that we can determine if we're looking at a "flag" enum.  */
16026   update_enumeration_type_from_children (die, type, cu);
16027
16028   /* If this type has an underlying type that is not a stub, then we
16029      may use its attributes.  We always use the "unsigned" attribute
16030      in this situation, because ordinarily we guess whether the type
16031      is unsigned -- but the guess can be wrong and the underlying type
16032      can tell us the reality.  However, we defer to a local size
16033      attribute if one exists, because this lets the compiler override
16034      the underlying type if needed.  */
16035   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16036     {
16037       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16038       if (TYPE_LENGTH (type) == 0)
16039         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16040       if (TYPE_RAW_ALIGN (type) == 0
16041           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16042         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16043     }
16044
16045   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16046
16047   return set_die_type (die, type, cu);
16048 }
16049
16050 /* Given a pointer to a die which begins an enumeration, process all
16051    the dies that define the members of the enumeration, and create the
16052    symbol for the enumeration type.
16053
16054    NOTE: We reverse the order of the element list.  */
16055
16056 static void
16057 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16058 {
16059   struct type *this_type;
16060
16061   this_type = get_die_type (die, cu);
16062   if (this_type == NULL)
16063     this_type = read_enumeration_type (die, cu);
16064
16065   if (die->child != NULL)
16066     {
16067       struct die_info *child_die;
16068       struct symbol *sym;
16069       std::vector<struct field> fields;
16070       const char *name;
16071
16072       child_die = die->child;
16073       while (child_die && child_die->tag)
16074         {
16075           if (child_die->tag != DW_TAG_enumerator)
16076             {
16077               process_die (child_die, cu);
16078             }
16079           else
16080             {
16081               name = dwarf2_name (child_die, cu);
16082               if (name)
16083                 {
16084                   sym = new_symbol (child_die, this_type, cu);
16085
16086                   fields.emplace_back ();
16087                   struct field &field = fields.back ();
16088
16089                   FIELD_NAME (field) = sym->linkage_name ();
16090                   FIELD_TYPE (field) = NULL;
16091                   SET_FIELD_ENUMVAL (field, SYMBOL_VALUE (sym));
16092                   FIELD_BITSIZE (field) = 0;
16093                 }
16094             }
16095
16096           child_die = sibling_die (child_die);
16097         }
16098
16099       if (!fields.empty ())
16100         {
16101           TYPE_NFIELDS (this_type) = fields.size ();
16102           TYPE_FIELDS (this_type) = (struct field *)
16103             TYPE_ALLOC (this_type, sizeof (struct field) * fields.size ());
16104           memcpy (TYPE_FIELDS (this_type), fields.data (),
16105                   sizeof (struct field) * fields.size ());
16106         }
16107     }
16108
16109   /* If we are reading an enum from a .debug_types unit, and the enum
16110      is a declaration, and the enum is not the signatured type in the
16111      unit, then we do not want to add a symbol for it.  Adding a
16112      symbol would in some cases obscure the true definition of the
16113      enum, giving users an incomplete type when the definition is
16114      actually available.  Note that we do not want to do this for all
16115      enums which are just declarations, because C++0x allows forward
16116      enum declarations.  */
16117   if (cu->per_cu->is_debug_types
16118       && die_is_declaration (die, cu))
16119     {
16120       struct signatured_type *sig_type;
16121
16122       sig_type = (struct signatured_type *) cu->per_cu;
16123       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16124       if (sig_type->type_offset_in_section != die->sect_off)
16125         return;
16126     }
16127
16128   new_symbol (die, this_type, cu);
16129 }
16130
16131 /* Extract all information from a DW_TAG_array_type DIE and put it in
16132    the DIE's type field.  For now, this only handles one dimensional
16133    arrays.  */
16134
16135 static struct type *
16136 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16137 {
16138   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16139   struct die_info *child_die;
16140   struct type *type;
16141   struct type *element_type, *range_type, *index_type;
16142   struct attribute *attr;
16143   const char *name;
16144   struct dynamic_prop *byte_stride_prop = NULL;
16145   unsigned int bit_stride = 0;
16146
16147   element_type = die_type (die, cu);
16148
16149   /* The die_type call above may have already set the type for this DIE.  */
16150   type = get_die_type (die, cu);
16151   if (type)
16152     return type;
16153
16154   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16155   if (attr != NULL)
16156     {
16157       int stride_ok;
16158       struct type *prop_type
16159         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
16160
16161       byte_stride_prop
16162         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16163       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop,
16164                                         prop_type);
16165       if (!stride_ok)
16166         {
16167           complaint (_("unable to read array DW_AT_byte_stride "
16168                        " - DIE at %s [in module %s]"),
16169                      sect_offset_str (die->sect_off),
16170                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16171           /* Ignore this attribute.  We will likely not be able to print
16172              arrays of this type correctly, but there is little we can do
16173              to help if we cannot read the attribute's value.  */
16174           byte_stride_prop = NULL;
16175         }
16176     }
16177
16178   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16179   if (attr != NULL)
16180     bit_stride = DW_UNSND (attr);
16181
16182   /* Irix 6.2 native cc creates array types without children for
16183      arrays with unspecified length.  */
16184   if (die->child == NULL)
16185     {
16186       index_type = objfile_type (objfile)->builtin_int;
16187       range_type = create_static_range_type (NULL, index_type, 0, -1);
16188       type = create_array_type_with_stride (NULL, element_type, range_type,
16189                                             byte_stride_prop, bit_stride);
16190       return set_die_type (die, type, cu);
16191     }
16192
16193   std::vector<struct type *> range_types;
16194   child_die = die->child;
16195   while (child_die && child_die->tag)
16196     {
16197       if (child_die->tag == DW_TAG_subrange_type)
16198         {
16199           struct type *child_type = read_type_die (child_die, cu);
16200
16201           if (child_type != NULL)
16202             {
16203               /* The range type was succesfully read.  Save it for the
16204                  array type creation.  */
16205               range_types.push_back (child_type);
16206             }
16207         }
16208       child_die = sibling_die (child_die);
16209     }
16210
16211   /* Dwarf2 dimensions are output from left to right, create the
16212      necessary array types in backwards order.  */
16213
16214   type = element_type;
16215
16216   if (read_array_order (die, cu) == DW_ORD_col_major)
16217     {
16218       int i = 0;
16219
16220       while (i < range_types.size ())
16221         type = create_array_type_with_stride (NULL, type, range_types[i++],
16222                                               byte_stride_prop, bit_stride);
16223     }
16224   else
16225     {
16226       size_t ndim = range_types.size ();
16227       while (ndim-- > 0)
16228         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16229                                               byte_stride_prop, bit_stride);
16230     }
16231
16232   /* Understand Dwarf2 support for vector types (like they occur on
16233      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16234      array type.  This is not part of the Dwarf2/3 standard yet, but a
16235      custom vendor extension.  The main difference between a regular
16236      array and the vector variant is that vectors are passed by value
16237      to functions.  */
16238   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16239   if (attr != nullptr)
16240     make_vector_type (type);
16241
16242   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16243      implementation may choose to implement triple vectors using this
16244      attribute.  */
16245   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16246   if (attr != nullptr)
16247     {
16248       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16249         TYPE_LENGTH (type) = DW_UNSND (attr);
16250       else
16251         complaint (_("DW_AT_byte_size for array type smaller "
16252                      "than the total size of elements"));
16253     }
16254
16255   name = dwarf2_name (die, cu);
16256   if (name)
16257     TYPE_NAME (type) = name;
16258
16259   maybe_set_alignment (cu, die, type);
16260
16261   /* Install the type in the die.  */
16262   set_die_type (die, type, cu);
16263
16264   /* set_die_type should be already done.  */
16265   set_descriptive_type (type, die, cu);
16266
16267   return type;
16268 }
16269
16270 static enum dwarf_array_dim_ordering
16271 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16272 {
16273   struct attribute *attr;
16274
16275   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16276
16277   if (attr != nullptr)
16278     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16279
16280   /* GNU F77 is a special case, as at 08/2004 array type info is the
16281      opposite order to the dwarf2 specification, but data is still
16282      laid out as per normal fortran.
16283
16284      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16285      version checking.  */
16286
16287   if (cu->language == language_fortran
16288       && cu->producer && strstr (cu->producer, "GNU F77"))
16289     {
16290       return DW_ORD_row_major;
16291     }
16292
16293   switch (cu->language_defn->la_array_ordering)
16294     {
16295     case array_column_major:
16296       return DW_ORD_col_major;
16297     case array_row_major:
16298     default:
16299       return DW_ORD_row_major;
16300     };
16301 }
16302
16303 /* Extract all information from a DW_TAG_set_type DIE and put it in
16304    the DIE's type field.  */
16305
16306 static struct type *
16307 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16308 {
16309   struct type *domain_type, *set_type;
16310   struct attribute *attr;
16311
16312   domain_type = die_type (die, cu);
16313
16314   /* The die_type call above may have already set the type for this DIE.  */
16315   set_type = get_die_type (die, cu);
16316   if (set_type)
16317     return set_type;
16318
16319   set_type = create_set_type (NULL, domain_type);
16320
16321   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16322   if (attr != nullptr)
16323     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16324
16325   maybe_set_alignment (cu, die, set_type);
16326
16327   return set_die_type (die, set_type, cu);
16328 }
16329
16330 /* A helper for read_common_block that creates a locexpr baton.
16331    SYM is the symbol which we are marking as computed.
16332    COMMON_DIE is the DIE for the common block.
16333    COMMON_LOC is the location expression attribute for the common
16334    block itself.
16335    MEMBER_LOC is the location expression attribute for the particular
16336    member of the common block that we are processing.
16337    CU is the CU from which the above come.  */
16338
16339 static void
16340 mark_common_block_symbol_computed (struct symbol *sym,
16341                                    struct die_info *common_die,
16342                                    struct attribute *common_loc,
16343                                    struct attribute *member_loc,
16344                                    struct dwarf2_cu *cu)
16345 {
16346   struct dwarf2_per_objfile *dwarf2_per_objfile
16347     = cu->per_cu->dwarf2_per_objfile;
16348   struct objfile *objfile = dwarf2_per_objfile->objfile;
16349   struct dwarf2_locexpr_baton *baton;
16350   gdb_byte *ptr;
16351   unsigned int cu_off;
16352   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16353   LONGEST offset = 0;
16354
16355   gdb_assert (common_loc && member_loc);
16356   gdb_assert (common_loc->form_is_block ());
16357   gdb_assert (member_loc->form_is_block ()
16358               || member_loc->form_is_constant ());
16359
16360   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16361   baton->per_cu = cu->per_cu;
16362   gdb_assert (baton->per_cu);
16363
16364   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16365
16366   if (member_loc->form_is_constant ())
16367     {
16368       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16369       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16370     }
16371   else
16372     baton->size += DW_BLOCK (member_loc)->size;
16373
16374   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16375   baton->data = ptr;
16376
16377   *ptr++ = DW_OP_call4;
16378   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16379   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16380   ptr += 4;
16381
16382   if (member_loc->form_is_constant ())
16383     {
16384       *ptr++ = DW_OP_addr;
16385       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16386       ptr += cu->header.addr_size;
16387     }
16388   else
16389     {
16390       /* We have to copy the data here, because DW_OP_call4 will only
16391          use a DW_AT_location attribute.  */
16392       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16393       ptr += DW_BLOCK (member_loc)->size;
16394     }
16395
16396   *ptr++ = DW_OP_plus;
16397   gdb_assert (ptr - baton->data == baton->size);
16398
16399   SYMBOL_LOCATION_BATON (sym) = baton;
16400   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16401 }
16402
16403 /* Create appropriate locally-scoped variables for all the
16404    DW_TAG_common_block entries.  Also create a struct common_block
16405    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16406    is used to separate the common blocks name namespace from regular
16407    variable names.  */
16408
16409 static void
16410 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16411 {
16412   struct attribute *attr;
16413
16414   attr = dwarf2_attr (die, DW_AT_location, cu);
16415   if (attr != nullptr)
16416     {
16417       /* Support the .debug_loc offsets.  */
16418       if (attr->form_is_block ())
16419         {
16420           /* Ok.  */
16421         }
16422       else if (attr->form_is_section_offset ())
16423         {
16424           dwarf2_complex_location_expr_complaint ();
16425           attr = NULL;
16426         }
16427       else
16428         {
16429           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16430                                                  "common block member");
16431           attr = NULL;
16432         }
16433     }
16434
16435   if (die->child != NULL)
16436     {
16437       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16438       struct die_info *child_die;
16439       size_t n_entries = 0, size;
16440       struct common_block *common_block;
16441       struct symbol *sym;
16442
16443       for (child_die = die->child;
16444            child_die && child_die->tag;
16445            child_die = sibling_die (child_die))
16446         ++n_entries;
16447
16448       size = (sizeof (struct common_block)
16449               + (n_entries - 1) * sizeof (struct symbol *));
16450       common_block
16451         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16452                                                  size);
16453       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16454       common_block->n_entries = 0;
16455
16456       for (child_die = die->child;
16457            child_die && child_die->tag;
16458            child_die = sibling_die (child_die))
16459         {
16460           /* Create the symbol in the DW_TAG_common_block block in the current
16461              symbol scope.  */
16462           sym = new_symbol (child_die, NULL, cu);
16463           if (sym != NULL)
16464             {
16465               struct attribute *member_loc;
16466
16467               common_block->contents[common_block->n_entries++] = sym;
16468
16469               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16470                                         cu);
16471               if (member_loc)
16472                 {
16473                   /* GDB has handled this for a long time, but it is
16474                      not specified by DWARF.  It seems to have been
16475                      emitted by gfortran at least as recently as:
16476                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16477                   complaint (_("Variable in common block has "
16478                                "DW_AT_data_member_location "
16479                                "- DIE at %s [in module %s]"),
16480                                sect_offset_str (child_die->sect_off),
16481                              objfile_name (objfile));
16482
16483                   if (member_loc->form_is_section_offset ())
16484                     dwarf2_complex_location_expr_complaint ();
16485                   else if (member_loc->form_is_constant ()
16486                            || member_loc->form_is_block ())
16487                     {
16488                       if (attr != nullptr)
16489                         mark_common_block_symbol_computed (sym, die, attr,
16490                                                            member_loc, cu);
16491                     }
16492                   else
16493                     dwarf2_complex_location_expr_complaint ();
16494                 }
16495             }
16496         }
16497
16498       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16499       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16500     }
16501 }
16502
16503 /* Create a type for a C++ namespace.  */
16504
16505 static struct type *
16506 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16507 {
16508   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16509   const char *previous_prefix, *name;
16510   int is_anonymous;
16511   struct type *type;
16512
16513   /* For extensions, reuse the type of the original namespace.  */
16514   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16515     {
16516       struct die_info *ext_die;
16517       struct dwarf2_cu *ext_cu = cu;
16518
16519       ext_die = dwarf2_extension (die, &ext_cu);
16520       type = read_type_die (ext_die, ext_cu);
16521
16522       /* EXT_CU may not be the same as CU.
16523          Ensure TYPE is recorded with CU in die_type_hash.  */
16524       return set_die_type (die, type, cu);
16525     }
16526
16527   name = namespace_name (die, &is_anonymous, cu);
16528
16529   /* Now build the name of the current namespace.  */
16530
16531   previous_prefix = determine_prefix (die, cu);
16532   if (previous_prefix[0] != '\0')
16533     name = typename_concat (&objfile->objfile_obstack,
16534                             previous_prefix, name, 0, cu);
16535
16536   /* Create the type.  */
16537   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16538
16539   return set_die_type (die, type, cu);
16540 }
16541
16542 /* Read a namespace scope.  */
16543
16544 static void
16545 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16546 {
16547   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16548   int is_anonymous;
16549
16550   /* Add a symbol associated to this if we haven't seen the namespace
16551      before.  Also, add a using directive if it's an anonymous
16552      namespace.  */
16553
16554   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16555     {
16556       struct type *type;
16557
16558       type = read_type_die (die, cu);
16559       new_symbol (die, type, cu);
16560
16561       namespace_name (die, &is_anonymous, cu);
16562       if (is_anonymous)
16563         {
16564           const char *previous_prefix = determine_prefix (die, cu);
16565
16566           std::vector<const char *> excludes;
16567           add_using_directive (using_directives (cu),
16568                                previous_prefix, TYPE_NAME (type), NULL,
16569                                NULL, excludes, 0, &objfile->objfile_obstack);
16570         }
16571     }
16572
16573   if (die->child != NULL)
16574     {
16575       struct die_info *child_die = die->child;
16576
16577       while (child_die && child_die->tag)
16578         {
16579           process_die (child_die, cu);
16580           child_die = sibling_die (child_die);
16581         }
16582     }
16583 }
16584
16585 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16586    imported module.  Still we need that type as local Fortran "use ... only"
16587    declaration imports depend on the created type in determine_prefix.  */
16588
16589 static struct type *
16590 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16591 {
16592   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16593   const char *module_name;
16594   struct type *type;
16595
16596   module_name = dwarf2_name (die, cu);
16597   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16598
16599   return set_die_type (die, type, cu);
16600 }
16601
16602 /* Read a Fortran module.  */
16603
16604 static void
16605 read_module (struct die_info *die, struct dwarf2_cu *cu)
16606 {
16607   struct die_info *child_die = die->child;
16608   struct type *type;
16609
16610   type = read_type_die (die, cu);
16611   new_symbol (die, type, cu);
16612
16613   while (child_die && child_die->tag)
16614     {
16615       process_die (child_die, cu);
16616       child_die = sibling_die (child_die);
16617     }
16618 }
16619
16620 /* Return the name of the namespace represented by DIE.  Set
16621    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16622    namespace.  */
16623
16624 static const char *
16625 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16626 {
16627   struct die_info *current_die;
16628   const char *name = NULL;
16629
16630   /* Loop through the extensions until we find a name.  */
16631
16632   for (current_die = die;
16633        current_die != NULL;
16634        current_die = dwarf2_extension (die, &cu))
16635     {
16636       /* We don't use dwarf2_name here so that we can detect the absence
16637          of a name -> anonymous namespace.  */
16638       name = dwarf2_string_attr (die, DW_AT_name, cu);
16639
16640       if (name != NULL)
16641         break;
16642     }
16643
16644   /* Is it an anonymous namespace?  */
16645
16646   *is_anonymous = (name == NULL);
16647   if (*is_anonymous)
16648     name = CP_ANONYMOUS_NAMESPACE_STR;
16649
16650   return name;
16651 }
16652
16653 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16654    the user defined type vector.  */
16655
16656 static struct type *
16657 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16658 {
16659   struct gdbarch *gdbarch
16660     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16661   struct comp_unit_head *cu_header = &cu->header;
16662   struct type *type;
16663   struct attribute *attr_byte_size;
16664   struct attribute *attr_address_class;
16665   int byte_size, addr_class;
16666   struct type *target_type;
16667
16668   target_type = die_type (die, cu);
16669
16670   /* The die_type call above may have already set the type for this DIE.  */
16671   type = get_die_type (die, cu);
16672   if (type)
16673     return type;
16674
16675   type = lookup_pointer_type (target_type);
16676
16677   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16678   if (attr_byte_size)
16679     byte_size = DW_UNSND (attr_byte_size);
16680   else
16681     byte_size = cu_header->addr_size;
16682
16683   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16684   if (attr_address_class)
16685     addr_class = DW_UNSND (attr_address_class);
16686   else
16687     addr_class = DW_ADDR_none;
16688
16689   ULONGEST alignment = get_alignment (cu, die);
16690
16691   /* If the pointer size, alignment, or address class is different
16692      than the default, create a type variant marked as such and set
16693      the length accordingly.  */
16694   if (TYPE_LENGTH (type) != byte_size
16695       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16696           && alignment != TYPE_RAW_ALIGN (type))
16697       || addr_class != DW_ADDR_none)
16698     {
16699       if (gdbarch_address_class_type_flags_p (gdbarch))
16700         {
16701           int type_flags;
16702
16703           type_flags = gdbarch_address_class_type_flags
16704                          (gdbarch, byte_size, addr_class);
16705           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16706                       == 0);
16707           type = make_type_with_address_space (type, type_flags);
16708         }
16709       else if (TYPE_LENGTH (type) != byte_size)
16710         {
16711           complaint (_("invalid pointer size %d"), byte_size);
16712         }
16713       else if (TYPE_RAW_ALIGN (type) != alignment)
16714         {
16715           complaint (_("Invalid DW_AT_alignment"
16716                        " - DIE at %s [in module %s]"),
16717                      sect_offset_str (die->sect_off),
16718                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16719         }
16720       else
16721         {
16722           /* Should we also complain about unhandled address classes?  */
16723         }
16724     }
16725
16726   TYPE_LENGTH (type) = byte_size;
16727   set_type_align (type, alignment);
16728   return set_die_type (die, type, cu);
16729 }
16730
16731 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16732    the user defined type vector.  */
16733
16734 static struct type *
16735 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16736 {
16737   struct type *type;
16738   struct type *to_type;
16739   struct type *domain;
16740
16741   to_type = die_type (die, cu);
16742   domain = die_containing_type (die, cu);
16743
16744   /* The calls above may have already set the type for this DIE.  */
16745   type = get_die_type (die, cu);
16746   if (type)
16747     return type;
16748
16749   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16750     type = lookup_methodptr_type (to_type);
16751   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16752     {
16753       struct type *new_type
16754         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16755
16756       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16757                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16758                             TYPE_VARARGS (to_type));
16759       type = lookup_methodptr_type (new_type);
16760     }
16761   else
16762     type = lookup_memberptr_type (to_type, domain);
16763
16764   return set_die_type (die, type, cu);
16765 }
16766
16767 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16768    the user defined type vector.  */
16769
16770 static struct type *
16771 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16772                           enum type_code refcode)
16773 {
16774   struct comp_unit_head *cu_header = &cu->header;
16775   struct type *type, *target_type;
16776   struct attribute *attr;
16777
16778   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16779
16780   target_type = die_type (die, cu);
16781
16782   /* The die_type call above may have already set the type for this DIE.  */
16783   type = get_die_type (die, cu);
16784   if (type)
16785     return type;
16786
16787   type = lookup_reference_type (target_type, refcode);
16788   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16789   if (attr != nullptr)
16790     {
16791       TYPE_LENGTH (type) = DW_UNSND (attr);
16792     }
16793   else
16794     {
16795       TYPE_LENGTH (type) = cu_header->addr_size;
16796     }
16797   maybe_set_alignment (cu, die, type);
16798   return set_die_type (die, type, cu);
16799 }
16800
16801 /* Add the given cv-qualifiers to the element type of the array.  GCC
16802    outputs DWARF type qualifiers that apply to an array, not the
16803    element type.  But GDB relies on the array element type to carry
16804    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16805    specification.  */
16806
16807 static struct type *
16808 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16809                    struct type *base_type, int cnst, int voltl)
16810 {
16811   struct type *el_type, *inner_array;
16812
16813   base_type = copy_type (base_type);
16814   inner_array = base_type;
16815
16816   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16817     {
16818       TYPE_TARGET_TYPE (inner_array) =
16819         copy_type (TYPE_TARGET_TYPE (inner_array));
16820       inner_array = TYPE_TARGET_TYPE (inner_array);
16821     }
16822
16823   el_type = TYPE_TARGET_TYPE (inner_array);
16824   cnst |= TYPE_CONST (el_type);
16825   voltl |= TYPE_VOLATILE (el_type);
16826   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16827
16828   return set_die_type (die, base_type, cu);
16829 }
16830
16831 static struct type *
16832 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16833 {
16834   struct type *base_type, *cv_type;
16835
16836   base_type = die_type (die, cu);
16837
16838   /* The die_type call above may have already set the type for this DIE.  */
16839   cv_type = get_die_type (die, cu);
16840   if (cv_type)
16841     return cv_type;
16842
16843   /* In case the const qualifier is applied to an array type, the element type
16844      is so qualified, not the array type (section 6.7.3 of C99).  */
16845   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16846     return add_array_cv_type (die, cu, base_type, 1, 0);
16847
16848   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16849   return set_die_type (die, cv_type, cu);
16850 }
16851
16852 static struct type *
16853 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16854 {
16855   struct type *base_type, *cv_type;
16856
16857   base_type = die_type (die, cu);
16858
16859   /* The die_type call above may have already set the type for this DIE.  */
16860   cv_type = get_die_type (die, cu);
16861   if (cv_type)
16862     return cv_type;
16863
16864   /* In case the volatile qualifier is applied to an array type, the
16865      element type is so qualified, not the array type (section 6.7.3
16866      of C99).  */
16867   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16868     return add_array_cv_type (die, cu, base_type, 0, 1);
16869
16870   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
16871   return set_die_type (die, cv_type, cu);
16872 }
16873
16874 /* Handle DW_TAG_restrict_type.  */
16875
16876 static struct type *
16877 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
16878 {
16879   struct type *base_type, *cv_type;
16880
16881   base_type = die_type (die, cu);
16882
16883   /* The die_type call above may have already set the type for this DIE.  */
16884   cv_type = get_die_type (die, cu);
16885   if (cv_type)
16886     return cv_type;
16887
16888   cv_type = make_restrict_type (base_type);
16889   return set_die_type (die, cv_type, cu);
16890 }
16891
16892 /* Handle DW_TAG_atomic_type.  */
16893
16894 static struct type *
16895 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
16896 {
16897   struct type *base_type, *cv_type;
16898
16899   base_type = die_type (die, cu);
16900
16901   /* The die_type call above may have already set the type for this DIE.  */
16902   cv_type = get_die_type (die, cu);
16903   if (cv_type)
16904     return cv_type;
16905
16906   cv_type = make_atomic_type (base_type);
16907   return set_die_type (die, cv_type, cu);
16908 }
16909
16910 /* Extract all information from a DW_TAG_string_type DIE and add to
16911    the user defined type vector.  It isn't really a user defined type,
16912    but it behaves like one, with other DIE's using an AT_user_def_type
16913    attribute to reference it.  */
16914
16915 static struct type *
16916 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
16917 {
16918   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16919   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16920   struct type *type, *range_type, *index_type, *char_type;
16921   struct attribute *attr;
16922   struct dynamic_prop prop;
16923   bool length_is_constant = true;
16924   LONGEST length;
16925
16926   /* There are a couple of places where bit sizes might be made use of
16927      when parsing a DW_TAG_string_type, however, no producer that we know
16928      of make use of these.  Handling bit sizes that are a multiple of the
16929      byte size is easy enough, but what about other bit sizes?  Lets deal
16930      with that problem when we have to.  Warn about these attributes being
16931      unsupported, then parse the type and ignore them like we always
16932      have.  */
16933   if (dwarf2_attr (die, DW_AT_bit_size, cu) != nullptr
16934       || dwarf2_attr (die, DW_AT_string_length_bit_size, cu) != nullptr)
16935     {
16936       static bool warning_printed = false;
16937       if (!warning_printed)
16938         {
16939           warning (_("DW_AT_bit_size and DW_AT_string_length_bit_size not "
16940                      "currently supported on DW_TAG_string_type."));
16941           warning_printed = true;
16942         }
16943     }
16944
16945   attr = dwarf2_attr (die, DW_AT_string_length, cu);
16946   if (attr != nullptr && !attr->form_is_constant ())
16947     {
16948       /* The string length describes the location at which the length of
16949          the string can be found.  The size of the length field can be
16950          specified with one of the attributes below.  */
16951       struct type *prop_type;
16952       struct attribute *len
16953         = dwarf2_attr (die, DW_AT_string_length_byte_size, cu);
16954       if (len == nullptr)
16955         len = dwarf2_attr (die, DW_AT_byte_size, cu);
16956       if (len != nullptr && len->form_is_constant ())
16957         {
16958           /* Pass 0 as the default as we know this attribute is constant
16959              and the default value will not be returned.  */
16960           LONGEST sz = dwarf2_get_attr_constant_value (len, 0);
16961           prop_type = dwarf2_per_cu_int_type (cu->per_cu, sz, true);
16962         }
16963       else
16964         {
16965           /* If the size is not specified then we assume it is the size of
16966              an address on this target.  */
16967           prop_type = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, true);
16968         }
16969
16970       /* Convert the attribute into a dynamic property.  */
16971       if (!attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
16972         length = 1;
16973       else
16974         length_is_constant = false;
16975     }
16976   else if (attr != nullptr)
16977     {
16978       /* This DW_AT_string_length just contains the length with no
16979          indirection.  There's no need to create a dynamic property in this
16980          case.  Pass 0 for the default value as we know it will not be
16981          returned in this case.  */
16982       length = dwarf2_get_attr_constant_value (attr, 0);
16983     }
16984   else if ((attr = dwarf2_attr (die, DW_AT_byte_size, cu)) != nullptr)
16985     {
16986       /* We don't currently support non-constant byte sizes for strings.  */
16987       length = dwarf2_get_attr_constant_value (attr, 1);
16988     }
16989   else
16990     {
16991       /* Use 1 as a fallback length if we have nothing else.  */
16992       length = 1;
16993     }
16994
16995   index_type = objfile_type (objfile)->builtin_int;
16996   if (length_is_constant)
16997     range_type = create_static_range_type (NULL, index_type, 1, length);
16998   else
16999     {
17000       struct dynamic_prop low_bound;
17001
17002       low_bound.kind = PROP_CONST;
17003       low_bound.data.const_val = 1;
17004       range_type = create_range_type (NULL, index_type, &low_bound, &prop, 0);
17005     }
17006   char_type = language_string_char_type (cu->language_defn, gdbarch);
17007   type = create_string_type (NULL, char_type, range_type);
17008
17009   return set_die_type (die, type, cu);
17010 }
17011
17012 /* Assuming that DIE corresponds to a function, returns nonzero
17013    if the function is prototyped.  */
17014
17015 static int
17016 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17017 {
17018   struct attribute *attr;
17019
17020   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17021   if (attr && (DW_UNSND (attr) != 0))
17022     return 1;
17023
17024   /* The DWARF standard implies that the DW_AT_prototyped attribute
17025      is only meaningful for C, but the concept also extends to other
17026      languages that allow unprototyped functions (Eg: Objective C).
17027      For all other languages, assume that functions are always
17028      prototyped.  */
17029   if (cu->language != language_c
17030       && cu->language != language_objc
17031       && cu->language != language_opencl)
17032     return 1;
17033
17034   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17035      prototyped and unprototyped functions; default to prototyped,
17036      since that is more common in modern code (and RealView warns
17037      about unprototyped functions).  */
17038   if (producer_is_realview (cu->producer))
17039     return 1;
17040
17041   return 0;
17042 }
17043
17044 /* Handle DIES due to C code like:
17045
17046    struct foo
17047    {
17048    int (*funcp)(int a, long l);
17049    int b;
17050    };
17051
17052    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17053
17054 static struct type *
17055 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17056 {
17057   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17058   struct type *type;            /* Type that this function returns.  */
17059   struct type *ftype;           /* Function that returns above type.  */
17060   struct attribute *attr;
17061
17062   type = die_type (die, cu);
17063
17064   /* The die_type call above may have already set the type for this DIE.  */
17065   ftype = get_die_type (die, cu);
17066   if (ftype)
17067     return ftype;
17068
17069   ftype = lookup_function_type (type);
17070
17071   if (prototyped_function_p (die, cu))
17072     TYPE_PROTOTYPED (ftype) = 1;
17073
17074   /* Store the calling convention in the type if it's available in
17075      the subroutine die.  Otherwise set the calling convention to
17076      the default value DW_CC_normal.  */
17077   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17078   if (attr != nullptr
17079       && is_valid_DW_AT_calling_convention_for_subroutine (DW_UNSND (attr)))
17080     TYPE_CALLING_CONVENTION (ftype)
17081       = (enum dwarf_calling_convention) (DW_UNSND (attr));
17082   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17083     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17084   else
17085     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17086
17087   /* Record whether the function returns normally to its caller or not
17088      if the DWARF producer set that information.  */
17089   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17090   if (attr && (DW_UNSND (attr) != 0))
17091     TYPE_NO_RETURN (ftype) = 1;
17092
17093   /* We need to add the subroutine type to the die immediately so
17094      we don't infinitely recurse when dealing with parameters
17095      declared as the same subroutine type.  */
17096   set_die_type (die, ftype, cu);
17097
17098   if (die->child != NULL)
17099     {
17100       struct type *void_type = objfile_type (objfile)->builtin_void;
17101       struct die_info *child_die;
17102       int nparams, iparams;
17103
17104       /* Count the number of parameters.
17105          FIXME: GDB currently ignores vararg functions, but knows about
17106          vararg member functions.  */
17107       nparams = 0;
17108       child_die = die->child;
17109       while (child_die && child_die->tag)
17110         {
17111           if (child_die->tag == DW_TAG_formal_parameter)
17112             nparams++;
17113           else if (child_die->tag == DW_TAG_unspecified_parameters)
17114             TYPE_VARARGS (ftype) = 1;
17115           child_die = sibling_die (child_die);
17116         }
17117
17118       /* Allocate storage for parameters and fill them in.  */
17119       TYPE_NFIELDS (ftype) = nparams;
17120       TYPE_FIELDS (ftype) = (struct field *)
17121         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17122
17123       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17124          even if we error out during the parameters reading below.  */
17125       for (iparams = 0; iparams < nparams; iparams++)
17126         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17127
17128       iparams = 0;
17129       child_die = die->child;
17130       while (child_die && child_die->tag)
17131         {
17132           if (child_die->tag == DW_TAG_formal_parameter)
17133             {
17134               struct type *arg_type;
17135
17136               /* DWARF version 2 has no clean way to discern C++
17137                  static and non-static member functions.  G++ helps
17138                  GDB by marking the first parameter for non-static
17139                  member functions (which is the this pointer) as
17140                  artificial.  We pass this information to
17141                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17142
17143                  DWARF version 3 added DW_AT_object_pointer, which GCC
17144                  4.5 does not yet generate.  */
17145               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17146               if (attr != nullptr)
17147                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17148               else
17149                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17150               arg_type = die_type (child_die, cu);
17151
17152               /* RealView does not mark THIS as const, which the testsuite
17153                  expects.  GCC marks THIS as const in method definitions,
17154                  but not in the class specifications (GCC PR 43053).  */
17155               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17156                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17157                 {
17158                   int is_this = 0;
17159                   struct dwarf2_cu *arg_cu = cu;
17160                   const char *name = dwarf2_name (child_die, cu);
17161
17162                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17163                   if (attr != nullptr)
17164                     {
17165                       /* If the compiler emits this, use it.  */
17166                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17167                         is_this = 1;
17168                     }
17169                   else if (name && strcmp (name, "this") == 0)
17170                     /* Function definitions will have the argument names.  */
17171                     is_this = 1;
17172                   else if (name == NULL && iparams == 0)
17173                     /* Declarations may not have the names, so like
17174                        elsewhere in GDB, assume an artificial first
17175                        argument is "this".  */
17176                     is_this = 1;
17177
17178                   if (is_this)
17179                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17180                                              arg_type, 0);
17181                 }
17182
17183               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17184               iparams++;
17185             }
17186           child_die = sibling_die (child_die);
17187         }
17188     }
17189
17190   return ftype;
17191 }
17192
17193 static struct type *
17194 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17195 {
17196   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17197   const char *name = NULL;
17198   struct type *this_type, *target_type;
17199
17200   name = dwarf2_full_name (NULL, die, cu);
17201   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17202   TYPE_TARGET_STUB (this_type) = 1;
17203   set_die_type (die, this_type, cu);
17204   target_type = die_type (die, cu);
17205   if (target_type != this_type)
17206     TYPE_TARGET_TYPE (this_type) = target_type;
17207   else
17208     {
17209       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17210          spec and cause infinite loops in GDB.  */
17211       complaint (_("Self-referential DW_TAG_typedef "
17212                    "- DIE at %s [in module %s]"),
17213                  sect_offset_str (die->sect_off), objfile_name (objfile));
17214       TYPE_TARGET_TYPE (this_type) = NULL;
17215     }
17216   return this_type;
17217 }
17218
17219 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17220    (which may be different from NAME) to the architecture back-end to allow
17221    it to guess the correct format if necessary.  */
17222
17223 static struct type *
17224 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17225                         const char *name_hint, enum bfd_endian byte_order)
17226 {
17227   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17228   const struct floatformat **format;
17229   struct type *type;
17230
17231   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17232   if (format)
17233     type = init_float_type (objfile, bits, name, format, byte_order);
17234   else
17235     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17236
17237   return type;
17238 }
17239
17240 /* Allocate an integer type of size BITS and name NAME.  */
17241
17242 static struct type *
17243 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17244                           int bits, int unsigned_p, const char *name)
17245 {
17246   struct type *type;
17247
17248   /* Versions of Intel's C Compiler generate an integer type called "void"
17249      instead of using DW_TAG_unspecified_type.  This has been seen on
17250      at least versions 14, 17, and 18.  */
17251   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17252       && strcmp (name, "void") == 0)
17253     type = objfile_type (objfile)->builtin_void;
17254   else
17255     type = init_integer_type (objfile, bits, unsigned_p, name);
17256
17257   return type;
17258 }
17259
17260 /* Initialise and return a floating point type of size BITS suitable for
17261    use as a component of a complex number.  The NAME_HINT is passed through
17262    when initialising the floating point type and is the name of the complex
17263    type.
17264
17265    As DWARF doesn't currently provide an explicit name for the components
17266    of a complex number, but it can be helpful to have these components
17267    named, we try to select a suitable name based on the size of the
17268    component.  */
17269 static struct type *
17270 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
17271                                  struct objfile *objfile,
17272                                  int bits, const char *name_hint,
17273                                  enum bfd_endian byte_order)
17274 {
17275   gdbarch *gdbarch = get_objfile_arch (objfile);
17276   struct type *tt = nullptr;
17277
17278   /* Try to find a suitable floating point builtin type of size BITS.
17279      We're going to use the name of this type as the name for the complex
17280      target type that we are about to create.  */
17281   switch (cu->language)
17282     {
17283     case language_fortran:
17284       switch (bits)
17285         {
17286         case 32:
17287           tt = builtin_f_type (gdbarch)->builtin_real;
17288           break;
17289         case 64:
17290           tt = builtin_f_type (gdbarch)->builtin_real_s8;
17291           break;
17292         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17293         case 128:
17294           tt = builtin_f_type (gdbarch)->builtin_real_s16;
17295           break;
17296         }
17297       break;
17298     default:
17299       switch (bits)
17300         {
17301         case 32:
17302           tt = builtin_type (gdbarch)->builtin_float;
17303           break;
17304         case 64:
17305           tt = builtin_type (gdbarch)->builtin_double;
17306           break;
17307         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17308         case 128:
17309           tt = builtin_type (gdbarch)->builtin_long_double;
17310           break;
17311         }
17312       break;
17313     }
17314
17315   /* If the type we found doesn't match the size we were looking for, then
17316      pretend we didn't find a type at all, the complex target type we
17317      create will then be nameless.  */
17318   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
17319     tt = nullptr;
17320
17321   const char *name = (tt == nullptr) ? nullptr : TYPE_NAME (tt);
17322   return dwarf2_init_float_type (objfile, bits, name, name_hint, byte_order);
17323 }
17324
17325 /* Find a representation of a given base type and install
17326    it in the TYPE field of the die.  */
17327
17328 static struct type *
17329 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17330 {
17331   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17332   struct type *type;
17333   struct attribute *attr;
17334   int encoding = 0, bits = 0;
17335   const char *name;
17336   gdbarch *arch;
17337
17338   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17339   if (attr != nullptr)
17340     encoding = DW_UNSND (attr);
17341   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17342   if (attr != nullptr)
17343     bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17344   name = dwarf2_name (die, cu);
17345   if (!name)
17346     complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17347
17348   arch = get_objfile_arch (objfile);
17349   enum bfd_endian byte_order = gdbarch_byte_order (arch);
17350
17351   attr = dwarf2_attr (die, DW_AT_endianity, cu);
17352   if (attr)
17353     {
17354       int endianity = DW_UNSND (attr);
17355
17356       switch (endianity)
17357         {
17358         case DW_END_big:
17359           byte_order = BFD_ENDIAN_BIG;
17360           break;
17361         case DW_END_little:
17362           byte_order = BFD_ENDIAN_LITTLE;
17363           break;
17364         default:
17365           complaint (_("DW_AT_endianity has unrecognized value %d"), endianity);
17366           break;
17367         }
17368     }
17369
17370   switch (encoding)
17371     {
17372       case DW_ATE_address:
17373         /* Turn DW_ATE_address into a void * pointer.  */
17374         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17375         type = init_pointer_type (objfile, bits, name, type);
17376         break;
17377       case DW_ATE_boolean:
17378         type = init_boolean_type (objfile, bits, 1, name);
17379         break;
17380       case DW_ATE_complex_float:
17381         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name,
17382                                                 byte_order);
17383         type = init_complex_type (objfile, name, type);
17384         break;
17385       case DW_ATE_decimal_float:
17386         type = init_decfloat_type (objfile, bits, name);
17387         break;
17388       case DW_ATE_float:
17389         type = dwarf2_init_float_type (objfile, bits, name, name, byte_order);
17390         break;
17391       case DW_ATE_signed:
17392         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17393         break;
17394       case DW_ATE_unsigned:
17395         if (cu->language == language_fortran
17396             && name
17397             && startswith (name, "character("))
17398           type = init_character_type (objfile, bits, 1, name);
17399         else
17400           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17401         break;
17402       case DW_ATE_signed_char:
17403         if (cu->language == language_ada || cu->language == language_m2
17404             || cu->language == language_pascal
17405             || cu->language == language_fortran)
17406           type = init_character_type (objfile, bits, 0, name);
17407         else
17408           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17409         break;
17410       case DW_ATE_unsigned_char:
17411         if (cu->language == language_ada || cu->language == language_m2
17412             || cu->language == language_pascal
17413             || cu->language == language_fortran
17414             || cu->language == language_rust)
17415           type = init_character_type (objfile, bits, 1, name);
17416         else
17417           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17418         break;
17419       case DW_ATE_UTF:
17420         {
17421           if (bits == 16)
17422             type = builtin_type (arch)->builtin_char16;
17423           else if (bits == 32)
17424             type = builtin_type (arch)->builtin_char32;
17425           else
17426             {
17427               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17428                          bits);
17429               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17430             }
17431           return set_die_type (die, type, cu);
17432         }
17433         break;
17434
17435       default:
17436         complaint (_("unsupported DW_AT_encoding: '%s'"),
17437                    dwarf_type_encoding_name (encoding));
17438         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17439         break;
17440     }
17441
17442   if (name && strcmp (name, "char") == 0)
17443     TYPE_NOSIGN (type) = 1;
17444
17445   maybe_set_alignment (cu, die, type);
17446
17447   TYPE_ENDIANITY_NOT_DEFAULT (type) = gdbarch_byte_order (arch) != byte_order;
17448
17449   return set_die_type (die, type, cu);
17450 }
17451
17452 /* Parse dwarf attribute if it's a block, reference or constant and put the
17453    resulting value of the attribute into struct bound_prop.
17454    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17455
17456 static int
17457 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17458                       struct dwarf2_cu *cu, struct dynamic_prop *prop,
17459                       struct type *default_type)
17460 {
17461   struct dwarf2_property_baton *baton;
17462   struct obstack *obstack
17463     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17464
17465   gdb_assert (default_type != NULL);
17466
17467   if (attr == NULL || prop == NULL)
17468     return 0;
17469
17470   if (attr->form_is_block ())
17471     {
17472       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17473       baton->property_type = default_type;
17474       baton->locexpr.per_cu = cu->per_cu;
17475       baton->locexpr.size = DW_BLOCK (attr)->size;
17476       baton->locexpr.data = DW_BLOCK (attr)->data;
17477       switch (attr->name)
17478         {
17479         case DW_AT_string_length:
17480           baton->locexpr.is_reference = true;
17481           break;
17482         default:
17483           baton->locexpr.is_reference = false;
17484           break;
17485         }
17486       prop->data.baton = baton;
17487       prop->kind = PROP_LOCEXPR;
17488       gdb_assert (prop->data.baton != NULL);
17489     }
17490   else if (attr->form_is_ref ())
17491     {
17492       struct dwarf2_cu *target_cu = cu;
17493       struct die_info *target_die;
17494       struct attribute *target_attr;
17495
17496       target_die = follow_die_ref (die, attr, &target_cu);
17497       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17498       if (target_attr == NULL)
17499         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17500                                    target_cu);
17501       if (target_attr == NULL)
17502         return 0;
17503
17504       switch (target_attr->name)
17505         {
17506           case DW_AT_location:
17507             if (target_attr->form_is_section_offset ())
17508               {
17509                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17510                 baton->property_type = die_type (target_die, target_cu);
17511                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17512                 prop->data.baton = baton;
17513                 prop->kind = PROP_LOCLIST;
17514                 gdb_assert (prop->data.baton != NULL);
17515               }
17516             else if (target_attr->form_is_block ())
17517               {
17518                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17519                 baton->property_type = die_type (target_die, target_cu);
17520                 baton->locexpr.per_cu = cu->per_cu;
17521                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17522                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17523                 baton->locexpr.is_reference = true;
17524                 prop->data.baton = baton;
17525                 prop->kind = PROP_LOCEXPR;
17526                 gdb_assert (prop->data.baton != NULL);
17527               }
17528             else
17529               {
17530                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17531                                                        "dynamic property");
17532                 return 0;
17533               }
17534             break;
17535           case DW_AT_data_member_location:
17536             {
17537               LONGEST offset;
17538
17539               if (!handle_data_member_location (target_die, target_cu,
17540                                                 &offset))
17541                 return 0;
17542
17543               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17544               baton->property_type = read_type_die (target_die->parent,
17545                                                       target_cu);
17546               baton->offset_info.offset = offset;
17547               baton->offset_info.type = die_type (target_die, target_cu);
17548               prop->data.baton = baton;
17549               prop->kind = PROP_ADDR_OFFSET;
17550               break;
17551             }
17552         }
17553     }
17554   else if (attr->form_is_constant ())
17555     {
17556       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17557       prop->kind = PROP_CONST;
17558     }
17559   else
17560     {
17561       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17562                                              dwarf2_name (die, cu));
17563       return 0;
17564     }
17565
17566   return 1;
17567 }
17568
17569 /* Find an integer type SIZE_IN_BYTES bytes in size and return it.
17570    UNSIGNED_P controls if the integer is unsigned or not.  */
17571
17572 static struct type *
17573 dwarf2_per_cu_int_type (struct dwarf2_per_cu_data *per_cu,
17574                         int size_in_bytes, bool unsigned_p)
17575 {
17576   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
17577   struct type *int_type;
17578
17579   /* Helper macro to examine the various builtin types.  */
17580 #define TRY_TYPE(F)                                                     \
17581   int_type = (unsigned_p                                                \
17582               ? objfile_type (objfile)->builtin_unsigned_ ## F          \
17583               : objfile_type (objfile)->builtin_ ## F);                 \
17584   if (int_type != NULL && TYPE_LENGTH (int_type) == size_in_bytes)      \
17585     return int_type
17586
17587   TRY_TYPE (char);
17588   TRY_TYPE (short);
17589   TRY_TYPE (int);
17590   TRY_TYPE (long);
17591   TRY_TYPE (long_long);
17592
17593 #undef TRY_TYPE
17594
17595   gdb_assert_not_reached ("unable to find suitable integer type");
17596 }
17597
17598 /* Find an integer type the same size as the address size given in the
17599    compilation unit header for PER_CU.  UNSIGNED_P controls if the integer
17600    is unsigned or not.  */
17601
17602 static struct type *
17603 dwarf2_per_cu_addr_sized_int_type (struct dwarf2_per_cu_data *per_cu,
17604                                    bool unsigned_p)
17605 {
17606   int addr_size = dwarf2_per_cu_addr_size (per_cu);
17607   return dwarf2_per_cu_int_type (per_cu, addr_size, unsigned_p);
17608 }
17609
17610 /* Read the DW_AT_type attribute for a sub-range.  If this attribute is not
17611    present (which is valid) then compute the default type based on the
17612    compilation units address size.  */
17613
17614 static struct type *
17615 read_subrange_index_type (struct die_info *die, struct dwarf2_cu *cu)
17616 {
17617   struct type *index_type = die_type (die, cu);
17618
17619   /* Dwarf-2 specifications explicitly allows to create subrange types
17620      without specifying a base type.
17621      In that case, the base type must be set to the type of
17622      the lower bound, upper bound or count, in that order, if any of these
17623      three attributes references an object that has a type.
17624      If no base type is found, the Dwarf-2 specifications say that
17625      a signed integer type of size equal to the size of an address should
17626      be used.
17627      For the following C code: `extern char gdb_int [];'
17628      GCC produces an empty range DIE.
17629      FIXME: muller/2010-05-28: Possible references to object for low bound,
17630      high bound or count are not yet handled by this code.  */
17631   if (TYPE_CODE (index_type) == TYPE_CODE_VOID)
17632     index_type = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
17633
17634   return index_type;
17635 }
17636
17637 /* Read the given DW_AT_subrange DIE.  */
17638
17639 static struct type *
17640 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17641 {
17642   struct type *base_type, *orig_base_type;
17643   struct type *range_type;
17644   struct attribute *attr;
17645   struct dynamic_prop low, high;
17646   int low_default_is_valid;
17647   int high_bound_is_count = 0;
17648   const char *name;
17649   ULONGEST negative_mask;
17650
17651   orig_base_type = read_subrange_index_type (die, cu);
17652
17653   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17654      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17655      creating the range type, but we use the result of check_typedef
17656      when examining properties of the type.  */
17657   base_type = check_typedef (orig_base_type);
17658
17659   /* The die_type call above may have already set the type for this DIE.  */
17660   range_type = get_die_type (die, cu);
17661   if (range_type)
17662     return range_type;
17663
17664   low.kind = PROP_CONST;
17665   high.kind = PROP_CONST;
17666   high.data.const_val = 0;
17667
17668   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17669      omitting DW_AT_lower_bound.  */
17670   switch (cu->language)
17671     {
17672     case language_c:
17673     case language_cplus:
17674       low.data.const_val = 0;
17675       low_default_is_valid = 1;
17676       break;
17677     case language_fortran:
17678       low.data.const_val = 1;
17679       low_default_is_valid = 1;
17680       break;
17681     case language_d:
17682     case language_objc:
17683     case language_rust:
17684       low.data.const_val = 0;
17685       low_default_is_valid = (cu->header.version >= 4);
17686       break;
17687     case language_ada:
17688     case language_m2:
17689     case language_pascal:
17690       low.data.const_val = 1;
17691       low_default_is_valid = (cu->header.version >= 4);
17692       break;
17693     default:
17694       low.data.const_val = 0;
17695       low_default_is_valid = 0;
17696       break;
17697     }
17698
17699   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17700   if (attr != nullptr)
17701     attr_to_dynamic_prop (attr, die, cu, &low, base_type);
17702   else if (!low_default_is_valid)
17703     complaint (_("Missing DW_AT_lower_bound "
17704                                       "- DIE at %s [in module %s]"),
17705                sect_offset_str (die->sect_off),
17706                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17707
17708   struct attribute *attr_ub, *attr_count;
17709   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17710   if (!attr_to_dynamic_prop (attr, die, cu, &high, base_type))
17711     {
17712       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17713       if (attr_to_dynamic_prop (attr, die, cu, &high, base_type))
17714         {
17715           /* If bounds are constant do the final calculation here.  */
17716           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17717             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17718           else
17719             high_bound_is_count = 1;
17720         }
17721       else
17722         {
17723           if (attr_ub != NULL)
17724             complaint (_("Unresolved DW_AT_upper_bound "
17725                          "- DIE at %s [in module %s]"),
17726                        sect_offset_str (die->sect_off),
17727                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17728           if (attr_count != NULL)
17729             complaint (_("Unresolved DW_AT_count "
17730                          "- DIE at %s [in module %s]"),
17731                        sect_offset_str (die->sect_off),
17732                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17733         }
17734     }
17735
17736   LONGEST bias = 0;
17737   struct attribute *bias_attr = dwarf2_attr (die, DW_AT_GNU_bias, cu);
17738   if (bias_attr != nullptr && bias_attr->form_is_constant ())
17739     bias = dwarf2_get_attr_constant_value (bias_attr, 0);
17740
17741   /* Normally, the DWARF producers are expected to use a signed
17742      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17743      But this is unfortunately not always the case, as witnessed
17744      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17745      is used instead.  To work around that ambiguity, we treat
17746      the bounds as signed, and thus sign-extend their values, when
17747      the base type is signed.  */
17748   negative_mask =
17749     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17750   if (low.kind == PROP_CONST
17751       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17752     low.data.const_val |= negative_mask;
17753   if (high.kind == PROP_CONST
17754       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17755     high.data.const_val |= negative_mask;
17756
17757   /* Check for bit and byte strides.  */
17758   struct dynamic_prop byte_stride_prop;
17759   attribute *attr_byte_stride = dwarf2_attr (die, DW_AT_byte_stride, cu);
17760   if (attr_byte_stride != nullptr)
17761     {
17762       struct type *prop_type
17763         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
17764       attr_to_dynamic_prop (attr_byte_stride, die, cu, &byte_stride_prop,
17765                             prop_type);
17766     }
17767
17768   struct dynamic_prop bit_stride_prop;
17769   attribute *attr_bit_stride = dwarf2_attr (die, DW_AT_bit_stride, cu);
17770   if (attr_bit_stride != nullptr)
17771     {
17772       /* It only makes sense to have either a bit or byte stride.  */
17773       if (attr_byte_stride != nullptr)
17774         {
17775           complaint (_("Found DW_AT_bit_stride and DW_AT_byte_stride "
17776                        "- DIE at %s [in module %s]"),
17777                      sect_offset_str (die->sect_off),
17778                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17779           attr_bit_stride = nullptr;
17780         }
17781       else
17782         {
17783           struct type *prop_type
17784             = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
17785           attr_to_dynamic_prop (attr_bit_stride, die, cu, &bit_stride_prop,
17786                                 prop_type);
17787         }
17788     }
17789
17790   if (attr_byte_stride != nullptr
17791       || attr_bit_stride != nullptr)
17792     {
17793       bool byte_stride_p = (attr_byte_stride != nullptr);
17794       struct dynamic_prop *stride
17795         = byte_stride_p ? &byte_stride_prop : &bit_stride_prop;
17796
17797       range_type
17798         = create_range_type_with_stride (NULL, orig_base_type, &low,
17799                                          &high, bias, stride, byte_stride_p);
17800     }
17801   else
17802     range_type = create_range_type (NULL, orig_base_type, &low, &high, bias);
17803
17804   if (high_bound_is_count)
17805     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17806
17807   /* Ada expects an empty array on no boundary attributes.  */
17808   if (attr == NULL && cu->language != language_ada)
17809     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17810
17811   name = dwarf2_name (die, cu);
17812   if (name)
17813     TYPE_NAME (range_type) = name;
17814
17815   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17816   if (attr != nullptr)
17817     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17818
17819   maybe_set_alignment (cu, die, range_type);
17820
17821   set_die_type (die, range_type, cu);
17822
17823   /* set_die_type should be already done.  */
17824   set_descriptive_type (range_type, die, cu);
17825
17826   return range_type;
17827 }
17828
17829 static struct type *
17830 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17831 {
17832   struct type *type;
17833
17834   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17835                     NULL);
17836   TYPE_NAME (type) = dwarf2_name (die, cu);
17837
17838   /* In Ada, an unspecified type is typically used when the description
17839      of the type is deferred to a different unit.  When encountering
17840      such a type, we treat it as a stub, and try to resolve it later on,
17841      when needed.  */
17842   if (cu->language == language_ada)
17843     TYPE_STUB (type) = 1;
17844
17845   return set_die_type (die, type, cu);
17846 }
17847
17848 /* Read a single die and all its descendents.  Set the die's sibling
17849    field to NULL; set other fields in the die correctly, and set all
17850    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17851    location of the info_ptr after reading all of those dies.  PARENT
17852    is the parent of the die in question.  */
17853
17854 static struct die_info *
17855 read_die_and_children (const struct die_reader_specs *reader,
17856                        const gdb_byte *info_ptr,
17857                        const gdb_byte **new_info_ptr,
17858                        struct die_info *parent)
17859 {
17860   struct die_info *die;
17861   const gdb_byte *cur_ptr;
17862
17863   cur_ptr = read_full_die_1 (reader, &die, info_ptr, 0);
17864   if (die == NULL)
17865     {
17866       *new_info_ptr = cur_ptr;
17867       return NULL;
17868     }
17869   store_in_ref_table (die, reader->cu);
17870
17871   if (die->has_children)
17872     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17873   else
17874     {
17875       die->child = NULL;
17876       *new_info_ptr = cur_ptr;
17877     }
17878
17879   die->sibling = NULL;
17880   die->parent = parent;
17881   return die;
17882 }
17883
17884 /* Read a die, all of its descendents, and all of its siblings; set
17885    all of the fields of all of the dies correctly.  Arguments are as
17886    in read_die_and_children.  */
17887
17888 static struct die_info *
17889 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17890                          const gdb_byte *info_ptr,
17891                          const gdb_byte **new_info_ptr,
17892                          struct die_info *parent)
17893 {
17894   struct die_info *first_die, *last_sibling;
17895   const gdb_byte *cur_ptr;
17896
17897   cur_ptr = info_ptr;
17898   first_die = last_sibling = NULL;
17899
17900   while (1)
17901     {
17902       struct die_info *die
17903         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17904
17905       if (die == NULL)
17906         {
17907           *new_info_ptr = cur_ptr;
17908           return first_die;
17909         }
17910
17911       if (!first_die)
17912         first_die = die;
17913       else
17914         last_sibling->sibling = die;
17915
17916       last_sibling = die;
17917     }
17918 }
17919
17920 /* Read a die, all of its descendents, and all of its siblings; set
17921    all of the fields of all of the dies correctly.  Arguments are as
17922    in read_die_and_children.
17923    This the main entry point for reading a DIE and all its children.  */
17924
17925 static struct die_info *
17926 read_die_and_siblings (const struct die_reader_specs *reader,
17927                        const gdb_byte *info_ptr,
17928                        const gdb_byte **new_info_ptr,
17929                        struct die_info *parent)
17930 {
17931   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17932                                                   new_info_ptr, parent);
17933
17934   if (dwarf_die_debug)
17935     {
17936       fprintf_unfiltered (gdb_stdlog,
17937                           "Read die from %s@0x%x of %s:\n",
17938                           reader->die_section->get_name (),
17939                           (unsigned) (info_ptr - reader->die_section->buffer),
17940                           bfd_get_filename (reader->abfd));
17941       dump_die (die, dwarf_die_debug);
17942     }
17943
17944   return die;
17945 }
17946
17947 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17948    attributes.
17949    The caller is responsible for filling in the extra attributes
17950    and updating (*DIEP)->num_attrs.
17951    Set DIEP to point to a newly allocated die with its information,
17952    except for its child, sibling, and parent fields.  */
17953
17954 static const gdb_byte *
17955 read_full_die_1 (const struct die_reader_specs *reader,
17956                  struct die_info **diep, const gdb_byte *info_ptr,
17957                  int num_extra_attrs)
17958 {
17959   unsigned int abbrev_number, bytes_read, i;
17960   struct abbrev_info *abbrev;
17961   struct die_info *die;
17962   struct dwarf2_cu *cu = reader->cu;
17963   bfd *abfd = reader->abfd;
17964
17965   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17966   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17967   info_ptr += bytes_read;
17968   if (!abbrev_number)
17969     {
17970       *diep = NULL;
17971       return info_ptr;
17972     }
17973
17974   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17975   if (!abbrev)
17976     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17977            abbrev_number,
17978            bfd_get_filename (abfd));
17979
17980   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17981   die->sect_off = sect_off;
17982   die->tag = abbrev->tag;
17983   die->abbrev = abbrev_number;
17984   die->has_children = abbrev->has_children;
17985
17986   /* Make the result usable.
17987      The caller needs to update num_attrs after adding the extra
17988      attributes.  */
17989   die->num_attrs = abbrev->num_attrs;
17990
17991   std::vector<int> indexes_that_need_reprocess;
17992   for (i = 0; i < abbrev->num_attrs; ++i)
17993     {
17994       bool need_reprocess;
17995       info_ptr =
17996         read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17997                         info_ptr, &need_reprocess);
17998       if (need_reprocess)
17999         indexes_that_need_reprocess.push_back (i);
18000     }
18001
18002   struct attribute *attr = dwarf2_attr_no_follow (die, DW_AT_str_offsets_base);
18003   if (attr != nullptr)
18004     cu->str_offsets_base = DW_UNSND (attr);
18005
18006   auto maybe_addr_base = lookup_addr_base(die);
18007   if (maybe_addr_base.has_value ())
18008     cu->addr_base = *maybe_addr_base;
18009   for (int index : indexes_that_need_reprocess)
18010     read_attribute_reprocess (reader, &die->attrs[index]);
18011   *diep = die;
18012   return info_ptr;
18013 }
18014
18015 /* Read a die and all its attributes.
18016    Set DIEP to point to a newly allocated die with its information,
18017    except for its child, sibling, and parent fields.  */
18018
18019 static const gdb_byte *
18020 read_full_die (const struct die_reader_specs *reader,
18021                struct die_info **diep, const gdb_byte *info_ptr)
18022 {
18023   const gdb_byte *result;
18024
18025   result = read_full_die_1 (reader, diep, info_ptr, 0);
18026
18027   if (dwarf_die_debug)
18028     {
18029       fprintf_unfiltered (gdb_stdlog,
18030                           "Read die from %s@0x%x of %s:\n",
18031                           reader->die_section->get_name (),
18032                           (unsigned) (info_ptr - reader->die_section->buffer),
18033                           bfd_get_filename (reader->abfd));
18034       dump_die (*diep, dwarf_die_debug);
18035     }
18036
18037   return result;
18038 }
18039 \f
18040
18041 /* Returns nonzero if TAG represents a type that we might generate a partial
18042    symbol for.  */
18043
18044 static int
18045 is_type_tag_for_partial (int tag)
18046 {
18047   switch (tag)
18048     {
18049 #if 0
18050     /* Some types that would be reasonable to generate partial symbols for,
18051        that we don't at present.  */
18052     case DW_TAG_array_type:
18053     case DW_TAG_file_type:
18054     case DW_TAG_ptr_to_member_type:
18055     case DW_TAG_set_type:
18056     case DW_TAG_string_type:
18057     case DW_TAG_subroutine_type:
18058 #endif
18059     case DW_TAG_base_type:
18060     case DW_TAG_class_type:
18061     case DW_TAG_interface_type:
18062     case DW_TAG_enumeration_type:
18063     case DW_TAG_structure_type:
18064     case DW_TAG_subrange_type:
18065     case DW_TAG_typedef:
18066     case DW_TAG_union_type:
18067       return 1;
18068     default:
18069       return 0;
18070     }
18071 }
18072
18073 /* Load all DIEs that are interesting for partial symbols into memory.  */
18074
18075 static struct partial_die_info *
18076 load_partial_dies (const struct die_reader_specs *reader,
18077                    const gdb_byte *info_ptr, int building_psymtab)
18078 {
18079   struct dwarf2_cu *cu = reader->cu;
18080   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18081   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18082   unsigned int bytes_read;
18083   unsigned int load_all = 0;
18084   int nesting_level = 1;
18085
18086   parent_die = NULL;
18087   last_die = NULL;
18088
18089   gdb_assert (cu->per_cu != NULL);
18090   if (cu->per_cu->load_all_dies)
18091     load_all = 1;
18092
18093   cu->partial_dies
18094     = htab_create_alloc_ex (cu->header.length / 12,
18095                             partial_die_hash,
18096                             partial_die_eq,
18097                             NULL,
18098                             &cu->comp_unit_obstack,
18099                             hashtab_obstack_allocate,
18100                             dummy_obstack_deallocate);
18101
18102   while (1)
18103     {
18104       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18105
18106       /* A NULL abbrev means the end of a series of children.  */
18107       if (abbrev == NULL)
18108         {
18109           if (--nesting_level == 0)
18110             return first_die;
18111
18112           info_ptr += bytes_read;
18113           last_die = parent_die;
18114           parent_die = parent_die->die_parent;
18115           continue;
18116         }
18117
18118       /* Check for template arguments.  We never save these; if
18119          they're seen, we just mark the parent, and go on our way.  */
18120       if (parent_die != NULL
18121           && cu->language == language_cplus
18122           && (abbrev->tag == DW_TAG_template_type_param
18123               || abbrev->tag == DW_TAG_template_value_param))
18124         {
18125           parent_die->has_template_arguments = 1;
18126
18127           if (!load_all)
18128             {
18129               /* We don't need a partial DIE for the template argument.  */
18130               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18131               continue;
18132             }
18133         }
18134
18135       /* We only recurse into c++ subprograms looking for template arguments.
18136          Skip their other children.  */
18137       if (!load_all
18138           && cu->language == language_cplus
18139           && parent_die != NULL
18140           && parent_die->tag == DW_TAG_subprogram)
18141         {
18142           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18143           continue;
18144         }
18145
18146       /* Check whether this DIE is interesting enough to save.  Normally
18147          we would not be interested in members here, but there may be
18148          later variables referencing them via DW_AT_specification (for
18149          static members).  */
18150       if (!load_all
18151           && !is_type_tag_for_partial (abbrev->tag)
18152           && abbrev->tag != DW_TAG_constant
18153           && abbrev->tag != DW_TAG_enumerator
18154           && abbrev->tag != DW_TAG_subprogram
18155           && abbrev->tag != DW_TAG_inlined_subroutine
18156           && abbrev->tag != DW_TAG_lexical_block
18157           && abbrev->tag != DW_TAG_variable
18158           && abbrev->tag != DW_TAG_namespace
18159           && abbrev->tag != DW_TAG_module
18160           && abbrev->tag != DW_TAG_member
18161           && abbrev->tag != DW_TAG_imported_unit
18162           && abbrev->tag != DW_TAG_imported_declaration)
18163         {
18164           /* Otherwise we skip to the next sibling, if any.  */
18165           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18166           continue;
18167         }
18168
18169       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18170                                    abbrev);
18171
18172       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18173
18174       /* This two-pass algorithm for processing partial symbols has a
18175          high cost in cache pressure.  Thus, handle some simple cases
18176          here which cover the majority of C partial symbols.  DIEs
18177          which neither have specification tags in them, nor could have
18178          specification tags elsewhere pointing at them, can simply be
18179          processed and discarded.
18180
18181          This segment is also optional; scan_partial_symbols and
18182          add_partial_symbol will handle these DIEs if we chain
18183          them in normally.  When compilers which do not emit large
18184          quantities of duplicate debug information are more common,
18185          this code can probably be removed.  */
18186
18187       /* Any complete simple types at the top level (pretty much all
18188          of them, for a language without namespaces), can be processed
18189          directly.  */
18190       if (parent_die == NULL
18191           && pdi.has_specification == 0
18192           && pdi.is_declaration == 0
18193           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18194               || pdi.tag == DW_TAG_base_type
18195               || pdi.tag == DW_TAG_subrange_type))
18196         {
18197           if (building_psymtab && pdi.name != NULL)
18198             add_psymbol_to_list (pdi.name, false,
18199                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18200                                  psymbol_placement::STATIC,
18201                                  0, cu->language, objfile);
18202           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18203           continue;
18204         }
18205
18206       /* The exception for DW_TAG_typedef with has_children above is
18207          a workaround of GCC PR debug/47510.  In the case of this complaint
18208          type_name_or_error will error on such types later.
18209
18210          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18211          it could not find the child DIEs referenced later, this is checked
18212          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18213
18214       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18215         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18216                      "- DIE at %s [in module %s]"),
18217                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18218
18219       /* If we're at the second level, and we're an enumerator, and
18220          our parent has no specification (meaning possibly lives in a
18221          namespace elsewhere), then we can add the partial symbol now
18222          instead of queueing it.  */
18223       if (pdi.tag == DW_TAG_enumerator
18224           && parent_die != NULL
18225           && parent_die->die_parent == NULL
18226           && parent_die->tag == DW_TAG_enumeration_type
18227           && parent_die->has_specification == 0)
18228         {
18229           if (pdi.name == NULL)
18230             complaint (_("malformed enumerator DIE ignored"));
18231           else if (building_psymtab)
18232             add_psymbol_to_list (pdi.name, false,
18233                                  VAR_DOMAIN, LOC_CONST, -1,
18234                                  cu->language == language_cplus
18235                                  ? psymbol_placement::GLOBAL
18236                                  : psymbol_placement::STATIC,
18237                                  0, cu->language, objfile);
18238
18239           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18240           continue;
18241         }
18242
18243       struct partial_die_info *part_die
18244         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18245
18246       /* We'll save this DIE so link it in.  */
18247       part_die->die_parent = parent_die;
18248       part_die->die_sibling = NULL;
18249       part_die->die_child = NULL;
18250
18251       if (last_die && last_die == parent_die)
18252         last_die->die_child = part_die;
18253       else if (last_die)
18254         last_die->die_sibling = part_die;
18255
18256       last_die = part_die;
18257
18258       if (first_die == NULL)
18259         first_die = part_die;
18260
18261       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18262          find interesting need to be in the hash table, because we
18263          also have the parent/sibling/child chains; only those that we
18264          might refer to by offset later during partial symbol reading.
18265
18266          For now this means things that might have be the target of a
18267          DW_AT_specification, DW_AT_abstract_origin, or
18268          DW_AT_extension.  DW_AT_extension will refer only to
18269          namespaces; DW_AT_abstract_origin refers to functions (and
18270          many things under the function DIE, but we do not recurse
18271          into function DIEs during partial symbol reading) and
18272          possibly variables as well; DW_AT_specification refers to
18273          declarations.  Declarations ought to have the DW_AT_declaration
18274          flag.  It happens that GCC forgets to put it in sometimes, but
18275          only for functions, not for types.
18276
18277          Adding more things than necessary to the hash table is harmless
18278          except for the performance cost.  Adding too few will result in
18279          wasted time in find_partial_die, when we reread the compilation
18280          unit with load_all_dies set.  */
18281
18282       if (load_all
18283           || abbrev->tag == DW_TAG_constant
18284           || abbrev->tag == DW_TAG_subprogram
18285           || abbrev->tag == DW_TAG_variable
18286           || abbrev->tag == DW_TAG_namespace
18287           || part_die->is_declaration)
18288         {
18289           void **slot;
18290
18291           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18292                                            to_underlying (part_die->sect_off),
18293                                            INSERT);
18294           *slot = part_die;
18295         }
18296
18297       /* For some DIEs we want to follow their children (if any).  For C
18298          we have no reason to follow the children of structures; for other
18299          languages we have to, so that we can get at method physnames
18300          to infer fully qualified class names, for DW_AT_specification,
18301          and for C++ template arguments.  For C++, we also look one level
18302          inside functions to find template arguments (if the name of the
18303          function does not already contain the template arguments).
18304
18305          For Ada and Fortran, we need to scan the children of subprograms
18306          and lexical blocks as well because these languages allow the
18307          definition of nested entities that could be interesting for the
18308          debugger, such as nested subprograms for instance.  */
18309       if (last_die->has_children
18310           && (load_all
18311               || last_die->tag == DW_TAG_namespace
18312               || last_die->tag == DW_TAG_module
18313               || last_die->tag == DW_TAG_enumeration_type
18314               || (cu->language == language_cplus
18315                   && last_die->tag == DW_TAG_subprogram
18316                   && (last_die->name == NULL
18317                       || strchr (last_die->name, '<') == NULL))
18318               || (cu->language != language_c
18319                   && (last_die->tag == DW_TAG_class_type
18320                       || last_die->tag == DW_TAG_interface_type
18321                       || last_die->tag == DW_TAG_structure_type
18322                       || last_die->tag == DW_TAG_union_type))
18323               || ((cu->language == language_ada
18324                    || cu->language == language_fortran)
18325                   && (last_die->tag == DW_TAG_subprogram
18326                       || last_die->tag == DW_TAG_lexical_block))))
18327         {
18328           nesting_level++;
18329           parent_die = last_die;
18330           continue;
18331         }
18332
18333       /* Otherwise we skip to the next sibling, if any.  */
18334       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18335
18336       /* Back to the top, do it again.  */
18337     }
18338 }
18339
18340 partial_die_info::partial_die_info (sect_offset sect_off_,
18341                                     struct abbrev_info *abbrev)
18342   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18343 {
18344 }
18345
18346 /* Read a minimal amount of information into the minimal die structure.
18347    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18348
18349 const gdb_byte *
18350 partial_die_info::read (const struct die_reader_specs *reader,
18351                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18352 {
18353   struct dwarf2_cu *cu = reader->cu;
18354   struct dwarf2_per_objfile *dwarf2_per_objfile
18355     = cu->per_cu->dwarf2_per_objfile;
18356   unsigned int i;
18357   int has_low_pc_attr = 0;
18358   int has_high_pc_attr = 0;
18359   int high_pc_relative = 0;
18360
18361   std::vector<struct attribute> attr_vec (abbrev.num_attrs);
18362   for (i = 0; i < abbrev.num_attrs; ++i)
18363     {
18364       bool need_reprocess;
18365       info_ptr = read_attribute (reader, &attr_vec[i], &abbrev.attrs[i],
18366                                  info_ptr, &need_reprocess);
18367       /* String and address offsets that need to do the reprocessing have
18368          already been read at this point, so there is no need to wait until
18369          the loop terminates to do the reprocessing.  */
18370       if (need_reprocess)
18371         read_attribute_reprocess (reader, &attr_vec[i]);
18372       attribute &attr = attr_vec[i];
18373       /* Store the data if it is of an attribute we want to keep in a
18374          partial symbol table.  */
18375       switch (attr.name)
18376         {
18377         case DW_AT_name:
18378           switch (tag)
18379             {
18380             case DW_TAG_compile_unit:
18381             case DW_TAG_partial_unit:
18382             case DW_TAG_type_unit:
18383               /* Compilation units have a DW_AT_name that is a filename, not
18384                  a source language identifier.  */
18385             case DW_TAG_enumeration_type:
18386             case DW_TAG_enumerator:
18387               /* These tags always have simple identifiers already; no need
18388                  to canonicalize them.  */
18389               name = DW_STRING (&attr);
18390               break;
18391             default:
18392               {
18393                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18394
18395                 name
18396                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18397                                               &objfile->per_bfd->storage_obstack);
18398               }
18399               break;
18400             }
18401           break;
18402         case DW_AT_linkage_name:
18403         case DW_AT_MIPS_linkage_name:
18404           /* Note that both forms of linkage name might appear.  We
18405              assume they will be the same, and we only store the last
18406              one we see.  */
18407           linkage_name = DW_STRING (&attr);
18408           break;
18409         case DW_AT_low_pc:
18410           has_low_pc_attr = 1;
18411           lowpc = attr.value_as_address ();
18412           break;
18413         case DW_AT_high_pc:
18414           has_high_pc_attr = 1;
18415           highpc = attr.value_as_address ();
18416           if (cu->header.version >= 4 && attr.form_is_constant ())
18417                 high_pc_relative = 1;
18418           break;
18419         case DW_AT_location:
18420           /* Support the .debug_loc offsets.  */
18421           if (attr.form_is_block ())
18422             {
18423                d.locdesc = DW_BLOCK (&attr);
18424             }
18425           else if (attr.form_is_section_offset ())
18426             {
18427               dwarf2_complex_location_expr_complaint ();
18428             }
18429           else
18430             {
18431               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18432                                                      "partial symbol information");
18433             }
18434           break;
18435         case DW_AT_external:
18436           is_external = DW_UNSND (&attr);
18437           break;
18438         case DW_AT_declaration:
18439           is_declaration = DW_UNSND (&attr);
18440           break;
18441         case DW_AT_type:
18442           has_type = 1;
18443           break;
18444         case DW_AT_abstract_origin:
18445         case DW_AT_specification:
18446         case DW_AT_extension:
18447           has_specification = 1;
18448           spec_offset = dwarf2_get_ref_die_offset (&attr);
18449           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18450                                    || cu->per_cu->is_dwz);
18451           break;
18452         case DW_AT_sibling:
18453           /* Ignore absolute siblings, they might point outside of
18454              the current compile unit.  */
18455           if (attr.form == DW_FORM_ref_addr)
18456             complaint (_("ignoring absolute DW_AT_sibling"));
18457           else
18458             {
18459               const gdb_byte *buffer = reader->buffer;
18460               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18461               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18462
18463               if (sibling_ptr < info_ptr)
18464                 complaint (_("DW_AT_sibling points backwards"));
18465               else if (sibling_ptr > reader->buffer_end)
18466                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18467               else
18468                 sibling = sibling_ptr;
18469             }
18470           break;
18471         case DW_AT_byte_size:
18472           has_byte_size = 1;
18473           break;
18474         case DW_AT_const_value:
18475           has_const_value = 1;
18476           break;
18477         case DW_AT_calling_convention:
18478           /* DWARF doesn't provide a way to identify a program's source-level
18479              entry point.  DW_AT_calling_convention attributes are only meant
18480              to describe functions' calling conventions.
18481
18482              However, because it's a necessary piece of information in
18483              Fortran, and before DWARF 4 DW_CC_program was the only
18484              piece of debugging information whose definition refers to
18485              a 'main program' at all, several compilers marked Fortran
18486              main programs with DW_CC_program --- even when those
18487              functions use the standard calling conventions.
18488
18489              Although DWARF now specifies a way to provide this
18490              information, we support this practice for backward
18491              compatibility.  */
18492           if (DW_UNSND (&attr) == DW_CC_program
18493               && cu->language == language_fortran)
18494             main_subprogram = 1;
18495           break;
18496         case DW_AT_inline:
18497           if (DW_UNSND (&attr) == DW_INL_inlined
18498               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18499             may_be_inlined = 1;
18500           break;
18501
18502         case DW_AT_import:
18503           if (tag == DW_TAG_imported_unit)
18504             {
18505               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18506               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18507                                   || cu->per_cu->is_dwz);
18508             }
18509           break;
18510
18511         case DW_AT_main_subprogram:
18512           main_subprogram = DW_UNSND (&attr);
18513           break;
18514
18515         case DW_AT_ranges:
18516           {
18517             /* It would be nice to reuse dwarf2_get_pc_bounds here,
18518                but that requires a full DIE, so instead we just
18519                reimplement it.  */
18520             int need_ranges_base = tag != DW_TAG_compile_unit;
18521             unsigned int ranges_offset = (DW_UNSND (&attr)
18522                                           + (need_ranges_base
18523                                              ? cu->ranges_base
18524                                              : 0));
18525
18526             /* Value of the DW_AT_ranges attribute is the offset in the
18527                .debug_ranges section.  */
18528             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
18529                                     nullptr))
18530               has_pc_info = 1;
18531           }
18532           break;
18533
18534         default:
18535           break;
18536         }
18537     }
18538
18539   /* For Ada, if both the name and the linkage name appear, we prefer
18540      the latter.  This lets "catch exception" work better, regardless
18541      of the order in which the name and linkage name were emitted.
18542      Really, though, this is just a workaround for the fact that gdb
18543      doesn't store both the name and the linkage name.  */
18544   if (cu->language == language_ada && linkage_name != nullptr)
18545     name = linkage_name;
18546
18547   if (high_pc_relative)
18548     highpc += lowpc;
18549
18550   if (has_low_pc_attr && has_high_pc_attr)
18551     {
18552       /* When using the GNU linker, .gnu.linkonce. sections are used to
18553          eliminate duplicate copies of functions and vtables and such.
18554          The linker will arbitrarily choose one and discard the others.
18555          The AT_*_pc values for such functions refer to local labels in
18556          these sections.  If the section from that file was discarded, the
18557          labels are not in the output, so the relocs get a value of 0.
18558          If this is a discarded function, mark the pc bounds as invalid,
18559          so that GDB will ignore it.  */
18560       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18561         {
18562           struct objfile *objfile = dwarf2_per_objfile->objfile;
18563           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18564
18565           complaint (_("DW_AT_low_pc %s is zero "
18566                        "for DIE at %s [in module %s]"),
18567                      paddress (gdbarch, lowpc),
18568                      sect_offset_str (sect_off),
18569                      objfile_name (objfile));
18570         }
18571       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18572       else if (lowpc >= highpc)
18573         {
18574           struct objfile *objfile = dwarf2_per_objfile->objfile;
18575           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18576
18577           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18578                        "for DIE at %s [in module %s]"),
18579                      paddress (gdbarch, lowpc),
18580                      paddress (gdbarch, highpc),
18581                      sect_offset_str (sect_off),
18582                      objfile_name (objfile));
18583         }
18584       else
18585         has_pc_info = 1;
18586     }
18587
18588   return info_ptr;
18589 }
18590
18591 /* Find a cached partial DIE at OFFSET in CU.  */
18592
18593 struct partial_die_info *
18594 dwarf2_cu::find_partial_die (sect_offset sect_off)
18595 {
18596   struct partial_die_info *lookup_die = NULL;
18597   struct partial_die_info part_die (sect_off);
18598
18599   lookup_die = ((struct partial_die_info *)
18600                 htab_find_with_hash (partial_dies, &part_die,
18601                                      to_underlying (sect_off)));
18602
18603   return lookup_die;
18604 }
18605
18606 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18607    except in the case of .debug_types DIEs which do not reference
18608    outside their CU (they do however referencing other types via
18609    DW_FORM_ref_sig8).  */
18610
18611 static const struct cu_partial_die_info
18612 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18613 {
18614   struct dwarf2_per_objfile *dwarf2_per_objfile
18615     = cu->per_cu->dwarf2_per_objfile;
18616   struct objfile *objfile = dwarf2_per_objfile->objfile;
18617   struct dwarf2_per_cu_data *per_cu = NULL;
18618   struct partial_die_info *pd = NULL;
18619
18620   if (offset_in_dwz == cu->per_cu->is_dwz
18621       && offset_in_cu_p (&cu->header, sect_off))
18622     {
18623       pd = cu->find_partial_die (sect_off);
18624       if (pd != NULL)
18625         return { cu, pd };
18626       /* We missed recording what we needed.
18627          Load all dies and try again.  */
18628       per_cu = cu->per_cu;
18629     }
18630   else
18631     {
18632       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18633       if (cu->per_cu->is_debug_types)
18634         {
18635           error (_("Dwarf Error: Type Unit at offset %s contains"
18636                    " external reference to offset %s [in module %s].\n"),
18637                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18638                  bfd_get_filename (objfile->obfd));
18639         }
18640       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18641                                                  dwarf2_per_objfile);
18642
18643       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18644         load_partial_comp_unit (per_cu);
18645
18646       per_cu->cu->last_used = 0;
18647       pd = per_cu->cu->find_partial_die (sect_off);
18648     }
18649
18650   /* If we didn't find it, and not all dies have been loaded,
18651      load them all and try again.  */
18652
18653   if (pd == NULL && per_cu->load_all_dies == 0)
18654     {
18655       per_cu->load_all_dies = 1;
18656
18657       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18658          THIS_CU->cu may already be in use.  So we can't just free it and
18659          replace its DIEs with the ones we read in.  Instead, we leave those
18660          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18661          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18662          set.  */
18663       load_partial_comp_unit (per_cu);
18664
18665       pd = per_cu->cu->find_partial_die (sect_off);
18666     }
18667
18668   if (pd == NULL)
18669     internal_error (__FILE__, __LINE__,
18670                     _("could not find partial DIE %s "
18671                       "in cache [from module %s]\n"),
18672                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18673   return { per_cu->cu, pd };
18674 }
18675
18676 /* See if we can figure out if the class lives in a namespace.  We do
18677    this by looking for a member function; its demangled name will
18678    contain namespace info, if there is any.  */
18679
18680 static void
18681 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18682                                   struct dwarf2_cu *cu)
18683 {
18684   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18685      what template types look like, because the demangler
18686      frequently doesn't give the same name as the debug info.  We
18687      could fix this by only using the demangled name to get the
18688      prefix (but see comment in read_structure_type).  */
18689
18690   struct partial_die_info *real_pdi;
18691   struct partial_die_info *child_pdi;
18692
18693   /* If this DIE (this DIE's specification, if any) has a parent, then
18694      we should not do this.  We'll prepend the parent's fully qualified
18695      name when we create the partial symbol.  */
18696
18697   real_pdi = struct_pdi;
18698   while (real_pdi->has_specification)
18699     {
18700       auto res = find_partial_die (real_pdi->spec_offset,
18701                                    real_pdi->spec_is_dwz, cu);
18702       real_pdi = res.pdi;
18703       cu = res.cu;
18704     }
18705
18706   if (real_pdi->die_parent != NULL)
18707     return;
18708
18709   for (child_pdi = struct_pdi->die_child;
18710        child_pdi != NULL;
18711        child_pdi = child_pdi->die_sibling)
18712     {
18713       if (child_pdi->tag == DW_TAG_subprogram
18714           && child_pdi->linkage_name != NULL)
18715         {
18716           gdb::unique_xmalloc_ptr<char> actual_class_name
18717             (language_class_name_from_physname (cu->language_defn,
18718                                                 child_pdi->linkage_name));
18719           if (actual_class_name != NULL)
18720             {
18721               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18722               struct_pdi->name
18723                 = obstack_strdup (&objfile->per_bfd->storage_obstack,
18724                                   actual_class_name.get ());
18725             }
18726           break;
18727         }
18728     }
18729 }
18730
18731 void
18732 partial_die_info::fixup (struct dwarf2_cu *cu)
18733 {
18734   /* Once we've fixed up a die, there's no point in doing so again.
18735      This also avoids a memory leak if we were to call
18736      guess_partial_die_structure_name multiple times.  */
18737   if (fixup_called)
18738     return;
18739
18740   /* If we found a reference attribute and the DIE has no name, try
18741      to find a name in the referred to DIE.  */
18742
18743   if (name == NULL && has_specification)
18744     {
18745       struct partial_die_info *spec_die;
18746
18747       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
18748       spec_die = res.pdi;
18749       cu = res.cu;
18750
18751       spec_die->fixup (cu);
18752
18753       if (spec_die->name)
18754         {
18755           name = spec_die->name;
18756
18757           /* Copy DW_AT_external attribute if it is set.  */
18758           if (spec_die->is_external)
18759             is_external = spec_die->is_external;
18760         }
18761     }
18762
18763   /* Set default names for some unnamed DIEs.  */
18764
18765   if (name == NULL && tag == DW_TAG_namespace)
18766     name = CP_ANONYMOUS_NAMESPACE_STR;
18767
18768   /* If there is no parent die to provide a namespace, and there are
18769      children, see if we can determine the namespace from their linkage
18770      name.  */
18771   if (cu->language == language_cplus
18772       && !cu->per_cu->dwarf2_per_objfile->types.empty ()
18773       && die_parent == NULL
18774       && has_children
18775       && (tag == DW_TAG_class_type
18776           || tag == DW_TAG_structure_type
18777           || tag == DW_TAG_union_type))
18778     guess_partial_die_structure_name (this, cu);
18779
18780   /* GCC might emit a nameless struct or union that has a linkage
18781      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18782   if (name == NULL
18783       && (tag == DW_TAG_class_type
18784           || tag == DW_TAG_interface_type
18785           || tag == DW_TAG_structure_type
18786           || tag == DW_TAG_union_type)
18787       && linkage_name != NULL)
18788     {
18789       gdb::unique_xmalloc_ptr<char> demangled
18790         (gdb_demangle (linkage_name, DMGL_TYPES));
18791       if (demangled != nullptr)
18792         {
18793           const char *base;
18794
18795           /* Strip any leading namespaces/classes, keep only the base name.
18796              DW_AT_name for named DIEs does not contain the prefixes.  */
18797           base = strrchr (demangled.get (), ':');
18798           if (base && base > demangled.get () && base[-1] == ':')
18799             base++;
18800           else
18801             base = demangled.get ();
18802
18803           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18804           name = obstack_strdup (&objfile->per_bfd->storage_obstack, base);
18805         }
18806     }
18807
18808   fixup_called = 1;
18809 }
18810
18811 /* Process the attributes that had to be skipped in the first round. These
18812    attributes are the ones that need str_offsets_base or addr_base attributes.
18813    They could not have been processed in the first round, because at the time
18814    the values of str_offsets_base or addr_base may not have been known.  */
18815 void read_attribute_reprocess (const struct die_reader_specs *reader,
18816                                struct attribute *attr)
18817 {
18818   struct dwarf2_cu *cu = reader->cu;
18819   switch (attr->form)
18820     {
18821       case DW_FORM_addrx:
18822       case DW_FORM_GNU_addr_index:
18823         DW_ADDR (attr) = read_addr_index (cu, DW_UNSND (attr));
18824         break;
18825       case DW_FORM_strx:
18826       case DW_FORM_strx1:
18827       case DW_FORM_strx2:
18828       case DW_FORM_strx3:
18829       case DW_FORM_strx4:
18830       case DW_FORM_GNU_str_index:
18831         {
18832           unsigned int str_index = DW_UNSND (attr);
18833           if (reader->dwo_file != NULL)
18834             {
18835               DW_STRING (attr) = read_dwo_str_index (reader, str_index);
18836               DW_STRING_IS_CANONICAL (attr) = 0;
18837             }
18838           else
18839             {
18840               DW_STRING (attr) = read_stub_str_index (cu, str_index);
18841               DW_STRING_IS_CANONICAL (attr) = 0;
18842             }
18843           break;
18844         }
18845       default:
18846         gdb_assert_not_reached (_("Unexpected DWARF form."));
18847     }
18848 }
18849
18850 /* Read an attribute value described by an attribute form.  */
18851
18852 static const gdb_byte *
18853 read_attribute_value (const struct die_reader_specs *reader,
18854                       struct attribute *attr, unsigned form,
18855                       LONGEST implicit_const, const gdb_byte *info_ptr,
18856                       bool *need_reprocess)
18857 {
18858   struct dwarf2_cu *cu = reader->cu;
18859   struct dwarf2_per_objfile *dwarf2_per_objfile
18860     = cu->per_cu->dwarf2_per_objfile;
18861   struct objfile *objfile = dwarf2_per_objfile->objfile;
18862   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18863   bfd *abfd = reader->abfd;
18864   struct comp_unit_head *cu_header = &cu->header;
18865   unsigned int bytes_read;
18866   struct dwarf_block *blk;
18867   *need_reprocess = false;
18868
18869   attr->form = (enum dwarf_form) form;
18870   switch (form)
18871     {
18872     case DW_FORM_ref_addr:
18873       if (cu->header.version == 2)
18874         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18875       else
18876         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18877                                        &cu->header, &bytes_read);
18878       info_ptr += bytes_read;
18879       break;
18880     case DW_FORM_GNU_ref_alt:
18881       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18882       info_ptr += bytes_read;
18883       break;
18884     case DW_FORM_addr:
18885       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18886       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18887       info_ptr += bytes_read;
18888       break;
18889     case DW_FORM_block2:
18890       blk = dwarf_alloc_block (cu);
18891       blk->size = read_2_bytes (abfd, info_ptr);
18892       info_ptr += 2;
18893       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18894       info_ptr += blk->size;
18895       DW_BLOCK (attr) = blk;
18896       break;
18897     case DW_FORM_block4:
18898       blk = dwarf_alloc_block (cu);
18899       blk->size = read_4_bytes (abfd, info_ptr);
18900       info_ptr += 4;
18901       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18902       info_ptr += blk->size;
18903       DW_BLOCK (attr) = blk;
18904       break;
18905     case DW_FORM_data2:
18906       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18907       info_ptr += 2;
18908       break;
18909     case DW_FORM_data4:
18910       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18911       info_ptr += 4;
18912       break;
18913     case DW_FORM_data8:
18914       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18915       info_ptr += 8;
18916       break;
18917     case DW_FORM_data16:
18918       blk = dwarf_alloc_block (cu);
18919       blk->size = 16;
18920       blk->data = read_n_bytes (abfd, info_ptr, 16);
18921       info_ptr += 16;
18922       DW_BLOCK (attr) = blk;
18923       break;
18924     case DW_FORM_sec_offset:
18925       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18926       info_ptr += bytes_read;
18927       break;
18928     case DW_FORM_string:
18929       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18930       DW_STRING_IS_CANONICAL (attr) = 0;
18931       info_ptr += bytes_read;
18932       break;
18933     case DW_FORM_strp:
18934       if (!cu->per_cu->is_dwz)
18935         {
18936           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18937                                                    abfd, info_ptr, cu_header,
18938                                                    &bytes_read);
18939           DW_STRING_IS_CANONICAL (attr) = 0;
18940           info_ptr += bytes_read;
18941           break;
18942         }
18943       /* FALLTHROUGH */
18944     case DW_FORM_line_strp:
18945       if (!cu->per_cu->is_dwz)
18946         {
18947           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18948                                                         abfd, info_ptr,
18949                                                         cu_header, &bytes_read);
18950           DW_STRING_IS_CANONICAL (attr) = 0;
18951           info_ptr += bytes_read;
18952           break;
18953         }
18954       /* FALLTHROUGH */
18955     case DW_FORM_GNU_strp_alt:
18956       {
18957         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18958         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18959                                           &bytes_read);
18960
18961         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18962                                                           dwz, str_offset);
18963         DW_STRING_IS_CANONICAL (attr) = 0;
18964         info_ptr += bytes_read;
18965       }
18966       break;
18967     case DW_FORM_exprloc:
18968     case DW_FORM_block:
18969       blk = dwarf_alloc_block (cu);
18970       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18971       info_ptr += bytes_read;
18972       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18973       info_ptr += blk->size;
18974       DW_BLOCK (attr) = blk;
18975       break;
18976     case DW_FORM_block1:
18977       blk = dwarf_alloc_block (cu);
18978       blk->size = read_1_byte (abfd, info_ptr);
18979       info_ptr += 1;
18980       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18981       info_ptr += blk->size;
18982       DW_BLOCK (attr) = blk;
18983       break;
18984     case DW_FORM_data1:
18985       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18986       info_ptr += 1;
18987       break;
18988     case DW_FORM_flag:
18989       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18990       info_ptr += 1;
18991       break;
18992     case DW_FORM_flag_present:
18993       DW_UNSND (attr) = 1;
18994       break;
18995     case DW_FORM_sdata:
18996       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18997       info_ptr += bytes_read;
18998       break;
18999     case DW_FORM_udata:
19000     case DW_FORM_rnglistx:
19001       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19002       info_ptr += bytes_read;
19003       break;
19004     case DW_FORM_ref1:
19005       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19006                          + read_1_byte (abfd, info_ptr));
19007       info_ptr += 1;
19008       break;
19009     case DW_FORM_ref2:
19010       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19011                          + read_2_bytes (abfd, info_ptr));
19012       info_ptr += 2;
19013       break;
19014     case DW_FORM_ref4:
19015       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19016                          + read_4_bytes (abfd, info_ptr));
19017       info_ptr += 4;
19018       break;
19019     case DW_FORM_ref8:
19020       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19021                          + read_8_bytes (abfd, info_ptr));
19022       info_ptr += 8;
19023       break;
19024     case DW_FORM_ref_sig8:
19025       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19026       info_ptr += 8;
19027       break;
19028     case DW_FORM_ref_udata:
19029       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19030                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19031       info_ptr += bytes_read;
19032       break;
19033     case DW_FORM_indirect:
19034       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19035       info_ptr += bytes_read;
19036       if (form == DW_FORM_implicit_const)
19037         {
19038           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19039           info_ptr += bytes_read;
19040         }
19041       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19042                                        info_ptr, need_reprocess);
19043       break;
19044     case DW_FORM_implicit_const:
19045       DW_SND (attr) = implicit_const;
19046       break;
19047     case DW_FORM_addrx:
19048     case DW_FORM_GNU_addr_index:
19049       *need_reprocess = true;
19050       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19051       info_ptr += bytes_read;
19052       break;
19053     case DW_FORM_strx:
19054     case DW_FORM_strx1:
19055     case DW_FORM_strx2:
19056     case DW_FORM_strx3:
19057     case DW_FORM_strx4:
19058     case DW_FORM_GNU_str_index:
19059       {
19060         ULONGEST str_index;
19061         if (form == DW_FORM_strx1)
19062           {
19063             str_index = read_1_byte (abfd, info_ptr);
19064             info_ptr += 1;
19065           }
19066         else if (form == DW_FORM_strx2)
19067           {
19068             str_index = read_2_bytes (abfd, info_ptr);
19069             info_ptr += 2;
19070           }
19071         else if (form == DW_FORM_strx3)
19072           {
19073             str_index = read_3_bytes (abfd, info_ptr);
19074             info_ptr += 3;
19075           }
19076         else if (form == DW_FORM_strx4)
19077           {
19078             str_index = read_4_bytes (abfd, info_ptr);
19079             info_ptr += 4;
19080           }
19081         else
19082           {
19083             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19084             info_ptr += bytes_read;
19085           }
19086         *need_reprocess = true;
19087          DW_UNSND (attr) = str_index;
19088         }
19089       break;
19090     default:
19091       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19092              dwarf_form_name (form),
19093              bfd_get_filename (abfd));
19094     }
19095
19096   /* Super hack.  */
19097   if (cu->per_cu->is_dwz && attr->form_is_ref ())
19098     attr->form = DW_FORM_GNU_ref_alt;
19099
19100   /* We have seen instances where the compiler tried to emit a byte
19101      size attribute of -1 which ended up being encoded as an unsigned
19102      0xffffffff.  Although 0xffffffff is technically a valid size value,
19103      an object of this size seems pretty unlikely so we can relatively
19104      safely treat these cases as if the size attribute was invalid and
19105      treat them as zero by default.  */
19106   if (attr->name == DW_AT_byte_size
19107       && form == DW_FORM_data4
19108       && DW_UNSND (attr) >= 0xffffffff)
19109     {
19110       complaint
19111         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19112          hex_string (DW_UNSND (attr)));
19113       DW_UNSND (attr) = 0;
19114     }
19115
19116   return info_ptr;
19117 }
19118
19119 /* Read an attribute described by an abbreviated attribute.  */
19120
19121 static const gdb_byte *
19122 read_attribute (const struct die_reader_specs *reader,
19123                 struct attribute *attr, struct attr_abbrev *abbrev,
19124                 const gdb_byte *info_ptr, bool *need_reprocess)
19125 {
19126   attr->name = abbrev->name;
19127   return read_attribute_value (reader, attr, abbrev->form,
19128                                abbrev->implicit_const, info_ptr,
19129                                need_reprocess);
19130 }
19131
19132 static CORE_ADDR
19133 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19134               unsigned int *bytes_read)
19135 {
19136   struct comp_unit_head *cu_header = &cu->header;
19137   CORE_ADDR retval = 0;
19138
19139   if (cu_header->signed_addr_p)
19140     {
19141       switch (cu_header->addr_size)
19142         {
19143         case 2:
19144           retval = bfd_get_signed_16 (abfd, buf);
19145           break;
19146         case 4:
19147           retval = bfd_get_signed_32 (abfd, buf);
19148           break;
19149         case 8:
19150           retval = bfd_get_signed_64 (abfd, buf);
19151           break;
19152         default:
19153           internal_error (__FILE__, __LINE__,
19154                           _("read_address: bad switch, signed [in module %s]"),
19155                           bfd_get_filename (abfd));
19156         }
19157     }
19158   else
19159     {
19160       switch (cu_header->addr_size)
19161         {
19162         case 2:
19163           retval = bfd_get_16 (abfd, buf);
19164           break;
19165         case 4:
19166           retval = bfd_get_32 (abfd, buf);
19167           break;
19168         case 8:
19169           retval = bfd_get_64 (abfd, buf);
19170           break;
19171         default:
19172           internal_error (__FILE__, __LINE__,
19173                           _("read_address: bad switch, "
19174                             "unsigned [in module %s]"),
19175                           bfd_get_filename (abfd));
19176         }
19177     }
19178
19179   *bytes_read = cu_header->addr_size;
19180   return retval;
19181 }
19182
19183 /* Read the initial length from a section.  The (draft) DWARF 3
19184    specification allows the initial length to take up either 4 bytes
19185    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19186    bytes describe the length and all offsets will be 8 bytes in length
19187    instead of 4.
19188
19189    An older, non-standard 64-bit format is also handled by this
19190    function.  The older format in question stores the initial length
19191    as an 8-byte quantity without an escape value.  Lengths greater
19192    than 2^32 aren't very common which means that the initial 4 bytes
19193    is almost always zero.  Since a length value of zero doesn't make
19194    sense for the 32-bit format, this initial zero can be considered to
19195    be an escape value which indicates the presence of the older 64-bit
19196    format.  As written, the code can't detect (old format) lengths
19197    greater than 4GB.  If it becomes necessary to handle lengths
19198    somewhat larger than 4GB, we could allow other small values (such
19199    as the non-sensical values of 1, 2, and 3) to also be used as
19200    escape values indicating the presence of the old format.
19201
19202    The value returned via bytes_read should be used to increment the
19203    relevant pointer after calling read_initial_length().
19204
19205    [ Note:  read_initial_length() and read_offset() are based on the
19206      document entitled "DWARF Debugging Information Format", revision
19207      3, draft 8, dated November 19, 2001.  This document was obtained
19208      from:
19209
19210         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19211
19212      This document is only a draft and is subject to change.  (So beware.)
19213
19214      Details regarding the older, non-standard 64-bit format were
19215      determined empirically by examining 64-bit ELF files produced by
19216      the SGI toolchain on an IRIX 6.5 machine.
19217
19218      - Kevin, July 16, 2002
19219    ] */
19220
19221 static LONGEST
19222 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19223 {
19224   LONGEST length = bfd_get_32 (abfd, buf);
19225
19226   if (length == 0xffffffff)
19227     {
19228       length = bfd_get_64 (abfd, buf + 4);
19229       *bytes_read = 12;
19230     }
19231   else if (length == 0)
19232     {
19233       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19234       length = bfd_get_64 (abfd, buf);
19235       *bytes_read = 8;
19236     }
19237   else
19238     {
19239       *bytes_read = 4;
19240     }
19241
19242   return length;
19243 }
19244
19245 /* Cover function for read_initial_length.
19246    Returns the length of the object at BUF, and stores the size of the
19247    initial length in *BYTES_READ and stores the size that offsets will be in
19248    *OFFSET_SIZE.
19249    If the initial length size is not equivalent to that specified in
19250    CU_HEADER then issue a complaint.
19251    This is useful when reading non-comp-unit headers.  */
19252
19253 static LONGEST
19254 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19255                                         const struct comp_unit_head *cu_header,
19256                                         unsigned int *bytes_read,
19257                                         unsigned int *offset_size)
19258 {
19259   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19260
19261   gdb_assert (cu_header->initial_length_size == 4
19262               || cu_header->initial_length_size == 8
19263               || cu_header->initial_length_size == 12);
19264
19265   if (cu_header->initial_length_size != *bytes_read)
19266     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19267
19268   *offset_size = (*bytes_read == 4) ? 4 : 8;
19269   return length;
19270 }
19271
19272 /* Read an offset from the data stream.  The size of the offset is
19273    given by cu_header->offset_size.  */
19274
19275 static LONGEST
19276 read_offset (bfd *abfd, const gdb_byte *buf,
19277              const struct comp_unit_head *cu_header,
19278              unsigned int *bytes_read)
19279 {
19280   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19281
19282   *bytes_read = cu_header->offset_size;
19283   return offset;
19284 }
19285
19286 /* Read an offset from the data stream.  */
19287
19288 static LONGEST
19289 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19290 {
19291   LONGEST retval = 0;
19292
19293   switch (offset_size)
19294     {
19295     case 4:
19296       retval = bfd_get_32 (abfd, buf);
19297       break;
19298     case 8:
19299       retval = bfd_get_64 (abfd, buf);
19300       break;
19301     default:
19302       internal_error (__FILE__, __LINE__,
19303                       _("read_offset_1: bad switch [in module %s]"),
19304                       bfd_get_filename (abfd));
19305     }
19306
19307   return retval;
19308 }
19309
19310 static const gdb_byte *
19311 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19312 {
19313   /* If the size of a host char is 8 bits, we can return a pointer
19314      to the buffer, otherwise we have to copy the data to a buffer
19315      allocated on the temporary obstack.  */
19316   gdb_assert (HOST_CHAR_BIT == 8);
19317   return buf;
19318 }
19319
19320 static const char *
19321 read_direct_string (bfd *abfd, const gdb_byte *buf,
19322                     unsigned int *bytes_read_ptr)
19323 {
19324   /* If the size of a host char is 8 bits, we can return a pointer
19325      to the string, otherwise we have to copy the string to a buffer
19326      allocated on the temporary obstack.  */
19327   gdb_assert (HOST_CHAR_BIT == 8);
19328   if (*buf == '\0')
19329     {
19330       *bytes_read_ptr = 1;
19331       return NULL;
19332     }
19333   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19334   return (const char *) buf;
19335 }
19336
19337 /* Return pointer to string at section SECT offset STR_OFFSET with error
19338    reporting strings FORM_NAME and SECT_NAME.  */
19339
19340 static const char *
19341 read_indirect_string_at_offset_from (struct objfile *objfile,
19342                                      bfd *abfd, LONGEST str_offset,
19343                                      struct dwarf2_section_info *sect,
19344                                      const char *form_name,
19345                                      const char *sect_name)
19346 {
19347   sect->read (objfile);
19348   if (sect->buffer == NULL)
19349     error (_("%s used without %s section [in module %s]"),
19350            form_name, sect_name, bfd_get_filename (abfd));
19351   if (str_offset >= sect->size)
19352     error (_("%s pointing outside of %s section [in module %s]"),
19353            form_name, sect_name, bfd_get_filename (abfd));
19354   gdb_assert (HOST_CHAR_BIT == 8);
19355   if (sect->buffer[str_offset] == '\0')
19356     return NULL;
19357   return (const char *) (sect->buffer + str_offset);
19358 }
19359
19360 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19361
19362 static const char *
19363 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19364                                 bfd *abfd, LONGEST str_offset)
19365 {
19366   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19367                                               abfd, str_offset,
19368                                               &dwarf2_per_objfile->str,
19369                                               "DW_FORM_strp", ".debug_str");
19370 }
19371
19372 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19373
19374 static const char *
19375 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19376                                      bfd *abfd, LONGEST str_offset)
19377 {
19378   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19379                                               abfd, str_offset,
19380                                               &dwarf2_per_objfile->line_str,
19381                                               "DW_FORM_line_strp",
19382                                               ".debug_line_str");
19383 }
19384
19385 /* Read a string at offset STR_OFFSET in the .debug_str section from
19386    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19387    the string consists of a single NUL byte, return NULL; otherwise
19388    return a pointer to the string.  */
19389
19390 static const char *
19391 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19392                                LONGEST str_offset)
19393 {
19394   dwz->str.read (objfile);
19395
19396   if (dwz->str.buffer == NULL)
19397     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19398              "section [in module %s]"),
19399            bfd_get_filename (dwz->dwz_bfd.get ()));
19400   if (str_offset >= dwz->str.size)
19401     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19402              ".debug_str section [in module %s]"),
19403            bfd_get_filename (dwz->dwz_bfd.get ()));
19404   gdb_assert (HOST_CHAR_BIT == 8);
19405   if (dwz->str.buffer[str_offset] == '\0')
19406     return NULL;
19407   return (const char *) (dwz->str.buffer + str_offset);
19408 }
19409
19410 /* Return pointer to string at .debug_str offset as read from BUF.
19411    BUF is assumed to be in a compilation unit described by CU_HEADER.
19412    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19413
19414 static const char *
19415 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19416                       const gdb_byte *buf,
19417                       const struct comp_unit_head *cu_header,
19418                       unsigned int *bytes_read_ptr)
19419 {
19420   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19421
19422   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19423 }
19424
19425 /* Return pointer to string at .debug_line_str offset as read from BUF.
19426    BUF is assumed to be in a compilation unit described by CU_HEADER.
19427    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19428
19429 static const char *
19430 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19431                            bfd *abfd, const gdb_byte *buf,
19432                            const struct comp_unit_head *cu_header,
19433                            unsigned int *bytes_read_ptr)
19434 {
19435   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19436
19437   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19438                                               str_offset);
19439 }
19440
19441 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19442    ADDR_BASE is the DW_AT_addr_base (DW_AT_GNU_addr_base) attribute or zero.
19443    ADDR_SIZE is the size of addresses from the CU header.  */
19444
19445 static CORE_ADDR
19446 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19447                    unsigned int addr_index, gdb::optional<ULONGEST> addr_base,
19448                    int addr_size)
19449 {
19450   struct objfile *objfile = dwarf2_per_objfile->objfile;
19451   bfd *abfd = objfile->obfd;
19452   const gdb_byte *info_ptr;
19453   ULONGEST addr_base_or_zero = addr_base.has_value () ? *addr_base : 0;
19454
19455   dwarf2_per_objfile->addr.read (objfile);
19456   if (dwarf2_per_objfile->addr.buffer == NULL)
19457     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19458            objfile_name (objfile));
19459   if (addr_base_or_zero + addr_index * addr_size
19460       >= dwarf2_per_objfile->addr.size)
19461     error (_("DW_FORM_addr_index pointing outside of "
19462              ".debug_addr section [in module %s]"),
19463            objfile_name (objfile));
19464   info_ptr = (dwarf2_per_objfile->addr.buffer
19465               + addr_base_or_zero + addr_index * addr_size);
19466   if (addr_size == 4)
19467     return bfd_get_32 (abfd, info_ptr);
19468   else
19469     return bfd_get_64 (abfd, info_ptr);
19470 }
19471
19472 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19473
19474 static CORE_ADDR
19475 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19476 {
19477   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19478                             cu->addr_base, cu->header.addr_size);
19479 }
19480
19481 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19482
19483 static CORE_ADDR
19484 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19485                              unsigned int *bytes_read)
19486 {
19487   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19488   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19489
19490   return read_addr_index (cu, addr_index);
19491 }
19492
19493 /* Given an index in .debug_addr, fetch the value.
19494    NOTE: This can be called during dwarf expression evaluation,
19495    long after the debug information has been read, and thus per_cu->cu
19496    may no longer exist.  */
19497
19498 CORE_ADDR
19499 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19500                         unsigned int addr_index)
19501 {
19502   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19503   struct dwarf2_cu *cu = per_cu->cu;
19504   gdb::optional<ULONGEST> addr_base;
19505   int addr_size;
19506
19507   /* We need addr_base and addr_size.
19508      If we don't have PER_CU->cu, we have to get it.
19509      Nasty, but the alternative is storing the needed info in PER_CU,
19510      which at this point doesn't seem justified: it's not clear how frequently
19511      it would get used and it would increase the size of every PER_CU.
19512      Entry points like dwarf2_per_cu_addr_size do a similar thing
19513      so we're not in uncharted territory here.
19514      Alas we need to be a bit more complicated as addr_base is contained
19515      in the DIE.
19516
19517      We don't need to read the entire CU(/TU).
19518      We just need the header and top level die.
19519
19520      IWBN to use the aging mechanism to let us lazily later discard the CU.
19521      For now we skip this optimization.  */
19522
19523   if (cu != NULL)
19524     {
19525       addr_base = cu->addr_base;
19526       addr_size = cu->header.addr_size;
19527     }
19528   else
19529     {
19530       cutu_reader reader (per_cu, NULL, 0, 0, false);
19531       addr_base = reader.cu->addr_base;
19532       addr_size = reader.cu->header.addr_size;
19533     }
19534
19535   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19536                             addr_size);
19537 }
19538
19539 /* Given a DW_FORM_GNU_str_index value STR_INDEX, fetch the string.
19540    STR_SECTION, STR_OFFSETS_SECTION can be from a Fission stub or a
19541    DWO file.  */
19542
19543 static const char *
19544 read_str_index (struct dwarf2_cu *cu,
19545                 struct dwarf2_section_info *str_section,
19546                 struct dwarf2_section_info *str_offsets_section,
19547                 ULONGEST str_offsets_base, ULONGEST str_index)
19548 {
19549   struct dwarf2_per_objfile *dwarf2_per_objfile
19550     = cu->per_cu->dwarf2_per_objfile;
19551   struct objfile *objfile = dwarf2_per_objfile->objfile;
19552   const char *objf_name = objfile_name (objfile);
19553   bfd *abfd = objfile->obfd;
19554   const gdb_byte *info_ptr;
19555   ULONGEST str_offset;
19556   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
19557
19558   str_section->read (objfile);
19559   str_offsets_section->read (objfile);
19560   if (str_section->buffer == NULL)
19561     error (_("%s used without %s section"
19562              " in CU at offset %s [in module %s]"),
19563            form_name, str_section->get_name (),
19564            sect_offset_str (cu->header.sect_off), objf_name);
19565   if (str_offsets_section->buffer == NULL)
19566     error (_("%s used without %s section"
19567              " in CU at offset %s [in module %s]"),
19568            form_name, str_section->get_name (),
19569            sect_offset_str (cu->header.sect_off), objf_name);
19570   info_ptr = (str_offsets_section->buffer
19571               + str_offsets_base
19572               + str_index * cu->header.offset_size);
19573   if (cu->header.offset_size == 4)
19574     str_offset = bfd_get_32 (abfd, info_ptr);
19575   else
19576     str_offset = bfd_get_64 (abfd, info_ptr);
19577   if (str_offset >= str_section->size)
19578     error (_("Offset from %s pointing outside of"
19579              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19580            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19581   return (const char *) (str_section->buffer + str_offset);
19582 }
19583
19584 /* Given a DW_FORM_GNU_str_index from a DWO file, fetch the string.  */
19585
19586 static const char *
19587 read_dwo_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19588 {
19589   ULONGEST str_offsets_base = reader->cu->header.version >= 5
19590                               ? reader->cu->header.addr_size : 0;
19591   return read_str_index (reader->cu,
19592                          &reader->dwo_file->sections.str,
19593                          &reader->dwo_file->sections.str_offsets,
19594                          str_offsets_base, str_index);
19595 }
19596
19597 /* Given a DW_FORM_GNU_str_index from a Fission stub, fetch the string.  */
19598
19599 static const char *
19600 read_stub_str_index (struct dwarf2_cu *cu, ULONGEST str_index)
19601 {
19602   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19603   const char *objf_name = objfile_name (objfile);
19604   static const char form_name[] = "DW_FORM_GNU_str_index";
19605   static const char str_offsets_attr_name[] = "DW_AT_str_offsets";
19606
19607   if (!cu->str_offsets_base.has_value ())
19608     error (_("%s used in Fission stub without %s"
19609              " in CU at offset 0x%lx [in module %s]"),
19610            form_name, str_offsets_attr_name,
19611            (long) cu->header.offset_size, objf_name);
19612
19613   return read_str_index (cu,
19614                          &cu->per_cu->dwarf2_per_objfile->str,
19615                          &cu->per_cu->dwarf2_per_objfile->str_offsets,
19616                          *cu->str_offsets_base, str_index);
19617 }
19618
19619 /* Return the length of an LEB128 number in BUF.  */
19620
19621 static int
19622 leb128_size (const gdb_byte *buf)
19623 {
19624   const gdb_byte *begin = buf;
19625   gdb_byte byte;
19626
19627   while (1)
19628     {
19629       byte = *buf++;
19630       if ((byte & 128) == 0)
19631         return buf - begin;
19632     }
19633 }
19634
19635 static void
19636 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19637 {
19638   switch (lang)
19639     {
19640     case DW_LANG_C89:
19641     case DW_LANG_C99:
19642     case DW_LANG_C11:
19643     case DW_LANG_C:
19644     case DW_LANG_UPC:
19645       cu->language = language_c;
19646       break;
19647     case DW_LANG_Java:
19648     case DW_LANG_C_plus_plus:
19649     case DW_LANG_C_plus_plus_11:
19650     case DW_LANG_C_plus_plus_14:
19651       cu->language = language_cplus;
19652       break;
19653     case DW_LANG_D:
19654       cu->language = language_d;
19655       break;
19656     case DW_LANG_Fortran77:
19657     case DW_LANG_Fortran90:
19658     case DW_LANG_Fortran95:
19659     case DW_LANG_Fortran03:
19660     case DW_LANG_Fortran08:
19661       cu->language = language_fortran;
19662       break;
19663     case DW_LANG_Go:
19664       cu->language = language_go;
19665       break;
19666     case DW_LANG_Mips_Assembler:
19667       cu->language = language_asm;
19668       break;
19669     case DW_LANG_Ada83:
19670     case DW_LANG_Ada95:
19671       cu->language = language_ada;
19672       break;
19673     case DW_LANG_Modula2:
19674       cu->language = language_m2;
19675       break;
19676     case DW_LANG_Pascal83:
19677       cu->language = language_pascal;
19678       break;
19679     case DW_LANG_ObjC:
19680       cu->language = language_objc;
19681       break;
19682     case DW_LANG_Rust:
19683     case DW_LANG_Rust_old:
19684       cu->language = language_rust;
19685       break;
19686     case DW_LANG_Cobol74:
19687     case DW_LANG_Cobol85:
19688     default:
19689       cu->language = language_minimal;
19690       break;
19691     }
19692   cu->language_defn = language_def (cu->language);
19693 }
19694
19695 /* Return the named attribute or NULL if not there.  */
19696
19697 static struct attribute *
19698 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19699 {
19700   for (;;)
19701     {
19702       unsigned int i;
19703       struct attribute *spec = NULL;
19704
19705       for (i = 0; i < die->num_attrs; ++i)
19706         {
19707           if (die->attrs[i].name == name)
19708             return &die->attrs[i];
19709           if (die->attrs[i].name == DW_AT_specification
19710               || die->attrs[i].name == DW_AT_abstract_origin)
19711             spec = &die->attrs[i];
19712         }
19713
19714       if (!spec)
19715         break;
19716
19717       die = follow_die_ref (die, spec, &cu);
19718     }
19719
19720   return NULL;
19721 }
19722
19723 /* Return the named attribute or NULL if not there,
19724    but do not follow DW_AT_specification, etc.
19725    This is for use in contexts where we're reading .debug_types dies.
19726    Following DW_AT_specification, DW_AT_abstract_origin will take us
19727    back up the chain, and we want to go down.  */
19728
19729 static struct attribute *
19730 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19731 {
19732   unsigned int i;
19733
19734   for (i = 0; i < die->num_attrs; ++i)
19735     if (die->attrs[i].name == name)
19736       return &die->attrs[i];
19737
19738   return NULL;
19739 }
19740
19741 /* Return the string associated with a string-typed attribute, or NULL if it
19742    is either not found or is of an incorrect type.  */
19743
19744 static const char *
19745 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19746 {
19747   struct attribute *attr;
19748   const char *str = NULL;
19749
19750   attr = dwarf2_attr (die, name, cu);
19751
19752   if (attr != NULL)
19753     {
19754       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19755           || attr->form == DW_FORM_string
19756           || attr->form == DW_FORM_strx
19757           || attr->form == DW_FORM_strx1
19758           || attr->form == DW_FORM_strx2
19759           || attr->form == DW_FORM_strx3
19760           || attr->form == DW_FORM_strx4
19761           || attr->form == DW_FORM_GNU_str_index
19762           || attr->form == DW_FORM_GNU_strp_alt)
19763         str = DW_STRING (attr);
19764       else
19765         complaint (_("string type expected for attribute %s for "
19766                      "DIE at %s in module %s"),
19767                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19768                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19769     }
19770
19771   return str;
19772 }
19773
19774 /* Return the dwo name or NULL if not present. If present, it is in either
19775    DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.  */
19776 static const char *
19777 dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu)
19778 {
19779   const char *dwo_name = dwarf2_string_attr (die, DW_AT_GNU_dwo_name, cu);
19780   if (dwo_name == nullptr)
19781     dwo_name = dwarf2_string_attr (die, DW_AT_dwo_name, cu);
19782   return dwo_name;
19783 }
19784
19785 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19786    and holds a non-zero value.  This function should only be used for
19787    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19788
19789 static int
19790 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19791 {
19792   struct attribute *attr = dwarf2_attr (die, name, cu);
19793
19794   return (attr && DW_UNSND (attr));
19795 }
19796
19797 static int
19798 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19799 {
19800   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19801      which value is non-zero.  However, we have to be careful with
19802      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19803      (via dwarf2_flag_true_p) follows this attribute.  So we may
19804      end up accidently finding a declaration attribute that belongs
19805      to a different DIE referenced by the specification attribute,
19806      even though the given DIE does not have a declaration attribute.  */
19807   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19808           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19809 }
19810
19811 /* Return the die giving the specification for DIE, if there is
19812    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19813    containing the return value on output.  If there is no
19814    specification, but there is an abstract origin, that is
19815    returned.  */
19816
19817 static struct die_info *
19818 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19819 {
19820   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19821                                              *spec_cu);
19822
19823   if (spec_attr == NULL)
19824     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19825
19826   if (spec_attr == NULL)
19827     return NULL;
19828   else
19829     return follow_die_ref (die, spec_attr, spec_cu);
19830 }
19831
19832 /* Stub for free_line_header to match void * callback types.  */
19833
19834 static void
19835 free_line_header_voidp (void *arg)
19836 {
19837   struct line_header *lh = (struct line_header *) arg;
19838
19839   delete lh;
19840 }
19841
19842 void
19843 line_header::add_include_dir (const char *include_dir)
19844 {
19845   if (dwarf_line_debug >= 2)
19846     {
19847       size_t new_size;
19848       if (version >= 5)
19849         new_size = m_include_dirs.size ();
19850       else
19851         new_size = m_include_dirs.size () + 1;
19852       fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19853                           new_size, include_dir);
19854     }
19855   m_include_dirs.push_back (include_dir);
19856 }
19857
19858 void
19859 line_header::add_file_name (const char *name,
19860                             dir_index d_index,
19861                             unsigned int mod_time,
19862                             unsigned int length)
19863 {
19864   if (dwarf_line_debug >= 2)
19865     {
19866       size_t new_size;
19867       if (version >= 5)
19868         new_size = file_names_size ();
19869       else
19870         new_size = file_names_size () + 1;
19871       fprintf_unfiltered (gdb_stdlog, "Adding file %zu: %s\n",
19872                           new_size, name);
19873     }
19874   m_file_names.emplace_back (name, d_index, mod_time, length);
19875 }
19876
19877 /* A convenience function to find the proper .debug_line section for a CU.  */
19878
19879 static struct dwarf2_section_info *
19880 get_debug_line_section (struct dwarf2_cu *cu)
19881 {
19882   struct dwarf2_section_info *section;
19883   struct dwarf2_per_objfile *dwarf2_per_objfile
19884     = cu->per_cu->dwarf2_per_objfile;
19885
19886   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19887      DWO file.  */
19888   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19889     section = &cu->dwo_unit->dwo_file->sections.line;
19890   else if (cu->per_cu->is_dwz)
19891     {
19892       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19893
19894       section = &dwz->line;
19895     }
19896   else
19897     section = &dwarf2_per_objfile->line;
19898
19899   return section;
19900 }
19901
19902 /* Read directory or file name entry format, starting with byte of
19903    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19904    entries count and the entries themselves in the described entry
19905    format.  */
19906
19907 static void
19908 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19909                         bfd *abfd, const gdb_byte **bufp,
19910                         struct line_header *lh,
19911                         const struct comp_unit_head *cu_header,
19912                         void (*callback) (struct line_header *lh,
19913                                           const char *name,
19914                                           dir_index d_index,
19915                                           unsigned int mod_time,
19916                                           unsigned int length))
19917 {
19918   gdb_byte format_count, formati;
19919   ULONGEST data_count, datai;
19920   const gdb_byte *buf = *bufp;
19921   const gdb_byte *format_header_data;
19922   unsigned int bytes_read;
19923
19924   format_count = read_1_byte (abfd, buf);
19925   buf += 1;
19926   format_header_data = buf;
19927   for (formati = 0; formati < format_count; formati++)
19928     {
19929       read_unsigned_leb128 (abfd, buf, &bytes_read);
19930       buf += bytes_read;
19931       read_unsigned_leb128 (abfd, buf, &bytes_read);
19932       buf += bytes_read;
19933     }
19934
19935   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19936   buf += bytes_read;
19937   for (datai = 0; datai < data_count; datai++)
19938     {
19939       const gdb_byte *format = format_header_data;
19940       struct file_entry fe;
19941
19942       for (formati = 0; formati < format_count; formati++)
19943         {
19944           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19945           format += bytes_read;
19946
19947           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19948           format += bytes_read;
19949
19950           gdb::optional<const char *> string;
19951           gdb::optional<unsigned int> uint;
19952
19953           switch (form)
19954             {
19955             case DW_FORM_string:
19956               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19957               buf += bytes_read;
19958               break;
19959
19960             case DW_FORM_line_strp:
19961               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
19962                                                          abfd, buf,
19963                                                          cu_header,
19964                                                          &bytes_read));
19965               buf += bytes_read;
19966               break;
19967
19968             case DW_FORM_data1:
19969               uint.emplace (read_1_byte (abfd, buf));
19970               buf += 1;
19971               break;
19972
19973             case DW_FORM_data2:
19974               uint.emplace (read_2_bytes (abfd, buf));
19975               buf += 2;
19976               break;
19977
19978             case DW_FORM_data4:
19979               uint.emplace (read_4_bytes (abfd, buf));
19980               buf += 4;
19981               break;
19982
19983             case DW_FORM_data8:
19984               uint.emplace (read_8_bytes (abfd, buf));
19985               buf += 8;
19986               break;
19987
19988             case DW_FORM_data16:
19989               /*  This is used for MD5, but file_entry does not record MD5s. */
19990               buf += 16;
19991               break;
19992
19993             case DW_FORM_udata:
19994               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
19995               buf += bytes_read;
19996               break;
19997
19998             case DW_FORM_block:
19999               /* It is valid only for DW_LNCT_timestamp which is ignored by
20000                  current GDB.  */
20001               break;
20002             }
20003
20004           switch (content_type)
20005             {
20006             case DW_LNCT_path:
20007               if (string.has_value ())
20008                 fe.name = *string;
20009               break;
20010             case DW_LNCT_directory_index:
20011               if (uint.has_value ())
20012                 fe.d_index = (dir_index) *uint;
20013               break;
20014             case DW_LNCT_timestamp:
20015               if (uint.has_value ())
20016                 fe.mod_time = *uint;
20017               break;
20018             case DW_LNCT_size:
20019               if (uint.has_value ())
20020                 fe.length = *uint;
20021               break;
20022             case DW_LNCT_MD5:
20023               break;
20024             default:
20025               complaint (_("Unknown format content type %s"),
20026                          pulongest (content_type));
20027             }
20028         }
20029
20030       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20031     }
20032
20033   *bufp = buf;
20034 }
20035
20036 /* Read the statement program header starting at OFFSET in
20037    .debug_line, or .debug_line.dwo.  Return a pointer
20038    to a struct line_header, allocated using xmalloc.
20039    Returns NULL if there is a problem reading the header, e.g., if it
20040    has a version we don't understand.
20041
20042    NOTE: the strings in the include directory and file name tables of
20043    the returned object point into the dwarf line section buffer,
20044    and must not be freed.  */
20045
20046 static line_header_up
20047 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20048 {
20049   const gdb_byte *line_ptr;
20050   unsigned int bytes_read, offset_size;
20051   int i;
20052   const char *cur_dir, *cur_file;
20053   struct dwarf2_section_info *section;
20054   bfd *abfd;
20055   struct dwarf2_per_objfile *dwarf2_per_objfile
20056     = cu->per_cu->dwarf2_per_objfile;
20057
20058   section = get_debug_line_section (cu);
20059   section->read (dwarf2_per_objfile->objfile);
20060   if (section->buffer == NULL)
20061     {
20062       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20063         complaint (_("missing .debug_line.dwo section"));
20064       else
20065         complaint (_("missing .debug_line section"));
20066       return 0;
20067     }
20068
20069   /* We can't do this until we know the section is non-empty.
20070      Only then do we know we have such a section.  */
20071   abfd = section->get_bfd_owner ();
20072
20073   /* Make sure that at least there's room for the total_length field.
20074      That could be 12 bytes long, but we're just going to fudge that.  */
20075   if (to_underlying (sect_off) + 4 >= section->size)
20076     {
20077       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20078       return 0;
20079     }
20080
20081   line_header_up lh (new line_header ());
20082
20083   lh->sect_off = sect_off;
20084   lh->offset_in_dwz = cu->per_cu->is_dwz;
20085
20086   line_ptr = section->buffer + to_underlying (sect_off);
20087
20088   /* Read in the header.  */
20089   lh->total_length =
20090     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20091                                             &bytes_read, &offset_size);
20092   line_ptr += bytes_read;
20093
20094   const gdb_byte *start_here = line_ptr;
20095
20096   if (line_ptr + lh->total_length > (section->buffer + section->size))
20097     {
20098       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20099       return 0;
20100     }
20101   lh->statement_program_end = start_here + lh->total_length;
20102   lh->version = read_2_bytes (abfd, line_ptr);
20103   line_ptr += 2;
20104   if (lh->version > 5)
20105     {
20106       /* This is a version we don't understand.  The format could have
20107          changed in ways we don't handle properly so just punt.  */
20108       complaint (_("unsupported version in .debug_line section"));
20109       return NULL;
20110     }
20111   if (lh->version >= 5)
20112     {
20113       gdb_byte segment_selector_size;
20114
20115       /* Skip address size.  */
20116       read_1_byte (abfd, line_ptr);
20117       line_ptr += 1;
20118
20119       segment_selector_size = read_1_byte (abfd, line_ptr);
20120       line_ptr += 1;
20121       if (segment_selector_size != 0)
20122         {
20123           complaint (_("unsupported segment selector size %u "
20124                        "in .debug_line section"),
20125                      segment_selector_size);
20126           return NULL;
20127         }
20128     }
20129   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20130   line_ptr += offset_size;
20131   lh->statement_program_start = line_ptr + lh->header_length;
20132   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20133   line_ptr += 1;
20134   if (lh->version >= 4)
20135     {
20136       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20137       line_ptr += 1;
20138     }
20139   else
20140     lh->maximum_ops_per_instruction = 1;
20141
20142   if (lh->maximum_ops_per_instruction == 0)
20143     {
20144       lh->maximum_ops_per_instruction = 1;
20145       complaint (_("invalid maximum_ops_per_instruction "
20146                    "in `.debug_line' section"));
20147     }
20148
20149   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20150   line_ptr += 1;
20151   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20152   line_ptr += 1;
20153   lh->line_range = read_1_byte (abfd, line_ptr);
20154   line_ptr += 1;
20155   lh->opcode_base = read_1_byte (abfd, line_ptr);
20156   line_ptr += 1;
20157   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20158
20159   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20160   for (i = 1; i < lh->opcode_base; ++i)
20161     {
20162       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20163       line_ptr += 1;
20164     }
20165
20166   if (lh->version >= 5)
20167     {
20168       /* Read directory table.  */
20169       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20170                               &cu->header,
20171                               [] (struct line_header *header, const char *name,
20172                                   dir_index d_index, unsigned int mod_time,
20173                                   unsigned int length)
20174         {
20175           header->add_include_dir (name);
20176         });
20177
20178       /* Read file name table.  */
20179       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20180                               &cu->header,
20181                               [] (struct line_header *header, const char *name,
20182                                   dir_index d_index, unsigned int mod_time,
20183                                   unsigned int length)
20184         {
20185           header->add_file_name (name, d_index, mod_time, length);
20186         });
20187     }
20188   else
20189     {
20190       /* Read directory table.  */
20191       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20192         {
20193           line_ptr += bytes_read;
20194           lh->add_include_dir (cur_dir);
20195         }
20196       line_ptr += bytes_read;
20197
20198       /* Read file name table.  */
20199       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20200         {
20201           unsigned int mod_time, length;
20202           dir_index d_index;
20203
20204           line_ptr += bytes_read;
20205           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20206           line_ptr += bytes_read;
20207           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20208           line_ptr += bytes_read;
20209           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20210           line_ptr += bytes_read;
20211
20212           lh->add_file_name (cur_file, d_index, mod_time, length);
20213         }
20214       line_ptr += bytes_read;
20215     }
20216
20217   if (line_ptr > (section->buffer + section->size))
20218     complaint (_("line number info header doesn't "
20219                  "fit in `.debug_line' section"));
20220
20221   return lh;
20222 }
20223
20224 /* Subroutine of dwarf_decode_lines to simplify it.
20225    Return the file name of the psymtab for the given file_entry.
20226    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20227    If space for the result is malloc'd, *NAME_HOLDER will be set.
20228    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20229
20230 static const char *
20231 psymtab_include_file_name (const struct line_header *lh, const file_entry &fe,
20232                            const dwarf2_psymtab *pst,
20233                            const char *comp_dir,
20234                            gdb::unique_xmalloc_ptr<char> *name_holder)
20235 {
20236   const char *include_name = fe.name;
20237   const char *include_name_to_compare = include_name;
20238   const char *pst_filename;
20239   int file_is_pst;
20240
20241   const char *dir_name = fe.include_dir (lh);
20242
20243   gdb::unique_xmalloc_ptr<char> hold_compare;
20244   if (!IS_ABSOLUTE_PATH (include_name)
20245       && (dir_name != NULL || comp_dir != NULL))
20246     {
20247       /* Avoid creating a duplicate psymtab for PST.
20248          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20249          Before we do the comparison, however, we need to account
20250          for DIR_NAME and COMP_DIR.
20251          First prepend dir_name (if non-NULL).  If we still don't
20252          have an absolute path prepend comp_dir (if non-NULL).
20253          However, the directory we record in the include-file's
20254          psymtab does not contain COMP_DIR (to match the
20255          corresponding symtab(s)).
20256
20257          Example:
20258
20259          bash$ cd /tmp
20260          bash$ gcc -g ./hello.c
20261          include_name = "hello.c"
20262          dir_name = "."
20263          DW_AT_comp_dir = comp_dir = "/tmp"
20264          DW_AT_name = "./hello.c"
20265
20266       */
20267
20268       if (dir_name != NULL)
20269         {
20270           name_holder->reset (concat (dir_name, SLASH_STRING,
20271                                       include_name, (char *) NULL));
20272           include_name = name_holder->get ();
20273           include_name_to_compare = include_name;
20274         }
20275       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20276         {
20277           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20278                                       include_name, (char *) NULL));
20279           include_name_to_compare = hold_compare.get ();
20280         }
20281     }
20282
20283   pst_filename = pst->filename;
20284   gdb::unique_xmalloc_ptr<char> copied_name;
20285   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20286     {
20287       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20288                                  pst_filename, (char *) NULL));
20289       pst_filename = copied_name.get ();
20290     }
20291
20292   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20293
20294   if (file_is_pst)
20295     return NULL;
20296   return include_name;
20297 }
20298
20299 /* State machine to track the state of the line number program.  */
20300
20301 class lnp_state_machine
20302 {
20303 public:
20304   /* Initialize a machine state for the start of a line number
20305      program.  */
20306   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20307                      bool record_lines_p);
20308
20309   file_entry *current_file ()
20310   {
20311     /* lh->file_names is 0-based, but the file name numbers in the
20312        statement program are 1-based.  */
20313     return m_line_header->file_name_at (m_file);
20314   }
20315
20316   /* Record the line in the state machine.  END_SEQUENCE is true if
20317      we're processing the end of a sequence.  */
20318   void record_line (bool end_sequence);
20319
20320   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20321      nop-out rest of the lines in this sequence.  */
20322   void check_line_address (struct dwarf2_cu *cu,
20323                            const gdb_byte *line_ptr,
20324                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20325
20326   void handle_set_discriminator (unsigned int discriminator)
20327   {
20328     m_discriminator = discriminator;
20329     m_line_has_non_zero_discriminator |= discriminator != 0;
20330   }
20331
20332   /* Handle DW_LNE_set_address.  */
20333   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20334   {
20335     m_op_index = 0;
20336     address += baseaddr;
20337     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20338   }
20339
20340   /* Handle DW_LNS_advance_pc.  */
20341   void handle_advance_pc (CORE_ADDR adjust);
20342
20343   /* Handle a special opcode.  */
20344   void handle_special_opcode (unsigned char op_code);
20345
20346   /* Handle DW_LNS_advance_line.  */
20347   void handle_advance_line (int line_delta)
20348   {
20349     advance_line (line_delta);
20350   }
20351
20352   /* Handle DW_LNS_set_file.  */
20353   void handle_set_file (file_name_index file);
20354
20355   /* Handle DW_LNS_negate_stmt.  */
20356   void handle_negate_stmt ()
20357   {
20358     m_is_stmt = !m_is_stmt;
20359   }
20360
20361   /* Handle DW_LNS_const_add_pc.  */
20362   void handle_const_add_pc ();
20363
20364   /* Handle DW_LNS_fixed_advance_pc.  */
20365   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20366   {
20367     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20368     m_op_index = 0;
20369   }
20370
20371   /* Handle DW_LNS_copy.  */
20372   void handle_copy ()
20373   {
20374     record_line (false);
20375     m_discriminator = 0;
20376   }
20377
20378   /* Handle DW_LNE_end_sequence.  */
20379   void handle_end_sequence ()
20380   {
20381     m_currently_recording_lines = true;
20382   }
20383
20384 private:
20385   /* Advance the line by LINE_DELTA.  */
20386   void advance_line (int line_delta)
20387   {
20388     m_line += line_delta;
20389
20390     if (line_delta != 0)
20391       m_line_has_non_zero_discriminator = m_discriminator != 0;
20392   }
20393
20394   struct dwarf2_cu *m_cu;
20395
20396   gdbarch *m_gdbarch;
20397
20398   /* True if we're recording lines.
20399      Otherwise we're building partial symtabs and are just interested in
20400      finding include files mentioned by the line number program.  */
20401   bool m_record_lines_p;
20402
20403   /* The line number header.  */
20404   line_header *m_line_header;
20405
20406   /* These are part of the standard DWARF line number state machine,
20407      and initialized according to the DWARF spec.  */
20408
20409   unsigned char m_op_index = 0;
20410   /* The line table index of the current file.  */
20411   file_name_index m_file = 1;
20412   unsigned int m_line = 1;
20413
20414   /* These are initialized in the constructor.  */
20415
20416   CORE_ADDR m_address;
20417   bool m_is_stmt;
20418   unsigned int m_discriminator;
20419
20420   /* Additional bits of state we need to track.  */
20421
20422   /* The last file that we called dwarf2_start_subfile for.
20423      This is only used for TLLs.  */
20424   unsigned int m_last_file = 0;
20425   /* The last file a line number was recorded for.  */
20426   struct subfile *m_last_subfile = NULL;
20427
20428   /* When true, record the lines we decode.  */
20429   bool m_currently_recording_lines = false;
20430
20431   /* The last line number that was recorded, used to coalesce
20432      consecutive entries for the same line.  This can happen, for
20433      example, when discriminators are present.  PR 17276.  */
20434   unsigned int m_last_line = 0;
20435   bool m_line_has_non_zero_discriminator = false;
20436 };
20437
20438 void
20439 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20440 {
20441   CORE_ADDR addr_adj = (((m_op_index + adjust)
20442                          / m_line_header->maximum_ops_per_instruction)
20443                         * m_line_header->minimum_instruction_length);
20444   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20445   m_op_index = ((m_op_index + adjust)
20446                 % m_line_header->maximum_ops_per_instruction);
20447 }
20448
20449 void
20450 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20451 {
20452   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20453   CORE_ADDR addr_adj = (((m_op_index
20454                           + (adj_opcode / m_line_header->line_range))
20455                          / m_line_header->maximum_ops_per_instruction)
20456                         * m_line_header->minimum_instruction_length);
20457   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20458   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20459                 % m_line_header->maximum_ops_per_instruction);
20460
20461   int line_delta = (m_line_header->line_base
20462                     + (adj_opcode % m_line_header->line_range));
20463   advance_line (line_delta);
20464   record_line (false);
20465   m_discriminator = 0;
20466 }
20467
20468 void
20469 lnp_state_machine::handle_set_file (file_name_index file)
20470 {
20471   m_file = file;
20472
20473   const file_entry *fe = current_file ();
20474   if (fe == NULL)
20475     dwarf2_debug_line_missing_file_complaint ();
20476   else if (m_record_lines_p)
20477     {
20478       const char *dir = fe->include_dir (m_line_header);
20479
20480       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20481       m_line_has_non_zero_discriminator = m_discriminator != 0;
20482       dwarf2_start_subfile (m_cu, fe->name, dir);
20483     }
20484 }
20485
20486 void
20487 lnp_state_machine::handle_const_add_pc ()
20488 {
20489   CORE_ADDR adjust
20490     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20491
20492   CORE_ADDR addr_adj
20493     = (((m_op_index + adjust)
20494         / m_line_header->maximum_ops_per_instruction)
20495        * m_line_header->minimum_instruction_length);
20496
20497   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20498   m_op_index = ((m_op_index + adjust)
20499                 % m_line_header->maximum_ops_per_instruction);
20500 }
20501
20502 /* Return non-zero if we should add LINE to the line number table.
20503    LINE is the line to add, LAST_LINE is the last line that was added,
20504    LAST_SUBFILE is the subfile for LAST_LINE.
20505    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20506    had a non-zero discriminator.
20507
20508    We have to be careful in the presence of discriminators.
20509    E.g., for this line:
20510
20511      for (i = 0; i < 100000; i++);
20512
20513    clang can emit four line number entries for that one line,
20514    each with a different discriminator.
20515    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20516
20517    However, we want gdb to coalesce all four entries into one.
20518    Otherwise the user could stepi into the middle of the line and
20519    gdb would get confused about whether the pc really was in the
20520    middle of the line.
20521
20522    Things are further complicated by the fact that two consecutive
20523    line number entries for the same line is a heuristic used by gcc
20524    to denote the end of the prologue.  So we can't just discard duplicate
20525    entries, we have to be selective about it.  The heuristic we use is
20526    that we only collapse consecutive entries for the same line if at least
20527    one of those entries has a non-zero discriminator.  PR 17276.
20528
20529    Note: Addresses in the line number state machine can never go backwards
20530    within one sequence, thus this coalescing is ok.  */
20531
20532 static int
20533 dwarf_record_line_p (struct dwarf2_cu *cu,
20534                      unsigned int line, unsigned int last_line,
20535                      int line_has_non_zero_discriminator,
20536                      struct subfile *last_subfile)
20537 {
20538   if (cu->get_builder ()->get_current_subfile () != last_subfile)
20539     return 1;
20540   if (line != last_line)
20541     return 1;
20542   /* Same line for the same file that we've seen already.
20543      As a last check, for pr 17276, only record the line if the line
20544      has never had a non-zero discriminator.  */
20545   if (!line_has_non_zero_discriminator)
20546     return 1;
20547   return 0;
20548 }
20549
20550 /* Use the CU's builder to record line number LINE beginning at
20551    address ADDRESS in the line table of subfile SUBFILE.  */
20552
20553 static void
20554 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20555                      unsigned int line, CORE_ADDR address,
20556                      struct dwarf2_cu *cu)
20557 {
20558   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20559
20560   if (dwarf_line_debug)
20561     {
20562       fprintf_unfiltered (gdb_stdlog,
20563                           "Recording line %u, file %s, address %s\n",
20564                           line, lbasename (subfile->name),
20565                           paddress (gdbarch, address));
20566     }
20567
20568   if (cu != nullptr)
20569     cu->get_builder ()->record_line (subfile, line, addr);
20570 }
20571
20572 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20573    Mark the end of a set of line number records.
20574    The arguments are the same as for dwarf_record_line_1.
20575    If SUBFILE is NULL the request is ignored.  */
20576
20577 static void
20578 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20579                    CORE_ADDR address, struct dwarf2_cu *cu)
20580 {
20581   if (subfile == NULL)
20582     return;
20583
20584   if (dwarf_line_debug)
20585     {
20586       fprintf_unfiltered (gdb_stdlog,
20587                           "Finishing current line, file %s, address %s\n",
20588                           lbasename (subfile->name),
20589                           paddress (gdbarch, address));
20590     }
20591
20592   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20593 }
20594
20595 void
20596 lnp_state_machine::record_line (bool end_sequence)
20597 {
20598   if (dwarf_line_debug)
20599     {
20600       fprintf_unfiltered (gdb_stdlog,
20601                           "Processing actual line %u: file %u,"
20602                           " address %s, is_stmt %u, discrim %u%s\n",
20603                           m_line, m_file,
20604                           paddress (m_gdbarch, m_address),
20605                           m_is_stmt, m_discriminator,
20606                           (end_sequence ? "\t(end sequence)" : ""));
20607     }
20608
20609   file_entry *fe = current_file ();
20610
20611   if (fe == NULL)
20612     dwarf2_debug_line_missing_file_complaint ();
20613   /* For now we ignore lines not starting on an instruction boundary.
20614      But not when processing end_sequence for compatibility with the
20615      previous version of the code.  */
20616   else if (m_op_index == 0 || end_sequence)
20617     {
20618       fe->included_p = 1;
20619       if (m_record_lines_p
20620           && (producer_is_codewarrior (m_cu) || m_is_stmt || end_sequence))
20621         {
20622           if (m_last_subfile != m_cu->get_builder ()->get_current_subfile ()
20623               || end_sequence)
20624             {
20625               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20626                                  m_currently_recording_lines ? m_cu : nullptr);
20627             }
20628
20629           if (!end_sequence)
20630             {
20631               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20632                                        m_line_has_non_zero_discriminator,
20633                                        m_last_subfile))
20634                 {
20635                   buildsym_compunit *builder = m_cu->get_builder ();
20636                   dwarf_record_line_1 (m_gdbarch,
20637                                        builder->get_current_subfile (),
20638                                        m_line, m_address,
20639                                        m_currently_recording_lines ? m_cu : nullptr);
20640                 }
20641               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20642               m_last_line = m_line;
20643             }
20644         }
20645     }
20646 }
20647
20648 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20649                                       line_header *lh, bool record_lines_p)
20650 {
20651   m_cu = cu;
20652   m_gdbarch = arch;
20653   m_record_lines_p = record_lines_p;
20654   m_line_header = lh;
20655
20656   m_currently_recording_lines = true;
20657
20658   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20659      was a line entry for it so that the backend has a chance to adjust it
20660      and also record it in case it needs it.  This is currently used by MIPS
20661      code, cf. `mips_adjust_dwarf2_line'.  */
20662   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20663   m_is_stmt = lh->default_is_stmt;
20664   m_discriminator = 0;
20665 }
20666
20667 void
20668 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20669                                        const gdb_byte *line_ptr,
20670                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20671 {
20672   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20673      the pc range of the CU.  However, we restrict the test to only ADDRESS
20674      values of zero to preserve GDB's previous behaviour which is to handle
20675      the specific case of a function being GC'd by the linker.  */
20676
20677   if (address == 0 && address < unrelocated_lowpc)
20678     {
20679       /* This line table is for a function which has been
20680          GCd by the linker.  Ignore it.  PR gdb/12528 */
20681
20682       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20683       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20684
20685       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20686                  line_offset, objfile_name (objfile));
20687       m_currently_recording_lines = false;
20688       /* Note: m_currently_recording_lines is left as false until we see
20689          DW_LNE_end_sequence.  */
20690     }
20691 }
20692
20693 /* Subroutine of dwarf_decode_lines to simplify it.
20694    Process the line number information in LH.
20695    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20696    program in order to set included_p for every referenced header.  */
20697
20698 static void
20699 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20700                       const int decode_for_pst_p, CORE_ADDR lowpc)
20701 {
20702   const gdb_byte *line_ptr, *extended_end;
20703   const gdb_byte *line_end;
20704   unsigned int bytes_read, extended_len;
20705   unsigned char op_code, extended_op;
20706   CORE_ADDR baseaddr;
20707   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20708   bfd *abfd = objfile->obfd;
20709   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20710   /* True if we're recording line info (as opposed to building partial
20711      symtabs and just interested in finding include files mentioned by
20712      the line number program).  */
20713   bool record_lines_p = !decode_for_pst_p;
20714
20715   baseaddr = objfile->text_section_offset ();
20716
20717   line_ptr = lh->statement_program_start;
20718   line_end = lh->statement_program_end;
20719
20720   /* Read the statement sequences until there's nothing left.  */
20721   while (line_ptr < line_end)
20722     {
20723       /* The DWARF line number program state machine.  Reset the state
20724          machine at the start of each sequence.  */
20725       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
20726       bool end_sequence = false;
20727
20728       if (record_lines_p)
20729         {
20730           /* Start a subfile for the current file of the state
20731              machine.  */
20732           const file_entry *fe = state_machine.current_file ();
20733
20734           if (fe != NULL)
20735             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
20736         }
20737
20738       /* Decode the table.  */
20739       while (line_ptr < line_end && !end_sequence)
20740         {
20741           op_code = read_1_byte (abfd, line_ptr);
20742           line_ptr += 1;
20743
20744           if (op_code >= lh->opcode_base)
20745             {
20746               /* Special opcode.  */
20747               state_machine.handle_special_opcode (op_code);
20748             }
20749           else switch (op_code)
20750             {
20751             case DW_LNS_extended_op:
20752               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20753                                                    &bytes_read);
20754               line_ptr += bytes_read;
20755               extended_end = line_ptr + extended_len;
20756               extended_op = read_1_byte (abfd, line_ptr);
20757               line_ptr += 1;
20758               switch (extended_op)
20759                 {
20760                 case DW_LNE_end_sequence:
20761                   state_machine.handle_end_sequence ();
20762                   end_sequence = true;
20763                   break;
20764                 case DW_LNE_set_address:
20765                   {
20766                     CORE_ADDR address
20767                       = read_address (abfd, line_ptr, cu, &bytes_read);
20768                     line_ptr += bytes_read;
20769
20770                     state_machine.check_line_address (cu, line_ptr,
20771                                                       lowpc - baseaddr, address);
20772                     state_machine.handle_set_address (baseaddr, address);
20773                   }
20774                   break;
20775                 case DW_LNE_define_file:
20776                   {
20777                     const char *cur_file;
20778                     unsigned int mod_time, length;
20779                     dir_index dindex;
20780
20781                     cur_file = read_direct_string (abfd, line_ptr,
20782                                                    &bytes_read);
20783                     line_ptr += bytes_read;
20784                     dindex = (dir_index)
20785                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20786                     line_ptr += bytes_read;
20787                     mod_time =
20788                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20789                     line_ptr += bytes_read;
20790                     length =
20791                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20792                     line_ptr += bytes_read;
20793                     lh->add_file_name (cur_file, dindex, mod_time, length);
20794                   }
20795                   break;
20796                 case DW_LNE_set_discriminator:
20797                   {
20798                     /* The discriminator is not interesting to the
20799                        debugger; just ignore it.  We still need to
20800                        check its value though:
20801                        if there are consecutive entries for the same
20802                        (non-prologue) line we want to coalesce them.
20803                        PR 17276.  */
20804                     unsigned int discr
20805                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20806                     line_ptr += bytes_read;
20807
20808                     state_machine.handle_set_discriminator (discr);
20809                   }
20810                   break;
20811                 default:
20812                   complaint (_("mangled .debug_line section"));
20813                   return;
20814                 }
20815               /* Make sure that we parsed the extended op correctly.  If e.g.
20816                  we expected a different address size than the producer used,
20817                  we may have read the wrong number of bytes.  */
20818               if (line_ptr != extended_end)
20819                 {
20820                   complaint (_("mangled .debug_line section"));
20821                   return;
20822                 }
20823               break;
20824             case DW_LNS_copy:
20825               state_machine.handle_copy ();
20826               break;
20827             case DW_LNS_advance_pc:
20828               {
20829                 CORE_ADDR adjust
20830                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20831                 line_ptr += bytes_read;
20832
20833                 state_machine.handle_advance_pc (adjust);
20834               }
20835               break;
20836             case DW_LNS_advance_line:
20837               {
20838                 int line_delta
20839                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20840                 line_ptr += bytes_read;
20841
20842                 state_machine.handle_advance_line (line_delta);
20843               }
20844               break;
20845             case DW_LNS_set_file:
20846               {
20847                 file_name_index file
20848                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20849                                                             &bytes_read);
20850                 line_ptr += bytes_read;
20851
20852                 state_machine.handle_set_file (file);
20853               }
20854               break;
20855             case DW_LNS_set_column:
20856               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20857               line_ptr += bytes_read;
20858               break;
20859             case DW_LNS_negate_stmt:
20860               state_machine.handle_negate_stmt ();
20861               break;
20862             case DW_LNS_set_basic_block:
20863               break;
20864             /* Add to the address register of the state machine the
20865                address increment value corresponding to special opcode
20866                255.  I.e., this value is scaled by the minimum
20867                instruction length since special opcode 255 would have
20868                scaled the increment.  */
20869             case DW_LNS_const_add_pc:
20870               state_machine.handle_const_add_pc ();
20871               break;
20872             case DW_LNS_fixed_advance_pc:
20873               {
20874                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20875                 line_ptr += 2;
20876
20877                 state_machine.handle_fixed_advance_pc (addr_adj);
20878               }
20879               break;
20880             default:
20881               {
20882                 /* Unknown standard opcode, ignore it.  */
20883                 int i;
20884
20885                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20886                   {
20887                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20888                     line_ptr += bytes_read;
20889                   }
20890               }
20891             }
20892         }
20893
20894       if (!end_sequence)
20895         dwarf2_debug_line_missing_end_sequence_complaint ();
20896
20897       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20898          in which case we still finish recording the last line).  */
20899       state_machine.record_line (true);
20900     }
20901 }
20902
20903 /* Decode the Line Number Program (LNP) for the given line_header
20904    structure and CU.  The actual information extracted and the type
20905    of structures created from the LNP depends on the value of PST.
20906
20907    1. If PST is NULL, then this procedure uses the data from the program
20908       to create all necessary symbol tables, and their linetables.
20909
20910    2. If PST is not NULL, this procedure reads the program to determine
20911       the list of files included by the unit represented by PST, and
20912       builds all the associated partial symbol tables.
20913
20914    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20915    It is used for relative paths in the line table.
20916    NOTE: When processing partial symtabs (pst != NULL),
20917    comp_dir == pst->dirname.
20918
20919    NOTE: It is important that psymtabs have the same file name (via strcmp)
20920    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20921    symtab we don't use it in the name of the psymtabs we create.
20922    E.g. expand_line_sal requires this when finding psymtabs to expand.
20923    A good testcase for this is mb-inline.exp.
20924
20925    LOWPC is the lowest address in CU (or 0 if not known).
20926
20927    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20928    for its PC<->lines mapping information.  Otherwise only the filename
20929    table is read in.  */
20930
20931 static void
20932 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20933                     struct dwarf2_cu *cu, dwarf2_psymtab *pst,
20934                     CORE_ADDR lowpc, int decode_mapping)
20935 {
20936   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20937   const int decode_for_pst_p = (pst != NULL);
20938
20939   if (decode_mapping)
20940     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20941
20942   if (decode_for_pst_p)
20943     {
20944       /* Now that we're done scanning the Line Header Program, we can
20945          create the psymtab of each included file.  */
20946       for (auto &file_entry : lh->file_names ())
20947         if (file_entry.included_p == 1)
20948           {
20949             gdb::unique_xmalloc_ptr<char> name_holder;
20950             const char *include_name =
20951               psymtab_include_file_name (lh, file_entry, pst,
20952                                          comp_dir, &name_holder);
20953             if (include_name != NULL)
20954               dwarf2_create_include_psymtab (include_name, pst, objfile);
20955           }
20956     }
20957   else
20958     {
20959       /* Make sure a symtab is created for every file, even files
20960          which contain only variables (i.e. no code with associated
20961          line numbers).  */
20962       buildsym_compunit *builder = cu->get_builder ();
20963       struct compunit_symtab *cust = builder->get_compunit_symtab ();
20964
20965       for (auto &fe : lh->file_names ())
20966         {
20967           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
20968           if (builder->get_current_subfile ()->symtab == NULL)
20969             {
20970               builder->get_current_subfile ()->symtab
20971                 = allocate_symtab (cust,
20972                                    builder->get_current_subfile ()->name);
20973             }
20974           fe.symtab = builder->get_current_subfile ()->symtab;
20975         }
20976     }
20977 }
20978
20979 /* Start a subfile for DWARF.  FILENAME is the name of the file and
20980    DIRNAME the name of the source directory which contains FILENAME
20981    or NULL if not known.
20982    This routine tries to keep line numbers from identical absolute and
20983    relative file names in a common subfile.
20984
20985    Using the `list' example from the GDB testsuite, which resides in
20986    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
20987    of /srcdir/list0.c yields the following debugging information for list0.c:
20988
20989    DW_AT_name:          /srcdir/list0.c
20990    DW_AT_comp_dir:      /compdir
20991    files.files[0].name: list0.h
20992    files.files[0].dir:  /srcdir
20993    files.files[1].name: list0.c
20994    files.files[1].dir:  /srcdir
20995
20996    The line number information for list0.c has to end up in a single
20997    subfile, so that `break /srcdir/list0.c:1' works as expected.
20998    start_subfile will ensure that this happens provided that we pass the
20999    concatenation of files.files[1].dir and files.files[1].name as the
21000    subfile's name.  */
21001
21002 static void
21003 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21004                       const char *dirname)
21005 {
21006   gdb::unique_xmalloc_ptr<char> copy;
21007
21008   /* In order not to lose the line information directory,
21009      we concatenate it to the filename when it makes sense.
21010      Note that the Dwarf3 standard says (speaking of filenames in line
21011      information): ``The directory index is ignored for file names
21012      that represent full path names''.  Thus ignoring dirname in the
21013      `else' branch below isn't an issue.  */
21014
21015   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21016     {
21017       copy.reset (concat (dirname, SLASH_STRING, filename, (char *) NULL));
21018       filename = copy.get ();
21019     }
21020
21021   cu->get_builder ()->start_subfile (filename);
21022 }
21023
21024 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21025    buildsym_compunit constructor.  */
21026
21027 struct compunit_symtab *
21028 dwarf2_cu::start_symtab (const char *name, const char *comp_dir,
21029                          CORE_ADDR low_pc)
21030 {
21031   gdb_assert (m_builder == nullptr);
21032
21033   m_builder.reset (new struct buildsym_compunit
21034                    (per_cu->dwarf2_per_objfile->objfile,
21035                     name, comp_dir, language, low_pc));
21036
21037   list_in_scope = get_builder ()->get_file_symbols ();
21038
21039   get_builder ()->record_debugformat ("DWARF 2");
21040   get_builder ()->record_producer (producer);
21041
21042   processing_has_namespace_info = false;
21043
21044   return get_builder ()->get_compunit_symtab ();
21045 }
21046
21047 static void
21048 var_decode_location (struct attribute *attr, struct symbol *sym,
21049                      struct dwarf2_cu *cu)
21050 {
21051   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21052   struct comp_unit_head *cu_header = &cu->header;
21053
21054   /* NOTE drow/2003-01-30: There used to be a comment and some special
21055      code here to turn a symbol with DW_AT_external and a
21056      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21057      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21058      with some versions of binutils) where shared libraries could have
21059      relocations against symbols in their debug information - the
21060      minimal symbol would have the right address, but the debug info
21061      would not.  It's no longer necessary, because we will explicitly
21062      apply relocations when we read in the debug information now.  */
21063
21064   /* A DW_AT_location attribute with no contents indicates that a
21065      variable has been optimized away.  */
21066   if (attr->form_is_block () && DW_BLOCK (attr)->size == 0)
21067     {
21068       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21069       return;
21070     }
21071
21072   /* Handle one degenerate form of location expression specially, to
21073      preserve GDB's previous behavior when section offsets are
21074      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
21075      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
21076
21077   if (attr->form_is_block ()
21078       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21079            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21080           || ((DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21081                || DW_BLOCK (attr)->data[0] == DW_OP_addrx)
21082               && (DW_BLOCK (attr)->size
21083                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21084     {
21085       unsigned int dummy;
21086
21087       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21088         SET_SYMBOL_VALUE_ADDRESS (sym,
21089                                   read_address (objfile->obfd,
21090                                                 DW_BLOCK (attr)->data + 1,
21091                                                 cu, &dummy));
21092       else
21093         SET_SYMBOL_VALUE_ADDRESS
21094           (sym, read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1,
21095                                              &dummy));
21096       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21097       fixup_symbol_section (sym, objfile);
21098       SET_SYMBOL_VALUE_ADDRESS
21099         (sym,
21100          SYMBOL_VALUE_ADDRESS (sym)
21101          + objfile->section_offsets[SYMBOL_SECTION (sym)]);
21102       return;
21103     }
21104
21105   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21106      expression evaluator, and use LOC_COMPUTED only when necessary
21107      (i.e. when the value of a register or memory location is
21108      referenced, or a thread-local block, etc.).  Then again, it might
21109      not be worthwhile.  I'm assuming that it isn't unless performance
21110      or memory numbers show me otherwise.  */
21111
21112   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21113
21114   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21115     cu->has_loclist = true;
21116 }
21117
21118 /* Given a pointer to a DWARF information entry, figure out if we need
21119    to make a symbol table entry for it, and if so, create a new entry
21120    and return a pointer to it.
21121    If TYPE is NULL, determine symbol type from the die, otherwise
21122    used the passed type.
21123    If SPACE is not NULL, use it to hold the new symbol.  If it is
21124    NULL, allocate a new symbol on the objfile's obstack.  */
21125
21126 static struct symbol *
21127 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21128             struct symbol *space)
21129 {
21130   struct dwarf2_per_objfile *dwarf2_per_objfile
21131     = cu->per_cu->dwarf2_per_objfile;
21132   struct objfile *objfile = dwarf2_per_objfile->objfile;
21133   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21134   struct symbol *sym = NULL;
21135   const char *name;
21136   struct attribute *attr = NULL;
21137   struct attribute *attr2 = NULL;
21138   CORE_ADDR baseaddr;
21139   struct pending **list_to_add = NULL;
21140
21141   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21142
21143   baseaddr = objfile->text_section_offset ();
21144
21145   name = dwarf2_name (die, cu);
21146   if (name)
21147     {
21148       const char *linkagename;
21149       int suppress_add = 0;
21150
21151       if (space)
21152         sym = space;
21153       else
21154         sym = allocate_symbol (objfile);
21155       OBJSTAT (objfile, n_syms++);
21156
21157       /* Cache this symbol's name and the name's demangled form (if any).  */
21158       sym->set_language (cu->language, &objfile->objfile_obstack);
21159       linkagename = dwarf2_physname (name, die, cu);
21160       sym->compute_and_set_names (linkagename, false, objfile->per_bfd);
21161
21162       /* Fortran does not have mangling standard and the mangling does differ
21163          between gfortran, iFort etc.  */
21164       if (cu->language == language_fortran
21165           && symbol_get_demangled_name (sym) == NULL)
21166         symbol_set_demangled_name (sym,
21167                                    dwarf2_full_name (name, die, cu),
21168                                    NULL);
21169
21170       /* Default assumptions.
21171          Use the passed type or decode it from the die.  */
21172       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21173       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21174       if (type != NULL)
21175         SYMBOL_TYPE (sym) = type;
21176       else
21177         SYMBOL_TYPE (sym) = die_type (die, cu);
21178       attr = dwarf2_attr (die,
21179                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21180                           cu);
21181       if (attr != nullptr)
21182         {
21183           SYMBOL_LINE (sym) = DW_UNSND (attr);
21184         }
21185
21186       attr = dwarf2_attr (die,
21187                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21188                           cu);
21189       if (attr != nullptr)
21190         {
21191           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21192           struct file_entry *fe;
21193
21194           if (cu->line_header != NULL)
21195             fe = cu->line_header->file_name_at (file_index);
21196           else
21197             fe = NULL;
21198
21199           if (fe == NULL)
21200             complaint (_("file index out of range"));
21201           else
21202             symbol_set_symtab (sym, fe->symtab);
21203         }
21204
21205       switch (die->tag)
21206         {
21207         case DW_TAG_label:
21208           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21209           if (attr != nullptr)
21210             {
21211               CORE_ADDR addr;
21212
21213               addr = attr->value_as_address ();
21214               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21215               SET_SYMBOL_VALUE_ADDRESS (sym, addr);
21216             }
21217           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21218           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21219           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21220           add_symbol_to_list (sym, cu->list_in_scope);
21221           break;
21222         case DW_TAG_subprogram:
21223           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21224              finish_block.  */
21225           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21226           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21227           if ((attr2 && (DW_UNSND (attr2) != 0))
21228               || cu->language == language_ada
21229               || cu->language == language_fortran)
21230             {
21231               /* Subprograms marked external are stored as a global symbol.
21232                  Ada and Fortran subprograms, whether marked external or
21233                  not, are always stored as a global symbol, because we want
21234                  to be able to access them globally.  For instance, we want
21235                  to be able to break on a nested subprogram without having
21236                  to specify the context.  */
21237               list_to_add = cu->get_builder ()->get_global_symbols ();
21238             }
21239           else
21240             {
21241               list_to_add = cu->list_in_scope;
21242             }
21243           break;
21244         case DW_TAG_inlined_subroutine:
21245           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21246              finish_block.  */
21247           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21248           SYMBOL_INLINED (sym) = 1;
21249           list_to_add = cu->list_in_scope;
21250           break;
21251         case DW_TAG_template_value_param:
21252           suppress_add = 1;
21253           /* Fall through.  */
21254         case DW_TAG_constant:
21255         case DW_TAG_variable:
21256         case DW_TAG_member:
21257           /* Compilation with minimal debug info may result in
21258              variables with missing type entries.  Change the
21259              misleading `void' type to something sensible.  */
21260           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21261             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21262
21263           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21264           /* In the case of DW_TAG_member, we should only be called for
21265              static const members.  */
21266           if (die->tag == DW_TAG_member)
21267             {
21268               /* dwarf2_add_field uses die_is_declaration,
21269                  so we do the same.  */
21270               gdb_assert (die_is_declaration (die, cu));
21271               gdb_assert (attr);
21272             }
21273           if (attr != nullptr)
21274             {
21275               dwarf2_const_value (attr, sym, cu);
21276               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21277               if (!suppress_add)
21278                 {
21279                   if (attr2 && (DW_UNSND (attr2) != 0))
21280                     list_to_add = cu->get_builder ()->get_global_symbols ();
21281                   else
21282                     list_to_add = cu->list_in_scope;
21283                 }
21284               break;
21285             }
21286           attr = dwarf2_attr (die, DW_AT_location, cu);
21287           if (attr != nullptr)
21288             {
21289               var_decode_location (attr, sym, cu);
21290               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21291
21292               /* Fortran explicitly imports any global symbols to the local
21293                  scope by DW_TAG_common_block.  */
21294               if (cu->language == language_fortran && die->parent
21295                   && die->parent->tag == DW_TAG_common_block)
21296                 attr2 = NULL;
21297
21298               if (SYMBOL_CLASS (sym) == LOC_STATIC
21299                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21300                   && !dwarf2_per_objfile->has_section_at_zero)
21301                 {
21302                   /* When a static variable is eliminated by the linker,
21303                      the corresponding debug information is not stripped
21304                      out, but the variable address is set to null;
21305                      do not add such variables into symbol table.  */
21306                 }
21307               else if (attr2 && (DW_UNSND (attr2) != 0))
21308                 {
21309                   if (SYMBOL_CLASS (sym) == LOC_STATIC
21310                       && (objfile->flags & OBJF_MAINLINE) == 0
21311                       && dwarf2_per_objfile->can_copy)
21312                     {
21313                       /* A global static variable might be subject to
21314                          copy relocation.  We first check for a local
21315                          minsym, though, because maybe the symbol was
21316                          marked hidden, in which case this would not
21317                          apply.  */
21318                       bound_minimal_symbol found
21319                         = (lookup_minimal_symbol_linkage
21320                            (sym->linkage_name (), objfile));
21321                       if (found.minsym != nullptr)
21322                         sym->maybe_copied = 1;
21323                     }
21324
21325                   /* A variable with DW_AT_external is never static,
21326                      but it may be block-scoped.  */
21327                   list_to_add
21328                     = ((cu->list_in_scope
21329                         == cu->get_builder ()->get_file_symbols ())
21330                        ? cu->get_builder ()->get_global_symbols ()
21331                        : cu->list_in_scope);
21332                 }
21333               else
21334                 list_to_add = cu->list_in_scope;
21335             }
21336           else
21337             {
21338               /* We do not know the address of this symbol.
21339                  If it is an external symbol and we have type information
21340                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21341                  The address of the variable will then be determined from
21342                  the minimal symbol table whenever the variable is
21343                  referenced.  */
21344               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21345
21346               /* Fortran explicitly imports any global symbols to the local
21347                  scope by DW_TAG_common_block.  */
21348               if (cu->language == language_fortran && die->parent
21349                   && die->parent->tag == DW_TAG_common_block)
21350                 {
21351                   /* SYMBOL_CLASS doesn't matter here because
21352                      read_common_block is going to reset it.  */
21353                   if (!suppress_add)
21354                     list_to_add = cu->list_in_scope;
21355                 }
21356               else if (attr2 && (DW_UNSND (attr2) != 0)
21357                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21358                 {
21359                   /* A variable with DW_AT_external is never static, but it
21360                      may be block-scoped.  */
21361                   list_to_add
21362                     = ((cu->list_in_scope
21363                         == cu->get_builder ()->get_file_symbols ())
21364                        ? cu->get_builder ()->get_global_symbols ()
21365                        : cu->list_in_scope);
21366
21367                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21368                 }
21369               else if (!die_is_declaration (die, cu))
21370                 {
21371                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21372                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21373                   if (!suppress_add)
21374                     list_to_add = cu->list_in_scope;
21375                 }
21376             }
21377           break;
21378         case DW_TAG_formal_parameter:
21379           {
21380             /* If we are inside a function, mark this as an argument.  If
21381                not, we might be looking at an argument to an inlined function
21382                when we do not have enough information to show inlined frames;
21383                pretend it's a local variable in that case so that the user can
21384                still see it.  */
21385             struct context_stack *curr
21386               = cu->get_builder ()->get_current_context_stack ();
21387             if (curr != nullptr && curr->name != nullptr)
21388               SYMBOL_IS_ARGUMENT (sym) = 1;
21389             attr = dwarf2_attr (die, DW_AT_location, cu);
21390             if (attr != nullptr)
21391               {
21392                 var_decode_location (attr, sym, cu);
21393               }
21394             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21395             if (attr != nullptr)
21396               {
21397                 dwarf2_const_value (attr, sym, cu);
21398               }
21399
21400             list_to_add = cu->list_in_scope;
21401           }
21402           break;
21403         case DW_TAG_unspecified_parameters:
21404           /* From varargs functions; gdb doesn't seem to have any
21405              interest in this information, so just ignore it for now.
21406              (FIXME?) */
21407           break;
21408         case DW_TAG_template_type_param:
21409           suppress_add = 1;
21410           /* Fall through.  */
21411         case DW_TAG_class_type:
21412         case DW_TAG_interface_type:
21413         case DW_TAG_structure_type:
21414         case DW_TAG_union_type:
21415         case DW_TAG_set_type:
21416         case DW_TAG_enumeration_type:
21417           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21418           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21419
21420           {
21421             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21422                really ever be static objects: otherwise, if you try
21423                to, say, break of a class's method and you're in a file
21424                which doesn't mention that class, it won't work unless
21425                the check for all static symbols in lookup_symbol_aux
21426                saves you.  See the OtherFileClass tests in
21427                gdb.c++/namespace.exp.  */
21428
21429             if (!suppress_add)
21430               {
21431                 buildsym_compunit *builder = cu->get_builder ();
21432                 list_to_add
21433                   = (cu->list_in_scope == builder->get_file_symbols ()
21434                      && cu->language == language_cplus
21435                      ? builder->get_global_symbols ()
21436                      : cu->list_in_scope);
21437
21438                 /* The semantics of C++ state that "struct foo {
21439                    ... }" also defines a typedef for "foo".  */
21440                 if (cu->language == language_cplus
21441                     || cu->language == language_ada
21442                     || cu->language == language_d
21443                     || cu->language == language_rust)
21444                   {
21445                     /* The symbol's name is already allocated along
21446                        with this objfile, so we don't need to
21447                        duplicate it for the type.  */
21448                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21449                       TYPE_NAME (SYMBOL_TYPE (sym)) = sym->search_name ();
21450                   }
21451               }
21452           }
21453           break;
21454         case DW_TAG_typedef:
21455           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21456           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21457           list_to_add = cu->list_in_scope;
21458           break;
21459         case DW_TAG_base_type:
21460         case DW_TAG_subrange_type:
21461           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21462           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21463           list_to_add = cu->list_in_scope;
21464           break;
21465         case DW_TAG_enumerator:
21466           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21467           if (attr != nullptr)
21468             {
21469               dwarf2_const_value (attr, sym, cu);
21470             }
21471           {
21472             /* NOTE: carlton/2003-11-10: See comment above in the
21473                DW_TAG_class_type, etc. block.  */
21474
21475             list_to_add
21476               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
21477                  && cu->language == language_cplus
21478                  ? cu->get_builder ()->get_global_symbols ()
21479                  : cu->list_in_scope);
21480           }
21481           break;
21482         case DW_TAG_imported_declaration:
21483         case DW_TAG_namespace:
21484           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21485           list_to_add = cu->get_builder ()->get_global_symbols ();
21486           break;
21487         case DW_TAG_module:
21488           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21489           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21490           list_to_add = cu->get_builder ()->get_global_symbols ();
21491           break;
21492         case DW_TAG_common_block:
21493           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21494           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21495           add_symbol_to_list (sym, cu->list_in_scope);
21496           break;
21497         default:
21498           /* Not a tag we recognize.  Hopefully we aren't processing
21499              trash data, but since we must specifically ignore things
21500              we don't recognize, there is nothing else we should do at
21501              this point.  */
21502           complaint (_("unsupported tag: '%s'"),
21503                      dwarf_tag_name (die->tag));
21504           break;
21505         }
21506
21507       if (suppress_add)
21508         {
21509           sym->hash_next = objfile->template_symbols;
21510           objfile->template_symbols = sym;
21511           list_to_add = NULL;
21512         }
21513
21514       if (list_to_add != NULL)
21515         add_symbol_to_list (sym, list_to_add);
21516
21517       /* For the benefit of old versions of GCC, check for anonymous
21518          namespaces based on the demangled name.  */
21519       if (!cu->processing_has_namespace_info
21520           && cu->language == language_cplus)
21521         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
21522     }
21523   return (sym);
21524 }
21525
21526 /* Given an attr with a DW_FORM_dataN value in host byte order,
21527    zero-extend it as appropriate for the symbol's type.  The DWARF
21528    standard (v4) is not entirely clear about the meaning of using
21529    DW_FORM_dataN for a constant with a signed type, where the type is
21530    wider than the data.  The conclusion of a discussion on the DWARF
21531    list was that this is unspecified.  We choose to always zero-extend
21532    because that is the interpretation long in use by GCC.  */
21533
21534 static gdb_byte *
21535 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21536                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21537 {
21538   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21539   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21540                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21541   LONGEST l = DW_UNSND (attr);
21542
21543   if (bits < sizeof (*value) * 8)
21544     {
21545       l &= ((LONGEST) 1 << bits) - 1;
21546       *value = l;
21547     }
21548   else if (bits == sizeof (*value) * 8)
21549     *value = l;
21550   else
21551     {
21552       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21553       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21554       return bytes;
21555     }
21556
21557   return NULL;
21558 }
21559
21560 /* Read a constant value from an attribute.  Either set *VALUE, or if
21561    the value does not fit in *VALUE, set *BYTES - either already
21562    allocated on the objfile obstack, or newly allocated on OBSTACK,
21563    or, set *BATON, if we translated the constant to a location
21564    expression.  */
21565
21566 static void
21567 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21568                          const char *name, struct obstack *obstack,
21569                          struct dwarf2_cu *cu,
21570                          LONGEST *value, const gdb_byte **bytes,
21571                          struct dwarf2_locexpr_baton **baton)
21572 {
21573   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21574   struct comp_unit_head *cu_header = &cu->header;
21575   struct dwarf_block *blk;
21576   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21577                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21578
21579   *value = 0;
21580   *bytes = NULL;
21581   *baton = NULL;
21582
21583   switch (attr->form)
21584     {
21585     case DW_FORM_addr:
21586     case DW_FORM_addrx:
21587     case DW_FORM_GNU_addr_index:
21588       {
21589         gdb_byte *data;
21590
21591         if (TYPE_LENGTH (type) != cu_header->addr_size)
21592           dwarf2_const_value_length_mismatch_complaint (name,
21593                                                         cu_header->addr_size,
21594                                                         TYPE_LENGTH (type));
21595         /* Symbols of this form are reasonably rare, so we just
21596            piggyback on the existing location code rather than writing
21597            a new implementation of symbol_computed_ops.  */
21598         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21599         (*baton)->per_cu = cu->per_cu;
21600         gdb_assert ((*baton)->per_cu);
21601
21602         (*baton)->size = 2 + cu_header->addr_size;
21603         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21604         (*baton)->data = data;
21605
21606         data[0] = DW_OP_addr;
21607         store_unsigned_integer (&data[1], cu_header->addr_size,
21608                                 byte_order, DW_ADDR (attr));
21609         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21610       }
21611       break;
21612     case DW_FORM_string:
21613     case DW_FORM_strp:
21614     case DW_FORM_strx:
21615     case DW_FORM_GNU_str_index:
21616     case DW_FORM_GNU_strp_alt:
21617       /* DW_STRING is already allocated on the objfile obstack, point
21618          directly to it.  */
21619       *bytes = (const gdb_byte *) DW_STRING (attr);
21620       break;
21621     case DW_FORM_block1:
21622     case DW_FORM_block2:
21623     case DW_FORM_block4:
21624     case DW_FORM_block:
21625     case DW_FORM_exprloc:
21626     case DW_FORM_data16:
21627       blk = DW_BLOCK (attr);
21628       if (TYPE_LENGTH (type) != blk->size)
21629         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21630                                                       TYPE_LENGTH (type));
21631       *bytes = blk->data;
21632       break;
21633
21634       /* The DW_AT_const_value attributes are supposed to carry the
21635          symbol's value "represented as it would be on the target
21636          architecture."  By the time we get here, it's already been
21637          converted to host endianness, so we just need to sign- or
21638          zero-extend it as appropriate.  */
21639     case DW_FORM_data1:
21640       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21641       break;
21642     case DW_FORM_data2:
21643       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21644       break;
21645     case DW_FORM_data4:
21646       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21647       break;
21648     case DW_FORM_data8:
21649       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21650       break;
21651
21652     case DW_FORM_sdata:
21653     case DW_FORM_implicit_const:
21654       *value = DW_SND (attr);
21655       break;
21656
21657     case DW_FORM_udata:
21658       *value = DW_UNSND (attr);
21659       break;
21660
21661     default:
21662       complaint (_("unsupported const value attribute form: '%s'"),
21663                  dwarf_form_name (attr->form));
21664       *value = 0;
21665       break;
21666     }
21667 }
21668
21669
21670 /* Copy constant value from an attribute to a symbol.  */
21671
21672 static void
21673 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21674                     struct dwarf2_cu *cu)
21675 {
21676   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21677   LONGEST value;
21678   const gdb_byte *bytes;
21679   struct dwarf2_locexpr_baton *baton;
21680
21681   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21682                            sym->print_name (),
21683                            &objfile->objfile_obstack, cu,
21684                            &value, &bytes, &baton);
21685
21686   if (baton != NULL)
21687     {
21688       SYMBOL_LOCATION_BATON (sym) = baton;
21689       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21690     }
21691   else if (bytes != NULL)
21692      {
21693       SYMBOL_VALUE_BYTES (sym) = bytes;
21694       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21695     }
21696   else
21697     {
21698       SYMBOL_VALUE (sym) = value;
21699       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21700     }
21701 }
21702
21703 /* Return the type of the die in question using its DW_AT_type attribute.  */
21704
21705 static struct type *
21706 die_type (struct die_info *die, struct dwarf2_cu *cu)
21707 {
21708   struct attribute *type_attr;
21709
21710   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21711   if (!type_attr)
21712     {
21713       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21714       /* A missing DW_AT_type represents a void type.  */
21715       return objfile_type (objfile)->builtin_void;
21716     }
21717
21718   return lookup_die_type (die, type_attr, cu);
21719 }
21720
21721 /* True iff CU's producer generates GNAT Ada auxiliary information
21722    that allows to find parallel types through that information instead
21723    of having to do expensive parallel lookups by type name.  */
21724
21725 static int
21726 need_gnat_info (struct dwarf2_cu *cu)
21727 {
21728   /* Assume that the Ada compiler was GNAT, which always produces
21729      the auxiliary information.  */
21730   return (cu->language == language_ada);
21731 }
21732
21733 /* Return the auxiliary type of the die in question using its
21734    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21735    attribute is not present.  */
21736
21737 static struct type *
21738 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21739 {
21740   struct attribute *type_attr;
21741
21742   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21743   if (!type_attr)
21744     return NULL;
21745
21746   return lookup_die_type (die, type_attr, cu);
21747 }
21748
21749 /* If DIE has a descriptive_type attribute, then set the TYPE's
21750    descriptive type accordingly.  */
21751
21752 static void
21753 set_descriptive_type (struct type *type, struct die_info *die,
21754                       struct dwarf2_cu *cu)
21755 {
21756   struct type *descriptive_type = die_descriptive_type (die, cu);
21757
21758   if (descriptive_type)
21759     {
21760       ALLOCATE_GNAT_AUX_TYPE (type);
21761       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21762     }
21763 }
21764
21765 /* Return the containing type of the die in question using its
21766    DW_AT_containing_type attribute.  */
21767
21768 static struct type *
21769 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21770 {
21771   struct attribute *type_attr;
21772   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21773
21774   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21775   if (!type_attr)
21776     error (_("Dwarf Error: Problem turning containing type into gdb type "
21777              "[in module %s]"), objfile_name (objfile));
21778
21779   return lookup_die_type (die, type_attr, cu);
21780 }
21781
21782 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21783
21784 static struct type *
21785 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21786 {
21787   struct dwarf2_per_objfile *dwarf2_per_objfile
21788     = cu->per_cu->dwarf2_per_objfile;
21789   struct objfile *objfile = dwarf2_per_objfile->objfile;
21790   char *saved;
21791
21792   std::string message
21793     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
21794                      objfile_name (objfile),
21795                      sect_offset_str (cu->header.sect_off),
21796                      sect_offset_str (die->sect_off));
21797   saved = obstack_strdup (&objfile->objfile_obstack, message);
21798
21799   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21800 }
21801
21802 /* Look up the type of DIE in CU using its type attribute ATTR.
21803    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21804    DW_AT_containing_type.
21805    If there is no type substitute an error marker.  */
21806
21807 static struct type *
21808 lookup_die_type (struct die_info *die, const struct attribute *attr,
21809                  struct dwarf2_cu *cu)
21810 {
21811   struct dwarf2_per_objfile *dwarf2_per_objfile
21812     = cu->per_cu->dwarf2_per_objfile;
21813   struct objfile *objfile = dwarf2_per_objfile->objfile;
21814   struct type *this_type;
21815
21816   gdb_assert (attr->name == DW_AT_type
21817               || attr->name == DW_AT_GNAT_descriptive_type
21818               || attr->name == DW_AT_containing_type);
21819
21820   /* First see if we have it cached.  */
21821
21822   if (attr->form == DW_FORM_GNU_ref_alt)
21823     {
21824       struct dwarf2_per_cu_data *per_cu;
21825       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21826
21827       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21828                                                  dwarf2_per_objfile);
21829       this_type = get_die_type_at_offset (sect_off, per_cu);
21830     }
21831   else if (attr->form_is_ref ())
21832     {
21833       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21834
21835       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21836     }
21837   else if (attr->form == DW_FORM_ref_sig8)
21838     {
21839       ULONGEST signature = DW_SIGNATURE (attr);
21840
21841       return get_signatured_type (die, signature, cu);
21842     }
21843   else
21844     {
21845       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21846                    " at %s [in module %s]"),
21847                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21848                  objfile_name (objfile));
21849       return build_error_marker_type (cu, die);
21850     }
21851
21852   /* If not cached we need to read it in.  */
21853
21854   if (this_type == NULL)
21855     {
21856       struct die_info *type_die = NULL;
21857       struct dwarf2_cu *type_cu = cu;
21858
21859       if (attr->form_is_ref ())
21860         type_die = follow_die_ref (die, attr, &type_cu);
21861       if (type_die == NULL)
21862         return build_error_marker_type (cu, die);
21863       /* If we find the type now, it's probably because the type came
21864          from an inter-CU reference and the type's CU got expanded before
21865          ours.  */
21866       this_type = read_type_die (type_die, type_cu);
21867     }
21868
21869   /* If we still don't have a type use an error marker.  */
21870
21871   if (this_type == NULL)
21872     return build_error_marker_type (cu, die);
21873
21874   return this_type;
21875 }
21876
21877 /* Return the type in DIE, CU.
21878    Returns NULL for invalid types.
21879
21880    This first does a lookup in die_type_hash,
21881    and only reads the die in if necessary.
21882
21883    NOTE: This can be called when reading in partial or full symbols.  */
21884
21885 static struct type *
21886 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21887 {
21888   struct type *this_type;
21889
21890   this_type = get_die_type (die, cu);
21891   if (this_type)
21892     return this_type;
21893
21894   return read_type_die_1 (die, cu);
21895 }
21896
21897 /* Read the type in DIE, CU.
21898    Returns NULL for invalid types.  */
21899
21900 static struct type *
21901 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21902 {
21903   struct type *this_type = NULL;
21904
21905   switch (die->tag)
21906     {
21907     case DW_TAG_class_type:
21908     case DW_TAG_interface_type:
21909     case DW_TAG_structure_type:
21910     case DW_TAG_union_type:
21911       this_type = read_structure_type (die, cu);
21912       break;
21913     case DW_TAG_enumeration_type:
21914       this_type = read_enumeration_type (die, cu);
21915       break;
21916     case DW_TAG_subprogram:
21917     case DW_TAG_subroutine_type:
21918     case DW_TAG_inlined_subroutine:
21919       this_type = read_subroutine_type (die, cu);
21920       break;
21921     case DW_TAG_array_type:
21922       this_type = read_array_type (die, cu);
21923       break;
21924     case DW_TAG_set_type:
21925       this_type = read_set_type (die, cu);
21926       break;
21927     case DW_TAG_pointer_type:
21928       this_type = read_tag_pointer_type (die, cu);
21929       break;
21930     case DW_TAG_ptr_to_member_type:
21931       this_type = read_tag_ptr_to_member_type (die, cu);
21932       break;
21933     case DW_TAG_reference_type:
21934       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21935       break;
21936     case DW_TAG_rvalue_reference_type:
21937       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21938       break;
21939     case DW_TAG_const_type:
21940       this_type = read_tag_const_type (die, cu);
21941       break;
21942     case DW_TAG_volatile_type:
21943       this_type = read_tag_volatile_type (die, cu);
21944       break;
21945     case DW_TAG_restrict_type:
21946       this_type = read_tag_restrict_type (die, cu);
21947       break;
21948     case DW_TAG_string_type:
21949       this_type = read_tag_string_type (die, cu);
21950       break;
21951     case DW_TAG_typedef:
21952       this_type = read_typedef (die, cu);
21953       break;
21954     case DW_TAG_subrange_type:
21955       this_type = read_subrange_type (die, cu);
21956       break;
21957     case DW_TAG_base_type:
21958       this_type = read_base_type (die, cu);
21959       break;
21960     case DW_TAG_unspecified_type:
21961       this_type = read_unspecified_type (die, cu);
21962       break;
21963     case DW_TAG_namespace:
21964       this_type = read_namespace_type (die, cu);
21965       break;
21966     case DW_TAG_module:
21967       this_type = read_module_type (die, cu);
21968       break;
21969     case DW_TAG_atomic_type:
21970       this_type = read_tag_atomic_type (die, cu);
21971       break;
21972     default:
21973       complaint (_("unexpected tag in read_type_die: '%s'"),
21974                  dwarf_tag_name (die->tag));
21975       break;
21976     }
21977
21978   return this_type;
21979 }
21980
21981 /* See if we can figure out if the class lives in a namespace.  We do
21982    this by looking for a member function; its demangled name will
21983    contain namespace info, if there is any.
21984    Return the computed name or NULL.
21985    Space for the result is allocated on the objfile's obstack.
21986    This is the full-die version of guess_partial_die_structure_name.
21987    In this case we know DIE has no useful parent.  */
21988
21989 static const char *
21990 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
21991 {
21992   struct die_info *spec_die;
21993   struct dwarf2_cu *spec_cu;
21994   struct die_info *child;
21995   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21996
21997   spec_cu = cu;
21998   spec_die = die_specification (die, &spec_cu);
21999   if (spec_die != NULL)
22000     {
22001       die = spec_die;
22002       cu = spec_cu;
22003     }
22004
22005   for (child = die->child;
22006        child != NULL;
22007        child = child->sibling)
22008     {
22009       if (child->tag == DW_TAG_subprogram)
22010         {
22011           const char *linkage_name = dw2_linkage_name (child, cu);
22012
22013           if (linkage_name != NULL)
22014             {
22015               gdb::unique_xmalloc_ptr<char> actual_name
22016                 (language_class_name_from_physname (cu->language_defn,
22017                                                     linkage_name));
22018               const char *name = NULL;
22019
22020               if (actual_name != NULL)
22021                 {
22022                   const char *die_name = dwarf2_name (die, cu);
22023
22024                   if (die_name != NULL
22025                       && strcmp (die_name, actual_name.get ()) != 0)
22026                     {
22027                       /* Strip off the class name from the full name.
22028                          We want the prefix.  */
22029                       int die_name_len = strlen (die_name);
22030                       int actual_name_len = strlen (actual_name.get ());
22031                       const char *ptr = actual_name.get ();
22032
22033                       /* Test for '::' as a sanity check.  */
22034                       if (actual_name_len > die_name_len + 2
22035                           && ptr[actual_name_len - die_name_len - 1] == ':')
22036                         name = obstack_strndup (
22037                           &objfile->per_bfd->storage_obstack,
22038                           ptr, actual_name_len - die_name_len - 2);
22039                     }
22040                 }
22041               return name;
22042             }
22043         }
22044     }
22045
22046   return NULL;
22047 }
22048
22049 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22050    prefix part in such case.  See
22051    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22052
22053 static const char *
22054 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22055 {
22056   struct attribute *attr;
22057   const char *base;
22058
22059   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22060       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22061     return NULL;
22062
22063   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22064     return NULL;
22065
22066   attr = dw2_linkage_name_attr (die, cu);
22067   if (attr == NULL || DW_STRING (attr) == NULL)
22068     return NULL;
22069
22070   /* dwarf2_name had to be already called.  */
22071   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22072
22073   /* Strip the base name, keep any leading namespaces/classes.  */
22074   base = strrchr (DW_STRING (attr), ':');
22075   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22076     return "";
22077
22078   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22079   return obstack_strndup (&objfile->per_bfd->storage_obstack,
22080                           DW_STRING (attr),
22081                           &base[-1] - DW_STRING (attr));
22082 }
22083
22084 /* Return the name of the namespace/class that DIE is defined within,
22085    or "" if we can't tell.  The caller should not xfree the result.
22086
22087    For example, if we're within the method foo() in the following
22088    code:
22089
22090    namespace N {
22091      class C {
22092        void foo () {
22093        }
22094      };
22095    }
22096
22097    then determine_prefix on foo's die will return "N::C".  */
22098
22099 static const char *
22100 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22101 {
22102   struct dwarf2_per_objfile *dwarf2_per_objfile
22103     = cu->per_cu->dwarf2_per_objfile;
22104   struct die_info *parent, *spec_die;
22105   struct dwarf2_cu *spec_cu;
22106   struct type *parent_type;
22107   const char *retval;
22108
22109   if (cu->language != language_cplus
22110       && cu->language != language_fortran && cu->language != language_d
22111       && cu->language != language_rust)
22112     return "";
22113
22114   retval = anonymous_struct_prefix (die, cu);
22115   if (retval)
22116     return retval;
22117
22118   /* We have to be careful in the presence of DW_AT_specification.
22119      For example, with GCC 3.4, given the code
22120
22121      namespace N {
22122        void foo() {
22123          // Definition of N::foo.
22124        }
22125      }
22126
22127      then we'll have a tree of DIEs like this:
22128
22129      1: DW_TAG_compile_unit
22130        2: DW_TAG_namespace        // N
22131          3: DW_TAG_subprogram     // declaration of N::foo
22132        4: DW_TAG_subprogram       // definition of N::foo
22133             DW_AT_specification   // refers to die #3
22134
22135      Thus, when processing die #4, we have to pretend that we're in
22136      the context of its DW_AT_specification, namely the contex of die
22137      #3.  */
22138   spec_cu = cu;
22139   spec_die = die_specification (die, &spec_cu);
22140   if (spec_die == NULL)
22141     parent = die->parent;
22142   else
22143     {
22144       parent = spec_die->parent;
22145       cu = spec_cu;
22146     }
22147
22148   if (parent == NULL)
22149     return "";
22150   else if (parent->building_fullname)
22151     {
22152       const char *name;
22153       const char *parent_name;
22154
22155       /* It has been seen on RealView 2.2 built binaries,
22156          DW_TAG_template_type_param types actually _defined_ as
22157          children of the parent class:
22158
22159          enum E {};
22160          template class <class Enum> Class{};
22161          Class<enum E> class_e;
22162
22163          1: DW_TAG_class_type (Class)
22164            2: DW_TAG_enumeration_type (E)
22165              3: DW_TAG_enumerator (enum1:0)
22166              3: DW_TAG_enumerator (enum2:1)
22167              ...
22168            2: DW_TAG_template_type_param
22169               DW_AT_type  DW_FORM_ref_udata (E)
22170
22171          Besides being broken debug info, it can put GDB into an
22172          infinite loop.  Consider:
22173
22174          When we're building the full name for Class<E>, we'll start
22175          at Class, and go look over its template type parameters,
22176          finding E.  We'll then try to build the full name of E, and
22177          reach here.  We're now trying to build the full name of E,
22178          and look over the parent DIE for containing scope.  In the
22179          broken case, if we followed the parent DIE of E, we'd again
22180          find Class, and once again go look at its template type
22181          arguments, etc., etc.  Simply don't consider such parent die
22182          as source-level parent of this die (it can't be, the language
22183          doesn't allow it), and break the loop here.  */
22184       name = dwarf2_name (die, cu);
22185       parent_name = dwarf2_name (parent, cu);
22186       complaint (_("template param type '%s' defined within parent '%s'"),
22187                  name ? name : "<unknown>",
22188                  parent_name ? parent_name : "<unknown>");
22189       return "";
22190     }
22191   else
22192     switch (parent->tag)
22193       {
22194       case DW_TAG_namespace:
22195         parent_type = read_type_die (parent, cu);
22196         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22197            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22198            Work around this problem here.  */
22199         if (cu->language == language_cplus
22200             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22201           return "";
22202         /* We give a name to even anonymous namespaces.  */
22203         return TYPE_NAME (parent_type);
22204       case DW_TAG_class_type:
22205       case DW_TAG_interface_type:
22206       case DW_TAG_structure_type:
22207       case DW_TAG_union_type:
22208       case DW_TAG_module:
22209         parent_type = read_type_die (parent, cu);
22210         if (TYPE_NAME (parent_type) != NULL)
22211           return TYPE_NAME (parent_type);
22212         else
22213           /* An anonymous structure is only allowed non-static data
22214              members; no typedefs, no member functions, et cetera.
22215              So it does not need a prefix.  */
22216           return "";
22217       case DW_TAG_compile_unit:
22218       case DW_TAG_partial_unit:
22219         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22220         if (cu->language == language_cplus
22221             && !dwarf2_per_objfile->types.empty ()
22222             && die->child != NULL
22223             && (die->tag == DW_TAG_class_type
22224                 || die->tag == DW_TAG_structure_type
22225                 || die->tag == DW_TAG_union_type))
22226           {
22227             const char *name = guess_full_die_structure_name (die, cu);
22228             if (name != NULL)
22229               return name;
22230           }
22231         return "";
22232       case DW_TAG_subprogram:
22233         /* Nested subroutines in Fortran get a prefix with the name
22234            of the parent's subroutine.  */
22235         if (cu->language == language_fortran)
22236           {
22237             if ((die->tag ==  DW_TAG_subprogram)
22238                 && (dwarf2_name (parent, cu) != NULL))
22239               return dwarf2_name (parent, cu);
22240           }
22241         return determine_prefix (parent, cu);
22242       case DW_TAG_enumeration_type:
22243         parent_type = read_type_die (parent, cu);
22244         if (TYPE_DECLARED_CLASS (parent_type))
22245           {
22246             if (TYPE_NAME (parent_type) != NULL)
22247               return TYPE_NAME (parent_type);
22248             return "";
22249           }
22250         /* Fall through.  */
22251       default:
22252         return determine_prefix (parent, cu);
22253       }
22254 }
22255
22256 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22257    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22258    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22259    an obconcat, otherwise allocate storage for the result.  The CU argument is
22260    used to determine the language and hence, the appropriate separator.  */
22261
22262 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22263
22264 static char *
22265 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22266                  int physname, struct dwarf2_cu *cu)
22267 {
22268   const char *lead = "";
22269   const char *sep;
22270
22271   if (suffix == NULL || suffix[0] == '\0'
22272       || prefix == NULL || prefix[0] == '\0')
22273     sep = "";
22274   else if (cu->language == language_d)
22275     {
22276       /* For D, the 'main' function could be defined in any module, but it
22277          should never be prefixed.  */
22278       if (strcmp (suffix, "D main") == 0)
22279         {
22280           prefix = "";
22281           sep = "";
22282         }
22283       else
22284         sep = ".";
22285     }
22286   else if (cu->language == language_fortran && physname)
22287     {
22288       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22289          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22290
22291       lead = "__";
22292       sep = "_MOD_";
22293     }
22294   else
22295     sep = "::";
22296
22297   if (prefix == NULL)
22298     prefix = "";
22299   if (suffix == NULL)
22300     suffix = "";
22301
22302   if (obs == NULL)
22303     {
22304       char *retval
22305         = ((char *)
22306            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22307
22308       strcpy (retval, lead);
22309       strcat (retval, prefix);
22310       strcat (retval, sep);
22311       strcat (retval, suffix);
22312       return retval;
22313     }
22314   else
22315     {
22316       /* We have an obstack.  */
22317       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22318     }
22319 }
22320
22321 /* Return sibling of die, NULL if no sibling.  */
22322
22323 static struct die_info *
22324 sibling_die (struct die_info *die)
22325 {
22326   return die->sibling;
22327 }
22328
22329 /* Get name of a die, return NULL if not found.  */
22330
22331 static const char *
22332 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22333                           struct obstack *obstack)
22334 {
22335   if (name && cu->language == language_cplus)
22336     {
22337       std::string canon_name = cp_canonicalize_string (name);
22338
22339       if (!canon_name.empty ())
22340         {
22341           if (canon_name != name)
22342             name = obstack_strdup (obstack, canon_name);
22343         }
22344     }
22345
22346   return name;
22347 }
22348
22349 /* Get name of a die, return NULL if not found.
22350    Anonymous namespaces are converted to their magic string.  */
22351
22352 static const char *
22353 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22354 {
22355   struct attribute *attr;
22356   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22357
22358   attr = dwarf2_attr (die, DW_AT_name, cu);
22359   if ((!attr || !DW_STRING (attr))
22360       && die->tag != DW_TAG_namespace
22361       && die->tag != DW_TAG_class_type
22362       && die->tag != DW_TAG_interface_type
22363       && die->tag != DW_TAG_structure_type
22364       && die->tag != DW_TAG_union_type)
22365     return NULL;
22366
22367   switch (die->tag)
22368     {
22369     case DW_TAG_compile_unit:
22370     case DW_TAG_partial_unit:
22371       /* Compilation units have a DW_AT_name that is a filename, not
22372          a source language identifier.  */
22373     case DW_TAG_enumeration_type:
22374     case DW_TAG_enumerator:
22375       /* These tags always have simple identifiers already; no need
22376          to canonicalize them.  */
22377       return DW_STRING (attr);
22378
22379     case DW_TAG_namespace:
22380       if (attr != NULL && DW_STRING (attr) != NULL)
22381         return DW_STRING (attr);
22382       return CP_ANONYMOUS_NAMESPACE_STR;
22383
22384     case DW_TAG_class_type:
22385     case DW_TAG_interface_type:
22386     case DW_TAG_structure_type:
22387     case DW_TAG_union_type:
22388       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22389          structures or unions.  These were of the form "._%d" in GCC 4.1,
22390          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22391          and GCC 4.4.  We work around this problem by ignoring these.  */
22392       if (attr && DW_STRING (attr)
22393           && (startswith (DW_STRING (attr), "._")
22394               || startswith (DW_STRING (attr), "<anonymous")))
22395         return NULL;
22396
22397       /* GCC might emit a nameless typedef that has a linkage name.  See
22398          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22399       if (!attr || DW_STRING (attr) == NULL)
22400         {
22401           attr = dw2_linkage_name_attr (die, cu);
22402           if (attr == NULL || DW_STRING (attr) == NULL)
22403             return NULL;
22404
22405           /* Avoid demangling DW_STRING (attr) the second time on a second
22406              call for the same DIE.  */
22407           if (!DW_STRING_IS_CANONICAL (attr))
22408             {
22409               gdb::unique_xmalloc_ptr<char> demangled
22410                 (gdb_demangle (DW_STRING (attr), DMGL_TYPES));
22411
22412               const char *base;
22413
22414               /* FIXME: we already did this for the partial symbol... */
22415               DW_STRING (attr)
22416                 = obstack_strdup (&objfile->per_bfd->storage_obstack,
22417                                   demangled.get ());
22418               DW_STRING_IS_CANONICAL (attr) = 1;
22419
22420               /* Strip any leading namespaces/classes, keep only the base name.
22421                  DW_AT_name for named DIEs does not contain the prefixes.  */
22422               base = strrchr (DW_STRING (attr), ':');
22423               if (base && base > DW_STRING (attr) && base[-1] == ':')
22424                 return &base[1];
22425               else
22426                 return DW_STRING (attr);
22427             }
22428         }
22429       break;
22430
22431     default:
22432       break;
22433     }
22434
22435   if (!DW_STRING_IS_CANONICAL (attr))
22436     {
22437       DW_STRING (attr)
22438         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22439                                     &objfile->per_bfd->storage_obstack);
22440       DW_STRING_IS_CANONICAL (attr) = 1;
22441     }
22442   return DW_STRING (attr);
22443 }
22444
22445 /* Return the die that this die in an extension of, or NULL if there
22446    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22447    containing the return value on output.  */
22448
22449 static struct die_info *
22450 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22451 {
22452   struct attribute *attr;
22453
22454   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22455   if (attr == NULL)
22456     return NULL;
22457
22458   return follow_die_ref (die, attr, ext_cu);
22459 }
22460
22461 /* A convenience function that returns an "unknown" DWARF name,
22462    including the value of V.  STR is the name of the entity being
22463    printed, e.g., "TAG".  */
22464
22465 static const char *
22466 dwarf_unknown (const char *str, unsigned v)
22467 {
22468   char *cell = get_print_cell ();
22469   xsnprintf (cell, PRINT_CELL_SIZE, "DW_%s_<unknown: %u>", str, v);
22470   return cell;
22471 }
22472
22473 /* Convert a DIE tag into its string name.  */
22474
22475 static const char *
22476 dwarf_tag_name (unsigned tag)
22477 {
22478   const char *name = get_DW_TAG_name (tag);
22479
22480   if (name == NULL)
22481     return dwarf_unknown ("TAG", tag);
22482
22483   return name;
22484 }
22485
22486 /* Convert a DWARF attribute code into its string name.  */
22487
22488 static const char *
22489 dwarf_attr_name (unsigned attr)
22490 {
22491   const char *name;
22492
22493 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22494   if (attr == DW_AT_MIPS_fde)
22495     return "DW_AT_MIPS_fde";
22496 #else
22497   if (attr == DW_AT_HP_block_index)
22498     return "DW_AT_HP_block_index";
22499 #endif
22500
22501   name = get_DW_AT_name (attr);
22502
22503   if (name == NULL)
22504     return dwarf_unknown ("AT", attr);
22505
22506   return name;
22507 }
22508
22509 /* Convert a unit type to corresponding DW_UT name.  */
22510
22511 static const char *
22512 dwarf_unit_type_name (int unit_type) {
22513   switch (unit_type)
22514     {
22515       case 0x01:
22516         return "DW_UT_compile (0x01)";
22517       case 0x02:
22518         return "DW_UT_type (0x02)";
22519       case 0x03:
22520         return "DW_UT_partial (0x03)";
22521       case 0x04:
22522         return "DW_UT_skeleton (0x04)";
22523       case 0x05:
22524         return "DW_UT_split_compile (0x05)";
22525       case 0x06:
22526         return "DW_UT_split_type (0x06)";
22527       case 0x80:
22528         return "DW_UT_lo_user (0x80)";
22529       case 0xff:
22530         return "DW_UT_hi_user (0xff)";
22531       default:
22532         return nullptr;
22533     }
22534 }
22535
22536 /* Convert a DWARF value form code into its string name.  */
22537
22538 static const char *
22539 dwarf_form_name (unsigned form)
22540 {
22541   const char *name = get_DW_FORM_name (form);
22542
22543   if (name == NULL)
22544     return dwarf_unknown ("FORM", form);
22545
22546   return name;
22547 }
22548
22549 static const char *
22550 dwarf_bool_name (unsigned mybool)
22551 {
22552   if (mybool)
22553     return "TRUE";
22554   else
22555     return "FALSE";
22556 }
22557
22558 /* Convert a DWARF type code into its string name.  */
22559
22560 static const char *
22561 dwarf_type_encoding_name (unsigned enc)
22562 {
22563   const char *name = get_DW_ATE_name (enc);
22564
22565   if (name == NULL)
22566     return dwarf_unknown ("ATE", enc);
22567
22568   return name;
22569 }
22570
22571 static void
22572 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22573 {
22574   unsigned int i;
22575
22576   print_spaces (indent, f);
22577   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22578                       dwarf_tag_name (die->tag), die->abbrev,
22579                       sect_offset_str (die->sect_off));
22580
22581   if (die->parent != NULL)
22582     {
22583       print_spaces (indent, f);
22584       fprintf_unfiltered (f, "  parent at offset: %s\n",
22585                           sect_offset_str (die->parent->sect_off));
22586     }
22587
22588   print_spaces (indent, f);
22589   fprintf_unfiltered (f, "  has children: %s\n",
22590            dwarf_bool_name (die->child != NULL));
22591
22592   print_spaces (indent, f);
22593   fprintf_unfiltered (f, "  attributes:\n");
22594
22595   for (i = 0; i < die->num_attrs; ++i)
22596     {
22597       print_spaces (indent, f);
22598       fprintf_unfiltered (f, "    %s (%s) ",
22599                dwarf_attr_name (die->attrs[i].name),
22600                dwarf_form_name (die->attrs[i].form));
22601
22602       switch (die->attrs[i].form)
22603         {
22604         case DW_FORM_addr:
22605         case DW_FORM_addrx:
22606         case DW_FORM_GNU_addr_index:
22607           fprintf_unfiltered (f, "address: ");
22608           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22609           break;
22610         case DW_FORM_block2:
22611         case DW_FORM_block4:
22612         case DW_FORM_block:
22613         case DW_FORM_block1:
22614           fprintf_unfiltered (f, "block: size %s",
22615                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22616           break;
22617         case DW_FORM_exprloc:
22618           fprintf_unfiltered (f, "expression: size %s",
22619                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22620           break;
22621         case DW_FORM_data16:
22622           fprintf_unfiltered (f, "constant of 16 bytes");
22623           break;
22624         case DW_FORM_ref_addr:
22625           fprintf_unfiltered (f, "ref address: ");
22626           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22627           break;
22628         case DW_FORM_GNU_ref_alt:
22629           fprintf_unfiltered (f, "alt ref address: ");
22630           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22631           break;
22632         case DW_FORM_ref1:
22633         case DW_FORM_ref2:
22634         case DW_FORM_ref4:
22635         case DW_FORM_ref8:
22636         case DW_FORM_ref_udata:
22637           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22638                               (long) (DW_UNSND (&die->attrs[i])));
22639           break;
22640         case DW_FORM_data1:
22641         case DW_FORM_data2:
22642         case DW_FORM_data4:
22643         case DW_FORM_data8:
22644         case DW_FORM_udata:
22645         case DW_FORM_sdata:
22646           fprintf_unfiltered (f, "constant: %s",
22647                               pulongest (DW_UNSND (&die->attrs[i])));
22648           break;
22649         case DW_FORM_sec_offset:
22650           fprintf_unfiltered (f, "section offset: %s",
22651                               pulongest (DW_UNSND (&die->attrs[i])));
22652           break;
22653         case DW_FORM_ref_sig8:
22654           fprintf_unfiltered (f, "signature: %s",
22655                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22656           break;
22657         case DW_FORM_string:
22658         case DW_FORM_strp:
22659         case DW_FORM_line_strp:
22660         case DW_FORM_strx:
22661         case DW_FORM_GNU_str_index:
22662         case DW_FORM_GNU_strp_alt:
22663           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22664                    DW_STRING (&die->attrs[i])
22665                    ? DW_STRING (&die->attrs[i]) : "",
22666                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22667           break;
22668         case DW_FORM_flag:
22669           if (DW_UNSND (&die->attrs[i]))
22670             fprintf_unfiltered (f, "flag: TRUE");
22671           else
22672             fprintf_unfiltered (f, "flag: FALSE");
22673           break;
22674         case DW_FORM_flag_present:
22675           fprintf_unfiltered (f, "flag: TRUE");
22676           break;
22677         case DW_FORM_indirect:
22678           /* The reader will have reduced the indirect form to
22679              the "base form" so this form should not occur.  */
22680           fprintf_unfiltered (f,
22681                               "unexpected attribute form: DW_FORM_indirect");
22682           break;
22683         case DW_FORM_implicit_const:
22684           fprintf_unfiltered (f, "constant: %s",
22685                               plongest (DW_SND (&die->attrs[i])));
22686           break;
22687         default:
22688           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22689                    die->attrs[i].form);
22690           break;
22691         }
22692       fprintf_unfiltered (f, "\n");
22693     }
22694 }
22695
22696 static void
22697 dump_die_for_error (struct die_info *die)
22698 {
22699   dump_die_shallow (gdb_stderr, 0, die);
22700 }
22701
22702 static void
22703 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22704 {
22705   int indent = level * 4;
22706
22707   gdb_assert (die != NULL);
22708
22709   if (level >= max_level)
22710     return;
22711
22712   dump_die_shallow (f, indent, die);
22713
22714   if (die->child != NULL)
22715     {
22716       print_spaces (indent, f);
22717       fprintf_unfiltered (f, "  Children:");
22718       if (level + 1 < max_level)
22719         {
22720           fprintf_unfiltered (f, "\n");
22721           dump_die_1 (f, level + 1, max_level, die->child);
22722         }
22723       else
22724         {
22725           fprintf_unfiltered (f,
22726                               " [not printed, max nesting level reached]\n");
22727         }
22728     }
22729
22730   if (die->sibling != NULL && level > 0)
22731     {
22732       dump_die_1 (f, level, max_level, die->sibling);
22733     }
22734 }
22735
22736 /* This is called from the pdie macro in gdbinit.in.
22737    It's not static so gcc will keep a copy callable from gdb.  */
22738
22739 void
22740 dump_die (struct die_info *die, int max_level)
22741 {
22742   dump_die_1 (gdb_stdlog, 0, max_level, die);
22743 }
22744
22745 static void
22746 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22747 {
22748   void **slot;
22749
22750   slot = htab_find_slot_with_hash (cu->die_hash, die,
22751                                    to_underlying (die->sect_off),
22752                                    INSERT);
22753
22754   *slot = die;
22755 }
22756
22757 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22758    required kind.  */
22759
22760 static sect_offset
22761 dwarf2_get_ref_die_offset (const struct attribute *attr)
22762 {
22763   if (attr->form_is_ref ())
22764     return (sect_offset) DW_UNSND (attr);
22765
22766   complaint (_("unsupported die ref attribute form: '%s'"),
22767              dwarf_form_name (attr->form));
22768   return {};
22769 }
22770
22771 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22772  * the value held by the attribute is not constant.  */
22773
22774 static LONGEST
22775 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22776 {
22777   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22778     return DW_SND (attr);
22779   else if (attr->form == DW_FORM_udata
22780            || attr->form == DW_FORM_data1
22781            || attr->form == DW_FORM_data2
22782            || attr->form == DW_FORM_data4
22783            || attr->form == DW_FORM_data8)
22784     return DW_UNSND (attr);
22785   else
22786     {
22787       /* For DW_FORM_data16 see attribute::form_is_constant.  */
22788       complaint (_("Attribute value is not a constant (%s)"),
22789                  dwarf_form_name (attr->form));
22790       return default_value;
22791     }
22792 }
22793
22794 /* Follow reference or signature attribute ATTR of SRC_DIE.
22795    On entry *REF_CU is the CU of SRC_DIE.
22796    On exit *REF_CU is the CU of the result.  */
22797
22798 static struct die_info *
22799 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22800                        struct dwarf2_cu **ref_cu)
22801 {
22802   struct die_info *die;
22803
22804   if (attr->form_is_ref ())
22805     die = follow_die_ref (src_die, attr, ref_cu);
22806   else if (attr->form == DW_FORM_ref_sig8)
22807     die = follow_die_sig (src_die, attr, ref_cu);
22808   else
22809     {
22810       dump_die_for_error (src_die);
22811       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22812              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22813     }
22814
22815   return die;
22816 }
22817
22818 /* Follow reference OFFSET.
22819    On entry *REF_CU is the CU of the source die referencing OFFSET.
22820    On exit *REF_CU is the CU of the result.
22821    Returns NULL if OFFSET is invalid.  */
22822
22823 static struct die_info *
22824 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22825                    struct dwarf2_cu **ref_cu)
22826 {
22827   struct die_info temp_die;
22828   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22829   struct dwarf2_per_objfile *dwarf2_per_objfile
22830     = cu->per_cu->dwarf2_per_objfile;
22831
22832   gdb_assert (cu->per_cu != NULL);
22833
22834   target_cu = cu;
22835
22836   if (cu->per_cu->is_debug_types)
22837     {
22838       /* .debug_types CUs cannot reference anything outside their CU.
22839          If they need to, they have to reference a signatured type via
22840          DW_FORM_ref_sig8.  */
22841       if (!offset_in_cu_p (&cu->header, sect_off))
22842         return NULL;
22843     }
22844   else if (offset_in_dwz != cu->per_cu->is_dwz
22845            || !offset_in_cu_p (&cu->header, sect_off))
22846     {
22847       struct dwarf2_per_cu_data *per_cu;
22848
22849       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22850                                                  dwarf2_per_objfile);
22851
22852       /* If necessary, add it to the queue and load its DIEs.  */
22853       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22854         load_full_comp_unit (per_cu, false, cu->language);
22855
22856       target_cu = per_cu->cu;
22857     }
22858   else if (cu->dies == NULL)
22859     {
22860       /* We're loading full DIEs during partial symbol reading.  */
22861       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22862       load_full_comp_unit (cu->per_cu, false, language_minimal);
22863     }
22864
22865   *ref_cu = target_cu;
22866   temp_die.sect_off = sect_off;
22867
22868   if (target_cu != cu)
22869     target_cu->ancestor = cu;
22870
22871   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22872                                                   &temp_die,
22873                                                   to_underlying (sect_off));
22874 }
22875
22876 /* Follow reference attribute ATTR of SRC_DIE.
22877    On entry *REF_CU is the CU of SRC_DIE.
22878    On exit *REF_CU is the CU of the result.  */
22879
22880 static struct die_info *
22881 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22882                 struct dwarf2_cu **ref_cu)
22883 {
22884   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22885   struct dwarf2_cu *cu = *ref_cu;
22886   struct die_info *die;
22887
22888   die = follow_die_offset (sect_off,
22889                            (attr->form == DW_FORM_GNU_ref_alt
22890                             || cu->per_cu->is_dwz),
22891                            ref_cu);
22892   if (!die)
22893     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22894            "at %s [in module %s]"),
22895            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22896            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22897
22898   return die;
22899 }
22900
22901 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22902    Returned value is intended for DW_OP_call*.  Returned
22903    dwarf2_locexpr_baton->data has lifetime of
22904    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22905
22906 struct dwarf2_locexpr_baton
22907 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22908                                struct dwarf2_per_cu_data *per_cu,
22909                                CORE_ADDR (*get_frame_pc) (void *baton),
22910                                void *baton, bool resolve_abstract_p)
22911 {
22912   struct dwarf2_cu *cu;
22913   struct die_info *die;
22914   struct attribute *attr;
22915   struct dwarf2_locexpr_baton retval;
22916   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22917   struct objfile *objfile = dwarf2_per_objfile->objfile;
22918
22919   if (per_cu->cu == NULL)
22920     load_cu (per_cu, false);
22921   cu = per_cu->cu;
22922   if (cu == NULL)
22923     {
22924       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22925          Instead just throw an error, not much else we can do.  */
22926       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22927              sect_offset_str (sect_off), objfile_name (objfile));
22928     }
22929
22930   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22931   if (!die)
22932     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22933            sect_offset_str (sect_off), objfile_name (objfile));
22934
22935   attr = dwarf2_attr (die, DW_AT_location, cu);
22936   if (!attr && resolve_abstract_p
22937       && (dwarf2_per_objfile->abstract_to_concrete.find (die->sect_off)
22938           != dwarf2_per_objfile->abstract_to_concrete.end ()))
22939     {
22940       CORE_ADDR pc = (*get_frame_pc) (baton);
22941       CORE_ADDR baseaddr = objfile->text_section_offset ();
22942       struct gdbarch *gdbarch = get_objfile_arch (objfile);
22943
22944       for (const auto &cand_off
22945              : dwarf2_per_objfile->abstract_to_concrete[die->sect_off])
22946         {
22947           struct dwarf2_cu *cand_cu = cu;
22948           struct die_info *cand
22949             = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
22950           if (!cand
22951               || !cand->parent
22952               || cand->parent->tag != DW_TAG_subprogram)
22953             continue;
22954
22955           CORE_ADDR pc_low, pc_high;
22956           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
22957           if (pc_low == ((CORE_ADDR) -1))
22958             continue;
22959           pc_low = gdbarch_adjust_dwarf2_addr (gdbarch, pc_low + baseaddr);
22960           pc_high = gdbarch_adjust_dwarf2_addr (gdbarch, pc_high + baseaddr);
22961           if (!(pc_low <= pc && pc < pc_high))
22962             continue;
22963
22964           die = cand;
22965           attr = dwarf2_attr (die, DW_AT_location, cu);
22966           break;
22967         }
22968     }
22969
22970   if (!attr)
22971     {
22972       /* DWARF: "If there is no such attribute, then there is no effect.".
22973          DATA is ignored if SIZE is 0.  */
22974
22975       retval.data = NULL;
22976       retval.size = 0;
22977     }
22978   else if (attr->form_is_section_offset ())
22979     {
22980       struct dwarf2_loclist_baton loclist_baton;
22981       CORE_ADDR pc = (*get_frame_pc) (baton);
22982       size_t size;
22983
22984       fill_in_loclist_baton (cu, &loclist_baton, attr);
22985
22986       retval.data = dwarf2_find_location_expression (&loclist_baton,
22987                                                      &size, pc);
22988       retval.size = size;
22989     }
22990   else
22991     {
22992       if (!attr->form_is_block ())
22993         error (_("Dwarf Error: DIE at %s referenced in module %s "
22994                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22995                sect_offset_str (sect_off), objfile_name (objfile));
22996
22997       retval.data = DW_BLOCK (attr)->data;
22998       retval.size = DW_BLOCK (attr)->size;
22999     }
23000   retval.per_cu = cu->per_cu;
23001
23002   age_cached_comp_units (dwarf2_per_objfile);
23003
23004   return retval;
23005 }
23006
23007 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23008    offset.  */
23009
23010 struct dwarf2_locexpr_baton
23011 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23012                              struct dwarf2_per_cu_data *per_cu,
23013                              CORE_ADDR (*get_frame_pc) (void *baton),
23014                              void *baton)
23015 {
23016   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23017
23018   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23019 }
23020
23021 /* Write a constant of a given type as target-ordered bytes into
23022    OBSTACK.  */
23023
23024 static const gdb_byte *
23025 write_constant_as_bytes (struct obstack *obstack,
23026                          enum bfd_endian byte_order,
23027                          struct type *type,
23028                          ULONGEST value,
23029                          LONGEST *len)
23030 {
23031   gdb_byte *result;
23032
23033   *len = TYPE_LENGTH (type);
23034   result = (gdb_byte *) obstack_alloc (obstack, *len);
23035   store_unsigned_integer (result, *len, byte_order, value);
23036
23037   return result;
23038 }
23039
23040 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23041    pointer to the constant bytes and set LEN to the length of the
23042    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23043    does not have a DW_AT_const_value, return NULL.  */
23044
23045 const gdb_byte *
23046 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23047                              struct dwarf2_per_cu_data *per_cu,
23048                              struct obstack *obstack,
23049                              LONGEST *len)
23050 {
23051   struct dwarf2_cu *cu;
23052   struct die_info *die;
23053   struct attribute *attr;
23054   const gdb_byte *result = NULL;
23055   struct type *type;
23056   LONGEST value;
23057   enum bfd_endian byte_order;
23058   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23059
23060   if (per_cu->cu == NULL)
23061     load_cu (per_cu, false);
23062   cu = per_cu->cu;
23063   if (cu == NULL)
23064     {
23065       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23066          Instead just throw an error, not much else we can do.  */
23067       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23068              sect_offset_str (sect_off), objfile_name (objfile));
23069     }
23070
23071   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23072   if (!die)
23073     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23074            sect_offset_str (sect_off), objfile_name (objfile));
23075
23076   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23077   if (attr == NULL)
23078     return NULL;
23079
23080   byte_order = (bfd_big_endian (objfile->obfd)
23081                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23082
23083   switch (attr->form)
23084     {
23085     case DW_FORM_addr:
23086     case DW_FORM_addrx:
23087     case DW_FORM_GNU_addr_index:
23088       {
23089         gdb_byte *tem;
23090
23091         *len = cu->header.addr_size;
23092         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23093         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23094         result = tem;
23095       }
23096       break;
23097     case DW_FORM_string:
23098     case DW_FORM_strp:
23099     case DW_FORM_strx:
23100     case DW_FORM_GNU_str_index:
23101     case DW_FORM_GNU_strp_alt:
23102       /* DW_STRING is already allocated on the objfile obstack, point
23103          directly to it.  */
23104       result = (const gdb_byte *) DW_STRING (attr);
23105       *len = strlen (DW_STRING (attr));
23106       break;
23107     case DW_FORM_block1:
23108     case DW_FORM_block2:
23109     case DW_FORM_block4:
23110     case DW_FORM_block:
23111     case DW_FORM_exprloc:
23112     case DW_FORM_data16:
23113       result = DW_BLOCK (attr)->data;
23114       *len = DW_BLOCK (attr)->size;
23115       break;
23116
23117       /* The DW_AT_const_value attributes are supposed to carry the
23118          symbol's value "represented as it would be on the target
23119          architecture."  By the time we get here, it's already been
23120          converted to host endianness, so we just need to sign- or
23121          zero-extend it as appropriate.  */
23122     case DW_FORM_data1:
23123       type = die_type (die, cu);
23124       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23125       if (result == NULL)
23126         result = write_constant_as_bytes (obstack, byte_order,
23127                                           type, value, len);
23128       break;
23129     case DW_FORM_data2:
23130       type = die_type (die, cu);
23131       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23132       if (result == NULL)
23133         result = write_constant_as_bytes (obstack, byte_order,
23134                                           type, value, len);
23135       break;
23136     case DW_FORM_data4:
23137       type = die_type (die, cu);
23138       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23139       if (result == NULL)
23140         result = write_constant_as_bytes (obstack, byte_order,
23141                                           type, value, len);
23142       break;
23143     case DW_FORM_data8:
23144       type = die_type (die, cu);
23145       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23146       if (result == NULL)
23147         result = write_constant_as_bytes (obstack, byte_order,
23148                                           type, value, len);
23149       break;
23150
23151     case DW_FORM_sdata:
23152     case DW_FORM_implicit_const:
23153       type = die_type (die, cu);
23154       result = write_constant_as_bytes (obstack, byte_order,
23155                                         type, DW_SND (attr), len);
23156       break;
23157
23158     case DW_FORM_udata:
23159       type = die_type (die, cu);
23160       result = write_constant_as_bytes (obstack, byte_order,
23161                                         type, DW_UNSND (attr), len);
23162       break;
23163
23164     default:
23165       complaint (_("unsupported const value attribute form: '%s'"),
23166                  dwarf_form_name (attr->form));
23167       break;
23168     }
23169
23170   return result;
23171 }
23172
23173 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23174    valid type for this die is found.  */
23175
23176 struct type *
23177 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23178                                 struct dwarf2_per_cu_data *per_cu)
23179 {
23180   struct dwarf2_cu *cu;
23181   struct die_info *die;
23182
23183   if (per_cu->cu == NULL)
23184     load_cu (per_cu, false);
23185   cu = per_cu->cu;
23186   if (!cu)
23187     return NULL;
23188
23189   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23190   if (!die)
23191     return NULL;
23192
23193   return die_type (die, cu);
23194 }
23195
23196 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23197    PER_CU.  */
23198
23199 struct type *
23200 dwarf2_get_die_type (cu_offset die_offset,
23201                      struct dwarf2_per_cu_data *per_cu)
23202 {
23203   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23204   return get_die_type_at_offset (die_offset_sect, per_cu);
23205 }
23206
23207 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23208    On entry *REF_CU is the CU of SRC_DIE.
23209    On exit *REF_CU is the CU of the result.
23210    Returns NULL if the referenced DIE isn't found.  */
23211
23212 static struct die_info *
23213 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23214                   struct dwarf2_cu **ref_cu)
23215 {
23216   struct die_info temp_die;
23217   struct dwarf2_cu *sig_cu, *cu = *ref_cu;
23218   struct die_info *die;
23219
23220   /* While it might be nice to assert sig_type->type == NULL here,
23221      we can get here for DW_AT_imported_declaration where we need
23222      the DIE not the type.  */
23223
23224   /* If necessary, add it to the queue and load its DIEs.  */
23225
23226   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23227     read_signatured_type (sig_type);
23228
23229   sig_cu = sig_type->per_cu.cu;
23230   gdb_assert (sig_cu != NULL);
23231   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23232   temp_die.sect_off = sig_type->type_offset_in_section;
23233   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23234                                                  to_underlying (temp_die.sect_off));
23235   if (die)
23236     {
23237       struct dwarf2_per_objfile *dwarf2_per_objfile
23238         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23239
23240       /* For .gdb_index version 7 keep track of included TUs.
23241          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23242       if (dwarf2_per_objfile->index_table != NULL
23243           && dwarf2_per_objfile->index_table->version <= 7)
23244         {
23245           (*ref_cu)->per_cu->imported_symtabs_push (sig_cu->per_cu);
23246         }
23247
23248       *ref_cu = sig_cu;
23249       if (sig_cu != cu)
23250         sig_cu->ancestor = cu;
23251
23252       return die;
23253     }
23254
23255   return NULL;
23256 }
23257
23258 /* Follow signatured type referenced by ATTR in SRC_DIE.
23259    On entry *REF_CU is the CU of SRC_DIE.
23260    On exit *REF_CU is the CU of the result.
23261    The result is the DIE of the type.
23262    If the referenced type cannot be found an error is thrown.  */
23263
23264 static struct die_info *
23265 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23266                 struct dwarf2_cu **ref_cu)
23267 {
23268   ULONGEST signature = DW_SIGNATURE (attr);
23269   struct signatured_type *sig_type;
23270   struct die_info *die;
23271
23272   gdb_assert (attr->form == DW_FORM_ref_sig8);
23273
23274   sig_type = lookup_signatured_type (*ref_cu, signature);
23275   /* sig_type will be NULL if the signatured type is missing from
23276      the debug info.  */
23277   if (sig_type == NULL)
23278     {
23279       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23280                " from DIE at %s [in module %s]"),
23281              hex_string (signature), sect_offset_str (src_die->sect_off),
23282              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23283     }
23284
23285   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23286   if (die == NULL)
23287     {
23288       dump_die_for_error (src_die);
23289       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23290                " from DIE at %s [in module %s]"),
23291              hex_string (signature), sect_offset_str (src_die->sect_off),
23292              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23293     }
23294
23295   return die;
23296 }
23297
23298 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23299    reading in and processing the type unit if necessary.  */
23300
23301 static struct type *
23302 get_signatured_type (struct die_info *die, ULONGEST signature,
23303                      struct dwarf2_cu *cu)
23304 {
23305   struct dwarf2_per_objfile *dwarf2_per_objfile
23306     = cu->per_cu->dwarf2_per_objfile;
23307   struct signatured_type *sig_type;
23308   struct dwarf2_cu *type_cu;
23309   struct die_info *type_die;
23310   struct type *type;
23311
23312   sig_type = lookup_signatured_type (cu, signature);
23313   /* sig_type will be NULL if the signatured type is missing from
23314      the debug info.  */
23315   if (sig_type == NULL)
23316     {
23317       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23318                    " from DIE at %s [in module %s]"),
23319                  hex_string (signature), sect_offset_str (die->sect_off),
23320                  objfile_name (dwarf2_per_objfile->objfile));
23321       return build_error_marker_type (cu, die);
23322     }
23323
23324   /* If we already know the type we're done.  */
23325   if (sig_type->type != NULL)
23326     return sig_type->type;
23327
23328   type_cu = cu;
23329   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23330   if (type_die != NULL)
23331     {
23332       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23333          is created.  This is important, for example, because for c++ classes
23334          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23335       type = read_type_die (type_die, type_cu);
23336       if (type == NULL)
23337         {
23338           complaint (_("Dwarf Error: Cannot build signatured type %s"
23339                        " referenced from DIE at %s [in module %s]"),
23340                      hex_string (signature), sect_offset_str (die->sect_off),
23341                      objfile_name (dwarf2_per_objfile->objfile));
23342           type = build_error_marker_type (cu, die);
23343         }
23344     }
23345   else
23346     {
23347       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23348                    " 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   sig_type->type = type;
23354
23355   return type;
23356 }
23357
23358 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23359    reading in and processing the type unit if necessary.  */
23360
23361 static struct type *
23362 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23363                           struct dwarf2_cu *cu) /* ARI: editCase function */
23364 {
23365   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23366   if (attr->form_is_ref ())
23367     {
23368       struct dwarf2_cu *type_cu = cu;
23369       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23370
23371       return read_type_die (type_die, type_cu);
23372     }
23373   else if (attr->form == DW_FORM_ref_sig8)
23374     {
23375       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23376     }
23377   else
23378     {
23379       struct dwarf2_per_objfile *dwarf2_per_objfile
23380         = cu->per_cu->dwarf2_per_objfile;
23381
23382       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23383                    " at %s [in module %s]"),
23384                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23385                  objfile_name (dwarf2_per_objfile->objfile));
23386       return build_error_marker_type (cu, die);
23387     }
23388 }
23389
23390 /* Load the DIEs associated with type unit PER_CU into memory.  */
23391
23392 static void
23393 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23394 {
23395   struct signatured_type *sig_type;
23396
23397   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23398   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23399
23400   /* We have the per_cu, but we need the signatured_type.
23401      Fortunately this is an easy translation.  */
23402   gdb_assert (per_cu->is_debug_types);
23403   sig_type = (struct signatured_type *) per_cu;
23404
23405   gdb_assert (per_cu->cu == NULL);
23406
23407   read_signatured_type (sig_type);
23408
23409   gdb_assert (per_cu->cu != NULL);
23410 }
23411
23412 /* Read in a signatured type and build its CU and DIEs.
23413    If the type is a stub for the real type in a DWO file,
23414    read in the real type from the DWO file as well.  */
23415
23416 static void
23417 read_signatured_type (struct signatured_type *sig_type)
23418 {
23419   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23420
23421   gdb_assert (per_cu->is_debug_types);
23422   gdb_assert (per_cu->cu == NULL);
23423
23424   cutu_reader reader (per_cu, NULL, 0, 1, false);
23425
23426   if (!reader.dummy_p)
23427     {
23428       struct dwarf2_cu *cu = reader.cu;
23429       const gdb_byte *info_ptr = reader.info_ptr;
23430
23431       gdb_assert (cu->die_hash == NULL);
23432       cu->die_hash =
23433         htab_create_alloc_ex (cu->header.length / 12,
23434                               die_hash,
23435                               die_eq,
23436                               NULL,
23437                               &cu->comp_unit_obstack,
23438                               hashtab_obstack_allocate,
23439                               dummy_obstack_deallocate);
23440
23441       if (reader.comp_unit_die->has_children)
23442         reader.comp_unit_die->child
23443           = read_die_and_siblings (&reader, info_ptr, &info_ptr,
23444                                    reader.comp_unit_die);
23445       cu->dies = reader.comp_unit_die;
23446       /* comp_unit_die is not stored in die_hash, no need.  */
23447
23448       /* We try not to read any attributes in this function, because
23449          not all CUs needed for references have been loaded yet, and
23450          symbol table processing isn't initialized.  But we have to
23451          set the CU language, or we won't be able to build types
23452          correctly.  Similarly, if we do not read the producer, we can
23453          not apply producer-specific interpretation.  */
23454       prepare_one_comp_unit (cu, cu->dies, language_minimal);
23455     }
23456
23457   sig_type->per_cu.tu_read = 1;
23458 }
23459
23460 /* Decode simple location descriptions.
23461    Given a pointer to a dwarf block that defines a location, compute
23462    the location and return the value.
23463
23464    NOTE drow/2003-11-18: This function is called in two situations
23465    now: for the address of static or global variables (partial symbols
23466    only) and for offsets into structures which are expected to be
23467    (more or less) constant.  The partial symbol case should go away,
23468    and only the constant case should remain.  That will let this
23469    function complain more accurately.  A few special modes are allowed
23470    without complaint for global variables (for instance, global
23471    register values and thread-local values).
23472
23473    A location description containing no operations indicates that the
23474    object is optimized out.  The return value is 0 for that case.
23475    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23476    callers will only want a very basic result and this can become a
23477    complaint.
23478
23479    Note that stack[0] is unused except as a default error return.  */
23480
23481 static CORE_ADDR
23482 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23483 {
23484   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23485   size_t i;
23486   size_t size = blk->size;
23487   const gdb_byte *data = blk->data;
23488   CORE_ADDR stack[64];
23489   int stacki;
23490   unsigned int bytes_read, unsnd;
23491   gdb_byte op;
23492
23493   i = 0;
23494   stacki = 0;
23495   stack[stacki] = 0;
23496   stack[++stacki] = 0;
23497
23498   while (i < size)
23499     {
23500       op = data[i++];
23501       switch (op)
23502         {
23503         case DW_OP_lit0:
23504         case DW_OP_lit1:
23505         case DW_OP_lit2:
23506         case DW_OP_lit3:
23507         case DW_OP_lit4:
23508         case DW_OP_lit5:
23509         case DW_OP_lit6:
23510         case DW_OP_lit7:
23511         case DW_OP_lit8:
23512         case DW_OP_lit9:
23513         case DW_OP_lit10:
23514         case DW_OP_lit11:
23515         case DW_OP_lit12:
23516         case DW_OP_lit13:
23517         case DW_OP_lit14:
23518         case DW_OP_lit15:
23519         case DW_OP_lit16:
23520         case DW_OP_lit17:
23521         case DW_OP_lit18:
23522         case DW_OP_lit19:
23523         case DW_OP_lit20:
23524         case DW_OP_lit21:
23525         case DW_OP_lit22:
23526         case DW_OP_lit23:
23527         case DW_OP_lit24:
23528         case DW_OP_lit25:
23529         case DW_OP_lit26:
23530         case DW_OP_lit27:
23531         case DW_OP_lit28:
23532         case DW_OP_lit29:
23533         case DW_OP_lit30:
23534         case DW_OP_lit31:
23535           stack[++stacki] = op - DW_OP_lit0;
23536           break;
23537
23538         case DW_OP_reg0:
23539         case DW_OP_reg1:
23540         case DW_OP_reg2:
23541         case DW_OP_reg3:
23542         case DW_OP_reg4:
23543         case DW_OP_reg5:
23544         case DW_OP_reg6:
23545         case DW_OP_reg7:
23546         case DW_OP_reg8:
23547         case DW_OP_reg9:
23548         case DW_OP_reg10:
23549         case DW_OP_reg11:
23550         case DW_OP_reg12:
23551         case DW_OP_reg13:
23552         case DW_OP_reg14:
23553         case DW_OP_reg15:
23554         case DW_OP_reg16:
23555         case DW_OP_reg17:
23556         case DW_OP_reg18:
23557         case DW_OP_reg19:
23558         case DW_OP_reg20:
23559         case DW_OP_reg21:
23560         case DW_OP_reg22:
23561         case DW_OP_reg23:
23562         case DW_OP_reg24:
23563         case DW_OP_reg25:
23564         case DW_OP_reg26:
23565         case DW_OP_reg27:
23566         case DW_OP_reg28:
23567         case DW_OP_reg29:
23568         case DW_OP_reg30:
23569         case DW_OP_reg31:
23570           stack[++stacki] = op - DW_OP_reg0;
23571           if (i < size)
23572             dwarf2_complex_location_expr_complaint ();
23573           break;
23574
23575         case DW_OP_regx:
23576           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23577           i += bytes_read;
23578           stack[++stacki] = unsnd;
23579           if (i < size)
23580             dwarf2_complex_location_expr_complaint ();
23581           break;
23582
23583         case DW_OP_addr:
23584           stack[++stacki] = read_address (objfile->obfd, &data[i],
23585                                           cu, &bytes_read);
23586           i += bytes_read;
23587           break;
23588
23589         case DW_OP_const1u:
23590           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23591           i += 1;
23592           break;
23593
23594         case DW_OP_const1s:
23595           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23596           i += 1;
23597           break;
23598
23599         case DW_OP_const2u:
23600           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23601           i += 2;
23602           break;
23603
23604         case DW_OP_const2s:
23605           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23606           i += 2;
23607           break;
23608
23609         case DW_OP_const4u:
23610           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23611           i += 4;
23612           break;
23613
23614         case DW_OP_const4s:
23615           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23616           i += 4;
23617           break;
23618
23619         case DW_OP_const8u:
23620           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23621           i += 8;
23622           break;
23623
23624         case DW_OP_constu:
23625           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23626                                                   &bytes_read);
23627           i += bytes_read;
23628           break;
23629
23630         case DW_OP_consts:
23631           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23632           i += bytes_read;
23633           break;
23634
23635         case DW_OP_dup:
23636           stack[stacki + 1] = stack[stacki];
23637           stacki++;
23638           break;
23639
23640         case DW_OP_plus:
23641           stack[stacki - 1] += stack[stacki];
23642           stacki--;
23643           break;
23644
23645         case DW_OP_plus_uconst:
23646           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23647                                                  &bytes_read);
23648           i += bytes_read;
23649           break;
23650
23651         case DW_OP_minus:
23652           stack[stacki - 1] -= stack[stacki];
23653           stacki--;
23654           break;
23655
23656         case DW_OP_deref:
23657           /* If we're not the last op, then we definitely can't encode
23658              this using GDB's address_class enum.  This is valid for partial
23659              global symbols, although the variable's address will be bogus
23660              in the psymtab.  */
23661           if (i < size)
23662             dwarf2_complex_location_expr_complaint ();
23663           break;
23664
23665         case DW_OP_GNU_push_tls_address:
23666         case DW_OP_form_tls_address:
23667           /* The top of the stack has the offset from the beginning
23668              of the thread control block at which the variable is located.  */
23669           /* Nothing should follow this operator, so the top of stack would
23670              be returned.  */
23671           /* This is valid for partial global symbols, but the variable's
23672              address will be bogus in the psymtab.  Make it always at least
23673              non-zero to not look as a variable garbage collected by linker
23674              which have DW_OP_addr 0.  */
23675           if (i < size)
23676             dwarf2_complex_location_expr_complaint ();
23677           stack[stacki]++;
23678           break;
23679
23680         case DW_OP_GNU_uninit:
23681           break;
23682
23683         case DW_OP_addrx:
23684         case DW_OP_GNU_addr_index:
23685         case DW_OP_GNU_const_index:
23686           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23687                                                          &bytes_read);
23688           i += bytes_read;
23689           break;
23690
23691         default:
23692           {
23693             const char *name = get_DW_OP_name (op);
23694
23695             if (name)
23696               complaint (_("unsupported stack op: '%s'"),
23697                          name);
23698             else
23699               complaint (_("unsupported stack op: '%02x'"),
23700                          op);
23701           }
23702
23703           return (stack[stacki]);
23704         }
23705
23706       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23707          outside of the allocated space.  Also enforce minimum>0.  */
23708       if (stacki >= ARRAY_SIZE (stack) - 1)
23709         {
23710           complaint (_("location description stack overflow"));
23711           return 0;
23712         }
23713
23714       if (stacki <= 0)
23715         {
23716           complaint (_("location description stack underflow"));
23717           return 0;
23718         }
23719     }
23720   return (stack[stacki]);
23721 }
23722
23723 /* memory allocation interface */
23724
23725 static struct dwarf_block *
23726 dwarf_alloc_block (struct dwarf2_cu *cu)
23727 {
23728   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23729 }
23730
23731 static struct die_info *
23732 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23733 {
23734   struct die_info *die;
23735   size_t size = sizeof (struct die_info);
23736
23737   if (num_attrs > 1)
23738     size += (num_attrs - 1) * sizeof (struct attribute);
23739
23740   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23741   memset (die, 0, sizeof (struct die_info));
23742   return (die);
23743 }
23744
23745 \f
23746 /* Macro support.  */
23747
23748 /* Return file name relative to the compilation directory of file number I in
23749    *LH's file name table.  The result is allocated using xmalloc; the caller is
23750    responsible for freeing it.  */
23751
23752 static char *
23753 file_file_name (int file, struct line_header *lh)
23754 {
23755   /* Is the file number a valid index into the line header's file name
23756      table?  Remember that file numbers start with one, not zero.  */
23757   if (lh->is_valid_file_index (file))
23758     {
23759       const file_entry *fe = lh->file_name_at (file);
23760
23761       if (!IS_ABSOLUTE_PATH (fe->name))
23762         {
23763           const char *dir = fe->include_dir (lh);
23764           if (dir != NULL)
23765             return concat (dir, SLASH_STRING, fe->name, (char *) NULL);
23766         }
23767       return xstrdup (fe->name);
23768     }
23769   else
23770     {
23771       /* The compiler produced a bogus file number.  We can at least
23772          record the macro definitions made in the file, even if we
23773          won't be able to find the file by name.  */
23774       char fake_name[80];
23775
23776       xsnprintf (fake_name, sizeof (fake_name),
23777                  "<bad macro file number %d>", file);
23778
23779       complaint (_("bad file number in macro information (%d)"),
23780                  file);
23781
23782       return xstrdup (fake_name);
23783     }
23784 }
23785
23786 /* Return the full name of file number I in *LH's file name table.
23787    Use COMP_DIR as the name of the current directory of the
23788    compilation.  The result is allocated using xmalloc; the caller is
23789    responsible for freeing it.  */
23790 static char *
23791 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23792 {
23793   /* Is the file number a valid index into the line header's file name
23794      table?  Remember that file numbers start with one, not zero.  */
23795   if (lh->is_valid_file_index (file))
23796     {
23797       char *relative = file_file_name (file, lh);
23798
23799       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23800         return relative;
23801       return reconcat (relative, comp_dir, SLASH_STRING,
23802                        relative, (char *) NULL);
23803     }
23804   else
23805     return file_file_name (file, lh);
23806 }
23807
23808
23809 static struct macro_source_file *
23810 macro_start_file (struct dwarf2_cu *cu,
23811                   int file, int line,
23812                   struct macro_source_file *current_file,
23813                   struct line_header *lh)
23814 {
23815   /* File name relative to the compilation directory of this source file.  */
23816   char *file_name = file_file_name (file, lh);
23817
23818   if (! current_file)
23819     {
23820       /* Note: We don't create a macro table for this compilation unit
23821          at all until we actually get a filename.  */
23822       struct macro_table *macro_table = cu->get_builder ()->get_macro_table ();
23823
23824       /* If we have no current file, then this must be the start_file
23825          directive for the compilation unit's main source file.  */
23826       current_file = macro_set_main (macro_table, file_name);
23827       macro_define_special (macro_table);
23828     }
23829   else
23830     current_file = macro_include (current_file, line, file_name);
23831
23832   xfree (file_name);
23833
23834   return current_file;
23835 }
23836
23837 static const char *
23838 consume_improper_spaces (const char *p, const char *body)
23839 {
23840   if (*p == ' ')
23841     {
23842       complaint (_("macro definition contains spaces "
23843                    "in formal argument list:\n`%s'"),
23844                  body);
23845
23846       while (*p == ' ')
23847         p++;
23848     }
23849
23850   return p;
23851 }
23852
23853
23854 static void
23855 parse_macro_definition (struct macro_source_file *file, int line,
23856                         const char *body)
23857 {
23858   const char *p;
23859
23860   /* The body string takes one of two forms.  For object-like macro
23861      definitions, it should be:
23862
23863         <macro name> " " <definition>
23864
23865      For function-like macro definitions, it should be:
23866
23867         <macro name> "() " <definition>
23868      or
23869         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23870
23871      Spaces may appear only where explicitly indicated, and in the
23872      <definition>.
23873
23874      The Dwarf 2 spec says that an object-like macro's name is always
23875      followed by a space, but versions of GCC around March 2002 omit
23876      the space when the macro's definition is the empty string.
23877
23878      The Dwarf 2 spec says that there should be no spaces between the
23879      formal arguments in a function-like macro's formal argument list,
23880      but versions of GCC around March 2002 include spaces after the
23881      commas.  */
23882
23883
23884   /* Find the extent of the macro name.  The macro name is terminated
23885      by either a space or null character (for an object-like macro) or
23886      an opening paren (for a function-like macro).  */
23887   for (p = body; *p; p++)
23888     if (*p == ' ' || *p == '(')
23889       break;
23890
23891   if (*p == ' ' || *p == '\0')
23892     {
23893       /* It's an object-like macro.  */
23894       int name_len = p - body;
23895       std::string name (body, name_len);
23896       const char *replacement;
23897
23898       if (*p == ' ')
23899         replacement = body + name_len + 1;
23900       else
23901         {
23902           dwarf2_macro_malformed_definition_complaint (body);
23903           replacement = body + name_len;
23904         }
23905
23906       macro_define_object (file, line, name.c_str (), replacement);
23907     }
23908   else if (*p == '(')
23909     {
23910       /* It's a function-like macro.  */
23911       std::string name (body, p - body);
23912       int argc = 0;
23913       int argv_size = 1;
23914       char **argv = XNEWVEC (char *, argv_size);
23915
23916       p++;
23917
23918       p = consume_improper_spaces (p, body);
23919
23920       /* Parse the formal argument list.  */
23921       while (*p && *p != ')')
23922         {
23923           /* Find the extent of the current argument name.  */
23924           const char *arg_start = p;
23925
23926           while (*p && *p != ',' && *p != ')' && *p != ' ')
23927             p++;
23928
23929           if (! *p || p == arg_start)
23930             dwarf2_macro_malformed_definition_complaint (body);
23931           else
23932             {
23933               /* Make sure argv has room for the new argument.  */
23934               if (argc >= argv_size)
23935                 {
23936                   argv_size *= 2;
23937                   argv = XRESIZEVEC (char *, argv, argv_size);
23938                 }
23939
23940               argv[argc++] = savestring (arg_start, p - arg_start);
23941             }
23942
23943           p = consume_improper_spaces (p, body);
23944
23945           /* Consume the comma, if present.  */
23946           if (*p == ',')
23947             {
23948               p++;
23949
23950               p = consume_improper_spaces (p, body);
23951             }
23952         }
23953
23954       if (*p == ')')
23955         {
23956           p++;
23957
23958           if (*p == ' ')
23959             /* Perfectly formed definition, no complaints.  */
23960             macro_define_function (file, line, name.c_str (),
23961                                    argc, (const char **) argv,
23962                                    p + 1);
23963           else if (*p == '\0')
23964             {
23965               /* Complain, but do define it.  */
23966               dwarf2_macro_malformed_definition_complaint (body);
23967               macro_define_function (file, line, name.c_str (),
23968                                      argc, (const char **) argv,
23969                                      p);
23970             }
23971           else
23972             /* Just complain.  */
23973             dwarf2_macro_malformed_definition_complaint (body);
23974         }
23975       else
23976         /* Just complain.  */
23977         dwarf2_macro_malformed_definition_complaint (body);
23978
23979       {
23980         int i;
23981
23982         for (i = 0; i < argc; i++)
23983           xfree (argv[i]);
23984       }
23985       xfree (argv);
23986     }
23987   else
23988     dwarf2_macro_malformed_definition_complaint (body);
23989 }
23990
23991 /* Skip some bytes from BYTES according to the form given in FORM.
23992    Returns the new pointer.  */
23993
23994 static const gdb_byte *
23995 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23996                  enum dwarf_form form,
23997                  unsigned int offset_size,
23998                  struct dwarf2_section_info *section)
23999 {
24000   unsigned int bytes_read;
24001
24002   switch (form)
24003     {
24004     case DW_FORM_data1:
24005     case DW_FORM_flag:
24006       ++bytes;
24007       break;
24008
24009     case DW_FORM_data2:
24010       bytes += 2;
24011       break;
24012
24013     case DW_FORM_data4:
24014       bytes += 4;
24015       break;
24016
24017     case DW_FORM_data8:
24018       bytes += 8;
24019       break;
24020
24021     case DW_FORM_data16:
24022       bytes += 16;
24023       break;
24024
24025     case DW_FORM_string:
24026       read_direct_string (abfd, bytes, &bytes_read);
24027       bytes += bytes_read;
24028       break;
24029
24030     case DW_FORM_sec_offset:
24031     case DW_FORM_strp:
24032     case DW_FORM_GNU_strp_alt:
24033       bytes += offset_size;
24034       break;
24035
24036     case DW_FORM_block:
24037       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24038       bytes += bytes_read;
24039       break;
24040
24041     case DW_FORM_block1:
24042       bytes += 1 + read_1_byte (abfd, bytes);
24043       break;
24044     case DW_FORM_block2:
24045       bytes += 2 + read_2_bytes (abfd, bytes);
24046       break;
24047     case DW_FORM_block4:
24048       bytes += 4 + read_4_bytes (abfd, bytes);
24049       break;
24050
24051     case DW_FORM_addrx:
24052     case DW_FORM_sdata:
24053     case DW_FORM_strx:
24054     case DW_FORM_udata:
24055     case DW_FORM_GNU_addr_index:
24056     case DW_FORM_GNU_str_index:
24057       bytes = gdb_skip_leb128 (bytes, buffer_end);
24058       if (bytes == NULL)
24059         {
24060           dwarf2_section_buffer_overflow_complaint (section);
24061           return NULL;
24062         }
24063       break;
24064
24065     case DW_FORM_implicit_const:
24066       break;
24067
24068     default:
24069       {
24070         complaint (_("invalid form 0x%x in `%s'"),
24071                    form, section->get_name ());
24072         return NULL;
24073       }
24074     }
24075
24076   return bytes;
24077 }
24078
24079 /* A helper for dwarf_decode_macros that handles skipping an unknown
24080    opcode.  Returns an updated pointer to the macro data buffer; or,
24081    on error, issues a complaint and returns NULL.  */
24082
24083 static const gdb_byte *
24084 skip_unknown_opcode (unsigned int opcode,
24085                      const gdb_byte **opcode_definitions,
24086                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24087                      bfd *abfd,
24088                      unsigned int offset_size,
24089                      struct dwarf2_section_info *section)
24090 {
24091   unsigned int bytes_read, i;
24092   unsigned long arg;
24093   const gdb_byte *defn;
24094
24095   if (opcode_definitions[opcode] == NULL)
24096     {
24097       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24098                  opcode);
24099       return NULL;
24100     }
24101
24102   defn = opcode_definitions[opcode];
24103   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24104   defn += bytes_read;
24105
24106   for (i = 0; i < arg; ++i)
24107     {
24108       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24109                                  (enum dwarf_form) defn[i], offset_size,
24110                                  section);
24111       if (mac_ptr == NULL)
24112         {
24113           /* skip_form_bytes already issued the complaint.  */
24114           return NULL;
24115         }
24116     }
24117
24118   return mac_ptr;
24119 }
24120
24121 /* A helper function which parses the header of a macro section.
24122    If the macro section is the extended (for now called "GNU") type,
24123    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24124    the header, or issues a complaint and returns NULL on error.  */
24125
24126 static const gdb_byte *
24127 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24128                           bfd *abfd,
24129                           const gdb_byte *mac_ptr,
24130                           unsigned int *offset_size,
24131                           int section_is_gnu)
24132 {
24133   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24134
24135   if (section_is_gnu)
24136     {
24137       unsigned int version, flags;
24138
24139       version = read_2_bytes (abfd, mac_ptr);
24140       if (version != 4 && version != 5)
24141         {
24142           complaint (_("unrecognized version `%d' in .debug_macro section"),
24143                      version);
24144           return NULL;
24145         }
24146       mac_ptr += 2;
24147
24148       flags = read_1_byte (abfd, mac_ptr);
24149       ++mac_ptr;
24150       *offset_size = (flags & 1) ? 8 : 4;
24151
24152       if ((flags & 2) != 0)
24153         /* We don't need the line table offset.  */
24154         mac_ptr += *offset_size;
24155
24156       /* Vendor opcode descriptions.  */
24157       if ((flags & 4) != 0)
24158         {
24159           unsigned int i, count;
24160
24161           count = read_1_byte (abfd, mac_ptr);
24162           ++mac_ptr;
24163           for (i = 0; i < count; ++i)
24164             {
24165               unsigned int opcode, bytes_read;
24166               unsigned long arg;
24167
24168               opcode = read_1_byte (abfd, mac_ptr);
24169               ++mac_ptr;
24170               opcode_definitions[opcode] = mac_ptr;
24171               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24172               mac_ptr += bytes_read;
24173               mac_ptr += arg;
24174             }
24175         }
24176     }
24177
24178   return mac_ptr;
24179 }
24180
24181 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24182    including DW_MACRO_import.  */
24183
24184 static void
24185 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24186                           bfd *abfd,
24187                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24188                           struct macro_source_file *current_file,
24189                           struct line_header *lh,
24190                           struct dwarf2_section_info *section,
24191                           int section_is_gnu, int section_is_dwz,
24192                           unsigned int offset_size,
24193                           htab_t include_hash)
24194 {
24195   struct dwarf2_per_objfile *dwarf2_per_objfile
24196     = cu->per_cu->dwarf2_per_objfile;
24197   struct objfile *objfile = dwarf2_per_objfile->objfile;
24198   enum dwarf_macro_record_type macinfo_type;
24199   int at_commandline;
24200   const gdb_byte *opcode_definitions[256];
24201
24202   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24203                                       &offset_size, section_is_gnu);
24204   if (mac_ptr == NULL)
24205     {
24206       /* We already issued a complaint.  */
24207       return;
24208     }
24209
24210   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24211      GDB is still reading the definitions from command line.  First
24212      DW_MACINFO_start_file will need to be ignored as it was already executed
24213      to create CURRENT_FILE for the main source holding also the command line
24214      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24215      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24216
24217   at_commandline = 1;
24218
24219   do
24220     {
24221       /* Do we at least have room for a macinfo type byte?  */
24222       if (mac_ptr >= mac_end)
24223         {
24224           dwarf2_section_buffer_overflow_complaint (section);
24225           break;
24226         }
24227
24228       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24229       mac_ptr++;
24230
24231       /* Note that we rely on the fact that the corresponding GNU and
24232          DWARF constants are the same.  */
24233       DIAGNOSTIC_PUSH
24234       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24235       switch (macinfo_type)
24236         {
24237           /* A zero macinfo type indicates the end of the macro
24238              information.  */
24239         case 0:
24240           break;
24241
24242         case DW_MACRO_define:
24243         case DW_MACRO_undef:
24244         case DW_MACRO_define_strp:
24245         case DW_MACRO_undef_strp:
24246         case DW_MACRO_define_sup:
24247         case DW_MACRO_undef_sup:
24248           {
24249             unsigned int bytes_read;
24250             int line;
24251             const char *body;
24252             int is_define;
24253
24254             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24255             mac_ptr += bytes_read;
24256
24257             if (macinfo_type == DW_MACRO_define
24258                 || macinfo_type == DW_MACRO_undef)
24259               {
24260                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24261                 mac_ptr += bytes_read;
24262               }
24263             else
24264               {
24265                 LONGEST str_offset;
24266
24267                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24268                 mac_ptr += offset_size;
24269
24270                 if (macinfo_type == DW_MACRO_define_sup
24271                     || macinfo_type == DW_MACRO_undef_sup
24272                     || section_is_dwz)
24273                   {
24274                     struct dwz_file *dwz
24275                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24276
24277                     body = read_indirect_string_from_dwz (objfile,
24278                                                           dwz, str_offset);
24279                   }
24280                 else
24281                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24282                                                          abfd, str_offset);
24283               }
24284
24285             is_define = (macinfo_type == DW_MACRO_define
24286                          || macinfo_type == DW_MACRO_define_strp
24287                          || macinfo_type == DW_MACRO_define_sup);
24288             if (! current_file)
24289               {
24290                 /* DWARF violation as no main source is present.  */
24291                 complaint (_("debug info with no main source gives macro %s "
24292                              "on line %d: %s"),
24293                            is_define ? _("definition") : _("undefinition"),
24294                            line, body);
24295                 break;
24296               }
24297             if ((line == 0 && !at_commandline)
24298                 || (line != 0 && at_commandline))
24299               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24300                          at_commandline ? _("command-line") : _("in-file"),
24301                          is_define ? _("definition") : _("undefinition"),
24302                          line == 0 ? _("zero") : _("non-zero"), line, body);
24303
24304             if (body == NULL)
24305               {
24306                 /* Fedora's rpm-build's "debugedit" binary
24307                    corrupted .debug_macro sections.
24308
24309                    For more info, see
24310                    https://bugzilla.redhat.com/show_bug.cgi?id=1708786 */
24311                 complaint (_("debug info gives %s invalid macro %s "
24312                              "without body (corrupted?) at line %d "
24313                              "on file %s"),
24314                            at_commandline ? _("command-line") : _("in-file"),
24315                            is_define ? _("definition") : _("undefinition"),
24316                            line, current_file->filename);
24317               }
24318             else if (is_define)
24319               parse_macro_definition (current_file, line, body);
24320             else
24321               {
24322                 gdb_assert (macinfo_type == DW_MACRO_undef
24323                             || macinfo_type == DW_MACRO_undef_strp
24324                             || macinfo_type == DW_MACRO_undef_sup);
24325                 macro_undef (current_file, line, body);
24326               }
24327           }
24328           break;
24329
24330         case DW_MACRO_start_file:
24331           {
24332             unsigned int bytes_read;
24333             int line, file;
24334
24335             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24336             mac_ptr += bytes_read;
24337             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24338             mac_ptr += bytes_read;
24339
24340             if ((line == 0 && !at_commandline)
24341                 || (line != 0 && at_commandline))
24342               complaint (_("debug info gives source %d included "
24343                            "from %s at %s line %d"),
24344                          file, at_commandline ? _("command-line") : _("file"),
24345                          line == 0 ? _("zero") : _("non-zero"), line);
24346
24347             if (at_commandline)
24348               {
24349                 /* This DW_MACRO_start_file was executed in the
24350                    pass one.  */
24351                 at_commandline = 0;
24352               }
24353             else
24354               current_file = macro_start_file (cu, file, line, current_file,
24355                                                lh);
24356           }
24357           break;
24358
24359         case DW_MACRO_end_file:
24360           if (! current_file)
24361             complaint (_("macro debug info has an unmatched "
24362                          "`close_file' directive"));
24363           else
24364             {
24365               current_file = current_file->included_by;
24366               if (! current_file)
24367                 {
24368                   enum dwarf_macro_record_type next_type;
24369
24370                   /* GCC circa March 2002 doesn't produce the zero
24371                      type byte marking the end of the compilation
24372                      unit.  Complain if it's not there, but exit no
24373                      matter what.  */
24374
24375                   /* Do we at least have room for a macinfo type byte?  */
24376                   if (mac_ptr >= mac_end)
24377                     {
24378                       dwarf2_section_buffer_overflow_complaint (section);
24379                       return;
24380                     }
24381
24382                   /* We don't increment mac_ptr here, so this is just
24383                      a look-ahead.  */
24384                   next_type
24385                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24386                                                                   mac_ptr);
24387                   if (next_type != 0)
24388                     complaint (_("no terminating 0-type entry for "
24389                                  "macros in `.debug_macinfo' section"));
24390
24391                   return;
24392                 }
24393             }
24394           break;
24395
24396         case DW_MACRO_import:
24397         case DW_MACRO_import_sup:
24398           {
24399             LONGEST offset;
24400             void **slot;
24401             bfd *include_bfd = abfd;
24402             struct dwarf2_section_info *include_section = section;
24403             const gdb_byte *include_mac_end = mac_end;
24404             int is_dwz = section_is_dwz;
24405             const gdb_byte *new_mac_ptr;
24406
24407             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24408             mac_ptr += offset_size;
24409
24410             if (macinfo_type == DW_MACRO_import_sup)
24411               {
24412                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24413
24414                 dwz->macro.read (objfile);
24415
24416                 include_section = &dwz->macro;
24417                 include_bfd = include_section->get_bfd_owner ();
24418                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24419                 is_dwz = 1;
24420               }
24421
24422             new_mac_ptr = include_section->buffer + offset;
24423             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24424
24425             if (*slot != NULL)
24426               {
24427                 /* This has actually happened; see
24428                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24429                 complaint (_("recursive DW_MACRO_import in "
24430                              ".debug_macro section"));
24431               }
24432             else
24433               {
24434                 *slot = (void *) new_mac_ptr;
24435
24436                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24437                                           include_mac_end, current_file, lh,
24438                                           section, section_is_gnu, is_dwz,
24439                                           offset_size, include_hash);
24440
24441                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24442               }
24443           }
24444           break;
24445
24446         case DW_MACINFO_vendor_ext:
24447           if (!section_is_gnu)
24448             {
24449               unsigned int bytes_read;
24450
24451               /* This reads the constant, but since we don't recognize
24452                  any vendor extensions, we ignore it.  */
24453               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24454               mac_ptr += bytes_read;
24455               read_direct_string (abfd, mac_ptr, &bytes_read);
24456               mac_ptr += bytes_read;
24457
24458               /* We don't recognize any vendor extensions.  */
24459               break;
24460             }
24461           /* FALLTHROUGH */
24462
24463         default:
24464           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24465                                          mac_ptr, mac_end, abfd, offset_size,
24466                                          section);
24467           if (mac_ptr == NULL)
24468             return;
24469           break;
24470         }
24471       DIAGNOSTIC_POP
24472     } while (macinfo_type != 0);
24473 }
24474
24475 static void
24476 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24477                      int section_is_gnu)
24478 {
24479   struct dwarf2_per_objfile *dwarf2_per_objfile
24480     = cu->per_cu->dwarf2_per_objfile;
24481   struct objfile *objfile = dwarf2_per_objfile->objfile;
24482   struct line_header *lh = cu->line_header;
24483   bfd *abfd;
24484   const gdb_byte *mac_ptr, *mac_end;
24485   struct macro_source_file *current_file = 0;
24486   enum dwarf_macro_record_type macinfo_type;
24487   unsigned int offset_size = cu->header.offset_size;
24488   const gdb_byte *opcode_definitions[256];
24489   void **slot;
24490   struct dwarf2_section_info *section;
24491   const char *section_name;
24492
24493   if (cu->dwo_unit != NULL)
24494     {
24495       if (section_is_gnu)
24496         {
24497           section = &cu->dwo_unit->dwo_file->sections.macro;
24498           section_name = ".debug_macro.dwo";
24499         }
24500       else
24501         {
24502           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24503           section_name = ".debug_macinfo.dwo";
24504         }
24505     }
24506   else
24507     {
24508       if (section_is_gnu)
24509         {
24510           section = &dwarf2_per_objfile->macro;
24511           section_name = ".debug_macro";
24512         }
24513       else
24514         {
24515           section = &dwarf2_per_objfile->macinfo;
24516           section_name = ".debug_macinfo";
24517         }
24518     }
24519
24520   section->read (objfile);
24521   if (section->buffer == NULL)
24522     {
24523       complaint (_("missing %s section"), section_name);
24524       return;
24525     }
24526   abfd = section->get_bfd_owner ();
24527
24528   /* First pass: Find the name of the base filename.
24529      This filename is needed in order to process all macros whose definition
24530      (or undefinition) comes from the command line.  These macros are defined
24531      before the first DW_MACINFO_start_file entry, and yet still need to be
24532      associated to the base file.
24533
24534      To determine the base file name, we scan the macro definitions until we
24535      reach the first DW_MACINFO_start_file entry.  We then initialize
24536      CURRENT_FILE accordingly so that any macro definition found before the
24537      first DW_MACINFO_start_file can still be associated to the base file.  */
24538
24539   mac_ptr = section->buffer + offset;
24540   mac_end = section->buffer + section->size;
24541
24542   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24543                                       &offset_size, section_is_gnu);
24544   if (mac_ptr == NULL)
24545     {
24546       /* We already issued a complaint.  */
24547       return;
24548     }
24549
24550   do
24551     {
24552       /* Do we at least have room for a macinfo type byte?  */
24553       if (mac_ptr >= mac_end)
24554         {
24555           /* Complaint is printed during the second pass as GDB will probably
24556              stop the first pass earlier upon finding
24557              DW_MACINFO_start_file.  */
24558           break;
24559         }
24560
24561       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24562       mac_ptr++;
24563
24564       /* Note that we rely on the fact that the corresponding GNU and
24565          DWARF constants are the same.  */
24566       DIAGNOSTIC_PUSH
24567       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24568       switch (macinfo_type)
24569         {
24570           /* A zero macinfo type indicates the end of the macro
24571              information.  */
24572         case 0:
24573           break;
24574
24575         case DW_MACRO_define:
24576         case DW_MACRO_undef:
24577           /* Only skip the data by MAC_PTR.  */
24578           {
24579             unsigned int bytes_read;
24580
24581             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24582             mac_ptr += bytes_read;
24583             read_direct_string (abfd, mac_ptr, &bytes_read);
24584             mac_ptr += bytes_read;
24585           }
24586           break;
24587
24588         case DW_MACRO_start_file:
24589           {
24590             unsigned int bytes_read;
24591             int line, file;
24592
24593             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24594             mac_ptr += bytes_read;
24595             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24596             mac_ptr += bytes_read;
24597
24598             current_file = macro_start_file (cu, file, line, current_file, lh);
24599           }
24600           break;
24601
24602         case DW_MACRO_end_file:
24603           /* No data to skip by MAC_PTR.  */
24604           break;
24605
24606         case DW_MACRO_define_strp:
24607         case DW_MACRO_undef_strp:
24608         case DW_MACRO_define_sup:
24609         case DW_MACRO_undef_sup:
24610           {
24611             unsigned int bytes_read;
24612
24613             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24614             mac_ptr += bytes_read;
24615             mac_ptr += offset_size;
24616           }
24617           break;
24618
24619         case DW_MACRO_import:
24620         case DW_MACRO_import_sup:
24621           /* Note that, according to the spec, a transparent include
24622              chain cannot call DW_MACRO_start_file.  So, we can just
24623              skip this opcode.  */
24624           mac_ptr += offset_size;
24625           break;
24626
24627         case DW_MACINFO_vendor_ext:
24628           /* Only skip the data by MAC_PTR.  */
24629           if (!section_is_gnu)
24630             {
24631               unsigned int bytes_read;
24632
24633               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24634               mac_ptr += bytes_read;
24635               read_direct_string (abfd, mac_ptr, &bytes_read);
24636               mac_ptr += bytes_read;
24637             }
24638           /* FALLTHROUGH */
24639
24640         default:
24641           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24642                                          mac_ptr, mac_end, abfd, offset_size,
24643                                          section);
24644           if (mac_ptr == NULL)
24645             return;
24646           break;
24647         }
24648       DIAGNOSTIC_POP
24649     } while (macinfo_type != 0 && current_file == NULL);
24650
24651   /* Second pass: Process all entries.
24652
24653      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24654      command-line macro definitions/undefinitions.  This flag is unset when we
24655      reach the first DW_MACINFO_start_file entry.  */
24656
24657   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24658                                            htab_eq_pointer,
24659                                            NULL, xcalloc, xfree));
24660   mac_ptr = section->buffer + offset;
24661   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24662   *slot = (void *) mac_ptr;
24663   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24664                             current_file, lh, section,
24665                             section_is_gnu, 0, offset_size,
24666                             include_hash.get ());
24667 }
24668
24669 /* Return the .debug_loc section to use for CU.
24670    For DWO files use .debug_loc.dwo.  */
24671
24672 static struct dwarf2_section_info *
24673 cu_debug_loc_section (struct dwarf2_cu *cu)
24674 {
24675   struct dwarf2_per_objfile *dwarf2_per_objfile
24676     = cu->per_cu->dwarf2_per_objfile;
24677
24678   if (cu->dwo_unit)
24679     {
24680       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24681
24682       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24683     }
24684   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24685                                   : &dwarf2_per_objfile->loc);
24686 }
24687
24688 /* A helper function that fills in a dwarf2_loclist_baton.  */
24689
24690 static void
24691 fill_in_loclist_baton (struct dwarf2_cu *cu,
24692                        struct dwarf2_loclist_baton *baton,
24693                        const struct attribute *attr)
24694 {
24695   struct dwarf2_per_objfile *dwarf2_per_objfile
24696     = cu->per_cu->dwarf2_per_objfile;
24697   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24698
24699   section->read (dwarf2_per_objfile->objfile);
24700
24701   baton->per_cu = cu->per_cu;
24702   gdb_assert (baton->per_cu);
24703   /* We don't know how long the location list is, but make sure we
24704      don't run off the edge of the section.  */
24705   baton->size = section->size - DW_UNSND (attr);
24706   baton->data = section->buffer + DW_UNSND (attr);
24707   baton->base_address = cu->base_address;
24708   baton->from_dwo = cu->dwo_unit != NULL;
24709 }
24710
24711 static void
24712 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24713                              struct dwarf2_cu *cu, int is_block)
24714 {
24715   struct dwarf2_per_objfile *dwarf2_per_objfile
24716     = cu->per_cu->dwarf2_per_objfile;
24717   struct objfile *objfile = dwarf2_per_objfile->objfile;
24718   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24719
24720   if (attr->form_is_section_offset ()
24721       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24722          the section.  If so, fall through to the complaint in the
24723          other branch.  */
24724       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24725     {
24726       struct dwarf2_loclist_baton *baton;
24727
24728       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24729
24730       fill_in_loclist_baton (cu, baton, attr);
24731
24732       if (cu->base_known == 0)
24733         complaint (_("Location list used without "
24734                      "specifying the CU base address."));
24735
24736       SYMBOL_ACLASS_INDEX (sym) = (is_block
24737                                    ? dwarf2_loclist_block_index
24738                                    : dwarf2_loclist_index);
24739       SYMBOL_LOCATION_BATON (sym) = baton;
24740     }
24741   else
24742     {
24743       struct dwarf2_locexpr_baton *baton;
24744
24745       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24746       baton->per_cu = cu->per_cu;
24747       gdb_assert (baton->per_cu);
24748
24749       if (attr->form_is_block ())
24750         {
24751           /* Note that we're just copying the block's data pointer
24752              here, not the actual data.  We're still pointing into the
24753              info_buffer for SYM's objfile; right now we never release
24754              that buffer, but when we do clean up properly this may
24755              need to change.  */
24756           baton->size = DW_BLOCK (attr)->size;
24757           baton->data = DW_BLOCK (attr)->data;
24758         }
24759       else
24760         {
24761           dwarf2_invalid_attrib_class_complaint ("location description",
24762                                                  sym->natural_name ());
24763           baton->size = 0;
24764         }
24765
24766       SYMBOL_ACLASS_INDEX (sym) = (is_block
24767                                    ? dwarf2_locexpr_block_index
24768                                    : dwarf2_locexpr_index);
24769       SYMBOL_LOCATION_BATON (sym) = baton;
24770     }
24771 }
24772
24773 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24774    came from a separate debuginfo file, then the master objfile is
24775    returned.  */
24776
24777 struct objfile *
24778 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24779 {
24780   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24781
24782   /* Return the master objfile, so that we can report and look up the
24783      correct file containing this variable.  */
24784   if (objfile->separate_debug_objfile_backlink)
24785     objfile = objfile->separate_debug_objfile_backlink;
24786
24787   return objfile;
24788 }
24789
24790 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24791    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24792    CU_HEADERP first.  */
24793
24794 static const struct comp_unit_head *
24795 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24796                        struct dwarf2_per_cu_data *per_cu)
24797 {
24798   const gdb_byte *info_ptr;
24799
24800   if (per_cu->cu)
24801     return &per_cu->cu->header;
24802
24803   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24804
24805   memset (cu_headerp, 0, sizeof (*cu_headerp));
24806   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24807                        rcuh_kind::COMPILE);
24808
24809   return cu_headerp;
24810 }
24811
24812 /* Return the address size given in the compilation unit header for CU.  */
24813
24814 int
24815 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24816 {
24817   struct comp_unit_head cu_header_local;
24818   const struct comp_unit_head *cu_headerp;
24819
24820   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24821
24822   return cu_headerp->addr_size;
24823 }
24824
24825 /* Return the offset size given in the compilation unit header for CU.  */
24826
24827 int
24828 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24829 {
24830   struct comp_unit_head cu_header_local;
24831   const struct comp_unit_head *cu_headerp;
24832
24833   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24834
24835   return cu_headerp->offset_size;
24836 }
24837
24838 /* See its dwarf2loc.h declaration.  */
24839
24840 int
24841 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24842 {
24843   struct comp_unit_head cu_header_local;
24844   const struct comp_unit_head *cu_headerp;
24845
24846   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24847
24848   if (cu_headerp->version == 2)
24849     return cu_headerp->addr_size;
24850   else
24851     return cu_headerp->offset_size;
24852 }
24853
24854 /* Return the text offset of the CU.  The returned offset comes from
24855    this CU's objfile.  If this objfile came from a separate debuginfo
24856    file, then the offset may be different from the corresponding
24857    offset in the parent objfile.  */
24858
24859 CORE_ADDR
24860 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24861 {
24862   return per_cu->dwarf2_per_objfile->objfile->text_section_offset ();
24863 }
24864
24865 /* Return a type that is a generic pointer type, the size of which matches
24866    the address size given in the compilation unit header for PER_CU.  */
24867 static struct type *
24868 dwarf2_per_cu_addr_type (struct dwarf2_per_cu_data *per_cu)
24869 {
24870   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24871   struct type *void_type = objfile_type (objfile)->builtin_void;
24872   struct type *addr_type = lookup_pointer_type (void_type);
24873   int addr_size = dwarf2_per_cu_addr_size (per_cu);
24874
24875   if (TYPE_LENGTH (addr_type) == addr_size)
24876     return addr_type;
24877
24878   addr_type
24879     = dwarf2_per_cu_addr_sized_int_type (per_cu, TYPE_UNSIGNED (addr_type));
24880   return addr_type;
24881 }
24882
24883 /* Return DWARF version number of PER_CU.  */
24884
24885 short
24886 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24887 {
24888   return per_cu->dwarf_version;
24889 }
24890
24891 /* Locate the .debug_info compilation unit from CU's objfile which contains
24892    the DIE at OFFSET.  Raises an error on failure.  */
24893
24894 static struct dwarf2_per_cu_data *
24895 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24896                                   unsigned int offset_in_dwz,
24897                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24898 {
24899   struct dwarf2_per_cu_data *this_cu;
24900   int low, high;
24901
24902   low = 0;
24903   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24904   while (high > low)
24905     {
24906       struct dwarf2_per_cu_data *mid_cu;
24907       int mid = low + (high - low) / 2;
24908
24909       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24910       if (mid_cu->is_dwz > offset_in_dwz
24911           || (mid_cu->is_dwz == offset_in_dwz
24912               && mid_cu->sect_off + mid_cu->length >= sect_off))
24913         high = mid;
24914       else
24915         low = mid + 1;
24916     }
24917   gdb_assert (low == high);
24918   this_cu = dwarf2_per_objfile->all_comp_units[low];
24919   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
24920     {
24921       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24922         error (_("Dwarf Error: could not find partial DIE containing "
24923                "offset %s [in module %s]"),
24924                sect_offset_str (sect_off),
24925                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24926
24927       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24928                   <= sect_off);
24929       return dwarf2_per_objfile->all_comp_units[low-1];
24930     }
24931   else
24932     {
24933       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24934           && sect_off >= this_cu->sect_off + this_cu->length)
24935         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24936       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24937       return this_cu;
24938     }
24939 }
24940
24941 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24942
24943 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24944   : per_cu (per_cu_),
24945     mark (false),
24946     has_loclist (false),
24947     checked_producer (false),
24948     producer_is_gxx_lt_4_6 (false),
24949     producer_is_gcc_lt_4_3 (false),
24950     producer_is_icc (false),
24951     producer_is_icc_lt_14 (false),
24952     producer_is_codewarrior (false),
24953     processing_has_namespace_info (false)
24954 {
24955   per_cu->cu = this;
24956 }
24957
24958 /* Destroy a dwarf2_cu.  */
24959
24960 dwarf2_cu::~dwarf2_cu ()
24961 {
24962   per_cu->cu = NULL;
24963 }
24964
24965 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24966
24967 static void
24968 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24969                        enum language pretend_language)
24970 {
24971   struct attribute *attr;
24972
24973   /* Set the language we're debugging.  */
24974   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24975   if (attr != nullptr)
24976     set_cu_language (DW_UNSND (attr), cu);
24977   else
24978     {
24979       cu->language = pretend_language;
24980       cu->language_defn = language_def (cu->language);
24981     }
24982
24983   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24984 }
24985
24986 /* Increase the age counter on each cached compilation unit, and free
24987    any that are too old.  */
24988
24989 static void
24990 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
24991 {
24992   struct dwarf2_per_cu_data *per_cu, **last_chain;
24993
24994   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24995   per_cu = dwarf2_per_objfile->read_in_chain;
24996   while (per_cu != NULL)
24997     {
24998       per_cu->cu->last_used ++;
24999       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25000         dwarf2_mark (per_cu->cu);
25001       per_cu = per_cu->cu->read_in_chain;
25002     }
25003
25004   per_cu = dwarf2_per_objfile->read_in_chain;
25005   last_chain = &dwarf2_per_objfile->read_in_chain;
25006   while (per_cu != NULL)
25007     {
25008       struct dwarf2_per_cu_data *next_cu;
25009
25010       next_cu = per_cu->cu->read_in_chain;
25011
25012       if (!per_cu->cu->mark)
25013         {
25014           delete per_cu->cu;
25015           *last_chain = next_cu;
25016         }
25017       else
25018         last_chain = &per_cu->cu->read_in_chain;
25019
25020       per_cu = next_cu;
25021     }
25022 }
25023
25024 /* Remove a single compilation unit from the cache.  */
25025
25026 static void
25027 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25028 {
25029   struct dwarf2_per_cu_data *per_cu, **last_chain;
25030   struct dwarf2_per_objfile *dwarf2_per_objfile
25031     = target_per_cu->dwarf2_per_objfile;
25032
25033   per_cu = dwarf2_per_objfile->read_in_chain;
25034   last_chain = &dwarf2_per_objfile->read_in_chain;
25035   while (per_cu != NULL)
25036     {
25037       struct dwarf2_per_cu_data *next_cu;
25038
25039       next_cu = per_cu->cu->read_in_chain;
25040
25041       if (per_cu == target_per_cu)
25042         {
25043           delete per_cu->cu;
25044           per_cu->cu = NULL;
25045           *last_chain = next_cu;
25046           break;
25047         }
25048       else
25049         last_chain = &per_cu->cu->read_in_chain;
25050
25051       per_cu = next_cu;
25052     }
25053 }
25054
25055 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25056    We store these in a hash table separate from the DIEs, and preserve them
25057    when the DIEs are flushed out of cache.
25058
25059    The CU "per_cu" pointer is needed because offset alone is not enough to
25060    uniquely identify the type.  A file may have multiple .debug_types sections,
25061    or the type may come from a DWO file.  Furthermore, while it's more logical
25062    to use per_cu->section+offset, with Fission the section with the data is in
25063    the DWO file but we don't know that section at the point we need it.
25064    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25065    because we can enter the lookup routine, get_die_type_at_offset, from
25066    outside this file, and thus won't necessarily have PER_CU->cu.
25067    Fortunately, PER_CU is stable for the life of the objfile.  */
25068
25069 struct dwarf2_per_cu_offset_and_type
25070 {
25071   const struct dwarf2_per_cu_data *per_cu;
25072   sect_offset sect_off;
25073   struct type *type;
25074 };
25075
25076 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25077
25078 static hashval_t
25079 per_cu_offset_and_type_hash (const void *item)
25080 {
25081   const struct dwarf2_per_cu_offset_and_type *ofs
25082     = (const struct dwarf2_per_cu_offset_and_type *) item;
25083
25084   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25085 }
25086
25087 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25088
25089 static int
25090 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25091 {
25092   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25093     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25094   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25095     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25096
25097   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25098           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25099 }
25100
25101 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25102    table if necessary.  For convenience, return TYPE.
25103
25104    The DIEs reading must have careful ordering to:
25105     * Not cause infinite loops trying to read in DIEs as a prerequisite for
25106       reading current DIE.
25107     * Not trying to dereference contents of still incompletely read in types
25108       while reading in other DIEs.
25109     * Enable referencing still incompletely read in types just by a pointer to
25110       the type without accessing its fields.
25111
25112    Therefore caller should follow these rules:
25113      * Try to fetch any prerequisite types we may need to build this DIE type
25114        before building the type and calling set_die_type.
25115      * After building type call set_die_type for current DIE as soon as
25116        possible before fetching more types to complete the current type.
25117      * Make the type as complete as possible before fetching more types.  */
25118
25119 static struct type *
25120 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25121 {
25122   struct dwarf2_per_objfile *dwarf2_per_objfile
25123     = cu->per_cu->dwarf2_per_objfile;
25124   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25125   struct objfile *objfile = dwarf2_per_objfile->objfile;
25126   struct attribute *attr;
25127   struct dynamic_prop prop;
25128
25129   /* For Ada types, make sure that the gnat-specific data is always
25130      initialized (if not already set).  There are a few types where
25131      we should not be doing so, because the type-specific area is
25132      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25133      where the type-specific area is used to store the floatformat).
25134      But this is not a problem, because the gnat-specific information
25135      is actually not needed for these types.  */
25136   if (need_gnat_info (cu)
25137       && TYPE_CODE (type) != TYPE_CODE_FUNC
25138       && TYPE_CODE (type) != TYPE_CODE_FLT
25139       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25140       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25141       && TYPE_CODE (type) != TYPE_CODE_METHOD
25142       && !HAVE_GNAT_AUX_INFO (type))
25143     INIT_GNAT_SPECIFIC (type);
25144
25145   /* Read DW_AT_allocated and set in type.  */
25146   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25147   if (attr != NULL && attr->form_is_block ())
25148     {
25149       struct type *prop_type
25150         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
25151       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
25152         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25153     }
25154   else if (attr != NULL)
25155     {
25156       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25157                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25158                  sect_offset_str (die->sect_off));
25159     }
25160
25161   /* Read DW_AT_associated and set in type.  */
25162   attr = dwarf2_attr (die, DW_AT_associated, cu);
25163   if (attr != NULL && attr->form_is_block ())
25164     {
25165       struct type *prop_type
25166         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
25167       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
25168         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25169     }
25170   else if (attr != NULL)
25171     {
25172       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25173                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25174                  sect_offset_str (die->sect_off));
25175     }
25176
25177   /* Read DW_AT_data_location and set in type.  */
25178   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25179   if (attr_to_dynamic_prop (attr, die, cu, &prop,
25180                             dwarf2_per_cu_addr_type (cu->per_cu)))
25181     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25182
25183   if (dwarf2_per_objfile->die_type_hash == NULL)
25184     dwarf2_per_objfile->die_type_hash
25185       = htab_up (htab_create_alloc (127,
25186                                     per_cu_offset_and_type_hash,
25187                                     per_cu_offset_and_type_eq,
25188                                     NULL, xcalloc, xfree));
25189
25190   ofs.per_cu = cu->per_cu;
25191   ofs.sect_off = die->sect_off;
25192   ofs.type = type;
25193   slot = (struct dwarf2_per_cu_offset_and_type **)
25194     htab_find_slot (dwarf2_per_objfile->die_type_hash.get (), &ofs, INSERT);
25195   if (*slot)
25196     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25197                sect_offset_str (die->sect_off));
25198   *slot = XOBNEW (&objfile->objfile_obstack,
25199                   struct dwarf2_per_cu_offset_and_type);
25200   **slot = ofs;
25201   return type;
25202 }
25203
25204 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25205    or return NULL if the die does not have a saved type.  */
25206
25207 static struct type *
25208 get_die_type_at_offset (sect_offset sect_off,
25209                         struct dwarf2_per_cu_data *per_cu)
25210 {
25211   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25212   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25213
25214   if (dwarf2_per_objfile->die_type_hash == NULL)
25215     return NULL;
25216
25217   ofs.per_cu = per_cu;
25218   ofs.sect_off = sect_off;
25219   slot = ((struct dwarf2_per_cu_offset_and_type *)
25220           htab_find (dwarf2_per_objfile->die_type_hash.get (), &ofs));
25221   if (slot)
25222     return slot->type;
25223   else
25224     return NULL;
25225 }
25226
25227 /* Look up the type for DIE in CU in die_type_hash,
25228    or return NULL if DIE does not have a saved type.  */
25229
25230 static struct type *
25231 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25232 {
25233   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25234 }
25235
25236 /* Add a dependence relationship from CU to REF_PER_CU.  */
25237
25238 static void
25239 dwarf2_add_dependence (struct dwarf2_cu *cu,
25240                        struct dwarf2_per_cu_data *ref_per_cu)
25241 {
25242   void **slot;
25243
25244   if (cu->dependencies == NULL)
25245     cu->dependencies
25246       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25247                               NULL, &cu->comp_unit_obstack,
25248                               hashtab_obstack_allocate,
25249                               dummy_obstack_deallocate);
25250
25251   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25252   if (*slot == NULL)
25253     *slot = ref_per_cu;
25254 }
25255
25256 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25257    Set the mark field in every compilation unit in the
25258    cache that we must keep because we are keeping CU.  */
25259
25260 static int
25261 dwarf2_mark_helper (void **slot, void *data)
25262 {
25263   struct dwarf2_per_cu_data *per_cu;
25264
25265   per_cu = (struct dwarf2_per_cu_data *) *slot;
25266
25267   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25268      reading of the chain.  As such dependencies remain valid it is not much
25269      useful to track and undo them during QUIT cleanups.  */
25270   if (per_cu->cu == NULL)
25271     return 1;
25272
25273   if (per_cu->cu->mark)
25274     return 1;
25275   per_cu->cu->mark = true;
25276
25277   if (per_cu->cu->dependencies != NULL)
25278     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25279
25280   return 1;
25281 }
25282
25283 /* Set the mark field in CU and in every other compilation unit in the
25284    cache that we must keep because we are keeping CU.  */
25285
25286 static void
25287 dwarf2_mark (struct dwarf2_cu *cu)
25288 {
25289   if (cu->mark)
25290     return;
25291   cu->mark = true;
25292   if (cu->dependencies != NULL)
25293     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25294 }
25295
25296 static void
25297 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25298 {
25299   while (per_cu)
25300     {
25301       per_cu->cu->mark = false;
25302       per_cu = per_cu->cu->read_in_chain;
25303     }
25304 }
25305
25306 /* Trivial hash function for partial_die_info: the hash value of a DIE
25307    is its offset in .debug_info for this objfile.  */
25308
25309 static hashval_t
25310 partial_die_hash (const void *item)
25311 {
25312   const struct partial_die_info *part_die
25313     = (const struct partial_die_info *) item;
25314
25315   return to_underlying (part_die->sect_off);
25316 }
25317
25318 /* Trivial comparison function for partial_die_info structures: two DIEs
25319    are equal if they have the same offset.  */
25320
25321 static int
25322 partial_die_eq (const void *item_lhs, const void *item_rhs)
25323 {
25324   const struct partial_die_info *part_die_lhs
25325     = (const struct partial_die_info *) item_lhs;
25326   const struct partial_die_info *part_die_rhs
25327     = (const struct partial_die_info *) item_rhs;
25328
25329   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25330 }
25331
25332 struct cmd_list_element *set_dwarf_cmdlist;
25333 struct cmd_list_element *show_dwarf_cmdlist;
25334
25335 static void
25336 set_dwarf_cmd (const char *args, int from_tty)
25337 {
25338   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25339              gdb_stdout);
25340 }
25341
25342 static void
25343 show_dwarf_cmd (const char *args, int from_tty)
25344 {
25345   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25346 }
25347
25348 bool dwarf_always_disassemble;
25349
25350 static void
25351 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25352                                struct cmd_list_element *c, const char *value)
25353 {
25354   fprintf_filtered (file,
25355                     _("Whether to always disassemble "
25356                       "DWARF expressions is %s.\n"),
25357                     value);
25358 }
25359
25360 static void
25361 show_check_physname (struct ui_file *file, int from_tty,
25362                      struct cmd_list_element *c, const char *value)
25363 {
25364   fprintf_filtered (file,
25365                     _("Whether to check \"physname\" is %s.\n"),
25366                     value);
25367 }
25368
25369 void _initialize_dwarf2_read ();
25370 void
25371 _initialize_dwarf2_read ()
25372 {
25373   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25374 Set DWARF specific variables.\n\
25375 Configure DWARF variables such as the cache size."),
25376                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25377                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25378
25379   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25380 Show DWARF specific variables.\n\
25381 Show DWARF variables such as the cache size."),
25382                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25383                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25384
25385   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25386                             &dwarf_max_cache_age, _("\
25387 Set the upper bound on the age of cached DWARF compilation units."), _("\
25388 Show the upper bound on the age of cached DWARF compilation units."), _("\
25389 A higher limit means that cached compilation units will be stored\n\
25390 in memory longer, and more total memory will be used.  Zero disables\n\
25391 caching, which can slow down startup."),
25392                             NULL,
25393                             show_dwarf_max_cache_age,
25394                             &set_dwarf_cmdlist,
25395                             &show_dwarf_cmdlist);
25396
25397   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25398                            &dwarf_always_disassemble, _("\
25399 Set whether `info address' always disassembles DWARF expressions."), _("\
25400 Show whether `info address' always disassembles DWARF expressions."), _("\
25401 When enabled, DWARF expressions are always printed in an assembly-like\n\
25402 syntax.  When disabled, expressions will be printed in a more\n\
25403 conversational style, when possible."),
25404                            NULL,
25405                            show_dwarf_always_disassemble,
25406                            &set_dwarf_cmdlist,
25407                            &show_dwarf_cmdlist);
25408
25409   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25410 Set debugging of the DWARF reader."), _("\
25411 Show debugging of the DWARF reader."), _("\
25412 When enabled (non-zero), debugging messages are printed during DWARF\n\
25413 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25414 information.  A value greater than 1 provides more verbose information."),
25415                             NULL,
25416                             NULL,
25417                             &setdebuglist, &showdebuglist);
25418
25419   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25420 Set debugging of the DWARF DIE reader."), _("\
25421 Show debugging of the DWARF DIE reader."), _("\
25422 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25423 The value is the maximum depth to print."),
25424                              NULL,
25425                              NULL,
25426                              &setdebuglist, &showdebuglist);
25427
25428   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25429 Set debugging of the dwarf line reader."), _("\
25430 Show debugging of the dwarf line reader."), _("\
25431 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25432 A value of 1 (one) provides basic information.\n\
25433 A value greater than 1 provides more verbose information."),
25434                              NULL,
25435                              NULL,
25436                              &setdebuglist, &showdebuglist);
25437
25438   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25439 Set cross-checking of \"physname\" code against demangler."), _("\
25440 Show cross-checking of \"physname\" code against demangler."), _("\
25441 When enabled, GDB's internal \"physname\" code is checked against\n\
25442 the demangler."),
25443                            NULL, show_check_physname,
25444                            &setdebuglist, &showdebuglist);
25445
25446   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25447                            no_class, &use_deprecated_index_sections, _("\
25448 Set whether to use deprecated gdb_index sections."), _("\
25449 Show whether to use deprecated gdb_index sections."), _("\
25450 When enabled, deprecated .gdb_index sections are used anyway.\n\
25451 Normally they are ignored either because of a missing feature or\n\
25452 performance issue.\n\
25453 Warning: This option must be enabled before gdb reads the file."),
25454                            NULL,
25455                            NULL,
25456                            &setlist, &showlist);
25457
25458   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25459                                                         &dwarf2_locexpr_funcs);
25460   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25461                                                         &dwarf2_loclist_funcs);
25462
25463   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25464                                         &dwarf2_block_frame_base_locexpr_funcs);
25465   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25466                                         &dwarf2_block_frame_base_loclist_funcs);
25467
25468 #if GDB_SELF_TEST
25469   selftests::register_test ("dw2_expand_symtabs_matching",
25470                             selftests::dw2_expand_symtabs_matching::run_test);
25471 #endif
25472 }
This page took 1.513007 seconds and 4 git commands to generate.