]> Git Repo - binutils.git/blob - gdb/dwarf2/read.c
Simplify setting of reading_partial_symbols
[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/comp-unit.h"
36 #include "dwarf2/index-cache.h"
37 #include "dwarf2/index-common.h"
38 #include "dwarf2/leb.h"
39 #include "dwarf2/line-header.h"
40 #include "bfd.h"
41 #include "elf-bfd.h"
42 #include "symtab.h"
43 #include "gdbtypes.h"
44 #include "objfiles.h"
45 #include "dwarf2.h"
46 #include "buildsym.h"
47 #include "demangle.h"
48 #include "gdb-demangle.h"
49 #include "filenames.h"  /* for DOSish file names */
50 #include "macrotab.h"
51 #include "language.h"
52 #include "complaints.h"
53 #include "dwarf2/expr.h"
54 #include "dwarf2/loc.h"
55 #include "cp-support.h"
56 #include "hashtab.h"
57 #include "command.h"
58 #include "gdbcmd.h"
59 #include "block.h"
60 #include "addrmap.h"
61 #include "typeprint.h"
62 #include "psympriv.h"
63 #include "c-lang.h"
64 #include "go-lang.h"
65 #include "valprint.h"
66 #include "gdbcore.h" /* for gnutarget */
67 #include "gdb/gdb-index.h"
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "build-id.h"
72 #include "namespace.h"
73 #include "gdbsupport/function-view.h"
74 #include "gdbsupport/gdb_optional.h"
75 #include "gdbsupport/underlying.h"
76 #include "gdbsupport/hash_enum.h"
77 #include "filename-seen-cache.h"
78 #include "producer.h"
79 #include <fcntl.h>
80 #include <algorithm>
81 #include <unordered_map>
82 #include "gdbsupport/selftest.h"
83 #include "rust-lang.h"
84 #include "gdbsupport/pathstuff.h"
85 #include "count-one-bits.h"
86
87 /* When == 1, print basic high level tracing messages.
88    When > 1, be more verbose.
89    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
90 static unsigned int dwarf_read_debug = 0;
91
92 /* When non-zero, dump DIEs after they are read in.  */
93 static unsigned int dwarf_die_debug = 0;
94
95 /* When non-zero, dump line number entries as they are read in.  */
96 unsigned int dwarf_line_debug = 0;
97
98 /* When true, cross-check physname against demangler.  */
99 static bool check_physname = false;
100
101 /* When true, do not reject deprecated .gdb_index sections.  */
102 static bool use_deprecated_index_sections = false;
103
104 static const struct objfile_key<dwarf2_per_objfile> dwarf2_objfile_data_key;
105
106 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
107
108 static int dwarf2_locexpr_index;
109 static int dwarf2_loclist_index;
110 static int dwarf2_locexpr_block_index;
111 static int dwarf2_loclist_block_index;
112
113 /* An index into a (C++) symbol name component in a symbol name as
114    recorded in the mapped_index's symbol table.  For each C++ symbol
115    in the symbol table, we record one entry for the start of each
116    component in the symbol in a table of name components, and then
117    sort the table, in order to be able to binary search symbol names,
118    ignoring leading namespaces, both completion and regular look up.
119    For example, for symbol "A::B::C", we'll have an entry that points
120    to "A::B::C", another that points to "B::C", and another for "C".
121    Note that function symbols in GDB index have no parameter
122    information, just the function/method names.  You can convert a
123    name_component to a "const char *" using the
124    'mapped_index::symbol_name_at(offset_type)' method.  */
125
126 struct name_component
127 {
128   /* Offset in the symbol name where the component starts.  Stored as
129      a (32-bit) offset instead of a pointer to save memory and improve
130      locality on 64-bit architectures.  */
131   offset_type name_offset;
132
133   /* The symbol's index in the symbol and constant pool tables of a
134      mapped_index.  */
135   offset_type idx;
136 };
137
138 /* Base class containing bits shared by both .gdb_index and
139    .debug_name indexes.  */
140
141 struct mapped_index_base
142 {
143   mapped_index_base () = default;
144   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
145
146   /* The name_component table (a sorted vector).  See name_component's
147      description above.  */
148   std::vector<name_component> name_components;
149
150   /* How NAME_COMPONENTS is sorted.  */
151   enum case_sensitivity name_components_casing;
152
153   /* Return the number of names in the symbol table.  */
154   virtual size_t symbol_name_count () const = 0;
155
156   /* Get the name of the symbol at IDX in the symbol table.  */
157   virtual const char *symbol_name_at (offset_type idx) const = 0;
158
159   /* Return whether the name at IDX in the symbol table should be
160      ignored.  */
161   virtual bool symbol_name_slot_invalid (offset_type idx) const
162   {
163     return false;
164   }
165
166   /* Build the symbol name component sorted vector, if we haven't
167      yet.  */
168   void build_name_components ();
169
170   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
171      possible matches for LN_NO_PARAMS in the name component
172      vector.  */
173   std::pair<std::vector<name_component>::const_iterator,
174             std::vector<name_component>::const_iterator>
175     find_name_components_bounds (const lookup_name_info &ln_no_params,
176                                  enum language lang) const;
177
178   /* Prevent deleting/destroying via a base class pointer.  */
179 protected:
180   ~mapped_index_base() = default;
181 };
182
183 /* A description of the mapped index.  The file format is described in
184    a comment by the code that writes the index.  */
185 struct mapped_index final : public mapped_index_base
186 {
187   /* A slot/bucket in the symbol table hash.  */
188   struct symbol_table_slot
189   {
190     const offset_type name;
191     const offset_type vec;
192   };
193
194   /* Index data format version.  */
195   int version = 0;
196
197   /* The address table data.  */
198   gdb::array_view<const gdb_byte> address_table;
199
200   /* The symbol table, implemented as a hash table.  */
201   gdb::array_view<symbol_table_slot> symbol_table;
202
203   /* A pointer to the constant pool.  */
204   const char *constant_pool = nullptr;
205
206   bool symbol_name_slot_invalid (offset_type idx) const override
207   {
208     const auto &bucket = this->symbol_table[idx];
209     return bucket.name == 0 && bucket.vec == 0;
210   }
211
212   /* Convenience method to get at the name of the symbol at IDX in the
213      symbol table.  */
214   const char *symbol_name_at (offset_type idx) const override
215   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
216
217   size_t symbol_name_count () const override
218   { return this->symbol_table.size (); }
219 };
220
221 /* A description of the mapped .debug_names.
222    Uninitialized map has CU_COUNT 0.  */
223 struct mapped_debug_names final : public mapped_index_base
224 {
225   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
226   : dwarf2_per_objfile (dwarf2_per_objfile_)
227   {}
228
229   struct dwarf2_per_objfile *dwarf2_per_objfile;
230   bfd_endian dwarf5_byte_order;
231   bool dwarf5_is_dwarf64;
232   bool augmentation_is_gdb;
233   uint8_t offset_size;
234   uint32_t cu_count = 0;
235   uint32_t tu_count, bucket_count, name_count;
236   const gdb_byte *cu_table_reordered, *tu_table_reordered;
237   const uint32_t *bucket_table_reordered, *hash_table_reordered;
238   const gdb_byte *name_table_string_offs_reordered;
239   const gdb_byte *name_table_entry_offs_reordered;
240   const gdb_byte *entry_pool;
241
242   struct index_val
243   {
244     ULONGEST dwarf_tag;
245     struct attr
246     {
247       /* Attribute name DW_IDX_*.  */
248       ULONGEST dw_idx;
249
250       /* Attribute form DW_FORM_*.  */
251       ULONGEST form;
252
253       /* Value if FORM is DW_FORM_implicit_const.  */
254       LONGEST implicit_const;
255     };
256     std::vector<attr> attr_vec;
257   };
258
259   std::unordered_map<ULONGEST, index_val> abbrev_map;
260
261   const char *namei_to_name (uint32_t namei) const;
262
263   /* Implementation of the mapped_index_base virtual interface, for
264      the name_components cache.  */
265
266   const char *symbol_name_at (offset_type idx) const override
267   { return namei_to_name (idx); }
268
269   size_t symbol_name_count () const override
270   { return this->name_count; }
271 };
272
273 /* See dwarf2read.h.  */
274
275 dwarf2_per_objfile *
276 get_dwarf2_per_objfile (struct objfile *objfile)
277 {
278   return dwarf2_objfile_data_key.get (objfile);
279 }
280
281 /* Default names of the debugging sections.  */
282
283 /* Note that if the debugging section has been compressed, it might
284    have a name like .zdebug_info.  */
285
286 static const struct dwarf2_debug_sections dwarf2_elf_names =
287 {
288   { ".debug_info", ".zdebug_info" },
289   { ".debug_abbrev", ".zdebug_abbrev" },
290   { ".debug_line", ".zdebug_line" },
291   { ".debug_loc", ".zdebug_loc" },
292   { ".debug_loclists", ".zdebug_loclists" },
293   { ".debug_macinfo", ".zdebug_macinfo" },
294   { ".debug_macro", ".zdebug_macro" },
295   { ".debug_str", ".zdebug_str" },
296   { ".debug_str_offsets", ".zdebug_str_offsets" },
297   { ".debug_line_str", ".zdebug_line_str" },
298   { ".debug_ranges", ".zdebug_ranges" },
299   { ".debug_rnglists", ".zdebug_rnglists" },
300   { ".debug_types", ".zdebug_types" },
301   { ".debug_addr", ".zdebug_addr" },
302   { ".debug_frame", ".zdebug_frame" },
303   { ".eh_frame", NULL },
304   { ".gdb_index", ".zgdb_index" },
305   { ".debug_names", ".zdebug_names" },
306   { ".debug_aranges", ".zdebug_aranges" },
307   23
308 };
309
310 /* List of DWO/DWP sections.  */
311
312 static const struct dwop_section_names
313 {
314   struct dwarf2_section_names abbrev_dwo;
315   struct dwarf2_section_names info_dwo;
316   struct dwarf2_section_names line_dwo;
317   struct dwarf2_section_names loc_dwo;
318   struct dwarf2_section_names loclists_dwo;
319   struct dwarf2_section_names macinfo_dwo;
320   struct dwarf2_section_names macro_dwo;
321   struct dwarf2_section_names str_dwo;
322   struct dwarf2_section_names str_offsets_dwo;
323   struct dwarf2_section_names types_dwo;
324   struct dwarf2_section_names cu_index;
325   struct dwarf2_section_names tu_index;
326 }
327 dwop_section_names =
328 {
329   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
330   { ".debug_info.dwo", ".zdebug_info.dwo" },
331   { ".debug_line.dwo", ".zdebug_line.dwo" },
332   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
333   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
334   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
335   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
336   { ".debug_str.dwo", ".zdebug_str.dwo" },
337   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
338   { ".debug_types.dwo", ".zdebug_types.dwo" },
339   { ".debug_cu_index", ".zdebug_cu_index" },
340   { ".debug_tu_index", ".zdebug_tu_index" },
341 };
342
343 /* local data types */
344
345 /* Type used for delaying computation of method physnames.
346    See comments for compute_delayed_physnames.  */
347 struct delayed_method_info
348 {
349   /* The type to which the method is attached, i.e., its parent class.  */
350   struct type *type;
351
352   /* The index of the method in the type's function fieldlists.  */
353   int fnfield_index;
354
355   /* The index of the method in the fieldlist.  */
356   int index;
357
358   /* The name of the DIE.  */
359   const char *name;
360
361   /*  The DIE associated with this method.  */
362   struct die_info *die;
363 };
364
365 /* Internal state when decoding a particular compilation unit.  */
366 struct dwarf2_cu
367 {
368   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
369   ~dwarf2_cu ();
370
371   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
372
373   /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
374      Create the set of symtabs used by this TU, or if this TU is sharing
375      symtabs with another TU and the symtabs have already been created
376      then restore those symtabs in the line header.
377      We don't need the pc/line-number mapping for type units.  */
378   void setup_type_unit_groups (struct die_info *die);
379
380   /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
381      buildsym_compunit constructor.  */
382   struct compunit_symtab *start_symtab (const char *name,
383                                         const char *comp_dir,
384                                         CORE_ADDR low_pc);
385
386   /* Reset the builder.  */
387   void reset_builder () { m_builder.reset (); }
388
389   /* The header of the compilation unit.  */
390   struct comp_unit_head header {};
391
392   /* Base address of this compilation unit.  */
393   CORE_ADDR base_address = 0;
394
395   /* Non-zero if base_address has been set.  */
396   int base_known = 0;
397
398   /* The language we are debugging.  */
399   enum language language = language_unknown;
400   const struct language_defn *language_defn = nullptr;
401
402   const char *producer = nullptr;
403
404 private:
405   /* The symtab builder for this CU.  This is only non-NULL when full
406      symbols are being read.  */
407   std::unique_ptr<buildsym_compunit> m_builder;
408
409 public:
410   /* The generic symbol table building routines have separate lists for
411      file scope symbols and all all other scopes (local scopes).  So
412      we need to select the right one to pass to add_symbol_to_list().
413      We do it by keeping a pointer to the correct list in list_in_scope.
414
415      FIXME: The original dwarf code just treated the file scope as the
416      first local scope, and all other local scopes as nested local
417      scopes, and worked fine.  Check to see if we really need to
418      distinguish these in buildsym.c.  */
419   struct pending **list_in_scope = nullptr;
420
421   /* Hash table holding all the loaded partial DIEs
422      with partial_die->offset.SECT_OFF as hash.  */
423   htab_t partial_dies = nullptr;
424
425   /* Storage for things with the same lifetime as this read-in compilation
426      unit, including partial DIEs.  */
427   auto_obstack comp_unit_obstack;
428
429   /* When multiple dwarf2_cu structures are living in memory, this field
430      chains them all together, so that they can be released efficiently.
431      We will probably also want a generation counter so that most-recently-used
432      compilation units are cached...  */
433   struct dwarf2_per_cu_data *read_in_chain = nullptr;
434
435   /* Backlink to our per_cu entry.  */
436   struct dwarf2_per_cu_data *per_cu;
437
438   /* How many compilation units ago was this CU last referenced?  */
439   int last_used = 0;
440
441   /* A hash table of DIE cu_offset for following references with
442      die_info->offset.sect_off as hash.  */
443   htab_t die_hash = nullptr;
444
445   /* Full DIEs if read in.  */
446   struct die_info *dies = nullptr;
447
448   /* A set of pointers to dwarf2_per_cu_data objects for compilation
449      units referenced by this one.  Only set during full symbol processing;
450      partial symbol tables do not have dependencies.  */
451   htab_t dependencies = nullptr;
452
453   /* Header data from the line table, during full symbol processing.  */
454   struct line_header *line_header = nullptr;
455   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
456      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
457      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
458      to the line header as long as this DIE is being processed.  See
459      process_die_scope.  */
460   die_info *line_header_die_owner = nullptr;
461
462   /* A list of methods which need to have physnames computed
463      after all type information has been read.  */
464   std::vector<delayed_method_info> method_list;
465
466   /* To be copied to symtab->call_site_htab.  */
467   htab_t call_site_htab = nullptr;
468
469   /* Non-NULL if this CU came from a DWO file.
470      There is an invariant here that is important to remember:
471      Except for attributes copied from the top level DIE in the "main"
472      (or "stub") file in preparation for reading the DWO file
473      (e.g., DW_AT_addr_base), we KISS: there is only *one* CU.
474      Either there isn't a DWO file (in which case this is NULL and the point
475      is moot), or there is and either we're not going to read it (in which
476      case this is NULL) or there is and we are reading it (in which case this
477      is non-NULL).  */
478   struct dwo_unit *dwo_unit = nullptr;
479
480   /* The DW_AT_addr_base (DW_AT_GNU_addr_base) attribute if present.
481      Note this value comes from the Fission stub CU/TU's DIE.  */
482   gdb::optional<ULONGEST> addr_base;
483
484   /* The DW_AT_rnglists_base attribute if present.
485      Note this value comes from the Fission stub CU/TU's DIE.
486      Also note that the value is zero in the non-DWO case so this value can
487      be used without needing to know whether DWO files are in use or not.
488      N.B. This does not apply to DW_AT_ranges appearing in
489      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
490      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
491      DW_AT_rnglists_base *would* have to be applied, and we'd have to care
492      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
493   ULONGEST ranges_base = 0;
494
495   /* When reading debug info generated by older versions of rustc, we
496      have to rewrite some union types to be struct types with a
497      variant part.  This rewriting must be done after the CU is fully
498      read in, because otherwise at the point of rewriting some struct
499      type might not have been fully processed.  So, we keep a list of
500      all such types here and process them after expansion.  */
501   std::vector<struct type *> rust_unions;
502
503   /* The DW_AT_str_offsets_base attribute if present.  For DWARF 4 version DWO
504      files, the value is implicitly zero.  For DWARF 5 version DWO files, the
505      value is often implicit and is the size of the header of
506      .debug_str_offsets section (8 or 4, depending on the address size).  */
507   gdb::optional<ULONGEST> str_offsets_base;
508
509   /* Mark used when releasing cached dies.  */
510   bool mark : 1;
511
512   /* This CU references .debug_loc.  See the symtab->locations_valid field.
513      This test is imperfect as there may exist optimized debug code not using
514      any location list and still facing inlining issues if handled as
515      unoptimized code.  For a future better test see GCC PR other/32998.  */
516   bool has_loclist : 1;
517
518   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is true
519      if all the producer_is_* fields are valid.  This information is cached
520      because profiling CU expansion showed excessive time spent in
521      producer_is_gxx_lt_4_6.  */
522   bool checked_producer : 1;
523   bool producer_is_gxx_lt_4_6 : 1;
524   bool producer_is_gcc_lt_4_3 : 1;
525   bool producer_is_icc : 1;
526   bool producer_is_icc_lt_14 : 1;
527   bool producer_is_codewarrior : 1;
528
529   /* When true, the file that we're processing is known to have
530      debugging info for C++ namespaces.  GCC 3.3.x did not produce
531      this information, but later versions do.  */
532
533   bool processing_has_namespace_info : 1;
534
535   struct partial_die_info *find_partial_die (sect_offset sect_off);
536
537   /* If this CU was inherited by another CU (via specification,
538      abstract_origin, etc), this is the ancestor CU.  */
539   dwarf2_cu *ancestor;
540
541   /* Get the buildsym_compunit for this CU.  */
542   buildsym_compunit *get_builder ()
543   {
544     /* If this CU has a builder associated with it, use that.  */
545     if (m_builder != nullptr)
546       return m_builder.get ();
547
548     /* Otherwise, search ancestors for a valid builder.  */
549     if (ancestor != nullptr)
550       return ancestor->get_builder ();
551
552     return nullptr;
553   }
554 };
555
556 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
557    This includes type_unit_group and quick_file_names.  */
558
559 struct stmt_list_hash
560 {
561   /* The DWO unit this table is from or NULL if there is none.  */
562   struct dwo_unit *dwo_unit;
563
564   /* Offset in .debug_line or .debug_line.dwo.  */
565   sect_offset line_sect_off;
566 };
567
568 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
569    an object of this type.  */
570
571 struct type_unit_group
572 {
573   /* dwarf2read.c's main "handle" on a TU symtab.
574      To simplify things we create an artificial CU that "includes" all the
575      type units using this stmt_list so that the rest of the code still has
576      a "per_cu" handle on the symtab.
577      This PER_CU is recognized by having no section.  */
578 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
579   struct dwarf2_per_cu_data per_cu;
580
581   /* The TUs that share this DW_AT_stmt_list entry.
582      This is added to while parsing type units to build partial symtabs,
583      and is deleted afterwards and not used again.  */
584   std::vector<signatured_type *> *tus;
585
586   /* The compunit symtab.
587      Type units in a group needn't all be defined in the same source file,
588      so we create an essentially anonymous symtab as the compunit symtab.  */
589   struct compunit_symtab *compunit_symtab;
590
591   /* The data used to construct the hash key.  */
592   struct stmt_list_hash hash;
593
594   /* The number of symtabs from the line header.
595      The value here must match line_header.num_file_names.  */
596   unsigned int num_symtabs;
597
598   /* The symbol tables for this TU (obtained from the files listed in
599      DW_AT_stmt_list).
600      WARNING: The order of entries here must match the order of entries
601      in the line header.  After the first TU using this type_unit_group, the
602      line header for the subsequent TUs is recreated from this.  This is done
603      because we need to use the same symtabs for each TU using the same
604      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
605      there's no guarantee the line header doesn't have duplicate entries.  */
606   struct symtab **symtabs;
607 };
608
609 /* These sections are what may appear in a (real or virtual) DWO file.  */
610
611 struct dwo_sections
612 {
613   struct dwarf2_section_info abbrev;
614   struct dwarf2_section_info line;
615   struct dwarf2_section_info loc;
616   struct dwarf2_section_info loclists;
617   struct dwarf2_section_info macinfo;
618   struct dwarf2_section_info macro;
619   struct dwarf2_section_info str;
620   struct dwarf2_section_info str_offsets;
621   /* In the case of a virtual DWO file, these two are unused.  */
622   struct dwarf2_section_info info;
623   std::vector<dwarf2_section_info> types;
624 };
625
626 /* CUs/TUs in DWP/DWO files.  */
627
628 struct dwo_unit
629 {
630   /* Backlink to the containing struct dwo_file.  */
631   struct dwo_file *dwo_file;
632
633   /* The "id" that distinguishes this CU/TU.
634      .debug_info calls this "dwo_id", .debug_types calls this "signature".
635      Since signatures came first, we stick with it for consistency.  */
636   ULONGEST signature;
637
638   /* The section this CU/TU lives in, in the DWO file.  */
639   struct dwarf2_section_info *section;
640
641   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
642   sect_offset sect_off;
643   unsigned int length;
644
645   /* For types, offset in the type's DIE of the type defined by this TU.  */
646   cu_offset type_offset_in_tu;
647 };
648
649 /* include/dwarf2.h defines the DWP section codes.
650    It defines a max value but it doesn't define a min value, which we
651    use for error checking, so provide one.  */
652
653 enum dwp_v2_section_ids
654 {
655   DW_SECT_MIN = 1
656 };
657
658 /* Data for one DWO file.
659
660    This includes virtual DWO files (a virtual DWO file is a DWO file as it
661    appears in a DWP file).  DWP files don't really have DWO files per se -
662    comdat folding of types "loses" the DWO file they came from, and from
663    a high level view DWP files appear to contain a mass of random types.
664    However, to maintain consistency with the non-DWP case we pretend DWP
665    files contain virtual DWO files, and we assign each TU with one virtual
666    DWO file (generally based on the line and abbrev section offsets -
667    a heuristic that seems to work in practice).  */
668
669 struct dwo_file
670 {
671   dwo_file () = default;
672   DISABLE_COPY_AND_ASSIGN (dwo_file);
673
674   /* The DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.
675      For virtual DWO files the name is constructed from the section offsets
676      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
677      from related CU+TUs.  */
678   const char *dwo_name = nullptr;
679
680   /* The DW_AT_comp_dir attribute.  */
681   const char *comp_dir = nullptr;
682
683   /* The bfd, when the file is open.  Otherwise this is NULL.
684      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
685   gdb_bfd_ref_ptr dbfd;
686
687   /* The sections that make up this DWO file.
688      Remember that for virtual DWO files in DWP V2, these are virtual
689      sections (for lack of a better name).  */
690   struct dwo_sections sections {};
691
692   /* The CUs in the file.
693      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
694      an extension to handle LLVM's Link Time Optimization output (where
695      multiple source files may be compiled into a single object/dwo pair). */
696   htab_up cus;
697
698   /* Table of TUs in the file.
699      Each element is a struct dwo_unit.  */
700   htab_up tus;
701 };
702
703 /* These sections are what may appear in a DWP file.  */
704
705 struct dwp_sections
706 {
707   /* These are used by both DWP version 1 and 2.  */
708   struct dwarf2_section_info str;
709   struct dwarf2_section_info cu_index;
710   struct dwarf2_section_info tu_index;
711
712   /* These are only used by DWP version 2 files.
713      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
714      sections are referenced by section number, and are not recorded here.
715      In DWP version 2 there is at most one copy of all these sections, each
716      section being (effectively) comprised of the concatenation of all of the
717      individual sections that exist in the version 1 format.
718      To keep the code simple we treat each of these concatenated pieces as a
719      section itself (a virtual section?).  */
720   struct dwarf2_section_info abbrev;
721   struct dwarf2_section_info info;
722   struct dwarf2_section_info line;
723   struct dwarf2_section_info loc;
724   struct dwarf2_section_info macinfo;
725   struct dwarf2_section_info macro;
726   struct dwarf2_section_info str_offsets;
727   struct dwarf2_section_info types;
728 };
729
730 /* These sections are what may appear in a virtual DWO file in DWP version 1.
731    A virtual DWO file is a DWO file as it appears in a DWP file.  */
732
733 struct virtual_v1_dwo_sections
734 {
735   struct dwarf2_section_info abbrev;
736   struct dwarf2_section_info line;
737   struct dwarf2_section_info loc;
738   struct dwarf2_section_info macinfo;
739   struct dwarf2_section_info macro;
740   struct dwarf2_section_info str_offsets;
741   /* Each DWP hash table entry records one CU or one TU.
742      That is recorded here, and copied to dwo_unit.section.  */
743   struct dwarf2_section_info info_or_types;
744 };
745
746 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
747    In version 2, the sections of the DWO files are concatenated together
748    and stored in one section of that name.  Thus each ELF section contains
749    several "virtual" sections.  */
750
751 struct virtual_v2_dwo_sections
752 {
753   bfd_size_type abbrev_offset;
754   bfd_size_type abbrev_size;
755
756   bfd_size_type line_offset;
757   bfd_size_type line_size;
758
759   bfd_size_type loc_offset;
760   bfd_size_type loc_size;
761
762   bfd_size_type macinfo_offset;
763   bfd_size_type macinfo_size;
764
765   bfd_size_type macro_offset;
766   bfd_size_type macro_size;
767
768   bfd_size_type str_offsets_offset;
769   bfd_size_type str_offsets_size;
770
771   /* Each DWP hash table entry records one CU or one TU.
772      That is recorded here, and copied to dwo_unit.section.  */
773   bfd_size_type info_or_types_offset;
774   bfd_size_type info_or_types_size;
775 };
776
777 /* Contents of DWP hash tables.  */
778
779 struct dwp_hash_table
780 {
781   uint32_t version, nr_columns;
782   uint32_t nr_units, nr_slots;
783   const gdb_byte *hash_table, *unit_table;
784   union
785   {
786     struct
787     {
788       const gdb_byte *indices;
789     } v1;
790     struct
791     {
792       /* This is indexed by column number and gives the id of the section
793          in that column.  */
794 #define MAX_NR_V2_DWO_SECTIONS \
795   (1 /* .debug_info or .debug_types */ \
796    + 1 /* .debug_abbrev */ \
797    + 1 /* .debug_line */ \
798    + 1 /* .debug_loc */ \
799    + 1 /* .debug_str_offsets */ \
800    + 1 /* .debug_macro or .debug_macinfo */)
801       int section_ids[MAX_NR_V2_DWO_SECTIONS];
802       const gdb_byte *offsets;
803       const gdb_byte *sizes;
804     } v2;
805   } section_pool;
806 };
807
808 /* Data for one DWP file.  */
809
810 struct dwp_file
811 {
812   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
813     : name (name_),
814       dbfd (std::move (abfd))
815   {
816   }
817
818   /* Name of the file.  */
819   const char *name;
820
821   /* File format version.  */
822   int version = 0;
823
824   /* The bfd.  */
825   gdb_bfd_ref_ptr dbfd;
826
827   /* Section info for this file.  */
828   struct dwp_sections sections {};
829
830   /* Table of CUs in the file.  */
831   const struct dwp_hash_table *cus = nullptr;
832
833   /* Table of TUs in the file.  */
834   const struct dwp_hash_table *tus = nullptr;
835
836   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
837   htab_up loaded_cus;
838   htab_up loaded_tus;
839
840   /* Table to map ELF section numbers to their sections.
841      This is only needed for the DWP V1 file format.  */
842   unsigned int num_sections = 0;
843   asection **elf_sections = nullptr;
844 };
845
846 /* Struct used to pass misc. parameters to read_die_and_children, et
847    al.  which are used for both .debug_info and .debug_types dies.
848    All parameters here are unchanging for the life of the call.  This
849    struct exists to abstract away the constant parameters of die reading.  */
850
851 struct die_reader_specs
852 {
853   /* The bfd of die_section.  */
854   bfd* abfd;
855
856   /* The CU of the DIE we are parsing.  */
857   struct dwarf2_cu *cu;
858
859   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
860   struct dwo_file *dwo_file;
861
862   /* The section the die comes from.
863      This is either .debug_info or .debug_types, or the .dwo variants.  */
864   struct dwarf2_section_info *die_section;
865
866   /* die_section->buffer.  */
867   const gdb_byte *buffer;
868
869   /* The end of the buffer.  */
870   const gdb_byte *buffer_end;
871
872   /* The abbreviation table to use when reading the DIEs.  */
873   struct abbrev_table *abbrev_table;
874 };
875
876 /* A subclass of die_reader_specs that holds storage and has complex
877    constructor and destructor behavior.  */
878
879 class cutu_reader : public die_reader_specs
880 {
881 public:
882
883   cutu_reader (struct dwarf2_per_cu_data *this_cu,
884                struct abbrev_table *abbrev_table,
885                int use_existing_cu,
886                bool skip_partial);
887
888   explicit cutu_reader (struct dwarf2_per_cu_data *this_cu,
889                         struct dwarf2_cu *parent_cu = nullptr,
890                         struct dwo_file *dwo_file = nullptr);
891
892   DISABLE_COPY_AND_ASSIGN (cutu_reader);
893
894   const gdb_byte *info_ptr = nullptr;
895   struct die_info *comp_unit_die = nullptr;
896   bool dummy_p = false;
897
898   /* Release the new CU, putting it on the chain.  This cannot be done
899      for dummy CUs.  */
900   void keep ();
901
902 private:
903   void init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
904                                   int use_existing_cu);
905
906   struct dwarf2_per_cu_data *m_this_cu;
907   std::unique_ptr<dwarf2_cu> m_new_cu;
908
909   /* The ordinary abbreviation table.  */
910   abbrev_table_up m_abbrev_table_holder;
911
912   /* The DWO abbreviation table.  */
913   abbrev_table_up m_dwo_abbrev_table;
914 };
915
916 /* When we construct a partial symbol table entry we only
917    need this much information.  */
918 struct partial_die_info : public allocate_on_obstack
919   {
920     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
921
922     /* Disable assign but still keep copy ctor, which is needed
923        load_partial_dies.   */
924     partial_die_info& operator=(const partial_die_info& rhs) = delete;
925
926     /* Adjust the partial die before generating a symbol for it.  This
927        function may set the is_external flag or change the DIE's
928        name.  */
929     void fixup (struct dwarf2_cu *cu);
930
931     /* Read a minimal amount of information into the minimal die
932        structure.  */
933     const gdb_byte *read (const struct die_reader_specs *reader,
934                           const struct abbrev_info &abbrev,
935                           const gdb_byte *info_ptr);
936
937     /* Offset of this DIE.  */
938     const sect_offset sect_off;
939
940     /* DWARF-2 tag for this DIE.  */
941     const ENUM_BITFIELD(dwarf_tag) tag : 16;
942
943     /* Assorted flags describing the data found in this DIE.  */
944     const unsigned int has_children : 1;
945
946     unsigned int is_external : 1;
947     unsigned int is_declaration : 1;
948     unsigned int has_type : 1;
949     unsigned int has_specification : 1;
950     unsigned int has_pc_info : 1;
951     unsigned int may_be_inlined : 1;
952
953     /* This DIE has been marked DW_AT_main_subprogram.  */
954     unsigned int main_subprogram : 1;
955
956     /* Flag set if the SCOPE field of this structure has been
957        computed.  */
958     unsigned int scope_set : 1;
959
960     /* Flag set if the DIE has a byte_size attribute.  */
961     unsigned int has_byte_size : 1;
962
963     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
964     unsigned int has_const_value : 1;
965
966     /* Flag set if any of the DIE's children are template arguments.  */
967     unsigned int has_template_arguments : 1;
968
969     /* Flag set if fixup has been called on this die.  */
970     unsigned int fixup_called : 1;
971
972     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
973     unsigned int is_dwz : 1;
974
975     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
976     unsigned int spec_is_dwz : 1;
977
978     /* The name of this DIE.  Normally the value of DW_AT_name, but
979        sometimes a default name for unnamed DIEs.  */
980     const char *name = nullptr;
981
982     /* The linkage name, if present.  */
983     const char *linkage_name = nullptr;
984
985     /* The scope to prepend to our children.  This is generally
986        allocated on the comp_unit_obstack, so will disappear
987        when this compilation unit leaves the cache.  */
988     const char *scope = nullptr;
989
990     /* Some data associated with the partial DIE.  The tag determines
991        which field is live.  */
992     union
993     {
994       /* The location description associated with this DIE, if any.  */
995       struct dwarf_block *locdesc;
996       /* The offset of an import, for DW_TAG_imported_unit.  */
997       sect_offset sect_off;
998     } d {};
999
1000     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1001     CORE_ADDR lowpc = 0;
1002     CORE_ADDR highpc = 0;
1003
1004     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1005        DW_AT_sibling, if any.  */
1006     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1007        could return DW_AT_sibling values to its caller load_partial_dies.  */
1008     const gdb_byte *sibling = nullptr;
1009
1010     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1011        DW_AT_specification (or DW_AT_abstract_origin or
1012        DW_AT_extension).  */
1013     sect_offset spec_offset {};
1014
1015     /* Pointers to this DIE's parent, first child, and next sibling,
1016        if any.  */
1017     struct partial_die_info *die_parent = nullptr;
1018     struct partial_die_info *die_child = nullptr;
1019     struct partial_die_info *die_sibling = nullptr;
1020
1021     friend struct partial_die_info *
1022     dwarf2_cu::find_partial_die (sect_offset sect_off);
1023
1024   private:
1025     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1026     partial_die_info (sect_offset sect_off)
1027       : partial_die_info (sect_off, DW_TAG_padding, 0)
1028     {
1029     }
1030
1031     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1032                       int has_children_)
1033       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1034     {
1035       is_external = 0;
1036       is_declaration = 0;
1037       has_type = 0;
1038       has_specification = 0;
1039       has_pc_info = 0;
1040       may_be_inlined = 0;
1041       main_subprogram = 0;
1042       scope_set = 0;
1043       has_byte_size = 0;
1044       has_const_value = 0;
1045       has_template_arguments = 0;
1046       fixup_called = 0;
1047       is_dwz = 0;
1048       spec_is_dwz = 0;
1049     }
1050   };
1051
1052 /* This data structure holds a complete die structure.  */
1053 struct die_info
1054   {
1055     /* DWARF-2 tag for this DIE.  */
1056     ENUM_BITFIELD(dwarf_tag) tag : 16;
1057
1058     /* Number of attributes */
1059     unsigned char num_attrs;
1060
1061     /* True if we're presently building the full type name for the
1062        type derived from this DIE.  */
1063     unsigned char building_fullname : 1;
1064
1065     /* True if this die is in process.  PR 16581.  */
1066     unsigned char in_process : 1;
1067
1068     /* True if this DIE has children.  */
1069     unsigned char has_children : 1;
1070
1071     /* Abbrev number */
1072     unsigned int abbrev;
1073
1074     /* Offset in .debug_info or .debug_types section.  */
1075     sect_offset sect_off;
1076
1077     /* The dies in a compilation unit form an n-ary tree.  PARENT
1078        points to this die's parent; CHILD points to the first child of
1079        this node; and all the children of a given node are chained
1080        together via their SIBLING fields.  */
1081     struct die_info *child;     /* Its first child, if any.  */
1082     struct die_info *sibling;   /* Its next sibling, if any.  */
1083     struct die_info *parent;    /* Its parent, if any.  */
1084
1085     /* An array of attributes, with NUM_ATTRS elements.  There may be
1086        zero, but it's not common and zero-sized arrays are not
1087        sufficiently portable C.  */
1088     struct attribute attrs[1];
1089   };
1090
1091 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1092    but this would require a corresponding change in unpack_field_as_long
1093    and friends.  */
1094 static int bits_per_byte = 8;
1095
1096 /* When reading a variant or variant part, we track a bit more
1097    information about the field, and store it in an object of this
1098    type.  */
1099
1100 struct variant_field
1101 {
1102   /* If we see a DW_TAG_variant, then this will be the discriminant
1103      value.  */
1104   ULONGEST discriminant_value;
1105   /* If we see a DW_TAG_variant, then this will be set if this is the
1106      default branch.  */
1107   bool default_branch;
1108   /* While reading a DW_TAG_variant_part, this will be set if this
1109      field is the discriminant.  */
1110   bool is_discriminant;
1111 };
1112
1113 struct nextfield
1114 {
1115   int accessibility = 0;
1116   int virtuality = 0;
1117   /* Extra information to describe a variant or variant part.  */
1118   struct variant_field variant {};
1119   struct field field {};
1120 };
1121
1122 struct fnfieldlist
1123 {
1124   const char *name = nullptr;
1125   std::vector<struct fn_field> fnfields;
1126 };
1127
1128 /* The routines that read and process dies for a C struct or C++ class
1129    pass lists of data member fields and lists of member function fields
1130    in an instance of a field_info structure, as defined below.  */
1131 struct field_info
1132   {
1133     /* List of data member and baseclasses fields.  */
1134     std::vector<struct nextfield> fields;
1135     std::vector<struct nextfield> baseclasses;
1136
1137     /* Number of fields (including baseclasses).  */
1138     int nfields = 0;
1139
1140     /* Set if the accessibility of one of the fields is not public.  */
1141     int non_public_fields = 0;
1142
1143     /* Member function fieldlist array, contains name of possibly overloaded
1144        member function, number of overloaded member functions and a pointer
1145        to the head of the member function field chain.  */
1146     std::vector<struct fnfieldlist> fnfieldlists;
1147
1148     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1149        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1150     std::vector<struct decl_field> typedef_field_list;
1151
1152     /* Nested types defined by this class and the number of elements in this
1153        list.  */
1154     std::vector<struct decl_field> nested_types_list;
1155   };
1156
1157 /* Loaded secondary compilation units are kept in memory until they
1158    have not been referenced for the processing of this many
1159    compilation units.  Set this to zero to disable caching.  Cache
1160    sizes of up to at least twenty will improve startup time for
1161    typical inter-CU-reference binaries, at an obvious memory cost.  */
1162 static int dwarf_max_cache_age = 5;
1163 static void
1164 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1165                           struct cmd_list_element *c, const char *value)
1166 {
1167   fprintf_filtered (file, _("The upper bound on the age of cached "
1168                             "DWARF compilation units is %s.\n"),
1169                     value);
1170 }
1171 \f
1172 /* local function prototypes */
1173
1174 static void dwarf2_find_base_address (struct die_info *die,
1175                                       struct dwarf2_cu *cu);
1176
1177 static dwarf2_psymtab *create_partial_symtab
1178   (struct dwarf2_per_cu_data *per_cu, const char *name);
1179
1180 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1181                                         const gdb_byte *info_ptr,
1182                                         struct die_info *type_unit_die);
1183
1184 static void dwarf2_build_psymtabs_hard
1185   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1186
1187 static void scan_partial_symbols (struct partial_die_info *,
1188                                   CORE_ADDR *, CORE_ADDR *,
1189                                   int, struct dwarf2_cu *);
1190
1191 static void add_partial_symbol (struct partial_die_info *,
1192                                 struct dwarf2_cu *);
1193
1194 static void add_partial_namespace (struct partial_die_info *pdi,
1195                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1196                                    int set_addrmap, struct dwarf2_cu *cu);
1197
1198 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1199                                 CORE_ADDR *highpc, int set_addrmap,
1200                                 struct dwarf2_cu *cu);
1201
1202 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1203                                      struct dwarf2_cu *cu);
1204
1205 static void add_partial_subprogram (struct partial_die_info *pdi,
1206                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1207                                     int need_pc, struct dwarf2_cu *cu);
1208
1209 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1210
1211 static struct partial_die_info *load_partial_dies
1212   (const struct die_reader_specs *, const gdb_byte *, int);
1213
1214 /* A pair of partial_die_info and compilation unit.  */
1215 struct cu_partial_die_info
1216 {
1217   /* The compilation unit of the partial_die_info.  */
1218   struct dwarf2_cu *cu;
1219   /* A partial_die_info.  */
1220   struct partial_die_info *pdi;
1221
1222   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1223     : cu (cu),
1224       pdi (pdi)
1225   { /* Nothing.  */ }
1226
1227 private:
1228   cu_partial_die_info () = delete;
1229 };
1230
1231 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1232                                                           struct dwarf2_cu *);
1233
1234 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1235                                        struct attribute *, struct attr_abbrev *,
1236                                        const gdb_byte *, bool *need_reprocess);
1237
1238 static void read_attribute_reprocess (const struct die_reader_specs *reader,
1239                                       struct attribute *attr);
1240
1241 static CORE_ADDR read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index);
1242
1243 static LONGEST read_checked_initial_length_and_offset
1244   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1245    unsigned int *, unsigned int *);
1246
1247 static sect_offset read_abbrev_offset
1248   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1249    struct dwarf2_section_info *, sect_offset);
1250
1251 static const char *read_indirect_string
1252   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1253    const struct comp_unit_head *, unsigned int *);
1254
1255 static const char *read_indirect_line_string
1256   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1257    const struct comp_unit_head *, unsigned int *);
1258
1259 static const char *read_indirect_string_at_offset
1260   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1261    LONGEST str_offset);
1262
1263 static const char *read_indirect_string_from_dwz
1264   (struct objfile *objfile, struct dwz_file *, LONGEST);
1265
1266 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1267                                               const gdb_byte *,
1268                                               unsigned int *);
1269
1270 static const char *read_dwo_str_index (const struct die_reader_specs *reader,
1271                                        ULONGEST str_index);
1272
1273 static const char *read_stub_str_index (struct dwarf2_cu *cu,
1274                                         ULONGEST str_index);
1275
1276 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1277
1278 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1279                                       struct dwarf2_cu *);
1280
1281 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1282                                                 unsigned int);
1283
1284 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1285                                        struct dwarf2_cu *cu);
1286
1287 static const char *dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu);
1288
1289 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1290                                struct dwarf2_cu *cu);
1291
1292 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1293
1294 static struct die_info *die_specification (struct die_info *die,
1295                                            struct dwarf2_cu **);
1296
1297 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1298                                                 struct dwarf2_cu *cu);
1299
1300 static void dwarf_decode_lines (struct line_header *, const char *,
1301                                 struct dwarf2_cu *, dwarf2_psymtab *,
1302                                 CORE_ADDR, int decode_mapping);
1303
1304 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1305                                   const char *);
1306
1307 static struct symbol *new_symbol (struct die_info *, struct type *,
1308                                   struct dwarf2_cu *, struct symbol * = NULL);
1309
1310 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1311                                 struct dwarf2_cu *);
1312
1313 static void dwarf2_const_value_attr (const struct attribute *attr,
1314                                      struct type *type,
1315                                      const char *name,
1316                                      struct obstack *obstack,
1317                                      struct dwarf2_cu *cu, LONGEST *value,
1318                                      const gdb_byte **bytes,
1319                                      struct dwarf2_locexpr_baton **baton);
1320
1321 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1322
1323 static int need_gnat_info (struct dwarf2_cu *);
1324
1325 static struct type *die_descriptive_type (struct die_info *,
1326                                           struct dwarf2_cu *);
1327
1328 static void set_descriptive_type (struct type *, struct die_info *,
1329                                   struct dwarf2_cu *);
1330
1331 static struct type *die_containing_type (struct die_info *,
1332                                          struct dwarf2_cu *);
1333
1334 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1335                                      struct dwarf2_cu *);
1336
1337 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1338
1339 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1340
1341 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1342
1343 static char *typename_concat (struct obstack *obs, const char *prefix,
1344                               const char *suffix, int physname,
1345                               struct dwarf2_cu *cu);
1346
1347 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1348
1349 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1350
1351 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1352
1353 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1354
1355 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1356
1357 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1358
1359 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1360                                struct dwarf2_cu *, dwarf2_psymtab *);
1361
1362 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1363    values.  Keep the items ordered with increasing constraints compliance.  */
1364 enum pc_bounds_kind
1365 {
1366   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1367   PC_BOUNDS_NOT_PRESENT,
1368
1369   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1370      were present but they do not form a valid range of PC addresses.  */
1371   PC_BOUNDS_INVALID,
1372
1373   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1374   PC_BOUNDS_RANGES,
1375
1376   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1377   PC_BOUNDS_HIGH_LOW,
1378 };
1379
1380 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1381                                                  CORE_ADDR *, CORE_ADDR *,
1382                                                  struct dwarf2_cu *,
1383                                                  dwarf2_psymtab *);
1384
1385 static void get_scope_pc_bounds (struct die_info *,
1386                                  CORE_ADDR *, CORE_ADDR *,
1387                                  struct dwarf2_cu *);
1388
1389 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1390                                         CORE_ADDR, struct dwarf2_cu *);
1391
1392 static void dwarf2_add_field (struct field_info *, struct die_info *,
1393                               struct dwarf2_cu *);
1394
1395 static void dwarf2_attach_fields_to_type (struct field_info *,
1396                                           struct type *, struct dwarf2_cu *);
1397
1398 static void dwarf2_add_member_fn (struct field_info *,
1399                                   struct die_info *, struct type *,
1400                                   struct dwarf2_cu *);
1401
1402 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1403                                              struct type *,
1404                                              struct dwarf2_cu *);
1405
1406 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1407
1408 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1409
1410 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1411
1412 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1413
1414 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1415
1416 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1417
1418 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1419
1420 static struct type *read_module_type (struct die_info *die,
1421                                       struct dwarf2_cu *cu);
1422
1423 static const char *namespace_name (struct die_info *die,
1424                                    int *is_anonymous, struct dwarf2_cu *);
1425
1426 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1427
1428 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1429
1430 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1431                                                        struct dwarf2_cu *);
1432
1433 static struct die_info *read_die_and_siblings_1
1434   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1435    struct die_info *);
1436
1437 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1438                                                const gdb_byte *info_ptr,
1439                                                const gdb_byte **new_info_ptr,
1440                                                struct die_info *parent);
1441
1442 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1443                                         struct die_info **, const gdb_byte *,
1444                                         int);
1445
1446 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1447                                       struct die_info **, const gdb_byte *);
1448
1449 static void process_die (struct die_info *, struct dwarf2_cu *);
1450
1451 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1452                                              struct obstack *);
1453
1454 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1455
1456 static const char *dwarf2_full_name (const char *name,
1457                                      struct die_info *die,
1458                                      struct dwarf2_cu *cu);
1459
1460 static const char *dwarf2_physname (const char *name, struct die_info *die,
1461                                     struct dwarf2_cu *cu);
1462
1463 static struct die_info *dwarf2_extension (struct die_info *die,
1464                                           struct dwarf2_cu **);
1465
1466 static const char *dwarf_tag_name (unsigned int);
1467
1468 static const char *dwarf_attr_name (unsigned int);
1469
1470 static const char *dwarf_form_name (unsigned int);
1471
1472 static const char *dwarf_bool_name (unsigned int);
1473
1474 static const char *dwarf_type_encoding_name (unsigned int);
1475
1476 static struct die_info *sibling_die (struct die_info *);
1477
1478 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1479
1480 static void dump_die_for_error (struct die_info *);
1481
1482 static void dump_die_1 (struct ui_file *, int level, int max_level,
1483                         struct die_info *);
1484
1485 /*static*/ void dump_die (struct die_info *, int max_level);
1486
1487 static void store_in_ref_table (struct die_info *,
1488                                 struct dwarf2_cu *);
1489
1490 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1491
1492 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1493
1494 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1495                                                const struct attribute *,
1496                                                struct dwarf2_cu **);
1497
1498 static struct die_info *follow_die_ref (struct die_info *,
1499                                         const struct attribute *,
1500                                         struct dwarf2_cu **);
1501
1502 static struct die_info *follow_die_sig (struct die_info *,
1503                                         const struct attribute *,
1504                                         struct dwarf2_cu **);
1505
1506 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1507                                          struct dwarf2_cu *);
1508
1509 static struct type *get_DW_AT_signature_type (struct die_info *,
1510                                               const struct attribute *,
1511                                               struct dwarf2_cu *);
1512
1513 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1514
1515 static void read_signatured_type (struct signatured_type *);
1516
1517 static int attr_to_dynamic_prop (const struct attribute *attr,
1518                                  struct die_info *die, struct dwarf2_cu *cu,
1519                                  struct dynamic_prop *prop, struct type *type);
1520
1521 /* memory allocation interface */
1522
1523 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1524
1525 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1526
1527 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1528
1529 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1530                                    struct dwarf2_loclist_baton *baton,
1531                                    const struct attribute *attr);
1532
1533 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1534                                          struct symbol *sym,
1535                                          struct dwarf2_cu *cu,
1536                                          int is_block);
1537
1538 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1539                                      const gdb_byte *info_ptr,
1540                                      struct abbrev_info *abbrev);
1541
1542 static hashval_t partial_die_hash (const void *item);
1543
1544 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1545
1546 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1547   (sect_offset sect_off, unsigned int offset_in_dwz,
1548    struct dwarf2_per_objfile *dwarf2_per_objfile);
1549
1550 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1551                                    struct die_info *comp_unit_die,
1552                                    enum language pretend_language);
1553
1554 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1555
1556 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1557
1558 static struct type *set_die_type (struct die_info *, struct type *,
1559                                   struct dwarf2_cu *);
1560
1561 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1562
1563 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1564
1565 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1566                                  enum language);
1567
1568 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1569                                     enum language);
1570
1571 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1572                                     enum language);
1573
1574 static void dwarf2_add_dependence (struct dwarf2_cu *,
1575                                    struct dwarf2_per_cu_data *);
1576
1577 static void dwarf2_mark (struct dwarf2_cu *);
1578
1579 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1580
1581 static struct type *get_die_type_at_offset (sect_offset,
1582                                             struct dwarf2_per_cu_data *);
1583
1584 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1585
1586 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1587                              enum language pretend_language);
1588
1589 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1590
1591 /* Class, the destructor of which frees all allocated queue entries.  This
1592    will only have work to do if an error was thrown while processing the
1593    dwarf.  If no error was thrown then the queue entries should have all
1594    been processed, and freed, as we went along.  */
1595
1596 class dwarf2_queue_guard
1597 {
1598 public:
1599   explicit dwarf2_queue_guard (dwarf2_per_objfile *per_objfile)
1600     : m_per_objfile (per_objfile)
1601   {
1602   }
1603
1604   /* Free any entries remaining on the queue.  There should only be
1605      entries left if we hit an error while processing the dwarf.  */
1606   ~dwarf2_queue_guard ()
1607   {
1608     /* Ensure that no memory is allocated by the queue.  */
1609     std::queue<dwarf2_queue_item> empty;
1610     std::swap (m_per_objfile->queue, empty);
1611   }
1612
1613   DISABLE_COPY_AND_ASSIGN (dwarf2_queue_guard);
1614
1615 private:
1616   dwarf2_per_objfile *m_per_objfile;
1617 };
1618
1619 dwarf2_queue_item::~dwarf2_queue_item ()
1620 {
1621   /* Anything still marked queued is likely to be in an
1622      inconsistent state, so discard it.  */
1623   if (per_cu->queued)
1624     {
1625       if (per_cu->cu != NULL)
1626         free_one_cached_comp_unit (per_cu);
1627       per_cu->queued = 0;
1628     }
1629 }
1630
1631 /* The return type of find_file_and_directory.  Note, the enclosed
1632    string pointers are only valid while this object is valid.  */
1633
1634 struct file_and_directory
1635 {
1636   /* The filename.  This is never NULL.  */
1637   const char *name;
1638
1639   /* The compilation directory.  NULL if not known.  If we needed to
1640      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1641      points directly to the DW_AT_comp_dir string attribute owned by
1642      the obstack that owns the DIE.  */
1643   const char *comp_dir;
1644
1645   /* If we needed to build a new string for comp_dir, this is what
1646      owns the storage.  */
1647   std::string comp_dir_storage;
1648 };
1649
1650 static file_and_directory find_file_and_directory (struct die_info *die,
1651                                                    struct dwarf2_cu *cu);
1652
1653 static htab_up allocate_signatured_type_table ();
1654
1655 static htab_up allocate_dwo_unit_table ();
1656
1657 static struct dwo_unit *lookup_dwo_unit_in_dwp
1658   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1659    struct dwp_file *dwp_file, const char *comp_dir,
1660    ULONGEST signature, int is_debug_types);
1661
1662 static struct dwp_file *get_dwp_file
1663   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1664
1665 static struct dwo_unit *lookup_dwo_comp_unit
1666   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1667
1668 static struct dwo_unit *lookup_dwo_type_unit
1669   (struct signatured_type *, const char *, const char *);
1670
1671 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1672
1673 /* A unique pointer to a dwo_file.  */
1674
1675 typedef std::unique_ptr<struct dwo_file> dwo_file_up;
1676
1677 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1678
1679 static void check_producer (struct dwarf2_cu *cu);
1680
1681 static void free_line_header_voidp (void *arg);
1682 \f
1683 /* Various complaints about symbol reading that don't abort the process.  */
1684
1685 static void
1686 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1687 {
1688   complaint (_("statement list doesn't fit in .debug_line section"));
1689 }
1690
1691 static void
1692 dwarf2_debug_line_missing_file_complaint (void)
1693 {
1694   complaint (_(".debug_line section has line data without a file"));
1695 }
1696
1697 static void
1698 dwarf2_debug_line_missing_end_sequence_complaint (void)
1699 {
1700   complaint (_(".debug_line section has line "
1701                "program sequence without an end"));
1702 }
1703
1704 static void
1705 dwarf2_complex_location_expr_complaint (void)
1706 {
1707   complaint (_("location expression too complex"));
1708 }
1709
1710 static void
1711 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1712                                               int arg3)
1713 {
1714   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
1715              arg1, arg2, arg3);
1716 }
1717
1718 static void
1719 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1720 {
1721   complaint (_("debug info runs off end of %s section"
1722                " [in module %s]"),
1723              section->get_name (),
1724              section->get_file_name ());
1725 }
1726
1727 static void
1728 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1729 {
1730   complaint (_("macro debug info contains a "
1731                "malformed macro definition:\n`%s'"),
1732              arg1);
1733 }
1734
1735 static void
1736 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1737 {
1738   complaint (_("invalid attribute class or form for '%s' in '%s'"),
1739              arg1, arg2);
1740 }
1741
1742 /* Hash function for line_header_hash.  */
1743
1744 static hashval_t
1745 line_header_hash (const struct line_header *ofs)
1746 {
1747   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
1748 }
1749
1750 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
1751
1752 static hashval_t
1753 line_header_hash_voidp (const void *item)
1754 {
1755   const struct line_header *ofs = (const struct line_header *) item;
1756
1757   return line_header_hash (ofs);
1758 }
1759
1760 /* Equality function for line_header_hash.  */
1761
1762 static int
1763 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
1764 {
1765   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
1766   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
1767
1768   return (ofs_lhs->sect_off == ofs_rhs->sect_off
1769           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
1770 }
1771
1772 \f
1773
1774 /* See declaration.  */
1775
1776 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
1777                                         const dwarf2_debug_sections *names,
1778                                         bool can_copy_)
1779   : objfile (objfile_),
1780     can_copy (can_copy_)
1781 {
1782   if (names == NULL)
1783     names = &dwarf2_elf_names;
1784
1785   bfd *obfd = objfile->obfd;
1786
1787   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
1788     locate_sections (obfd, sec, *names);
1789 }
1790
1791 dwarf2_per_objfile::~dwarf2_per_objfile ()
1792 {
1793   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
1794   free_cached_comp_units ();
1795
1796   for (dwarf2_per_cu_data *per_cu : all_comp_units)
1797     per_cu->imported_symtabs_free ();
1798
1799   for (signatured_type *sig_type : all_type_units)
1800     sig_type->per_cu.imported_symtabs_free ();
1801
1802   /* Everything else should be on the objfile obstack.  */
1803 }
1804
1805 /* See declaration.  */
1806
1807 void
1808 dwarf2_per_objfile::free_cached_comp_units ()
1809 {
1810   dwarf2_per_cu_data *per_cu = read_in_chain;
1811   dwarf2_per_cu_data **last_chain = &read_in_chain;
1812   while (per_cu != NULL)
1813     {
1814       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
1815
1816       delete per_cu->cu;
1817       *last_chain = next_cu;
1818       per_cu = next_cu;
1819     }
1820 }
1821
1822 /* A helper class that calls free_cached_comp_units on
1823    destruction.  */
1824
1825 class free_cached_comp_units
1826 {
1827 public:
1828
1829   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
1830     : m_per_objfile (per_objfile)
1831   {
1832   }
1833
1834   ~free_cached_comp_units ()
1835   {
1836     m_per_objfile->free_cached_comp_units ();
1837   }
1838
1839   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
1840
1841 private:
1842
1843   dwarf2_per_objfile *m_per_objfile;
1844 };
1845
1846 /* Try to locate the sections we need for DWARF 2 debugging
1847    information and return true if we have enough to do something.
1848    NAMES points to the dwarf2 section names, or is NULL if the standard
1849    ELF names are used.  CAN_COPY is true for formats where symbol
1850    interposition is possible and so symbol values must follow copy
1851    relocation rules.  */
1852
1853 int
1854 dwarf2_has_info (struct objfile *objfile,
1855                  const struct dwarf2_debug_sections *names,
1856                  bool can_copy)
1857 {
1858   if (objfile->flags & OBJF_READNEVER)
1859     return 0;
1860
1861   struct dwarf2_per_objfile *dwarf2_per_objfile
1862     = get_dwarf2_per_objfile (objfile);
1863
1864   if (dwarf2_per_objfile == NULL)
1865     dwarf2_per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile,
1866                                                           names,
1867                                                           can_copy);
1868
1869   return (!dwarf2_per_objfile->info.is_virtual
1870           && dwarf2_per_objfile->info.s.section != NULL
1871           && !dwarf2_per_objfile->abbrev.is_virtual
1872           && dwarf2_per_objfile->abbrev.s.section != NULL);
1873 }
1874
1875 /* When loading sections, we look either for uncompressed section or for
1876    compressed section names.  */
1877
1878 static int
1879 section_is_p (const char *section_name,
1880               const struct dwarf2_section_names *names)
1881 {
1882   if (names->normal != NULL
1883       && strcmp (section_name, names->normal) == 0)
1884     return 1;
1885   if (names->compressed != NULL
1886       && strcmp (section_name, names->compressed) == 0)
1887     return 1;
1888   return 0;
1889 }
1890
1891 /* See declaration.  */
1892
1893 void
1894 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
1895                                      const dwarf2_debug_sections &names)
1896 {
1897   flagword aflag = bfd_section_flags (sectp);
1898
1899   if ((aflag & SEC_HAS_CONTENTS) == 0)
1900     {
1901     }
1902   else if (elf_section_data (sectp)->this_hdr.sh_size
1903            > bfd_get_file_size (abfd))
1904     {
1905       bfd_size_type size = elf_section_data (sectp)->this_hdr.sh_size;
1906       warning (_("Discarding section %s which has a section size (%s"
1907                  ") larger than the file size [in module %s]"),
1908                bfd_section_name (sectp), phex_nz (size, sizeof (size)),
1909                bfd_get_filename (abfd));
1910     }
1911   else if (section_is_p (sectp->name, &names.info))
1912     {
1913       this->info.s.section = sectp;
1914       this->info.size = bfd_section_size (sectp);
1915     }
1916   else if (section_is_p (sectp->name, &names.abbrev))
1917     {
1918       this->abbrev.s.section = sectp;
1919       this->abbrev.size = bfd_section_size (sectp);
1920     }
1921   else if (section_is_p (sectp->name, &names.line))
1922     {
1923       this->line.s.section = sectp;
1924       this->line.size = bfd_section_size (sectp);
1925     }
1926   else if (section_is_p (sectp->name, &names.loc))
1927     {
1928       this->loc.s.section = sectp;
1929       this->loc.size = bfd_section_size (sectp);
1930     }
1931   else if (section_is_p (sectp->name, &names.loclists))
1932     {
1933       this->loclists.s.section = sectp;
1934       this->loclists.size = bfd_section_size (sectp);
1935     }
1936   else if (section_is_p (sectp->name, &names.macinfo))
1937     {
1938       this->macinfo.s.section = sectp;
1939       this->macinfo.size = bfd_section_size (sectp);
1940     }
1941   else if (section_is_p (sectp->name, &names.macro))
1942     {
1943       this->macro.s.section = sectp;
1944       this->macro.size = bfd_section_size (sectp);
1945     }
1946   else if (section_is_p (sectp->name, &names.str))
1947     {
1948       this->str.s.section = sectp;
1949       this->str.size = bfd_section_size (sectp);
1950     }
1951   else if (section_is_p (sectp->name, &names.str_offsets))
1952     {
1953       this->str_offsets.s.section = sectp;
1954       this->str_offsets.size = bfd_section_size (sectp);
1955     }
1956   else if (section_is_p (sectp->name, &names.line_str))
1957     {
1958       this->line_str.s.section = sectp;
1959       this->line_str.size = bfd_section_size (sectp);
1960     }
1961   else if (section_is_p (sectp->name, &names.addr))
1962     {
1963       this->addr.s.section = sectp;
1964       this->addr.size = bfd_section_size (sectp);
1965     }
1966   else if (section_is_p (sectp->name, &names.frame))
1967     {
1968       this->frame.s.section = sectp;
1969       this->frame.size = bfd_section_size (sectp);
1970     }
1971   else if (section_is_p (sectp->name, &names.eh_frame))
1972     {
1973       this->eh_frame.s.section = sectp;
1974       this->eh_frame.size = bfd_section_size (sectp);
1975     }
1976   else if (section_is_p (sectp->name, &names.ranges))
1977     {
1978       this->ranges.s.section = sectp;
1979       this->ranges.size = bfd_section_size (sectp);
1980     }
1981   else if (section_is_p (sectp->name, &names.rnglists))
1982     {
1983       this->rnglists.s.section = sectp;
1984       this->rnglists.size = bfd_section_size (sectp);
1985     }
1986   else if (section_is_p (sectp->name, &names.types))
1987     {
1988       struct dwarf2_section_info type_section;
1989
1990       memset (&type_section, 0, sizeof (type_section));
1991       type_section.s.section = sectp;
1992       type_section.size = bfd_section_size (sectp);
1993
1994       this->types.push_back (type_section);
1995     }
1996   else if (section_is_p (sectp->name, &names.gdb_index))
1997     {
1998       this->gdb_index.s.section = sectp;
1999       this->gdb_index.size = bfd_section_size (sectp);
2000     }
2001   else if (section_is_p (sectp->name, &names.debug_names))
2002     {
2003       this->debug_names.s.section = sectp;
2004       this->debug_names.size = bfd_section_size (sectp);
2005     }
2006   else if (section_is_p (sectp->name, &names.debug_aranges))
2007     {
2008       this->debug_aranges.s.section = sectp;
2009       this->debug_aranges.size = bfd_section_size (sectp);
2010     }
2011
2012   if ((bfd_section_flags (sectp) & (SEC_LOAD | SEC_ALLOC))
2013       && bfd_section_vma (sectp) == 0)
2014     this->has_section_at_zero = true;
2015 }
2016
2017 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2018    SECTION_NAME.  */
2019
2020 void
2021 dwarf2_get_section_info (struct objfile *objfile,
2022                          enum dwarf2_section_enum sect,
2023                          asection **sectp, const gdb_byte **bufp,
2024                          bfd_size_type *sizep)
2025 {
2026   struct dwarf2_per_objfile *data = dwarf2_objfile_data_key.get (objfile);
2027   struct dwarf2_section_info *info;
2028
2029   /* We may see an objfile without any DWARF, in which case we just
2030      return nothing.  */
2031   if (data == NULL)
2032     {
2033       *sectp = NULL;
2034       *bufp = NULL;
2035       *sizep = 0;
2036       return;
2037     }
2038   switch (sect)
2039     {
2040     case DWARF2_DEBUG_FRAME:
2041       info = &data->frame;
2042       break;
2043     case DWARF2_EH_FRAME:
2044       info = &data->eh_frame;
2045       break;
2046     default:
2047       gdb_assert_not_reached ("unexpected section");
2048     }
2049
2050   info->read (objfile);
2051
2052   *sectp = info->get_bfd_section ();
2053   *bufp = info->buffer;
2054   *sizep = info->size;
2055 }
2056
2057 /* A helper function to find the sections for a .dwz file.  */
2058
2059 static void
2060 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2061 {
2062   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2063
2064   /* Note that we only support the standard ELF names, because .dwz
2065      is ELF-only (at the time of writing).  */
2066   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2067     {
2068       dwz_file->abbrev.s.section = sectp;
2069       dwz_file->abbrev.size = bfd_section_size (sectp);
2070     }
2071   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2072     {
2073       dwz_file->info.s.section = sectp;
2074       dwz_file->info.size = bfd_section_size (sectp);
2075     }
2076   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2077     {
2078       dwz_file->str.s.section = sectp;
2079       dwz_file->str.size = bfd_section_size (sectp);
2080     }
2081   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2082     {
2083       dwz_file->line.s.section = sectp;
2084       dwz_file->line.size = bfd_section_size (sectp);
2085     }
2086   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2087     {
2088       dwz_file->macro.s.section = sectp;
2089       dwz_file->macro.size = bfd_section_size (sectp);
2090     }
2091   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2092     {
2093       dwz_file->gdb_index.s.section = sectp;
2094       dwz_file->gdb_index.size = bfd_section_size (sectp);
2095     }
2096   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2097     {
2098       dwz_file->debug_names.s.section = sectp;
2099       dwz_file->debug_names.size = bfd_section_size (sectp);
2100     }
2101 }
2102
2103 /* See dwarf2read.h.  */
2104
2105 struct dwz_file *
2106 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2107 {
2108   const char *filename;
2109   bfd_size_type buildid_len_arg;
2110   size_t buildid_len;
2111   bfd_byte *buildid;
2112
2113   if (dwarf2_per_objfile->dwz_file != NULL)
2114     return dwarf2_per_objfile->dwz_file.get ();
2115
2116   bfd_set_error (bfd_error_no_error);
2117   gdb::unique_xmalloc_ptr<char> data
2118     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2119                                   &buildid_len_arg, &buildid));
2120   if (data == NULL)
2121     {
2122       if (bfd_get_error () == bfd_error_no_error)
2123         return NULL;
2124       error (_("could not read '.gnu_debugaltlink' section: %s"),
2125              bfd_errmsg (bfd_get_error ()));
2126     }
2127
2128   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2129
2130   buildid_len = (size_t) buildid_len_arg;
2131
2132   filename = data.get ();
2133
2134   std::string abs_storage;
2135   if (!IS_ABSOLUTE_PATH (filename))
2136     {
2137       gdb::unique_xmalloc_ptr<char> abs
2138         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2139
2140       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2141       filename = abs_storage.c_str ();
2142     }
2143
2144   /* First try the file name given in the section.  If that doesn't
2145      work, try to use the build-id instead.  */
2146   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2147   if (dwz_bfd != NULL)
2148     {
2149       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2150         dwz_bfd.reset (nullptr);
2151     }
2152
2153   if (dwz_bfd == NULL)
2154     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2155
2156   if (dwz_bfd == NULL)
2157     error (_("could not find '.gnu_debugaltlink' file for %s"),
2158            objfile_name (dwarf2_per_objfile->objfile));
2159
2160   std::unique_ptr<struct dwz_file> result
2161     (new struct dwz_file (std::move (dwz_bfd)));
2162
2163   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2164                          result.get ());
2165
2166   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2167                             result->dwz_bfd.get ());
2168   dwarf2_per_objfile->dwz_file = std::move (result);
2169   return dwarf2_per_objfile->dwz_file.get ();
2170 }
2171 \f
2172 /* DWARF quick_symbols_functions support.  */
2173
2174 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2175    unique line tables, so we maintain a separate table of all .debug_line
2176    derived entries to support the sharing.
2177    All the quick functions need is the list of file names.  We discard the
2178    line_header when we're done and don't need to record it here.  */
2179 struct quick_file_names
2180 {
2181   /* The data used to construct the hash key.  */
2182   struct stmt_list_hash hash;
2183
2184   /* The number of entries in file_names, real_names.  */
2185   unsigned int num_file_names;
2186
2187   /* The file names from the line table, after being run through
2188      file_full_name.  */
2189   const char **file_names;
2190
2191   /* The file names from the line table after being run through
2192      gdb_realpath.  These are computed lazily.  */
2193   const char **real_names;
2194 };
2195
2196 /* When using the index (and thus not using psymtabs), each CU has an
2197    object of this type.  This is used to hold information needed by
2198    the various "quick" methods.  */
2199 struct dwarf2_per_cu_quick_data
2200 {
2201   /* The file table.  This can be NULL if there was no file table
2202      or it's currently not read in.
2203      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2204   struct quick_file_names *file_names;
2205
2206   /* The corresponding symbol table.  This is NULL if symbols for this
2207      CU have not yet been read.  */
2208   struct compunit_symtab *compunit_symtab;
2209
2210   /* A temporary mark bit used when iterating over all CUs in
2211      expand_symtabs_matching.  */
2212   unsigned int mark : 1;
2213
2214   /* True if we've tried to read the file table and found there isn't one.
2215      There will be no point in trying to read it again next time.  */
2216   unsigned int no_file_data : 1;
2217 };
2218
2219 /* Utility hash function for a stmt_list_hash.  */
2220
2221 static hashval_t
2222 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2223 {
2224   hashval_t v = 0;
2225
2226   if (stmt_list_hash->dwo_unit != NULL)
2227     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2228   v += to_underlying (stmt_list_hash->line_sect_off);
2229   return v;
2230 }
2231
2232 /* Utility equality function for a stmt_list_hash.  */
2233
2234 static int
2235 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2236                     const struct stmt_list_hash *rhs)
2237 {
2238   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2239     return 0;
2240   if (lhs->dwo_unit != NULL
2241       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2242     return 0;
2243
2244   return lhs->line_sect_off == rhs->line_sect_off;
2245 }
2246
2247 /* Hash function for a quick_file_names.  */
2248
2249 static hashval_t
2250 hash_file_name_entry (const void *e)
2251 {
2252   const struct quick_file_names *file_data
2253     = (const struct quick_file_names *) e;
2254
2255   return hash_stmt_list_entry (&file_data->hash);
2256 }
2257
2258 /* Equality function for a quick_file_names.  */
2259
2260 static int
2261 eq_file_name_entry (const void *a, const void *b)
2262 {
2263   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2264   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2265
2266   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2267 }
2268
2269 /* Delete function for a quick_file_names.  */
2270
2271 static void
2272 delete_file_name_entry (void *e)
2273 {
2274   struct quick_file_names *file_data = (struct quick_file_names *) e;
2275   int i;
2276
2277   for (i = 0; i < file_data->num_file_names; ++i)
2278     {
2279       xfree ((void*) file_data->file_names[i]);
2280       if (file_data->real_names)
2281         xfree ((void*) file_data->real_names[i]);
2282     }
2283
2284   /* The space for the struct itself lives on objfile_obstack,
2285      so we don't free it here.  */
2286 }
2287
2288 /* Create a quick_file_names hash table.  */
2289
2290 static htab_up
2291 create_quick_file_names_table (unsigned int nr_initial_entries)
2292 {
2293   return htab_up (htab_create_alloc (nr_initial_entries,
2294                                      hash_file_name_entry, eq_file_name_entry,
2295                                      delete_file_name_entry, xcalloc, xfree));
2296 }
2297
2298 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2299    have to be created afterwards.  You should call age_cached_comp_units after
2300    processing PER_CU->CU.  dw2_setup must have been already called.  */
2301
2302 static void
2303 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2304 {
2305   if (per_cu->is_debug_types)
2306     load_full_type_unit (per_cu);
2307   else
2308     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2309
2310   if (per_cu->cu == NULL)
2311     return;  /* Dummy CU.  */
2312
2313   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2314 }
2315
2316 /* Read in the symbols for PER_CU.  */
2317
2318 static void
2319 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2320 {
2321   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2322
2323   /* Skip type_unit_groups, reading the type units they contain
2324      is handled elsewhere.  */
2325   if (IS_TYPE_UNIT_GROUP (per_cu))
2326     return;
2327
2328   /* The destructor of dwarf2_queue_guard frees any entries left on
2329      the queue.  After this point we're guaranteed to leave this function
2330      with the dwarf queue empty.  */
2331   dwarf2_queue_guard q_guard (dwarf2_per_objfile);
2332
2333   if (dwarf2_per_objfile->using_index
2334       ? per_cu->v.quick->compunit_symtab == NULL
2335       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2336     {
2337       queue_comp_unit (per_cu, language_minimal);
2338       load_cu (per_cu, skip_partial);
2339
2340       /* If we just loaded a CU from a DWO, and we're working with an index
2341          that may badly handle TUs, load all the TUs in that DWO as well.
2342          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2343       if (!per_cu->is_debug_types
2344           && per_cu->cu != NULL
2345           && per_cu->cu->dwo_unit != NULL
2346           && dwarf2_per_objfile->index_table != NULL
2347           && dwarf2_per_objfile->index_table->version <= 7
2348           /* DWP files aren't supported yet.  */
2349           && get_dwp_file (dwarf2_per_objfile) == NULL)
2350         queue_and_load_all_dwo_tus (per_cu);
2351     }
2352
2353   process_queue (dwarf2_per_objfile);
2354
2355   /* Age the cache, releasing compilation units that have not
2356      been used recently.  */
2357   age_cached_comp_units (dwarf2_per_objfile);
2358 }
2359
2360 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2361    the objfile from which this CU came.  Returns the resulting symbol
2362    table.  */
2363
2364 static struct compunit_symtab *
2365 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2366 {
2367   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2368
2369   gdb_assert (dwarf2_per_objfile->using_index);
2370   if (!per_cu->v.quick->compunit_symtab)
2371     {
2372       free_cached_comp_units freer (dwarf2_per_objfile);
2373       scoped_restore decrementer = increment_reading_symtab ();
2374       dw2_do_instantiate_symtab (per_cu, skip_partial);
2375       process_cu_includes (dwarf2_per_objfile);
2376     }
2377
2378   return per_cu->v.quick->compunit_symtab;
2379 }
2380
2381 /* See declaration.  */
2382
2383 dwarf2_per_cu_data *
2384 dwarf2_per_objfile::get_cutu (int index)
2385 {
2386   if (index >= this->all_comp_units.size ())
2387     {
2388       index -= this->all_comp_units.size ();
2389       gdb_assert (index < this->all_type_units.size ());
2390       return &this->all_type_units[index]->per_cu;
2391     }
2392
2393   return this->all_comp_units[index];
2394 }
2395
2396 /* See declaration.  */
2397
2398 dwarf2_per_cu_data *
2399 dwarf2_per_objfile::get_cu (int index)
2400 {
2401   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2402
2403   return this->all_comp_units[index];
2404 }
2405
2406 /* See declaration.  */
2407
2408 signatured_type *
2409 dwarf2_per_objfile::get_tu (int index)
2410 {
2411   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2412
2413   return this->all_type_units[index];
2414 }
2415
2416 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2417    objfile_obstack, and constructed with the specified field
2418    values.  */
2419
2420 static dwarf2_per_cu_data *
2421 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2422                           struct dwarf2_section_info *section,
2423                           int is_dwz,
2424                           sect_offset sect_off, ULONGEST length)
2425 {
2426   struct objfile *objfile = dwarf2_per_objfile->objfile;
2427   dwarf2_per_cu_data *the_cu
2428     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2429                      struct dwarf2_per_cu_data);
2430   the_cu->sect_off = sect_off;
2431   the_cu->length = length;
2432   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2433   the_cu->section = section;
2434   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2435                                    struct dwarf2_per_cu_quick_data);
2436   the_cu->is_dwz = is_dwz;
2437   return the_cu;
2438 }
2439
2440 /* A helper for create_cus_from_index that handles a given list of
2441    CUs.  */
2442
2443 static void
2444 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2445                             const gdb_byte *cu_list, offset_type n_elements,
2446                             struct dwarf2_section_info *section,
2447                             int is_dwz)
2448 {
2449   for (offset_type i = 0; i < n_elements; i += 2)
2450     {
2451       gdb_static_assert (sizeof (ULONGEST) >= 8);
2452
2453       sect_offset sect_off
2454         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2455       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2456       cu_list += 2 * 8;
2457
2458       dwarf2_per_cu_data *per_cu
2459         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2460                                      sect_off, length);
2461       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2462     }
2463 }
2464
2465 /* Read the CU list from the mapped index, and use it to create all
2466    the CU objects for this objfile.  */
2467
2468 static void
2469 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
2470                        const gdb_byte *cu_list, offset_type cu_list_elements,
2471                        const gdb_byte *dwz_list, offset_type dwz_elements)
2472 {
2473   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
2474   dwarf2_per_objfile->all_comp_units.reserve
2475     ((cu_list_elements + dwz_elements) / 2);
2476
2477   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
2478                               &dwarf2_per_objfile->info, 0);
2479
2480   if (dwz_elements == 0)
2481     return;
2482
2483   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
2484   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
2485                               &dwz->info, 1);
2486 }
2487
2488 /* Create the signatured type hash table from the index.  */
2489
2490 static void
2491 create_signatured_type_table_from_index
2492   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2493    struct dwarf2_section_info *section,
2494    const gdb_byte *bytes,
2495    offset_type elements)
2496 {
2497   struct objfile *objfile = dwarf2_per_objfile->objfile;
2498
2499   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
2500   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
2501
2502   htab_up sig_types_hash = allocate_signatured_type_table ();
2503
2504   for (offset_type i = 0; i < elements; i += 3)
2505     {
2506       struct signatured_type *sig_type;
2507       ULONGEST signature;
2508       void **slot;
2509       cu_offset type_offset_in_tu;
2510
2511       gdb_static_assert (sizeof (ULONGEST) >= 8);
2512       sect_offset sect_off
2513         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2514       type_offset_in_tu
2515         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
2516                                                 BFD_ENDIAN_LITTLE);
2517       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2518       bytes += 3 * 8;
2519
2520       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2521                                  struct signatured_type);
2522       sig_type->signature = signature;
2523       sig_type->type_offset_in_tu = type_offset_in_tu;
2524       sig_type->per_cu.is_debug_types = 1;
2525       sig_type->per_cu.section = section;
2526       sig_type->per_cu.sect_off = sect_off;
2527       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
2528       sig_type->per_cu.v.quick
2529         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2530                           struct dwarf2_per_cu_quick_data);
2531
2532       slot = htab_find_slot (sig_types_hash.get (), sig_type, INSERT);
2533       *slot = sig_type;
2534
2535       dwarf2_per_objfile->all_type_units.push_back (sig_type);
2536     }
2537
2538   dwarf2_per_objfile->signatured_types = std::move (sig_types_hash);
2539 }
2540
2541 /* Create the signatured type hash table from .debug_names.  */
2542
2543 static void
2544 create_signatured_type_table_from_debug_names
2545   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2546    const mapped_debug_names &map,
2547    struct dwarf2_section_info *section,
2548    struct dwarf2_section_info *abbrev_section)
2549 {
2550   struct objfile *objfile = dwarf2_per_objfile->objfile;
2551
2552   section->read (objfile);
2553   abbrev_section->read (objfile);
2554
2555   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
2556   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
2557
2558   htab_up sig_types_hash = allocate_signatured_type_table ();
2559
2560   for (uint32_t i = 0; i < map.tu_count; ++i)
2561     {
2562       struct signatured_type *sig_type;
2563       void **slot;
2564
2565       sect_offset sect_off
2566         = (sect_offset) (extract_unsigned_integer
2567                          (map.tu_table_reordered + i * map.offset_size,
2568                           map.offset_size,
2569                           map.dwarf5_byte_order));
2570
2571       comp_unit_head cu_header;
2572       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
2573                                      abbrev_section,
2574                                      section->buffer + to_underlying (sect_off),
2575                                      rcuh_kind::TYPE);
2576
2577       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2578                                  struct signatured_type);
2579       sig_type->signature = cu_header.signature;
2580       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
2581       sig_type->per_cu.is_debug_types = 1;
2582       sig_type->per_cu.section = section;
2583       sig_type->per_cu.sect_off = sect_off;
2584       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
2585       sig_type->per_cu.v.quick
2586         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2587                           struct dwarf2_per_cu_quick_data);
2588
2589       slot = htab_find_slot (sig_types_hash.get (), sig_type, INSERT);
2590       *slot = sig_type;
2591
2592       dwarf2_per_objfile->all_type_units.push_back (sig_type);
2593     }
2594
2595   dwarf2_per_objfile->signatured_types = std::move (sig_types_hash);
2596 }
2597
2598 /* Read the address map data from the mapped index, and use it to
2599    populate the objfile's psymtabs_addrmap.  */
2600
2601 static void
2602 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
2603                            struct mapped_index *index)
2604 {
2605   struct objfile *objfile = dwarf2_per_objfile->objfile;
2606   struct gdbarch *gdbarch = get_objfile_arch (objfile);
2607   const gdb_byte *iter, *end;
2608   struct addrmap *mutable_map;
2609   CORE_ADDR baseaddr;
2610
2611   auto_obstack temp_obstack;
2612
2613   mutable_map = addrmap_create_mutable (&temp_obstack);
2614
2615   iter = index->address_table.data ();
2616   end = iter + index->address_table.size ();
2617
2618   baseaddr = objfile->text_section_offset ();
2619
2620   while (iter < end)
2621     {
2622       ULONGEST hi, lo, cu_index;
2623       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2624       iter += 8;
2625       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2626       iter += 8;
2627       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2628       iter += 4;
2629
2630       if (lo > hi)
2631         {
2632           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
2633                      hex_string (lo), hex_string (hi));
2634           continue;
2635         }
2636
2637       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
2638         {
2639           complaint (_(".gdb_index address table has invalid CU number %u"),
2640                      (unsigned) cu_index);
2641           continue;
2642         }
2643
2644       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
2645       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
2646       addrmap_set_empty (mutable_map, lo, hi - 1,
2647                          dwarf2_per_objfile->get_cu (cu_index));
2648     }
2649
2650   objfile->partial_symtabs->psymtabs_addrmap
2651     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
2652 }
2653
2654 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
2655    populate the objfile's psymtabs_addrmap.  */
2656
2657 static void
2658 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
2659                              struct dwarf2_section_info *section)
2660 {
2661   struct objfile *objfile = dwarf2_per_objfile->objfile;
2662   bfd *abfd = objfile->obfd;
2663   struct gdbarch *gdbarch = get_objfile_arch (objfile);
2664   const CORE_ADDR baseaddr = objfile->text_section_offset ();
2665
2666   auto_obstack temp_obstack;
2667   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
2668
2669   std::unordered_map<sect_offset,
2670                      dwarf2_per_cu_data *,
2671                      gdb::hash_enum<sect_offset>>
2672     debug_info_offset_to_per_cu;
2673   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
2674     {
2675       const auto insertpair
2676         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
2677       if (!insertpair.second)
2678         {
2679           warning (_("Section .debug_aranges in %s has duplicate "
2680                      "debug_info_offset %s, ignoring .debug_aranges."),
2681                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
2682           return;
2683         }
2684     }
2685
2686   section->read (objfile);
2687
2688   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
2689
2690   const gdb_byte *addr = section->buffer;
2691
2692   while (addr < section->buffer + section->size)
2693     {
2694       const gdb_byte *const entry_addr = addr;
2695       unsigned int bytes_read;
2696
2697       const LONGEST entry_length = read_initial_length (abfd, addr,
2698                                                         &bytes_read);
2699       addr += bytes_read;
2700
2701       const gdb_byte *const entry_end = addr + entry_length;
2702       const bool dwarf5_is_dwarf64 = bytes_read != 4;
2703       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
2704       if (addr + entry_length > section->buffer + section->size)
2705         {
2706           warning (_("Section .debug_aranges in %s entry at offset %s "
2707                      "length %s exceeds section length %s, "
2708                      "ignoring .debug_aranges."),
2709                    objfile_name (objfile),
2710                    plongest (entry_addr - section->buffer),
2711                    plongest (bytes_read + entry_length),
2712                    pulongest (section->size));
2713           return;
2714         }
2715
2716       /* The version number.  */
2717       const uint16_t version = read_2_bytes (abfd, addr);
2718       addr += 2;
2719       if (version != 2)
2720         {
2721           warning (_("Section .debug_aranges in %s entry at offset %s "
2722                      "has unsupported version %d, ignoring .debug_aranges."),
2723                    objfile_name (objfile),
2724                    plongest (entry_addr - section->buffer), version);
2725           return;
2726         }
2727
2728       const uint64_t debug_info_offset
2729         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
2730       addr += offset_size;
2731       const auto per_cu_it
2732         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
2733       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
2734         {
2735           warning (_("Section .debug_aranges in %s entry at offset %s "
2736                      "debug_info_offset %s does not exists, "
2737                      "ignoring .debug_aranges."),
2738                    objfile_name (objfile),
2739                    plongest (entry_addr - section->buffer),
2740                    pulongest (debug_info_offset));
2741           return;
2742         }
2743       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
2744
2745       const uint8_t address_size = *addr++;
2746       if (address_size < 1 || address_size > 8)
2747         {
2748           warning (_("Section .debug_aranges in %s entry at offset %s "
2749                      "address_size %u is invalid, ignoring .debug_aranges."),
2750                    objfile_name (objfile),
2751                    plongest (entry_addr - section->buffer), address_size);
2752           return;
2753         }
2754
2755       const uint8_t segment_selector_size = *addr++;
2756       if (segment_selector_size != 0)
2757         {
2758           warning (_("Section .debug_aranges in %s entry at offset %s "
2759                      "segment_selector_size %u is not supported, "
2760                      "ignoring .debug_aranges."),
2761                    objfile_name (objfile),
2762                    plongest (entry_addr - section->buffer),
2763                    segment_selector_size);
2764           return;
2765         }
2766
2767       /* Must pad to an alignment boundary that is twice the address
2768          size.  It is undocumented by the DWARF standard but GCC does
2769          use it.  */
2770       for (size_t padding = ((-(addr - section->buffer))
2771                              & (2 * address_size - 1));
2772            padding > 0; padding--)
2773         if (*addr++ != 0)
2774           {
2775             warning (_("Section .debug_aranges in %s entry at offset %s "
2776                        "padding is not zero, ignoring .debug_aranges."),
2777                      objfile_name (objfile),
2778                      plongest (entry_addr - section->buffer));
2779             return;
2780           }
2781
2782       for (;;)
2783         {
2784           if (addr + 2 * address_size > entry_end)
2785             {
2786               warning (_("Section .debug_aranges in %s entry at offset %s "
2787                          "address list is not properly terminated, "
2788                          "ignoring .debug_aranges."),
2789                        objfile_name (objfile),
2790                        plongest (entry_addr - section->buffer));
2791               return;
2792             }
2793           ULONGEST start = extract_unsigned_integer (addr, address_size,
2794                                                      dwarf5_byte_order);
2795           addr += address_size;
2796           ULONGEST length = extract_unsigned_integer (addr, address_size,
2797                                                       dwarf5_byte_order);
2798           addr += address_size;
2799           if (start == 0 && length == 0)
2800             break;
2801           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
2802             {
2803               /* Symbol was eliminated due to a COMDAT group.  */
2804               continue;
2805             }
2806           ULONGEST end = start + length;
2807           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
2808                    - baseaddr);
2809           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
2810                  - baseaddr);
2811           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
2812         }
2813     }
2814
2815   objfile->partial_symtabs->psymtabs_addrmap
2816     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
2817 }
2818
2819 /* Find a slot in the mapped index INDEX for the object named NAME.
2820    If NAME is found, set *VEC_OUT to point to the CU vector in the
2821    constant pool and return true.  If NAME cannot be found, return
2822    false.  */
2823
2824 static bool
2825 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2826                           offset_type **vec_out)
2827 {
2828   offset_type hash;
2829   offset_type slot, step;
2830   int (*cmp) (const char *, const char *);
2831
2832   gdb::unique_xmalloc_ptr<char> without_params;
2833   if (current_language->la_language == language_cplus
2834       || current_language->la_language == language_fortran
2835       || current_language->la_language == language_d)
2836     {
2837       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2838          not contain any.  */
2839
2840       if (strchr (name, '(') != NULL)
2841         {
2842           without_params = cp_remove_params (name);
2843
2844           if (without_params != NULL)
2845             name = without_params.get ();
2846         }
2847     }
2848
2849   /* Index version 4 did not support case insensitive searches.  But the
2850      indices for case insensitive languages are built in lowercase, therefore
2851      simulate our NAME being searched is also lowercased.  */
2852   hash = mapped_index_string_hash ((index->version == 4
2853                                     && case_sensitivity == case_sensitive_off
2854                                     ? 5 : index->version),
2855                                    name);
2856
2857   slot = hash & (index->symbol_table.size () - 1);
2858   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
2859   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2860
2861   for (;;)
2862     {
2863       const char *str;
2864
2865       const auto &bucket = index->symbol_table[slot];
2866       if (bucket.name == 0 && bucket.vec == 0)
2867         return false;
2868
2869       str = index->constant_pool + MAYBE_SWAP (bucket.name);
2870       if (!cmp (name, str))
2871         {
2872           *vec_out = (offset_type *) (index->constant_pool
2873                                       + MAYBE_SWAP (bucket.vec));
2874           return true;
2875         }
2876
2877       slot = (slot + step) & (index->symbol_table.size () - 1);
2878     }
2879 }
2880
2881 /* A helper function that reads the .gdb_index from BUFFER and fills
2882    in MAP.  FILENAME is the name of the file containing the data;
2883    it is used for error reporting.  DEPRECATED_OK is true if it is
2884    ok to use deprecated sections.
2885
2886    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2887    out parameters that are filled in with information about the CU and
2888    TU lists in the section.
2889
2890    Returns true if all went well, false otherwise.  */
2891
2892 static bool
2893 read_gdb_index_from_buffer (struct objfile *objfile,
2894                             const char *filename,
2895                             bool deprecated_ok,
2896                             gdb::array_view<const gdb_byte> buffer,
2897                             struct mapped_index *map,
2898                             const gdb_byte **cu_list,
2899                             offset_type *cu_list_elements,
2900                             const gdb_byte **types_list,
2901                             offset_type *types_list_elements)
2902 {
2903   const gdb_byte *addr = &buffer[0];
2904
2905   /* Version check.  */
2906   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
2907   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2908      causes the index to behave very poorly for certain requests.  Version 3
2909      contained incomplete addrmap.  So, it seems better to just ignore such
2910      indices.  */
2911   if (version < 4)
2912     {
2913       static int warning_printed = 0;
2914       if (!warning_printed)
2915         {
2916           warning (_("Skipping obsolete .gdb_index section in %s."),
2917                    filename);
2918           warning_printed = 1;
2919         }
2920       return 0;
2921     }
2922   /* Index version 4 uses a different hash function than index version
2923      5 and later.
2924
2925      Versions earlier than 6 did not emit psymbols for inlined
2926      functions.  Using these files will cause GDB not to be able to
2927      set breakpoints on inlined functions by name, so we ignore these
2928      indices unless the user has done
2929      "set use-deprecated-index-sections on".  */
2930   if (version < 6 && !deprecated_ok)
2931     {
2932       static int warning_printed = 0;
2933       if (!warning_printed)
2934         {
2935           warning (_("\
2936 Skipping deprecated .gdb_index section in %s.\n\
2937 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2938 to use the section anyway."),
2939                    filename);
2940           warning_printed = 1;
2941         }
2942       return 0;
2943     }
2944   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2945      of the TU (for symbols coming from TUs),
2946      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
2947      Plus gold-generated indices can have duplicate entries for global symbols,
2948      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
2949      These are just performance bugs, and we can't distinguish gdb-generated
2950      indices from gold-generated ones, so issue no warning here.  */
2951
2952   /* Indexes with higher version than the one supported by GDB may be no
2953      longer backward compatible.  */
2954   if (version > 8)
2955     return 0;
2956
2957   map->version = version;
2958
2959   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
2960
2961   int i = 0;
2962   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2963   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2964                        / 8);
2965   ++i;
2966
2967   *types_list = addr + MAYBE_SWAP (metadata[i]);
2968   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2969                            - MAYBE_SWAP (metadata[i]))
2970                           / 8);
2971   ++i;
2972
2973   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
2974   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
2975   map->address_table
2976     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
2977   ++i;
2978
2979   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
2980   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
2981   map->symbol_table
2982     = gdb::array_view<mapped_index::symbol_table_slot>
2983        ((mapped_index::symbol_table_slot *) symbol_table,
2984         (mapped_index::symbol_table_slot *) symbol_table_end);
2985
2986   ++i;
2987   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2988
2989   return 1;
2990 }
2991
2992 /* Callback types for dwarf2_read_gdb_index.  */
2993
2994 typedef gdb::function_view
2995     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
2996     get_gdb_index_contents_ftype;
2997 typedef gdb::function_view
2998     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
2999     get_gdb_index_contents_dwz_ftype;
3000
3001 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3002    elements of all the CUs and return 1.  Otherwise, return 0.  */
3003
3004 static int
3005 dwarf2_read_gdb_index
3006   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3007    get_gdb_index_contents_ftype get_gdb_index_contents,
3008    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3009 {
3010   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3011   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3012   struct dwz_file *dwz;
3013   struct objfile *objfile = dwarf2_per_objfile->objfile;
3014
3015   gdb::array_view<const gdb_byte> main_index_contents
3016     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3017
3018   if (main_index_contents.empty ())
3019     return 0;
3020
3021   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3022   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3023                                    use_deprecated_index_sections,
3024                                    main_index_contents, map.get (), &cu_list,
3025                                    &cu_list_elements, &types_list,
3026                                    &types_list_elements))
3027     return 0;
3028
3029   /* Don't use the index if it's empty.  */
3030   if (map->symbol_table.empty ())
3031     return 0;
3032
3033   /* If there is a .dwz file, read it so we can get its CU list as
3034      well.  */
3035   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3036   if (dwz != NULL)
3037     {
3038       struct mapped_index dwz_map;
3039       const gdb_byte *dwz_types_ignore;
3040       offset_type dwz_types_elements_ignore;
3041
3042       gdb::array_view<const gdb_byte> dwz_index_content
3043         = get_gdb_index_contents_dwz (objfile, dwz);
3044
3045       if (dwz_index_content.empty ())
3046         return 0;
3047
3048       if (!read_gdb_index_from_buffer (objfile,
3049                                        bfd_get_filename (dwz->dwz_bfd.get ()),
3050                                        1, dwz_index_content, &dwz_map,
3051                                        &dwz_list, &dwz_list_elements,
3052                                        &dwz_types_ignore,
3053                                        &dwz_types_elements_ignore))
3054         {
3055           warning (_("could not read '.gdb_index' section from %s; skipping"),
3056                    bfd_get_filename (dwz->dwz_bfd.get ()));
3057           return 0;
3058         }
3059     }
3060
3061   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3062                          dwz_list, dwz_list_elements);
3063
3064   if (types_list_elements)
3065     {
3066       /* We can only handle a single .debug_types when we have an
3067          index.  */
3068       if (dwarf2_per_objfile->types.size () != 1)
3069         return 0;
3070
3071       dwarf2_section_info *section = &dwarf2_per_objfile->types[0];
3072
3073       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3074                                                types_list, types_list_elements);
3075     }
3076
3077   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3078
3079   dwarf2_per_objfile->index_table = std::move (map);
3080   dwarf2_per_objfile->using_index = 1;
3081   dwarf2_per_objfile->quick_file_names_table =
3082     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3083
3084   return 1;
3085 }
3086
3087 /* die_reader_func for dw2_get_file_names.  */
3088
3089 static void
3090 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3091                            const gdb_byte *info_ptr,
3092                            struct die_info *comp_unit_die)
3093 {
3094   struct dwarf2_cu *cu = reader->cu;
3095   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3096   struct dwarf2_per_objfile *dwarf2_per_objfile
3097     = cu->per_cu->dwarf2_per_objfile;
3098   struct objfile *objfile = dwarf2_per_objfile->objfile;
3099   struct dwarf2_per_cu_data *lh_cu;
3100   struct attribute *attr;
3101   void **slot;
3102   struct quick_file_names *qfn;
3103
3104   gdb_assert (! this_cu->is_debug_types);
3105
3106   /* Our callers never want to match partial units -- instead they
3107      will match the enclosing full CU.  */
3108   if (comp_unit_die->tag == DW_TAG_partial_unit)
3109     {
3110       this_cu->v.quick->no_file_data = 1;
3111       return;
3112     }
3113
3114   lh_cu = this_cu;
3115   slot = NULL;
3116
3117   line_header_up lh;
3118   sect_offset line_offset {};
3119
3120   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3121   if (attr != nullptr)
3122     {
3123       struct quick_file_names find_entry;
3124
3125       line_offset = (sect_offset) DW_UNSND (attr);
3126
3127       /* We may have already read in this line header (TU line header sharing).
3128          If we have we're done.  */
3129       find_entry.hash.dwo_unit = cu->dwo_unit;
3130       find_entry.hash.line_sect_off = line_offset;
3131       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table.get (),
3132                              &find_entry, INSERT);
3133       if (*slot != NULL)
3134         {
3135           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3136           return;
3137         }
3138
3139       lh = dwarf_decode_line_header (line_offset, cu);
3140     }
3141   if (lh == NULL)
3142     {
3143       lh_cu->v.quick->no_file_data = 1;
3144       return;
3145     }
3146
3147   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3148   qfn->hash.dwo_unit = cu->dwo_unit;
3149   qfn->hash.line_sect_off = line_offset;
3150   gdb_assert (slot != NULL);
3151   *slot = qfn;
3152
3153   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3154
3155   int offset = 0;
3156   if (strcmp (fnd.name, "<unknown>") != 0)
3157     ++offset;
3158
3159   qfn->num_file_names = offset + lh->file_names_size ();
3160   qfn->file_names =
3161     XOBNEWVEC (&objfile->objfile_obstack, const char *, qfn->num_file_names);
3162   if (offset != 0)
3163     qfn->file_names[0] = xstrdup (fnd.name);
3164   for (int i = 0; i < lh->file_names_size (); ++i)
3165     qfn->file_names[i + offset] = lh->file_full_name (i + 1,
3166                                                       fnd.comp_dir).release ();
3167   qfn->real_names = NULL;
3168
3169   lh_cu->v.quick->file_names = qfn;
3170 }
3171
3172 /* A helper for the "quick" functions which attempts to read the line
3173    table for THIS_CU.  */
3174
3175 static struct quick_file_names *
3176 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3177 {
3178   /* This should never be called for TUs.  */
3179   gdb_assert (! this_cu->is_debug_types);
3180   /* Nor type unit groups.  */
3181   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3182
3183   if (this_cu->v.quick->file_names != NULL)
3184     return this_cu->v.quick->file_names;
3185   /* If we know there is no line data, no point in looking again.  */
3186   if (this_cu->v.quick->no_file_data)
3187     return NULL;
3188
3189   cutu_reader reader (this_cu);
3190   if (!reader.dummy_p)
3191     dw2_get_file_names_reader (&reader, reader.info_ptr, reader.comp_unit_die);
3192
3193   if (this_cu->v.quick->no_file_data)
3194     return NULL;
3195   return this_cu->v.quick->file_names;
3196 }
3197
3198 /* A helper for the "quick" functions which computes and caches the
3199    real path for a given file name from the line table.  */
3200
3201 static const char *
3202 dw2_get_real_path (struct objfile *objfile,
3203                    struct quick_file_names *qfn, int index)
3204 {
3205   if (qfn->real_names == NULL)
3206     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3207                                       qfn->num_file_names, const char *);
3208
3209   if (qfn->real_names[index] == NULL)
3210     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3211
3212   return qfn->real_names[index];
3213 }
3214
3215 static struct symtab *
3216 dw2_find_last_source_symtab (struct objfile *objfile)
3217 {
3218   struct dwarf2_per_objfile *dwarf2_per_objfile
3219     = get_dwarf2_per_objfile (objfile);
3220   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3221   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3222
3223   if (cust == NULL)
3224     return NULL;
3225
3226   return compunit_primary_filetab (cust);
3227 }
3228
3229 /* Traversal function for dw2_forget_cached_source_info.  */
3230
3231 static int
3232 dw2_free_cached_file_names (void **slot, void *info)
3233 {
3234   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3235
3236   if (file_data->real_names)
3237     {
3238       int i;
3239
3240       for (i = 0; i < file_data->num_file_names; ++i)
3241         {
3242           xfree ((void*) file_data->real_names[i]);
3243           file_data->real_names[i] = NULL;
3244         }
3245     }
3246
3247   return 1;
3248 }
3249
3250 static void
3251 dw2_forget_cached_source_info (struct objfile *objfile)
3252 {
3253   struct dwarf2_per_objfile *dwarf2_per_objfile
3254     = get_dwarf2_per_objfile (objfile);
3255
3256   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table.get (),
3257                           dw2_free_cached_file_names, NULL);
3258 }
3259
3260 /* Helper function for dw2_map_symtabs_matching_filename that expands
3261    the symtabs and calls the iterator.  */
3262
3263 static int
3264 dw2_map_expand_apply (struct objfile *objfile,
3265                       struct dwarf2_per_cu_data *per_cu,
3266                       const char *name, const char *real_path,
3267                       gdb::function_view<bool (symtab *)> callback)
3268 {
3269   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3270
3271   /* Don't visit already-expanded CUs.  */
3272   if (per_cu->v.quick->compunit_symtab)
3273     return 0;
3274
3275   /* This may expand more than one symtab, and we want to iterate over
3276      all of them.  */
3277   dw2_instantiate_symtab (per_cu, false);
3278
3279   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3280                                     last_made, callback);
3281 }
3282
3283 /* Implementation of the map_symtabs_matching_filename method.  */
3284
3285 static bool
3286 dw2_map_symtabs_matching_filename
3287   (struct objfile *objfile, const char *name, const char *real_path,
3288    gdb::function_view<bool (symtab *)> callback)
3289 {
3290   const char *name_basename = lbasename (name);
3291   struct dwarf2_per_objfile *dwarf2_per_objfile
3292     = get_dwarf2_per_objfile (objfile);
3293
3294   /* The rule is CUs specify all the files, including those used by
3295      any TU, so there's no need to scan TUs here.  */
3296
3297   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3298     {
3299       /* We only need to look at symtabs not already expanded.  */
3300       if (per_cu->v.quick->compunit_symtab)
3301         continue;
3302
3303       quick_file_names *file_data = dw2_get_file_names (per_cu);
3304       if (file_data == NULL)
3305         continue;
3306
3307       for (int j = 0; j < file_data->num_file_names; ++j)
3308         {
3309           const char *this_name = file_data->file_names[j];
3310           const char *this_real_name;
3311
3312           if (compare_filenames_for_search (this_name, name))
3313             {
3314               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3315                                         callback))
3316                 return true;
3317               continue;
3318             }
3319
3320           /* Before we invoke realpath, which can get expensive when many
3321              files are involved, do a quick comparison of the basenames.  */
3322           if (! basenames_may_differ
3323               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3324             continue;
3325
3326           this_real_name = dw2_get_real_path (objfile, file_data, j);
3327           if (compare_filenames_for_search (this_real_name, name))
3328             {
3329               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3330                                         callback))
3331                 return true;
3332               continue;
3333             }
3334
3335           if (real_path != NULL)
3336             {
3337               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3338               gdb_assert (IS_ABSOLUTE_PATH (name));
3339               if (this_real_name != NULL
3340                   && FILENAME_CMP (real_path, this_real_name) == 0)
3341                 {
3342                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3343                                             callback))
3344                     return true;
3345                   continue;
3346                 }
3347             }
3348         }
3349     }
3350
3351   return false;
3352 }
3353
3354 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3355
3356 struct dw2_symtab_iterator
3357 {
3358   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3359   struct dwarf2_per_objfile *dwarf2_per_objfile;
3360   /* If set, only look for symbols that match that block.  Valid values are
3361      GLOBAL_BLOCK and STATIC_BLOCK.  */
3362   gdb::optional<block_enum> block_index;
3363   /* The kind of symbol we're looking for.  */
3364   domain_enum domain;
3365   /* The list of CUs from the index entry of the symbol,
3366      or NULL if not found.  */
3367   offset_type *vec;
3368   /* The next element in VEC to look at.  */
3369   int next;
3370   /* The number of elements in VEC, or zero if there is no match.  */
3371   int length;
3372   /* Have we seen a global version of the symbol?
3373      If so we can ignore all further global instances.
3374      This is to work around gold/15646, inefficient gold-generated
3375      indices.  */
3376   int global_seen;
3377 };
3378
3379 /* Initialize the index symtab iterator ITER.  */
3380
3381 static void
3382 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3383                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3384                       gdb::optional<block_enum> block_index,
3385                       domain_enum domain,
3386                       const char *name)
3387 {
3388   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3389   iter->block_index = block_index;
3390   iter->domain = domain;
3391   iter->next = 0;
3392   iter->global_seen = 0;
3393
3394   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3395
3396   /* index is NULL if OBJF_READNOW.  */
3397   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3398     iter->length = MAYBE_SWAP (*iter->vec);
3399   else
3400     {
3401       iter->vec = NULL;
3402       iter->length = 0;
3403     }
3404 }
3405
3406 /* Return the next matching CU or NULL if there are no more.  */
3407
3408 static struct dwarf2_per_cu_data *
3409 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3410 {
3411   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3412
3413   for ( ; iter->next < iter->length; ++iter->next)
3414     {
3415       offset_type cu_index_and_attrs =
3416         MAYBE_SWAP (iter->vec[iter->next + 1]);
3417       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3418       gdb_index_symbol_kind symbol_kind =
3419         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3420       /* Only check the symbol attributes if they're present.
3421          Indices prior to version 7 don't record them,
3422          and indices >= 7 may elide them for certain symbols
3423          (gold does this).  */
3424       int attrs_valid =
3425         (dwarf2_per_objfile->index_table->version >= 7
3426          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3427
3428       /* Don't crash on bad data.  */
3429       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3430                        + dwarf2_per_objfile->all_type_units.size ()))
3431         {
3432           complaint (_(".gdb_index entry has bad CU index"
3433                        " [in module %s]"),
3434                      objfile_name (dwarf2_per_objfile->objfile));
3435           continue;
3436         }
3437
3438       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3439
3440       /* Skip if already read in.  */
3441       if (per_cu->v.quick->compunit_symtab)
3442         continue;
3443
3444       /* Check static vs global.  */
3445       if (attrs_valid)
3446         {
3447           bool is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3448
3449           if (iter->block_index.has_value ())
3450             {
3451               bool want_static = *iter->block_index == STATIC_BLOCK;
3452
3453               if (is_static != want_static)
3454                 continue;
3455             }
3456
3457           /* Work around gold/15646.  */
3458           if (!is_static && iter->global_seen)
3459             continue;
3460           if (!is_static)
3461             iter->global_seen = 1;
3462         }
3463
3464       /* Only check the symbol's kind if it has one.  */
3465       if (attrs_valid)
3466         {
3467           switch (iter->domain)
3468             {
3469             case VAR_DOMAIN:
3470               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3471                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3472                   /* Some types are also in VAR_DOMAIN.  */
3473                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3474                 continue;
3475               break;
3476             case STRUCT_DOMAIN:
3477               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3478                 continue;
3479               break;
3480             case LABEL_DOMAIN:
3481               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3482                 continue;
3483               break;
3484             case MODULE_DOMAIN:
3485               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3486                 continue;
3487               break;
3488             default:
3489               break;
3490             }
3491         }
3492
3493       ++iter->next;
3494       return per_cu;
3495     }
3496
3497   return NULL;
3498 }
3499
3500 static struct compunit_symtab *
3501 dw2_lookup_symbol (struct objfile *objfile, block_enum block_index,
3502                    const char *name, domain_enum domain)
3503 {
3504   struct compunit_symtab *stab_best = NULL;
3505   struct dwarf2_per_objfile *dwarf2_per_objfile
3506     = get_dwarf2_per_objfile (objfile);
3507
3508   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3509
3510   struct dw2_symtab_iterator iter;
3511   struct dwarf2_per_cu_data *per_cu;
3512
3513   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, block_index, domain, name);
3514
3515   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3516     {
3517       struct symbol *sym, *with_opaque = NULL;
3518       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
3519       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3520       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3521
3522       sym = block_find_symbol (block, name, domain,
3523                                block_find_non_opaque_type_preferred,
3524                                &with_opaque);
3525
3526       /* Some caution must be observed with overloaded functions
3527          and methods, since the index will not contain any overload
3528          information (but NAME might contain it).  */
3529
3530       if (sym != NULL
3531           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3532         return stab;
3533       if (with_opaque != NULL
3534           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3535         stab_best = stab;
3536
3537       /* Keep looking through other CUs.  */
3538     }
3539
3540   return stab_best;
3541 }
3542
3543 static void
3544 dw2_print_stats (struct objfile *objfile)
3545 {
3546   struct dwarf2_per_objfile *dwarf2_per_objfile
3547     = get_dwarf2_per_objfile (objfile);
3548   int total = (dwarf2_per_objfile->all_comp_units.size ()
3549                + dwarf2_per_objfile->all_type_units.size ());
3550   int count = 0;
3551
3552   for (int i = 0; i < total; ++i)
3553     {
3554       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
3555
3556       if (!per_cu->v.quick->compunit_symtab)
3557         ++count;
3558     }
3559   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3560   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3561 }
3562
3563 /* This dumps minimal information about the index.
3564    It is called via "mt print objfiles".
3565    One use is to verify .gdb_index has been loaded by the
3566    gdb.dwarf2/gdb-index.exp testcase.  */
3567
3568 static void
3569 dw2_dump (struct objfile *objfile)
3570 {
3571   struct dwarf2_per_objfile *dwarf2_per_objfile
3572     = get_dwarf2_per_objfile (objfile);
3573
3574   gdb_assert (dwarf2_per_objfile->using_index);
3575   printf_filtered (".gdb_index:");
3576   if (dwarf2_per_objfile->index_table != NULL)
3577     {
3578       printf_filtered (" version %d\n",
3579                        dwarf2_per_objfile->index_table->version);
3580     }
3581   else
3582     printf_filtered (" faked for \"readnow\"\n");
3583   printf_filtered ("\n");
3584 }
3585
3586 static void
3587 dw2_expand_symtabs_for_function (struct objfile *objfile,
3588                                  const char *func_name)
3589 {
3590   struct dwarf2_per_objfile *dwarf2_per_objfile
3591     = get_dwarf2_per_objfile (objfile);
3592
3593   struct dw2_symtab_iterator iter;
3594   struct dwarf2_per_cu_data *per_cu;
3595
3596   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, {}, VAR_DOMAIN, func_name);
3597
3598   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3599     dw2_instantiate_symtab (per_cu, false);
3600
3601 }
3602
3603 static void
3604 dw2_expand_all_symtabs (struct objfile *objfile)
3605 {
3606   struct dwarf2_per_objfile *dwarf2_per_objfile
3607     = get_dwarf2_per_objfile (objfile);
3608   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
3609                      + dwarf2_per_objfile->all_type_units.size ());
3610
3611   for (int i = 0; i < total_units; ++i)
3612     {
3613       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
3614
3615       /* We don't want to directly expand a partial CU, because if we
3616          read it with the wrong language, then assertion failures can
3617          be triggered later on.  See PR symtab/23010.  So, tell
3618          dw2_instantiate_symtab to skip partial CUs -- any important
3619          partial CU will be read via DW_TAG_imported_unit anyway.  */
3620       dw2_instantiate_symtab (per_cu, true);
3621     }
3622 }
3623
3624 static void
3625 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3626                                   const char *fullname)
3627 {
3628   struct dwarf2_per_objfile *dwarf2_per_objfile
3629     = get_dwarf2_per_objfile (objfile);
3630
3631   /* We don't need to consider type units here.
3632      This is only called for examining code, e.g. expand_line_sal.
3633      There can be an order of magnitude (or more) more type units
3634      than comp units, and we avoid them if we can.  */
3635
3636   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3637     {
3638       /* We only need to look at symtabs not already expanded.  */
3639       if (per_cu->v.quick->compunit_symtab)
3640         continue;
3641
3642       quick_file_names *file_data = dw2_get_file_names (per_cu);
3643       if (file_data == NULL)
3644         continue;
3645
3646       for (int j = 0; j < file_data->num_file_names; ++j)
3647         {
3648           const char *this_fullname = file_data->file_names[j];
3649
3650           if (filename_cmp (this_fullname, fullname) == 0)
3651             {
3652               dw2_instantiate_symtab (per_cu, false);
3653               break;
3654             }
3655         }
3656     }
3657 }
3658
3659 static void
3660 dw2_map_matching_symbols
3661   (struct objfile *objfile,
3662    const lookup_name_info &name, domain_enum domain,
3663    int global,
3664    gdb::function_view<symbol_found_callback_ftype> callback,
3665    symbol_compare_ftype *ordered_compare)
3666 {
3667   /* Currently unimplemented; used for Ada.  The function can be called if the
3668      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3669      does not look for non-Ada symbols this function should just return.  */
3670 }
3671
3672 /* Starting from a search name, return the string that finds the upper
3673    bound of all strings that start with SEARCH_NAME in a sorted name
3674    list.  Returns the empty string to indicate that the upper bound is
3675    the end of the list.  */
3676
3677 static std::string
3678 make_sort_after_prefix_name (const char *search_name)
3679 {
3680   /* When looking to complete "func", we find the upper bound of all
3681      symbols that start with "func" by looking for where we'd insert
3682      the closest string that would follow "func" in lexicographical
3683      order.  Usually, that's "func"-with-last-character-incremented,
3684      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
3685      will be UTF-8 multi-byte sequences, but we can't be certain.
3686      Especially mind the 0xff character, which is a valid character in
3687      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
3688      rule out compilers allowing it in identifiers.  Note that
3689      conveniently, strcmp/strcasecmp are specified to compare
3690      characters interpreted as unsigned char.  So what we do is treat
3691      the whole string as a base 256 number composed of a sequence of
3692      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
3693      to 0, and carries 1 to the following more-significant position.
3694      If the very first character in SEARCH_NAME ends up incremented
3695      and carries/overflows, then the upper bound is the end of the
3696      list.  The string after the empty string is also the empty
3697      string.
3698
3699      Some examples of this operation:
3700
3701        SEARCH_NAME  => "+1" RESULT
3702
3703        "abc"              => "abd"
3704        "ab\xff"           => "ac"
3705        "\xff" "a" "\xff"  => "\xff" "b"
3706        "\xff"             => ""
3707        "\xff\xff"         => ""
3708        ""                 => ""
3709
3710      Then, with these symbols for example:
3711
3712       func
3713       func1
3714       fund
3715
3716      completing "func" looks for symbols between "func" and
3717      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
3718      which finds "func" and "func1", but not "fund".
3719
3720      And with:
3721
3722       funcÿ     (Latin1 'ÿ' [0xff])
3723       funcÿ1
3724       fund
3725
3726      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
3727      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
3728
3729      And with:
3730
3731       ÿÿ        (Latin1 'ÿ' [0xff])
3732       ÿÿ1
3733
3734      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
3735      the end of the list.
3736   */
3737   std::string after = search_name;
3738   while (!after.empty () && (unsigned char) after.back () == 0xff)
3739     after.pop_back ();
3740   if (!after.empty ())
3741     after.back () = (unsigned char) after.back () + 1;
3742   return after;
3743 }
3744
3745 /* See declaration.  */
3746
3747 std::pair<std::vector<name_component>::const_iterator,
3748           std::vector<name_component>::const_iterator>
3749 mapped_index_base::find_name_components_bounds
3750   (const lookup_name_info &lookup_name_without_params, language lang) const
3751 {
3752   auto *name_cmp
3753     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3754
3755   const char *lang_name
3756     = lookup_name_without_params.language_lookup_name (lang).c_str ();
3757
3758   /* Comparison function object for lower_bound that matches against a
3759      given symbol name.  */
3760   auto lookup_compare_lower = [&] (const name_component &elem,
3761                                    const char *name)
3762     {
3763       const char *elem_qualified = this->symbol_name_at (elem.idx);
3764       const char *elem_name = elem_qualified + elem.name_offset;
3765       return name_cmp (elem_name, name) < 0;
3766     };
3767
3768   /* Comparison function object for upper_bound that matches against a
3769      given symbol name.  */
3770   auto lookup_compare_upper = [&] (const char *name,
3771                                    const name_component &elem)
3772     {
3773       const char *elem_qualified = this->symbol_name_at (elem.idx);
3774       const char *elem_name = elem_qualified + elem.name_offset;
3775       return name_cmp (name, elem_name) < 0;
3776     };
3777
3778   auto begin = this->name_components.begin ();
3779   auto end = this->name_components.end ();
3780
3781   /* Find the lower bound.  */
3782   auto lower = [&] ()
3783     {
3784       if (lookup_name_without_params.completion_mode () && lang_name[0] == '\0')
3785         return begin;
3786       else
3787         return std::lower_bound (begin, end, lang_name, lookup_compare_lower);
3788     } ();
3789
3790   /* Find the upper bound.  */
3791   auto upper = [&] ()
3792     {
3793       if (lookup_name_without_params.completion_mode ())
3794         {
3795           /* In completion mode, we want UPPER to point past all
3796              symbols names that have the same prefix.  I.e., with
3797              these symbols, and completing "func":
3798
3799               function        << lower bound
3800               function1
3801               other_function  << upper bound
3802
3803              We find the upper bound by looking for the insertion
3804              point of "func"-with-last-character-incremented,
3805              i.e. "fund".  */
3806           std::string after = make_sort_after_prefix_name (lang_name);
3807           if (after.empty ())
3808             return end;
3809           return std::lower_bound (lower, end, after.c_str (),
3810                                    lookup_compare_lower);
3811         }
3812       else
3813         return std::upper_bound (lower, end, lang_name, lookup_compare_upper);
3814     } ();
3815
3816   return {lower, upper};
3817 }
3818
3819 /* See declaration.  */
3820
3821 void
3822 mapped_index_base::build_name_components ()
3823 {
3824   if (!this->name_components.empty ())
3825     return;
3826
3827   this->name_components_casing = case_sensitivity;
3828   auto *name_cmp
3829     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3830
3831   /* The code below only knows how to break apart components of C++
3832      symbol names (and other languages that use '::' as
3833      namespace/module separator) and Ada symbol names.  */
3834   auto count = this->symbol_name_count ();
3835   for (offset_type idx = 0; idx < count; idx++)
3836     {
3837       if (this->symbol_name_slot_invalid (idx))
3838         continue;
3839
3840       const char *name = this->symbol_name_at (idx);
3841
3842       /* Add each name component to the name component table.  */
3843       unsigned int previous_len = 0;
3844
3845       if (strstr (name, "::") != nullptr)
3846         {
3847           for (unsigned int current_len = cp_find_first_component (name);
3848                name[current_len] != '\0';
3849                current_len += cp_find_first_component (name + current_len))
3850             {
3851               gdb_assert (name[current_len] == ':');
3852               this->name_components.push_back ({previous_len, idx});
3853               /* Skip the '::'.  */
3854               current_len += 2;
3855               previous_len = current_len;
3856             }
3857         }
3858       else
3859         {
3860           /* Handle the Ada encoded (aka mangled) form here.  */
3861           for (const char *iter = strstr (name, "__");
3862                iter != nullptr;
3863                iter = strstr (iter, "__"))
3864             {
3865               this->name_components.push_back ({previous_len, idx});
3866               iter += 2;
3867               previous_len = iter - name;
3868             }
3869         }
3870
3871       this->name_components.push_back ({previous_len, idx});
3872     }
3873
3874   /* Sort name_components elements by name.  */
3875   auto name_comp_compare = [&] (const name_component &left,
3876                                 const name_component &right)
3877     {
3878       const char *left_qualified = this->symbol_name_at (left.idx);
3879       const char *right_qualified = this->symbol_name_at (right.idx);
3880
3881       const char *left_name = left_qualified + left.name_offset;
3882       const char *right_name = right_qualified + right.name_offset;
3883
3884       return name_cmp (left_name, right_name) < 0;
3885     };
3886
3887   std::sort (this->name_components.begin (),
3888              this->name_components.end (),
3889              name_comp_compare);
3890 }
3891
3892 /* Helper for dw2_expand_symtabs_matching that works with a
3893    mapped_index_base instead of the containing objfile.  This is split
3894    to a separate function in order to be able to unit test the
3895    name_components matching using a mock mapped_index_base.  For each
3896    symbol name that matches, calls MATCH_CALLBACK, passing it the
3897    symbol's index in the mapped_index_base symbol table.  */
3898
3899 static void
3900 dw2_expand_symtabs_matching_symbol
3901   (mapped_index_base &index,
3902    const lookup_name_info &lookup_name_in,
3903    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
3904    enum search_domain kind,
3905    gdb::function_view<bool (offset_type)> match_callback)
3906 {
3907   lookup_name_info lookup_name_without_params
3908     = lookup_name_in.make_ignore_params ();
3909
3910   /* Build the symbol name component sorted vector, if we haven't
3911      yet.  */
3912   index.build_name_components ();
3913
3914   /* The same symbol may appear more than once in the range though.
3915      E.g., if we're looking for symbols that complete "w", and we have
3916      a symbol named "w1::w2", we'll find the two name components for
3917      that same symbol in the range.  To be sure we only call the
3918      callback once per symbol, we first collect the symbol name
3919      indexes that matched in a temporary vector and ignore
3920      duplicates.  */
3921   std::vector<offset_type> matches;
3922
3923   struct name_and_matcher
3924   {
3925     symbol_name_matcher_ftype *matcher;
3926     const std::string &name;
3927
3928     bool operator== (const name_and_matcher &other) const
3929     {
3930       return matcher == other.matcher && name == other.name;
3931     }
3932   };
3933
3934   /* A vector holding all the different symbol name matchers, for all
3935      languages.  */
3936   std::vector<name_and_matcher> matchers;
3937
3938   for (int i = 0; i < nr_languages; i++)
3939     {
3940       enum language lang_e = (enum language) i;
3941
3942       const language_defn *lang = language_def (lang_e);
3943       symbol_name_matcher_ftype *name_matcher
3944         = get_symbol_name_matcher (lang, lookup_name_without_params);
3945
3946       name_and_matcher key {
3947          name_matcher,
3948          lookup_name_without_params.language_lookup_name (lang_e)
3949       };
3950
3951       /* Don't insert the same comparison routine more than once.
3952          Note that we do this linear walk.  This is not a problem in
3953          practice because the number of supported languages is
3954          low.  */
3955       if (std::find (matchers.begin (), matchers.end (), key)
3956           != matchers.end ())
3957         continue;
3958       matchers.push_back (std::move (key));
3959
3960       auto bounds
3961         = index.find_name_components_bounds (lookup_name_without_params,
3962                                              lang_e);
3963
3964       /* Now for each symbol name in range, check to see if we have a name
3965          match, and if so, call the MATCH_CALLBACK callback.  */
3966
3967       for (; bounds.first != bounds.second; ++bounds.first)
3968         {
3969           const char *qualified = index.symbol_name_at (bounds.first->idx);
3970
3971           if (!name_matcher (qualified, lookup_name_without_params, NULL)
3972               || (symbol_matcher != NULL && !symbol_matcher (qualified)))
3973             continue;
3974
3975           matches.push_back (bounds.first->idx);
3976         }
3977     }
3978
3979   std::sort (matches.begin (), matches.end ());
3980
3981   /* Finally call the callback, once per match.  */
3982   ULONGEST prev = -1;
3983   for (offset_type idx : matches)
3984     {
3985       if (prev != idx)
3986         {
3987           if (!match_callback (idx))
3988             break;
3989           prev = idx;
3990         }
3991     }
3992
3993   /* Above we use a type wider than idx's for 'prev', since 0 and
3994      (offset_type)-1 are both possible values.  */
3995   static_assert (sizeof (prev) > sizeof (offset_type), "");
3996 }
3997
3998 #if GDB_SELF_TEST
3999
4000 namespace selftests { namespace dw2_expand_symtabs_matching {
4001
4002 /* A mock .gdb_index/.debug_names-like name index table, enough to
4003    exercise dw2_expand_symtabs_matching_symbol, which works with the
4004    mapped_index_base interface.  Builds an index from the symbol list
4005    passed as parameter to the constructor.  */
4006 class mock_mapped_index : public mapped_index_base
4007 {
4008 public:
4009   mock_mapped_index (gdb::array_view<const char *> symbols)
4010     : m_symbol_table (symbols)
4011   {}
4012
4013   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4014
4015   /* Return the number of names in the symbol table.  */
4016   size_t symbol_name_count () const override
4017   {
4018     return m_symbol_table.size ();
4019   }
4020
4021   /* Get the name of the symbol at IDX in the symbol table.  */
4022   const char *symbol_name_at (offset_type idx) const override
4023   {
4024     return m_symbol_table[idx];
4025   }
4026
4027 private:
4028   gdb::array_view<const char *> m_symbol_table;
4029 };
4030
4031 /* Convenience function that converts a NULL pointer to a "<null>"
4032    string, to pass to print routines.  */
4033
4034 static const char *
4035 string_or_null (const char *str)
4036 {
4037   return str != NULL ? str : "<null>";
4038 }
4039
4040 /* Check if a lookup_name_info built from
4041    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4042    index.  EXPECTED_LIST is the list of expected matches, in expected
4043    matching order.  If no match expected, then an empty list is
4044    specified.  Returns true on success.  On failure prints a warning
4045    indicating the file:line that failed, and returns false.  */
4046
4047 static bool
4048 check_match (const char *file, int line,
4049              mock_mapped_index &mock_index,
4050              const char *name, symbol_name_match_type match_type,
4051              bool completion_mode,
4052              std::initializer_list<const char *> expected_list)
4053 {
4054   lookup_name_info lookup_name (name, match_type, completion_mode);
4055
4056   bool matched = true;
4057
4058   auto mismatch = [&] (const char *expected_str,
4059                        const char *got)
4060   {
4061     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4062                "expected=\"%s\", got=\"%s\"\n"),
4063              file, line,
4064              (match_type == symbol_name_match_type::FULL
4065               ? "FULL" : "WILD"),
4066              name, string_or_null (expected_str), string_or_null (got));
4067     matched = false;
4068   };
4069
4070   auto expected_it = expected_list.begin ();
4071   auto expected_end = expected_list.end ();
4072
4073   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4074                                       NULL, ALL_DOMAIN,
4075                                       [&] (offset_type idx)
4076   {
4077     const char *matched_name = mock_index.symbol_name_at (idx);
4078     const char *expected_str
4079       = expected_it == expected_end ? NULL : *expected_it++;
4080
4081     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4082       mismatch (expected_str, matched_name);
4083     return true;
4084   });
4085
4086   const char *expected_str
4087   = expected_it == expected_end ? NULL : *expected_it++;
4088   if (expected_str != NULL)
4089     mismatch (expected_str, NULL);
4090
4091   return matched;
4092 }
4093
4094 /* The symbols added to the mock mapped_index for testing (in
4095    canonical form).  */
4096 static const char *test_symbols[] = {
4097   "function",
4098   "std::bar",
4099   "std::zfunction",
4100   "std::zfunction2",
4101   "w1::w2",
4102   "ns::foo<char*>",
4103   "ns::foo<int>",
4104   "ns::foo<long>",
4105   "ns2::tmpl<int>::foo2",
4106   "(anonymous namespace)::A::B::C",
4107
4108   /* These are used to check that the increment-last-char in the
4109      matching algorithm for completion doesn't match "t1_fund" when
4110      completing "t1_func".  */
4111   "t1_func",
4112   "t1_func1",
4113   "t1_fund",
4114   "t1_fund1",
4115
4116   /* A UTF-8 name with multi-byte sequences to make sure that
4117      cp-name-parser understands this as a single identifier ("função"
4118      is "function" in PT).  */
4119   u8"u8função",
4120
4121   /* \377 (0xff) is Latin1 'ÿ'.  */
4122   "yfunc\377",
4123
4124   /* \377 (0xff) is Latin1 'ÿ'.  */
4125   "\377",
4126   "\377\377123",
4127
4128   /* A name with all sorts of complications.  Starts with "z" to make
4129      it easier for the completion tests below.  */
4130 #define Z_SYM_NAME \
4131   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4132     "::tuple<(anonymous namespace)::ui*, " \
4133     "std::default_delete<(anonymous namespace)::ui>, void>"
4134
4135   Z_SYM_NAME
4136 };
4137
4138 /* Returns true if the mapped_index_base::find_name_component_bounds
4139    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4140    in completion mode.  */
4141
4142 static bool
4143 check_find_bounds_finds (mapped_index_base &index,
4144                          const char *search_name,
4145                          gdb::array_view<const char *> expected_syms)
4146 {
4147   lookup_name_info lookup_name (search_name,
4148                                 symbol_name_match_type::FULL, true);
4149
4150   auto bounds = index.find_name_components_bounds (lookup_name,
4151                                                    language_cplus);
4152
4153   size_t distance = std::distance (bounds.first, bounds.second);
4154   if (distance != expected_syms.size ())
4155     return false;
4156
4157   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4158     {
4159       auto nc_elem = bounds.first + exp_elem;
4160       const char *qualified = index.symbol_name_at (nc_elem->idx);
4161       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4162         return false;
4163     }
4164
4165   return true;
4166 }
4167
4168 /* Test the lower-level mapped_index::find_name_component_bounds
4169    method.  */
4170
4171 static void
4172 test_mapped_index_find_name_component_bounds ()
4173 {
4174   mock_mapped_index mock_index (test_symbols);
4175
4176   mock_index.build_name_components ();
4177
4178   /* Test the lower-level mapped_index::find_name_component_bounds
4179      method in completion mode.  */
4180   {
4181     static const char *expected_syms[] = {
4182       "t1_func",
4183       "t1_func1",
4184     };
4185
4186     SELF_CHECK (check_find_bounds_finds (mock_index,
4187                                          "t1_func", expected_syms));
4188   }
4189
4190   /* Check that the increment-last-char in the name matching algorithm
4191      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4192   {
4193     static const char *expected_syms1[] = {
4194       "\377",
4195       "\377\377123",
4196     };
4197     SELF_CHECK (check_find_bounds_finds (mock_index,
4198                                          "\377", expected_syms1));
4199
4200     static const char *expected_syms2[] = {
4201       "\377\377123",
4202     };
4203     SELF_CHECK (check_find_bounds_finds (mock_index,
4204                                          "\377\377", expected_syms2));
4205   }
4206 }
4207
4208 /* Test dw2_expand_symtabs_matching_symbol.  */
4209
4210 static void
4211 test_dw2_expand_symtabs_matching_symbol ()
4212 {
4213   mock_mapped_index mock_index (test_symbols);
4214
4215   /* We let all tests run until the end even if some fails, for debug
4216      convenience.  */
4217   bool any_mismatch = false;
4218
4219   /* Create the expected symbols list (an initializer_list).  Needed
4220      because lists have commas, and we need to pass them to CHECK,
4221      which is a macro.  */
4222 #define EXPECT(...) { __VA_ARGS__ }
4223
4224   /* Wrapper for check_match that passes down the current
4225      __FILE__/__LINE__.  */
4226 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4227   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4228                                 mock_index,                             \
4229                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4230                                 EXPECTED_LIST)
4231
4232   /* Identity checks.  */
4233   for (const char *sym : test_symbols)
4234     {
4235       /* Should be able to match all existing symbols.  */
4236       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4237                    EXPECT (sym));
4238
4239       /* Should be able to match all existing symbols with
4240          parameters.  */
4241       std::string with_params = std::string (sym) + "(int)";
4242       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4243                    EXPECT (sym));
4244
4245       /* Should be able to match all existing symbols with
4246          parameters and qualifiers.  */
4247       with_params = std::string (sym) + " ( int ) const";
4248       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4249                    EXPECT (sym));
4250
4251       /* This should really find sym, but cp-name-parser.y doesn't
4252          know about lvalue/rvalue qualifiers yet.  */
4253       with_params = std::string (sym) + " ( int ) &&";
4254       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4255                    {});
4256     }
4257
4258   /* Check that the name matching algorithm for completion doesn't get
4259      confused with Latin1 'ÿ' / 0xff.  */
4260   {
4261     static const char str[] = "\377";
4262     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4263                  EXPECT ("\377", "\377\377123"));
4264   }
4265
4266   /* Check that the increment-last-char in the matching algorithm for
4267      completion doesn't match "t1_fund" when completing "t1_func".  */
4268   {
4269     static const char str[] = "t1_func";
4270     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4271                  EXPECT ("t1_func", "t1_func1"));
4272   }
4273
4274   /* Check that completion mode works at each prefix of the expected
4275      symbol name.  */
4276   {
4277     static const char str[] = "function(int)";
4278     size_t len = strlen (str);
4279     std::string lookup;
4280
4281     for (size_t i = 1; i < len; i++)
4282       {
4283         lookup.assign (str, i);
4284         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4285                      EXPECT ("function"));
4286       }
4287   }
4288
4289   /* While "w" is a prefix of both components, the match function
4290      should still only be called once.  */
4291   {
4292     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4293                  EXPECT ("w1::w2"));
4294     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4295                  EXPECT ("w1::w2"));
4296   }
4297
4298   /* Same, with a "complicated" symbol.  */
4299   {
4300     static const char str[] = Z_SYM_NAME;
4301     size_t len = strlen (str);
4302     std::string lookup;
4303
4304     for (size_t i = 1; i < len; i++)
4305       {
4306         lookup.assign (str, i);
4307         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4308                      EXPECT (Z_SYM_NAME));
4309       }
4310   }
4311
4312   /* In FULL mode, an incomplete symbol doesn't match.  */
4313   {
4314     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4315                  {});
4316   }
4317
4318   /* A complete symbol with parameters matches any overload, since the
4319      index has no overload info.  */
4320   {
4321     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4322                  EXPECT ("std::zfunction", "std::zfunction2"));
4323     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4324                  EXPECT ("std::zfunction", "std::zfunction2"));
4325     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4326                  EXPECT ("std::zfunction", "std::zfunction2"));
4327   }
4328
4329   /* Check that whitespace is ignored appropriately.  A symbol with a
4330      template argument list. */
4331   {
4332     static const char expected[] = "ns::foo<int>";
4333     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4334                  EXPECT (expected));
4335     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4336                  EXPECT (expected));
4337   }
4338
4339   /* Check that whitespace is ignored appropriately.  A symbol with a
4340      template argument list that includes a pointer.  */
4341   {
4342     static const char expected[] = "ns::foo<char*>";
4343     /* Try both completion and non-completion modes.  */
4344     static const bool completion_mode[2] = {false, true};
4345     for (size_t i = 0; i < 2; i++)
4346       {
4347         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4348                      completion_mode[i], EXPECT (expected));
4349         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4350                      completion_mode[i], EXPECT (expected));
4351
4352         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4353                      completion_mode[i], EXPECT (expected));
4354         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4355                      completion_mode[i], EXPECT (expected));
4356       }
4357   }
4358
4359   {
4360     /* Check method qualifiers are ignored.  */
4361     static const char expected[] = "ns::foo<char*>";
4362     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4363                  symbol_name_match_type::FULL, true, EXPECT (expected));
4364     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4365                  symbol_name_match_type::FULL, true, EXPECT (expected));
4366     CHECK_MATCH ("foo < char * >  ( int ) const",
4367                  symbol_name_match_type::WILD, true, EXPECT (expected));
4368     CHECK_MATCH ("foo < char * >  ( int ) &&",
4369                  symbol_name_match_type::WILD, true, EXPECT (expected));
4370   }
4371
4372   /* Test lookup names that don't match anything.  */
4373   {
4374     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4375                  {});
4376
4377     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4378                  {});
4379   }
4380
4381   /* Some wild matching tests, exercising "(anonymous namespace)",
4382      which should not be confused with a parameter list.  */
4383   {
4384     static const char *syms[] = {
4385       "A::B::C",
4386       "B::C",
4387       "C",
4388       "A :: B :: C ( int )",
4389       "B :: C ( int )",
4390       "C ( int )",
4391     };
4392
4393     for (const char *s : syms)
4394       {
4395         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4396                      EXPECT ("(anonymous namespace)::A::B::C"));
4397       }
4398   }
4399
4400   {
4401     static const char expected[] = "ns2::tmpl<int>::foo2";
4402     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4403                  EXPECT (expected));
4404     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4405                  EXPECT (expected));
4406   }
4407
4408   SELF_CHECK (!any_mismatch);
4409
4410 #undef EXPECT
4411 #undef CHECK_MATCH
4412 }
4413
4414 static void
4415 run_test ()
4416 {
4417   test_mapped_index_find_name_component_bounds ();
4418   test_dw2_expand_symtabs_matching_symbol ();
4419 }
4420
4421 }} // namespace selftests::dw2_expand_symtabs_matching
4422
4423 #endif /* GDB_SELF_TEST */
4424
4425 /* If FILE_MATCHER is NULL or if PER_CU has
4426    dwarf2_per_cu_quick_data::MARK set (see
4427    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4428    EXPANSION_NOTIFY on it.  */
4429
4430 static void
4431 dw2_expand_symtabs_matching_one
4432   (struct dwarf2_per_cu_data *per_cu,
4433    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4434    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4435 {
4436   if (file_matcher == NULL || per_cu->v.quick->mark)
4437     {
4438       bool symtab_was_null
4439         = (per_cu->v.quick->compunit_symtab == NULL);
4440
4441       dw2_instantiate_symtab (per_cu, false);
4442
4443       if (expansion_notify != NULL
4444           && symtab_was_null
4445           && per_cu->v.quick->compunit_symtab != NULL)
4446         expansion_notify (per_cu->v.quick->compunit_symtab);
4447     }
4448 }
4449
4450 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4451    matched, to expand corresponding CUs that were marked.  IDX is the
4452    index of the symbol name that matched.  */
4453
4454 static void
4455 dw2_expand_marked_cus
4456   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
4457    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4458    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4459    search_domain kind)
4460 {
4461   offset_type *vec, vec_len, vec_idx;
4462   bool global_seen = false;
4463   mapped_index &index = *dwarf2_per_objfile->index_table;
4464
4465   vec = (offset_type *) (index.constant_pool
4466                          + MAYBE_SWAP (index.symbol_table[idx].vec));
4467   vec_len = MAYBE_SWAP (vec[0]);
4468   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4469     {
4470       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4471       /* This value is only valid for index versions >= 7.  */
4472       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4473       gdb_index_symbol_kind symbol_kind =
4474         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4475       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4476       /* Only check the symbol attributes if they're present.
4477          Indices prior to version 7 don't record them,
4478          and indices >= 7 may elide them for certain symbols
4479          (gold does this).  */
4480       int attrs_valid =
4481         (index.version >= 7
4482          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4483
4484       /* Work around gold/15646.  */
4485       if (attrs_valid)
4486         {
4487           if (!is_static && global_seen)
4488             continue;
4489           if (!is_static)
4490             global_seen = true;
4491         }
4492
4493       /* Only check the symbol's kind if it has one.  */
4494       if (attrs_valid)
4495         {
4496           switch (kind)
4497             {
4498             case VARIABLES_DOMAIN:
4499               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4500                 continue;
4501               break;
4502             case FUNCTIONS_DOMAIN:
4503               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4504                 continue;
4505               break;
4506             case TYPES_DOMAIN:
4507               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4508                 continue;
4509               break;
4510             case MODULES_DOMAIN:
4511               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4512                 continue;
4513               break;
4514             default:
4515               break;
4516             }
4517         }
4518
4519       /* Don't crash on bad data.  */
4520       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
4521                        + dwarf2_per_objfile->all_type_units.size ()))
4522         {
4523           complaint (_(".gdb_index entry has bad CU index"
4524                        " [in module %s]"),
4525                        objfile_name (dwarf2_per_objfile->objfile));
4526           continue;
4527         }
4528
4529       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
4530       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
4531                                        expansion_notify);
4532     }
4533 }
4534
4535 /* If FILE_MATCHER is non-NULL, set all the
4536    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
4537    that match FILE_MATCHER.  */
4538
4539 static void
4540 dw_expand_symtabs_matching_file_matcher
4541   (struct dwarf2_per_objfile *dwarf2_per_objfile,
4542    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
4543 {
4544   if (file_matcher == NULL)
4545     return;
4546
4547   objfile *const objfile = dwarf2_per_objfile->objfile;
4548
4549   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4550                                             htab_eq_pointer,
4551                                             NULL, xcalloc, xfree));
4552   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4553                                                 htab_eq_pointer,
4554                                                 NULL, xcalloc, xfree));
4555
4556   /* The rule is CUs specify all the files, including those used by
4557      any TU, so there's no need to scan TUs here.  */
4558
4559   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4560     {
4561       QUIT;
4562
4563       per_cu->v.quick->mark = 0;
4564
4565       /* We only need to look at symtabs not already expanded.  */
4566       if (per_cu->v.quick->compunit_symtab)
4567         continue;
4568
4569       quick_file_names *file_data = dw2_get_file_names (per_cu);
4570       if (file_data == NULL)
4571         continue;
4572
4573       if (htab_find (visited_not_found.get (), file_data) != NULL)
4574         continue;
4575       else if (htab_find (visited_found.get (), file_data) != NULL)
4576         {
4577           per_cu->v.quick->mark = 1;
4578           continue;
4579         }
4580
4581       for (int j = 0; j < file_data->num_file_names; ++j)
4582         {
4583           const char *this_real_name;
4584
4585           if (file_matcher (file_data->file_names[j], false))
4586             {
4587               per_cu->v.quick->mark = 1;
4588               break;
4589             }
4590
4591           /* Before we invoke realpath, which can get expensive when many
4592              files are involved, do a quick comparison of the basenames.  */
4593           if (!basenames_may_differ
4594               && !file_matcher (lbasename (file_data->file_names[j]),
4595                                 true))
4596             continue;
4597
4598           this_real_name = dw2_get_real_path (objfile, file_data, j);
4599           if (file_matcher (this_real_name, false))
4600             {
4601               per_cu->v.quick->mark = 1;
4602               break;
4603             }
4604         }
4605
4606       void **slot = htab_find_slot (per_cu->v.quick->mark
4607                                     ? visited_found.get ()
4608                                     : visited_not_found.get (),
4609                                     file_data, INSERT);
4610       *slot = file_data;
4611     }
4612 }
4613
4614 static void
4615 dw2_expand_symtabs_matching
4616   (struct objfile *objfile,
4617    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4618    const lookup_name_info &lookup_name,
4619    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4620    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4621    enum search_domain kind)
4622 {
4623   struct dwarf2_per_objfile *dwarf2_per_objfile
4624     = get_dwarf2_per_objfile (objfile);
4625
4626   /* index_table is NULL if OBJF_READNOW.  */
4627   if (!dwarf2_per_objfile->index_table)
4628     return;
4629
4630   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
4631
4632   mapped_index &index = *dwarf2_per_objfile->index_table;
4633
4634   dw2_expand_symtabs_matching_symbol (index, lookup_name,
4635                                       symbol_matcher,
4636                                       kind, [&] (offset_type idx)
4637     {
4638       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
4639                              expansion_notify, kind);
4640       return true;
4641     });
4642 }
4643
4644 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4645    symtab.  */
4646
4647 static struct compunit_symtab *
4648 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4649                                           CORE_ADDR pc)
4650 {
4651   int i;
4652
4653   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4654       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4655     return cust;
4656
4657   if (cust->includes == NULL)
4658     return NULL;
4659
4660   for (i = 0; cust->includes[i]; ++i)
4661     {
4662       struct compunit_symtab *s = cust->includes[i];
4663
4664       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4665       if (s != NULL)
4666         return s;
4667     }
4668
4669   return NULL;
4670 }
4671
4672 static struct compunit_symtab *
4673 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4674                                   struct bound_minimal_symbol msymbol,
4675                                   CORE_ADDR pc,
4676                                   struct obj_section *section,
4677                                   int warn_if_readin)
4678 {
4679   struct dwarf2_per_cu_data *data;
4680   struct compunit_symtab *result;
4681
4682   if (!objfile->partial_symtabs->psymtabs_addrmap)
4683     return NULL;
4684
4685   CORE_ADDR baseaddr = objfile->text_section_offset ();
4686   data = (struct dwarf2_per_cu_data *) addrmap_find
4687     (objfile->partial_symtabs->psymtabs_addrmap, pc - baseaddr);
4688   if (!data)
4689     return NULL;
4690
4691   if (warn_if_readin && data->v.quick->compunit_symtab)
4692     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4693              paddress (get_objfile_arch (objfile), pc));
4694
4695   result
4696     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
4697                                                                         false),
4698                                                 pc);
4699   gdb_assert (result != NULL);
4700   return result;
4701 }
4702
4703 static void
4704 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4705                           void *data, int need_fullname)
4706 {
4707   struct dwarf2_per_objfile *dwarf2_per_objfile
4708     = get_dwarf2_per_objfile (objfile);
4709
4710   if (!dwarf2_per_objfile->filenames_cache)
4711     {
4712       dwarf2_per_objfile->filenames_cache.emplace ();
4713
4714       htab_up visited (htab_create_alloc (10,
4715                                           htab_hash_pointer, htab_eq_pointer,
4716                                           NULL, xcalloc, xfree));
4717
4718       /* The rule is CUs specify all the files, including those used
4719          by any TU, so there's no need to scan TUs here.  We can
4720          ignore file names coming from already-expanded CUs.  */
4721
4722       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4723         {
4724           if (per_cu->v.quick->compunit_symtab)
4725             {
4726               void **slot = htab_find_slot (visited.get (),
4727                                             per_cu->v.quick->file_names,
4728                                             INSERT);
4729
4730               *slot = per_cu->v.quick->file_names;
4731             }
4732         }
4733
4734       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4735         {
4736           /* We only need to look at symtabs not already expanded.  */
4737           if (per_cu->v.quick->compunit_symtab)
4738             continue;
4739
4740           quick_file_names *file_data = dw2_get_file_names (per_cu);
4741           if (file_data == NULL)
4742             continue;
4743
4744           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
4745           if (*slot)
4746             {
4747               /* Already visited.  */
4748               continue;
4749             }
4750           *slot = file_data;
4751
4752           for (int j = 0; j < file_data->num_file_names; ++j)
4753             {
4754               const char *filename = file_data->file_names[j];
4755               dwarf2_per_objfile->filenames_cache->seen (filename);
4756             }
4757         }
4758     }
4759
4760   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4761     {
4762       gdb::unique_xmalloc_ptr<char> this_real_name;
4763
4764       if (need_fullname)
4765         this_real_name = gdb_realpath (filename);
4766       (*fun) (filename, this_real_name.get (), data);
4767     });
4768 }
4769
4770 static int
4771 dw2_has_symbols (struct objfile *objfile)
4772 {
4773   return 1;
4774 }
4775
4776 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4777 {
4778   dw2_has_symbols,
4779   dw2_find_last_source_symtab,
4780   dw2_forget_cached_source_info,
4781   dw2_map_symtabs_matching_filename,
4782   dw2_lookup_symbol,
4783   dw2_print_stats,
4784   dw2_dump,
4785   dw2_expand_symtabs_for_function,
4786   dw2_expand_all_symtabs,
4787   dw2_expand_symtabs_with_fullname,
4788   dw2_map_matching_symbols,
4789   dw2_expand_symtabs_matching,
4790   dw2_find_pc_sect_compunit_symtab,
4791   NULL,
4792   dw2_map_symbol_filenames
4793 };
4794
4795 /* DWARF-5 debug_names reader.  */
4796
4797 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
4798 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
4799
4800 /* A helper function that reads the .debug_names section in SECTION
4801    and fills in MAP.  FILENAME is the name of the file containing the
4802    section; it is used for error reporting.
4803
4804    Returns true if all went well, false otherwise.  */
4805
4806 static bool
4807 read_debug_names_from_section (struct objfile *objfile,
4808                                const char *filename,
4809                                struct dwarf2_section_info *section,
4810                                mapped_debug_names &map)
4811 {
4812   if (section->empty ())
4813     return false;
4814
4815   /* Older elfutils strip versions could keep the section in the main
4816      executable while splitting it for the separate debug info file.  */
4817   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
4818     return false;
4819
4820   section->read (objfile);
4821
4822   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
4823
4824   const gdb_byte *addr = section->buffer;
4825
4826   bfd *const abfd = section->get_bfd_owner ();
4827
4828   unsigned int bytes_read;
4829   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
4830   addr += bytes_read;
4831
4832   map.dwarf5_is_dwarf64 = bytes_read != 4;
4833   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
4834   if (bytes_read + length != section->size)
4835     {
4836       /* There may be multiple per-CU indices.  */
4837       warning (_("Section .debug_names in %s length %s does not match "
4838                  "section length %s, ignoring .debug_names."),
4839                filename, plongest (bytes_read + length),
4840                pulongest (section->size));
4841       return false;
4842     }
4843
4844   /* The version number.  */
4845   uint16_t version = read_2_bytes (abfd, addr);
4846   addr += 2;
4847   if (version != 5)
4848     {
4849       warning (_("Section .debug_names in %s has unsupported version %d, "
4850                  "ignoring .debug_names."),
4851                filename, version);
4852       return false;
4853     }
4854
4855   /* Padding.  */
4856   uint16_t padding = read_2_bytes (abfd, addr);
4857   addr += 2;
4858   if (padding != 0)
4859     {
4860       warning (_("Section .debug_names in %s has unsupported padding %d, "
4861                  "ignoring .debug_names."),
4862                filename, padding);
4863       return false;
4864     }
4865
4866   /* comp_unit_count - The number of CUs in the CU list.  */
4867   map.cu_count = read_4_bytes (abfd, addr);
4868   addr += 4;
4869
4870   /* local_type_unit_count - The number of TUs in the local TU
4871      list.  */
4872   map.tu_count = read_4_bytes (abfd, addr);
4873   addr += 4;
4874
4875   /* foreign_type_unit_count - The number of TUs in the foreign TU
4876      list.  */
4877   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
4878   addr += 4;
4879   if (foreign_tu_count != 0)
4880     {
4881       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
4882                  "ignoring .debug_names."),
4883                filename, static_cast<unsigned long> (foreign_tu_count));
4884       return false;
4885     }
4886
4887   /* bucket_count - The number of hash buckets in the hash lookup
4888      table.  */
4889   map.bucket_count = read_4_bytes (abfd, addr);
4890   addr += 4;
4891
4892   /* name_count - The number of unique names in the index.  */
4893   map.name_count = read_4_bytes (abfd, addr);
4894   addr += 4;
4895
4896   /* abbrev_table_size - The size in bytes of the abbreviations
4897      table.  */
4898   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
4899   addr += 4;
4900
4901   /* augmentation_string_size - The size in bytes of the augmentation
4902      string.  This value is rounded up to a multiple of 4.  */
4903   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
4904   addr += 4;
4905   map.augmentation_is_gdb = ((augmentation_string_size
4906                               == sizeof (dwarf5_augmentation))
4907                              && memcmp (addr, dwarf5_augmentation,
4908                                         sizeof (dwarf5_augmentation)) == 0);
4909   augmentation_string_size += (-augmentation_string_size) & 3;
4910   addr += augmentation_string_size;
4911
4912   /* List of CUs */
4913   map.cu_table_reordered = addr;
4914   addr += map.cu_count * map.offset_size;
4915
4916   /* List of Local TUs */
4917   map.tu_table_reordered = addr;
4918   addr += map.tu_count * map.offset_size;
4919
4920   /* Hash Lookup Table */
4921   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
4922   addr += map.bucket_count * 4;
4923   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
4924   addr += map.name_count * 4;
4925
4926   /* Name Table */
4927   map.name_table_string_offs_reordered = addr;
4928   addr += map.name_count * map.offset_size;
4929   map.name_table_entry_offs_reordered = addr;
4930   addr += map.name_count * map.offset_size;
4931
4932   const gdb_byte *abbrev_table_start = addr;
4933   for (;;)
4934     {
4935       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
4936       addr += bytes_read;
4937       if (index_num == 0)
4938         break;
4939
4940       const auto insertpair
4941         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
4942       if (!insertpair.second)
4943         {
4944           warning (_("Section .debug_names in %s has duplicate index %s, "
4945                      "ignoring .debug_names."),
4946                    filename, pulongest (index_num));
4947           return false;
4948         }
4949       mapped_debug_names::index_val &indexval = insertpair.first->second;
4950       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
4951       addr += bytes_read;
4952
4953       for (;;)
4954         {
4955           mapped_debug_names::index_val::attr attr;
4956           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
4957           addr += bytes_read;
4958           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
4959           addr += bytes_read;
4960           if (attr.form == DW_FORM_implicit_const)
4961             {
4962               attr.implicit_const = read_signed_leb128 (abfd, addr,
4963                                                         &bytes_read);
4964               addr += bytes_read;
4965             }
4966           if (attr.dw_idx == 0 && attr.form == 0)
4967             break;
4968           indexval.attr_vec.push_back (std::move (attr));
4969         }
4970     }
4971   if (addr != abbrev_table_start + abbrev_table_size)
4972     {
4973       warning (_("Section .debug_names in %s has abbreviation_table "
4974                  "of size %s vs. written as %u, ignoring .debug_names."),
4975                filename, plongest (addr - abbrev_table_start),
4976                abbrev_table_size);
4977       return false;
4978     }
4979   map.entry_pool = addr;
4980
4981   return true;
4982 }
4983
4984 /* A helper for create_cus_from_debug_names that handles the MAP's CU
4985    list.  */
4986
4987 static void
4988 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
4989                                   const mapped_debug_names &map,
4990                                   dwarf2_section_info &section,
4991                                   bool is_dwz)
4992 {
4993   sect_offset sect_off_prev;
4994   for (uint32_t i = 0; i <= map.cu_count; ++i)
4995     {
4996       sect_offset sect_off_next;
4997       if (i < map.cu_count)
4998         {
4999           sect_off_next
5000             = (sect_offset) (extract_unsigned_integer
5001                              (map.cu_table_reordered + i * map.offset_size,
5002                               map.offset_size,
5003                               map.dwarf5_byte_order));
5004         }
5005       else
5006         sect_off_next = (sect_offset) section.size;
5007       if (i >= 1)
5008         {
5009           const ULONGEST length = sect_off_next - sect_off_prev;
5010           dwarf2_per_cu_data *per_cu
5011             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5012                                          sect_off_prev, length);
5013           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5014         }
5015       sect_off_prev = sect_off_next;
5016     }
5017 }
5018
5019 /* Read the CU list from the mapped index, and use it to create all
5020    the CU objects for this dwarf2_per_objfile.  */
5021
5022 static void
5023 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5024                              const mapped_debug_names &map,
5025                              const mapped_debug_names &dwz_map)
5026 {
5027   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5028   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5029
5030   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5031                                     dwarf2_per_objfile->info,
5032                                     false /* is_dwz */);
5033
5034   if (dwz_map.cu_count == 0)
5035     return;
5036
5037   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5038   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5039                                     true /* is_dwz */);
5040 }
5041
5042 /* Read .debug_names.  If everything went ok, initialize the "quick"
5043    elements of all the CUs and return true.  Otherwise, return false.  */
5044
5045 static bool
5046 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5047 {
5048   std::unique_ptr<mapped_debug_names> map
5049     (new mapped_debug_names (dwarf2_per_objfile));
5050   mapped_debug_names dwz_map (dwarf2_per_objfile);
5051   struct objfile *objfile = dwarf2_per_objfile->objfile;
5052
5053   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5054                                       &dwarf2_per_objfile->debug_names,
5055                                       *map))
5056     return false;
5057
5058   /* Don't use the index if it's empty.  */
5059   if (map->name_count == 0)
5060     return false;
5061
5062   /* If there is a .dwz file, read it so we can get its CU list as
5063      well.  */
5064   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5065   if (dwz != NULL)
5066     {
5067       if (!read_debug_names_from_section (objfile,
5068                                           bfd_get_filename (dwz->dwz_bfd.get ()),
5069                                           &dwz->debug_names, dwz_map))
5070         {
5071           warning (_("could not read '.debug_names' section from %s; skipping"),
5072                    bfd_get_filename (dwz->dwz_bfd.get ()));
5073           return false;
5074         }
5075     }
5076
5077   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5078
5079   if (map->tu_count != 0)
5080     {
5081       /* We can only handle a single .debug_types when we have an
5082          index.  */
5083       if (dwarf2_per_objfile->types.size () != 1)
5084         return false;
5085
5086       dwarf2_section_info *section = &dwarf2_per_objfile->types[0];
5087
5088       create_signatured_type_table_from_debug_names
5089         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5090     }
5091
5092   create_addrmap_from_aranges (dwarf2_per_objfile,
5093                                &dwarf2_per_objfile->debug_aranges);
5094
5095   dwarf2_per_objfile->debug_names_table = std::move (map);
5096   dwarf2_per_objfile->using_index = 1;
5097   dwarf2_per_objfile->quick_file_names_table =
5098     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5099
5100   return true;
5101 }
5102
5103 /* Type used to manage iterating over all CUs looking for a symbol for
5104    .debug_names.  */
5105
5106 class dw2_debug_names_iterator
5107 {
5108 public:
5109   dw2_debug_names_iterator (const mapped_debug_names &map,
5110                             gdb::optional<block_enum> block_index,
5111                             domain_enum domain,
5112                             const char *name)
5113     : m_map (map), m_block_index (block_index), m_domain (domain),
5114       m_addr (find_vec_in_debug_names (map, name))
5115   {}
5116
5117   dw2_debug_names_iterator (const mapped_debug_names &map,
5118                             search_domain search, uint32_t namei)
5119     : m_map (map),
5120       m_search (search),
5121       m_addr (find_vec_in_debug_names (map, namei))
5122   {}
5123
5124   dw2_debug_names_iterator (const mapped_debug_names &map,
5125                             block_enum block_index, domain_enum domain,
5126                             uint32_t namei)
5127     : m_map (map), m_block_index (block_index), m_domain (domain),
5128       m_addr (find_vec_in_debug_names (map, namei))
5129   {}
5130
5131   /* Return the next matching CU or NULL if there are no more.  */
5132   dwarf2_per_cu_data *next ();
5133
5134 private:
5135   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5136                                                   const char *name);
5137   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5138                                                   uint32_t namei);
5139
5140   /* The internalized form of .debug_names.  */
5141   const mapped_debug_names &m_map;
5142
5143   /* If set, only look for symbols that match that block.  Valid values are
5144      GLOBAL_BLOCK and STATIC_BLOCK.  */
5145   const gdb::optional<block_enum> m_block_index;
5146
5147   /* The kind of symbol we're looking for.  */
5148   const domain_enum m_domain = UNDEF_DOMAIN;
5149   const search_domain m_search = ALL_DOMAIN;
5150
5151   /* The list of CUs from the index entry of the symbol, or NULL if
5152      not found.  */
5153   const gdb_byte *m_addr;
5154 };
5155
5156 const char *
5157 mapped_debug_names::namei_to_name (uint32_t namei) const
5158 {
5159   const ULONGEST namei_string_offs
5160     = extract_unsigned_integer ((name_table_string_offs_reordered
5161                                  + namei * offset_size),
5162                                 offset_size,
5163                                 dwarf5_byte_order);
5164   return read_indirect_string_at_offset
5165     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5166 }
5167
5168 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5169    found, return pointer to its pool data.  If NAME cannot be found,
5170    return NULL.  */
5171
5172 const gdb_byte *
5173 dw2_debug_names_iterator::find_vec_in_debug_names
5174   (const mapped_debug_names &map, const char *name)
5175 {
5176   int (*cmp) (const char *, const char *);
5177
5178   gdb::unique_xmalloc_ptr<char> without_params;
5179   if (current_language->la_language == language_cplus
5180       || current_language->la_language == language_fortran
5181       || current_language->la_language == language_d)
5182     {
5183       /* NAME is already canonical.  Drop any qualifiers as
5184          .debug_names does not contain any.  */
5185
5186       if (strchr (name, '(') != NULL)
5187         {
5188           without_params = cp_remove_params (name);
5189           if (without_params != NULL)
5190             name = without_params.get ();
5191         }
5192     }
5193
5194   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5195
5196   const uint32_t full_hash = dwarf5_djb_hash (name);
5197   uint32_t namei
5198     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5199                                 (map.bucket_table_reordered
5200                                  + (full_hash % map.bucket_count)), 4,
5201                                 map.dwarf5_byte_order);
5202   if (namei == 0)
5203     return NULL;
5204   --namei;
5205   if (namei >= map.name_count)
5206     {
5207       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5208                    "[in module %s]"),
5209                  namei, map.name_count,
5210                  objfile_name (map.dwarf2_per_objfile->objfile));
5211       return NULL;
5212     }
5213
5214   for (;;)
5215     {
5216       const uint32_t namei_full_hash
5217         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5218                                     (map.hash_table_reordered + namei), 4,
5219                                     map.dwarf5_byte_order);
5220       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5221         return NULL;
5222
5223       if (full_hash == namei_full_hash)
5224         {
5225           const char *const namei_string = map.namei_to_name (namei);
5226
5227 #if 0 /* An expensive sanity check.  */
5228           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5229             {
5230               complaint (_("Wrong .debug_names hash for string at index %u "
5231                            "[in module %s]"),
5232                          namei, objfile_name (dwarf2_per_objfile->objfile));
5233               return NULL;
5234             }
5235 #endif
5236
5237           if (cmp (namei_string, name) == 0)
5238             {
5239               const ULONGEST namei_entry_offs
5240                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5241                                              + namei * map.offset_size),
5242                                             map.offset_size, map.dwarf5_byte_order);
5243               return map.entry_pool + namei_entry_offs;
5244             }
5245         }
5246
5247       ++namei;
5248       if (namei >= map.name_count)
5249         return NULL;
5250     }
5251 }
5252
5253 const gdb_byte *
5254 dw2_debug_names_iterator::find_vec_in_debug_names
5255   (const mapped_debug_names &map, uint32_t namei)
5256 {
5257   if (namei >= map.name_count)
5258     {
5259       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5260                    "[in module %s]"),
5261                  namei, map.name_count,
5262                  objfile_name (map.dwarf2_per_objfile->objfile));
5263       return NULL;
5264     }
5265
5266   const ULONGEST namei_entry_offs
5267     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5268                                  + namei * map.offset_size),
5269                                 map.offset_size, map.dwarf5_byte_order);
5270   return map.entry_pool + namei_entry_offs;
5271 }
5272
5273 /* See dw2_debug_names_iterator.  */
5274
5275 dwarf2_per_cu_data *
5276 dw2_debug_names_iterator::next ()
5277 {
5278   if (m_addr == NULL)
5279     return NULL;
5280
5281   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5282   struct objfile *objfile = dwarf2_per_objfile->objfile;
5283   bfd *const abfd = objfile->obfd;
5284
5285  again:
5286
5287   unsigned int bytes_read;
5288   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5289   m_addr += bytes_read;
5290   if (abbrev == 0)
5291     return NULL;
5292
5293   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5294   if (indexval_it == m_map.abbrev_map.cend ())
5295     {
5296       complaint (_("Wrong .debug_names undefined abbrev code %s "
5297                    "[in module %s]"),
5298                  pulongest (abbrev), objfile_name (objfile));
5299       return NULL;
5300     }
5301   const mapped_debug_names::index_val &indexval = indexval_it->second;
5302   enum class symbol_linkage {
5303     unknown,
5304     static_,
5305     extern_,
5306   } symbol_linkage_ = symbol_linkage::unknown;
5307   dwarf2_per_cu_data *per_cu = NULL;
5308   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5309     {
5310       ULONGEST ull;
5311       switch (attr.form)
5312         {
5313         case DW_FORM_implicit_const:
5314           ull = attr.implicit_const;
5315           break;
5316         case DW_FORM_flag_present:
5317           ull = 1;
5318           break;
5319         case DW_FORM_udata:
5320           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5321           m_addr += bytes_read;
5322           break;
5323         default:
5324           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5325                      dwarf_form_name (attr.form),
5326                      objfile_name (objfile));
5327           return NULL;
5328         }
5329       switch (attr.dw_idx)
5330         {
5331         case DW_IDX_compile_unit:
5332           /* Don't crash on bad data.  */
5333           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5334             {
5335               complaint (_(".debug_names entry has bad CU index %s"
5336                            " [in module %s]"),
5337                          pulongest (ull),
5338                          objfile_name (dwarf2_per_objfile->objfile));
5339               continue;
5340             }
5341           per_cu = dwarf2_per_objfile->get_cutu (ull);
5342           break;
5343         case DW_IDX_type_unit:
5344           /* Don't crash on bad data.  */
5345           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5346             {
5347               complaint (_(".debug_names entry has bad TU index %s"
5348                            " [in module %s]"),
5349                          pulongest (ull),
5350                          objfile_name (dwarf2_per_objfile->objfile));
5351               continue;
5352             }
5353           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5354           break;
5355         case DW_IDX_GNU_internal:
5356           if (!m_map.augmentation_is_gdb)
5357             break;
5358           symbol_linkage_ = symbol_linkage::static_;
5359           break;
5360         case DW_IDX_GNU_external:
5361           if (!m_map.augmentation_is_gdb)
5362             break;
5363           symbol_linkage_ = symbol_linkage::extern_;
5364           break;
5365         }
5366     }
5367
5368   /* Skip if already read in.  */
5369   if (per_cu->v.quick->compunit_symtab)
5370     goto again;
5371
5372   /* Check static vs global.  */
5373   if (symbol_linkage_ != symbol_linkage::unknown && m_block_index.has_value ())
5374     {
5375         const bool want_static = *m_block_index == STATIC_BLOCK;
5376         const bool symbol_is_static =
5377           symbol_linkage_ == symbol_linkage::static_;
5378         if (want_static != symbol_is_static)
5379           goto again;
5380     }
5381
5382   /* Match dw2_symtab_iter_next, symbol_kind
5383      and debug_names::psymbol_tag.  */
5384   switch (m_domain)
5385     {
5386     case VAR_DOMAIN:
5387       switch (indexval.dwarf_tag)
5388         {
5389         case DW_TAG_variable:
5390         case DW_TAG_subprogram:
5391         /* Some types are also in VAR_DOMAIN.  */
5392         case DW_TAG_typedef:
5393         case DW_TAG_structure_type:
5394           break;
5395         default:
5396           goto again;
5397         }
5398       break;
5399     case STRUCT_DOMAIN:
5400       switch (indexval.dwarf_tag)
5401         {
5402         case DW_TAG_typedef:
5403         case DW_TAG_structure_type:
5404           break;
5405         default:
5406           goto again;
5407         }
5408       break;
5409     case LABEL_DOMAIN:
5410       switch (indexval.dwarf_tag)
5411         {
5412         case 0:
5413         case DW_TAG_variable:
5414           break;
5415         default:
5416           goto again;
5417         }
5418       break;
5419     case MODULE_DOMAIN:
5420       switch (indexval.dwarf_tag)
5421         {
5422         case DW_TAG_module:
5423           break;
5424         default:
5425           goto again;
5426         }
5427       break;
5428     default:
5429       break;
5430     }
5431
5432   /* Match dw2_expand_symtabs_matching, symbol_kind and
5433      debug_names::psymbol_tag.  */
5434   switch (m_search)
5435     {
5436     case VARIABLES_DOMAIN:
5437       switch (indexval.dwarf_tag)
5438         {
5439         case DW_TAG_variable:
5440           break;
5441         default:
5442           goto again;
5443         }
5444       break;
5445     case FUNCTIONS_DOMAIN:
5446       switch (indexval.dwarf_tag)
5447         {
5448         case DW_TAG_subprogram:
5449           break;
5450         default:
5451           goto again;
5452         }
5453       break;
5454     case TYPES_DOMAIN:
5455       switch (indexval.dwarf_tag)
5456         {
5457         case DW_TAG_typedef:
5458         case DW_TAG_structure_type:
5459           break;
5460         default:
5461           goto again;
5462         }
5463       break;
5464     case MODULES_DOMAIN:
5465       switch (indexval.dwarf_tag)
5466         {
5467         case DW_TAG_module:
5468           break;
5469         default:
5470           goto again;
5471         }
5472     default:
5473       break;
5474     }
5475
5476   return per_cu;
5477 }
5478
5479 static struct compunit_symtab *
5480 dw2_debug_names_lookup_symbol (struct objfile *objfile, block_enum block_index,
5481                                const char *name, domain_enum domain)
5482 {
5483   struct dwarf2_per_objfile *dwarf2_per_objfile
5484     = get_dwarf2_per_objfile (objfile);
5485
5486   const auto &mapp = dwarf2_per_objfile->debug_names_table;
5487   if (!mapp)
5488     {
5489       /* index is NULL if OBJF_READNOW.  */
5490       return NULL;
5491     }
5492   const auto &map = *mapp;
5493
5494   dw2_debug_names_iterator iter (map, block_index, domain, name);
5495
5496   struct compunit_symtab *stab_best = NULL;
5497   struct dwarf2_per_cu_data *per_cu;
5498   while ((per_cu = iter.next ()) != NULL)
5499     {
5500       struct symbol *sym, *with_opaque = NULL;
5501       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
5502       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
5503       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
5504
5505       sym = block_find_symbol (block, name, domain,
5506                                block_find_non_opaque_type_preferred,
5507                                &with_opaque);
5508
5509       /* Some caution must be observed with overloaded functions and
5510          methods, since the index will not contain any overload
5511          information (but NAME might contain it).  */
5512
5513       if (sym != NULL
5514           && strcmp_iw (sym->search_name (), name) == 0)
5515         return stab;
5516       if (with_opaque != NULL
5517           && strcmp_iw (with_opaque->search_name (), name) == 0)
5518         stab_best = stab;
5519
5520       /* Keep looking through other CUs.  */
5521     }
5522
5523   return stab_best;
5524 }
5525
5526 /* This dumps minimal information about .debug_names.  It is called
5527    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
5528    uses this to verify that .debug_names has been loaded.  */
5529
5530 static void
5531 dw2_debug_names_dump (struct objfile *objfile)
5532 {
5533   struct dwarf2_per_objfile *dwarf2_per_objfile
5534     = get_dwarf2_per_objfile (objfile);
5535
5536   gdb_assert (dwarf2_per_objfile->using_index);
5537   printf_filtered (".debug_names:");
5538   if (dwarf2_per_objfile->debug_names_table)
5539     printf_filtered (" exists\n");
5540   else
5541     printf_filtered (" faked for \"readnow\"\n");
5542   printf_filtered ("\n");
5543 }
5544
5545 static void
5546 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
5547                                              const char *func_name)
5548 {
5549   struct dwarf2_per_objfile *dwarf2_per_objfile
5550     = get_dwarf2_per_objfile (objfile);
5551
5552   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
5553   if (dwarf2_per_objfile->debug_names_table)
5554     {
5555       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5556
5557       dw2_debug_names_iterator iter (map, {}, VAR_DOMAIN, func_name);
5558
5559       struct dwarf2_per_cu_data *per_cu;
5560       while ((per_cu = iter.next ()) != NULL)
5561         dw2_instantiate_symtab (per_cu, false);
5562     }
5563 }
5564
5565 static void
5566 dw2_debug_names_map_matching_symbols
5567   (struct objfile *objfile,
5568    const lookup_name_info &name, domain_enum domain,
5569    int global,
5570    gdb::function_view<symbol_found_callback_ftype> callback,
5571    symbol_compare_ftype *ordered_compare)
5572 {
5573   struct dwarf2_per_objfile *dwarf2_per_objfile
5574     = get_dwarf2_per_objfile (objfile);
5575
5576   /* debug_names_table is NULL if OBJF_READNOW.  */
5577   if (!dwarf2_per_objfile->debug_names_table)
5578     return;
5579
5580   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5581   const block_enum block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5582
5583   const char *match_name = name.ada ().lookup_name ().c_str ();
5584   auto matcher = [&] (const char *symname)
5585     {
5586       if (ordered_compare == nullptr)
5587         return true;
5588       return ordered_compare (symname, match_name) == 0;
5589     };
5590
5591   dw2_expand_symtabs_matching_symbol (map, name, matcher, ALL_DOMAIN,
5592                                       [&] (offset_type namei)
5593     {
5594       /* The name was matched, now expand corresponding CUs that were
5595          marked.  */
5596       dw2_debug_names_iterator iter (map, block_kind, domain, namei);
5597
5598       struct dwarf2_per_cu_data *per_cu;
5599       while ((per_cu = iter.next ()) != NULL)
5600         dw2_expand_symtabs_matching_one (per_cu, nullptr, nullptr);
5601       return true;
5602     });
5603
5604   /* It's a shame we couldn't do this inside the
5605      dw2_expand_symtabs_matching_symbol callback, but that skips CUs
5606      that have already been expanded.  Instead, this loop matches what
5607      the psymtab code does.  */
5608   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5609     {
5610       struct compunit_symtab *cust = per_cu->v.quick->compunit_symtab;
5611       if (cust != nullptr)
5612         {
5613           const struct block *block
5614             = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cust), block_kind);
5615           if (!iterate_over_symbols_terminated (block, name,
5616                                                 domain, callback))
5617             break;
5618         }
5619     }
5620 }
5621
5622 static void
5623 dw2_debug_names_expand_symtabs_matching
5624   (struct objfile *objfile,
5625    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5626    const lookup_name_info &lookup_name,
5627    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5628    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5629    enum search_domain kind)
5630 {
5631   struct dwarf2_per_objfile *dwarf2_per_objfile
5632     = get_dwarf2_per_objfile (objfile);
5633
5634   /* debug_names_table is NULL if OBJF_READNOW.  */
5635   if (!dwarf2_per_objfile->debug_names_table)
5636     return;
5637
5638   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5639
5640   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
5641
5642   dw2_expand_symtabs_matching_symbol (map, lookup_name,
5643                                       symbol_matcher,
5644                                       kind, [&] (offset_type namei)
5645     {
5646       /* The name was matched, now expand corresponding CUs that were
5647          marked.  */
5648       dw2_debug_names_iterator iter (map, kind, namei);
5649
5650       struct dwarf2_per_cu_data *per_cu;
5651       while ((per_cu = iter.next ()) != NULL)
5652         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5653                                          expansion_notify);
5654       return true;
5655     });
5656 }
5657
5658 const struct quick_symbol_functions dwarf2_debug_names_functions =
5659 {
5660   dw2_has_symbols,
5661   dw2_find_last_source_symtab,
5662   dw2_forget_cached_source_info,
5663   dw2_map_symtabs_matching_filename,
5664   dw2_debug_names_lookup_symbol,
5665   dw2_print_stats,
5666   dw2_debug_names_dump,
5667   dw2_debug_names_expand_symtabs_for_function,
5668   dw2_expand_all_symtabs,
5669   dw2_expand_symtabs_with_fullname,
5670   dw2_debug_names_map_matching_symbols,
5671   dw2_debug_names_expand_symtabs_matching,
5672   dw2_find_pc_sect_compunit_symtab,
5673   NULL,
5674   dw2_map_symbol_filenames
5675 };
5676
5677 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
5678    to either a dwarf2_per_objfile or dwz_file object.  */
5679
5680 template <typename T>
5681 static gdb::array_view<const gdb_byte>
5682 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
5683 {
5684   dwarf2_section_info *section = &section_owner->gdb_index;
5685
5686   if (section->empty ())
5687     return {};
5688
5689   /* Older elfutils strip versions could keep the section in the main
5690      executable while splitting it for the separate debug info file.  */
5691   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5692     return {};
5693
5694   section->read (obj);
5695
5696   /* dwarf2_section_info::size is a bfd_size_type, while
5697      gdb::array_view works with size_t.  On 32-bit hosts, with
5698      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
5699      is 32-bit.  So we need an explicit narrowing conversion here.
5700      This is fine, because it's impossible to allocate or mmap an
5701      array/buffer larger than what size_t can represent.  */
5702   return gdb::make_array_view (section->buffer, section->size);
5703 }
5704
5705 /* Lookup the index cache for the contents of the index associated to
5706    DWARF2_OBJ.  */
5707
5708 static gdb::array_view<const gdb_byte>
5709 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_objfile *dwarf2_obj)
5710 {
5711   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
5712   if (build_id == nullptr)
5713     return {};
5714
5715   return global_index_cache.lookup_gdb_index (build_id,
5716                                               &dwarf2_obj->index_cache_res);
5717 }
5718
5719 /* Same as the above, but for DWZ.  */
5720
5721 static gdb::array_view<const gdb_byte>
5722 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
5723 {
5724   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
5725   if (build_id == nullptr)
5726     return {};
5727
5728   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
5729 }
5730
5731 /* See symfile.h.  */
5732
5733 bool
5734 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
5735 {
5736   struct dwarf2_per_objfile *dwarf2_per_objfile
5737     = get_dwarf2_per_objfile (objfile);
5738
5739   /* If we're about to read full symbols, don't bother with the
5740      indices.  In this case we also don't care if some other debug
5741      format is making psymtabs, because they are all about to be
5742      expanded anyway.  */
5743   if ((objfile->flags & OBJF_READNOW))
5744     {
5745       dwarf2_per_objfile->using_index = 1;
5746       create_all_comp_units (dwarf2_per_objfile);
5747       create_all_type_units (dwarf2_per_objfile);
5748       dwarf2_per_objfile->quick_file_names_table
5749         = create_quick_file_names_table
5750             (dwarf2_per_objfile->all_comp_units.size ());
5751
5752       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
5753                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
5754         {
5755           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
5756
5757           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5758                                             struct dwarf2_per_cu_quick_data);
5759         }
5760
5761       /* Return 1 so that gdb sees the "quick" functions.  However,
5762          these functions will be no-ops because we will have expanded
5763          all symtabs.  */
5764       *index_kind = dw_index_kind::GDB_INDEX;
5765       return true;
5766     }
5767
5768   if (dwarf2_read_debug_names (dwarf2_per_objfile))
5769     {
5770       *index_kind = dw_index_kind::DEBUG_NAMES;
5771       return true;
5772     }
5773
5774   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
5775                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
5776                              get_gdb_index_contents_from_section<dwz_file>))
5777     {
5778       *index_kind = dw_index_kind::GDB_INDEX;
5779       return true;
5780     }
5781
5782   /* ... otherwise, try to find the index in the index cache.  */
5783   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
5784                              get_gdb_index_contents_from_cache,
5785                              get_gdb_index_contents_from_cache_dwz))
5786     {
5787       global_index_cache.hit ();
5788       *index_kind = dw_index_kind::GDB_INDEX;
5789       return true;
5790     }
5791
5792   global_index_cache.miss ();
5793   return false;
5794 }
5795
5796 \f
5797
5798 /* Build a partial symbol table.  */
5799
5800 void
5801 dwarf2_build_psymtabs (struct objfile *objfile)
5802 {
5803   struct dwarf2_per_objfile *dwarf2_per_objfile
5804     = get_dwarf2_per_objfile (objfile);
5805
5806   init_psymbol_list (objfile, 1024);
5807
5808   try
5809     {
5810       /* This isn't really ideal: all the data we allocate on the
5811          objfile's obstack is still uselessly kept around.  However,
5812          freeing it seems unsafe.  */
5813       psymtab_discarder psymtabs (objfile);
5814       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
5815       psymtabs.keep ();
5816
5817       /* (maybe) store an index in the cache.  */
5818       global_index_cache.store (dwarf2_per_objfile);
5819     }
5820   catch (const gdb_exception_error &except)
5821     {
5822       exception_print (gdb_stderr, except);
5823     }
5824 }
5825
5826 /* Find the base address of the compilation unit for range lists and
5827    location lists.  It will normally be specified by DW_AT_low_pc.
5828    In DWARF-3 draft 4, the base address could be overridden by
5829    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
5830    compilation units with discontinuous ranges.  */
5831
5832 static void
5833 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
5834 {
5835   struct attribute *attr;
5836
5837   cu->base_known = 0;
5838   cu->base_address = 0;
5839
5840   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
5841   if (attr != nullptr)
5842     {
5843       cu->base_address = attr->value_as_address ();
5844       cu->base_known = 1;
5845     }
5846   else
5847     {
5848       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
5849       if (attr != nullptr)
5850         {
5851           cu->base_address = attr->value_as_address ();
5852           cu->base_known = 1;
5853         }
5854     }
5855 }
5856
5857 /* Helper function that returns the proper abbrev section for
5858    THIS_CU.  */
5859
5860 static struct dwarf2_section_info *
5861 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
5862 {
5863   struct dwarf2_section_info *abbrev;
5864   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
5865
5866   if (this_cu->is_dwz)
5867     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
5868   else
5869     abbrev = &dwarf2_per_objfile->abbrev;
5870
5871   return abbrev;
5872 }
5873
5874 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5875
5876 static sect_offset
5877 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
5878                     struct dwarf2_section_info *section,
5879                     sect_offset sect_off)
5880 {
5881   bfd *abfd = section->get_bfd_owner ();
5882   const gdb_byte *info_ptr;
5883   unsigned int initial_length_size, offset_size;
5884   uint16_t version;
5885
5886   section->read (dwarf2_per_objfile->objfile);
5887   info_ptr = section->buffer + to_underlying (sect_off);
5888   read_initial_length (abfd, info_ptr, &initial_length_size);
5889   offset_size = initial_length_size == 4 ? 4 : 8;
5890   info_ptr += initial_length_size;
5891
5892   version = read_2_bytes (abfd, info_ptr);
5893   info_ptr += 2;
5894   if (version >= 5)
5895     {
5896       /* Skip unit type and address size.  */
5897       info_ptr += 2;
5898     }
5899
5900   return (sect_offset) read_offset (abfd, info_ptr, offset_size);
5901 }
5902
5903 /* Allocate a new partial symtab for file named NAME and mark this new
5904    partial symtab as being an include of PST.  */
5905
5906 static void
5907 dwarf2_create_include_psymtab (const char *name, dwarf2_psymtab *pst,
5908                                struct objfile *objfile)
5909 {
5910   dwarf2_psymtab *subpst = new dwarf2_psymtab (name, objfile);
5911
5912   if (!IS_ABSOLUTE_PATH (subpst->filename))
5913     {
5914       /* It shares objfile->objfile_obstack.  */
5915       subpst->dirname = pst->dirname;
5916     }
5917
5918   subpst->dependencies = objfile->partial_symtabs->allocate_dependencies (1);
5919   subpst->dependencies[0] = pst;
5920   subpst->number_of_dependencies = 1;
5921
5922   /* No private part is necessary for include psymtabs.  This property
5923      can be used to differentiate between such include psymtabs and
5924      the regular ones.  */
5925   subpst->per_cu_data = nullptr;
5926 }
5927
5928 /* Read the Line Number Program data and extract the list of files
5929    included by the source file represented by PST.  Build an include
5930    partial symtab for each of these included files.  */
5931
5932 static void
5933 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5934                                struct die_info *die,
5935                                dwarf2_psymtab *pst)
5936 {
5937   line_header_up lh;
5938   struct attribute *attr;
5939
5940   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5941   if (attr != nullptr)
5942     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
5943   if (lh == NULL)
5944     return;  /* No linetable, so no includes.  */
5945
5946   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
5947      that we pass in the raw text_low here; that is ok because we're
5948      only decoding the line table to make include partial symtabs, and
5949      so the addresses aren't really used.  */
5950   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
5951                       pst->raw_text_low (), 1);
5952 }
5953
5954 static hashval_t
5955 hash_signatured_type (const void *item)
5956 {
5957   const struct signatured_type *sig_type
5958     = (const struct signatured_type *) item;
5959
5960   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5961   return sig_type->signature;
5962 }
5963
5964 static int
5965 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5966 {
5967   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5968   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5969
5970   return lhs->signature == rhs->signature;
5971 }
5972
5973 /* Allocate a hash table for signatured types.  */
5974
5975 static htab_up
5976 allocate_signatured_type_table ()
5977 {
5978   return htab_up (htab_create_alloc (41,
5979                                      hash_signatured_type,
5980                                      eq_signatured_type,
5981                                      NULL, xcalloc, xfree));
5982 }
5983
5984 /* A helper function to add a signatured type CU to a table.  */
5985
5986 static int
5987 add_signatured_type_cu_to_table (void **slot, void *datum)
5988 {
5989   struct signatured_type *sigt = (struct signatured_type *) *slot;
5990   std::vector<signatured_type *> *all_type_units
5991     = (std::vector<signatured_type *> *) datum;
5992
5993   all_type_units->push_back (sigt);
5994
5995   return 1;
5996 }
5997
5998 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5999    and fill them into TYPES_HTAB.  It will process only type units,
6000    therefore DW_UT_type.  */
6001
6002 static void
6003 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6004                               struct dwo_file *dwo_file,
6005                               dwarf2_section_info *section, htab_up &types_htab,
6006                               rcuh_kind section_kind)
6007 {
6008   struct objfile *objfile = dwarf2_per_objfile->objfile;
6009   struct dwarf2_section_info *abbrev_section;
6010   bfd *abfd;
6011   const gdb_byte *info_ptr, *end_ptr;
6012
6013   abbrev_section = (dwo_file != NULL
6014                     ? &dwo_file->sections.abbrev
6015                     : &dwarf2_per_objfile->abbrev);
6016
6017   if (dwarf_read_debug)
6018     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6019                         section->get_name (),
6020                         abbrev_section->get_file_name ());
6021
6022   section->read (objfile);
6023   info_ptr = section->buffer;
6024
6025   if (info_ptr == NULL)
6026     return;
6027
6028   /* We can't set abfd until now because the section may be empty or
6029      not present, in which case the bfd is unknown.  */
6030   abfd = section->get_bfd_owner ();
6031
6032   /* We don't use cutu_reader here because we don't need to read
6033      any dies: the signature is in the header.  */
6034
6035   end_ptr = info_ptr + section->size;
6036   while (info_ptr < end_ptr)
6037     {
6038       struct signatured_type *sig_type;
6039       struct dwo_unit *dwo_tu;
6040       void **slot;
6041       const gdb_byte *ptr = info_ptr;
6042       struct comp_unit_head header;
6043       unsigned int length;
6044
6045       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6046
6047       /* Initialize it due to a false compiler warning.  */
6048       header.signature = -1;
6049       header.type_cu_offset_in_tu = (cu_offset) -1;
6050
6051       /* We need to read the type's signature in order to build the hash
6052          table, but we don't need anything else just yet.  */
6053
6054       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6055                                            abbrev_section, ptr, section_kind);
6056
6057       length = header.get_length ();
6058
6059       /* Skip dummy type units.  */
6060       if (ptr >= info_ptr + length
6061           || peek_abbrev_code (abfd, ptr) == 0
6062           || header.unit_type != DW_UT_type)
6063         {
6064           info_ptr += length;
6065           continue;
6066         }
6067
6068       if (types_htab == NULL)
6069         {
6070           if (dwo_file)
6071             types_htab = allocate_dwo_unit_table ();
6072           else
6073             types_htab = allocate_signatured_type_table ();
6074         }
6075
6076       if (dwo_file)
6077         {
6078           sig_type = NULL;
6079           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6080                                    struct dwo_unit);
6081           dwo_tu->dwo_file = dwo_file;
6082           dwo_tu->signature = header.signature;
6083           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6084           dwo_tu->section = section;
6085           dwo_tu->sect_off = sect_off;
6086           dwo_tu->length = length;
6087         }
6088       else
6089         {
6090           /* N.B.: type_offset is not usable if this type uses a DWO file.
6091              The real type_offset is in the DWO file.  */
6092           dwo_tu = NULL;
6093           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6094                                      struct signatured_type);
6095           sig_type->signature = header.signature;
6096           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6097           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6098           sig_type->per_cu.is_debug_types = 1;
6099           sig_type->per_cu.section = section;
6100           sig_type->per_cu.sect_off = sect_off;
6101           sig_type->per_cu.length = length;
6102         }
6103
6104       slot = htab_find_slot (types_htab.get (),
6105                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6106                              INSERT);
6107       gdb_assert (slot != NULL);
6108       if (*slot != NULL)
6109         {
6110           sect_offset dup_sect_off;
6111
6112           if (dwo_file)
6113             {
6114               const struct dwo_unit *dup_tu
6115                 = (const struct dwo_unit *) *slot;
6116
6117               dup_sect_off = dup_tu->sect_off;
6118             }
6119           else
6120             {
6121               const struct signatured_type *dup_tu
6122                 = (const struct signatured_type *) *slot;
6123
6124               dup_sect_off = dup_tu->per_cu.sect_off;
6125             }
6126
6127           complaint (_("debug type entry at offset %s is duplicate to"
6128                        " the entry at offset %s, signature %s"),
6129                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6130                      hex_string (header.signature));
6131         }
6132       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6133
6134       if (dwarf_read_debug > 1)
6135         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6136                             sect_offset_str (sect_off),
6137                             hex_string (header.signature));
6138
6139       info_ptr += length;
6140     }
6141 }
6142
6143 /* Create the hash table of all entries in the .debug_types
6144    (or .debug_types.dwo) section(s).
6145    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6146    otherwise it is NULL.
6147
6148    The result is a pointer to the hash table or NULL if there are no types.
6149
6150    Note: This function processes DWO files only, not DWP files.  */
6151
6152 static void
6153 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6154                                struct dwo_file *dwo_file,
6155                                gdb::array_view<dwarf2_section_info> type_sections,
6156                                htab_up &types_htab)
6157 {
6158   for (dwarf2_section_info &section : type_sections)
6159     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, &section,
6160                                   types_htab, rcuh_kind::TYPE);
6161 }
6162
6163 /* Create the hash table of all entries in the .debug_types section,
6164    and initialize all_type_units.
6165    The result is zero if there is an error (e.g. missing .debug_types section),
6166    otherwise non-zero.  */
6167
6168 static int
6169 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6170 {
6171   htab_up types_htab;
6172
6173   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6174                                 &dwarf2_per_objfile->info, types_htab,
6175                                 rcuh_kind::COMPILE);
6176   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6177                                  dwarf2_per_objfile->types, types_htab);
6178   if (types_htab == NULL)
6179     {
6180       dwarf2_per_objfile->signatured_types = NULL;
6181       return 0;
6182     }
6183
6184   dwarf2_per_objfile->signatured_types = std::move (types_htab);
6185
6186   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6187   dwarf2_per_objfile->all_type_units.reserve
6188     (htab_elements (dwarf2_per_objfile->signatured_types.get ()));
6189
6190   htab_traverse_noresize (dwarf2_per_objfile->signatured_types.get (),
6191                           add_signatured_type_cu_to_table,
6192                           &dwarf2_per_objfile->all_type_units);
6193
6194   return 1;
6195 }
6196
6197 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6198    If SLOT is non-NULL, it is the entry to use in the hash table.
6199    Otherwise we find one.  */
6200
6201 static struct signatured_type *
6202 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6203                void **slot)
6204 {
6205   struct objfile *objfile = dwarf2_per_objfile->objfile;
6206
6207   if (dwarf2_per_objfile->all_type_units.size ()
6208       == dwarf2_per_objfile->all_type_units.capacity ())
6209     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6210
6211   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6212                                               struct signatured_type);
6213
6214   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6215   sig_type->signature = sig;
6216   sig_type->per_cu.is_debug_types = 1;
6217   if (dwarf2_per_objfile->using_index)
6218     {
6219       sig_type->per_cu.v.quick =
6220         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6221                         struct dwarf2_per_cu_quick_data);
6222     }
6223
6224   if (slot == NULL)
6225     {
6226       slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6227                              sig_type, INSERT);
6228     }
6229   gdb_assert (*slot == NULL);
6230   *slot = sig_type;
6231   /* The rest of sig_type must be filled in by the caller.  */
6232   return sig_type;
6233 }
6234
6235 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6236    Fill in SIG_ENTRY with DWO_ENTRY.  */
6237
6238 static void
6239 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6240                                   struct signatured_type *sig_entry,
6241                                   struct dwo_unit *dwo_entry)
6242 {
6243   /* Make sure we're not clobbering something we don't expect to.  */
6244   gdb_assert (! sig_entry->per_cu.queued);
6245   gdb_assert (sig_entry->per_cu.cu == NULL);
6246   if (dwarf2_per_objfile->using_index)
6247     {
6248       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6249       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6250     }
6251   else
6252       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6253   gdb_assert (sig_entry->signature == dwo_entry->signature);
6254   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6255   gdb_assert (sig_entry->type_unit_group == NULL);
6256   gdb_assert (sig_entry->dwo_unit == NULL);
6257
6258   sig_entry->per_cu.section = dwo_entry->section;
6259   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6260   sig_entry->per_cu.length = dwo_entry->length;
6261   sig_entry->per_cu.reading_dwo_directly = 1;
6262   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6263   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6264   sig_entry->dwo_unit = dwo_entry;
6265 }
6266
6267 /* Subroutine of lookup_signatured_type.
6268    If we haven't read the TU yet, create the signatured_type data structure
6269    for a TU to be read in directly from a DWO file, bypassing the stub.
6270    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6271    using .gdb_index, then when reading a CU we want to stay in the DWO file
6272    containing that CU.  Otherwise we could end up reading several other DWO
6273    files (due to comdat folding) to process the transitive closure of all the
6274    mentioned TUs, and that can be slow.  The current DWO file will have every
6275    type signature that it needs.
6276    We only do this for .gdb_index because in the psymtab case we already have
6277    to read all the DWOs to build the type unit groups.  */
6278
6279 static struct signatured_type *
6280 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6281 {
6282   struct dwarf2_per_objfile *dwarf2_per_objfile
6283     = cu->per_cu->dwarf2_per_objfile;
6284   struct dwo_file *dwo_file;
6285   struct dwo_unit find_dwo_entry, *dwo_entry;
6286   struct signatured_type find_sig_entry, *sig_entry;
6287   void **slot;
6288
6289   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6290
6291   /* If TU skeletons have been removed then we may not have read in any
6292      TUs yet.  */
6293   if (dwarf2_per_objfile->signatured_types == NULL)
6294     dwarf2_per_objfile->signatured_types = allocate_signatured_type_table ();
6295
6296   /* We only ever need to read in one copy of a signatured type.
6297      Use the global signatured_types array to do our own comdat-folding
6298      of types.  If this is the first time we're reading this TU, and
6299      the TU has an entry in .gdb_index, replace the recorded data from
6300      .gdb_index with this TU.  */
6301
6302   find_sig_entry.signature = sig;
6303   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6304                          &find_sig_entry, INSERT);
6305   sig_entry = (struct signatured_type *) *slot;
6306
6307   /* We can get here with the TU already read, *or* in the process of being
6308      read.  Don't reassign the global entry to point to this DWO if that's
6309      the case.  Also note that if the TU is already being read, it may not
6310      have come from a DWO, the program may be a mix of Fission-compiled
6311      code and non-Fission-compiled code.  */
6312
6313   /* Have we already tried to read this TU?
6314      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6315      needn't exist in the global table yet).  */
6316   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6317     return sig_entry;
6318
6319   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6320      dwo_unit of the TU itself.  */
6321   dwo_file = cu->dwo_unit->dwo_file;
6322
6323   /* Ok, this is the first time we're reading this TU.  */
6324   if (dwo_file->tus == NULL)
6325     return NULL;
6326   find_dwo_entry.signature = sig;
6327   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
6328                                              &find_dwo_entry);
6329   if (dwo_entry == NULL)
6330     return NULL;
6331
6332   /* If the global table doesn't have an entry for this TU, add one.  */
6333   if (sig_entry == NULL)
6334     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6335
6336   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6337   sig_entry->per_cu.tu_read = 1;
6338   return sig_entry;
6339 }
6340
6341 /* Subroutine of lookup_signatured_type.
6342    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6343    then try the DWP file.  If the TU stub (skeleton) has been removed then
6344    it won't be in .gdb_index.  */
6345
6346 static struct signatured_type *
6347 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6348 {
6349   struct dwarf2_per_objfile *dwarf2_per_objfile
6350     = cu->per_cu->dwarf2_per_objfile;
6351   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6352   struct dwo_unit *dwo_entry;
6353   struct signatured_type find_sig_entry, *sig_entry;
6354   void **slot;
6355
6356   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6357   gdb_assert (dwp_file != NULL);
6358
6359   /* If TU skeletons have been removed then we may not have read in any
6360      TUs yet.  */
6361   if (dwarf2_per_objfile->signatured_types == NULL)
6362     dwarf2_per_objfile->signatured_types = allocate_signatured_type_table ();
6363
6364   find_sig_entry.signature = sig;
6365   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
6366                          &find_sig_entry, INSERT);
6367   sig_entry = (struct signatured_type *) *slot;
6368
6369   /* Have we already tried to read this TU?
6370      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6371      needn't exist in the global table yet).  */
6372   if (sig_entry != NULL)
6373     return sig_entry;
6374
6375   if (dwp_file->tus == NULL)
6376     return NULL;
6377   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
6378                                       sig, 1 /* is_debug_types */);
6379   if (dwo_entry == NULL)
6380     return NULL;
6381
6382   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6383   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6384
6385   return sig_entry;
6386 }
6387
6388 /* Lookup a signature based type for DW_FORM_ref_sig8.
6389    Returns NULL if signature SIG is not present in the table.
6390    It is up to the caller to complain about this.  */
6391
6392 static struct signatured_type *
6393 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6394 {
6395   struct dwarf2_per_objfile *dwarf2_per_objfile
6396     = cu->per_cu->dwarf2_per_objfile;
6397
6398   if (cu->dwo_unit
6399       && dwarf2_per_objfile->using_index)
6400     {
6401       /* We're in a DWO/DWP file, and we're using .gdb_index.
6402          These cases require special processing.  */
6403       if (get_dwp_file (dwarf2_per_objfile) == NULL)
6404         return lookup_dwo_signatured_type (cu, sig);
6405       else
6406         return lookup_dwp_signatured_type (cu, sig);
6407     }
6408   else
6409     {
6410       struct signatured_type find_entry, *entry;
6411
6412       if (dwarf2_per_objfile->signatured_types == NULL)
6413         return NULL;
6414       find_entry.signature = sig;
6415       entry = ((struct signatured_type *)
6416                htab_find (dwarf2_per_objfile->signatured_types.get (),
6417                           &find_entry));
6418       return entry;
6419     }
6420 }
6421
6422 /* Return the address base of the compile unit, which, if exists, is stored
6423    either at the attribute DW_AT_GNU_addr_base, or DW_AT_addr_base.  */
6424 static gdb::optional<ULONGEST>
6425 lookup_addr_base (struct die_info *comp_unit_die)
6426 {
6427   struct attribute *attr;
6428   attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_addr_base);
6429   if (attr == nullptr)
6430     attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_GNU_addr_base);
6431   if (attr == nullptr)
6432     return gdb::optional<ULONGEST> ();
6433   return DW_UNSND (attr);
6434 }
6435
6436 /* Return range lists base of the compile unit, which, if exists, is stored
6437    either at the attribute DW_AT_rnglists_base or DW_AT_GNU_ranges_base.  */
6438 static ULONGEST
6439 lookup_ranges_base (struct die_info *comp_unit_die)
6440 {
6441   struct attribute *attr;
6442   attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_rnglists_base);
6443   if (attr == nullptr)
6444     attr = dwarf2_attr_no_follow (comp_unit_die, DW_AT_GNU_ranges_base);
6445   if (attr == nullptr)
6446     return 0;
6447   return DW_UNSND (attr);
6448 }
6449
6450 /* Low level DIE reading support.  */
6451
6452 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6453
6454 static void
6455 init_cu_die_reader (struct die_reader_specs *reader,
6456                     struct dwarf2_cu *cu,
6457                     struct dwarf2_section_info *section,
6458                     struct dwo_file *dwo_file,
6459                     struct abbrev_table *abbrev_table)
6460 {
6461   gdb_assert (section->readin && section->buffer != NULL);
6462   reader->abfd = section->get_bfd_owner ();
6463   reader->cu = cu;
6464   reader->dwo_file = dwo_file;
6465   reader->die_section = section;
6466   reader->buffer = section->buffer;
6467   reader->buffer_end = section->buffer + section->size;
6468   reader->abbrev_table = abbrev_table;
6469 }
6470
6471 /* Subroutine of cutu_reader to simplify it.
6472    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6473    There's just a lot of work to do, and cutu_reader is big enough
6474    already.
6475
6476    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6477    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6478    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6479    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6480    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6481    STUB_COMP_DIR may be non-NULL.
6482    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE
6483    are filled in with the info of the DIE from the DWO file.
6484    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
6485    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
6486    kept around for at least as long as *RESULT_READER.
6487
6488    The result is non-zero if a valid (non-dummy) DIE was found.  */
6489
6490 static int
6491 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
6492                         struct dwo_unit *dwo_unit,
6493                         struct die_info *stub_comp_unit_die,
6494                         const char *stub_comp_dir,
6495                         struct die_reader_specs *result_reader,
6496                         const gdb_byte **result_info_ptr,
6497                         struct die_info **result_comp_unit_die,
6498                         abbrev_table_up *result_dwo_abbrev_table)
6499 {
6500   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6501   struct objfile *objfile = dwarf2_per_objfile->objfile;
6502   struct dwarf2_cu *cu = this_cu->cu;
6503   bfd *abfd;
6504   const gdb_byte *begin_info_ptr, *info_ptr;
6505   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6506   int i,num_extra_attrs;
6507   struct dwarf2_section_info *dwo_abbrev_section;
6508   struct die_info *comp_unit_die;
6509
6510   /* At most one of these may be provided.  */
6511   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6512
6513   /* These attributes aren't processed until later:
6514      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6515      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6516      referenced later.  However, these attributes are found in the stub
6517      which we won't have later.  In order to not impose this complication
6518      on the rest of the code, we read them here and copy them to the
6519      DWO CU/TU die.  */
6520
6521   stmt_list = NULL;
6522   low_pc = NULL;
6523   high_pc = NULL;
6524   ranges = NULL;
6525   comp_dir = NULL;
6526
6527   if (stub_comp_unit_die != NULL)
6528     {
6529       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6530          DWO file.  */
6531       if (! this_cu->is_debug_types)
6532         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6533       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6534       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6535       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6536       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6537
6538       cu->addr_base = lookup_addr_base (stub_comp_unit_die);
6539
6540       /* There should be a DW_AT_rnglists_base (DW_AT_GNU_ranges_base) attribute
6541          here (if needed). We need the value before we can process
6542          DW_AT_ranges.  */
6543       cu->ranges_base = lookup_ranges_base (stub_comp_unit_die);
6544     }
6545   else if (stub_comp_dir != NULL)
6546     {
6547       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6548       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
6549       comp_dir->name = DW_AT_comp_dir;
6550       comp_dir->form = DW_FORM_string;
6551       DW_STRING_IS_CANONICAL (comp_dir) = 0;
6552       DW_STRING (comp_dir) = stub_comp_dir;
6553     }
6554
6555   /* Set up for reading the DWO CU/TU.  */
6556   cu->dwo_unit = dwo_unit;
6557   dwarf2_section_info *section = dwo_unit->section;
6558   section->read (objfile);
6559   abfd = section->get_bfd_owner ();
6560   begin_info_ptr = info_ptr = (section->buffer
6561                                + to_underlying (dwo_unit->sect_off));
6562   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
6563
6564   if (this_cu->is_debug_types)
6565     {
6566       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
6567
6568       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
6569                                                 &cu->header, section,
6570                                                 dwo_abbrev_section,
6571                                                 info_ptr, rcuh_kind::TYPE);
6572       /* This is not an assert because it can be caused by bad debug info.  */
6573       if (sig_type->signature != cu->header.signature)
6574         {
6575           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
6576                    " TU at offset %s [in module %s]"),
6577                  hex_string (sig_type->signature),
6578                  hex_string (cu->header.signature),
6579                  sect_offset_str (dwo_unit->sect_off),
6580                  bfd_get_filename (abfd));
6581         }
6582       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6583       /* For DWOs coming from DWP files, we don't know the CU length
6584          nor the type's offset in the TU until now.  */
6585       dwo_unit->length = cu->header.get_length ();
6586       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
6587
6588       /* Establish the type offset that can be used to lookup the type.
6589          For DWO files, we don't know it until now.  */
6590       sig_type->type_offset_in_section
6591         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
6592     }
6593   else
6594     {
6595       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
6596                                                 &cu->header, section,
6597                                                 dwo_abbrev_section,
6598                                                 info_ptr, rcuh_kind::COMPILE);
6599       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6600       /* For DWOs coming from DWP files, we don't know the CU length
6601          until now.  */
6602       dwo_unit->length = cu->header.get_length ();
6603     }
6604
6605   *result_dwo_abbrev_table
6606     = abbrev_table::read (objfile, dwo_abbrev_section,
6607                           cu->header.abbrev_sect_off);
6608   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
6609                       result_dwo_abbrev_table->get ());
6610
6611   /* Read in the die, but leave space to copy over the attributes
6612      from the stub.  This has the benefit of simplifying the rest of
6613      the code - all the work to maintain the illusion of a single
6614      DW_TAG_{compile,type}_unit DIE is done here.  */
6615   num_extra_attrs = ((stmt_list != NULL)
6616                      + (low_pc != NULL)
6617                      + (high_pc != NULL)
6618                      + (ranges != NULL)
6619                      + (comp_dir != NULL));
6620   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
6621                               num_extra_attrs);
6622
6623   /* Copy over the attributes from the stub to the DIE we just read in.  */
6624   comp_unit_die = *result_comp_unit_die;
6625   i = comp_unit_die->num_attrs;
6626   if (stmt_list != NULL)
6627     comp_unit_die->attrs[i++] = *stmt_list;
6628   if (low_pc != NULL)
6629     comp_unit_die->attrs[i++] = *low_pc;
6630   if (high_pc != NULL)
6631     comp_unit_die->attrs[i++] = *high_pc;
6632   if (ranges != NULL)
6633     comp_unit_die->attrs[i++] = *ranges;
6634   if (comp_dir != NULL)
6635     comp_unit_die->attrs[i++] = *comp_dir;
6636   comp_unit_die->num_attrs += num_extra_attrs;
6637
6638   if (dwarf_die_debug)
6639     {
6640       fprintf_unfiltered (gdb_stdlog,
6641                           "Read die from %s@0x%x of %s:\n",
6642                           section->get_name (),
6643                           (unsigned) (begin_info_ptr - section->buffer),
6644                           bfd_get_filename (abfd));
6645       dump_die (comp_unit_die, dwarf_die_debug);
6646     }
6647
6648   /* Skip dummy compilation units.  */
6649   if (info_ptr >= begin_info_ptr + dwo_unit->length
6650       || peek_abbrev_code (abfd, info_ptr) == 0)
6651     return 0;
6652
6653   *result_info_ptr = info_ptr;
6654   return 1;
6655 }
6656
6657 /* Return the signature of the compile unit, if found. In DWARF 4 and before,
6658    the signature is in the DW_AT_GNU_dwo_id attribute. In DWARF 5 and later, the
6659    signature is part of the header.  */
6660 static gdb::optional<ULONGEST>
6661 lookup_dwo_id (struct dwarf2_cu *cu, struct die_info* comp_unit_die)
6662 {
6663   if (cu->header.version >= 5)
6664     return cu->header.signature;
6665   struct attribute *attr;
6666   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6667   if (attr == nullptr)
6668     return gdb::optional<ULONGEST> ();
6669   return DW_UNSND (attr);
6670 }
6671
6672 /* Subroutine of cutu_reader to simplify it.
6673    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
6674    Returns NULL if the specified DWO unit cannot be found.  */
6675
6676 static struct dwo_unit *
6677 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
6678                  struct die_info *comp_unit_die,
6679                  const char *dwo_name)
6680 {
6681   struct dwarf2_cu *cu = this_cu->cu;
6682   struct dwo_unit *dwo_unit;
6683   const char *comp_dir;
6684
6685   gdb_assert (cu != NULL);
6686
6687   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
6688   dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
6689   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6690
6691   if (this_cu->is_debug_types)
6692     {
6693       struct signatured_type *sig_type;
6694
6695       /* Since this_cu is the first member of struct signatured_type,
6696          we can go from a pointer to one to a pointer to the other.  */
6697       sig_type = (struct signatured_type *) this_cu;
6698       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
6699     }
6700   else
6701     {
6702       gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
6703       if (!signature.has_value ())
6704         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
6705                  " [in module %s]"),
6706                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
6707       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
6708                                        *signature);
6709     }
6710
6711   return dwo_unit;
6712 }
6713
6714 /* Subroutine of cutu_reader to simplify it.
6715    See it for a description of the parameters.
6716    Read a TU directly from a DWO file, bypassing the stub.  */
6717
6718 void
6719 cutu_reader::init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
6720                                         int use_existing_cu)
6721 {
6722   struct signatured_type *sig_type;
6723   struct die_reader_specs reader;
6724
6725   /* Verify we can do the following downcast, and that we have the
6726      data we need.  */
6727   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
6728   sig_type = (struct signatured_type *) this_cu;
6729   gdb_assert (sig_type->dwo_unit != NULL);
6730
6731   if (use_existing_cu && this_cu->cu != NULL)
6732     {
6733       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
6734       /* There's no need to do the rereading_dwo_cu handling that
6735          cutu_reader does since we don't read the stub.  */
6736     }
6737   else
6738     {
6739       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6740       gdb_assert (this_cu->cu == NULL);
6741       m_new_cu.reset (new dwarf2_cu (this_cu));
6742     }
6743
6744   /* A future optimization, if needed, would be to use an existing
6745      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
6746      could share abbrev tables.  */
6747
6748   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
6749                               NULL /* stub_comp_unit_die */,
6750                               sig_type->dwo_unit->dwo_file->comp_dir,
6751                               &reader, &info_ptr,
6752                               &comp_unit_die,
6753                               &m_dwo_abbrev_table) == 0)
6754     {
6755       /* Dummy die.  */
6756       dummy_p = true;
6757     }
6758 }
6759
6760 /* Initialize a CU (or TU) and read its DIEs.
6761    If the CU defers to a DWO file, read the DWO file as well.
6762
6763    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
6764    Otherwise the table specified in the comp unit header is read in and used.
6765    This is an optimization for when we already have the abbrev table.
6766
6767    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
6768    Otherwise, a new CU is allocated with xmalloc.  */
6769
6770 cutu_reader::cutu_reader (struct dwarf2_per_cu_data *this_cu,
6771                           struct abbrev_table *abbrev_table,
6772                           int use_existing_cu,
6773                           bool skip_partial)
6774   : die_reader_specs {},
6775     m_this_cu (this_cu)
6776 {
6777   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6778   struct objfile *objfile = dwarf2_per_objfile->objfile;
6779   struct dwarf2_section_info *section = this_cu->section;
6780   bfd *abfd = section->get_bfd_owner ();
6781   struct dwarf2_cu *cu;
6782   const gdb_byte *begin_info_ptr;
6783   struct signatured_type *sig_type = NULL;
6784   struct dwarf2_section_info *abbrev_section;
6785   /* Non-zero if CU currently points to a DWO file and we need to
6786      reread it.  When this happens we need to reread the skeleton die
6787      before we can reread the DWO file (this only applies to CUs, not TUs).  */
6788   int rereading_dwo_cu = 0;
6789
6790   if (dwarf_die_debug)
6791     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
6792                         this_cu->is_debug_types ? "type" : "comp",
6793                         sect_offset_str (this_cu->sect_off));
6794
6795   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6796      file (instead of going through the stub), short-circuit all of this.  */
6797   if (this_cu->reading_dwo_directly)
6798     {
6799       /* Narrow down the scope of possibilities to have to understand.  */
6800       gdb_assert (this_cu->is_debug_types);
6801       gdb_assert (abbrev_table == NULL);
6802       init_tu_and_read_dwo_dies (this_cu, use_existing_cu);
6803       return;
6804     }
6805
6806   /* This is cheap if the section is already read in.  */
6807   section->read (objfile);
6808
6809   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6810
6811   abbrev_section = get_abbrev_section_for_cu (this_cu);
6812
6813   if (use_existing_cu && this_cu->cu != NULL)
6814     {
6815       cu = this_cu->cu;
6816       /* If this CU is from a DWO file we need to start over, we need to
6817          refetch the attributes from the skeleton CU.
6818          This could be optimized by retrieving those attributes from when we
6819          were here the first time: the previous comp_unit_die was stored in
6820          comp_unit_obstack.  But there's no data yet that we need this
6821          optimization.  */
6822       if (cu->dwo_unit != NULL)
6823         rereading_dwo_cu = 1;
6824     }
6825   else
6826     {
6827       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6828       gdb_assert (this_cu->cu == NULL);
6829       m_new_cu.reset (new dwarf2_cu (this_cu));
6830       cu = m_new_cu.get ();
6831     }
6832
6833   /* Get the header.  */
6834   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6835     {
6836       /* We already have the header, there's no need to read it in again.  */
6837       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6838     }
6839   else
6840     {
6841       if (this_cu->is_debug_types)
6842         {
6843           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
6844                                                     &cu->header, section,
6845                                                     abbrev_section, info_ptr,
6846                                                     rcuh_kind::TYPE);
6847
6848           /* Since per_cu is the first member of struct signatured_type,
6849              we can go from a pointer to one to a pointer to the other.  */
6850           sig_type = (struct signatured_type *) this_cu;
6851           gdb_assert (sig_type->signature == cu->header.signature);
6852           gdb_assert (sig_type->type_offset_in_tu
6853                       == cu->header.type_cu_offset_in_tu);
6854           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6855
6856           /* LENGTH has not been set yet for type units if we're
6857              using .gdb_index.  */
6858           this_cu->length = cu->header.get_length ();
6859
6860           /* Establish the type offset that can be used to lookup the type.  */
6861           sig_type->type_offset_in_section =
6862             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6863
6864           this_cu->dwarf_version = cu->header.version;
6865         }
6866       else
6867         {
6868           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
6869                                                     &cu->header, section,
6870                                                     abbrev_section,
6871                                                     info_ptr,
6872                                                     rcuh_kind::COMPILE);
6873
6874           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6875           gdb_assert (this_cu->length == cu->header.get_length ());
6876           this_cu->dwarf_version = cu->header.version;
6877         }
6878     }
6879
6880   /* Skip dummy compilation units.  */
6881   if (info_ptr >= begin_info_ptr + this_cu->length
6882       || peek_abbrev_code (abfd, info_ptr) == 0)
6883     {
6884       dummy_p = true;
6885       return;
6886     }
6887
6888   /* If we don't have them yet, read the abbrevs for this compilation unit.
6889      And if we need to read them now, make sure they're freed when we're
6890      done.  */
6891   if (abbrev_table != NULL)
6892     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6893   else
6894     {
6895       m_abbrev_table_holder
6896         = abbrev_table::read (objfile, abbrev_section,
6897                               cu->header.abbrev_sect_off);
6898       abbrev_table = m_abbrev_table_holder.get ();
6899     }
6900
6901   /* Read the top level CU/TU die.  */
6902   init_cu_die_reader (this, cu, section, NULL, abbrev_table);
6903   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
6904
6905   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
6906     {
6907       dummy_p = true;
6908       return;
6909     }
6910
6911   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6912      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
6913      table from the DWO file and pass the ownership over to us.  It will be
6914      referenced from READER, so we must make sure to free it after we're done
6915      with READER.
6916
6917      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6918      DWO CU, that this test will fail (the attribute will not be present).  */
6919   const char *dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
6920   if (dwo_name != nullptr)
6921     {
6922       struct dwo_unit *dwo_unit;
6923       struct die_info *dwo_comp_unit_die;
6924
6925       if (comp_unit_die->has_children)
6926         {
6927           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
6928                        " has children (offset %s) [in module %s]"),
6929                      sect_offset_str (this_cu->sect_off),
6930                      bfd_get_filename (abfd));
6931         }
6932       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die, dwo_name);
6933       if (dwo_unit != NULL)
6934         {
6935           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
6936                                       comp_unit_die, NULL,
6937                                       this, &info_ptr,
6938                                       &dwo_comp_unit_die,
6939                                       &m_dwo_abbrev_table) == 0)
6940             {
6941               /* Dummy die.  */
6942               dummy_p = true;
6943               return;
6944             }
6945           comp_unit_die = dwo_comp_unit_die;
6946         }
6947       else
6948         {
6949           /* Yikes, we couldn't find the rest of the DIE, we only have
6950              the stub.  A complaint has already been logged.  There's
6951              not much more we can do except pass on the stub DIE to
6952              die_reader_func.  We don't want to throw an error on bad
6953              debug info.  */
6954         }
6955     }
6956 }
6957
6958 void
6959 cutu_reader::keep ()
6960 {
6961   /* Done, clean up.  */
6962   gdb_assert (!dummy_p);
6963   if (m_new_cu != NULL)
6964     {
6965       struct dwarf2_per_objfile *dwarf2_per_objfile
6966         = m_this_cu->dwarf2_per_objfile;
6967       /* Link this CU into read_in_chain.  */
6968       m_this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6969       dwarf2_per_objfile->read_in_chain = m_this_cu;
6970       /* The chain owns it now.  */
6971       m_new_cu.release ();
6972     }
6973 }
6974
6975 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name (DW_AT_dwo_name)
6976    if present. DWO_FILE, if non-NULL, is the DWO file to read (the caller is
6977    assumed to have already done the lookup to find the DWO file).
6978
6979    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6980    THIS_CU->is_debug_types, but nothing else.
6981
6982    We fill in THIS_CU->length.
6983
6984    THIS_CU->cu is always freed when done.
6985    This is done in order to not leave THIS_CU->cu in a state where we have
6986    to care whether it refers to the "main" CU or the DWO CU.
6987
6988    When parent_cu is passed, it is used to provide a default value for
6989    str_offsets_base and addr_base from the parent.  */
6990
6991 cutu_reader::cutu_reader (struct dwarf2_per_cu_data *this_cu,
6992                           struct dwarf2_cu *parent_cu,
6993                           struct dwo_file *dwo_file)
6994   : die_reader_specs {},
6995     m_this_cu (this_cu)
6996 {
6997   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6998   struct objfile *objfile = dwarf2_per_objfile->objfile;
6999   struct dwarf2_section_info *section = this_cu->section;
7000   bfd *abfd = section->get_bfd_owner ();
7001   struct dwarf2_section_info *abbrev_section;
7002   const gdb_byte *begin_info_ptr, *info_ptr;
7003
7004   if (dwarf_die_debug)
7005     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7006                         this_cu->is_debug_types ? "type" : "comp",
7007                         sect_offset_str (this_cu->sect_off));
7008
7009   gdb_assert (this_cu->cu == NULL);
7010
7011   abbrev_section = (dwo_file != NULL
7012                     ? &dwo_file->sections.abbrev
7013                     : get_abbrev_section_for_cu (this_cu));
7014
7015   /* This is cheap if the section is already read in.  */
7016   section->read (objfile);
7017
7018   m_new_cu.reset (new dwarf2_cu (this_cu));
7019
7020   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7021   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7022                                             &m_new_cu->header, section,
7023                                             abbrev_section, info_ptr,
7024                                             (this_cu->is_debug_types
7025                                              ? rcuh_kind::TYPE
7026                                              : rcuh_kind::COMPILE));
7027
7028   if (parent_cu != nullptr)
7029     {
7030       m_new_cu->str_offsets_base = parent_cu->str_offsets_base;
7031       m_new_cu->addr_base = parent_cu->addr_base;
7032     }
7033   this_cu->length = m_new_cu->header.get_length ();
7034
7035   /* Skip dummy compilation units.  */
7036   if (info_ptr >= begin_info_ptr + this_cu->length
7037       || peek_abbrev_code (abfd, info_ptr) == 0)
7038     {
7039       dummy_p = true;
7040       return;
7041     }
7042
7043   m_abbrev_table_holder
7044     = abbrev_table::read (objfile, abbrev_section,
7045                           m_new_cu->header.abbrev_sect_off);
7046
7047   init_cu_die_reader (this, m_new_cu.get (), section, dwo_file,
7048                       m_abbrev_table_holder.get ());
7049   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
7050 }
7051
7052 \f
7053 /* Type Unit Groups.
7054
7055    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7056    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7057    so that all types coming from the same compilation (.o file) are grouped
7058    together.  A future step could be to put the types in the same symtab as
7059    the CU the types ultimately came from.  */
7060
7061 static hashval_t
7062 hash_type_unit_group (const void *item)
7063 {
7064   const struct type_unit_group *tu_group
7065     = (const struct type_unit_group *) item;
7066
7067   return hash_stmt_list_entry (&tu_group->hash);
7068 }
7069
7070 static int
7071 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7072 {
7073   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7074   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7075
7076   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7077 }
7078
7079 /* Allocate a hash table for type unit groups.  */
7080
7081 static htab_up
7082 allocate_type_unit_groups_table ()
7083 {
7084   return htab_up (htab_create_alloc (3,
7085                                      hash_type_unit_group,
7086                                      eq_type_unit_group,
7087                                      NULL, xcalloc, xfree));
7088 }
7089
7090 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7091    partial symtabs.  We combine several TUs per psymtab to not let the size
7092    of any one psymtab grow too big.  */
7093 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7094 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7095
7096 /* Helper routine for get_type_unit_group.
7097    Create the type_unit_group object used to hold one or more TUs.  */
7098
7099 static struct type_unit_group *
7100 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7101 {
7102   struct dwarf2_per_objfile *dwarf2_per_objfile
7103     = cu->per_cu->dwarf2_per_objfile;
7104   struct objfile *objfile = dwarf2_per_objfile->objfile;
7105   struct dwarf2_per_cu_data *per_cu;
7106   struct type_unit_group *tu_group;
7107
7108   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7109                              struct type_unit_group);
7110   per_cu = &tu_group->per_cu;
7111   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7112
7113   if (dwarf2_per_objfile->using_index)
7114     {
7115       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7116                                         struct dwarf2_per_cu_quick_data);
7117     }
7118   else
7119     {
7120       unsigned int line_offset = to_underlying (line_offset_struct);
7121       dwarf2_psymtab *pst;
7122       std::string name;
7123
7124       /* Give the symtab a useful name for debug purposes.  */
7125       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7126         name = string_printf ("<type_units_%d>",
7127                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7128       else
7129         name = string_printf ("<type_units_at_0x%x>", line_offset);
7130
7131       pst = create_partial_symtab (per_cu, name.c_str ());
7132       pst->anonymous = true;
7133     }
7134
7135   tu_group->hash.dwo_unit = cu->dwo_unit;
7136   tu_group->hash.line_sect_off = line_offset_struct;
7137
7138   return tu_group;
7139 }
7140
7141 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7142    STMT_LIST is a DW_AT_stmt_list attribute.  */
7143
7144 static struct type_unit_group *
7145 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7146 {
7147   struct dwarf2_per_objfile *dwarf2_per_objfile
7148     = cu->per_cu->dwarf2_per_objfile;
7149   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7150   struct type_unit_group *tu_group;
7151   void **slot;
7152   unsigned int line_offset;
7153   struct type_unit_group type_unit_group_for_lookup;
7154
7155   if (dwarf2_per_objfile->type_unit_groups == NULL)
7156     dwarf2_per_objfile->type_unit_groups = allocate_type_unit_groups_table ();
7157
7158   /* Do we need to create a new group, or can we use an existing one?  */
7159
7160   if (stmt_list)
7161     {
7162       line_offset = DW_UNSND (stmt_list);
7163       ++tu_stats->nr_symtab_sharers;
7164     }
7165   else
7166     {
7167       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7168          We can do various things here like create one group per TU or
7169          spread them over multiple groups to split up the expansion work.
7170          To avoid worst case scenarios (too many groups or too large groups)
7171          we, umm, group them in bunches.  */
7172       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7173                      | (tu_stats->nr_stmt_less_type_units
7174                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7175       ++tu_stats->nr_stmt_less_type_units;
7176     }
7177
7178   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7179   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7180   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups.get (),
7181                          &type_unit_group_for_lookup, INSERT);
7182   if (*slot != NULL)
7183     {
7184       tu_group = (struct type_unit_group *) *slot;
7185       gdb_assert (tu_group != NULL);
7186     }
7187   else
7188     {
7189       sect_offset line_offset_struct = (sect_offset) line_offset;
7190       tu_group = create_type_unit_group (cu, line_offset_struct);
7191       *slot = tu_group;
7192       ++tu_stats->nr_symtabs;
7193     }
7194
7195   return tu_group;
7196 }
7197 \f
7198 /* Partial symbol tables.  */
7199
7200 /* Create a psymtab named NAME and assign it to PER_CU.
7201
7202    The caller must fill in the following details:
7203    dirname, textlow, texthigh.  */
7204
7205 static dwarf2_psymtab *
7206 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7207 {
7208   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7209   dwarf2_psymtab *pst;
7210
7211   pst = new dwarf2_psymtab (name, objfile, 0);
7212
7213   pst->psymtabs_addrmap_supported = true;
7214
7215   /* This is the glue that links PST into GDB's symbol API.  */
7216   pst->per_cu_data = per_cu;
7217   per_cu->v.psymtab = pst;
7218
7219   return pst;
7220 }
7221
7222 /* DIE reader function for process_psymtab_comp_unit.  */
7223
7224 static void
7225 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7226                                   const gdb_byte *info_ptr,
7227                                   struct die_info *comp_unit_die,
7228                                   enum language pretend_language)
7229 {
7230   struct dwarf2_cu *cu = reader->cu;
7231   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7232   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7233   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7234   CORE_ADDR baseaddr;
7235   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7236   dwarf2_psymtab *pst;
7237   enum pc_bounds_kind cu_bounds_kind;
7238   const char *filename;
7239
7240   gdb_assert (! per_cu->is_debug_types);
7241
7242   prepare_one_comp_unit (cu, comp_unit_die, pretend_language);
7243
7244   /* Allocate a new partial symbol table structure.  */
7245   gdb::unique_xmalloc_ptr<char> debug_filename;
7246   static const char artificial[] = "<artificial>";
7247   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7248   if (filename == NULL)
7249     filename = "";
7250   else if (strcmp (filename, artificial) == 0)
7251     {
7252       debug_filename.reset (concat (artificial, "@",
7253                                     sect_offset_str (per_cu->sect_off),
7254                                     (char *) NULL));
7255       filename = debug_filename.get ();
7256     }
7257
7258   pst = create_partial_symtab (per_cu, filename);
7259
7260   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7261   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7262
7263   baseaddr = objfile->text_section_offset ();
7264
7265   dwarf2_find_base_address (comp_unit_die, cu);
7266
7267   /* Possibly set the default values of LOWPC and HIGHPC from
7268      `DW_AT_ranges'.  */
7269   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7270                                          &best_highpc, cu, pst);
7271   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7272     {
7273       CORE_ADDR low
7274         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
7275            - baseaddr);
7276       CORE_ADDR high
7277         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
7278            - baseaddr - 1);
7279       /* Store the contiguous range if it is not empty; it can be
7280          empty for CUs with no code.  */
7281       addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
7282                          low, high, pst);
7283     }
7284
7285   /* Check if comp unit has_children.
7286      If so, read the rest of the partial symbols from this comp unit.
7287      If not, there's no more debug_info for this comp unit.  */
7288   if (comp_unit_die->has_children)
7289     {
7290       struct partial_die_info *first_die;
7291       CORE_ADDR lowpc, highpc;
7292
7293       lowpc = ((CORE_ADDR) -1);
7294       highpc = ((CORE_ADDR) 0);
7295
7296       first_die = load_partial_dies (reader, info_ptr, 1);
7297
7298       scan_partial_symbols (first_die, &lowpc, &highpc,
7299                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7300
7301       /* If we didn't find a lowpc, set it to highpc to avoid
7302          complaints from `maint check'.  */
7303       if (lowpc == ((CORE_ADDR) -1))
7304         lowpc = highpc;
7305
7306       /* If the compilation unit didn't have an explicit address range,
7307          then use the information extracted from its child dies.  */
7308       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7309         {
7310           best_lowpc = lowpc;
7311           best_highpc = highpc;
7312         }
7313     }
7314   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
7315                                                  best_lowpc + baseaddr)
7316                      - baseaddr);
7317   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
7318                                                   best_highpc + baseaddr)
7319                       - baseaddr);
7320
7321   end_psymtab_common (objfile, pst);
7322
7323   if (!cu->per_cu->imported_symtabs_empty ())
7324     {
7325       int i;
7326       int len = cu->per_cu->imported_symtabs_size ();
7327
7328       /* Fill in 'dependencies' here; we fill in 'users' in a
7329          post-pass.  */
7330       pst->number_of_dependencies = len;
7331       pst->dependencies
7332         = objfile->partial_symtabs->allocate_dependencies (len);
7333       for (i = 0; i < len; ++i)
7334         {
7335           pst->dependencies[i]
7336             = cu->per_cu->imported_symtabs->at (i)->v.psymtab;
7337         }
7338
7339       cu->per_cu->imported_symtabs_free ();
7340     }
7341
7342   /* Get the list of files included in the current compilation unit,
7343      and build a psymtab for each of them.  */
7344   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7345
7346   if (dwarf_read_debug)
7347     fprintf_unfiltered (gdb_stdlog,
7348                         "Psymtab for %s unit @%s: %s - %s"
7349                         ", %d global, %d static syms\n",
7350                         per_cu->is_debug_types ? "type" : "comp",
7351                         sect_offset_str (per_cu->sect_off),
7352                         paddress (gdbarch, pst->text_low (objfile)),
7353                         paddress (gdbarch, pst->text_high (objfile)),
7354                         pst->n_global_syms, pst->n_static_syms);
7355 }
7356
7357 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7358    Process compilation unit THIS_CU for a psymtab.  */
7359
7360 static void
7361 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
7362                            bool want_partial_unit,
7363                            enum language pretend_language)
7364 {
7365   /* If this compilation unit was already read in, free the
7366      cached copy in order to read it in again.  This is
7367      necessary because we skipped some symbols when we first
7368      read in the compilation unit (see load_partial_dies).
7369      This problem could be avoided, but the benefit is unclear.  */
7370   if (this_cu->cu != NULL)
7371     free_one_cached_comp_unit (this_cu);
7372
7373   cutu_reader reader (this_cu, NULL, 0, false);
7374
7375   if (reader.dummy_p)
7376     {
7377       /* Nothing.  */
7378     }
7379   else if (this_cu->is_debug_types)
7380     build_type_psymtabs_reader (&reader, reader.info_ptr,
7381                                 reader.comp_unit_die);
7382   else if (want_partial_unit
7383            || reader.comp_unit_die->tag != DW_TAG_partial_unit)
7384     process_psymtab_comp_unit_reader (&reader, reader.info_ptr,
7385                                       reader.comp_unit_die,
7386                                       pretend_language);
7387
7388   /* Age out any secondary CUs.  */
7389   age_cached_comp_units (this_cu->dwarf2_per_objfile);
7390 }
7391
7392 /* Reader function for build_type_psymtabs.  */
7393
7394 static void
7395 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7396                             const gdb_byte *info_ptr,
7397                             struct die_info *type_unit_die)
7398 {
7399   struct dwarf2_per_objfile *dwarf2_per_objfile
7400     = reader->cu->per_cu->dwarf2_per_objfile;
7401   struct objfile *objfile = dwarf2_per_objfile->objfile;
7402   struct dwarf2_cu *cu = reader->cu;
7403   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7404   struct signatured_type *sig_type;
7405   struct type_unit_group *tu_group;
7406   struct attribute *attr;
7407   struct partial_die_info *first_die;
7408   CORE_ADDR lowpc, highpc;
7409   dwarf2_psymtab *pst;
7410
7411   gdb_assert (per_cu->is_debug_types);
7412   sig_type = (struct signatured_type *) per_cu;
7413
7414   if (! type_unit_die->has_children)
7415     return;
7416
7417   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
7418   tu_group = get_type_unit_group (cu, attr);
7419
7420   if (tu_group->tus == nullptr)
7421     tu_group->tus = new std::vector<signatured_type *>;
7422   tu_group->tus->push_back (sig_type);
7423
7424   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7425   pst = create_partial_symtab (per_cu, "");
7426   pst->anonymous = true;
7427
7428   first_die = load_partial_dies (reader, info_ptr, 1);
7429
7430   lowpc = (CORE_ADDR) -1;
7431   highpc = (CORE_ADDR) 0;
7432   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7433
7434   end_psymtab_common (objfile, pst);
7435 }
7436
7437 /* Struct used to sort TUs by their abbreviation table offset.  */
7438
7439 struct tu_abbrev_offset
7440 {
7441   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
7442   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
7443   {}
7444
7445   signatured_type *sig_type;
7446   sect_offset abbrev_offset;
7447 };
7448
7449 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
7450
7451 static bool
7452 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
7453                           const struct tu_abbrev_offset &b)
7454 {
7455   return a.abbrev_offset < b.abbrev_offset;
7456 }
7457
7458 /* Efficiently read all the type units.
7459    This does the bulk of the work for build_type_psymtabs.
7460
7461    The efficiency is because we sort TUs by the abbrev table they use and
7462    only read each abbrev table once.  In one program there are 200K TUs
7463    sharing 8K abbrev tables.
7464
7465    The main purpose of this function is to support building the
7466    dwarf2_per_objfile->type_unit_groups table.
7467    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7468    can collapse the search space by grouping them by stmt_list.
7469    The savings can be significant, in the same program from above the 200K TUs
7470    share 8K stmt_list tables.
7471
7472    FUNC is expected to call get_type_unit_group, which will create the
7473    struct type_unit_group if necessary and add it to
7474    dwarf2_per_objfile->type_unit_groups.  */
7475
7476 static void
7477 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
7478 {
7479   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7480   abbrev_table_up abbrev_table;
7481   sect_offset abbrev_offset;
7482
7483   /* It's up to the caller to not call us multiple times.  */
7484   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
7485
7486   if (dwarf2_per_objfile->all_type_units.empty ())
7487     return;
7488
7489   /* TUs typically share abbrev tables, and there can be way more TUs than
7490      abbrev tables.  Sort by abbrev table to reduce the number of times we
7491      read each abbrev table in.
7492      Alternatives are to punt or to maintain a cache of abbrev tables.
7493      This is simpler and efficient enough for now.
7494
7495      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7496      symtab to use).  Typically TUs with the same abbrev offset have the same
7497      stmt_list value too so in practice this should work well.
7498
7499      The basic algorithm here is:
7500
7501       sort TUs by abbrev table
7502       for each TU with same abbrev table:
7503         read abbrev table if first user
7504         read TU top level DIE
7505           [IWBN if DWO skeletons had DW_AT_stmt_list]
7506         call FUNC  */
7507
7508   if (dwarf_read_debug)
7509     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
7510
7511   /* Sort in a separate table to maintain the order of all_type_units
7512      for .gdb_index: TU indices directly index all_type_units.  */
7513   std::vector<tu_abbrev_offset> sorted_by_abbrev;
7514   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
7515
7516   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
7517     sorted_by_abbrev.emplace_back
7518       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
7519                                      sig_type->per_cu.section,
7520                                      sig_type->per_cu.sect_off));
7521
7522   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
7523              sort_tu_by_abbrev_offset);
7524
7525   abbrev_offset = (sect_offset) ~(unsigned) 0;
7526
7527   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
7528     {
7529       /* Switch to the next abbrev table if necessary.  */
7530       if (abbrev_table == NULL
7531           || tu.abbrev_offset != abbrev_offset)
7532         {
7533           abbrev_offset = tu.abbrev_offset;
7534           abbrev_table =
7535             abbrev_table::read (dwarf2_per_objfile->objfile,
7536                                 &dwarf2_per_objfile->abbrev,
7537                                 abbrev_offset);
7538           ++tu_stats->nr_uniq_abbrev_tables;
7539         }
7540
7541       cutu_reader reader (&tu.sig_type->per_cu, abbrev_table.get (),
7542                           0, false);
7543       if (!reader.dummy_p)
7544         build_type_psymtabs_reader (&reader, reader.info_ptr,
7545                                     reader.comp_unit_die);
7546     }
7547 }
7548
7549 /* Print collected type unit statistics.  */
7550
7551 static void
7552 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
7553 {
7554   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7555
7556   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
7557   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
7558                       dwarf2_per_objfile->all_type_units.size ());
7559   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
7560                       tu_stats->nr_uniq_abbrev_tables);
7561   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
7562                       tu_stats->nr_symtabs);
7563   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
7564                       tu_stats->nr_symtab_sharers);
7565   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
7566                       tu_stats->nr_stmt_less_type_units);
7567   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
7568                       tu_stats->nr_all_type_units_reallocs);
7569 }
7570
7571 /* Traversal function for build_type_psymtabs.  */
7572
7573 static int
7574 build_type_psymtab_dependencies (void **slot, void *info)
7575 {
7576   struct dwarf2_per_objfile *dwarf2_per_objfile
7577     = (struct dwarf2_per_objfile *) info;
7578   struct objfile *objfile = dwarf2_per_objfile->objfile;
7579   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
7580   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
7581   dwarf2_psymtab *pst = per_cu->v.psymtab;
7582   int len = (tu_group->tus == nullptr) ? 0 : tu_group->tus->size ();
7583   int i;
7584
7585   gdb_assert (len > 0);
7586   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
7587
7588   pst->number_of_dependencies = len;
7589   pst->dependencies = objfile->partial_symtabs->allocate_dependencies (len);
7590   for (i = 0; i < len; ++i)
7591     {
7592       struct signatured_type *iter = tu_group->tus->at (i);
7593       gdb_assert (iter->per_cu.is_debug_types);
7594       pst->dependencies[i] = iter->per_cu.v.psymtab;
7595       iter->type_unit_group = tu_group;
7596     }
7597
7598   delete tu_group->tus;
7599   tu_group->tus = nullptr;
7600
7601   return 1;
7602 }
7603
7604 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7605    Build partial symbol tables for the .debug_types comp-units.  */
7606
7607 static void
7608 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
7609 {
7610   if (! create_all_type_units (dwarf2_per_objfile))
7611     return;
7612
7613   build_type_psymtabs_1 (dwarf2_per_objfile);
7614 }
7615
7616 /* Traversal function for process_skeletonless_type_unit.
7617    Read a TU in a DWO file and build partial symbols for it.  */
7618
7619 static int
7620 process_skeletonless_type_unit (void **slot, void *info)
7621 {
7622   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
7623   struct dwarf2_per_objfile *dwarf2_per_objfile
7624     = (struct dwarf2_per_objfile *) info;
7625   struct signatured_type find_entry, *entry;
7626
7627   /* If this TU doesn't exist in the global table, add it and read it in.  */
7628
7629   if (dwarf2_per_objfile->signatured_types == NULL)
7630     dwarf2_per_objfile->signatured_types = allocate_signatured_type_table ();
7631
7632   find_entry.signature = dwo_unit->signature;
7633   slot = htab_find_slot (dwarf2_per_objfile->signatured_types.get (),
7634                          &find_entry, INSERT);
7635   /* If we've already seen this type there's nothing to do.  What's happening
7636      is we're doing our own version of comdat-folding here.  */
7637   if (*slot != NULL)
7638     return 1;
7639
7640   /* This does the job that create_all_type_units would have done for
7641      this TU.  */
7642   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
7643   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
7644   *slot = entry;
7645
7646   /* This does the job that build_type_psymtabs_1 would have done.  */
7647   cutu_reader reader (&entry->per_cu, NULL, 0, false);
7648   if (!reader.dummy_p)
7649     build_type_psymtabs_reader (&reader, reader.info_ptr,
7650                                 reader.comp_unit_die);
7651
7652   return 1;
7653 }
7654
7655 /* Traversal function for process_skeletonless_type_units.  */
7656
7657 static int
7658 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
7659 {
7660   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7661
7662   if (dwo_file->tus != NULL)
7663     htab_traverse_noresize (dwo_file->tus.get (),
7664                             process_skeletonless_type_unit, info);
7665
7666   return 1;
7667 }
7668
7669 /* Scan all TUs of DWO files, verifying we've processed them.
7670    This is needed in case a TU was emitted without its skeleton.
7671    Note: This can't be done until we know what all the DWO files are.  */
7672
7673 static void
7674 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7675 {
7676   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
7677   if (get_dwp_file (dwarf2_per_objfile) == NULL
7678       && dwarf2_per_objfile->dwo_files != NULL)
7679     {
7680       htab_traverse_noresize (dwarf2_per_objfile->dwo_files.get (),
7681                               process_dwo_file_for_skeletonless_type_units,
7682                               dwarf2_per_objfile);
7683     }
7684 }
7685
7686 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
7687
7688 static void
7689 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
7690 {
7691   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
7692     {
7693       dwarf2_psymtab *pst = per_cu->v.psymtab;
7694
7695       if (pst == NULL)
7696         continue;
7697
7698       for (int j = 0; j < pst->number_of_dependencies; ++j)
7699         {
7700           /* Set the 'user' field only if it is not already set.  */
7701           if (pst->dependencies[j]->user == NULL)
7702             pst->dependencies[j]->user = pst;
7703         }
7704     }
7705 }
7706
7707 /* Build the partial symbol table by doing a quick pass through the
7708    .debug_info and .debug_abbrev sections.  */
7709
7710 static void
7711 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
7712 {
7713   struct objfile *objfile = dwarf2_per_objfile->objfile;
7714
7715   if (dwarf_read_debug)
7716     {
7717       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
7718                           objfile_name (objfile));
7719     }
7720
7721   scoped_restore restore_reading_psyms
7722     = make_scoped_restore (&dwarf2_per_objfile->reading_partial_symbols,
7723                            true);
7724
7725   dwarf2_per_objfile->info.read (objfile);
7726
7727   /* Any cached compilation units will be linked by the per-objfile
7728      read_in_chain.  Make sure to free them when we're done.  */
7729   free_cached_comp_units freer (dwarf2_per_objfile);
7730
7731   build_type_psymtabs (dwarf2_per_objfile);
7732
7733   create_all_comp_units (dwarf2_per_objfile);
7734
7735   /* Create a temporary address map on a temporary obstack.  We later
7736      copy this to the final obstack.  */
7737   auto_obstack temp_obstack;
7738
7739   scoped_restore save_psymtabs_addrmap
7740     = make_scoped_restore (&objfile->partial_symtabs->psymtabs_addrmap,
7741                            addrmap_create_mutable (&temp_obstack));
7742
7743   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
7744     process_psymtab_comp_unit (per_cu, false, language_minimal);
7745
7746   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7747   process_skeletonless_type_units (dwarf2_per_objfile);
7748
7749   /* Now that all TUs have been processed we can fill in the dependencies.  */
7750   if (dwarf2_per_objfile->type_unit_groups != NULL)
7751     {
7752       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups.get (),
7753                               build_type_psymtab_dependencies, dwarf2_per_objfile);
7754     }
7755
7756   if (dwarf_read_debug)
7757     print_tu_stats (dwarf2_per_objfile);
7758
7759   set_partial_user (dwarf2_per_objfile);
7760
7761   objfile->partial_symtabs->psymtabs_addrmap
7762     = addrmap_create_fixed (objfile->partial_symtabs->psymtabs_addrmap,
7763                             objfile->partial_symtabs->obstack ());
7764   /* At this point we want to keep the address map.  */
7765   save_psymtabs_addrmap.release ();
7766
7767   if (dwarf_read_debug)
7768     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
7769                         objfile_name (objfile));
7770 }
7771
7772 /* Load the partial DIEs for a secondary CU into memory.
7773    This is also used when rereading a primary CU with load_all_dies.  */
7774
7775 static void
7776 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
7777 {
7778   cutu_reader reader (this_cu, NULL, 1, false);
7779
7780   if (!reader.dummy_p)
7781     {
7782       prepare_one_comp_unit (reader.cu, reader.comp_unit_die,
7783                              language_minimal);
7784
7785       /* Check if comp unit has_children.
7786          If so, read the rest of the partial symbols from this comp unit.
7787          If not, there's no more debug_info for this comp unit.  */
7788       if (reader.comp_unit_die->has_children)
7789         load_partial_dies (&reader, reader.info_ptr, 0);
7790
7791       reader.keep ();
7792     }
7793 }
7794
7795 static void
7796 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
7797                               struct dwarf2_section_info *section,
7798                               struct dwarf2_section_info *abbrev_section,
7799                               unsigned int is_dwz)
7800 {
7801   const gdb_byte *info_ptr;
7802   struct objfile *objfile = dwarf2_per_objfile->objfile;
7803
7804   if (dwarf_read_debug)
7805     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
7806                         section->get_name (),
7807                         section->get_file_name ());
7808
7809   section->read (objfile);
7810
7811   info_ptr = section->buffer;
7812
7813   while (info_ptr < section->buffer + section->size)
7814     {
7815       struct dwarf2_per_cu_data *this_cu;
7816
7817       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7818
7819       comp_unit_head cu_header;
7820       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
7821                                      abbrev_section, info_ptr,
7822                                      rcuh_kind::COMPILE);
7823
7824       /* Save the compilation unit for later lookup.  */
7825       if (cu_header.unit_type != DW_UT_type)
7826         {
7827           this_cu = XOBNEW (&objfile->objfile_obstack,
7828                             struct dwarf2_per_cu_data);
7829           memset (this_cu, 0, sizeof (*this_cu));
7830         }
7831       else
7832         {
7833           auto sig_type = XOBNEW (&objfile->objfile_obstack,
7834                                   struct signatured_type);
7835           memset (sig_type, 0, sizeof (*sig_type));
7836           sig_type->signature = cu_header.signature;
7837           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7838           this_cu = &sig_type->per_cu;
7839         }
7840       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
7841       this_cu->sect_off = sect_off;
7842       this_cu->length = cu_header.length + cu_header.initial_length_size;
7843       this_cu->is_dwz = is_dwz;
7844       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7845       this_cu->section = section;
7846
7847       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
7848
7849       info_ptr = info_ptr + this_cu->length;
7850     }
7851 }
7852
7853 /* Create a list of all compilation units in OBJFILE.
7854    This is only done for -readnow and building partial symtabs.  */
7855
7856 static void
7857 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7858 {
7859   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
7860   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
7861                                 &dwarf2_per_objfile->abbrev, 0);
7862
7863   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
7864   if (dwz != NULL)
7865     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
7866                                   1);
7867 }
7868
7869 /* Process all loaded DIEs for compilation unit CU, starting at
7870    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7871    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7872    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7873    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7874
7875 static void
7876 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7877                       CORE_ADDR *highpc, int set_addrmap,
7878                       struct dwarf2_cu *cu)
7879 {
7880   struct partial_die_info *pdi;
7881
7882   /* Now, march along the PDI's, descending into ones which have
7883      interesting children but skipping the children of the other ones,
7884      until we reach the end of the compilation unit.  */
7885
7886   pdi = first_die;
7887
7888   while (pdi != NULL)
7889     {
7890       pdi->fixup (cu);
7891
7892       /* Anonymous namespaces or modules have no name but have interesting
7893          children, so we need to look at them.  Ditto for anonymous
7894          enums.  */
7895
7896       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
7897           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7898           || pdi->tag == DW_TAG_imported_unit
7899           || pdi->tag == DW_TAG_inlined_subroutine)
7900         {
7901           switch (pdi->tag)
7902             {
7903             case DW_TAG_subprogram:
7904             case DW_TAG_inlined_subroutine:
7905               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7906               break;
7907             case DW_TAG_constant:
7908             case DW_TAG_variable:
7909             case DW_TAG_typedef:
7910             case DW_TAG_union_type:
7911               if (!pdi->is_declaration)
7912                 {
7913                   add_partial_symbol (pdi, cu);
7914                 }
7915               break;
7916             case DW_TAG_class_type:
7917             case DW_TAG_interface_type:
7918             case DW_TAG_structure_type:
7919               if (!pdi->is_declaration)
7920                 {
7921                   add_partial_symbol (pdi, cu);
7922                 }
7923               if ((cu->language == language_rust
7924                    || cu->language == language_cplus) && pdi->has_children)
7925                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7926                                       set_addrmap, cu);
7927               break;
7928             case DW_TAG_enumeration_type:
7929               if (!pdi->is_declaration)
7930                 add_partial_enumeration (pdi, cu);
7931               break;
7932             case DW_TAG_base_type:
7933             case DW_TAG_subrange_type:
7934               /* File scope base type definitions are added to the partial
7935                  symbol table.  */
7936               add_partial_symbol (pdi, cu);
7937               break;
7938             case DW_TAG_namespace:
7939               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7940               break;
7941             case DW_TAG_module:
7942               if (!pdi->is_declaration)
7943                 add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7944               break;
7945             case DW_TAG_imported_unit:
7946               {
7947                 struct dwarf2_per_cu_data *per_cu;
7948
7949                 /* For now we don't handle imported units in type units.  */
7950                 if (cu->per_cu->is_debug_types)
7951                   {
7952                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
7953                              " supported in type units [in module %s]"),
7954                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
7955                   }
7956
7957                 per_cu = dwarf2_find_containing_comp_unit
7958                            (pdi->d.sect_off, pdi->is_dwz,
7959                             cu->per_cu->dwarf2_per_objfile);
7960
7961                 /* Go read the partial unit, if needed.  */
7962                 if (per_cu->v.psymtab == NULL)
7963                   process_psymtab_comp_unit (per_cu, true, cu->language);
7964
7965                 cu->per_cu->imported_symtabs_push (per_cu);
7966               }
7967               break;
7968             case DW_TAG_imported_declaration:
7969               add_partial_symbol (pdi, cu);
7970               break;
7971             default:
7972               break;
7973             }
7974         }
7975
7976       /* If the die has a sibling, skip to the sibling.  */
7977
7978       pdi = pdi->die_sibling;
7979     }
7980 }
7981
7982 /* Functions used to compute the fully scoped name of a partial DIE.
7983
7984    Normally, this is simple.  For C++, the parent DIE's fully scoped
7985    name is concatenated with "::" and the partial DIE's name.
7986    Enumerators are an exception; they use the scope of their parent
7987    enumeration type, i.e. the name of the enumeration type is not
7988    prepended to the enumerator.
7989
7990    There are two complexities.  One is DW_AT_specification; in this
7991    case "parent" means the parent of the target of the specification,
7992    instead of the direct parent of the DIE.  The other is compilers
7993    which do not emit DW_TAG_namespace; in this case we try to guess
7994    the fully qualified name of structure types from their members'
7995    linkage names.  This must be done using the DIE's children rather
7996    than the children of any DW_AT_specification target.  We only need
7997    to do this for structures at the top level, i.e. if the target of
7998    any DW_AT_specification (if any; otherwise the DIE itself) does not
7999    have a parent.  */
8000
8001 /* Compute the scope prefix associated with PDI's parent, in
8002    compilation unit CU.  The result will be allocated on CU's
8003    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8004    field.  NULL is returned if no prefix is necessary.  */
8005 static const char *
8006 partial_die_parent_scope (struct partial_die_info *pdi,
8007                           struct dwarf2_cu *cu)
8008 {
8009   const char *grandparent_scope;
8010   struct partial_die_info *parent, *real_pdi;
8011
8012   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8013      then this means the parent of the specification DIE.  */
8014
8015   real_pdi = pdi;
8016   while (real_pdi->has_specification)
8017     {
8018       auto res = find_partial_die (real_pdi->spec_offset,
8019                                    real_pdi->spec_is_dwz, cu);
8020       real_pdi = res.pdi;
8021       cu = res.cu;
8022     }
8023
8024   parent = real_pdi->die_parent;
8025   if (parent == NULL)
8026     return NULL;
8027
8028   if (parent->scope_set)
8029     return parent->scope;
8030
8031   parent->fixup (cu);
8032
8033   grandparent_scope = partial_die_parent_scope (parent, cu);
8034
8035   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8036      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8037      Work around this problem here.  */
8038   if (cu->language == language_cplus
8039       && parent->tag == DW_TAG_namespace
8040       && strcmp (parent->name, "::") == 0
8041       && grandparent_scope == NULL)
8042     {
8043       parent->scope = NULL;
8044       parent->scope_set = 1;
8045       return NULL;
8046     }
8047
8048   /* Nested subroutines in Fortran get a prefix.  */
8049   if (pdi->tag == DW_TAG_enumerator)
8050     /* Enumerators should not get the name of the enumeration as a prefix.  */
8051     parent->scope = grandparent_scope;
8052   else if (parent->tag == DW_TAG_namespace
8053       || parent->tag == DW_TAG_module
8054       || parent->tag == DW_TAG_structure_type
8055       || parent->tag == DW_TAG_class_type
8056       || parent->tag == DW_TAG_interface_type
8057       || parent->tag == DW_TAG_union_type
8058       || parent->tag == DW_TAG_enumeration_type
8059       || (cu->language == language_fortran
8060           && parent->tag == DW_TAG_subprogram
8061           && pdi->tag == DW_TAG_subprogram))
8062     {
8063       if (grandparent_scope == NULL)
8064         parent->scope = parent->name;
8065       else
8066         parent->scope = typename_concat (&cu->comp_unit_obstack,
8067                                          grandparent_scope,
8068                                          parent->name, 0, cu);
8069     }
8070   else
8071     {
8072       /* FIXME drow/2004-04-01: What should we be doing with
8073          function-local names?  For partial symbols, we should probably be
8074          ignoring them.  */
8075       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
8076                  dwarf_tag_name (parent->tag),
8077                  sect_offset_str (pdi->sect_off));
8078       parent->scope = grandparent_scope;
8079     }
8080
8081   parent->scope_set = 1;
8082   return parent->scope;
8083 }
8084
8085 /* Return the fully scoped name associated with PDI, from compilation unit
8086    CU.  The result will be allocated with malloc.  */
8087
8088 static gdb::unique_xmalloc_ptr<char>
8089 partial_die_full_name (struct partial_die_info *pdi,
8090                        struct dwarf2_cu *cu)
8091 {
8092   const char *parent_scope;
8093
8094   /* If this is a template instantiation, we can not work out the
8095      template arguments from partial DIEs.  So, unfortunately, we have
8096      to go through the full DIEs.  At least any work we do building
8097      types here will be reused if full symbols are loaded later.  */
8098   if (pdi->has_template_arguments)
8099     {
8100       pdi->fixup (cu);
8101
8102       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8103         {
8104           struct die_info *die;
8105           struct attribute attr;
8106           struct dwarf2_cu *ref_cu = cu;
8107
8108           /* DW_FORM_ref_addr is using section offset.  */
8109           attr.name = (enum dwarf_attribute) 0;
8110           attr.form = DW_FORM_ref_addr;
8111           attr.u.unsnd = to_underlying (pdi->sect_off);
8112           die = follow_die_ref (NULL, &attr, &ref_cu);
8113
8114           return make_unique_xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8115         }
8116     }
8117
8118   parent_scope = partial_die_parent_scope (pdi, cu);
8119   if (parent_scope == NULL)
8120     return NULL;
8121   else
8122     return gdb::unique_xmalloc_ptr<char> (typename_concat (NULL, parent_scope,
8123                                                            pdi->name, 0, cu));
8124 }
8125
8126 static void
8127 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8128 {
8129   struct dwarf2_per_objfile *dwarf2_per_objfile
8130     = cu->per_cu->dwarf2_per_objfile;
8131   struct objfile *objfile = dwarf2_per_objfile->objfile;
8132   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8133   CORE_ADDR addr = 0;
8134   const char *actual_name = NULL;
8135   CORE_ADDR baseaddr;
8136
8137   baseaddr = objfile->text_section_offset ();
8138
8139   gdb::unique_xmalloc_ptr<char> built_actual_name
8140     = partial_die_full_name (pdi, cu);
8141   if (built_actual_name != NULL)
8142     actual_name = built_actual_name.get ();
8143
8144   if (actual_name == NULL)
8145     actual_name = pdi->name;
8146
8147   switch (pdi->tag)
8148     {
8149     case DW_TAG_inlined_subroutine:
8150     case DW_TAG_subprogram:
8151       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8152               - baseaddr);
8153       if (pdi->is_external
8154           || cu->language == language_ada
8155           || (cu->language == language_fortran
8156               && pdi->die_parent != NULL
8157               && pdi->die_parent->tag == DW_TAG_subprogram))
8158         {
8159           /* Normally, only "external" DIEs are part of the global scope.
8160              But in Ada and Fortran, we want to be able to access nested
8161              procedures globally.  So all Ada and Fortran subprograms are
8162              stored in the global scope.  */
8163           add_psymbol_to_list (actual_name,
8164                                built_actual_name != NULL,
8165                                VAR_DOMAIN, LOC_BLOCK,
8166                                SECT_OFF_TEXT (objfile),
8167                                psymbol_placement::GLOBAL,
8168                                addr,
8169                                cu->language, objfile);
8170         }
8171       else
8172         {
8173           add_psymbol_to_list (actual_name,
8174                                built_actual_name != NULL,
8175                                VAR_DOMAIN, LOC_BLOCK,
8176                                SECT_OFF_TEXT (objfile),
8177                                psymbol_placement::STATIC,
8178                                addr, cu->language, objfile);
8179         }
8180
8181       if (pdi->main_subprogram && actual_name != NULL)
8182         set_objfile_main_name (objfile, actual_name, cu->language);
8183       break;
8184     case DW_TAG_constant:
8185       add_psymbol_to_list (actual_name,
8186                            built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8187                            -1, (pdi->is_external
8188                                 ? psymbol_placement::GLOBAL
8189                                 : psymbol_placement::STATIC),
8190                            0, cu->language, objfile);
8191       break;
8192     case DW_TAG_variable:
8193       if (pdi->d.locdesc)
8194         addr = decode_locdesc (pdi->d.locdesc, cu);
8195
8196       if (pdi->d.locdesc
8197           && addr == 0
8198           && !dwarf2_per_objfile->has_section_at_zero)
8199         {
8200           /* A global or static variable may also have been stripped
8201              out by the linker if unused, in which case its address
8202              will be nullified; do not add such variables into partial
8203              symbol table then.  */
8204         }
8205       else if (pdi->is_external)
8206         {
8207           /* Global Variable.
8208              Don't enter into the minimal symbol tables as there is
8209              a minimal symbol table entry from the ELF symbols already.
8210              Enter into partial symbol table if it has a location
8211              descriptor or a type.
8212              If the location descriptor is missing, new_symbol will create
8213              a LOC_UNRESOLVED symbol, the address of the variable will then
8214              be determined from the minimal symbol table whenever the variable
8215              is referenced.
8216              The address for the partial symbol table entry is not
8217              used by GDB, but it comes in handy for debugging partial symbol
8218              table building.  */
8219
8220           if (pdi->d.locdesc || pdi->has_type)
8221             add_psymbol_to_list (actual_name,
8222                                  built_actual_name != NULL,
8223                                  VAR_DOMAIN, LOC_STATIC,
8224                                  SECT_OFF_TEXT (objfile),
8225                                  psymbol_placement::GLOBAL,
8226                                  addr, cu->language, objfile);
8227         }
8228       else
8229         {
8230           int has_loc = pdi->d.locdesc != NULL;
8231
8232           /* Static Variable.  Skip symbols whose value we cannot know (those
8233              without location descriptors or constant values).  */
8234           if (!has_loc && !pdi->has_const_value)
8235             return;
8236
8237           add_psymbol_to_list (actual_name,
8238                                built_actual_name != NULL,
8239                                VAR_DOMAIN, LOC_STATIC,
8240                                SECT_OFF_TEXT (objfile),
8241                                psymbol_placement::STATIC,
8242                                has_loc ? addr : 0,
8243                                cu->language, objfile);
8244         }
8245       break;
8246     case DW_TAG_typedef:
8247     case DW_TAG_base_type:
8248     case DW_TAG_subrange_type:
8249       add_psymbol_to_list (actual_name,
8250                            built_actual_name != NULL,
8251                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8252                            psymbol_placement::STATIC,
8253                            0, cu->language, objfile);
8254       break;
8255     case DW_TAG_imported_declaration:
8256     case DW_TAG_namespace:
8257       add_psymbol_to_list (actual_name,
8258                            built_actual_name != NULL,
8259                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8260                            psymbol_placement::GLOBAL,
8261                            0, cu->language, objfile);
8262       break;
8263     case DW_TAG_module:
8264       /* With Fortran 77 there might be a "BLOCK DATA" module
8265          available without any name.  If so, we skip the module as it
8266          doesn't bring any value.  */
8267       if (actual_name != nullptr)
8268         add_psymbol_to_list (actual_name,
8269                              built_actual_name != NULL,
8270                              MODULE_DOMAIN, LOC_TYPEDEF, -1,
8271                              psymbol_placement::GLOBAL,
8272                              0, cu->language, objfile);
8273       break;
8274     case DW_TAG_class_type:
8275     case DW_TAG_interface_type:
8276     case DW_TAG_structure_type:
8277     case DW_TAG_union_type:
8278     case DW_TAG_enumeration_type:
8279       /* Skip external references.  The DWARF standard says in the section
8280          about "Structure, Union, and Class Type Entries": "An incomplete
8281          structure, union or class type is represented by a structure,
8282          union or class entry that does not have a byte size attribute
8283          and that has a DW_AT_declaration attribute."  */
8284       if (!pdi->has_byte_size && pdi->is_declaration)
8285         return;
8286
8287       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8288          static vs. global.  */
8289       add_psymbol_to_list (actual_name,
8290                            built_actual_name != NULL,
8291                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
8292                            cu->language == language_cplus
8293                            ? psymbol_placement::GLOBAL
8294                            : psymbol_placement::STATIC,
8295                            0, cu->language, objfile);
8296
8297       break;
8298     case DW_TAG_enumerator:
8299       add_psymbol_to_list (actual_name,
8300                            built_actual_name != NULL,
8301                            VAR_DOMAIN, LOC_CONST, -1,
8302                            cu->language == language_cplus
8303                            ? psymbol_placement::GLOBAL
8304                            : psymbol_placement::STATIC,
8305                            0, cu->language, objfile);
8306       break;
8307     default:
8308       break;
8309     }
8310 }
8311
8312 /* Read a partial die corresponding to a namespace; also, add a symbol
8313    corresponding to that namespace to the symbol table.  NAMESPACE is
8314    the name of the enclosing namespace.  */
8315
8316 static void
8317 add_partial_namespace (struct partial_die_info *pdi,
8318                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8319                        int set_addrmap, struct dwarf2_cu *cu)
8320 {
8321   /* Add a symbol for the namespace.  */
8322
8323   add_partial_symbol (pdi, cu);
8324
8325   /* Now scan partial symbols in that namespace.  */
8326
8327   if (pdi->has_children)
8328     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8329 }
8330
8331 /* Read a partial die corresponding to a Fortran module.  */
8332
8333 static void
8334 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8335                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8336 {
8337   /* Add a symbol for the namespace.  */
8338
8339   add_partial_symbol (pdi, cu);
8340
8341   /* Now scan partial symbols in that module.  */
8342
8343   if (pdi->has_children)
8344     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8345 }
8346
8347 /* Read a partial die corresponding to a subprogram or an inlined
8348    subprogram and create a partial symbol for that subprogram.
8349    When the CU language allows it, this routine also defines a partial
8350    symbol for each nested subprogram that this subprogram contains.
8351    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
8352    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
8353
8354    PDI may also be a lexical block, in which case we simply search
8355    recursively for subprograms defined inside that lexical block.
8356    Again, this is only performed when the CU language allows this
8357    type of definitions.  */
8358
8359 static void
8360 add_partial_subprogram (struct partial_die_info *pdi,
8361                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
8362                         int set_addrmap, struct dwarf2_cu *cu)
8363 {
8364   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
8365     {
8366       if (pdi->has_pc_info)
8367         {
8368           if (pdi->lowpc < *lowpc)
8369             *lowpc = pdi->lowpc;
8370           if (pdi->highpc > *highpc)
8371             *highpc = pdi->highpc;
8372           if (set_addrmap)
8373             {
8374               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8375               struct gdbarch *gdbarch = get_objfile_arch (objfile);
8376               CORE_ADDR baseaddr;
8377               CORE_ADDR this_highpc;
8378               CORE_ADDR this_lowpc;
8379
8380               baseaddr = objfile->text_section_offset ();
8381               this_lowpc
8382                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8383                                                pdi->lowpc + baseaddr)
8384                    - baseaddr);
8385               this_highpc
8386                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8387                                                pdi->highpc + baseaddr)
8388                    - baseaddr);
8389               addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
8390                                  this_lowpc, this_highpc - 1,
8391                                  cu->per_cu->v.psymtab);
8392             }
8393         }
8394
8395       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8396         {
8397           if (!pdi->is_declaration)
8398             /* Ignore subprogram DIEs that do not have a name, they are
8399                illegal.  Do not emit a complaint at this point, we will
8400                do so when we convert this psymtab into a symtab.  */
8401             if (pdi->name)
8402               add_partial_symbol (pdi, cu);
8403         }
8404     }
8405
8406   if (! pdi->has_children)
8407     return;
8408
8409   if (cu->language == language_ada || cu->language == language_fortran)
8410     {
8411       pdi = pdi->die_child;
8412       while (pdi != NULL)
8413         {
8414           pdi->fixup (cu);
8415           if (pdi->tag == DW_TAG_subprogram
8416               || pdi->tag == DW_TAG_inlined_subroutine
8417               || pdi->tag == DW_TAG_lexical_block)
8418             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8419           pdi = pdi->die_sibling;
8420         }
8421     }
8422 }
8423
8424 /* Read a partial die corresponding to an enumeration type.  */
8425
8426 static void
8427 add_partial_enumeration (struct partial_die_info *enum_pdi,
8428                          struct dwarf2_cu *cu)
8429 {
8430   struct partial_die_info *pdi;
8431
8432   if (enum_pdi->name != NULL)
8433     add_partial_symbol (enum_pdi, cu);
8434
8435   pdi = enum_pdi->die_child;
8436   while (pdi)
8437     {
8438       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
8439         complaint (_("malformed enumerator DIE ignored"));
8440       else
8441         add_partial_symbol (pdi, cu);
8442       pdi = pdi->die_sibling;
8443     }
8444 }
8445
8446 /* Return the initial uleb128 in the die at INFO_PTR.  */
8447
8448 static unsigned int
8449 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8450 {
8451   unsigned int bytes_read;
8452
8453   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8454 }
8455
8456 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
8457    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
8458
8459    Return the corresponding abbrev, or NULL if the number is zero (indicating
8460    an empty DIE).  In either case *BYTES_READ will be set to the length of
8461    the initial number.  */
8462
8463 static struct abbrev_info *
8464 peek_die_abbrev (const die_reader_specs &reader,
8465                  const gdb_byte *info_ptr, unsigned int *bytes_read)
8466 {
8467   dwarf2_cu *cu = reader.cu;
8468   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
8469   unsigned int abbrev_number
8470     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8471
8472   if (abbrev_number == 0)
8473     return NULL;
8474
8475   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
8476   if (!abbrev)
8477     {
8478       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8479                " at offset %s [in module %s]"),
8480              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8481              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
8482     }
8483
8484   return abbrev;
8485 }
8486
8487 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8488    Returns a pointer to the end of a series of DIEs, terminated by an empty
8489    DIE.  Any children of the skipped DIEs will also be skipped.  */
8490
8491 static const gdb_byte *
8492 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8493 {
8494   while (1)
8495     {
8496       unsigned int bytes_read;
8497       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
8498
8499       if (abbrev == NULL)
8500         return info_ptr + bytes_read;
8501       else
8502         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8503     }
8504 }
8505
8506 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8507    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8508    abbrev corresponding to that skipped uleb128 should be passed in
8509    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8510    children.  */
8511
8512 static const gdb_byte *
8513 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8514               struct abbrev_info *abbrev)
8515 {
8516   unsigned int bytes_read;
8517   struct attribute attr;
8518   bfd *abfd = reader->abfd;
8519   struct dwarf2_cu *cu = reader->cu;
8520   const gdb_byte *buffer = reader->buffer;
8521   const gdb_byte *buffer_end = reader->buffer_end;
8522   unsigned int form, i;
8523
8524   for (i = 0; i < abbrev->num_attrs; i++)
8525     {
8526       /* The only abbrev we care about is DW_AT_sibling.  */
8527       if (abbrev->attrs[i].name == DW_AT_sibling)
8528         {
8529           bool ignored;
8530           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr,
8531                           &ignored);
8532           if (attr.form == DW_FORM_ref_addr)
8533             complaint (_("ignoring absolute DW_AT_sibling"));
8534           else
8535             {
8536               sect_offset off = dwarf2_get_ref_die_offset (&attr);
8537               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8538
8539               if (sibling_ptr < info_ptr)
8540                 complaint (_("DW_AT_sibling points backwards"));
8541               else if (sibling_ptr > reader->buffer_end)
8542                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
8543               else
8544                 return sibling_ptr;
8545             }
8546         }
8547
8548       /* If it isn't DW_AT_sibling, skip this attribute.  */
8549       form = abbrev->attrs[i].form;
8550     skip_attribute:
8551       switch (form)
8552         {
8553         case DW_FORM_ref_addr:
8554           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8555              and later it is offset sized.  */
8556           if (cu->header.version == 2)
8557             info_ptr += cu->header.addr_size;
8558           else
8559             info_ptr += cu->header.offset_size;
8560           break;
8561         case DW_FORM_GNU_ref_alt:
8562           info_ptr += cu->header.offset_size;
8563           break;
8564         case DW_FORM_addr:
8565           info_ptr += cu->header.addr_size;
8566           break;
8567         case DW_FORM_data1:
8568         case DW_FORM_ref1:
8569         case DW_FORM_flag:
8570         case DW_FORM_strx1:
8571           info_ptr += 1;
8572           break;
8573         case DW_FORM_flag_present:
8574         case DW_FORM_implicit_const:
8575           break;
8576         case DW_FORM_data2:
8577         case DW_FORM_ref2:
8578         case DW_FORM_strx2:
8579           info_ptr += 2;
8580           break;
8581         case DW_FORM_strx3:
8582           info_ptr += 3;
8583           break;
8584         case DW_FORM_data4:
8585         case DW_FORM_ref4:
8586         case DW_FORM_strx4:
8587           info_ptr += 4;
8588           break;
8589         case DW_FORM_data8:
8590         case DW_FORM_ref8:
8591         case DW_FORM_ref_sig8:
8592           info_ptr += 8;
8593           break;
8594         case DW_FORM_data16:
8595           info_ptr += 16;
8596           break;
8597         case DW_FORM_string:
8598           read_direct_string (abfd, info_ptr, &bytes_read);
8599           info_ptr += bytes_read;
8600           break;
8601         case DW_FORM_sec_offset:
8602         case DW_FORM_strp:
8603         case DW_FORM_GNU_strp_alt:
8604           info_ptr += cu->header.offset_size;
8605           break;
8606         case DW_FORM_exprloc:
8607         case DW_FORM_block:
8608           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8609           info_ptr += bytes_read;
8610           break;
8611         case DW_FORM_block1:
8612           info_ptr += 1 + read_1_byte (abfd, info_ptr);
8613           break;
8614         case DW_FORM_block2:
8615           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
8616           break;
8617         case DW_FORM_block4:
8618           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
8619           break;
8620         case DW_FORM_addrx:
8621         case DW_FORM_strx:
8622         case DW_FORM_sdata:
8623         case DW_FORM_udata:
8624         case DW_FORM_ref_udata:
8625         case DW_FORM_GNU_addr_index:
8626         case DW_FORM_GNU_str_index:
8627         case DW_FORM_rnglistx:
8628           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
8629           break;
8630         case DW_FORM_indirect:
8631           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8632           info_ptr += bytes_read;
8633           /* We need to continue parsing from here, so just go back to
8634              the top.  */
8635           goto skip_attribute;
8636
8637         default:
8638           error (_("Dwarf Error: Cannot handle %s "
8639                    "in DWARF reader [in module %s]"),
8640                  dwarf_form_name (form),
8641                  bfd_get_filename (abfd));
8642         }
8643     }
8644
8645   if (abbrev->has_children)
8646     return skip_children (reader, info_ptr);
8647   else
8648     return info_ptr;
8649 }
8650
8651 /* Locate ORIG_PDI's sibling.
8652    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
8653
8654 static const gdb_byte *
8655 locate_pdi_sibling (const struct die_reader_specs *reader,
8656                     struct partial_die_info *orig_pdi,
8657                     const gdb_byte *info_ptr)
8658 {
8659   /* Do we know the sibling already?  */
8660
8661   if (orig_pdi->sibling)
8662     return orig_pdi->sibling;
8663
8664   /* Are there any children to deal with?  */
8665
8666   if (!orig_pdi->has_children)
8667     return info_ptr;
8668
8669   /* Skip the children the long way.  */
8670
8671   return skip_children (reader, info_ptr);
8672 }
8673
8674 /* Expand this partial symbol table into a full symbol table.  SELF is
8675    not NULL.  */
8676
8677 void
8678 dwarf2_psymtab::read_symtab (struct objfile *objfile)
8679 {
8680   struct dwarf2_per_objfile *dwarf2_per_objfile
8681     = get_dwarf2_per_objfile (objfile);
8682
8683   gdb_assert (!readin);
8684   /* If this psymtab is constructed from a debug-only objfile, the
8685      has_section_at_zero flag will not necessarily be correct.  We
8686      can get the correct value for this flag by looking at the data
8687      associated with the (presumably stripped) associated objfile.  */
8688   if (objfile->separate_debug_objfile_backlink)
8689     {
8690       struct dwarf2_per_objfile *dpo_backlink
8691         = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
8692
8693       dwarf2_per_objfile->has_section_at_zero
8694         = dpo_backlink->has_section_at_zero;
8695     }
8696
8697   expand_psymtab (objfile);
8698
8699   process_cu_includes (dwarf2_per_objfile);
8700 }
8701 \f
8702 /* Reading in full CUs.  */
8703
8704 /* Add PER_CU to the queue.  */
8705
8706 static void
8707 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
8708                  enum language pretend_language)
8709 {
8710   per_cu->queued = 1;
8711   per_cu->dwarf2_per_objfile->queue.emplace (per_cu, pretend_language);
8712 }
8713
8714 /* If PER_CU is not yet queued, add it to the queue.
8715    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8716    dependency.
8717    The result is non-zero if PER_CU was queued, otherwise the result is zero
8718    meaning either PER_CU is already queued or it is already loaded.
8719
8720    N.B. There is an invariant here that if a CU is queued then it is loaded.
8721    The caller is required to load PER_CU if we return non-zero.  */
8722
8723 static int
8724 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8725                        struct dwarf2_per_cu_data *per_cu,
8726                        enum language pretend_language)
8727 {
8728   /* We may arrive here during partial symbol reading, if we need full
8729      DIEs to process an unusual case (e.g. template arguments).  Do
8730      not queue PER_CU, just tell our caller to load its DIEs.  */
8731   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
8732     {
8733       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
8734         return 1;
8735       return 0;
8736     }
8737
8738   /* Mark the dependence relation so that we don't flush PER_CU
8739      too early.  */
8740   if (dependent_cu != NULL)
8741     dwarf2_add_dependence (dependent_cu, per_cu);
8742
8743   /* If it's already on the queue, we have nothing to do.  */
8744   if (per_cu->queued)
8745     return 0;
8746
8747   /* If the compilation unit is already loaded, just mark it as
8748      used.  */
8749   if (per_cu->cu != NULL)
8750     {
8751       per_cu->cu->last_used = 0;
8752       return 0;
8753     }
8754
8755   /* Add it to the queue.  */
8756   queue_comp_unit (per_cu, pretend_language);
8757
8758   return 1;
8759 }
8760
8761 /* Process the queue.  */
8762
8763 static void
8764 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
8765 {
8766   if (dwarf_read_debug)
8767     {
8768       fprintf_unfiltered (gdb_stdlog,
8769                           "Expanding one or more symtabs of objfile %s ...\n",
8770                           objfile_name (dwarf2_per_objfile->objfile));
8771     }
8772
8773   /* The queue starts out with one item, but following a DIE reference
8774      may load a new CU, adding it to the end of the queue.  */
8775   while (!dwarf2_per_objfile->queue.empty ())
8776     {
8777       dwarf2_queue_item &item = dwarf2_per_objfile->queue.front ();
8778
8779       if ((dwarf2_per_objfile->using_index
8780            ? !item.per_cu->v.quick->compunit_symtab
8781            : (item.per_cu->v.psymtab && !item.per_cu->v.psymtab->readin))
8782           /* Skip dummy CUs.  */
8783           && item.per_cu->cu != NULL)
8784         {
8785           struct dwarf2_per_cu_data *per_cu = item.per_cu;
8786           unsigned int debug_print_threshold;
8787           char buf[100];
8788
8789           if (per_cu->is_debug_types)
8790             {
8791               struct signatured_type *sig_type =
8792                 (struct signatured_type *) per_cu;
8793
8794               sprintf (buf, "TU %s at offset %s",
8795                        hex_string (sig_type->signature),
8796                        sect_offset_str (per_cu->sect_off));
8797               /* There can be 100s of TUs.
8798                  Only print them in verbose mode.  */
8799               debug_print_threshold = 2;
8800             }
8801           else
8802             {
8803               sprintf (buf, "CU at offset %s",
8804                        sect_offset_str (per_cu->sect_off));
8805               debug_print_threshold = 1;
8806             }
8807
8808           if (dwarf_read_debug >= debug_print_threshold)
8809             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
8810
8811           if (per_cu->is_debug_types)
8812             process_full_type_unit (per_cu, item.pretend_language);
8813           else
8814             process_full_comp_unit (per_cu, item.pretend_language);
8815
8816           if (dwarf_read_debug >= debug_print_threshold)
8817             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
8818         }
8819
8820       item.per_cu->queued = 0;
8821       dwarf2_per_objfile->queue.pop ();
8822     }
8823
8824   if (dwarf_read_debug)
8825     {
8826       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
8827                           objfile_name (dwarf2_per_objfile->objfile));
8828     }
8829 }
8830
8831 /* Read in full symbols for PST, and anything it depends on.  */
8832
8833 void
8834 dwarf2_psymtab::expand_psymtab (struct objfile *objfile)
8835 {
8836   struct dwarf2_per_cu_data *per_cu;
8837
8838   if (readin)
8839     return;
8840
8841   read_dependencies (objfile);
8842
8843   per_cu = per_cu_data;
8844
8845   if (per_cu == NULL)
8846     {
8847       /* It's an include file, no symbols to read for it.
8848          Everything is in the parent symtab.  */
8849       readin = true;
8850       return;
8851     }
8852
8853   dw2_do_instantiate_symtab (per_cu, false);
8854 }
8855
8856 /* Trivial hash function for die_info: the hash value of a DIE
8857    is its offset in .debug_info for this objfile.  */
8858
8859 static hashval_t
8860 die_hash (const void *item)
8861 {
8862   const struct die_info *die = (const struct die_info *) item;
8863
8864   return to_underlying (die->sect_off);
8865 }
8866
8867 /* Trivial comparison function for die_info structures: two DIEs
8868    are equal if they have the same offset.  */
8869
8870 static int
8871 die_eq (const void *item_lhs, const void *item_rhs)
8872 {
8873   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8874   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8875
8876   return die_lhs->sect_off == die_rhs->sect_off;
8877 }
8878
8879 /* Load the DIEs associated with PER_CU into memory.  */
8880
8881 static void
8882 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8883                      bool skip_partial,
8884                      enum language pretend_language)
8885 {
8886   gdb_assert (! this_cu->is_debug_types);
8887
8888   cutu_reader reader (this_cu, NULL, 1, skip_partial);
8889   if (reader.dummy_p)
8890     return;
8891
8892   struct dwarf2_cu *cu = reader.cu;
8893   const gdb_byte *info_ptr = reader.info_ptr;
8894
8895   gdb_assert (cu->die_hash == NULL);
8896   cu->die_hash =
8897     htab_create_alloc_ex (cu->header.length / 12,
8898                           die_hash,
8899                           die_eq,
8900                           NULL,
8901                           &cu->comp_unit_obstack,
8902                           hashtab_obstack_allocate,
8903                           dummy_obstack_deallocate);
8904
8905   if (reader.comp_unit_die->has_children)
8906     reader.comp_unit_die->child
8907       = read_die_and_siblings (&reader, reader.info_ptr,
8908                                &info_ptr, reader.comp_unit_die);
8909   cu->dies = reader.comp_unit_die;
8910   /* comp_unit_die is not stored in die_hash, no need.  */
8911
8912   /* We try not to read any attributes in this function, because not
8913      all CUs needed for references have been loaded yet, and symbol
8914      table processing isn't initialized.  But we have to set the CU language,
8915      or we won't be able to build types correctly.
8916      Similarly, if we do not read the producer, we can not apply
8917      producer-specific interpretation.  */
8918   prepare_one_comp_unit (cu, cu->dies, pretend_language);
8919
8920   reader.keep ();
8921 }
8922
8923 /* Add a DIE to the delayed physname list.  */
8924
8925 static void
8926 add_to_method_list (struct type *type, int fnfield_index, int index,
8927                     const char *name, struct die_info *die,
8928                     struct dwarf2_cu *cu)
8929 {
8930   struct delayed_method_info mi;
8931   mi.type = type;
8932   mi.fnfield_index = fnfield_index;
8933   mi.index = index;
8934   mi.name = name;
8935   mi.die = die;
8936   cu->method_list.push_back (mi);
8937 }
8938
8939 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8940    "const" / "volatile".  If so, decrements LEN by the length of the
8941    modifier and return true.  Otherwise return false.  */
8942
8943 template<size_t N>
8944 static bool
8945 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8946 {
8947   size_t mod_len = sizeof (mod) - 1;
8948   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8949     {
8950       len -= mod_len;
8951       return true;
8952     }
8953   return false;
8954 }
8955
8956 /* Compute the physnames of any methods on the CU's method list.
8957
8958    The computation of method physnames is delayed in order to avoid the
8959    (bad) condition that one of the method's formal parameters is of an as yet
8960    incomplete type.  */
8961
8962 static void
8963 compute_delayed_physnames (struct dwarf2_cu *cu)
8964 {
8965   /* Only C++ delays computing physnames.  */
8966   if (cu->method_list.empty ())
8967     return;
8968   gdb_assert (cu->language == language_cplus);
8969
8970   for (const delayed_method_info &mi : cu->method_list)
8971     {
8972       const char *physname;
8973       struct fn_fieldlist *fn_flp
8974         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
8975       physname = dwarf2_physname (mi.name, mi.die, cu);
8976       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
8977         = physname ? physname : "";
8978
8979       /* Since there's no tag to indicate whether a method is a
8980          const/volatile overload, extract that information out of the
8981          demangled name.  */
8982       if (physname != NULL)
8983         {
8984           size_t len = strlen (physname);
8985
8986           while (1)
8987             {
8988               if (physname[len] == ')') /* shortcut */
8989                 break;
8990               else if (check_modifier (physname, len, " const"))
8991                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
8992               else if (check_modifier (physname, len, " volatile"))
8993                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
8994               else
8995                 break;
8996             }
8997         }
8998     }
8999
9000   /* The list is no longer needed.  */
9001   cu->method_list.clear ();
9002 }
9003
9004 /* Go objects should be embedded in a DW_TAG_module DIE,
9005    and it's not clear if/how imported objects will appear.
9006    To keep Go support simple until that's worked out,
9007    go back through what we've read and create something usable.
9008    We could do this while processing each DIE, and feels kinda cleaner,
9009    but that way is more invasive.
9010    This is to, for example, allow the user to type "p var" or "b main"
9011    without having to specify the package name, and allow lookups
9012    of module.object to work in contexts that use the expression
9013    parser.  */
9014
9015 static void
9016 fixup_go_packaging (struct dwarf2_cu *cu)
9017 {
9018   gdb::unique_xmalloc_ptr<char> package_name;
9019   struct pending *list;
9020   int i;
9021
9022   for (list = *cu->get_builder ()->get_global_symbols ();
9023        list != NULL;
9024        list = list->next)
9025     {
9026       for (i = 0; i < list->nsyms; ++i)
9027         {
9028           struct symbol *sym = list->symbol[i];
9029
9030           if (sym->language () == language_go
9031               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9032             {
9033               gdb::unique_xmalloc_ptr<char> this_package_name
9034                 (go_symbol_package_name (sym));
9035
9036               if (this_package_name == NULL)
9037                 continue;
9038               if (package_name == NULL)
9039                 package_name = std::move (this_package_name);
9040               else
9041                 {
9042                   struct objfile *objfile
9043                     = cu->per_cu->dwarf2_per_objfile->objfile;
9044                   if (strcmp (package_name.get (), this_package_name.get ()) != 0)
9045                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9046                                (symbol_symtab (sym) != NULL
9047                                 ? symtab_to_filename_for_display
9048                                     (symbol_symtab (sym))
9049                                 : objfile_name (objfile)),
9050                                this_package_name.get (), package_name.get ());
9051                 }
9052             }
9053         }
9054     }
9055
9056   if (package_name != NULL)
9057     {
9058       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9059       const char *saved_package_name
9060         = obstack_strdup (&objfile->per_bfd->storage_obstack, package_name.get ());
9061       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9062                                      saved_package_name);
9063       struct symbol *sym;
9064
9065       sym = allocate_symbol (objfile);
9066       sym->set_language (language_go, &objfile->objfile_obstack);
9067       sym->compute_and_set_names (saved_package_name, false, objfile->per_bfd);
9068       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9069          e.g., "main" finds the "main" module and not C's main().  */
9070       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9071       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9072       SYMBOL_TYPE (sym) = type;
9073
9074       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
9075     }
9076 }
9077
9078 /* Allocate a fully-qualified name consisting of the two parts on the
9079    obstack.  */
9080
9081 static const char *
9082 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9083 {
9084   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9085 }
9086
9087 /* A helper that allocates a struct discriminant_info to attach to a
9088    union type.  */
9089
9090 static struct discriminant_info *
9091 alloc_discriminant_info (struct type *type, int discriminant_index,
9092                          int default_index)
9093 {
9094   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9095   gdb_assert (discriminant_index == -1
9096               || (discriminant_index >= 0
9097                   && discriminant_index < TYPE_NFIELDS (type)));
9098   gdb_assert (default_index == -1
9099               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9100
9101   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9102
9103   struct discriminant_info *disc
9104     = ((struct discriminant_info *)
9105        TYPE_ZALLOC (type,
9106                     offsetof (struct discriminant_info, discriminants)
9107                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9108   disc->default_index = default_index;
9109   disc->discriminant_index = discriminant_index;
9110
9111   struct dynamic_prop prop;
9112   prop.kind = PROP_UNDEFINED;
9113   prop.data.baton = disc;
9114
9115   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9116
9117   return disc;
9118 }
9119
9120 /* Some versions of rustc emitted enums in an unusual way.
9121
9122    Ordinary enums were emitted as unions.  The first element of each
9123    structure in the union was named "RUST$ENUM$DISR".  This element
9124    held the discriminant.
9125
9126    These versions of Rust also implemented the "non-zero"
9127    optimization.  When the enum had two values, and one is empty and
9128    the other holds a pointer that cannot be zero, the pointer is used
9129    as the discriminant, with a zero value meaning the empty variant.
9130    Here, the union's first member is of the form
9131    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9132    where the fieldnos are the indices of the fields that should be
9133    traversed in order to find the field (which may be several fields deep)
9134    and the variantname is the name of the variant of the case when the
9135    field is zero.
9136
9137    This function recognizes whether TYPE is of one of these forms,
9138    and, if so, smashes it to be a variant type.  */
9139
9140 static void
9141 quirk_rust_enum (struct type *type, struct objfile *objfile)
9142 {
9143   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9144
9145   /* We don't need to deal with empty enums.  */
9146   if (TYPE_NFIELDS (type) == 0)
9147     return;
9148
9149 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9150   if (TYPE_NFIELDS (type) == 1
9151       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9152     {
9153       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9154
9155       /* Decode the field name to find the offset of the
9156          discriminant.  */
9157       ULONGEST bit_offset = 0;
9158       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9159       while (name[0] >= '0' && name[0] <= '9')
9160         {
9161           char *tail;
9162           unsigned long index = strtoul (name, &tail, 10);
9163           name = tail;
9164           if (*name != '$'
9165               || index >= TYPE_NFIELDS (field_type)
9166               || (TYPE_FIELD_LOC_KIND (field_type, index)
9167                   != FIELD_LOC_KIND_BITPOS))
9168             {
9169               complaint (_("Could not parse Rust enum encoding string \"%s\""
9170                            "[in module %s]"),
9171                          TYPE_FIELD_NAME (type, 0),
9172                          objfile_name (objfile));
9173               return;
9174             }
9175           ++name;
9176
9177           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9178           field_type = TYPE_FIELD_TYPE (field_type, index);
9179         }
9180
9181       /* Make a union to hold the variants.  */
9182       struct type *union_type = alloc_type (objfile);
9183       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9184       TYPE_NFIELDS (union_type) = 3;
9185       TYPE_FIELDS (union_type)
9186         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9187       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9188       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9189
9190       /* Put the discriminant must at index 0.  */
9191       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9192       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9193       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9194       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9195
9196       /* The order of fields doesn't really matter, so put the real
9197          field at index 1 and the data-less field at index 2.  */
9198       struct discriminant_info *disc
9199         = alloc_discriminant_info (union_type, 0, 1);
9200       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9201       TYPE_FIELD_NAME (union_type, 1)
9202         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9203       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9204         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9205                               TYPE_FIELD_NAME (union_type, 1));
9206
9207       const char *dataless_name
9208         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9209                               name);
9210       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9211                                               dataless_name);
9212       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9213       /* NAME points into the original discriminant name, which
9214          already has the correct lifetime.  */
9215       TYPE_FIELD_NAME (union_type, 2) = name;
9216       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9217       disc->discriminants[2] = 0;
9218
9219       /* Smash this type to be a structure type.  We have to do this
9220          because the type has already been recorded.  */
9221       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9222       TYPE_NFIELDS (type) = 1;
9223       TYPE_FIELDS (type)
9224         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9225
9226       /* Install the variant part.  */
9227       TYPE_FIELD_TYPE (type, 0) = union_type;
9228       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9229       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9230     }
9231   /* A union with a single anonymous field is probably an old-style
9232      univariant enum.  */
9233   else if (TYPE_NFIELDS (type) == 1 && streq (TYPE_FIELD_NAME (type, 0), ""))
9234     {
9235       /* Smash this type to be a structure type.  We have to do this
9236          because the type has already been recorded.  */
9237       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9238
9239       /* Make a union to hold the variants.  */
9240       struct type *union_type = alloc_type (objfile);
9241       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9242       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9243       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9244       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9245       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9246
9247       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9248       const char *variant_name
9249         = rust_last_path_segment (TYPE_NAME (field_type));
9250       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9251       TYPE_NAME (field_type)
9252         = rust_fully_qualify (&objfile->objfile_obstack,
9253                               TYPE_NAME (type), variant_name);
9254
9255       /* Install the union in the outer struct type.  */
9256       TYPE_NFIELDS (type) = 1;
9257       TYPE_FIELDS (type)
9258         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9259       TYPE_FIELD_TYPE (type, 0) = union_type;
9260       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9261       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9262
9263       alloc_discriminant_info (union_type, -1, 0);
9264     }
9265   else
9266     {
9267       struct type *disr_type = nullptr;
9268       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9269         {
9270           disr_type = TYPE_FIELD_TYPE (type, i);
9271
9272           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9273             {
9274               /* All fields of a true enum will be structs.  */
9275               return;
9276             }
9277           else if (TYPE_NFIELDS (disr_type) == 0)
9278             {
9279               /* Could be data-less variant, so keep going.  */
9280               disr_type = nullptr;
9281             }
9282           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9283                            "RUST$ENUM$DISR") != 0)
9284             {
9285               /* Not a Rust enum.  */
9286               return;
9287             }
9288           else
9289             {
9290               /* Found one.  */
9291               break;
9292             }
9293         }
9294
9295       /* If we got here without a discriminant, then it's probably
9296          just a union.  */
9297       if (disr_type == nullptr)
9298         return;
9299
9300       /* Smash this type to be a structure type.  We have to do this
9301          because the type has already been recorded.  */
9302       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9303
9304       /* Make a union to hold the variants.  */
9305       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
9306       struct type *union_type = alloc_type (objfile);
9307       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9308       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
9309       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9310       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9311       TYPE_FIELDS (union_type)
9312         = (struct field *) TYPE_ZALLOC (union_type,
9313                                         (TYPE_NFIELDS (union_type)
9314                                          * sizeof (struct field)));
9315
9316       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
9317               TYPE_NFIELDS (type) * sizeof (struct field));
9318
9319       /* Install the discriminant at index 0 in the union.  */
9320       TYPE_FIELD (union_type, 0) = *disr_field;
9321       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9322       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9323
9324       /* Install the union in the outer struct type.  */
9325       TYPE_FIELD_TYPE (type, 0) = union_type;
9326       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9327       TYPE_NFIELDS (type) = 1;
9328
9329       /* Set the size and offset of the union type.  */
9330       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9331
9332       /* We need a way to find the correct discriminant given a
9333          variant name.  For convenience we build a map here.  */
9334       struct type *enum_type = FIELD_TYPE (*disr_field);
9335       std::unordered_map<std::string, ULONGEST> discriminant_map;
9336       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
9337         {
9338           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
9339             {
9340               const char *name
9341                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
9342               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
9343             }
9344         }
9345
9346       int n_fields = TYPE_NFIELDS (union_type);
9347       struct discriminant_info *disc
9348         = alloc_discriminant_info (union_type, 0, -1);
9349       /* Skip the discriminant here.  */
9350       for (int i = 1; i < n_fields; ++i)
9351         {
9352           /* Find the final word in the name of this variant's type.
9353              That name can be used to look up the correct
9354              discriminant.  */
9355           const char *variant_name
9356             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
9357                                                                   i)));
9358
9359           auto iter = discriminant_map.find (variant_name);
9360           if (iter != discriminant_map.end ())
9361             disc->discriminants[i] = iter->second;
9362
9363           /* Remove the discriminant field, if it exists.  */
9364           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
9365           if (TYPE_NFIELDS (sub_type) > 0)
9366             {
9367               --TYPE_NFIELDS (sub_type);
9368               ++TYPE_FIELDS (sub_type);
9369             }
9370           TYPE_FIELD_NAME (union_type, i) = variant_name;
9371           TYPE_NAME (sub_type)
9372             = rust_fully_qualify (&objfile->objfile_obstack,
9373                                   TYPE_NAME (type), variant_name);
9374         }
9375     }
9376 }
9377
9378 /* Rewrite some Rust unions to be structures with variants parts.  */
9379
9380 static void
9381 rust_union_quirks (struct dwarf2_cu *cu)
9382 {
9383   gdb_assert (cu->language == language_rust);
9384   for (type *type_ : cu->rust_unions)
9385     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
9386   /* We don't need this any more.  */
9387   cu->rust_unions.clear ();
9388 }
9389
9390 /* Return the symtab for PER_CU.  This works properly regardless of
9391    whether we're using the index or psymtabs.  */
9392
9393 static struct compunit_symtab *
9394 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
9395 {
9396   return (per_cu->dwarf2_per_objfile->using_index
9397           ? per_cu->v.quick->compunit_symtab
9398           : per_cu->v.psymtab->compunit_symtab);
9399 }
9400
9401 /* A helper function for computing the list of all symbol tables
9402    included by PER_CU.  */
9403
9404 static void
9405 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
9406                                 htab_t all_children, htab_t all_type_symtabs,
9407                                 struct dwarf2_per_cu_data *per_cu,
9408                                 struct compunit_symtab *immediate_parent)
9409 {
9410   void **slot;
9411   struct compunit_symtab *cust;
9412
9413   slot = htab_find_slot (all_children, per_cu, INSERT);
9414   if (*slot != NULL)
9415     {
9416       /* This inclusion and its children have been processed.  */
9417       return;
9418     }
9419
9420   *slot = per_cu;
9421   /* Only add a CU if it has a symbol table.  */
9422   cust = get_compunit_symtab (per_cu);
9423   if (cust != NULL)
9424     {
9425       /* If this is a type unit only add its symbol table if we haven't
9426          seen it yet (type unit per_cu's can share symtabs).  */
9427       if (per_cu->is_debug_types)
9428         {
9429           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9430           if (*slot == NULL)
9431             {
9432               *slot = cust;
9433               result->push_back (cust);
9434               if (cust->user == NULL)
9435                 cust->user = immediate_parent;
9436             }
9437         }
9438       else
9439         {
9440           result->push_back (cust);
9441           if (cust->user == NULL)
9442             cust->user = immediate_parent;
9443         }
9444     }
9445
9446   if (!per_cu->imported_symtabs_empty ())
9447     for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9448       {
9449         recursively_compute_inclusions (result, all_children,
9450                                         all_type_symtabs, ptr, cust);
9451       }
9452 }
9453
9454 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9455    PER_CU.  */
9456
9457 static void
9458 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
9459 {
9460   gdb_assert (! per_cu->is_debug_types);
9461
9462   if (!per_cu->imported_symtabs_empty ())
9463     {
9464       int len;
9465       std::vector<compunit_symtab *> result_symtabs;
9466       htab_t all_children, all_type_symtabs;
9467       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
9468
9469       /* If we don't have a symtab, we can just skip this case.  */
9470       if (cust == NULL)
9471         return;
9472
9473       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9474                                         NULL, xcalloc, xfree);
9475       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9476                                             NULL, xcalloc, xfree);
9477
9478       for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9479         {
9480           recursively_compute_inclusions (&result_symtabs, all_children,
9481                                           all_type_symtabs, ptr, cust);
9482         }
9483
9484       /* Now we have a transitive closure of all the included symtabs.  */
9485       len = result_symtabs.size ();
9486       cust->includes
9487         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
9488                      struct compunit_symtab *, len + 1);
9489       memcpy (cust->includes, result_symtabs.data (),
9490               len * sizeof (compunit_symtab *));
9491       cust->includes[len] = NULL;
9492
9493       htab_delete (all_children);
9494       htab_delete (all_type_symtabs);
9495     }
9496 }
9497
9498 /* Compute the 'includes' field for the symtabs of all the CUs we just
9499    read.  */
9500
9501 static void
9502 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
9503 {
9504   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
9505     {
9506       if (! iter->is_debug_types)
9507         compute_compunit_symtab_includes (iter);
9508     }
9509
9510   dwarf2_per_objfile->just_read_cus.clear ();
9511 }
9512
9513 /* Generate full symbol information for PER_CU, whose DIEs have
9514    already been loaded into memory.  */
9515
9516 static void
9517 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
9518                         enum language pretend_language)
9519 {
9520   struct dwarf2_cu *cu = per_cu->cu;
9521   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
9522   struct objfile *objfile = dwarf2_per_objfile->objfile;
9523   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9524   CORE_ADDR lowpc, highpc;
9525   struct compunit_symtab *cust;
9526   CORE_ADDR baseaddr;
9527   struct block *static_block;
9528   CORE_ADDR addr;
9529
9530   baseaddr = objfile->text_section_offset ();
9531
9532   /* Clear the list here in case something was left over.  */
9533   cu->method_list.clear ();
9534
9535   cu->language = pretend_language;
9536   cu->language_defn = language_def (cu->language);
9537
9538   /* Do line number decoding in read_file_scope () */
9539   process_die (cu->dies, cu);
9540
9541   /* For now fudge the Go package.  */
9542   if (cu->language == language_go)
9543     fixup_go_packaging (cu);
9544
9545   /* Now that we have processed all the DIEs in the CU, all the types
9546      should be complete, and it should now be safe to compute all of the
9547      physnames.  */
9548   compute_delayed_physnames (cu);
9549
9550   if (cu->language == language_rust)
9551     rust_union_quirks (cu);
9552
9553   /* Some compilers don't define a DW_AT_high_pc attribute for the
9554      compilation unit.  If the DW_AT_high_pc is missing, synthesize
9555      it, by scanning the DIE's below the compilation unit.  */
9556   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
9557
9558   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
9559   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
9560
9561   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
9562      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
9563      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
9564      addrmap to help ensure it has an accurate map of pc values belonging to
9565      this comp unit.  */
9566   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
9567
9568   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
9569                                                     SECT_OFF_TEXT (objfile),
9570                                                     0);
9571
9572   if (cust != NULL)
9573     {
9574       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
9575
9576       /* Set symtab language to language from DW_AT_language.  If the
9577          compilation is from a C file generated by language preprocessors, do
9578          not set the language if it was already deduced by start_subfile.  */
9579       if (!(cu->language == language_c
9580             && COMPUNIT_FILETABS (cust)->language != language_unknown))
9581         COMPUNIT_FILETABS (cust)->language = cu->language;
9582
9583       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
9584          produce DW_AT_location with location lists but it can be possibly
9585          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
9586          there were bugs in prologue debug info, fixed later in GCC-4.5
9587          by "unwind info for epilogues" patch (which is not directly related).
9588
9589          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
9590          needed, it would be wrong due to missing DW_AT_producer there.
9591
9592          Still one can confuse GDB by using non-standard GCC compilation
9593          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
9594          */
9595       if (cu->has_loclist && gcc_4_minor >= 5)
9596         cust->locations_valid = 1;
9597
9598       if (gcc_4_minor >= 5)
9599         cust->epilogue_unwind_valid = 1;
9600
9601       cust->call_site_htab = cu->call_site_htab;
9602     }
9603
9604   if (dwarf2_per_objfile->using_index)
9605     per_cu->v.quick->compunit_symtab = cust;
9606   else
9607     {
9608       dwarf2_psymtab *pst = per_cu->v.psymtab;
9609       pst->compunit_symtab = cust;
9610       pst->readin = true;
9611     }
9612
9613   /* Push it for inclusion processing later.  */
9614   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
9615
9616   /* Not needed any more.  */
9617   cu->reset_builder ();
9618 }
9619
9620 /* Generate full symbol information for type unit PER_CU, whose DIEs have
9621    already been loaded into memory.  */
9622
9623 static void
9624 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
9625                         enum language pretend_language)
9626 {
9627   struct dwarf2_cu *cu = per_cu->cu;
9628   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
9629   struct objfile *objfile = dwarf2_per_objfile->objfile;
9630   struct compunit_symtab *cust;
9631   struct signatured_type *sig_type;
9632
9633   gdb_assert (per_cu->is_debug_types);
9634   sig_type = (struct signatured_type *) per_cu;
9635
9636   /* Clear the list here in case something was left over.  */
9637   cu->method_list.clear ();
9638
9639   cu->language = pretend_language;
9640   cu->language_defn = language_def (cu->language);
9641
9642   /* The symbol tables are set up in read_type_unit_scope.  */
9643   process_die (cu->dies, cu);
9644
9645   /* For now fudge the Go package.  */
9646   if (cu->language == language_go)
9647     fixup_go_packaging (cu);
9648
9649   /* Now that we have processed all the DIEs in the CU, all the types
9650      should be complete, and it should now be safe to compute all of the
9651      physnames.  */
9652   compute_delayed_physnames (cu);
9653
9654   if (cu->language == language_rust)
9655     rust_union_quirks (cu);
9656
9657   /* TUs share symbol tables.
9658      If this is the first TU to use this symtab, complete the construction
9659      of it with end_expandable_symtab.  Otherwise, complete the addition of
9660      this TU's symbols to the existing symtab.  */
9661   if (sig_type->type_unit_group->compunit_symtab == NULL)
9662     {
9663       buildsym_compunit *builder = cu->get_builder ();
9664       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
9665       sig_type->type_unit_group->compunit_symtab = cust;
9666
9667       if (cust != NULL)
9668         {
9669           /* Set symtab language to language from DW_AT_language.  If the
9670              compilation is from a C file generated by language preprocessors,
9671              do not set the language if it was already deduced by
9672              start_subfile.  */
9673           if (!(cu->language == language_c
9674                 && COMPUNIT_FILETABS (cust)->language != language_c))
9675             COMPUNIT_FILETABS (cust)->language = cu->language;
9676         }
9677     }
9678   else
9679     {
9680       cu->get_builder ()->augment_type_symtab ();
9681       cust = sig_type->type_unit_group->compunit_symtab;
9682     }
9683
9684   if (dwarf2_per_objfile->using_index)
9685     per_cu->v.quick->compunit_symtab = cust;
9686   else
9687     {
9688       dwarf2_psymtab *pst = per_cu->v.psymtab;
9689       pst->compunit_symtab = cust;
9690       pst->readin = true;
9691     }
9692
9693   /* Not needed any more.  */
9694   cu->reset_builder ();
9695 }
9696
9697 /* Process an imported unit DIE.  */
9698
9699 static void
9700 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
9701 {
9702   struct attribute *attr;
9703
9704   /* For now we don't handle imported units in type units.  */
9705   if (cu->per_cu->is_debug_types)
9706     {
9707       error (_("Dwarf Error: DW_TAG_imported_unit is not"
9708                " supported in type units [in module %s]"),
9709              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9710     }
9711
9712   attr = dwarf2_attr (die, DW_AT_import, cu);
9713   if (attr != NULL)
9714     {
9715       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9716       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
9717       dwarf2_per_cu_data *per_cu
9718         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
9719                                             cu->per_cu->dwarf2_per_objfile);
9720
9721       /* If necessary, add it to the queue and load its DIEs.  */
9722       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
9723         load_full_comp_unit (per_cu, false, cu->language);
9724
9725       cu->per_cu->imported_symtabs_push (per_cu);
9726     }
9727 }
9728
9729 /* RAII object that represents a process_die scope: i.e.,
9730    starts/finishes processing a DIE.  */
9731 class process_die_scope
9732 {
9733 public:
9734   process_die_scope (die_info *die, dwarf2_cu *cu)
9735     : m_die (die), m_cu (cu)
9736   {
9737     /* We should only be processing DIEs not already in process.  */
9738     gdb_assert (!m_die->in_process);
9739     m_die->in_process = true;
9740   }
9741
9742   ~process_die_scope ()
9743   {
9744     m_die->in_process = false;
9745
9746     /* If we're done processing the DIE for the CU that owns the line
9747        header, we don't need the line header anymore.  */
9748     if (m_cu->line_header_die_owner == m_die)
9749       {
9750         delete m_cu->line_header;
9751         m_cu->line_header = NULL;
9752         m_cu->line_header_die_owner = NULL;
9753       }
9754   }
9755
9756 private:
9757   die_info *m_die;
9758   dwarf2_cu *m_cu;
9759 };
9760
9761 /* Process a die and its children.  */
9762
9763 static void
9764 process_die (struct die_info *die, struct dwarf2_cu *cu)
9765 {
9766   process_die_scope scope (die, cu);
9767
9768   switch (die->tag)
9769     {
9770     case DW_TAG_padding:
9771       break;
9772     case DW_TAG_compile_unit:
9773     case DW_TAG_partial_unit:
9774       read_file_scope (die, cu);
9775       break;
9776     case DW_TAG_type_unit:
9777       read_type_unit_scope (die, cu);
9778       break;
9779     case DW_TAG_subprogram:
9780       /* Nested subprograms in Fortran get a prefix.  */
9781       if (cu->language == language_fortran
9782           && die->parent != NULL
9783           && die->parent->tag == DW_TAG_subprogram)
9784         cu->processing_has_namespace_info = true;
9785       /* Fall through.  */
9786     case DW_TAG_inlined_subroutine:
9787       read_func_scope (die, cu);
9788       break;
9789     case DW_TAG_lexical_block:
9790     case DW_TAG_try_block:
9791     case DW_TAG_catch_block:
9792       read_lexical_block_scope (die, cu);
9793       break;
9794     case DW_TAG_call_site:
9795     case DW_TAG_GNU_call_site:
9796       read_call_site_scope (die, cu);
9797       break;
9798     case DW_TAG_class_type:
9799     case DW_TAG_interface_type:
9800     case DW_TAG_structure_type:
9801     case DW_TAG_union_type:
9802       process_structure_scope (die, cu);
9803       break;
9804     case DW_TAG_enumeration_type:
9805       process_enumeration_scope (die, cu);
9806       break;
9807
9808     /* These dies have a type, but processing them does not create
9809        a symbol or recurse to process the children.  Therefore we can
9810        read them on-demand through read_type_die.  */
9811     case DW_TAG_subroutine_type:
9812     case DW_TAG_set_type:
9813     case DW_TAG_array_type:
9814     case DW_TAG_pointer_type:
9815     case DW_TAG_ptr_to_member_type:
9816     case DW_TAG_reference_type:
9817     case DW_TAG_rvalue_reference_type:
9818     case DW_TAG_string_type:
9819       break;
9820
9821     case DW_TAG_base_type:
9822     case DW_TAG_subrange_type:
9823     case DW_TAG_typedef:
9824       /* Add a typedef symbol for the type definition, if it has a
9825          DW_AT_name.  */
9826       new_symbol (die, read_type_die (die, cu), cu);
9827       break;
9828     case DW_TAG_common_block:
9829       read_common_block (die, cu);
9830       break;
9831     case DW_TAG_common_inclusion:
9832       break;
9833     case DW_TAG_namespace:
9834       cu->processing_has_namespace_info = true;
9835       read_namespace (die, cu);
9836       break;
9837     case DW_TAG_module:
9838       cu->processing_has_namespace_info = true;
9839       read_module (die, cu);
9840       break;
9841     case DW_TAG_imported_declaration:
9842       cu->processing_has_namespace_info = true;
9843       if (read_namespace_alias (die, cu))
9844         break;
9845       /* The declaration is not a global namespace alias.  */
9846       /* Fall through.  */
9847     case DW_TAG_imported_module:
9848       cu->processing_has_namespace_info = true;
9849       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
9850                                  || cu->language != language_fortran))
9851         complaint (_("Tag '%s' has unexpected children"),
9852                    dwarf_tag_name (die->tag));
9853       read_import_statement (die, cu);
9854       break;
9855
9856     case DW_TAG_imported_unit:
9857       process_imported_unit_die (die, cu);
9858       break;
9859
9860     case DW_TAG_variable:
9861       read_variable (die, cu);
9862       break;
9863
9864     default:
9865       new_symbol (die, NULL, cu);
9866       break;
9867     }
9868 }
9869 \f
9870 /* DWARF name computation.  */
9871
9872 /* A helper function for dwarf2_compute_name which determines whether DIE
9873    needs to have the name of the scope prepended to the name listed in the
9874    die.  */
9875
9876 static int
9877 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
9878 {
9879   struct attribute *attr;
9880
9881   switch (die->tag)
9882     {
9883     case DW_TAG_namespace:
9884     case DW_TAG_typedef:
9885     case DW_TAG_class_type:
9886     case DW_TAG_interface_type:
9887     case DW_TAG_structure_type:
9888     case DW_TAG_union_type:
9889     case DW_TAG_enumeration_type:
9890     case DW_TAG_enumerator:
9891     case DW_TAG_subprogram:
9892     case DW_TAG_inlined_subroutine:
9893     case DW_TAG_member:
9894     case DW_TAG_imported_declaration:
9895       return 1;
9896
9897     case DW_TAG_variable:
9898     case DW_TAG_constant:
9899       /* We only need to prefix "globally" visible variables.  These include
9900          any variable marked with DW_AT_external or any variable that
9901          lives in a namespace.  [Variables in anonymous namespaces
9902          require prefixing, but they are not DW_AT_external.]  */
9903
9904       if (dwarf2_attr (die, DW_AT_specification, cu))
9905         {
9906           struct dwarf2_cu *spec_cu = cu;
9907
9908           return die_needs_namespace (die_specification (die, &spec_cu),
9909                                       spec_cu);
9910         }
9911
9912       attr = dwarf2_attr (die, DW_AT_external, cu);
9913       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9914           && die->parent->tag != DW_TAG_module)
9915         return 0;
9916       /* A variable in a lexical block of some kind does not need a
9917          namespace, even though in C++ such variables may be external
9918          and have a mangled name.  */
9919       if (die->parent->tag ==  DW_TAG_lexical_block
9920           || die->parent->tag ==  DW_TAG_try_block
9921           || die->parent->tag ==  DW_TAG_catch_block
9922           || die->parent->tag == DW_TAG_subprogram)
9923         return 0;
9924       return 1;
9925
9926     default:
9927       return 0;
9928     }
9929 }
9930
9931 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9932    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9933    defined for the given DIE.  */
9934
9935 static struct attribute *
9936 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9937 {
9938   struct attribute *attr;
9939
9940   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9941   if (attr == NULL)
9942     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9943
9944   return attr;
9945 }
9946
9947 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9948    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9949    defined for the given DIE.  */
9950
9951 static const char *
9952 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9953 {
9954   const char *linkage_name;
9955
9956   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9957   if (linkage_name == NULL)
9958     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9959
9960   return linkage_name;
9961 }
9962
9963 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9964    compute the physname for the object, which include a method's:
9965    - formal parameters (C++),
9966    - receiver type (Go),
9967
9968    The term "physname" is a bit confusing.
9969    For C++, for example, it is the demangled name.
9970    For Go, for example, it's the mangled name.
9971
9972    For Ada, return the DIE's linkage name rather than the fully qualified
9973    name.  PHYSNAME is ignored..
9974
9975    The result is allocated on the objfile_obstack and canonicalized.  */
9976
9977 static const char *
9978 dwarf2_compute_name (const char *name,
9979                      struct die_info *die, struct dwarf2_cu *cu,
9980                      int physname)
9981 {
9982   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9983
9984   if (name == NULL)
9985     name = dwarf2_name (die, cu);
9986
9987   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9988      but otherwise compute it by typename_concat inside GDB.
9989      FIXME: Actually this is not really true, or at least not always true.
9990      It's all very confusing.  compute_and_set_names doesn't try to demangle
9991      Fortran names because there is no mangling standard.  So new_symbol
9992      will set the demangled name to the result of dwarf2_full_name, and it is
9993      the demangled name that GDB uses if it exists.  */
9994   if (cu->language == language_ada
9995       || (cu->language == language_fortran && physname))
9996     {
9997       /* For Ada unit, we prefer the linkage name over the name, as
9998          the former contains the exported name, which the user expects
9999          to be able to reference.  Ideally, we want the user to be able
10000          to reference this entity using either natural or linkage name,
10001          but we haven't started looking at this enhancement yet.  */
10002       const char *linkage_name = dw2_linkage_name (die, cu);
10003
10004       if (linkage_name != NULL)
10005         return linkage_name;
10006     }
10007
10008   /* These are the only languages we know how to qualify names in.  */
10009   if (name != NULL
10010       && (cu->language == language_cplus
10011           || cu->language == language_fortran || cu->language == language_d
10012           || cu->language == language_rust))
10013     {
10014       if (die_needs_namespace (die, cu))
10015         {
10016           const char *prefix;
10017           const char *canonical_name = NULL;
10018
10019           string_file buf;
10020
10021           prefix = determine_prefix (die, cu);
10022           if (*prefix != '\0')
10023             {
10024               gdb::unique_xmalloc_ptr<char> prefixed_name
10025                 (typename_concat (NULL, prefix, name, physname, cu));
10026
10027               buf.puts (prefixed_name.get ());
10028             }
10029           else
10030             buf.puts (name);
10031
10032           /* Template parameters may be specified in the DIE's DW_AT_name, or
10033              as children with DW_TAG_template_type_param or
10034              DW_TAG_value_type_param.  If the latter, add them to the name
10035              here.  If the name already has template parameters, then
10036              skip this step; some versions of GCC emit both, and
10037              it is more efficient to use the pre-computed name.
10038
10039              Something to keep in mind about this process: it is very
10040              unlikely, or in some cases downright impossible, to produce
10041              something that will match the mangled name of a function.
10042              If the definition of the function has the same debug info,
10043              we should be able to match up with it anyway.  But fallbacks
10044              using the minimal symbol, for instance to find a method
10045              implemented in a stripped copy of libstdc++, will not work.
10046              If we do not have debug info for the definition, we will have to
10047              match them up some other way.
10048
10049              When we do name matching there is a related problem with function
10050              templates; two instantiated function templates are allowed to
10051              differ only by their return types, which we do not add here.  */
10052
10053           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10054             {
10055               struct attribute *attr;
10056               struct die_info *child;
10057               int first = 1;
10058
10059               die->building_fullname = 1;
10060
10061               for (child = die->child; child != NULL; child = child->sibling)
10062                 {
10063                   struct type *type;
10064                   LONGEST value;
10065                   const gdb_byte *bytes;
10066                   struct dwarf2_locexpr_baton *baton;
10067                   struct value *v;
10068
10069                   if (child->tag != DW_TAG_template_type_param
10070                       && child->tag != DW_TAG_template_value_param)
10071                     continue;
10072
10073                   if (first)
10074                     {
10075                       buf.puts ("<");
10076                       first = 0;
10077                     }
10078                   else
10079                     buf.puts (", ");
10080
10081                   attr = dwarf2_attr (child, DW_AT_type, cu);
10082                   if (attr == NULL)
10083                     {
10084                       complaint (_("template parameter missing DW_AT_type"));
10085                       buf.puts ("UNKNOWN_TYPE");
10086                       continue;
10087                     }
10088                   type = die_type (child, cu);
10089
10090                   if (child->tag == DW_TAG_template_type_param)
10091                     {
10092                       c_print_type (type, "", &buf, -1, 0, cu->language,
10093                                     &type_print_raw_options);
10094                       continue;
10095                     }
10096
10097                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10098                   if (attr == NULL)
10099                     {
10100                       complaint (_("template parameter missing "
10101                                    "DW_AT_const_value"));
10102                       buf.puts ("UNKNOWN_VALUE");
10103                       continue;
10104                     }
10105
10106                   dwarf2_const_value_attr (attr, type, name,
10107                                            &cu->comp_unit_obstack, cu,
10108                                            &value, &bytes, &baton);
10109
10110                   if (TYPE_NOSIGN (type))
10111                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10112                        changed, this can use value_print instead.  */
10113                     c_printchar (value, type, &buf);
10114                   else
10115                     {
10116                       struct value_print_options opts;
10117
10118                       if (baton != NULL)
10119                         v = dwarf2_evaluate_loc_desc (type, NULL,
10120                                                       baton->data,
10121                                                       baton->size,
10122                                                       baton->per_cu);
10123                       else if (bytes != NULL)
10124                         {
10125                           v = allocate_value (type);
10126                           memcpy (value_contents_writeable (v), bytes,
10127                                   TYPE_LENGTH (type));
10128                         }
10129                       else
10130                         v = value_from_longest (type, value);
10131
10132                       /* Specify decimal so that we do not depend on
10133                          the radix.  */
10134                       get_formatted_print_options (&opts, 'd');
10135                       opts.raw = 1;
10136                       value_print (v, &buf, &opts);
10137                       release_value (v);
10138                     }
10139                 }
10140
10141               die->building_fullname = 0;
10142
10143               if (!first)
10144                 {
10145                   /* Close the argument list, with a space if necessary
10146                      (nested templates).  */
10147                   if (!buf.empty () && buf.string ().back () == '>')
10148                     buf.puts (" >");
10149                   else
10150                     buf.puts (">");
10151                 }
10152             }
10153
10154           /* For C++ methods, append formal parameter type
10155              information, if PHYSNAME.  */
10156
10157           if (physname && die->tag == DW_TAG_subprogram
10158               && cu->language == language_cplus)
10159             {
10160               struct type *type = read_type_die (die, cu);
10161
10162               c_type_print_args (type, &buf, 1, cu->language,
10163                                  &type_print_raw_options);
10164
10165               if (cu->language == language_cplus)
10166                 {
10167                   /* Assume that an artificial first parameter is
10168                      "this", but do not crash if it is not.  RealView
10169                      marks unnamed (and thus unused) parameters as
10170                      artificial; there is no way to differentiate
10171                      the two cases.  */
10172                   if (TYPE_NFIELDS (type) > 0
10173                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10174                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10175                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10176                                                                         0))))
10177                     buf.puts (" const");
10178                 }
10179             }
10180
10181           const std::string &intermediate_name = buf.string ();
10182
10183           if (cu->language == language_cplus)
10184             canonical_name
10185               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10186                                           &objfile->per_bfd->storage_obstack);
10187
10188           /* If we only computed INTERMEDIATE_NAME, or if
10189              INTERMEDIATE_NAME is already canonical, then we need to
10190              copy it to the appropriate obstack.  */
10191           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10192             name = obstack_strdup (&objfile->per_bfd->storage_obstack,
10193                                    intermediate_name);
10194           else
10195             name = canonical_name;
10196         }
10197     }
10198
10199   return name;
10200 }
10201
10202 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10203    If scope qualifiers are appropriate they will be added.  The result
10204    will be allocated on the storage_obstack, or NULL if the DIE does
10205    not have a name.  NAME may either be from a previous call to
10206    dwarf2_name or NULL.
10207
10208    The output string will be canonicalized (if C++).  */
10209
10210 static const char *
10211 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10212 {
10213   return dwarf2_compute_name (name, die, cu, 0);
10214 }
10215
10216 /* Construct a physname for the given DIE in CU.  NAME may either be
10217    from a previous call to dwarf2_name or NULL.  The result will be
10218    allocated on the objfile_objstack or NULL if the DIE does not have a
10219    name.
10220
10221    The output string will be canonicalized (if C++).  */
10222
10223 static const char *
10224 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10225 {
10226   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10227   const char *retval, *mangled = NULL, *canon = NULL;
10228   int need_copy = 1;
10229
10230   /* In this case dwarf2_compute_name is just a shortcut not building anything
10231      on its own.  */
10232   if (!die_needs_namespace (die, cu))
10233     return dwarf2_compute_name (name, die, cu, 1);
10234
10235   mangled = dw2_linkage_name (die, cu);
10236
10237   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10238      See https://github.com/rust-lang/rust/issues/32925.  */
10239   if (cu->language == language_rust && mangled != NULL
10240       && strchr (mangled, '{') != NULL)
10241     mangled = NULL;
10242
10243   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10244      has computed.  */
10245   gdb::unique_xmalloc_ptr<char> demangled;
10246   if (mangled != NULL)
10247     {
10248
10249       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10250         {
10251           /* Do nothing (do not demangle the symbol name).  */
10252         }
10253       else if (cu->language == language_go)
10254         {
10255           /* This is a lie, but we already lie to the caller new_symbol.
10256              new_symbol assumes we return the mangled name.
10257              This just undoes that lie until things are cleaned up.  */
10258         }
10259       else
10260         {
10261           /* Use DMGL_RET_DROP for C++ template functions to suppress
10262              their return type.  It is easier for GDB users to search
10263              for such functions as `name(params)' than `long name(params)'.
10264              In such case the minimal symbol names do not match the full
10265              symbol names but for template functions there is never a need
10266              to look up their definition from their declaration so
10267              the only disadvantage remains the minimal symbol variant
10268              `long name(params)' does not have the proper inferior type.  */
10269           demangled.reset (gdb_demangle (mangled,
10270                                          (DMGL_PARAMS | DMGL_ANSI
10271                                           | DMGL_RET_DROP)));
10272         }
10273       if (demangled)
10274         canon = demangled.get ();
10275       else
10276         {
10277           canon = mangled;
10278           need_copy = 0;
10279         }
10280     }
10281
10282   if (canon == NULL || check_physname)
10283     {
10284       const char *physname = dwarf2_compute_name (name, die, cu, 1);
10285
10286       if (canon != NULL && strcmp (physname, canon) != 0)
10287         {
10288           /* It may not mean a bug in GDB.  The compiler could also
10289              compute DW_AT_linkage_name incorrectly.  But in such case
10290              GDB would need to be bug-to-bug compatible.  */
10291
10292           complaint (_("Computed physname <%s> does not match demangled <%s> "
10293                        "(from linkage <%s>) - DIE at %s [in module %s]"),
10294                      physname, canon, mangled, sect_offset_str (die->sect_off),
10295                      objfile_name (objfile));
10296
10297           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
10298              is available here - over computed PHYSNAME.  It is safer
10299              against both buggy GDB and buggy compilers.  */
10300
10301           retval = canon;
10302         }
10303       else
10304         {
10305           retval = physname;
10306           need_copy = 0;
10307         }
10308     }
10309   else
10310     retval = canon;
10311
10312   if (need_copy)
10313     retval = obstack_strdup (&objfile->per_bfd->storage_obstack, retval);
10314
10315   return retval;
10316 }
10317
10318 /* Inspect DIE in CU for a namespace alias.  If one exists, record
10319    a new symbol for it.
10320
10321    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
10322
10323 static int
10324 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
10325 {
10326   struct attribute *attr;
10327
10328   /* If the die does not have a name, this is not a namespace
10329      alias.  */
10330   attr = dwarf2_attr (die, DW_AT_name, cu);
10331   if (attr != NULL)
10332     {
10333       int num;
10334       struct die_info *d = die;
10335       struct dwarf2_cu *imported_cu = cu;
10336
10337       /* If the compiler has nested DW_AT_imported_declaration DIEs,
10338          keep inspecting DIEs until we hit the underlying import.  */
10339 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
10340       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
10341         {
10342           attr = dwarf2_attr (d, DW_AT_import, cu);
10343           if (attr == NULL)
10344             break;
10345
10346           d = follow_die_ref (d, attr, &imported_cu);
10347           if (d->tag != DW_TAG_imported_declaration)
10348             break;
10349         }
10350
10351       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10352         {
10353           complaint (_("DIE at %s has too many recursively imported "
10354                        "declarations"), sect_offset_str (d->sect_off));
10355           return 0;
10356         }
10357
10358       if (attr != NULL)
10359         {
10360           struct type *type;
10361           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10362
10363           type = get_die_type_at_offset (sect_off, cu->per_cu);
10364           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
10365             {
10366               /* This declaration is a global namespace alias.  Add
10367                  a symbol for it whose type is the aliased namespace.  */
10368               new_symbol (die, type, cu);
10369               return 1;
10370             }
10371         }
10372     }
10373
10374   return 0;
10375 }
10376
10377 /* Return the using directives repository (global or local?) to use in the
10378    current context for CU.
10379
10380    For Ada, imported declarations can materialize renamings, which *may* be
10381    global.  However it is impossible (for now?) in DWARF to distinguish
10382    "external" imported declarations and "static" ones.  As all imported
10383    declarations seem to be static in all other languages, make them all CU-wide
10384    global only in Ada.  */
10385
10386 static struct using_direct **
10387 using_directives (struct dwarf2_cu *cu)
10388 {
10389   if (cu->language == language_ada
10390       && cu->get_builder ()->outermost_context_p ())
10391     return cu->get_builder ()->get_global_using_directives ();
10392   else
10393     return cu->get_builder ()->get_local_using_directives ();
10394 }
10395
10396 /* Read the import statement specified by the given die and record it.  */
10397
10398 static void
10399 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10400 {
10401   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10402   struct attribute *import_attr;
10403   struct die_info *imported_die, *child_die;
10404   struct dwarf2_cu *imported_cu;
10405   const char *imported_name;
10406   const char *imported_name_prefix;
10407   const char *canonical_name;
10408   const char *import_alias;
10409   const char *imported_declaration = NULL;
10410   const char *import_prefix;
10411   std::vector<const char *> excludes;
10412
10413   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10414   if (import_attr == NULL)
10415     {
10416       complaint (_("Tag '%s' has no DW_AT_import"),
10417                  dwarf_tag_name (die->tag));
10418       return;
10419     }
10420
10421   imported_cu = cu;
10422   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10423   imported_name = dwarf2_name (imported_die, imported_cu);
10424   if (imported_name == NULL)
10425     {
10426       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10427
10428         The import in the following code:
10429         namespace A
10430           {
10431             typedef int B;
10432           }
10433
10434         int main ()
10435           {
10436             using A::B;
10437             B b;
10438             return b;
10439           }
10440
10441         ...
10442          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10443             <52>   DW_AT_decl_file   : 1
10444             <53>   DW_AT_decl_line   : 6
10445             <54>   DW_AT_import      : <0x75>
10446          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10447             <59>   DW_AT_name        : B
10448             <5b>   DW_AT_decl_file   : 1
10449             <5c>   DW_AT_decl_line   : 2
10450             <5d>   DW_AT_type        : <0x6e>
10451         ...
10452          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10453             <76>   DW_AT_byte_size   : 4
10454             <77>   DW_AT_encoding    : 5        (signed)
10455
10456         imports the wrong die ( 0x75 instead of 0x58 ).
10457         This case will be ignored until the gcc bug is fixed.  */
10458       return;
10459     }
10460
10461   /* Figure out the local name after import.  */
10462   import_alias = dwarf2_name (die, cu);
10463
10464   /* Figure out where the statement is being imported to.  */
10465   import_prefix = determine_prefix (die, cu);
10466
10467   /* Figure out what the scope of the imported die is and prepend it
10468      to the name of the imported die.  */
10469   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10470
10471   if (imported_die->tag != DW_TAG_namespace
10472       && imported_die->tag != DW_TAG_module)
10473     {
10474       imported_declaration = imported_name;
10475       canonical_name = imported_name_prefix;
10476     }
10477   else if (strlen (imported_name_prefix) > 0)
10478     canonical_name = obconcat (&objfile->objfile_obstack,
10479                                imported_name_prefix,
10480                                (cu->language == language_d ? "." : "::"),
10481                                imported_name, (char *) NULL);
10482   else
10483     canonical_name = imported_name;
10484
10485   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
10486     for (child_die = die->child; child_die && child_die->tag;
10487          child_die = sibling_die (child_die))
10488       {
10489         /* DWARF-4: A Fortran use statement with a “rename list” may be
10490            represented by an imported module entry with an import attribute
10491            referring to the module and owned entries corresponding to those
10492            entities that are renamed as part of being imported.  */
10493
10494         if (child_die->tag != DW_TAG_imported_declaration)
10495           {
10496             complaint (_("child DW_TAG_imported_declaration expected "
10497                          "- DIE at %s [in module %s]"),
10498                        sect_offset_str (child_die->sect_off),
10499                        objfile_name (objfile));
10500             continue;
10501           }
10502
10503         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10504         if (import_attr == NULL)
10505           {
10506             complaint (_("Tag '%s' has no DW_AT_import"),
10507                        dwarf_tag_name (child_die->tag));
10508             continue;
10509           }
10510
10511         imported_cu = cu;
10512         imported_die = follow_die_ref_or_sig (child_die, import_attr,
10513                                               &imported_cu);
10514         imported_name = dwarf2_name (imported_die, imported_cu);
10515         if (imported_name == NULL)
10516           {
10517             complaint (_("child DW_TAG_imported_declaration has unknown "
10518                          "imported name - DIE at %s [in module %s]"),
10519                        sect_offset_str (child_die->sect_off),
10520                        objfile_name (objfile));
10521             continue;
10522           }
10523
10524         excludes.push_back (imported_name);
10525
10526         process_die (child_die, cu);
10527       }
10528
10529   add_using_directive (using_directives (cu),
10530                        import_prefix,
10531                        canonical_name,
10532                        import_alias,
10533                        imported_declaration,
10534                        excludes,
10535                        0,
10536                        &objfile->objfile_obstack);
10537 }
10538
10539 /* ICC<14 does not output the required DW_AT_declaration on incomplete
10540    types, but gives them a size of zero.  Starting with version 14,
10541    ICC is compatible with GCC.  */
10542
10543 static bool
10544 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
10545 {
10546   if (!cu->checked_producer)
10547     check_producer (cu);
10548
10549   return cu->producer_is_icc_lt_14;
10550 }
10551
10552 /* ICC generates a DW_AT_type for C void functions.  This was observed on
10553    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
10554    which says that void functions should not have a DW_AT_type.  */
10555
10556 static bool
10557 producer_is_icc (struct dwarf2_cu *cu)
10558 {
10559   if (!cu->checked_producer)
10560     check_producer (cu);
10561
10562   return cu->producer_is_icc;
10563 }
10564
10565 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
10566    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
10567    this, it was first present in GCC release 4.3.0.  */
10568
10569 static bool
10570 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
10571 {
10572   if (!cu->checked_producer)
10573     check_producer (cu);
10574
10575   return cu->producer_is_gcc_lt_4_3;
10576 }
10577
10578 static file_and_directory
10579 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
10580 {
10581   file_and_directory res;
10582
10583   /* Find the filename.  Do not use dwarf2_name here, since the filename
10584      is not a source language identifier.  */
10585   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
10586   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
10587
10588   if (res.comp_dir == NULL
10589       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
10590       && IS_ABSOLUTE_PATH (res.name))
10591     {
10592       res.comp_dir_storage = ldirname (res.name);
10593       if (!res.comp_dir_storage.empty ())
10594         res.comp_dir = res.comp_dir_storage.c_str ();
10595     }
10596   if (res.comp_dir != NULL)
10597     {
10598       /* Irix 6.2 native cc prepends <machine>.: to the compilation
10599          directory, get rid of it.  */
10600       const char *cp = strchr (res.comp_dir, ':');
10601
10602       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
10603         res.comp_dir = cp + 1;
10604     }
10605
10606   if (res.name == NULL)
10607     res.name = "<unknown>";
10608
10609   return res;
10610 }
10611
10612 /* Handle DW_AT_stmt_list for a compilation unit.
10613    DIE is the DW_TAG_compile_unit die for CU.
10614    COMP_DIR is the compilation directory.  LOWPC is passed to
10615    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
10616
10617 static void
10618 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
10619                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
10620 {
10621   struct dwarf2_per_objfile *dwarf2_per_objfile
10622     = cu->per_cu->dwarf2_per_objfile;
10623   struct attribute *attr;
10624   struct line_header line_header_local;
10625   hashval_t line_header_local_hash;
10626   void **slot;
10627   int decode_mapping;
10628
10629   gdb_assert (! cu->per_cu->is_debug_types);
10630
10631   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10632   if (attr == NULL)
10633     return;
10634
10635   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10636
10637   /* The line header hash table is only created if needed (it exists to
10638      prevent redundant reading of the line table for partial_units).
10639      If we're given a partial_unit, we'll need it.  If we're given a
10640      compile_unit, then use the line header hash table if it's already
10641      created, but don't create one just yet.  */
10642
10643   if (dwarf2_per_objfile->line_header_hash == NULL
10644       && die->tag == DW_TAG_partial_unit)
10645     {
10646       dwarf2_per_objfile->line_header_hash
10647         .reset (htab_create_alloc (127, line_header_hash_voidp,
10648                                    line_header_eq_voidp,
10649                                    free_line_header_voidp,
10650                                    xcalloc, xfree));
10651     }
10652
10653   line_header_local.sect_off = line_offset;
10654   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
10655   line_header_local_hash = line_header_hash (&line_header_local);
10656   if (dwarf2_per_objfile->line_header_hash != NULL)
10657     {
10658       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash.get (),
10659                                        &line_header_local,
10660                                        line_header_local_hash, NO_INSERT);
10661
10662       /* For DW_TAG_compile_unit we need info like symtab::linetable which
10663          is not present in *SLOT (since if there is something in *SLOT then
10664          it will be for a partial_unit).  */
10665       if (die->tag == DW_TAG_partial_unit && slot != NULL)
10666         {
10667           gdb_assert (*slot != NULL);
10668           cu->line_header = (struct line_header *) *slot;
10669           return;
10670         }
10671     }
10672
10673   /* dwarf_decode_line_header does not yet provide sufficient information.
10674      We always have to call also dwarf_decode_lines for it.  */
10675   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
10676   if (lh == NULL)
10677     return;
10678
10679   cu->line_header = lh.release ();
10680   cu->line_header_die_owner = die;
10681
10682   if (dwarf2_per_objfile->line_header_hash == NULL)
10683     slot = NULL;
10684   else
10685     {
10686       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash.get (),
10687                                        &line_header_local,
10688                                        line_header_local_hash, INSERT);
10689       gdb_assert (slot != NULL);
10690     }
10691   if (slot != NULL && *slot == NULL)
10692     {
10693       /* This newly decoded line number information unit will be owned
10694          by line_header_hash hash table.  */
10695       *slot = cu->line_header;
10696       cu->line_header_die_owner = NULL;
10697     }
10698   else
10699     {
10700       /* We cannot free any current entry in (*slot) as that struct line_header
10701          may be already used by multiple CUs.  Create only temporary decoded
10702          line_header for this CU - it may happen at most once for each line
10703          number information unit.  And if we're not using line_header_hash
10704          then this is what we want as well.  */
10705       gdb_assert (die->tag != DW_TAG_partial_unit);
10706     }
10707   decode_mapping = (die->tag != DW_TAG_partial_unit);
10708   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
10709                       decode_mapping);
10710
10711 }
10712
10713 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
10714
10715 static void
10716 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
10717 {
10718   struct dwarf2_per_objfile *dwarf2_per_objfile
10719     = cu->per_cu->dwarf2_per_objfile;
10720   struct objfile *objfile = dwarf2_per_objfile->objfile;
10721   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10722   CORE_ADDR lowpc = ((CORE_ADDR) -1);
10723   CORE_ADDR highpc = ((CORE_ADDR) 0);
10724   struct attribute *attr;
10725   struct die_info *child_die;
10726   CORE_ADDR baseaddr;
10727
10728   prepare_one_comp_unit (cu, die, cu->language);
10729   baseaddr = objfile->text_section_offset ();
10730
10731   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
10732
10733   /* If we didn't find a lowpc, set it to highpc to avoid complaints
10734      from finish_block.  */
10735   if (lowpc == ((CORE_ADDR) -1))
10736     lowpc = highpc;
10737   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
10738
10739   file_and_directory fnd = find_file_and_directory (die, cu);
10740
10741   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
10742      standardised yet.  As a workaround for the language detection we fall
10743      back to the DW_AT_producer string.  */
10744   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
10745     cu->language = language_opencl;
10746
10747   /* Similar hack for Go.  */
10748   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
10749     set_cu_language (DW_LANG_Go, cu);
10750
10751   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
10752
10753   /* Decode line number information if present.  We do this before
10754      processing child DIEs, so that the line header table is available
10755      for DW_AT_decl_file.  */
10756   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
10757
10758   /* Process all dies in compilation unit.  */
10759   if (die->child != NULL)
10760     {
10761       child_die = die->child;
10762       while (child_die && child_die->tag)
10763         {
10764           process_die (child_die, cu);
10765           child_die = sibling_die (child_die);
10766         }
10767     }
10768
10769   /* Decode macro information, if present.  Dwarf 2 macro information
10770      refers to information in the line number info statement program
10771      header, so we can only read it if we've read the header
10772      successfully.  */
10773   attr = dwarf2_attr (die, DW_AT_macros, cu);
10774   if (attr == NULL)
10775     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
10776   if (attr && cu->line_header)
10777     {
10778       if (dwarf2_attr (die, DW_AT_macro_info, cu))
10779         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
10780
10781       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
10782     }
10783   else
10784     {
10785       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
10786       if (attr && cu->line_header)
10787         {
10788           unsigned int macro_offset = DW_UNSND (attr);
10789
10790           dwarf_decode_macros (cu, macro_offset, 0);
10791         }
10792     }
10793 }
10794
10795 void
10796 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
10797 {
10798   struct type_unit_group *tu_group;
10799   int first_time;
10800   struct attribute *attr;
10801   unsigned int i;
10802   struct signatured_type *sig_type;
10803
10804   gdb_assert (per_cu->is_debug_types);
10805   sig_type = (struct signatured_type *) per_cu;
10806
10807   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
10808
10809   /* If we're using .gdb_index (includes -readnow) then
10810      per_cu->type_unit_group may not have been set up yet.  */
10811   if (sig_type->type_unit_group == NULL)
10812     sig_type->type_unit_group = get_type_unit_group (this, attr);
10813   tu_group = sig_type->type_unit_group;
10814
10815   /* If we've already processed this stmt_list there's no real need to
10816      do it again, we could fake it and just recreate the part we need
10817      (file name,index -> symtab mapping).  If data shows this optimization
10818      is useful we can do it then.  */
10819   first_time = tu_group->compunit_symtab == NULL;
10820
10821   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
10822      debug info.  */
10823   line_header_up lh;
10824   if (attr != NULL)
10825     {
10826       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10827       lh = dwarf_decode_line_header (line_offset, this);
10828     }
10829   if (lh == NULL)
10830     {
10831       if (first_time)
10832         start_symtab ("", NULL, 0);
10833       else
10834         {
10835           gdb_assert (tu_group->symtabs == NULL);
10836           gdb_assert (m_builder == nullptr);
10837           struct compunit_symtab *cust = tu_group->compunit_symtab;
10838           m_builder.reset (new struct buildsym_compunit
10839                            (COMPUNIT_OBJFILE (cust), "",
10840                             COMPUNIT_DIRNAME (cust),
10841                             compunit_language (cust),
10842                             0, cust));
10843         }
10844       return;
10845     }
10846
10847   line_header = lh.release ();
10848   line_header_die_owner = die;
10849
10850   if (first_time)
10851     {
10852       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
10853
10854       /* Note: We don't assign tu_group->compunit_symtab yet because we're
10855          still initializing it, and our caller (a few levels up)
10856          process_full_type_unit still needs to know if this is the first
10857          time.  */
10858
10859       tu_group->num_symtabs = line_header->file_names_size ();
10860       tu_group->symtabs = XNEWVEC (struct symtab *,
10861                                    line_header->file_names_size ());
10862
10863       auto &file_names = line_header->file_names ();
10864       for (i = 0; i < file_names.size (); ++i)
10865         {
10866           file_entry &fe = file_names[i];
10867           dwarf2_start_subfile (this, fe.name,
10868                                 fe.include_dir (line_header));
10869           buildsym_compunit *b = get_builder ();
10870           if (b->get_current_subfile ()->symtab == NULL)
10871             {
10872               /* NOTE: start_subfile will recognize when it's been
10873                  passed a file it has already seen.  So we can't
10874                  assume there's a simple mapping from
10875                  cu->line_header->file_names to subfiles, plus
10876                  cu->line_header->file_names may contain dups.  */
10877               b->get_current_subfile ()->symtab
10878                 = allocate_symtab (cust, b->get_current_subfile ()->name);
10879             }
10880
10881           fe.symtab = b->get_current_subfile ()->symtab;
10882           tu_group->symtabs[i] = fe.symtab;
10883         }
10884     }
10885   else
10886     {
10887       gdb_assert (m_builder == nullptr);
10888       struct compunit_symtab *cust = tu_group->compunit_symtab;
10889       m_builder.reset (new struct buildsym_compunit
10890                        (COMPUNIT_OBJFILE (cust), "",
10891                         COMPUNIT_DIRNAME (cust),
10892                         compunit_language (cust),
10893                         0, cust));
10894
10895       auto &file_names = line_header->file_names ();
10896       for (i = 0; i < file_names.size (); ++i)
10897         {
10898           file_entry &fe = file_names[i];
10899           fe.symtab = tu_group->symtabs[i];
10900         }
10901     }
10902
10903   /* The main symtab is allocated last.  Type units don't have DW_AT_name
10904      so they don't have a "real" (so to speak) symtab anyway.
10905      There is later code that will assign the main symtab to all symbols
10906      that don't have one.  We need to handle the case of a symbol with a
10907      missing symtab (DW_AT_decl_file) anyway.  */
10908 }
10909
10910 /* Process DW_TAG_type_unit.
10911    For TUs we want to skip the first top level sibling if it's not the
10912    actual type being defined by this TU.  In this case the first top
10913    level sibling is there to provide context only.  */
10914
10915 static void
10916 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
10917 {
10918   struct die_info *child_die;
10919
10920   prepare_one_comp_unit (cu, die, language_minimal);
10921
10922   /* Initialize (or reinitialize) the machinery for building symtabs.
10923      We do this before processing child DIEs, so that the line header table
10924      is available for DW_AT_decl_file.  */
10925   cu->setup_type_unit_groups (die);
10926
10927   if (die->child != NULL)
10928     {
10929       child_die = die->child;
10930       while (child_die && child_die->tag)
10931         {
10932           process_die (child_die, cu);
10933           child_die = sibling_die (child_die);
10934         }
10935     }
10936 }
10937 \f
10938 /* DWO/DWP files.
10939
10940    http://gcc.gnu.org/wiki/DebugFission
10941    http://gcc.gnu.org/wiki/DebugFissionDWP
10942
10943    To simplify handling of both DWO files ("object" files with the DWARF info)
10944    and DWP files (a file with the DWOs packaged up into one file), we treat
10945    DWP files as having a collection of virtual DWO files.  */
10946
10947 static hashval_t
10948 hash_dwo_file (const void *item)
10949 {
10950   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10951   hashval_t hash;
10952
10953   hash = htab_hash_string (dwo_file->dwo_name);
10954   if (dwo_file->comp_dir != NULL)
10955     hash += htab_hash_string (dwo_file->comp_dir);
10956   return hash;
10957 }
10958
10959 static int
10960 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10961 {
10962   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10963   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10964
10965   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10966     return 0;
10967   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10968     return lhs->comp_dir == rhs->comp_dir;
10969   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10970 }
10971
10972 /* Allocate a hash table for DWO files.  */
10973
10974 static htab_up
10975 allocate_dwo_file_hash_table ()
10976 {
10977   auto delete_dwo_file = [] (void *item)
10978     {
10979       struct dwo_file *dwo_file = (struct dwo_file *) item;
10980
10981       delete dwo_file;
10982     };
10983
10984   return htab_up (htab_create_alloc (41,
10985                                      hash_dwo_file,
10986                                      eq_dwo_file,
10987                                      delete_dwo_file,
10988                                      xcalloc, xfree));
10989 }
10990
10991 /* Lookup DWO file DWO_NAME.  */
10992
10993 static void **
10994 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
10995                       const char *dwo_name,
10996                       const char *comp_dir)
10997 {
10998   struct dwo_file find_entry;
10999   void **slot;
11000
11001   if (dwarf2_per_objfile->dwo_files == NULL)
11002     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
11003
11004   find_entry.dwo_name = dwo_name;
11005   find_entry.comp_dir = comp_dir;
11006   slot = htab_find_slot (dwarf2_per_objfile->dwo_files.get (), &find_entry,
11007                          INSERT);
11008
11009   return slot;
11010 }
11011
11012 static hashval_t
11013 hash_dwo_unit (const void *item)
11014 {
11015   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11016
11017   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11018   return dwo_unit->signature;
11019 }
11020
11021 static int
11022 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11023 {
11024   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11025   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11026
11027   /* The signature is assumed to be unique within the DWO file.
11028      So while object file CU dwo_id's always have the value zero,
11029      that's OK, assuming each object file DWO file has only one CU,
11030      and that's the rule for now.  */
11031   return lhs->signature == rhs->signature;
11032 }
11033
11034 /* Allocate a hash table for DWO CUs,TUs.
11035    There is one of these tables for each of CUs,TUs for each DWO file.  */
11036
11037 static htab_up
11038 allocate_dwo_unit_table ()
11039 {
11040   /* Start out with a pretty small number.
11041      Generally DWO files contain only one CU and maybe some TUs.  */
11042   return htab_up (htab_create_alloc (3,
11043                                      hash_dwo_unit,
11044                                      eq_dwo_unit,
11045                                      NULL, xcalloc, xfree));
11046 }
11047
11048 /* die_reader_func for create_dwo_cu.  */
11049
11050 static void
11051 create_dwo_cu_reader (const struct die_reader_specs *reader,
11052                       const gdb_byte *info_ptr,
11053                       struct die_info *comp_unit_die,
11054                       struct dwo_file *dwo_file,
11055                       struct dwo_unit *dwo_unit)
11056 {
11057   struct dwarf2_cu *cu = reader->cu;
11058   sect_offset sect_off = cu->per_cu->sect_off;
11059   struct dwarf2_section_info *section = cu->per_cu->section;
11060
11061   gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
11062   if (!signature.has_value ())
11063     {
11064       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11065                    " its dwo_id [in module %s]"),
11066                  sect_offset_str (sect_off), dwo_file->dwo_name);
11067       return;
11068     }
11069
11070   dwo_unit->dwo_file = dwo_file;
11071   dwo_unit->signature = *signature;
11072   dwo_unit->section = section;
11073   dwo_unit->sect_off = sect_off;
11074   dwo_unit->length = cu->per_cu->length;
11075
11076   if (dwarf_read_debug)
11077     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11078                         sect_offset_str (sect_off),
11079                         hex_string (dwo_unit->signature));
11080 }
11081
11082 /* Create the dwo_units for the CUs in a DWO_FILE.
11083    Note: This function processes DWO files only, not DWP files.  */
11084
11085 static void
11086 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11087                        dwarf2_cu *cu, struct dwo_file &dwo_file,
11088                        dwarf2_section_info &section, htab_up &cus_htab)
11089 {
11090   struct objfile *objfile = dwarf2_per_objfile->objfile;
11091   const gdb_byte *info_ptr, *end_ptr;
11092
11093   section.read (objfile);
11094   info_ptr = section.buffer;
11095
11096   if (info_ptr == NULL)
11097     return;
11098
11099   if (dwarf_read_debug)
11100     {
11101       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11102                           section.get_name (),
11103                           section.get_file_name ());
11104     }
11105
11106   end_ptr = info_ptr + section.size;
11107   while (info_ptr < end_ptr)
11108     {
11109       struct dwarf2_per_cu_data per_cu;
11110       struct dwo_unit read_unit {};
11111       struct dwo_unit *dwo_unit;
11112       void **slot;
11113       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11114
11115       memset (&per_cu, 0, sizeof (per_cu));
11116       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11117       per_cu.is_debug_types = 0;
11118       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11119       per_cu.section = &section;
11120
11121       cutu_reader reader (&per_cu, cu, &dwo_file);
11122       if (!reader.dummy_p)
11123         create_dwo_cu_reader (&reader, reader.info_ptr, reader.comp_unit_die,
11124                               &dwo_file, &read_unit);
11125       info_ptr += per_cu.length;
11126
11127       // If the unit could not be parsed, skip it.
11128       if (read_unit.dwo_file == NULL)
11129         continue;
11130
11131       if (cus_htab == NULL)
11132         cus_htab = allocate_dwo_unit_table ();
11133
11134       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11135       *dwo_unit = read_unit;
11136       slot = htab_find_slot (cus_htab.get (), dwo_unit, INSERT);
11137       gdb_assert (slot != NULL);
11138       if (*slot != NULL)
11139         {
11140           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11141           sect_offset dup_sect_off = dup_cu->sect_off;
11142
11143           complaint (_("debug cu entry at offset %s is duplicate to"
11144                        " the entry at offset %s, signature %s"),
11145                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11146                      hex_string (dwo_unit->signature));
11147         }
11148       *slot = (void *)dwo_unit;
11149     }
11150 }
11151
11152 /* DWP file .debug_{cu,tu}_index section format:
11153    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11154
11155    DWP Version 1:
11156
11157    Both index sections have the same format, and serve to map a 64-bit
11158    signature to a set of section numbers.  Each section begins with a header,
11159    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11160    indexes, and a pool of 32-bit section numbers.  The index sections will be
11161    aligned at 8-byte boundaries in the file.
11162
11163    The index section header consists of:
11164
11165     V, 32 bit version number
11166     -, 32 bits unused
11167     N, 32 bit number of compilation units or type units in the index
11168     M, 32 bit number of slots in the hash table
11169
11170    Numbers are recorded using the byte order of the application binary.
11171
11172    The hash table begins at offset 16 in the section, and consists of an array
11173    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11174    order of the application binary).  Unused slots in the hash table are 0.
11175    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11176
11177    The parallel table begins immediately after the hash table
11178    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11179    array of 32-bit indexes (using the byte order of the application binary),
11180    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11181    table contains a 32-bit index into the pool of section numbers.  For unused
11182    hash table slots, the corresponding entry in the parallel table will be 0.
11183
11184    The pool of section numbers begins immediately following the hash table
11185    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11186    section numbers consists of an array of 32-bit words (using the byte order
11187    of the application binary).  Each item in the array is indexed starting
11188    from 0.  The hash table entry provides the index of the first section
11189    number in the set.  Additional section numbers in the set follow, and the
11190    set is terminated by a 0 entry (section number 0 is not used in ELF).
11191
11192    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11193    section must be the first entry in the set, and the .debug_abbrev.dwo must
11194    be the second entry. Other members of the set may follow in any order.
11195
11196    ---
11197
11198    DWP Version 2:
11199
11200    DWP Version 2 combines all the .debug_info, etc. sections into one,
11201    and the entries in the index tables are now offsets into these sections.
11202    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11203    section.
11204
11205    Index Section Contents:
11206     Header
11207     Hash Table of Signatures   dwp_hash_table.hash_table
11208     Parallel Table of Indices  dwp_hash_table.unit_table
11209     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11210     Table of Section Sizes     dwp_hash_table.v2.sizes
11211
11212    The index section header consists of:
11213
11214     V, 32 bit version number
11215     L, 32 bit number of columns in the table of section offsets
11216     N, 32 bit number of compilation units or type units in the index
11217     M, 32 bit number of slots in the hash table
11218
11219    Numbers are recorded using the byte order of the application binary.
11220
11221    The hash table has the same format as version 1.
11222    The parallel table of indices has the same format as version 1,
11223    except that the entries are origin-1 indices into the table of sections
11224    offsets and the table of section sizes.
11225
11226    The table of offsets begins immediately following the parallel table
11227    (at offset 16 + 12 * M from the beginning of the section).  The table is
11228    a two-dimensional array of 32-bit words (using the byte order of the
11229    application binary), with L columns and N+1 rows, in row-major order.
11230    Each row in the array is indexed starting from 0.  The first row provides
11231    a key to the remaining rows: each column in this row provides an identifier
11232    for a debug section, and the offsets in the same column of subsequent rows
11233    refer to that section.  The section identifiers are:
11234
11235     DW_SECT_INFO         1  .debug_info.dwo
11236     DW_SECT_TYPES        2  .debug_types.dwo
11237     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11238     DW_SECT_LINE         4  .debug_line.dwo
11239     DW_SECT_LOC          5  .debug_loc.dwo
11240     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11241     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11242     DW_SECT_MACRO        8  .debug_macro.dwo
11243
11244    The offsets provided by the CU and TU index sections are the base offsets
11245    for the contributions made by each CU or TU to the corresponding section
11246    in the package file.  Each CU and TU header contains an abbrev_offset
11247    field, used to find the abbreviations table for that CU or TU within the
11248    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11249    be interpreted as relative to the base offset given in the index section.
11250    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11251    should be interpreted as relative to the base offset for .debug_line.dwo,
11252    and offsets into other debug sections obtained from DWARF attributes should
11253    also be interpreted as relative to the corresponding base offset.
11254
11255    The table of sizes begins immediately following the table of offsets.
11256    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11257    with L columns and N rows, in row-major order.  Each row in the array is
11258    indexed starting from 1 (row 0 is shared by the two tables).
11259
11260    ---
11261
11262    Hash table lookup is handled the same in version 1 and 2:
11263
11264    We assume that N and M will not exceed 2^32 - 1.
11265    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11266
11267    Given a 64-bit compilation unit signature or a type signature S, an entry
11268    in the hash table is located as follows:
11269
11270    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11271       the low-order k bits all set to 1.
11272
11273    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11274
11275    3) If the hash table entry at index H matches the signature, use that
11276       entry.  If the hash table entry at index H is unused (all zeroes),
11277       terminate the search: the signature is not present in the table.
11278
11279    4) Let H = (H + H') modulo M. Repeat at Step 3.
11280
11281    Because M > N and H' and M are relatively prime, the search is guaranteed
11282    to stop at an unused slot or find the match.  */
11283
11284 /* Create a hash table to map DWO IDs to their CU/TU entry in
11285    .debug_{info,types}.dwo in DWP_FILE.
11286    Returns NULL if there isn't one.
11287    Note: This function processes DWP files only, not DWO files.  */
11288
11289 static struct dwp_hash_table *
11290 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11291                        struct dwp_file *dwp_file, int is_debug_types)
11292 {
11293   struct objfile *objfile = dwarf2_per_objfile->objfile;
11294   bfd *dbfd = dwp_file->dbfd.get ();
11295   const gdb_byte *index_ptr, *index_end;
11296   struct dwarf2_section_info *index;
11297   uint32_t version, nr_columns, nr_units, nr_slots;
11298   struct dwp_hash_table *htab;
11299
11300   if (is_debug_types)
11301     index = &dwp_file->sections.tu_index;
11302   else
11303     index = &dwp_file->sections.cu_index;
11304
11305   if (index->empty ())
11306     return NULL;
11307   index->read (objfile);
11308
11309   index_ptr = index->buffer;
11310   index_end = index_ptr + index->size;
11311
11312   version = read_4_bytes (dbfd, index_ptr);
11313   index_ptr += 4;
11314   if (version == 2)
11315     nr_columns = read_4_bytes (dbfd, index_ptr);
11316   else
11317     nr_columns = 0;
11318   index_ptr += 4;
11319   nr_units = read_4_bytes (dbfd, index_ptr);
11320   index_ptr += 4;
11321   nr_slots = read_4_bytes (dbfd, index_ptr);
11322   index_ptr += 4;
11323
11324   if (version != 1 && version != 2)
11325     {
11326       error (_("Dwarf Error: unsupported DWP file version (%s)"
11327                " [in module %s]"),
11328              pulongest (version), dwp_file->name);
11329     }
11330   if (nr_slots != (nr_slots & -nr_slots))
11331     {
11332       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
11333                " is not power of 2 [in module %s]"),
11334              pulongest (nr_slots), dwp_file->name);
11335     }
11336
11337   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
11338   htab->version = version;
11339   htab->nr_columns = nr_columns;
11340   htab->nr_units = nr_units;
11341   htab->nr_slots = nr_slots;
11342   htab->hash_table = index_ptr;
11343   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
11344
11345   /* Exit early if the table is empty.  */
11346   if (nr_slots == 0 || nr_units == 0
11347       || (version == 2 && nr_columns == 0))
11348     {
11349       /* All must be zero.  */
11350       if (nr_slots != 0 || nr_units != 0
11351           || (version == 2 && nr_columns != 0))
11352         {
11353           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
11354                        " all zero [in modules %s]"),
11355                      dwp_file->name);
11356         }
11357       return htab;
11358     }
11359
11360   if (version == 1)
11361     {
11362       htab->section_pool.v1.indices =
11363         htab->unit_table + sizeof (uint32_t) * nr_slots;
11364       /* It's harder to decide whether the section is too small in v1.
11365          V1 is deprecated anyway so we punt.  */
11366     }
11367   else
11368     {
11369       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11370       int *ids = htab->section_pool.v2.section_ids;
11371       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
11372       /* Reverse map for error checking.  */
11373       int ids_seen[DW_SECT_MAX + 1];
11374       int i;
11375
11376       if (nr_columns < 2)
11377         {
11378           error (_("Dwarf Error: bad DWP hash table, too few columns"
11379                    " in section table [in module %s]"),
11380                  dwp_file->name);
11381         }
11382       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11383         {
11384           error (_("Dwarf Error: bad DWP hash table, too many columns"
11385                    " in section table [in module %s]"),
11386                  dwp_file->name);
11387         }
11388       memset (ids, 255, sizeof_ids);
11389       memset (ids_seen, 255, sizeof (ids_seen));
11390       for (i = 0; i < nr_columns; ++i)
11391         {
11392           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11393
11394           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11395             {
11396               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11397                        " in section table [in module %s]"),
11398                      id, dwp_file->name);
11399             }
11400           if (ids_seen[id] != -1)
11401             {
11402               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11403                        " id %d in section table [in module %s]"),
11404                      id, dwp_file->name);
11405             }
11406           ids_seen[id] = i;
11407           ids[i] = id;
11408         }
11409       /* Must have exactly one info or types section.  */
11410       if (((ids_seen[DW_SECT_INFO] != -1)
11411            + (ids_seen[DW_SECT_TYPES] != -1))
11412           != 1)
11413         {
11414           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11415                    " DWO info/types section [in module %s]"),
11416                  dwp_file->name);
11417         }
11418       /* Must have an abbrev section.  */
11419       if (ids_seen[DW_SECT_ABBREV] == -1)
11420         {
11421           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11422                    " section [in module %s]"),
11423                  dwp_file->name);
11424         }
11425       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11426       htab->section_pool.v2.sizes =
11427         htab->section_pool.v2.offsets + (sizeof (uint32_t)
11428                                          * nr_units * nr_columns);
11429       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11430                                           * nr_units * nr_columns))
11431           > index_end)
11432         {
11433           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11434                    " [in module %s]"),
11435                  dwp_file->name);
11436         }
11437     }
11438
11439   return htab;
11440 }
11441
11442 /* Update SECTIONS with the data from SECTP.
11443
11444    This function is like the other "locate" section routines that are
11445    passed to bfd_map_over_sections, but in this context the sections to
11446    read comes from the DWP V1 hash table, not the full ELF section table.
11447
11448    The result is non-zero for success, or zero if an error was found.  */
11449
11450 static int
11451 locate_v1_virtual_dwo_sections (asection *sectp,
11452                                 struct virtual_v1_dwo_sections *sections)
11453 {
11454   const struct dwop_section_names *names = &dwop_section_names;
11455
11456   if (section_is_p (sectp->name, &names->abbrev_dwo))
11457     {
11458       /* There can be only one.  */
11459       if (sections->abbrev.s.section != NULL)
11460         return 0;
11461       sections->abbrev.s.section = sectp;
11462       sections->abbrev.size = bfd_section_size (sectp);
11463     }
11464   else if (section_is_p (sectp->name, &names->info_dwo)
11465            || section_is_p (sectp->name, &names->types_dwo))
11466     {
11467       /* There can be only one.  */
11468       if (sections->info_or_types.s.section != NULL)
11469         return 0;
11470       sections->info_or_types.s.section = sectp;
11471       sections->info_or_types.size = bfd_section_size (sectp);
11472     }
11473   else if (section_is_p (sectp->name, &names->line_dwo))
11474     {
11475       /* There can be only one.  */
11476       if (sections->line.s.section != NULL)
11477         return 0;
11478       sections->line.s.section = sectp;
11479       sections->line.size = bfd_section_size (sectp);
11480     }
11481   else if (section_is_p (sectp->name, &names->loc_dwo))
11482     {
11483       /* There can be only one.  */
11484       if (sections->loc.s.section != NULL)
11485         return 0;
11486       sections->loc.s.section = sectp;
11487       sections->loc.size = bfd_section_size (sectp);
11488     }
11489   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11490     {
11491       /* There can be only one.  */
11492       if (sections->macinfo.s.section != NULL)
11493         return 0;
11494       sections->macinfo.s.section = sectp;
11495       sections->macinfo.size = bfd_section_size (sectp);
11496     }
11497   else if (section_is_p (sectp->name, &names->macro_dwo))
11498     {
11499       /* There can be only one.  */
11500       if (sections->macro.s.section != NULL)
11501         return 0;
11502       sections->macro.s.section = sectp;
11503       sections->macro.size = bfd_section_size (sectp);
11504     }
11505   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11506     {
11507       /* There can be only one.  */
11508       if (sections->str_offsets.s.section != NULL)
11509         return 0;
11510       sections->str_offsets.s.section = sectp;
11511       sections->str_offsets.size = bfd_section_size (sectp);
11512     }
11513   else
11514     {
11515       /* No other kind of section is valid.  */
11516       return 0;
11517     }
11518
11519   return 1;
11520 }
11521
11522 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11523    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11524    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11525    This is for DWP version 1 files.  */
11526
11527 static struct dwo_unit *
11528 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
11529                            struct dwp_file *dwp_file,
11530                            uint32_t unit_index,
11531                            const char *comp_dir,
11532                            ULONGEST signature, int is_debug_types)
11533 {
11534   struct objfile *objfile = dwarf2_per_objfile->objfile;
11535   const struct dwp_hash_table *dwp_htab =
11536     is_debug_types ? dwp_file->tus : dwp_file->cus;
11537   bfd *dbfd = dwp_file->dbfd.get ();
11538   const char *kind = is_debug_types ? "TU" : "CU";
11539   struct dwo_file *dwo_file;
11540   struct dwo_unit *dwo_unit;
11541   struct virtual_v1_dwo_sections sections;
11542   void **dwo_file_slot;
11543   int i;
11544
11545   gdb_assert (dwp_file->version == 1);
11546
11547   if (dwarf_read_debug)
11548     {
11549       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
11550                           kind,
11551                           pulongest (unit_index), hex_string (signature),
11552                           dwp_file->name);
11553     }
11554
11555   /* Fetch the sections of this DWO unit.
11556      Put a limit on the number of sections we look for so that bad data
11557      doesn't cause us to loop forever.  */
11558
11559 #define MAX_NR_V1_DWO_SECTIONS \
11560   (1 /* .debug_info or .debug_types */ \
11561    + 1 /* .debug_abbrev */ \
11562    + 1 /* .debug_line */ \
11563    + 1 /* .debug_loc */ \
11564    + 1 /* .debug_str_offsets */ \
11565    + 1 /* .debug_macro or .debug_macinfo */ \
11566    + 1 /* trailing zero */)
11567
11568   memset (&sections, 0, sizeof (sections));
11569
11570   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
11571     {
11572       asection *sectp;
11573       uint32_t section_nr =
11574         read_4_bytes (dbfd,
11575                       dwp_htab->section_pool.v1.indices
11576                       + (unit_index + i) * sizeof (uint32_t));
11577
11578       if (section_nr == 0)
11579         break;
11580       if (section_nr >= dwp_file->num_sections)
11581         {
11582           error (_("Dwarf Error: bad DWP hash table, section number too large"
11583                    " [in module %s]"),
11584                  dwp_file->name);
11585         }
11586
11587       sectp = dwp_file->elf_sections[section_nr];
11588       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
11589         {
11590           error (_("Dwarf Error: bad DWP hash table, invalid section found"
11591                    " [in module %s]"),
11592                  dwp_file->name);
11593         }
11594     }
11595
11596   if (i < 2
11597       || sections.info_or_types.empty ()
11598       || sections.abbrev.empty ())
11599     {
11600       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
11601                " [in module %s]"),
11602              dwp_file->name);
11603     }
11604   if (i == MAX_NR_V1_DWO_SECTIONS)
11605     {
11606       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
11607                " [in module %s]"),
11608              dwp_file->name);
11609     }
11610
11611   /* It's easier for the rest of the code if we fake a struct dwo_file and
11612      have dwo_unit "live" in that.  At least for now.
11613
11614      The DWP file can be made up of a random collection of CUs and TUs.
11615      However, for each CU + set of TUs that came from the same original DWO
11616      file, we can combine them back into a virtual DWO file to save space
11617      (fewer struct dwo_file objects to allocate).  Remember that for really
11618      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11619
11620   std::string virtual_dwo_name =
11621     string_printf ("virtual-dwo/%d-%d-%d-%d",
11622                    sections.abbrev.get_id (),
11623                    sections.line.get_id (),
11624                    sections.loc.get_id (),
11625                    sections.str_offsets.get_id ());
11626   /* Can we use an existing virtual DWO file?  */
11627   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
11628                                         virtual_dwo_name.c_str (),
11629                                         comp_dir);
11630   /* Create one if necessary.  */
11631   if (*dwo_file_slot == NULL)
11632     {
11633       if (dwarf_read_debug)
11634         {
11635           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11636                               virtual_dwo_name.c_str ());
11637         }
11638       dwo_file = new struct dwo_file;
11639       dwo_file->dwo_name = obstack_strdup (&objfile->objfile_obstack,
11640                                            virtual_dwo_name);
11641       dwo_file->comp_dir = comp_dir;
11642       dwo_file->sections.abbrev = sections.abbrev;
11643       dwo_file->sections.line = sections.line;
11644       dwo_file->sections.loc = sections.loc;
11645       dwo_file->sections.macinfo = sections.macinfo;
11646       dwo_file->sections.macro = sections.macro;
11647       dwo_file->sections.str_offsets = sections.str_offsets;
11648       /* The "str" section is global to the entire DWP file.  */
11649       dwo_file->sections.str = dwp_file->sections.str;
11650       /* The info or types section is assigned below to dwo_unit,
11651          there's no need to record it in dwo_file.
11652          Also, we can't simply record type sections in dwo_file because
11653          we record a pointer into the vector in dwo_unit.  As we collect more
11654          types we'll grow the vector and eventually have to reallocate space
11655          for it, invalidating all copies of pointers into the previous
11656          contents.  */
11657       *dwo_file_slot = dwo_file;
11658     }
11659   else
11660     {
11661       if (dwarf_read_debug)
11662         {
11663           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11664                               virtual_dwo_name.c_str ());
11665         }
11666       dwo_file = (struct dwo_file *) *dwo_file_slot;
11667     }
11668
11669   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11670   dwo_unit->dwo_file = dwo_file;
11671   dwo_unit->signature = signature;
11672   dwo_unit->section =
11673     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11674   *dwo_unit->section = sections.info_or_types;
11675   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11676
11677   return dwo_unit;
11678 }
11679
11680 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
11681    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
11682    piece within that section used by a TU/CU, return a virtual section
11683    of just that piece.  */
11684
11685 static struct dwarf2_section_info
11686 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
11687                        struct dwarf2_section_info *section,
11688                        bfd_size_type offset, bfd_size_type size)
11689 {
11690   struct dwarf2_section_info result;
11691   asection *sectp;
11692
11693   gdb_assert (section != NULL);
11694   gdb_assert (!section->is_virtual);
11695
11696   memset (&result, 0, sizeof (result));
11697   result.s.containing_section = section;
11698   result.is_virtual = true;
11699
11700   if (size == 0)
11701     return result;
11702
11703   sectp = section->get_bfd_section ();
11704
11705   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
11706      bounds of the real section.  This is a pretty-rare event, so just
11707      flag an error (easier) instead of a warning and trying to cope.  */
11708   if (sectp == NULL
11709       || offset + size > bfd_section_size (sectp))
11710     {
11711       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
11712                " in section %s [in module %s]"),
11713              sectp ? bfd_section_name (sectp) : "<unknown>",
11714              objfile_name (dwarf2_per_objfile->objfile));
11715     }
11716
11717   result.virtual_offset = offset;
11718   result.size = size;
11719   return result;
11720 }
11721
11722 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11723    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11724    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11725    This is for DWP version 2 files.  */
11726
11727 static struct dwo_unit *
11728 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
11729                            struct dwp_file *dwp_file,
11730                            uint32_t unit_index,
11731                            const char *comp_dir,
11732                            ULONGEST signature, int is_debug_types)
11733 {
11734   struct objfile *objfile = dwarf2_per_objfile->objfile;
11735   const struct dwp_hash_table *dwp_htab =
11736     is_debug_types ? dwp_file->tus : dwp_file->cus;
11737   bfd *dbfd = dwp_file->dbfd.get ();
11738   const char *kind = is_debug_types ? "TU" : "CU";
11739   struct dwo_file *dwo_file;
11740   struct dwo_unit *dwo_unit;
11741   struct virtual_v2_dwo_sections sections;
11742   void **dwo_file_slot;
11743   int i;
11744
11745   gdb_assert (dwp_file->version == 2);
11746
11747   if (dwarf_read_debug)
11748     {
11749       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
11750                           kind,
11751                           pulongest (unit_index), hex_string (signature),
11752                           dwp_file->name);
11753     }
11754
11755   /* Fetch the section offsets of this DWO unit.  */
11756
11757   memset (&sections, 0, sizeof (sections));
11758
11759   for (i = 0; i < dwp_htab->nr_columns; ++i)
11760     {
11761       uint32_t offset = read_4_bytes (dbfd,
11762                                       dwp_htab->section_pool.v2.offsets
11763                                       + (((unit_index - 1) * dwp_htab->nr_columns
11764                                           + i)
11765                                          * sizeof (uint32_t)));
11766       uint32_t size = read_4_bytes (dbfd,
11767                                     dwp_htab->section_pool.v2.sizes
11768                                     + (((unit_index - 1) * dwp_htab->nr_columns
11769                                         + i)
11770                                        * sizeof (uint32_t)));
11771
11772       switch (dwp_htab->section_pool.v2.section_ids[i])
11773         {
11774         case DW_SECT_INFO:
11775         case DW_SECT_TYPES:
11776           sections.info_or_types_offset = offset;
11777           sections.info_or_types_size = size;
11778           break;
11779         case DW_SECT_ABBREV:
11780           sections.abbrev_offset = offset;
11781           sections.abbrev_size = size;
11782           break;
11783         case DW_SECT_LINE:
11784           sections.line_offset = offset;
11785           sections.line_size = size;
11786           break;
11787         case DW_SECT_LOC:
11788           sections.loc_offset = offset;
11789           sections.loc_size = size;
11790           break;
11791         case DW_SECT_STR_OFFSETS:
11792           sections.str_offsets_offset = offset;
11793           sections.str_offsets_size = size;
11794           break;
11795         case DW_SECT_MACINFO:
11796           sections.macinfo_offset = offset;
11797           sections.macinfo_size = size;
11798           break;
11799         case DW_SECT_MACRO:
11800           sections.macro_offset = offset;
11801           sections.macro_size = size;
11802           break;
11803         }
11804     }
11805
11806   /* It's easier for the rest of the code if we fake a struct dwo_file and
11807      have dwo_unit "live" in that.  At least for now.
11808
11809      The DWP file can be made up of a random collection of CUs and TUs.
11810      However, for each CU + set of TUs that came from the same original DWO
11811      file, we can combine them back into a virtual DWO file to save space
11812      (fewer struct dwo_file objects to allocate).  Remember that for really
11813      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11814
11815   std::string virtual_dwo_name =
11816     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
11817                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11818                    (long) (sections.line_size ? sections.line_offset : 0),
11819                    (long) (sections.loc_size ? sections.loc_offset : 0),
11820                    (long) (sections.str_offsets_size
11821                            ? sections.str_offsets_offset : 0));
11822   /* Can we use an existing virtual DWO file?  */
11823   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
11824                                         virtual_dwo_name.c_str (),
11825                                         comp_dir);
11826   /* Create one if necessary.  */
11827   if (*dwo_file_slot == NULL)
11828     {
11829       if (dwarf_read_debug)
11830         {
11831           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11832                               virtual_dwo_name.c_str ());
11833         }
11834       dwo_file = new struct dwo_file;
11835       dwo_file->dwo_name = obstack_strdup (&objfile->objfile_obstack,
11836                                            virtual_dwo_name);
11837       dwo_file->comp_dir = comp_dir;
11838       dwo_file->sections.abbrev =
11839         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
11840                                sections.abbrev_offset, sections.abbrev_size);
11841       dwo_file->sections.line =
11842         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
11843                                sections.line_offset, sections.line_size);
11844       dwo_file->sections.loc =
11845         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
11846                                sections.loc_offset, sections.loc_size);
11847       dwo_file->sections.macinfo =
11848         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
11849                                sections.macinfo_offset, sections.macinfo_size);
11850       dwo_file->sections.macro =
11851         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
11852                                sections.macro_offset, sections.macro_size);
11853       dwo_file->sections.str_offsets =
11854         create_dwp_v2_section (dwarf2_per_objfile,
11855                                &dwp_file->sections.str_offsets,
11856                                sections.str_offsets_offset,
11857                                sections.str_offsets_size);
11858       /* The "str" section is global to the entire DWP file.  */
11859       dwo_file->sections.str = dwp_file->sections.str;
11860       /* The info or types section is assigned below to dwo_unit,
11861          there's no need to record it in dwo_file.
11862          Also, we can't simply record type sections in dwo_file because
11863          we record a pointer into the vector in dwo_unit.  As we collect more
11864          types we'll grow the vector and eventually have to reallocate space
11865          for it, invalidating all copies of pointers into the previous
11866          contents.  */
11867       *dwo_file_slot = dwo_file;
11868     }
11869   else
11870     {
11871       if (dwarf_read_debug)
11872         {
11873           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11874                               virtual_dwo_name.c_str ());
11875         }
11876       dwo_file = (struct dwo_file *) *dwo_file_slot;
11877     }
11878
11879   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11880   dwo_unit->dwo_file = dwo_file;
11881   dwo_unit->signature = signature;
11882   dwo_unit->section =
11883     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11884   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
11885                                               is_debug_types
11886                                               ? &dwp_file->sections.types
11887                                               : &dwp_file->sections.info,
11888                                               sections.info_or_types_offset,
11889                                               sections.info_or_types_size);
11890   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11891
11892   return dwo_unit;
11893 }
11894
11895 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
11896    Returns NULL if the signature isn't found.  */
11897
11898 static struct dwo_unit *
11899 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
11900                         struct dwp_file *dwp_file, const char *comp_dir,
11901                         ULONGEST signature, int is_debug_types)
11902 {
11903   const struct dwp_hash_table *dwp_htab =
11904     is_debug_types ? dwp_file->tus : dwp_file->cus;
11905   bfd *dbfd = dwp_file->dbfd.get ();
11906   uint32_t mask = dwp_htab->nr_slots - 1;
11907   uint32_t hash = signature & mask;
11908   uint32_t hash2 = ((signature >> 32) & mask) | 1;
11909   unsigned int i;
11910   void **slot;
11911   struct dwo_unit find_dwo_cu;
11912
11913   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
11914   find_dwo_cu.signature = signature;
11915   slot = htab_find_slot (is_debug_types
11916                          ? dwp_file->loaded_tus.get ()
11917                          : dwp_file->loaded_cus.get (),
11918                          &find_dwo_cu, INSERT);
11919
11920   if (*slot != NULL)
11921     return (struct dwo_unit *) *slot;
11922
11923   /* Use a for loop so that we don't loop forever on bad debug info.  */
11924   for (i = 0; i < dwp_htab->nr_slots; ++i)
11925     {
11926       ULONGEST signature_in_table;
11927
11928       signature_in_table =
11929         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
11930       if (signature_in_table == signature)
11931         {
11932           uint32_t unit_index =
11933             read_4_bytes (dbfd,
11934                           dwp_htab->unit_table + hash * sizeof (uint32_t));
11935
11936           if (dwp_file->version == 1)
11937             {
11938               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
11939                                                  dwp_file, unit_index,
11940                                                  comp_dir, signature,
11941                                                  is_debug_types);
11942             }
11943           else
11944             {
11945               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
11946                                                  dwp_file, unit_index,
11947                                                  comp_dir, signature,
11948                                                  is_debug_types);
11949             }
11950           return (struct dwo_unit *) *slot;
11951         }
11952       if (signature_in_table == 0)
11953         return NULL;
11954       hash = (hash + hash2) & mask;
11955     }
11956
11957   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
11958            " [in module %s]"),
11959          dwp_file->name);
11960 }
11961
11962 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
11963    Open the file specified by FILE_NAME and hand it off to BFD for
11964    preliminary analysis.  Return a newly initialized bfd *, which
11965    includes a canonicalized copy of FILE_NAME.
11966    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
11967    SEARCH_CWD is true if the current directory is to be searched.
11968    It will be searched before debug-file-directory.
11969    If successful, the file is added to the bfd include table of the
11970    objfile's bfd (see gdb_bfd_record_inclusion).
11971    If unable to find/open the file, return NULL.
11972    NOTE: This function is derived from symfile_bfd_open.  */
11973
11974 static gdb_bfd_ref_ptr
11975 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
11976                     const char *file_name, int is_dwp, int search_cwd)
11977 {
11978   int desc;
11979   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
11980      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
11981      to debug_file_directory.  */
11982   const char *search_path;
11983   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
11984
11985   gdb::unique_xmalloc_ptr<char> search_path_holder;
11986   if (search_cwd)
11987     {
11988       if (*debug_file_directory != '\0')
11989         {
11990           search_path_holder.reset (concat (".", dirname_separator_string,
11991                                             debug_file_directory,
11992                                             (char *) NULL));
11993           search_path = search_path_holder.get ();
11994         }
11995       else
11996         search_path = ".";
11997     }
11998   else
11999     search_path = debug_file_directory;
12000
12001   openp_flags flags = OPF_RETURN_REALPATH;
12002   if (is_dwp)
12003     flags |= OPF_SEARCH_IN_PATH;
12004
12005   gdb::unique_xmalloc_ptr<char> absolute_name;
12006   desc = openp (search_path, flags, file_name,
12007                 O_RDONLY | O_BINARY, &absolute_name);
12008   if (desc < 0)
12009     return NULL;
12010
12011   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12012                                          gnutarget, desc));
12013   if (sym_bfd == NULL)
12014     return NULL;
12015   bfd_set_cacheable (sym_bfd.get (), 1);
12016
12017   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12018     return NULL;
12019
12020   /* Success.  Record the bfd as having been included by the objfile's bfd.
12021      This is important because things like demangled_names_hash lives in the
12022      objfile's per_bfd space and may have references to things like symbol
12023      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12024   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12025
12026   return sym_bfd;
12027 }
12028
12029 /* Try to open DWO file FILE_NAME.
12030    COMP_DIR is the DW_AT_comp_dir attribute.
12031    The result is the bfd handle of the file.
12032    If there is a problem finding or opening the file, return NULL.
12033    Upon success, the canonicalized path of the file is stored in the bfd,
12034    same as symfile_bfd_open.  */
12035
12036 static gdb_bfd_ref_ptr
12037 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12038                const char *file_name, const char *comp_dir)
12039 {
12040   if (IS_ABSOLUTE_PATH (file_name))
12041     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12042                                0 /*is_dwp*/, 0 /*search_cwd*/);
12043
12044   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12045
12046   if (comp_dir != NULL)
12047     {
12048       gdb::unique_xmalloc_ptr<char> path_to_try
12049         (concat (comp_dir, SLASH_STRING, file_name, (char *) NULL));
12050
12051       /* NOTE: If comp_dir is a relative path, this will also try the
12052          search path, which seems useful.  */
12053       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12054                                                 path_to_try.get (),
12055                                                 0 /*is_dwp*/,
12056                                                 1 /*search_cwd*/));
12057       if (abfd != NULL)
12058         return abfd;
12059     }
12060
12061   /* That didn't work, try debug-file-directory, which, despite its name,
12062      is a list of paths.  */
12063
12064   if (*debug_file_directory == '\0')
12065     return NULL;
12066
12067   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12068                              0 /*is_dwp*/, 1 /*search_cwd*/);
12069 }
12070
12071 /* This function is mapped across the sections and remembers the offset and
12072    size of each of the DWO debugging sections we are interested in.  */
12073
12074 static void
12075 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12076 {
12077   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12078   const struct dwop_section_names *names = &dwop_section_names;
12079
12080   if (section_is_p (sectp->name, &names->abbrev_dwo))
12081     {
12082       dwo_sections->abbrev.s.section = sectp;
12083       dwo_sections->abbrev.size = bfd_section_size (sectp);
12084     }
12085   else if (section_is_p (sectp->name, &names->info_dwo))
12086     {
12087       dwo_sections->info.s.section = sectp;
12088       dwo_sections->info.size = bfd_section_size (sectp);
12089     }
12090   else if (section_is_p (sectp->name, &names->line_dwo))
12091     {
12092       dwo_sections->line.s.section = sectp;
12093       dwo_sections->line.size = bfd_section_size (sectp);
12094     }
12095   else if (section_is_p (sectp->name, &names->loc_dwo))
12096     {
12097       dwo_sections->loc.s.section = sectp;
12098       dwo_sections->loc.size = bfd_section_size (sectp);
12099     }
12100   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12101     {
12102       dwo_sections->macinfo.s.section = sectp;
12103       dwo_sections->macinfo.size = bfd_section_size (sectp);
12104     }
12105   else if (section_is_p (sectp->name, &names->macro_dwo))
12106     {
12107       dwo_sections->macro.s.section = sectp;
12108       dwo_sections->macro.size = bfd_section_size (sectp);
12109     }
12110   else if (section_is_p (sectp->name, &names->str_dwo))
12111     {
12112       dwo_sections->str.s.section = sectp;
12113       dwo_sections->str.size = bfd_section_size (sectp);
12114     }
12115   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12116     {
12117       dwo_sections->str_offsets.s.section = sectp;
12118       dwo_sections->str_offsets.size = bfd_section_size (sectp);
12119     }
12120   else if (section_is_p (sectp->name, &names->types_dwo))
12121     {
12122       struct dwarf2_section_info type_section;
12123
12124       memset (&type_section, 0, sizeof (type_section));
12125       type_section.s.section = sectp;
12126       type_section.size = bfd_section_size (sectp);
12127       dwo_sections->types.push_back (type_section);
12128     }
12129 }
12130
12131 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12132    by PER_CU.  This is for the non-DWP case.
12133    The result is NULL if DWO_NAME can't be found.  */
12134
12135 static struct dwo_file *
12136 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12137                         const char *dwo_name, const char *comp_dir)
12138 {
12139   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12140
12141   gdb_bfd_ref_ptr dbfd = open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir);
12142   if (dbfd == NULL)
12143     {
12144       if (dwarf_read_debug)
12145         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12146       return NULL;
12147     }
12148
12149   dwo_file_up dwo_file (new struct dwo_file);
12150   dwo_file->dwo_name = dwo_name;
12151   dwo_file->comp_dir = comp_dir;
12152   dwo_file->dbfd = std::move (dbfd);
12153
12154   bfd_map_over_sections (dwo_file->dbfd.get (), dwarf2_locate_dwo_sections,
12155                          &dwo_file->sections);
12156
12157   create_cus_hash_table (dwarf2_per_objfile, per_cu->cu, *dwo_file,
12158                          dwo_file->sections.info, dwo_file->cus);
12159
12160   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12161                                  dwo_file->sections.types, dwo_file->tus);
12162
12163   if (dwarf_read_debug)
12164     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12165
12166   return dwo_file.release ();
12167 }
12168
12169 /* This function is mapped across the sections and remembers the offset and
12170    size of each of the DWP debugging sections common to version 1 and 2 that
12171    we are interested in.  */
12172
12173 static void
12174 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12175                                    void *dwp_file_ptr)
12176 {
12177   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12178   const struct dwop_section_names *names = &dwop_section_names;
12179   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12180
12181   /* Record the ELF section number for later lookup: this is what the
12182      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12183   gdb_assert (elf_section_nr < dwp_file->num_sections);
12184   dwp_file->elf_sections[elf_section_nr] = sectp;
12185
12186   /* Look for specific sections that we need.  */
12187   if (section_is_p (sectp->name, &names->str_dwo))
12188     {
12189       dwp_file->sections.str.s.section = sectp;
12190       dwp_file->sections.str.size = bfd_section_size (sectp);
12191     }
12192   else if (section_is_p (sectp->name, &names->cu_index))
12193     {
12194       dwp_file->sections.cu_index.s.section = sectp;
12195       dwp_file->sections.cu_index.size = bfd_section_size (sectp);
12196     }
12197   else if (section_is_p (sectp->name, &names->tu_index))
12198     {
12199       dwp_file->sections.tu_index.s.section = sectp;
12200       dwp_file->sections.tu_index.size = bfd_section_size (sectp);
12201     }
12202 }
12203
12204 /* This function is mapped across the sections and remembers the offset and
12205    size of each of the DWP version 2 debugging sections that we are interested
12206    in.  This is split into a separate function because we don't know if we
12207    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12208
12209 static void
12210 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12211 {
12212   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12213   const struct dwop_section_names *names = &dwop_section_names;
12214   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12215
12216   /* Record the ELF section number for later lookup: this is what the
12217      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12218   gdb_assert (elf_section_nr < dwp_file->num_sections);
12219   dwp_file->elf_sections[elf_section_nr] = sectp;
12220
12221   /* Look for specific sections that we need.  */
12222   if (section_is_p (sectp->name, &names->abbrev_dwo))
12223     {
12224       dwp_file->sections.abbrev.s.section = sectp;
12225       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
12226     }
12227   else if (section_is_p (sectp->name, &names->info_dwo))
12228     {
12229       dwp_file->sections.info.s.section = sectp;
12230       dwp_file->sections.info.size = bfd_section_size (sectp);
12231     }
12232   else if (section_is_p (sectp->name, &names->line_dwo))
12233     {
12234       dwp_file->sections.line.s.section = sectp;
12235       dwp_file->sections.line.size = bfd_section_size (sectp);
12236     }
12237   else if (section_is_p (sectp->name, &names->loc_dwo))
12238     {
12239       dwp_file->sections.loc.s.section = sectp;
12240       dwp_file->sections.loc.size = bfd_section_size (sectp);
12241     }
12242   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12243     {
12244       dwp_file->sections.macinfo.s.section = sectp;
12245       dwp_file->sections.macinfo.size = bfd_section_size (sectp);
12246     }
12247   else if (section_is_p (sectp->name, &names->macro_dwo))
12248     {
12249       dwp_file->sections.macro.s.section = sectp;
12250       dwp_file->sections.macro.size = bfd_section_size (sectp);
12251     }
12252   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12253     {
12254       dwp_file->sections.str_offsets.s.section = sectp;
12255       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
12256     }
12257   else if (section_is_p (sectp->name, &names->types_dwo))
12258     {
12259       dwp_file->sections.types.s.section = sectp;
12260       dwp_file->sections.types.size = bfd_section_size (sectp);
12261     }
12262 }
12263
12264 /* Hash function for dwp_file loaded CUs/TUs.  */
12265
12266 static hashval_t
12267 hash_dwp_loaded_cutus (const void *item)
12268 {
12269   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12270
12271   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
12272   return dwo_unit->signature;
12273 }
12274
12275 /* Equality function for dwp_file loaded CUs/TUs.  */
12276
12277 static int
12278 eq_dwp_loaded_cutus (const void *a, const void *b)
12279 {
12280   const struct dwo_unit *dua = (const struct dwo_unit *) a;
12281   const struct dwo_unit *dub = (const struct dwo_unit *) b;
12282
12283   return dua->signature == dub->signature;
12284 }
12285
12286 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
12287
12288 static htab_up
12289 allocate_dwp_loaded_cutus_table ()
12290 {
12291   return htab_up (htab_create_alloc (3,
12292                                      hash_dwp_loaded_cutus,
12293                                      eq_dwp_loaded_cutus,
12294                                      NULL, xcalloc, xfree));
12295 }
12296
12297 /* Try to open DWP file FILE_NAME.
12298    The result is the bfd handle of the file.
12299    If there is a problem finding or opening the file, return NULL.
12300    Upon success, the canonicalized path of the file is stored in the bfd,
12301    same as symfile_bfd_open.  */
12302
12303 static gdb_bfd_ref_ptr
12304 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12305                const char *file_name)
12306 {
12307   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
12308                                             1 /*is_dwp*/,
12309                                             1 /*search_cwd*/));
12310   if (abfd != NULL)
12311     return abfd;
12312
12313   /* Work around upstream bug 15652.
12314      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
12315      [Whether that's a "bug" is debatable, but it is getting in our way.]
12316      We have no real idea where the dwp file is, because gdb's realpath-ing
12317      of the executable's path may have discarded the needed info.
12318      [IWBN if the dwp file name was recorded in the executable, akin to
12319      .gnu_debuglink, but that doesn't exist yet.]
12320      Strip the directory from FILE_NAME and search again.  */
12321   if (*debug_file_directory != '\0')
12322     {
12323       /* Don't implicitly search the current directory here.
12324          If the user wants to search "." to handle this case,
12325          it must be added to debug-file-directory.  */
12326       return try_open_dwop_file (dwarf2_per_objfile,
12327                                  lbasename (file_name), 1 /*is_dwp*/,
12328                                  0 /*search_cwd*/);
12329     }
12330
12331   return NULL;
12332 }
12333
12334 /* Initialize the use of the DWP file for the current objfile.
12335    By convention the name of the DWP file is ${objfile}.dwp.
12336    The result is NULL if it can't be found.  */
12337
12338 static std::unique_ptr<struct dwp_file>
12339 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
12340 {
12341   struct objfile *objfile = dwarf2_per_objfile->objfile;
12342
12343   /* Try to find first .dwp for the binary file before any symbolic links
12344      resolving.  */
12345
12346   /* If the objfile is a debug file, find the name of the real binary
12347      file and get the name of dwp file from there.  */
12348   std::string dwp_name;
12349   if (objfile->separate_debug_objfile_backlink != NULL)
12350     {
12351       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
12352       const char *backlink_basename = lbasename (backlink->original_name);
12353
12354       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
12355     }
12356   else
12357     dwp_name = objfile->original_name;
12358
12359   dwp_name += ".dwp";
12360
12361   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
12362   if (dbfd == NULL
12363       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
12364     {
12365       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
12366       dwp_name = objfile_name (objfile);
12367       dwp_name += ".dwp";
12368       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
12369     }
12370
12371   if (dbfd == NULL)
12372     {
12373       if (dwarf_read_debug)
12374         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
12375       return std::unique_ptr<dwp_file> ();
12376     }
12377
12378   const char *name = bfd_get_filename (dbfd.get ());
12379   std::unique_ptr<struct dwp_file> dwp_file
12380     (new struct dwp_file (name, std::move (dbfd)));
12381
12382   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
12383   dwp_file->elf_sections =
12384     OBSTACK_CALLOC (&objfile->objfile_obstack,
12385                     dwp_file->num_sections, asection *);
12386
12387   bfd_map_over_sections (dwp_file->dbfd.get (),
12388                          dwarf2_locate_common_dwp_sections,
12389                          dwp_file.get ());
12390
12391   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
12392                                          0);
12393
12394   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
12395                                          1);
12396
12397   /* The DWP file version is stored in the hash table.  Oh well.  */
12398   if (dwp_file->cus && dwp_file->tus
12399       && dwp_file->cus->version != dwp_file->tus->version)
12400     {
12401       /* Technically speaking, we should try to limp along, but this is
12402          pretty bizarre.  We use pulongest here because that's the established
12403          portability solution (e.g, we cannot use %u for uint32_t).  */
12404       error (_("Dwarf Error: DWP file CU version %s doesn't match"
12405                " TU version %s [in DWP file %s]"),
12406              pulongest (dwp_file->cus->version),
12407              pulongest (dwp_file->tus->version), dwp_name.c_str ());
12408     }
12409
12410   if (dwp_file->cus)
12411     dwp_file->version = dwp_file->cus->version;
12412   else if (dwp_file->tus)
12413     dwp_file->version = dwp_file->tus->version;
12414   else
12415     dwp_file->version = 2;
12416
12417   if (dwp_file->version == 2)
12418     bfd_map_over_sections (dwp_file->dbfd.get (),
12419                            dwarf2_locate_v2_dwp_sections,
12420                            dwp_file.get ());
12421
12422   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table ();
12423   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table ();
12424
12425   if (dwarf_read_debug)
12426     {
12427       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
12428       fprintf_unfiltered (gdb_stdlog,
12429                           "    %s CUs, %s TUs\n",
12430                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
12431                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
12432     }
12433
12434   return dwp_file;
12435 }
12436
12437 /* Wrapper around open_and_init_dwp_file, only open it once.  */
12438
12439 static struct dwp_file *
12440 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
12441 {
12442   if (! dwarf2_per_objfile->dwp_checked)
12443     {
12444       dwarf2_per_objfile->dwp_file
12445         = open_and_init_dwp_file (dwarf2_per_objfile);
12446       dwarf2_per_objfile->dwp_checked = 1;
12447     }
12448   return dwarf2_per_objfile->dwp_file.get ();
12449 }
12450
12451 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
12452    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
12453    or in the DWP file for the objfile, referenced by THIS_UNIT.
12454    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
12455    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
12456
12457    This is called, for example, when wanting to read a variable with a
12458    complex location.  Therefore we don't want to do file i/o for every call.
12459    Therefore we don't want to look for a DWO file on every call.
12460    Therefore we first see if we've already seen SIGNATURE in a DWP file,
12461    then we check if we've already seen DWO_NAME, and only THEN do we check
12462    for a DWO file.
12463
12464    The result is a pointer to the dwo_unit object or NULL if we didn't find it
12465    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
12466
12467 static struct dwo_unit *
12468 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
12469                  const char *dwo_name, const char *comp_dir,
12470                  ULONGEST signature, int is_debug_types)
12471 {
12472   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
12473   struct objfile *objfile = dwarf2_per_objfile->objfile;
12474   const char *kind = is_debug_types ? "TU" : "CU";
12475   void **dwo_file_slot;
12476   struct dwo_file *dwo_file;
12477   struct dwp_file *dwp_file;
12478
12479   /* First see if there's a DWP file.
12480      If we have a DWP file but didn't find the DWO inside it, don't
12481      look for the original DWO file.  It makes gdb behave differently
12482      depending on whether one is debugging in the build tree.  */
12483
12484   dwp_file = get_dwp_file (dwarf2_per_objfile);
12485   if (dwp_file != NULL)
12486     {
12487       const struct dwp_hash_table *dwp_htab =
12488         is_debug_types ? dwp_file->tus : dwp_file->cus;
12489
12490       if (dwp_htab != NULL)
12491         {
12492           struct dwo_unit *dwo_cutu =
12493             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
12494                                     signature, is_debug_types);
12495
12496           if (dwo_cutu != NULL)
12497             {
12498               if (dwarf_read_debug)
12499                 {
12500                   fprintf_unfiltered (gdb_stdlog,
12501                                       "Virtual DWO %s %s found: @%s\n",
12502                                       kind, hex_string (signature),
12503                                       host_address_to_string (dwo_cutu));
12504                 }
12505               return dwo_cutu;
12506             }
12507         }
12508     }
12509   else
12510     {
12511       /* No DWP file, look for the DWO file.  */
12512
12513       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12514                                             dwo_name, comp_dir);
12515       if (*dwo_file_slot == NULL)
12516         {
12517           /* Read in the file and build a table of the CUs/TUs it contains.  */
12518           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
12519         }
12520       /* NOTE: This will be NULL if unable to open the file.  */
12521       dwo_file = (struct dwo_file *) *dwo_file_slot;
12522
12523       if (dwo_file != NULL)
12524         {
12525           struct dwo_unit *dwo_cutu = NULL;
12526
12527           if (is_debug_types && dwo_file->tus)
12528             {
12529               struct dwo_unit find_dwo_cutu;
12530
12531               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12532               find_dwo_cutu.signature = signature;
12533               dwo_cutu
12534                 = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
12535                                                  &find_dwo_cutu);
12536             }
12537           else if (!is_debug_types && dwo_file->cus)
12538             {
12539               struct dwo_unit find_dwo_cutu;
12540
12541               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12542               find_dwo_cutu.signature = signature;
12543               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus.get (),
12544                                                        &find_dwo_cutu);
12545             }
12546
12547           if (dwo_cutu != NULL)
12548             {
12549               if (dwarf_read_debug)
12550                 {
12551                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
12552                                       kind, dwo_name, hex_string (signature),
12553                                       host_address_to_string (dwo_cutu));
12554                 }
12555               return dwo_cutu;
12556             }
12557         }
12558     }
12559
12560   /* We didn't find it.  This could mean a dwo_id mismatch, or
12561      someone deleted the DWO/DWP file, or the search path isn't set up
12562      correctly to find the file.  */
12563
12564   if (dwarf_read_debug)
12565     {
12566       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
12567                           kind, dwo_name, hex_string (signature));
12568     }
12569
12570   /* This is a warning and not a complaint because it can be caused by
12571      pilot error (e.g., user accidentally deleting the DWO).  */
12572   {
12573     /* Print the name of the DWP file if we looked there, helps the user
12574        better diagnose the problem.  */
12575     std::string dwp_text;
12576
12577     if (dwp_file != NULL)
12578       dwp_text = string_printf (" [in DWP file %s]",
12579                                 lbasename (dwp_file->name));
12580
12581     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
12582                " [in module %s]"),
12583              kind, dwo_name, hex_string (signature),
12584              dwp_text.c_str (),
12585              this_unit->is_debug_types ? "TU" : "CU",
12586              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
12587   }
12588   return NULL;
12589 }
12590
12591 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
12592    See lookup_dwo_cutu_unit for details.  */
12593
12594 static struct dwo_unit *
12595 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
12596                       const char *dwo_name, const char *comp_dir,
12597                       ULONGEST signature)
12598 {
12599   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
12600 }
12601
12602 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
12603    See lookup_dwo_cutu_unit for details.  */
12604
12605 static struct dwo_unit *
12606 lookup_dwo_type_unit (struct signatured_type *this_tu,
12607                       const char *dwo_name, const char *comp_dir)
12608 {
12609   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
12610 }
12611
12612 /* Traversal function for queue_and_load_all_dwo_tus.  */
12613
12614 static int
12615 queue_and_load_dwo_tu (void **slot, void *info)
12616 {
12617   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
12618   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
12619   ULONGEST signature = dwo_unit->signature;
12620   struct signatured_type *sig_type =
12621     lookup_dwo_signatured_type (per_cu->cu, signature);
12622
12623   if (sig_type != NULL)
12624     {
12625       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
12626
12627       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
12628          a real dependency of PER_CU on SIG_TYPE.  That is detected later
12629          while processing PER_CU.  */
12630       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
12631         load_full_type_unit (sig_cu);
12632       per_cu->imported_symtabs_push (sig_cu);
12633     }
12634
12635   return 1;
12636 }
12637
12638 /* Queue all TUs contained in the DWO of PER_CU to be read in.
12639    The DWO may have the only definition of the type, though it may not be
12640    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
12641    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
12642
12643 static void
12644 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
12645 {
12646   struct dwo_unit *dwo_unit;
12647   struct dwo_file *dwo_file;
12648
12649   gdb_assert (!per_cu->is_debug_types);
12650   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
12651   gdb_assert (per_cu->cu != NULL);
12652
12653   dwo_unit = per_cu->cu->dwo_unit;
12654   gdb_assert (dwo_unit != NULL);
12655
12656   dwo_file = dwo_unit->dwo_file;
12657   if (dwo_file->tus != NULL)
12658     htab_traverse_noresize (dwo_file->tus.get (), queue_and_load_dwo_tu,
12659                             per_cu);
12660 }
12661
12662 /* Read in various DIEs.  */
12663
12664 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
12665    Inherit only the children of the DW_AT_abstract_origin DIE not being
12666    already referenced by DW_AT_abstract_origin from the children of the
12667    current DIE.  */
12668
12669 static void
12670 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
12671 {
12672   struct die_info *child_die;
12673   sect_offset *offsetp;
12674   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
12675   struct die_info *origin_die;
12676   /* Iterator of the ORIGIN_DIE children.  */
12677   struct die_info *origin_child_die;
12678   struct attribute *attr;
12679   struct dwarf2_cu *origin_cu;
12680   struct pending **origin_previous_list_in_scope;
12681
12682   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12683   if (!attr)
12684     return;
12685
12686   /* Note that following die references may follow to a die in a
12687      different cu.  */
12688
12689   origin_cu = cu;
12690   origin_die = follow_die_ref (die, attr, &origin_cu);
12691
12692   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
12693      symbols in.  */
12694   origin_previous_list_in_scope = origin_cu->list_in_scope;
12695   origin_cu->list_in_scope = cu->list_in_scope;
12696
12697   if (die->tag != origin_die->tag
12698       && !(die->tag == DW_TAG_inlined_subroutine
12699            && origin_die->tag == DW_TAG_subprogram))
12700     complaint (_("DIE %s and its abstract origin %s have different tags"),
12701                sect_offset_str (die->sect_off),
12702                sect_offset_str (origin_die->sect_off));
12703
12704   std::vector<sect_offset> offsets;
12705
12706   for (child_die = die->child;
12707        child_die && child_die->tag;
12708        child_die = sibling_die (child_die))
12709     {
12710       struct die_info *child_origin_die;
12711       struct dwarf2_cu *child_origin_cu;
12712
12713       /* We are trying to process concrete instance entries:
12714          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
12715          it's not relevant to our analysis here. i.e. detecting DIEs that are
12716          present in the abstract instance but not referenced in the concrete
12717          one.  */
12718       if (child_die->tag == DW_TAG_call_site
12719           || child_die->tag == DW_TAG_GNU_call_site)
12720         continue;
12721
12722       /* For each CHILD_DIE, find the corresponding child of
12723          ORIGIN_DIE.  If there is more than one layer of
12724          DW_AT_abstract_origin, follow them all; there shouldn't be,
12725          but GCC versions at least through 4.4 generate this (GCC PR
12726          40573).  */
12727       child_origin_die = child_die;
12728       child_origin_cu = cu;
12729       while (1)
12730         {
12731           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
12732                               child_origin_cu);
12733           if (attr == NULL)
12734             break;
12735           child_origin_die = follow_die_ref (child_origin_die, attr,
12736                                              &child_origin_cu);
12737         }
12738
12739       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
12740          counterpart may exist.  */
12741       if (child_origin_die != child_die)
12742         {
12743           if (child_die->tag != child_origin_die->tag
12744               && !(child_die->tag == DW_TAG_inlined_subroutine
12745                    && child_origin_die->tag == DW_TAG_subprogram))
12746             complaint (_("Child DIE %s and its abstract origin %s have "
12747                          "different tags"),
12748                        sect_offset_str (child_die->sect_off),
12749                        sect_offset_str (child_origin_die->sect_off));
12750           if (child_origin_die->parent != origin_die)
12751             complaint (_("Child DIE %s and its abstract origin %s have "
12752                          "different parents"),
12753                        sect_offset_str (child_die->sect_off),
12754                        sect_offset_str (child_origin_die->sect_off));
12755           else
12756             offsets.push_back (child_origin_die->sect_off);
12757         }
12758     }
12759   std::sort (offsets.begin (), offsets.end ());
12760   sect_offset *offsets_end = offsets.data () + offsets.size ();
12761   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
12762     if (offsetp[-1] == *offsetp)
12763       complaint (_("Multiple children of DIE %s refer "
12764                    "to DIE %s as their abstract origin"),
12765                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
12766
12767   offsetp = offsets.data ();
12768   origin_child_die = origin_die->child;
12769   while (origin_child_die && origin_child_die->tag)
12770     {
12771       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
12772       while (offsetp < offsets_end
12773              && *offsetp < origin_child_die->sect_off)
12774         offsetp++;
12775       if (offsetp >= offsets_end
12776           || *offsetp > origin_child_die->sect_off)
12777         {
12778           /* Found that ORIGIN_CHILD_DIE is really not referenced.
12779              Check whether we're already processing ORIGIN_CHILD_DIE.
12780              This can happen with mutually referenced abstract_origins.
12781              PR 16581.  */
12782           if (!origin_child_die->in_process)
12783             process_die (origin_child_die, origin_cu);
12784         }
12785       origin_child_die = sibling_die (origin_child_die);
12786     }
12787   origin_cu->list_in_scope = origin_previous_list_in_scope;
12788
12789   if (cu != origin_cu)
12790     compute_delayed_physnames (origin_cu);
12791 }
12792
12793 static void
12794 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
12795 {
12796   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
12797   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12798   struct context_stack *newobj;
12799   CORE_ADDR lowpc;
12800   CORE_ADDR highpc;
12801   struct die_info *child_die;
12802   struct attribute *attr, *call_line, *call_file;
12803   const char *name;
12804   CORE_ADDR baseaddr;
12805   struct block *block;
12806   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
12807   std::vector<struct symbol *> template_args;
12808   struct template_symbol *templ_func = NULL;
12809
12810   if (inlined_func)
12811     {
12812       /* If we do not have call site information, we can't show the
12813          caller of this inlined function.  That's too confusing, so
12814          only use the scope for local variables.  */
12815       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
12816       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
12817       if (call_line == NULL || call_file == NULL)
12818         {
12819           read_lexical_block_scope (die, cu);
12820           return;
12821         }
12822     }
12823
12824   baseaddr = objfile->text_section_offset ();
12825
12826   name = dwarf2_name (die, cu);
12827
12828   /* Ignore functions with missing or empty names.  These are actually
12829      illegal according to the DWARF standard.  */
12830   if (name == NULL)
12831     {
12832       complaint (_("missing name for subprogram DIE at %s"),
12833                  sect_offset_str (die->sect_off));
12834       return;
12835     }
12836
12837   /* Ignore functions with missing or invalid low and high pc attributes.  */
12838   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
12839       <= PC_BOUNDS_INVALID)
12840     {
12841       attr = dwarf2_attr (die, DW_AT_external, cu);
12842       if (!attr || !DW_UNSND (attr))
12843         complaint (_("cannot get low and high bounds "
12844                      "for subprogram DIE at %s"),
12845                    sect_offset_str (die->sect_off));
12846       return;
12847     }
12848
12849   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12850   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12851
12852   /* If we have any template arguments, then we must allocate a
12853      different sort of symbol.  */
12854   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
12855     {
12856       if (child_die->tag == DW_TAG_template_type_param
12857           || child_die->tag == DW_TAG_template_value_param)
12858         {
12859           templ_func = allocate_template_symbol (objfile);
12860           templ_func->subclass = SYMBOL_TEMPLATE;
12861           break;
12862         }
12863     }
12864
12865   newobj = cu->get_builder ()->push_context (0, lowpc);
12866   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
12867                              (struct symbol *) templ_func);
12868
12869   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
12870     set_objfile_main_name (objfile, newobj->name->linkage_name (),
12871                            cu->language);
12872
12873   /* If there is a location expression for DW_AT_frame_base, record
12874      it.  */
12875   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
12876   if (attr != nullptr)
12877     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
12878
12879   /* If there is a location for the static link, record it.  */
12880   newobj->static_link = NULL;
12881   attr = dwarf2_attr (die, DW_AT_static_link, cu);
12882   if (attr != nullptr)
12883     {
12884       newobj->static_link
12885         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
12886       attr_to_dynamic_prop (attr, die, cu, newobj->static_link,
12887                             cu->per_cu->addr_type ());
12888     }
12889
12890   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
12891
12892   if (die->child != NULL)
12893     {
12894       child_die = die->child;
12895       while (child_die && child_die->tag)
12896         {
12897           if (child_die->tag == DW_TAG_template_type_param
12898               || child_die->tag == DW_TAG_template_value_param)
12899             {
12900               struct symbol *arg = new_symbol (child_die, NULL, cu);
12901
12902               if (arg != NULL)
12903                 template_args.push_back (arg);
12904             }
12905           else
12906             process_die (child_die, cu);
12907           child_die = sibling_die (child_die);
12908         }
12909     }
12910
12911   inherit_abstract_dies (die, cu);
12912
12913   /* If we have a DW_AT_specification, we might need to import using
12914      directives from the context of the specification DIE.  See the
12915      comment in determine_prefix.  */
12916   if (cu->language == language_cplus
12917       && dwarf2_attr (die, DW_AT_specification, cu))
12918     {
12919       struct dwarf2_cu *spec_cu = cu;
12920       struct die_info *spec_die = die_specification (die, &spec_cu);
12921
12922       while (spec_die)
12923         {
12924           child_die = spec_die->child;
12925           while (child_die && child_die->tag)
12926             {
12927               if (child_die->tag == DW_TAG_imported_module)
12928                 process_die (child_die, spec_cu);
12929               child_die = sibling_die (child_die);
12930             }
12931
12932           /* In some cases, GCC generates specification DIEs that
12933              themselves contain DW_AT_specification attributes.  */
12934           spec_die = die_specification (spec_die, &spec_cu);
12935         }
12936     }
12937
12938   struct context_stack cstk = cu->get_builder ()->pop_context ();
12939   /* Make a block for the local symbols within.  */
12940   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
12941                                      cstk.static_link, lowpc, highpc);
12942
12943   /* For C++, set the block's scope.  */
12944   if ((cu->language == language_cplus
12945        || cu->language == language_fortran
12946        || cu->language == language_d
12947        || cu->language == language_rust)
12948       && cu->processing_has_namespace_info)
12949     block_set_scope (block, determine_prefix (die, cu),
12950                      &objfile->objfile_obstack);
12951
12952   /* If we have address ranges, record them.  */
12953   dwarf2_record_block_ranges (die, block, baseaddr, cu);
12954
12955   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
12956
12957   /* Attach template arguments to function.  */
12958   if (!template_args.empty ())
12959     {
12960       gdb_assert (templ_func != NULL);
12961
12962       templ_func->n_template_arguments = template_args.size ();
12963       templ_func->template_arguments
12964         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
12965                      templ_func->n_template_arguments);
12966       memcpy (templ_func->template_arguments,
12967               template_args.data (),
12968               (templ_func->n_template_arguments * sizeof (struct symbol *)));
12969
12970       /* Make sure that the symtab is set on the new symbols.  Even
12971          though they don't appear in this symtab directly, other parts
12972          of gdb assume that symbols do, and this is reasonably
12973          true.  */
12974       for (symbol *sym : template_args)
12975         symbol_set_symtab (sym, symbol_symtab (templ_func));
12976     }
12977
12978   /* In C++, we can have functions nested inside functions (e.g., when
12979      a function declares a class that has methods).  This means that
12980      when we finish processing a function scope, we may need to go
12981      back to building a containing block's symbol lists.  */
12982   *cu->get_builder ()->get_local_symbols () = cstk.locals;
12983   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
12984
12985   /* If we've finished processing a top-level function, subsequent
12986      symbols go in the file symbol list.  */
12987   if (cu->get_builder ()->outermost_context_p ())
12988     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
12989 }
12990
12991 /* Process all the DIES contained within a lexical block scope.  Start
12992    a new scope, process the dies, and then close the scope.  */
12993
12994 static void
12995 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
12996 {
12997   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
12998   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12999   CORE_ADDR lowpc, highpc;
13000   struct die_info *child_die;
13001   CORE_ADDR baseaddr;
13002
13003   baseaddr = objfile->text_section_offset ();
13004
13005   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13006   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13007      as multiple lexical blocks?  Handling children in a sane way would
13008      be nasty.  Might be easier to properly extend generic blocks to
13009      describe ranges.  */
13010   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13011     {
13012     case PC_BOUNDS_NOT_PRESENT:
13013       /* DW_TAG_lexical_block has no attributes, process its children as if
13014          there was no wrapping by that DW_TAG_lexical_block.
13015          GCC does no longer produces such DWARF since GCC r224161.  */
13016       for (child_die = die->child;
13017            child_die != NULL && child_die->tag;
13018            child_die = sibling_die (child_die))
13019         process_die (child_die, cu);
13020       return;
13021     case PC_BOUNDS_INVALID:
13022       return;
13023     }
13024   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13025   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13026
13027   cu->get_builder ()->push_context (0, lowpc);
13028   if (die->child != NULL)
13029     {
13030       child_die = die->child;
13031       while (child_die && child_die->tag)
13032         {
13033           process_die (child_die, cu);
13034           child_die = sibling_die (child_die);
13035         }
13036     }
13037   inherit_abstract_dies (die, cu);
13038   struct context_stack cstk = cu->get_builder ()->pop_context ();
13039
13040   if (*cu->get_builder ()->get_local_symbols () != NULL
13041       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13042     {
13043       struct block *block
13044         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13045                                      cstk.start_addr, highpc);
13046
13047       /* Note that recording ranges after traversing children, as we
13048          do here, means that recording a parent's ranges entails
13049          walking across all its children's ranges as they appear in
13050          the address map, which is quadratic behavior.
13051
13052          It would be nicer to record the parent's ranges before
13053          traversing its children, simply overriding whatever you find
13054          there.  But since we don't even decide whether to create a
13055          block until after we've traversed its children, that's hard
13056          to do.  */
13057       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13058     }
13059   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13060   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13061 }
13062
13063 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13064
13065 static void
13066 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13067 {
13068   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13069   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13070   CORE_ADDR pc, baseaddr;
13071   struct attribute *attr;
13072   struct call_site *call_site, call_site_local;
13073   void **slot;
13074   int nparams;
13075   struct die_info *child_die;
13076
13077   baseaddr = objfile->text_section_offset ();
13078
13079   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13080   if (attr == NULL)
13081     {
13082       /* This was a pre-DWARF-5 GNU extension alias
13083          for DW_AT_call_return_pc.  */
13084       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13085     }
13086   if (!attr)
13087     {
13088       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13089                    "DIE %s [in module %s]"),
13090                  sect_offset_str (die->sect_off), objfile_name (objfile));
13091       return;
13092     }
13093   pc = attr->value_as_address () + baseaddr;
13094   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13095
13096   if (cu->call_site_htab == NULL)
13097     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13098                                                NULL, &objfile->objfile_obstack,
13099                                                hashtab_obstack_allocate, NULL);
13100   call_site_local.pc = pc;
13101   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13102   if (*slot != NULL)
13103     {
13104       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13105                    "DIE %s [in module %s]"),
13106                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13107                  objfile_name (objfile));
13108       return;
13109     }
13110
13111   /* Count parameters at the caller.  */
13112
13113   nparams = 0;
13114   for (child_die = die->child; child_die && child_die->tag;
13115        child_die = sibling_die (child_die))
13116     {
13117       if (child_die->tag != DW_TAG_call_site_parameter
13118           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13119         {
13120           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13121                        "DW_TAG_call_site child DIE %s [in module %s]"),
13122                      child_die->tag, sect_offset_str (child_die->sect_off),
13123                      objfile_name (objfile));
13124           continue;
13125         }
13126
13127       nparams++;
13128     }
13129
13130   call_site
13131     = ((struct call_site *)
13132        obstack_alloc (&objfile->objfile_obstack,
13133                       sizeof (*call_site)
13134                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13135   *slot = call_site;
13136   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13137   call_site->pc = pc;
13138
13139   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13140       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13141     {
13142       struct die_info *func_die;
13143
13144       /* Skip also over DW_TAG_inlined_subroutine.  */
13145       for (func_die = die->parent;
13146            func_die && func_die->tag != DW_TAG_subprogram
13147            && func_die->tag != DW_TAG_subroutine_type;
13148            func_die = func_die->parent);
13149
13150       /* DW_AT_call_all_calls is a superset
13151          of DW_AT_call_all_tail_calls.  */
13152       if (func_die
13153           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13154           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13155           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13156           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13157         {
13158           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13159              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13160              both the initial caller containing the real return address PC and
13161              the final callee containing the current PC of a chain of tail
13162              calls do not need to have the tail call list complete.  But any
13163              function candidate for a virtual tail call frame searched via
13164              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13165              determined unambiguously.  */
13166         }
13167       else
13168         {
13169           struct type *func_type = NULL;
13170
13171           if (func_die)
13172             func_type = get_die_type (func_die, cu);
13173           if (func_type != NULL)
13174             {
13175               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13176
13177               /* Enlist this call site to the function.  */
13178               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13179               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13180             }
13181           else
13182             complaint (_("Cannot find function owning DW_TAG_call_site "
13183                          "DIE %s [in module %s]"),
13184                        sect_offset_str (die->sect_off), objfile_name (objfile));
13185         }
13186     }
13187
13188   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13189   if (attr == NULL)
13190     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13191   if (attr == NULL)
13192     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13193   if (attr == NULL)
13194     {
13195       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13196       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13197     }
13198   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13199   if (!attr || (attr->form_is_block () && DW_BLOCK (attr)->size == 0))
13200     /* Keep NULL DWARF_BLOCK.  */;
13201   else if (attr->form_is_block ())
13202     {
13203       struct dwarf2_locexpr_baton *dlbaton;
13204
13205       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13206       dlbaton->data = DW_BLOCK (attr)->data;
13207       dlbaton->size = DW_BLOCK (attr)->size;
13208       dlbaton->per_cu = cu->per_cu;
13209
13210       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13211     }
13212   else if (attr->form_is_ref ())
13213     {
13214       struct dwarf2_cu *target_cu = cu;
13215       struct die_info *target_die;
13216
13217       target_die = follow_die_ref (die, attr, &target_cu);
13218       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13219       if (die_is_declaration (target_die, target_cu))
13220         {
13221           const char *target_physname;
13222
13223           /* Prefer the mangled name; otherwise compute the demangled one.  */
13224           target_physname = dw2_linkage_name (target_die, target_cu);
13225           if (target_physname == NULL)
13226             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13227           if (target_physname == NULL)
13228             complaint (_("DW_AT_call_target target DIE has invalid "
13229                          "physname, for referencing DIE %s [in module %s]"),
13230                        sect_offset_str (die->sect_off), objfile_name (objfile));
13231           else
13232             SET_FIELD_PHYSNAME (call_site->target, target_physname);
13233         }
13234       else
13235         {
13236           CORE_ADDR lowpc;
13237
13238           /* DW_AT_entry_pc should be preferred.  */
13239           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13240               <= PC_BOUNDS_INVALID)
13241             complaint (_("DW_AT_call_target target DIE has invalid "
13242                          "low pc, for referencing DIE %s [in module %s]"),
13243                        sect_offset_str (die->sect_off), objfile_name (objfile));
13244           else
13245             {
13246               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13247               SET_FIELD_PHYSADDR (call_site->target, lowpc);
13248             }
13249         }
13250     }
13251   else
13252     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
13253                  "block nor reference, for DIE %s [in module %s]"),
13254                sect_offset_str (die->sect_off), objfile_name (objfile));
13255
13256   call_site->per_cu = cu->per_cu;
13257
13258   for (child_die = die->child;
13259        child_die && child_die->tag;
13260        child_die = sibling_die (child_die))
13261     {
13262       struct call_site_parameter *parameter;
13263       struct attribute *loc, *origin;
13264
13265       if (child_die->tag != DW_TAG_call_site_parameter
13266           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13267         {
13268           /* Already printed the complaint above.  */
13269           continue;
13270         }
13271
13272       gdb_assert (call_site->parameter_count < nparams);
13273       parameter = &call_site->parameter[call_site->parameter_count];
13274
13275       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
13276          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
13277          register is contained in DW_AT_call_value.  */
13278
13279       loc = dwarf2_attr (child_die, DW_AT_location, cu);
13280       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
13281       if (origin == NULL)
13282         {
13283           /* This was a pre-DWARF-5 GNU extension alias
13284              for DW_AT_call_parameter.  */
13285           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
13286         }
13287       if (loc == NULL && origin != NULL && origin->form_is_ref ())
13288         {
13289           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
13290
13291           sect_offset sect_off
13292             = (sect_offset) dwarf2_get_ref_die_offset (origin);
13293           if (!cu->header.offset_in_cu_p (sect_off))
13294             {
13295               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
13296                  binding can be done only inside one CU.  Such referenced DIE
13297                  therefore cannot be even moved to DW_TAG_partial_unit.  */
13298               complaint (_("DW_AT_call_parameter offset is not in CU for "
13299                            "DW_TAG_call_site child DIE %s [in module %s]"),
13300                          sect_offset_str (child_die->sect_off),
13301                          objfile_name (objfile));
13302               continue;
13303             }
13304           parameter->u.param_cu_off
13305             = (cu_offset) (sect_off - cu->header.sect_off);
13306         }
13307       else if (loc == NULL || origin != NULL || !loc->form_is_block ())
13308         {
13309           complaint (_("No DW_FORM_block* DW_AT_location for "
13310                        "DW_TAG_call_site child DIE %s [in module %s]"),
13311                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
13312           continue;
13313         }
13314       else
13315         {
13316           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
13317             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
13318           if (parameter->u.dwarf_reg != -1)
13319             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
13320           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
13321                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
13322                                              &parameter->u.fb_offset))
13323             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
13324           else
13325             {
13326               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
13327                            "for DW_FORM_block* DW_AT_location is supported for "
13328                            "DW_TAG_call_site child DIE %s "
13329                            "[in module %s]"),
13330                          sect_offset_str (child_die->sect_off),
13331                          objfile_name (objfile));
13332               continue;
13333             }
13334         }
13335
13336       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
13337       if (attr == NULL)
13338         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
13339       if (attr == NULL || !attr->form_is_block ())
13340         {
13341           complaint (_("No DW_FORM_block* DW_AT_call_value for "
13342                        "DW_TAG_call_site child DIE %s [in module %s]"),
13343                      sect_offset_str (child_die->sect_off),
13344                      objfile_name (objfile));
13345           continue;
13346         }
13347       parameter->value = DW_BLOCK (attr)->data;
13348       parameter->value_size = DW_BLOCK (attr)->size;
13349
13350       /* Parameters are not pre-cleared by memset above.  */
13351       parameter->data_value = NULL;
13352       parameter->data_value_size = 0;
13353       call_site->parameter_count++;
13354
13355       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
13356       if (attr == NULL)
13357         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
13358       if (attr != nullptr)
13359         {
13360           if (!attr->form_is_block ())
13361             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
13362                          "DW_TAG_call_site child DIE %s [in module %s]"),
13363                        sect_offset_str (child_die->sect_off),
13364                        objfile_name (objfile));
13365           else
13366             {
13367               parameter->data_value = DW_BLOCK (attr)->data;
13368               parameter->data_value_size = DW_BLOCK (attr)->size;
13369             }
13370         }
13371     }
13372 }
13373
13374 /* Helper function for read_variable.  If DIE represents a virtual
13375    table, then return the type of the concrete object that is
13376    associated with the virtual table.  Otherwise, return NULL.  */
13377
13378 static struct type *
13379 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13380 {
13381   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
13382   if (attr == NULL)
13383     return NULL;
13384
13385   /* Find the type DIE.  */
13386   struct die_info *type_die = NULL;
13387   struct dwarf2_cu *type_cu = cu;
13388
13389   if (attr->form_is_ref ())
13390     type_die = follow_die_ref (die, attr, &type_cu);
13391   if (type_die == NULL)
13392     return NULL;
13393
13394   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
13395     return NULL;
13396   return die_containing_type (type_die, type_cu);
13397 }
13398
13399 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
13400
13401 static void
13402 read_variable (struct die_info *die, struct dwarf2_cu *cu)
13403 {
13404   struct rust_vtable_symbol *storage = NULL;
13405
13406   if (cu->language == language_rust)
13407     {
13408       struct type *containing_type = rust_containing_type (die, cu);
13409
13410       if (containing_type != NULL)
13411         {
13412           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13413
13414           storage = new (&objfile->objfile_obstack) rust_vtable_symbol ();
13415           initialize_objfile_symbol (storage);
13416           storage->concrete_type = containing_type;
13417           storage->subclass = SYMBOL_RUST_VTABLE;
13418         }
13419     }
13420
13421   struct symbol *res = new_symbol (die, NULL, cu, storage);
13422   struct attribute *abstract_origin
13423     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13424   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
13425   if (res == NULL && loc && abstract_origin)
13426     {
13427       /* We have a variable without a name, but with a location and an abstract
13428          origin.  This may be a concrete instance of an abstract variable
13429          referenced from an DW_OP_GNU_variable_value, so save it to find it back
13430          later.  */
13431       struct dwarf2_cu *origin_cu = cu;
13432       struct die_info *origin_die
13433         = follow_die_ref (die, abstract_origin, &origin_cu);
13434       dwarf2_per_objfile *dpo = cu->per_cu->dwarf2_per_objfile;
13435       dpo->abstract_to_concrete[origin_die->sect_off].push_back (die->sect_off);
13436     }
13437 }
13438
13439 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
13440    reading .debug_rnglists.
13441    Callback's type should be:
13442     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13443    Return true if the attributes are present and valid, otherwise,
13444    return false.  */
13445
13446 template <typename Callback>
13447 static bool
13448 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
13449                          Callback &&callback)
13450 {
13451   struct dwarf2_per_objfile *dwarf2_per_objfile
13452     = cu->per_cu->dwarf2_per_objfile;
13453   struct objfile *objfile = dwarf2_per_objfile->objfile;
13454   bfd *obfd = objfile->obfd;
13455   /* Base address selection entry.  */
13456   CORE_ADDR base;
13457   int found_base;
13458   const gdb_byte *buffer;
13459   CORE_ADDR baseaddr;
13460   bool overflow = false;
13461
13462   found_base = cu->base_known;
13463   base = cu->base_address;
13464
13465   dwarf2_per_objfile->rnglists.read (objfile);
13466   if (offset >= dwarf2_per_objfile->rnglists.size)
13467     {
13468       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
13469                  offset);
13470       return false;
13471     }
13472   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
13473
13474   baseaddr = objfile->text_section_offset ();
13475
13476   while (1)
13477     {
13478       /* Initialize it due to a false compiler warning.  */
13479       CORE_ADDR range_beginning = 0, range_end = 0;
13480       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
13481                                  + dwarf2_per_objfile->rnglists.size);
13482       unsigned int bytes_read;
13483
13484       if (buffer == buf_end)
13485         {
13486           overflow = true;
13487           break;
13488         }
13489       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
13490       switch (rlet)
13491         {
13492         case DW_RLE_end_of_list:
13493           break;
13494         case DW_RLE_base_address:
13495           if (buffer + cu->header.addr_size > buf_end)
13496             {
13497               overflow = true;
13498               break;
13499             }
13500           base = cu->header.read_address (obfd, buffer, &bytes_read);
13501           found_base = 1;
13502           buffer += bytes_read;
13503           break;
13504         case DW_RLE_start_length:
13505           if (buffer + cu->header.addr_size > buf_end)
13506             {
13507               overflow = true;
13508               break;
13509             }
13510           range_beginning = cu->header.read_address (obfd, buffer,
13511                                                      &bytes_read);
13512           buffer += bytes_read;
13513           range_end = (range_beginning
13514                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13515           buffer += bytes_read;
13516           if (buffer > buf_end)
13517             {
13518               overflow = true;
13519               break;
13520             }
13521           break;
13522         case DW_RLE_offset_pair:
13523           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13524           buffer += bytes_read;
13525           if (buffer > buf_end)
13526             {
13527               overflow = true;
13528               break;
13529             }
13530           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13531           buffer += bytes_read;
13532           if (buffer > buf_end)
13533             {
13534               overflow = true;
13535               break;
13536             }
13537           break;
13538         case DW_RLE_start_end:
13539           if (buffer + 2 * cu->header.addr_size > buf_end)
13540             {
13541               overflow = true;
13542               break;
13543             }
13544           range_beginning = cu->header.read_address (obfd, buffer,
13545                                                      &bytes_read);
13546           buffer += bytes_read;
13547           range_end = cu->header.read_address (obfd, buffer, &bytes_read);
13548           buffer += bytes_read;
13549           break;
13550         default:
13551           complaint (_("Invalid .debug_rnglists data (no base address)"));
13552           return false;
13553         }
13554       if (rlet == DW_RLE_end_of_list || overflow)
13555         break;
13556       if (rlet == DW_RLE_base_address)
13557         continue;
13558
13559       if (!found_base)
13560         {
13561           /* We have no valid base address for the ranges
13562              data.  */
13563           complaint (_("Invalid .debug_rnglists data (no base address)"));
13564           return false;
13565         }
13566
13567       if (range_beginning > range_end)
13568         {
13569           /* Inverted range entries are invalid.  */
13570           complaint (_("Invalid .debug_rnglists data (inverted range)"));
13571           return false;
13572         }
13573
13574       /* Empty range entries have no effect.  */
13575       if (range_beginning == range_end)
13576         continue;
13577
13578       range_beginning += base;
13579       range_end += base;
13580
13581       /* A not-uncommon case of bad debug info.
13582          Don't pollute the addrmap with bad data.  */
13583       if (range_beginning + baseaddr == 0
13584           && !dwarf2_per_objfile->has_section_at_zero)
13585         {
13586           complaint (_(".debug_rnglists entry has start address of zero"
13587                        " [in module %s]"), objfile_name (objfile));
13588           continue;
13589         }
13590
13591       callback (range_beginning, range_end);
13592     }
13593
13594   if (overflow)
13595     {
13596       complaint (_("Offset %d is not terminated "
13597                    "for DW_AT_ranges attribute"),
13598                  offset);
13599       return false;
13600     }
13601
13602   return true;
13603 }
13604
13605 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
13606    Callback's type should be:
13607     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13608    Return 1 if the attributes are present and valid, otherwise, return 0.  */
13609
13610 template <typename Callback>
13611 static int
13612 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
13613                        Callback &&callback)
13614 {
13615   struct dwarf2_per_objfile *dwarf2_per_objfile
13616       = cu->per_cu->dwarf2_per_objfile;
13617   struct objfile *objfile = dwarf2_per_objfile->objfile;
13618   struct comp_unit_head *cu_header = &cu->header;
13619   bfd *obfd = objfile->obfd;
13620   unsigned int addr_size = cu_header->addr_size;
13621   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13622   /* Base address selection entry.  */
13623   CORE_ADDR base;
13624   int found_base;
13625   unsigned int dummy;
13626   const gdb_byte *buffer;
13627   CORE_ADDR baseaddr;
13628
13629   if (cu_header->version >= 5)
13630     return dwarf2_rnglists_process (offset, cu, callback);
13631
13632   found_base = cu->base_known;
13633   base = cu->base_address;
13634
13635   dwarf2_per_objfile->ranges.read (objfile);
13636   if (offset >= dwarf2_per_objfile->ranges.size)
13637     {
13638       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
13639                  offset);
13640       return 0;
13641     }
13642   buffer = dwarf2_per_objfile->ranges.buffer + offset;
13643
13644   baseaddr = objfile->text_section_offset ();
13645
13646   while (1)
13647     {
13648       CORE_ADDR range_beginning, range_end;
13649
13650       range_beginning = cu->header.read_address (obfd, buffer, &dummy);
13651       buffer += addr_size;
13652       range_end = cu->header.read_address (obfd, buffer, &dummy);
13653       buffer += addr_size;
13654       offset += 2 * addr_size;
13655
13656       /* An end of list marker is a pair of zero addresses.  */
13657       if (range_beginning == 0 && range_end == 0)
13658         /* Found the end of list entry.  */
13659         break;
13660
13661       /* Each base address selection entry is a pair of 2 values.
13662          The first is the largest possible address, the second is
13663          the base address.  Check for a base address here.  */
13664       if ((range_beginning & mask) == mask)
13665         {
13666           /* If we found the largest possible address, then we already
13667              have the base address in range_end.  */
13668           base = range_end;
13669           found_base = 1;
13670           continue;
13671         }
13672
13673       if (!found_base)
13674         {
13675           /* We have no valid base address for the ranges
13676              data.  */
13677           complaint (_("Invalid .debug_ranges data (no base address)"));
13678           return 0;
13679         }
13680
13681       if (range_beginning > range_end)
13682         {
13683           /* Inverted range entries are invalid.  */
13684           complaint (_("Invalid .debug_ranges data (inverted range)"));
13685           return 0;
13686         }
13687
13688       /* Empty range entries have no effect.  */
13689       if (range_beginning == range_end)
13690         continue;
13691
13692       range_beginning += base;
13693       range_end += base;
13694
13695       /* A not-uncommon case of bad debug info.
13696          Don't pollute the addrmap with bad data.  */
13697       if (range_beginning + baseaddr == 0
13698           && !dwarf2_per_objfile->has_section_at_zero)
13699         {
13700           complaint (_(".debug_ranges entry has start address of zero"
13701                        " [in module %s]"), objfile_name (objfile));
13702           continue;
13703         }
13704
13705       callback (range_beginning, range_end);
13706     }
13707
13708   return 1;
13709 }
13710
13711 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
13712    Return 1 if the attributes are present and valid, otherwise, return 0.
13713    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
13714
13715 static int
13716 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
13717                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
13718                     dwarf2_psymtab *ranges_pst)
13719 {
13720   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13721   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13722   const CORE_ADDR baseaddr = objfile->text_section_offset ();
13723   int low_set = 0;
13724   CORE_ADDR low = 0;
13725   CORE_ADDR high = 0;
13726   int retval;
13727
13728   retval = dwarf2_ranges_process (offset, cu,
13729     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
13730     {
13731       if (ranges_pst != NULL)
13732         {
13733           CORE_ADDR lowpc;
13734           CORE_ADDR highpc;
13735
13736           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
13737                                                range_beginning + baseaddr)
13738                    - baseaddr);
13739           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
13740                                                 range_end + baseaddr)
13741                     - baseaddr);
13742           addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
13743                              lowpc, highpc - 1, ranges_pst);
13744         }
13745
13746       /* FIXME: This is recording everything as a low-high
13747          segment of consecutive addresses.  We should have a
13748          data structure for discontiguous block ranges
13749          instead.  */
13750       if (! low_set)
13751         {
13752           low = range_beginning;
13753           high = range_end;
13754           low_set = 1;
13755         }
13756       else
13757         {
13758           if (range_beginning < low)
13759             low = range_beginning;
13760           if (range_end > high)
13761             high = range_end;
13762         }
13763     });
13764   if (!retval)
13765     return 0;
13766
13767   if (! low_set)
13768     /* If the first entry is an end-of-list marker, the range
13769        describes an empty scope, i.e. no instructions.  */
13770     return 0;
13771
13772   if (low_return)
13773     *low_return = low;
13774   if (high_return)
13775     *high_return = high;
13776   return 1;
13777 }
13778
13779 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
13780    definition for the return value.  *LOWPC and *HIGHPC are set iff
13781    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
13782
13783 static enum pc_bounds_kind
13784 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
13785                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
13786                       dwarf2_psymtab *pst)
13787 {
13788   struct dwarf2_per_objfile *dwarf2_per_objfile
13789     = cu->per_cu->dwarf2_per_objfile;
13790   struct attribute *attr;
13791   struct attribute *attr_high;
13792   CORE_ADDR low = 0;
13793   CORE_ADDR high = 0;
13794   enum pc_bounds_kind ret;
13795
13796   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13797   if (attr_high)
13798     {
13799       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13800       if (attr != nullptr)
13801         {
13802           low = attr->value_as_address ();
13803           high = attr_high->value_as_address ();
13804           if (cu->header.version >= 4 && attr_high->form_is_constant ())
13805             high += low;
13806         }
13807       else
13808         /* Found high w/o low attribute.  */
13809         return PC_BOUNDS_INVALID;
13810
13811       /* Found consecutive range of addresses.  */
13812       ret = PC_BOUNDS_HIGH_LOW;
13813     }
13814   else
13815     {
13816       attr = dwarf2_attr (die, DW_AT_ranges, cu);
13817       if (attr != NULL)
13818         {
13819           /* DW_AT_rnglists_base does not apply to DIEs from the DWO skeleton.
13820              We take advantage of the fact that DW_AT_ranges does not appear
13821              in DW_TAG_compile_unit of DWO files.  */
13822           int need_ranges_base = die->tag != DW_TAG_compile_unit;
13823           unsigned int ranges_offset = (DW_UNSND (attr)
13824                                         + (need_ranges_base
13825                                            ? cu->ranges_base
13826                                            : 0));
13827
13828           /* Value of the DW_AT_ranges attribute is the offset in the
13829              .debug_ranges section.  */
13830           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
13831             return PC_BOUNDS_INVALID;
13832           /* Found discontinuous range of addresses.  */
13833           ret = PC_BOUNDS_RANGES;
13834         }
13835       else
13836         return PC_BOUNDS_NOT_PRESENT;
13837     }
13838
13839   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
13840   if (high <= low)
13841     return PC_BOUNDS_INVALID;
13842
13843   /* When using the GNU linker, .gnu.linkonce. sections are used to
13844      eliminate duplicate copies of functions and vtables and such.
13845      The linker will arbitrarily choose one and discard the others.
13846      The AT_*_pc values for such functions refer to local labels in
13847      these sections.  If the section from that file was discarded, the
13848      labels are not in the output, so the relocs get a value of 0.
13849      If this is a discarded function, mark the pc bounds as invalid,
13850      so that GDB will ignore it.  */
13851   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
13852     return PC_BOUNDS_INVALID;
13853
13854   *lowpc = low;
13855   if (highpc)
13856     *highpc = high;
13857   return ret;
13858 }
13859
13860 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
13861    its low and high PC addresses.  Do nothing if these addresses could not
13862    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
13863    and HIGHPC to the high address if greater than HIGHPC.  */
13864
13865 static void
13866 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
13867                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
13868                                  struct dwarf2_cu *cu)
13869 {
13870   CORE_ADDR low, high;
13871   struct die_info *child = die->child;
13872
13873   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
13874     {
13875       *lowpc = std::min (*lowpc, low);
13876       *highpc = std::max (*highpc, high);
13877     }
13878
13879   /* If the language does not allow nested subprograms (either inside
13880      subprograms or lexical blocks), we're done.  */
13881   if (cu->language != language_ada)
13882     return;
13883
13884   /* Check all the children of the given DIE.  If it contains nested
13885      subprograms, then check their pc bounds.  Likewise, we need to
13886      check lexical blocks as well, as they may also contain subprogram
13887      definitions.  */
13888   while (child && child->tag)
13889     {
13890       if (child->tag == DW_TAG_subprogram
13891           || child->tag == DW_TAG_lexical_block)
13892         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
13893       child = sibling_die (child);
13894     }
13895 }
13896
13897 /* Get the low and high pc's represented by the scope DIE, and store
13898    them in *LOWPC and *HIGHPC.  If the correct values can't be
13899    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
13900
13901 static void
13902 get_scope_pc_bounds (struct die_info *die,
13903                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
13904                      struct dwarf2_cu *cu)
13905 {
13906   CORE_ADDR best_low = (CORE_ADDR) -1;
13907   CORE_ADDR best_high = (CORE_ADDR) 0;
13908   CORE_ADDR current_low, current_high;
13909
13910   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
13911       >= PC_BOUNDS_RANGES)
13912     {
13913       best_low = current_low;
13914       best_high = current_high;
13915     }
13916   else
13917     {
13918       struct die_info *child = die->child;
13919
13920       while (child && child->tag)
13921         {
13922           switch (child->tag) {
13923           case DW_TAG_subprogram:
13924             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
13925             break;
13926           case DW_TAG_namespace:
13927           case DW_TAG_module:
13928             /* FIXME: carlton/2004-01-16: Should we do this for
13929                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
13930                that current GCC's always emit the DIEs corresponding
13931                to definitions of methods of classes as children of a
13932                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
13933                the DIEs giving the declarations, which could be
13934                anywhere).  But I don't see any reason why the
13935                standards says that they have to be there.  */
13936             get_scope_pc_bounds (child, &current_low, &current_high, cu);
13937
13938             if (current_low != ((CORE_ADDR) -1))
13939               {
13940                 best_low = std::min (best_low, current_low);
13941                 best_high = std::max (best_high, current_high);
13942               }
13943             break;
13944           default:
13945             /* Ignore.  */
13946             break;
13947           }
13948
13949           child = sibling_die (child);
13950         }
13951     }
13952
13953   *lowpc = best_low;
13954   *highpc = best_high;
13955 }
13956
13957 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
13958    in DIE.  */
13959
13960 static void
13961 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
13962                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
13963 {
13964   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13965   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13966   struct attribute *attr;
13967   struct attribute *attr_high;
13968
13969   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13970   if (attr_high)
13971     {
13972       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13973       if (attr != nullptr)
13974         {
13975           CORE_ADDR low = attr->value_as_address ();
13976           CORE_ADDR high = attr_high->value_as_address ();
13977
13978           if (cu->header.version >= 4 && attr_high->form_is_constant ())
13979             high += low;
13980
13981           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
13982           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
13983           cu->get_builder ()->record_block_range (block, low, high - 1);
13984         }
13985     }
13986
13987   attr = dwarf2_attr (die, DW_AT_ranges, cu);
13988   if (attr != nullptr)
13989     {
13990       /* DW_AT_rnglists_base does not apply to DIEs from the DWO skeleton.
13991          We take advantage of the fact that DW_AT_ranges does not appear
13992          in DW_TAG_compile_unit of DWO files.  */
13993       int need_ranges_base = die->tag != DW_TAG_compile_unit;
13994
13995       /* The value of the DW_AT_ranges attribute is the offset of the
13996          address range list in the .debug_ranges section.  */
13997       unsigned long offset = (DW_UNSND (attr)
13998                               + (need_ranges_base ? cu->ranges_base : 0));
13999
14000       std::vector<blockrange> blockvec;
14001       dwarf2_ranges_process (offset, cu,
14002         [&] (CORE_ADDR start, CORE_ADDR end)
14003         {
14004           start += baseaddr;
14005           end += baseaddr;
14006           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14007           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14008           cu->get_builder ()->record_block_range (block, start, end - 1);
14009           blockvec.emplace_back (start, end);
14010         });
14011
14012       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14013     }
14014 }
14015
14016 /* Check whether the producer field indicates either of GCC < 4.6, or the
14017    Intel C/C++ compiler, and cache the result in CU.  */
14018
14019 static void
14020 check_producer (struct dwarf2_cu *cu)
14021 {
14022   int major, minor;
14023
14024   if (cu->producer == NULL)
14025     {
14026       /* For unknown compilers expect their behavior is DWARF version
14027          compliant.
14028
14029          GCC started to support .debug_types sections by -gdwarf-4 since
14030          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14031          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14032          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14033          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14034     }
14035   else if (producer_is_gcc (cu->producer, &major, &minor))
14036     {
14037       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14038       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14039     }
14040   else if (producer_is_icc (cu->producer, &major, &minor))
14041     {
14042       cu->producer_is_icc = true;
14043       cu->producer_is_icc_lt_14 = major < 14;
14044     }
14045   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14046     cu->producer_is_codewarrior = true;
14047   else
14048     {
14049       /* For other non-GCC compilers, expect their behavior is DWARF version
14050          compliant.  */
14051     }
14052
14053   cu->checked_producer = true;
14054 }
14055
14056 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14057    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14058    during 4.6.0 experimental.  */
14059
14060 static bool
14061 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14062 {
14063   if (!cu->checked_producer)
14064     check_producer (cu);
14065
14066   return cu->producer_is_gxx_lt_4_6;
14067 }
14068
14069
14070 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14071    with incorrect is_stmt attributes.  */
14072
14073 static bool
14074 producer_is_codewarrior (struct dwarf2_cu *cu)
14075 {
14076   if (!cu->checked_producer)
14077     check_producer (cu);
14078
14079   return cu->producer_is_codewarrior;
14080 }
14081
14082 /* Return the default accessibility type if it is not overridden by
14083    DW_AT_accessibility.  */
14084
14085 static enum dwarf_access_attribute
14086 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14087 {
14088   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14089     {
14090       /* The default DWARF 2 accessibility for members is public, the default
14091          accessibility for inheritance is private.  */
14092
14093       if (die->tag != DW_TAG_inheritance)
14094         return DW_ACCESS_public;
14095       else
14096         return DW_ACCESS_private;
14097     }
14098   else
14099     {
14100       /* DWARF 3+ defines the default accessibility a different way.  The same
14101          rules apply now for DW_TAG_inheritance as for the members and it only
14102          depends on the container kind.  */
14103
14104       if (die->parent->tag == DW_TAG_class_type)
14105         return DW_ACCESS_private;
14106       else
14107         return DW_ACCESS_public;
14108     }
14109 }
14110
14111 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14112    offset.  If the attribute was not found return 0, otherwise return
14113    1.  If it was found but could not properly be handled, set *OFFSET
14114    to 0.  */
14115
14116 static int
14117 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14118                              LONGEST *offset)
14119 {
14120   struct attribute *attr;
14121
14122   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14123   if (attr != NULL)
14124     {
14125       *offset = 0;
14126
14127       /* Note that we do not check for a section offset first here.
14128          This is because DW_AT_data_member_location is new in DWARF 4,
14129          so if we see it, we can assume that a constant form is really
14130          a constant and not a section offset.  */
14131       if (attr->form_is_constant ())
14132         *offset = dwarf2_get_attr_constant_value (attr, 0);
14133       else if (attr->form_is_section_offset ())
14134         dwarf2_complex_location_expr_complaint ();
14135       else if (attr->form_is_block ())
14136         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14137       else
14138         dwarf2_complex_location_expr_complaint ();
14139
14140       return 1;
14141     }
14142
14143   return 0;
14144 }
14145
14146 /* Add an aggregate field to the field list.  */
14147
14148 static void
14149 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14150                   struct dwarf2_cu *cu)
14151 {
14152   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14153   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14154   struct nextfield *new_field;
14155   struct attribute *attr;
14156   struct field *fp;
14157   const char *fieldname = "";
14158
14159   if (die->tag == DW_TAG_inheritance)
14160     {
14161       fip->baseclasses.emplace_back ();
14162       new_field = &fip->baseclasses.back ();
14163     }
14164   else
14165     {
14166       fip->fields.emplace_back ();
14167       new_field = &fip->fields.back ();
14168     }
14169
14170   fip->nfields++;
14171
14172   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14173   if (attr != nullptr)
14174     new_field->accessibility = DW_UNSND (attr);
14175   else
14176     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14177   if (new_field->accessibility != DW_ACCESS_public)
14178     fip->non_public_fields = 1;
14179
14180   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14181   if (attr != nullptr)
14182     new_field->virtuality = DW_UNSND (attr);
14183   else
14184     new_field->virtuality = DW_VIRTUALITY_none;
14185
14186   fp = &new_field->field;
14187
14188   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14189     {
14190       LONGEST offset;
14191
14192       /* Data member other than a C++ static data member.  */
14193
14194       /* Get type of field.  */
14195       fp->type = die_type (die, cu);
14196
14197       SET_FIELD_BITPOS (*fp, 0);
14198
14199       /* Get bit size of field (zero if none).  */
14200       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14201       if (attr != nullptr)
14202         {
14203           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14204         }
14205       else
14206         {
14207           FIELD_BITSIZE (*fp) = 0;
14208         }
14209
14210       /* Get bit offset of field.  */
14211       if (handle_data_member_location (die, cu, &offset))
14212         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14213       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14214       if (attr != nullptr)
14215         {
14216           if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
14217             {
14218               /* For big endian bits, the DW_AT_bit_offset gives the
14219                  additional bit offset from the MSB of the containing
14220                  anonymous object to the MSB of the field.  We don't
14221                  have to do anything special since we don't need to
14222                  know the size of the anonymous object.  */
14223               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14224             }
14225           else
14226             {
14227               /* For little endian bits, compute the bit offset to the
14228                  MSB of the anonymous object, subtract off the number of
14229                  bits from the MSB of the field to the MSB of the
14230                  object, and then subtract off the number of bits of
14231                  the field itself.  The result is the bit offset of
14232                  the LSB of the field.  */
14233               int anonymous_size;
14234               int bit_offset = DW_UNSND (attr);
14235
14236               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14237               if (attr != nullptr)
14238                 {
14239                   /* The size of the anonymous object containing
14240                      the bit field is explicit, so use the
14241                      indicated size (in bytes).  */
14242                   anonymous_size = DW_UNSND (attr);
14243                 }
14244               else
14245                 {
14246                   /* The size of the anonymous object containing
14247                      the bit field must be inferred from the type
14248                      attribute of the data member containing the
14249                      bit field.  */
14250                   anonymous_size = TYPE_LENGTH (fp->type);
14251                 }
14252               SET_FIELD_BITPOS (*fp,
14253                                 (FIELD_BITPOS (*fp)
14254                                  + anonymous_size * bits_per_byte
14255                                  - bit_offset - FIELD_BITSIZE (*fp)));
14256             }
14257         }
14258       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14259       if (attr != NULL)
14260         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14261                                 + dwarf2_get_attr_constant_value (attr, 0)));
14262
14263       /* Get name of field.  */
14264       fieldname = dwarf2_name (die, cu);
14265       if (fieldname == NULL)
14266         fieldname = "";
14267
14268       /* The name is already allocated along with this objfile, so we don't
14269          need to duplicate it for the type.  */
14270       fp->name = fieldname;
14271
14272       /* Change accessibility for artificial fields (e.g. virtual table
14273          pointer or virtual base class pointer) to private.  */
14274       if (dwarf2_attr (die, DW_AT_artificial, cu))
14275         {
14276           FIELD_ARTIFICIAL (*fp) = 1;
14277           new_field->accessibility = DW_ACCESS_private;
14278           fip->non_public_fields = 1;
14279         }
14280     }
14281   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
14282     {
14283       /* C++ static member.  */
14284
14285       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
14286          is a declaration, but all versions of G++ as of this writing
14287          (so through at least 3.2.1) incorrectly generate
14288          DW_TAG_variable tags.  */
14289
14290       const char *physname;
14291
14292       /* Get name of field.  */
14293       fieldname = dwarf2_name (die, cu);
14294       if (fieldname == NULL)
14295         return;
14296
14297       attr = dwarf2_attr (die, DW_AT_const_value, cu);
14298       if (attr
14299           /* Only create a symbol if this is an external value.
14300              new_symbol checks this and puts the value in the global symbol
14301              table, which we want.  If it is not external, new_symbol
14302              will try to put the value in cu->list_in_scope which is wrong.  */
14303           && dwarf2_flag_true_p (die, DW_AT_external, cu))
14304         {
14305           /* A static const member, not much different than an enum as far as
14306              we're concerned, except that we can support more types.  */
14307           new_symbol (die, NULL, cu);
14308         }
14309
14310       /* Get physical name.  */
14311       physname = dwarf2_physname (fieldname, die, cu);
14312
14313       /* The name is already allocated along with this objfile, so we don't
14314          need to duplicate it for the type.  */
14315       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
14316       FIELD_TYPE (*fp) = die_type (die, cu);
14317       FIELD_NAME (*fp) = fieldname;
14318     }
14319   else if (die->tag == DW_TAG_inheritance)
14320     {
14321       LONGEST offset;
14322
14323       /* C++ base class field.  */
14324       if (handle_data_member_location (die, cu, &offset))
14325         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14326       FIELD_BITSIZE (*fp) = 0;
14327       FIELD_TYPE (*fp) = die_type (die, cu);
14328       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
14329     }
14330   else if (die->tag == DW_TAG_variant_part)
14331     {
14332       /* process_structure_scope will treat this DIE as a union.  */
14333       process_structure_scope (die, cu);
14334
14335       /* The variant part is relative to the start of the enclosing
14336          structure.  */
14337       SET_FIELD_BITPOS (*fp, 0);
14338       fp->type = get_die_type (die, cu);
14339       fp->artificial = 1;
14340       fp->name = "<<variant>>";
14341
14342       /* Normally a DW_TAG_variant_part won't have a size, but our
14343          representation requires one, so set it to the maximum of the
14344          child sizes, being sure to account for the offset at which
14345          each child is seen.  */
14346       if (TYPE_LENGTH (fp->type) == 0)
14347         {
14348           unsigned max = 0;
14349           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
14350             {
14351               unsigned len = ((TYPE_FIELD_BITPOS (fp->type, i) + 7) / 8
14352                               + TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)));
14353               if (len > max)
14354                 max = len;
14355             }
14356           TYPE_LENGTH (fp->type) = max;
14357         }
14358     }
14359   else
14360     gdb_assert_not_reached ("missing case in dwarf2_add_field");
14361 }
14362
14363 /* Can the type given by DIE define another type?  */
14364
14365 static bool
14366 type_can_define_types (const struct die_info *die)
14367 {
14368   switch (die->tag)
14369     {
14370     case DW_TAG_typedef:
14371     case DW_TAG_class_type:
14372     case DW_TAG_structure_type:
14373     case DW_TAG_union_type:
14374     case DW_TAG_enumeration_type:
14375       return true;
14376
14377     default:
14378       return false;
14379     }
14380 }
14381
14382 /* Add a type definition defined in the scope of the FIP's class.  */
14383
14384 static void
14385 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
14386                       struct dwarf2_cu *cu)
14387 {
14388   struct decl_field fp;
14389   memset (&fp, 0, sizeof (fp));
14390
14391   gdb_assert (type_can_define_types (die));
14392
14393   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
14394   fp.name = dwarf2_name (die, cu);
14395   fp.type = read_type_die (die, cu);
14396
14397   /* Save accessibility.  */
14398   enum dwarf_access_attribute accessibility;
14399   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14400   if (attr != NULL)
14401     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14402   else
14403     accessibility = dwarf2_default_access_attribute (die, cu);
14404   switch (accessibility)
14405     {
14406     case DW_ACCESS_public:
14407       /* The assumed value if neither private nor protected.  */
14408       break;
14409     case DW_ACCESS_private:
14410       fp.is_private = 1;
14411       break;
14412     case DW_ACCESS_protected:
14413       fp.is_protected = 1;
14414       break;
14415     default:
14416       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
14417     }
14418
14419   if (die->tag == DW_TAG_typedef)
14420     fip->typedef_field_list.push_back (fp);
14421   else
14422     fip->nested_types_list.push_back (fp);
14423 }
14424
14425 /* Create the vector of fields, and attach it to the type.  */
14426
14427 static void
14428 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
14429                               struct dwarf2_cu *cu)
14430 {
14431   int nfields = fip->nfields;
14432
14433   /* Record the field count, allocate space for the array of fields,
14434      and create blank accessibility bitfields if necessary.  */
14435   TYPE_NFIELDS (type) = nfields;
14436   TYPE_FIELDS (type) = (struct field *)
14437     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
14438
14439   if (fip->non_public_fields && cu->language != language_ada)
14440     {
14441       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14442
14443       TYPE_FIELD_PRIVATE_BITS (type) =
14444         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14445       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
14446
14447       TYPE_FIELD_PROTECTED_BITS (type) =
14448         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14449       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
14450
14451       TYPE_FIELD_IGNORE_BITS (type) =
14452         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14453       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
14454     }
14455
14456   /* If the type has baseclasses, allocate and clear a bit vector for
14457      TYPE_FIELD_VIRTUAL_BITS.  */
14458   if (!fip->baseclasses.empty () && cu->language != language_ada)
14459     {
14460       int num_bytes = B_BYTES (fip->baseclasses.size ());
14461       unsigned char *pointer;
14462
14463       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14464       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
14465       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
14466       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
14467       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
14468     }
14469
14470   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
14471     {
14472       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
14473
14474       for (int index = 0; index < nfields; ++index)
14475         {
14476           struct nextfield &field = fip->fields[index];
14477
14478           if (field.variant.is_discriminant)
14479             di->discriminant_index = index;
14480           else if (field.variant.default_branch)
14481             di->default_index = index;
14482           else
14483             di->discriminants[index] = field.variant.discriminant_value;
14484         }
14485     }
14486
14487   /* Copy the saved-up fields into the field vector.  */
14488   for (int i = 0; i < nfields; ++i)
14489     {
14490       struct nextfield &field
14491         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
14492            : fip->fields[i - fip->baseclasses.size ()]);
14493
14494       TYPE_FIELD (type, i) = field.field;
14495       switch (field.accessibility)
14496         {
14497         case DW_ACCESS_private:
14498           if (cu->language != language_ada)
14499             SET_TYPE_FIELD_PRIVATE (type, i);
14500           break;
14501
14502         case DW_ACCESS_protected:
14503           if (cu->language != language_ada)
14504             SET_TYPE_FIELD_PROTECTED (type, i);
14505           break;
14506
14507         case DW_ACCESS_public:
14508           break;
14509
14510         default:
14511           /* Unknown accessibility.  Complain and treat it as public.  */
14512           {
14513             complaint (_("unsupported accessibility %d"),
14514                        field.accessibility);
14515           }
14516           break;
14517         }
14518       if (i < fip->baseclasses.size ())
14519         {
14520           switch (field.virtuality)
14521             {
14522             case DW_VIRTUALITY_virtual:
14523             case DW_VIRTUALITY_pure_virtual:
14524               if (cu->language == language_ada)
14525                 error (_("unexpected virtuality in component of Ada type"));
14526               SET_TYPE_FIELD_VIRTUAL (type, i);
14527               break;
14528             }
14529         }
14530     }
14531 }
14532
14533 /* Return true if this member function is a constructor, false
14534    otherwise.  */
14535
14536 static int
14537 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
14538 {
14539   const char *fieldname;
14540   const char *type_name;
14541   int len;
14542
14543   if (die->parent == NULL)
14544     return 0;
14545
14546   if (die->parent->tag != DW_TAG_structure_type
14547       && die->parent->tag != DW_TAG_union_type
14548       && die->parent->tag != DW_TAG_class_type)
14549     return 0;
14550
14551   fieldname = dwarf2_name (die, cu);
14552   type_name = dwarf2_name (die->parent, cu);
14553   if (fieldname == NULL || type_name == NULL)
14554     return 0;
14555
14556   len = strlen (fieldname);
14557   return (strncmp (fieldname, type_name, len) == 0
14558           && (type_name[len] == '\0' || type_name[len] == '<'));
14559 }
14560
14561 /* Check if the given VALUE is a recognized enum
14562    dwarf_defaulted_attribute constant according to DWARF5 spec,
14563    Table 7.24.  */
14564
14565 static bool
14566 is_valid_DW_AT_defaulted (ULONGEST value)
14567 {
14568   switch (value)
14569     {
14570     case DW_DEFAULTED_no:
14571     case DW_DEFAULTED_in_class:
14572     case DW_DEFAULTED_out_of_class:
14573       return true;
14574     }
14575
14576   complaint (_("unrecognized DW_AT_defaulted value (%s)"), pulongest (value));
14577   return false;
14578 }
14579
14580 /* Add a member function to the proper fieldlist.  */
14581
14582 static void
14583 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
14584                       struct type *type, struct dwarf2_cu *cu)
14585 {
14586   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14587   struct attribute *attr;
14588   int i;
14589   struct fnfieldlist *flp = nullptr;
14590   struct fn_field *fnp;
14591   const char *fieldname;
14592   struct type *this_type;
14593   enum dwarf_access_attribute accessibility;
14594
14595   if (cu->language == language_ada)
14596     error (_("unexpected member function in Ada type"));
14597
14598   /* Get name of member function.  */
14599   fieldname = dwarf2_name (die, cu);
14600   if (fieldname == NULL)
14601     return;
14602
14603   /* Look up member function name in fieldlist.  */
14604   for (i = 0; i < fip->fnfieldlists.size (); i++)
14605     {
14606       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
14607         {
14608           flp = &fip->fnfieldlists[i];
14609           break;
14610         }
14611     }
14612
14613   /* Create a new fnfieldlist if necessary.  */
14614   if (flp == nullptr)
14615     {
14616       fip->fnfieldlists.emplace_back ();
14617       flp = &fip->fnfieldlists.back ();
14618       flp->name = fieldname;
14619       i = fip->fnfieldlists.size () - 1;
14620     }
14621
14622   /* Create a new member function field and add it to the vector of
14623      fnfieldlists.  */
14624   flp->fnfields.emplace_back ();
14625   fnp = &flp->fnfields.back ();
14626
14627   /* Delay processing of the physname until later.  */
14628   if (cu->language == language_cplus)
14629     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
14630                         die, cu);
14631   else
14632     {
14633       const char *physname = dwarf2_physname (fieldname, die, cu);
14634       fnp->physname = physname ? physname : "";
14635     }
14636
14637   fnp->type = alloc_type (objfile);
14638   this_type = read_type_die (die, cu);
14639   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
14640     {
14641       int nparams = TYPE_NFIELDS (this_type);
14642
14643       /* TYPE is the domain of this method, and THIS_TYPE is the type
14644            of the method itself (TYPE_CODE_METHOD).  */
14645       smash_to_method_type (fnp->type, type,
14646                             TYPE_TARGET_TYPE (this_type),
14647                             TYPE_FIELDS (this_type),
14648                             TYPE_NFIELDS (this_type),
14649                             TYPE_VARARGS (this_type));
14650
14651       /* Handle static member functions.
14652          Dwarf2 has no clean way to discern C++ static and non-static
14653          member functions.  G++ helps GDB by marking the first
14654          parameter for non-static member functions (which is the this
14655          pointer) as artificial.  We obtain this information from
14656          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
14657       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
14658         fnp->voffset = VOFFSET_STATIC;
14659     }
14660   else
14661     complaint (_("member function type missing for '%s'"),
14662                dwarf2_full_name (fieldname, die, cu));
14663
14664   /* Get fcontext from DW_AT_containing_type if present.  */
14665   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14666     fnp->fcontext = die_containing_type (die, cu);
14667
14668   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
14669      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
14670
14671   /* Get accessibility.  */
14672   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14673   if (attr != nullptr)
14674     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14675   else
14676     accessibility = dwarf2_default_access_attribute (die, cu);
14677   switch (accessibility)
14678     {
14679     case DW_ACCESS_private:
14680       fnp->is_private = 1;
14681       break;
14682     case DW_ACCESS_protected:
14683       fnp->is_protected = 1;
14684       break;
14685     }
14686
14687   /* Check for artificial methods.  */
14688   attr = dwarf2_attr (die, DW_AT_artificial, cu);
14689   if (attr && DW_UNSND (attr) != 0)
14690     fnp->is_artificial = 1;
14691
14692   /* Check for defaulted methods.  */
14693   attr = dwarf2_attr (die, DW_AT_defaulted, cu);
14694   if (attr != nullptr && is_valid_DW_AT_defaulted (DW_UNSND (attr)))
14695     fnp->defaulted = (enum dwarf_defaulted_attribute) DW_UNSND (attr);
14696
14697   /* Check for deleted methods.  */
14698   attr = dwarf2_attr (die, DW_AT_deleted, cu);
14699   if (attr != nullptr && DW_UNSND (attr) != 0)
14700     fnp->is_deleted = 1;
14701
14702   fnp->is_constructor = dwarf2_is_constructor (die, cu);
14703
14704   /* Get index in virtual function table if it is a virtual member
14705      function.  For older versions of GCC, this is an offset in the
14706      appropriate virtual table, as specified by DW_AT_containing_type.
14707      For everyone else, it is an expression to be evaluated relative
14708      to the object address.  */
14709
14710   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
14711   if (attr != nullptr)
14712     {
14713       if (attr->form_is_block () && DW_BLOCK (attr)->size > 0)
14714         {
14715           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
14716             {
14717               /* Old-style GCC.  */
14718               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
14719             }
14720           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
14721                    || (DW_BLOCK (attr)->size > 1
14722                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
14723                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
14724             {
14725               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
14726               if ((fnp->voffset % cu->header.addr_size) != 0)
14727                 dwarf2_complex_location_expr_complaint ();
14728               else
14729                 fnp->voffset /= cu->header.addr_size;
14730               fnp->voffset += 2;
14731             }
14732           else
14733             dwarf2_complex_location_expr_complaint ();
14734
14735           if (!fnp->fcontext)
14736             {
14737               /* If there is no `this' field and no DW_AT_containing_type,
14738                  we cannot actually find a base class context for the
14739                  vtable!  */
14740               if (TYPE_NFIELDS (this_type) == 0
14741                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
14742                 {
14743                   complaint (_("cannot determine context for virtual member "
14744                                "function \"%s\" (offset %s)"),
14745                              fieldname, sect_offset_str (die->sect_off));
14746                 }
14747               else
14748                 {
14749                   fnp->fcontext
14750                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
14751                 }
14752             }
14753         }
14754       else if (attr->form_is_section_offset ())
14755         {
14756           dwarf2_complex_location_expr_complaint ();
14757         }
14758       else
14759         {
14760           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
14761                                                  fieldname);
14762         }
14763     }
14764   else
14765     {
14766       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14767       if (attr && DW_UNSND (attr))
14768         {
14769           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
14770           complaint (_("Member function \"%s\" (offset %s) is virtual "
14771                        "but the vtable offset is not specified"),
14772                      fieldname, sect_offset_str (die->sect_off));
14773           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14774           TYPE_CPLUS_DYNAMIC (type) = 1;
14775         }
14776     }
14777 }
14778
14779 /* Create the vector of member function fields, and attach it to the type.  */
14780
14781 static void
14782 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
14783                                  struct dwarf2_cu *cu)
14784 {
14785   if (cu->language == language_ada)
14786     error (_("unexpected member functions in Ada type"));
14787
14788   ALLOCATE_CPLUS_STRUCT_TYPE (type);
14789   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
14790     TYPE_ALLOC (type,
14791                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
14792
14793   for (int i = 0; i < fip->fnfieldlists.size (); i++)
14794     {
14795       struct fnfieldlist &nf = fip->fnfieldlists[i];
14796       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
14797
14798       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
14799       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
14800       fn_flp->fn_fields = (struct fn_field *)
14801         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
14802
14803       for (int k = 0; k < nf.fnfields.size (); ++k)
14804         fn_flp->fn_fields[k] = nf.fnfields[k];
14805     }
14806
14807   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
14808 }
14809
14810 /* Returns non-zero if NAME is the name of a vtable member in CU's
14811    language, zero otherwise.  */
14812 static int
14813 is_vtable_name (const char *name, struct dwarf2_cu *cu)
14814 {
14815   static const char vptr[] = "_vptr";
14816
14817   /* Look for the C++ form of the vtable.  */
14818   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
14819     return 1;
14820
14821   return 0;
14822 }
14823
14824 /* GCC outputs unnamed structures that are really pointers to member
14825    functions, with the ABI-specified layout.  If TYPE describes
14826    such a structure, smash it into a member function type.
14827
14828    GCC shouldn't do this; it should just output pointer to member DIEs.
14829    This is GCC PR debug/28767.  */
14830
14831 static void
14832 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
14833 {
14834   struct type *pfn_type, *self_type, *new_type;
14835
14836   /* Check for a structure with no name and two children.  */
14837   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
14838     return;
14839
14840   /* Check for __pfn and __delta members.  */
14841   if (TYPE_FIELD_NAME (type, 0) == NULL
14842       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
14843       || TYPE_FIELD_NAME (type, 1) == NULL
14844       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
14845     return;
14846
14847   /* Find the type of the method.  */
14848   pfn_type = TYPE_FIELD_TYPE (type, 0);
14849   if (pfn_type == NULL
14850       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
14851       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
14852     return;
14853
14854   /* Look for the "this" argument.  */
14855   pfn_type = TYPE_TARGET_TYPE (pfn_type);
14856   if (TYPE_NFIELDS (pfn_type) == 0
14857       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
14858       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
14859     return;
14860
14861   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
14862   new_type = alloc_type (objfile);
14863   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
14864                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
14865                         TYPE_VARARGS (pfn_type));
14866   smash_to_methodptr_type (type, new_type);
14867 }
14868
14869 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
14870    appropriate error checking and issuing complaints if there is a
14871    problem.  */
14872
14873 static ULONGEST
14874 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
14875 {
14876   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
14877
14878   if (attr == nullptr)
14879     return 0;
14880
14881   if (!attr->form_is_constant ())
14882     {
14883       complaint (_("DW_AT_alignment must have constant form"
14884                    " - DIE at %s [in module %s]"),
14885                  sect_offset_str (die->sect_off),
14886                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
14887       return 0;
14888     }
14889
14890   ULONGEST align;
14891   if (attr->form == DW_FORM_sdata)
14892     {
14893       LONGEST val = DW_SND (attr);
14894       if (val < 0)
14895         {
14896           complaint (_("DW_AT_alignment value must not be negative"
14897                        " - DIE at %s [in module %s]"),
14898                      sect_offset_str (die->sect_off),
14899                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
14900           return 0;
14901         }
14902       align = val;
14903     }
14904   else
14905     align = DW_UNSND (attr);
14906
14907   if (align == 0)
14908     {
14909       complaint (_("DW_AT_alignment value must not be zero"
14910                    " - DIE at %s [in module %s]"),
14911                  sect_offset_str (die->sect_off),
14912                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
14913       return 0;
14914     }
14915   if ((align & (align - 1)) != 0)
14916     {
14917       complaint (_("DW_AT_alignment value must be a power of 2"
14918                    " - DIE at %s [in module %s]"),
14919                  sect_offset_str (die->sect_off),
14920                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
14921       return 0;
14922     }
14923
14924   return align;
14925 }
14926
14927 /* If the DIE has a DW_AT_alignment attribute, use its value to set
14928    the alignment for TYPE.  */
14929
14930 static void
14931 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
14932                      struct type *type)
14933 {
14934   if (!set_type_align (type, get_alignment (cu, die)))
14935     complaint (_("DW_AT_alignment value too large"
14936                  " - DIE at %s [in module %s]"),
14937                sect_offset_str (die->sect_off),
14938                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
14939 }
14940
14941 /* Check if the given VALUE is a valid enum dwarf_calling_convention
14942    constant for a type, according to DWARF5 spec, Table 5.5.  */
14943
14944 static bool
14945 is_valid_DW_AT_calling_convention_for_type (ULONGEST value)
14946 {
14947   switch (value)
14948     {
14949     case DW_CC_normal:
14950     case DW_CC_pass_by_reference:
14951     case DW_CC_pass_by_value:
14952       return true;
14953
14954     default:
14955       complaint (_("unrecognized DW_AT_calling_convention value "
14956                    "(%s) for a type"), pulongest (value));
14957       return false;
14958     }
14959 }
14960
14961 /* Check if the given VALUE is a valid enum dwarf_calling_convention
14962    constant for a subroutine, according to DWARF5 spec, Table 3.3, and
14963    also according to GNU-specific values (see include/dwarf2.h).  */
14964
14965 static bool
14966 is_valid_DW_AT_calling_convention_for_subroutine (ULONGEST value)
14967 {
14968   switch (value)
14969     {
14970     case DW_CC_normal:
14971     case DW_CC_program:
14972     case DW_CC_nocall:
14973       return true;
14974
14975     case DW_CC_GNU_renesas_sh:
14976     case DW_CC_GNU_borland_fastcall_i386:
14977     case DW_CC_GDB_IBM_OpenCL:
14978       return true;
14979
14980     default:
14981       complaint (_("unrecognized DW_AT_calling_convention value "
14982                    "(%s) for a subroutine"), pulongest (value));
14983       return false;
14984     }
14985 }
14986
14987 /* Called when we find the DIE that starts a structure or union scope
14988    (definition) to create a type for the structure or union.  Fill in
14989    the type's name and general properties; the members will not be
14990    processed until process_structure_scope.  A symbol table entry for
14991    the type will also not be done until process_structure_scope (assuming
14992    the type has a name).
14993
14994    NOTE: we need to call these functions regardless of whether or not the
14995    DIE has a DW_AT_name attribute, since it might be an anonymous
14996    structure or union.  This gets the type entered into our set of
14997    user defined types.  */
14998
14999 static struct type *
15000 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15001 {
15002   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15003   struct type *type;
15004   struct attribute *attr;
15005   const char *name;
15006
15007   /* If the definition of this type lives in .debug_types, read that type.
15008      Don't follow DW_AT_specification though, that will take us back up
15009      the chain and we want to go down.  */
15010   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15011   if (attr != nullptr)
15012     {
15013       type = get_DW_AT_signature_type (die, attr, cu);
15014
15015       /* The type's CU may not be the same as CU.
15016          Ensure TYPE is recorded with CU in die_type_hash.  */
15017       return set_die_type (die, type, cu);
15018     }
15019
15020   type = alloc_type (objfile);
15021   INIT_CPLUS_SPECIFIC (type);
15022
15023   name = dwarf2_name (die, cu);
15024   if (name != NULL)
15025     {
15026       if (cu->language == language_cplus
15027           || cu->language == language_d
15028           || cu->language == language_rust)
15029         {
15030           const char *full_name = dwarf2_full_name (name, die, cu);
15031
15032           /* dwarf2_full_name might have already finished building the DIE's
15033              type.  If so, there is no need to continue.  */
15034           if (get_die_type (die, cu) != NULL)
15035             return get_die_type (die, cu);
15036
15037           TYPE_NAME (type) = full_name;
15038         }
15039       else
15040         {
15041           /* The name is already allocated along with this objfile, so
15042              we don't need to duplicate it for the type.  */
15043           TYPE_NAME (type) = name;
15044         }
15045     }
15046
15047   if (die->tag == DW_TAG_structure_type)
15048     {
15049       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15050     }
15051   else if (die->tag == DW_TAG_union_type)
15052     {
15053       TYPE_CODE (type) = TYPE_CODE_UNION;
15054     }
15055   else if (die->tag == DW_TAG_variant_part)
15056     {
15057       TYPE_CODE (type) = TYPE_CODE_UNION;
15058       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15059     }
15060   else
15061     {
15062       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15063     }
15064
15065   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15066     TYPE_DECLARED_CLASS (type) = 1;
15067
15068   /* Store the calling convention in the type if it's available in
15069      the die.  Otherwise the calling convention remains set to
15070      the default value DW_CC_normal.  */
15071   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15072   if (attr != nullptr
15073       && is_valid_DW_AT_calling_convention_for_type (DW_UNSND (attr)))
15074     {
15075       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15076       TYPE_CPLUS_CALLING_CONVENTION (type)
15077         = (enum dwarf_calling_convention) (DW_UNSND (attr));
15078     }
15079
15080   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15081   if (attr != nullptr)
15082     {
15083       if (attr->form_is_constant ())
15084         TYPE_LENGTH (type) = DW_UNSND (attr);
15085       else
15086         {
15087           /* For the moment, dynamic type sizes are not supported
15088              by GDB's struct type.  The actual size is determined
15089              on-demand when resolving the type of a given object,
15090              so set the type's length to zero for now.  Otherwise,
15091              we record an expression as the length, and that expression
15092              could lead to a very large value, which could eventually
15093              lead to us trying to allocate that much memory when creating
15094              a value of that type.  */
15095           TYPE_LENGTH (type) = 0;
15096         }
15097     }
15098   else
15099     {
15100       TYPE_LENGTH (type) = 0;
15101     }
15102
15103   maybe_set_alignment (cu, die, type);
15104
15105   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15106     {
15107       /* ICC<14 does not output the required DW_AT_declaration on
15108          incomplete types, but gives them a size of zero.  */
15109       TYPE_STUB (type) = 1;
15110     }
15111   else
15112     TYPE_STUB_SUPPORTED (type) = 1;
15113
15114   if (die_is_declaration (die, cu))
15115     TYPE_STUB (type) = 1;
15116   else if (attr == NULL && die->child == NULL
15117            && producer_is_realview (cu->producer))
15118     /* RealView does not output the required DW_AT_declaration
15119        on incomplete types.  */
15120     TYPE_STUB (type) = 1;
15121
15122   /* We need to add the type field to the die immediately so we don't
15123      infinitely recurse when dealing with pointers to the structure
15124      type within the structure itself.  */
15125   set_die_type (die, type, cu);
15126
15127   /* set_die_type should be already done.  */
15128   set_descriptive_type (type, die, cu);
15129
15130   return type;
15131 }
15132
15133 /* A helper for process_structure_scope that handles a single member
15134    DIE.  */
15135
15136 static void
15137 handle_struct_member_die (struct die_info *child_die, struct type *type,
15138                           struct field_info *fi,
15139                           std::vector<struct symbol *> *template_args,
15140                           struct dwarf2_cu *cu)
15141 {
15142   if (child_die->tag == DW_TAG_member
15143       || child_die->tag == DW_TAG_variable
15144       || child_die->tag == DW_TAG_variant_part)
15145     {
15146       /* NOTE: carlton/2002-11-05: A C++ static data member
15147          should be a DW_TAG_member that is a declaration, but
15148          all versions of G++ as of this writing (so through at
15149          least 3.2.1) incorrectly generate DW_TAG_variable
15150          tags for them instead.  */
15151       dwarf2_add_field (fi, child_die, cu);
15152     }
15153   else if (child_die->tag == DW_TAG_subprogram)
15154     {
15155       /* Rust doesn't have member functions in the C++ sense.
15156          However, it does emit ordinary functions as children
15157          of a struct DIE.  */
15158       if (cu->language == language_rust)
15159         read_func_scope (child_die, cu);
15160       else
15161         {
15162           /* C++ member function.  */
15163           dwarf2_add_member_fn (fi, child_die, type, cu);
15164         }
15165     }
15166   else if (child_die->tag == DW_TAG_inheritance)
15167     {
15168       /* C++ base class field.  */
15169       dwarf2_add_field (fi, child_die, cu);
15170     }
15171   else if (type_can_define_types (child_die))
15172     dwarf2_add_type_defn (fi, child_die, cu);
15173   else if (child_die->tag == DW_TAG_template_type_param
15174            || child_die->tag == DW_TAG_template_value_param)
15175     {
15176       struct symbol *arg = new_symbol (child_die, NULL, cu);
15177
15178       if (arg != NULL)
15179         template_args->push_back (arg);
15180     }
15181   else if (child_die->tag == DW_TAG_variant)
15182     {
15183       /* In a variant we want to get the discriminant and also add a
15184          field for our sole member child.  */
15185       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15186
15187       for (die_info *variant_child = child_die->child;
15188            variant_child != NULL;
15189            variant_child = sibling_die (variant_child))
15190         {
15191           if (variant_child->tag == DW_TAG_member)
15192             {
15193               handle_struct_member_die (variant_child, type, fi,
15194                                         template_args, cu);
15195               /* Only handle the one.  */
15196               break;
15197             }
15198         }
15199
15200       /* We don't handle this but we might as well report it if we see
15201          it.  */
15202       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15203           complaint (_("DW_AT_discr_list is not supported yet"
15204                        " - DIE at %s [in module %s]"),
15205                      sect_offset_str (child_die->sect_off),
15206                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15207
15208       /* The first field was just added, so we can stash the
15209          discriminant there.  */
15210       gdb_assert (!fi->fields.empty ());
15211       if (discr == NULL)
15212         fi->fields.back ().variant.default_branch = true;
15213       else
15214         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15215     }
15216 }
15217
15218 /* Finish creating a structure or union type, including filling in
15219    its members and creating a symbol for it.  */
15220
15221 static void
15222 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15223 {
15224   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15225   struct die_info *child_die;
15226   struct type *type;
15227
15228   type = get_die_type (die, cu);
15229   if (type == NULL)
15230     type = read_structure_type (die, cu);
15231
15232   /* When reading a DW_TAG_variant_part, we need to notice when we
15233      read the discriminant member, so we can record it later in the
15234      discriminant_info.  */
15235   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15236   sect_offset discr_offset {};
15237   bool has_template_parameters = false;
15238
15239   if (is_variant_part)
15240     {
15241       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15242       if (discr == NULL)
15243         {
15244           /* Maybe it's a univariant form, an extension we support.
15245              In this case arrange not to check the offset.  */
15246           is_variant_part = false;
15247         }
15248       else if (discr->form_is_ref ())
15249         {
15250           struct dwarf2_cu *target_cu = cu;
15251           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15252
15253           discr_offset = target_die->sect_off;
15254         }
15255       else
15256         {
15257           complaint (_("DW_AT_discr does not have DIE reference form"
15258                        " - DIE at %s [in module %s]"),
15259                      sect_offset_str (die->sect_off),
15260                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15261           is_variant_part = false;
15262         }
15263     }
15264
15265   if (die->child != NULL && ! die_is_declaration (die, cu))
15266     {
15267       struct field_info fi;
15268       std::vector<struct symbol *> template_args;
15269
15270       child_die = die->child;
15271
15272       while (child_die && child_die->tag)
15273         {
15274           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15275
15276           if (is_variant_part && discr_offset == child_die->sect_off)
15277             fi.fields.back ().variant.is_discriminant = true;
15278
15279           child_die = sibling_die (child_die);
15280         }
15281
15282       /* Attach template arguments to type.  */
15283       if (!template_args.empty ())
15284         {
15285           has_template_parameters = true;
15286           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15287           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15288           TYPE_TEMPLATE_ARGUMENTS (type)
15289             = XOBNEWVEC (&objfile->objfile_obstack,
15290                          struct symbol *,
15291                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15292           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15293                   template_args.data (),
15294                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15295                    * sizeof (struct symbol *)));
15296         }
15297
15298       /* Attach fields and member functions to the type.  */
15299       if (fi.nfields)
15300         dwarf2_attach_fields_to_type (&fi, type, cu);
15301       if (!fi.fnfieldlists.empty ())
15302         {
15303           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15304
15305           /* Get the type which refers to the base class (possibly this
15306              class itself) which contains the vtable pointer for the current
15307              class from the DW_AT_containing_type attribute.  This use of
15308              DW_AT_containing_type is a GNU extension.  */
15309
15310           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15311             {
15312               struct type *t = die_containing_type (die, cu);
15313
15314               set_type_vptr_basetype (type, t);
15315               if (type == t)
15316                 {
15317                   int i;
15318
15319                   /* Our own class provides vtbl ptr.  */
15320                   for (i = TYPE_NFIELDS (t) - 1;
15321                        i >= TYPE_N_BASECLASSES (t);
15322                        --i)
15323                     {
15324                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15325
15326                       if (is_vtable_name (fieldname, cu))
15327                         {
15328                           set_type_vptr_fieldno (type, i);
15329                           break;
15330                         }
15331                     }
15332
15333                   /* Complain if virtual function table field not found.  */
15334                   if (i < TYPE_N_BASECLASSES (t))
15335                     complaint (_("virtual function table pointer "
15336                                  "not found when defining class '%s'"),
15337                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15338                 }
15339               else
15340                 {
15341                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15342                 }
15343             }
15344           else if (cu->producer
15345                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15346             {
15347               /* The IBM XLC compiler does not provide direct indication
15348                  of the containing type, but the vtable pointer is
15349                  always named __vfp.  */
15350
15351               int i;
15352
15353               for (i = TYPE_NFIELDS (type) - 1;
15354                    i >= TYPE_N_BASECLASSES (type);
15355                    --i)
15356                 {
15357                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15358                     {
15359                       set_type_vptr_fieldno (type, i);
15360                       set_type_vptr_basetype (type, type);
15361                       break;
15362                     }
15363                 }
15364             }
15365         }
15366
15367       /* Copy fi.typedef_field_list linked list elements content into the
15368          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15369       if (!fi.typedef_field_list.empty ())
15370         {
15371           int count = fi.typedef_field_list.size ();
15372
15373           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15374           TYPE_TYPEDEF_FIELD_ARRAY (type)
15375             = ((struct decl_field *)
15376                TYPE_ALLOC (type,
15377                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
15378           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
15379
15380           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
15381             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
15382         }
15383
15384       /* Copy fi.nested_types_list linked list elements content into the
15385          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15386       if (!fi.nested_types_list.empty () && cu->language != language_ada)
15387         {
15388           int count = fi.nested_types_list.size ();
15389
15390           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15391           TYPE_NESTED_TYPES_ARRAY (type)
15392             = ((struct decl_field *)
15393                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
15394           TYPE_NESTED_TYPES_COUNT (type) = count;
15395
15396           for (int i = 0; i < fi.nested_types_list.size (); ++i)
15397             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
15398         }
15399     }
15400
15401   quirk_gcc_member_function_pointer (type, objfile);
15402   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
15403     cu->rust_unions.push_back (type);
15404
15405   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
15406      snapshots) has been known to create a die giving a declaration
15407      for a class that has, as a child, a die giving a definition for a
15408      nested class.  So we have to process our children even if the
15409      current die is a declaration.  Normally, of course, a declaration
15410      won't have any children at all.  */
15411
15412   child_die = die->child;
15413
15414   while (child_die != NULL && child_die->tag)
15415     {
15416       if (child_die->tag == DW_TAG_member
15417           || child_die->tag == DW_TAG_variable
15418           || child_die->tag == DW_TAG_inheritance
15419           || child_die->tag == DW_TAG_template_value_param
15420           || child_die->tag == DW_TAG_template_type_param)
15421         {
15422           /* Do nothing.  */
15423         }
15424       else
15425         process_die (child_die, cu);
15426
15427       child_die = sibling_die (child_die);
15428     }
15429
15430   /* Do not consider external references.  According to the DWARF standard,
15431      these DIEs are identified by the fact that they have no byte_size
15432      attribute, and a declaration attribute.  */
15433   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
15434       || !die_is_declaration (die, cu))
15435     {
15436       struct symbol *sym = new_symbol (die, type, cu);
15437
15438       if (has_template_parameters)
15439         {
15440           struct symtab *symtab;
15441           if (sym != nullptr)
15442             symtab = symbol_symtab (sym);
15443           else if (cu->line_header != nullptr)
15444             {
15445               /* Any related symtab will do.  */
15446               symtab
15447                 = cu->line_header->file_names ()[0].symtab;
15448             }
15449           else
15450             {
15451               symtab = nullptr;
15452               complaint (_("could not find suitable "
15453                            "symtab for template parameter"
15454                            " - DIE at %s [in module %s]"),
15455                          sect_offset_str (die->sect_off),
15456                          objfile_name (objfile));
15457             }
15458
15459           if (symtab != nullptr)
15460             {
15461               /* Make sure that the symtab is set on the new symbols.
15462                  Even though they don't appear in this symtab directly,
15463                  other parts of gdb assume that symbols do, and this is
15464                  reasonably true.  */
15465               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
15466                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
15467             }
15468         }
15469     }
15470 }
15471
15472 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
15473    update TYPE using some information only available in DIE's children.  */
15474
15475 static void
15476 update_enumeration_type_from_children (struct die_info *die,
15477                                        struct type *type,
15478                                        struct dwarf2_cu *cu)
15479 {
15480   struct die_info *child_die;
15481   int unsigned_enum = 1;
15482   int flag_enum = 1;
15483
15484   auto_obstack obstack;
15485
15486   for (child_die = die->child;
15487        child_die != NULL && child_die->tag;
15488        child_die = sibling_die (child_die))
15489     {
15490       struct attribute *attr;
15491       LONGEST value;
15492       const gdb_byte *bytes;
15493       struct dwarf2_locexpr_baton *baton;
15494       const char *name;
15495
15496       if (child_die->tag != DW_TAG_enumerator)
15497         continue;
15498
15499       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
15500       if (attr == NULL)
15501         continue;
15502
15503       name = dwarf2_name (child_die, cu);
15504       if (name == NULL)
15505         name = "<anonymous enumerator>";
15506
15507       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
15508                                &value, &bytes, &baton);
15509       if (value < 0)
15510         {
15511           unsigned_enum = 0;
15512           flag_enum = 0;
15513         }
15514       else
15515         {
15516           if (count_one_bits_ll (value) >= 2)
15517             flag_enum = 0;
15518         }
15519
15520       /* If we already know that the enum type is neither unsigned, nor
15521          a flag type, no need to look at the rest of the enumerates.  */
15522       if (!unsigned_enum && !flag_enum)
15523         break;
15524     }
15525
15526   if (unsigned_enum)
15527     TYPE_UNSIGNED (type) = 1;
15528   if (flag_enum)
15529     TYPE_FLAG_ENUM (type) = 1;
15530 }
15531
15532 /* Given a DW_AT_enumeration_type die, set its type.  We do not
15533    complete the type's fields yet, or create any symbols.  */
15534
15535 static struct type *
15536 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
15537 {
15538   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15539   struct type *type;
15540   struct attribute *attr;
15541   const char *name;
15542
15543   /* If the definition of this type lives in .debug_types, read that type.
15544      Don't follow DW_AT_specification though, that will take us back up
15545      the chain and we want to go down.  */
15546   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15547   if (attr != nullptr)
15548     {
15549       type = get_DW_AT_signature_type (die, attr, cu);
15550
15551       /* The type's CU may not be the same as CU.
15552          Ensure TYPE is recorded with CU in die_type_hash.  */
15553       return set_die_type (die, type, cu);
15554     }
15555
15556   type = alloc_type (objfile);
15557
15558   TYPE_CODE (type) = TYPE_CODE_ENUM;
15559   name = dwarf2_full_name (NULL, die, cu);
15560   if (name != NULL)
15561     TYPE_NAME (type) = name;
15562
15563   attr = dwarf2_attr (die, DW_AT_type, cu);
15564   if (attr != NULL)
15565     {
15566       struct type *underlying_type = die_type (die, cu);
15567
15568       TYPE_TARGET_TYPE (type) = underlying_type;
15569     }
15570
15571   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15572   if (attr != nullptr)
15573     {
15574       TYPE_LENGTH (type) = DW_UNSND (attr);
15575     }
15576   else
15577     {
15578       TYPE_LENGTH (type) = 0;
15579     }
15580
15581   maybe_set_alignment (cu, die, type);
15582
15583   /* The enumeration DIE can be incomplete.  In Ada, any type can be
15584      declared as private in the package spec, and then defined only
15585      inside the package body.  Such types are known as Taft Amendment
15586      Types.  When another package uses such a type, an incomplete DIE
15587      may be generated by the compiler.  */
15588   if (die_is_declaration (die, cu))
15589     TYPE_STUB (type) = 1;
15590
15591   /* Finish the creation of this type by using the enum's children.
15592      We must call this even when the underlying type has been provided
15593      so that we can determine if we're looking at a "flag" enum.  */
15594   update_enumeration_type_from_children (die, type, cu);
15595
15596   /* If this type has an underlying type that is not a stub, then we
15597      may use its attributes.  We always use the "unsigned" attribute
15598      in this situation, because ordinarily we guess whether the type
15599      is unsigned -- but the guess can be wrong and the underlying type
15600      can tell us the reality.  However, we defer to a local size
15601      attribute if one exists, because this lets the compiler override
15602      the underlying type if needed.  */
15603   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
15604     {
15605       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
15606       if (TYPE_LENGTH (type) == 0)
15607         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
15608       if (TYPE_RAW_ALIGN (type) == 0
15609           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
15610         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
15611     }
15612
15613   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
15614
15615   return set_die_type (die, type, cu);
15616 }
15617
15618 /* Given a pointer to a die which begins an enumeration, process all
15619    the dies that define the members of the enumeration, and create the
15620    symbol for the enumeration type.
15621
15622    NOTE: We reverse the order of the element list.  */
15623
15624 static void
15625 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
15626 {
15627   struct type *this_type;
15628
15629   this_type = get_die_type (die, cu);
15630   if (this_type == NULL)
15631     this_type = read_enumeration_type (die, cu);
15632
15633   if (die->child != NULL)
15634     {
15635       struct die_info *child_die;
15636       struct symbol *sym;
15637       std::vector<struct field> fields;
15638       const char *name;
15639
15640       child_die = die->child;
15641       while (child_die && child_die->tag)
15642         {
15643           if (child_die->tag != DW_TAG_enumerator)
15644             {
15645               process_die (child_die, cu);
15646             }
15647           else
15648             {
15649               name = dwarf2_name (child_die, cu);
15650               if (name)
15651                 {
15652                   sym = new_symbol (child_die, this_type, cu);
15653
15654                   fields.emplace_back ();
15655                   struct field &field = fields.back ();
15656
15657                   FIELD_NAME (field) = sym->linkage_name ();
15658                   FIELD_TYPE (field) = NULL;
15659                   SET_FIELD_ENUMVAL (field, SYMBOL_VALUE (sym));
15660                   FIELD_BITSIZE (field) = 0;
15661                 }
15662             }
15663
15664           child_die = sibling_die (child_die);
15665         }
15666
15667       if (!fields.empty ())
15668         {
15669           TYPE_NFIELDS (this_type) = fields.size ();
15670           TYPE_FIELDS (this_type) = (struct field *)
15671             TYPE_ALLOC (this_type, sizeof (struct field) * fields.size ());
15672           memcpy (TYPE_FIELDS (this_type), fields.data (),
15673                   sizeof (struct field) * fields.size ());
15674         }
15675     }
15676
15677   /* If we are reading an enum from a .debug_types unit, and the enum
15678      is a declaration, and the enum is not the signatured type in the
15679      unit, then we do not want to add a symbol for it.  Adding a
15680      symbol would in some cases obscure the true definition of the
15681      enum, giving users an incomplete type when the definition is
15682      actually available.  Note that we do not want to do this for all
15683      enums which are just declarations, because C++0x allows forward
15684      enum declarations.  */
15685   if (cu->per_cu->is_debug_types
15686       && die_is_declaration (die, cu))
15687     {
15688       struct signatured_type *sig_type;
15689
15690       sig_type = (struct signatured_type *) cu->per_cu;
15691       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
15692       if (sig_type->type_offset_in_section != die->sect_off)
15693         return;
15694     }
15695
15696   new_symbol (die, this_type, cu);
15697 }
15698
15699 /* Extract all information from a DW_TAG_array_type DIE and put it in
15700    the DIE's type field.  For now, this only handles one dimensional
15701    arrays.  */
15702
15703 static struct type *
15704 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
15705 {
15706   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15707   struct die_info *child_die;
15708   struct type *type;
15709   struct type *element_type, *range_type, *index_type;
15710   struct attribute *attr;
15711   const char *name;
15712   struct dynamic_prop *byte_stride_prop = NULL;
15713   unsigned int bit_stride = 0;
15714
15715   element_type = die_type (die, cu);
15716
15717   /* The die_type call above may have already set the type for this DIE.  */
15718   type = get_die_type (die, cu);
15719   if (type)
15720     return type;
15721
15722   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
15723   if (attr != NULL)
15724     {
15725       int stride_ok;
15726       struct type *prop_type = cu->per_cu->addr_sized_int_type (false);
15727
15728       byte_stride_prop
15729         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
15730       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop,
15731                                         prop_type);
15732       if (!stride_ok)
15733         {
15734           complaint (_("unable to read array DW_AT_byte_stride "
15735                        " - DIE at %s [in module %s]"),
15736                      sect_offset_str (die->sect_off),
15737                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15738           /* Ignore this attribute.  We will likely not be able to print
15739              arrays of this type correctly, but there is little we can do
15740              to help if we cannot read the attribute's value.  */
15741           byte_stride_prop = NULL;
15742         }
15743     }
15744
15745   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
15746   if (attr != NULL)
15747     bit_stride = DW_UNSND (attr);
15748
15749   /* Irix 6.2 native cc creates array types without children for
15750      arrays with unspecified length.  */
15751   if (die->child == NULL)
15752     {
15753       index_type = objfile_type (objfile)->builtin_int;
15754       range_type = create_static_range_type (NULL, index_type, 0, -1);
15755       type = create_array_type_with_stride (NULL, element_type, range_type,
15756                                             byte_stride_prop, bit_stride);
15757       return set_die_type (die, type, cu);
15758     }
15759
15760   std::vector<struct type *> range_types;
15761   child_die = die->child;
15762   while (child_die && child_die->tag)
15763     {
15764       if (child_die->tag == DW_TAG_subrange_type)
15765         {
15766           struct type *child_type = read_type_die (child_die, cu);
15767
15768           if (child_type != NULL)
15769             {
15770               /* The range type was succesfully read.  Save it for the
15771                  array type creation.  */
15772               range_types.push_back (child_type);
15773             }
15774         }
15775       child_die = sibling_die (child_die);
15776     }
15777
15778   /* Dwarf2 dimensions are output from left to right, create the
15779      necessary array types in backwards order.  */
15780
15781   type = element_type;
15782
15783   if (read_array_order (die, cu) == DW_ORD_col_major)
15784     {
15785       int i = 0;
15786
15787       while (i < range_types.size ())
15788         type = create_array_type_with_stride (NULL, type, range_types[i++],
15789                                               byte_stride_prop, bit_stride);
15790     }
15791   else
15792     {
15793       size_t ndim = range_types.size ();
15794       while (ndim-- > 0)
15795         type = create_array_type_with_stride (NULL, type, range_types[ndim],
15796                                               byte_stride_prop, bit_stride);
15797     }
15798
15799   /* Understand Dwarf2 support for vector types (like they occur on
15800      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
15801      array type.  This is not part of the Dwarf2/3 standard yet, but a
15802      custom vendor extension.  The main difference between a regular
15803      array and the vector variant is that vectors are passed by value
15804      to functions.  */
15805   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
15806   if (attr != nullptr)
15807     make_vector_type (type);
15808
15809   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
15810      implementation may choose to implement triple vectors using this
15811      attribute.  */
15812   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15813   if (attr != nullptr)
15814     {
15815       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
15816         TYPE_LENGTH (type) = DW_UNSND (attr);
15817       else
15818         complaint (_("DW_AT_byte_size for array type smaller "
15819                      "than the total size of elements"));
15820     }
15821
15822   name = dwarf2_name (die, cu);
15823   if (name)
15824     TYPE_NAME (type) = name;
15825
15826   maybe_set_alignment (cu, die, type);
15827
15828   /* Install the type in the die.  */
15829   set_die_type (die, type, cu);
15830
15831   /* set_die_type should be already done.  */
15832   set_descriptive_type (type, die, cu);
15833
15834   return type;
15835 }
15836
15837 static enum dwarf_array_dim_ordering
15838 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
15839 {
15840   struct attribute *attr;
15841
15842   attr = dwarf2_attr (die, DW_AT_ordering, cu);
15843
15844   if (attr != nullptr)
15845     return (enum dwarf_array_dim_ordering) DW_SND (attr);
15846
15847   /* GNU F77 is a special case, as at 08/2004 array type info is the
15848      opposite order to the dwarf2 specification, but data is still
15849      laid out as per normal fortran.
15850
15851      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
15852      version checking.  */
15853
15854   if (cu->language == language_fortran
15855       && cu->producer && strstr (cu->producer, "GNU F77"))
15856     {
15857       return DW_ORD_row_major;
15858     }
15859
15860   switch (cu->language_defn->la_array_ordering)
15861     {
15862     case array_column_major:
15863       return DW_ORD_col_major;
15864     case array_row_major:
15865     default:
15866       return DW_ORD_row_major;
15867     };
15868 }
15869
15870 /* Extract all information from a DW_TAG_set_type DIE and put it in
15871    the DIE's type field.  */
15872
15873 static struct type *
15874 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
15875 {
15876   struct type *domain_type, *set_type;
15877   struct attribute *attr;
15878
15879   domain_type = die_type (die, cu);
15880
15881   /* The die_type call above may have already set the type for this DIE.  */
15882   set_type = get_die_type (die, cu);
15883   if (set_type)
15884     return set_type;
15885
15886   set_type = create_set_type (NULL, domain_type);
15887
15888   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15889   if (attr != nullptr)
15890     TYPE_LENGTH (set_type) = DW_UNSND (attr);
15891
15892   maybe_set_alignment (cu, die, set_type);
15893
15894   return set_die_type (die, set_type, cu);
15895 }
15896
15897 /* A helper for read_common_block that creates a locexpr baton.
15898    SYM is the symbol which we are marking as computed.
15899    COMMON_DIE is the DIE for the common block.
15900    COMMON_LOC is the location expression attribute for the common
15901    block itself.
15902    MEMBER_LOC is the location expression attribute for the particular
15903    member of the common block that we are processing.
15904    CU is the CU from which the above come.  */
15905
15906 static void
15907 mark_common_block_symbol_computed (struct symbol *sym,
15908                                    struct die_info *common_die,
15909                                    struct attribute *common_loc,
15910                                    struct attribute *member_loc,
15911                                    struct dwarf2_cu *cu)
15912 {
15913   struct dwarf2_per_objfile *dwarf2_per_objfile
15914     = cu->per_cu->dwarf2_per_objfile;
15915   struct objfile *objfile = dwarf2_per_objfile->objfile;
15916   struct dwarf2_locexpr_baton *baton;
15917   gdb_byte *ptr;
15918   unsigned int cu_off;
15919   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
15920   LONGEST offset = 0;
15921
15922   gdb_assert (common_loc && member_loc);
15923   gdb_assert (common_loc->form_is_block ());
15924   gdb_assert (member_loc->form_is_block ()
15925               || member_loc->form_is_constant ());
15926
15927   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
15928   baton->per_cu = cu->per_cu;
15929   gdb_assert (baton->per_cu);
15930
15931   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
15932
15933   if (member_loc->form_is_constant ())
15934     {
15935       offset = dwarf2_get_attr_constant_value (member_loc, 0);
15936       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
15937     }
15938   else
15939     baton->size += DW_BLOCK (member_loc)->size;
15940
15941   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
15942   baton->data = ptr;
15943
15944   *ptr++ = DW_OP_call4;
15945   cu_off = common_die->sect_off - cu->per_cu->sect_off;
15946   store_unsigned_integer (ptr, 4, byte_order, cu_off);
15947   ptr += 4;
15948
15949   if (member_loc->form_is_constant ())
15950     {
15951       *ptr++ = DW_OP_addr;
15952       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
15953       ptr += cu->header.addr_size;
15954     }
15955   else
15956     {
15957       /* We have to copy the data here, because DW_OP_call4 will only
15958          use a DW_AT_location attribute.  */
15959       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
15960       ptr += DW_BLOCK (member_loc)->size;
15961     }
15962
15963   *ptr++ = DW_OP_plus;
15964   gdb_assert (ptr - baton->data == baton->size);
15965
15966   SYMBOL_LOCATION_BATON (sym) = baton;
15967   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
15968 }
15969
15970 /* Create appropriate locally-scoped variables for all the
15971    DW_TAG_common_block entries.  Also create a struct common_block
15972    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
15973    is used to separate the common blocks name namespace from regular
15974    variable names.  */
15975
15976 static void
15977 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
15978 {
15979   struct attribute *attr;
15980
15981   attr = dwarf2_attr (die, DW_AT_location, cu);
15982   if (attr != nullptr)
15983     {
15984       /* Support the .debug_loc offsets.  */
15985       if (attr->form_is_block ())
15986         {
15987           /* Ok.  */
15988         }
15989       else if (attr->form_is_section_offset ())
15990         {
15991           dwarf2_complex_location_expr_complaint ();
15992           attr = NULL;
15993         }
15994       else
15995         {
15996           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15997                                                  "common block member");
15998           attr = NULL;
15999         }
16000     }
16001
16002   if (die->child != NULL)
16003     {
16004       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16005       struct die_info *child_die;
16006       size_t n_entries = 0, size;
16007       struct common_block *common_block;
16008       struct symbol *sym;
16009
16010       for (child_die = die->child;
16011            child_die && child_die->tag;
16012            child_die = sibling_die (child_die))
16013         ++n_entries;
16014
16015       size = (sizeof (struct common_block)
16016               + (n_entries - 1) * sizeof (struct symbol *));
16017       common_block
16018         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16019                                                  size);
16020       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16021       common_block->n_entries = 0;
16022
16023       for (child_die = die->child;
16024            child_die && child_die->tag;
16025            child_die = sibling_die (child_die))
16026         {
16027           /* Create the symbol in the DW_TAG_common_block block in the current
16028              symbol scope.  */
16029           sym = new_symbol (child_die, NULL, cu);
16030           if (sym != NULL)
16031             {
16032               struct attribute *member_loc;
16033
16034               common_block->contents[common_block->n_entries++] = sym;
16035
16036               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16037                                         cu);
16038               if (member_loc)
16039                 {
16040                   /* GDB has handled this for a long time, but it is
16041                      not specified by DWARF.  It seems to have been
16042                      emitted by gfortran at least as recently as:
16043                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16044                   complaint (_("Variable in common block has "
16045                                "DW_AT_data_member_location "
16046                                "- DIE at %s [in module %s]"),
16047                                sect_offset_str (child_die->sect_off),
16048                              objfile_name (objfile));
16049
16050                   if (member_loc->form_is_section_offset ())
16051                     dwarf2_complex_location_expr_complaint ();
16052                   else if (member_loc->form_is_constant ()
16053                            || member_loc->form_is_block ())
16054                     {
16055                       if (attr != nullptr)
16056                         mark_common_block_symbol_computed (sym, die, attr,
16057                                                            member_loc, cu);
16058                     }
16059                   else
16060                     dwarf2_complex_location_expr_complaint ();
16061                 }
16062             }
16063         }
16064
16065       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16066       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16067     }
16068 }
16069
16070 /* Create a type for a C++ namespace.  */
16071
16072 static struct type *
16073 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16074 {
16075   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16076   const char *previous_prefix, *name;
16077   int is_anonymous;
16078   struct type *type;
16079
16080   /* For extensions, reuse the type of the original namespace.  */
16081   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16082     {
16083       struct die_info *ext_die;
16084       struct dwarf2_cu *ext_cu = cu;
16085
16086       ext_die = dwarf2_extension (die, &ext_cu);
16087       type = read_type_die (ext_die, ext_cu);
16088
16089       /* EXT_CU may not be the same as CU.
16090          Ensure TYPE is recorded with CU in die_type_hash.  */
16091       return set_die_type (die, type, cu);
16092     }
16093
16094   name = namespace_name (die, &is_anonymous, cu);
16095
16096   /* Now build the name of the current namespace.  */
16097
16098   previous_prefix = determine_prefix (die, cu);
16099   if (previous_prefix[0] != '\0')
16100     name = typename_concat (&objfile->objfile_obstack,
16101                             previous_prefix, name, 0, cu);
16102
16103   /* Create the type.  */
16104   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16105
16106   return set_die_type (die, type, cu);
16107 }
16108
16109 /* Read a namespace scope.  */
16110
16111 static void
16112 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16113 {
16114   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16115   int is_anonymous;
16116
16117   /* Add a symbol associated to this if we haven't seen the namespace
16118      before.  Also, add a using directive if it's an anonymous
16119      namespace.  */
16120
16121   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16122     {
16123       struct type *type;
16124
16125       type = read_type_die (die, cu);
16126       new_symbol (die, type, cu);
16127
16128       namespace_name (die, &is_anonymous, cu);
16129       if (is_anonymous)
16130         {
16131           const char *previous_prefix = determine_prefix (die, cu);
16132
16133           std::vector<const char *> excludes;
16134           add_using_directive (using_directives (cu),
16135                                previous_prefix, TYPE_NAME (type), NULL,
16136                                NULL, excludes, 0, &objfile->objfile_obstack);
16137         }
16138     }
16139
16140   if (die->child != NULL)
16141     {
16142       struct die_info *child_die = die->child;
16143
16144       while (child_die && child_die->tag)
16145         {
16146           process_die (child_die, cu);
16147           child_die = sibling_die (child_die);
16148         }
16149     }
16150 }
16151
16152 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16153    imported module.  Still we need that type as local Fortran "use ... only"
16154    declaration imports depend on the created type in determine_prefix.  */
16155
16156 static struct type *
16157 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16158 {
16159   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16160   const char *module_name;
16161   struct type *type;
16162
16163   module_name = dwarf2_name (die, cu);
16164   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16165
16166   return set_die_type (die, type, cu);
16167 }
16168
16169 /* Read a Fortran module.  */
16170
16171 static void
16172 read_module (struct die_info *die, struct dwarf2_cu *cu)
16173 {
16174   struct die_info *child_die = die->child;
16175   struct type *type;
16176
16177   type = read_type_die (die, cu);
16178   new_symbol (die, type, cu);
16179
16180   while (child_die && child_die->tag)
16181     {
16182       process_die (child_die, cu);
16183       child_die = sibling_die (child_die);
16184     }
16185 }
16186
16187 /* Return the name of the namespace represented by DIE.  Set
16188    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16189    namespace.  */
16190
16191 static const char *
16192 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16193 {
16194   struct die_info *current_die;
16195   const char *name = NULL;
16196
16197   /* Loop through the extensions until we find a name.  */
16198
16199   for (current_die = die;
16200        current_die != NULL;
16201        current_die = dwarf2_extension (die, &cu))
16202     {
16203       /* We don't use dwarf2_name here so that we can detect the absence
16204          of a name -> anonymous namespace.  */
16205       name = dwarf2_string_attr (die, DW_AT_name, cu);
16206
16207       if (name != NULL)
16208         break;
16209     }
16210
16211   /* Is it an anonymous namespace?  */
16212
16213   *is_anonymous = (name == NULL);
16214   if (*is_anonymous)
16215     name = CP_ANONYMOUS_NAMESPACE_STR;
16216
16217   return name;
16218 }
16219
16220 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16221    the user defined type vector.  */
16222
16223 static struct type *
16224 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16225 {
16226   struct gdbarch *gdbarch
16227     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16228   struct comp_unit_head *cu_header = &cu->header;
16229   struct type *type;
16230   struct attribute *attr_byte_size;
16231   struct attribute *attr_address_class;
16232   int byte_size, addr_class;
16233   struct type *target_type;
16234
16235   target_type = die_type (die, cu);
16236
16237   /* The die_type call above may have already set the type for this DIE.  */
16238   type = get_die_type (die, cu);
16239   if (type)
16240     return type;
16241
16242   type = lookup_pointer_type (target_type);
16243
16244   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16245   if (attr_byte_size)
16246     byte_size = DW_UNSND (attr_byte_size);
16247   else
16248     byte_size = cu_header->addr_size;
16249
16250   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16251   if (attr_address_class)
16252     addr_class = DW_UNSND (attr_address_class);
16253   else
16254     addr_class = DW_ADDR_none;
16255
16256   ULONGEST alignment = get_alignment (cu, die);
16257
16258   /* If the pointer size, alignment, or address class is different
16259      than the default, create a type variant marked as such and set
16260      the length accordingly.  */
16261   if (TYPE_LENGTH (type) != byte_size
16262       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16263           && alignment != TYPE_RAW_ALIGN (type))
16264       || addr_class != DW_ADDR_none)
16265     {
16266       if (gdbarch_address_class_type_flags_p (gdbarch))
16267         {
16268           int type_flags;
16269
16270           type_flags = gdbarch_address_class_type_flags
16271                          (gdbarch, byte_size, addr_class);
16272           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16273                       == 0);
16274           type = make_type_with_address_space (type, type_flags);
16275         }
16276       else if (TYPE_LENGTH (type) != byte_size)
16277         {
16278           complaint (_("invalid pointer size %d"), byte_size);
16279         }
16280       else if (TYPE_RAW_ALIGN (type) != alignment)
16281         {
16282           complaint (_("Invalid DW_AT_alignment"
16283                        " - DIE at %s [in module %s]"),
16284                      sect_offset_str (die->sect_off),
16285                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16286         }
16287       else
16288         {
16289           /* Should we also complain about unhandled address classes?  */
16290         }
16291     }
16292
16293   TYPE_LENGTH (type) = byte_size;
16294   set_type_align (type, alignment);
16295   return set_die_type (die, type, cu);
16296 }
16297
16298 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16299    the user defined type vector.  */
16300
16301 static struct type *
16302 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16303 {
16304   struct type *type;
16305   struct type *to_type;
16306   struct type *domain;
16307
16308   to_type = die_type (die, cu);
16309   domain = die_containing_type (die, cu);
16310
16311   /* The calls above may have already set the type for this DIE.  */
16312   type = get_die_type (die, cu);
16313   if (type)
16314     return type;
16315
16316   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16317     type = lookup_methodptr_type (to_type);
16318   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16319     {
16320       struct type *new_type
16321         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16322
16323       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16324                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16325                             TYPE_VARARGS (to_type));
16326       type = lookup_methodptr_type (new_type);
16327     }
16328   else
16329     type = lookup_memberptr_type (to_type, domain);
16330
16331   return set_die_type (die, type, cu);
16332 }
16333
16334 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16335    the user defined type vector.  */
16336
16337 static struct type *
16338 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16339                           enum type_code refcode)
16340 {
16341   struct comp_unit_head *cu_header = &cu->header;
16342   struct type *type, *target_type;
16343   struct attribute *attr;
16344
16345   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16346
16347   target_type = die_type (die, cu);
16348
16349   /* The die_type call above may have already set the type for this DIE.  */
16350   type = get_die_type (die, cu);
16351   if (type)
16352     return type;
16353
16354   type = lookup_reference_type (target_type, refcode);
16355   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16356   if (attr != nullptr)
16357     {
16358       TYPE_LENGTH (type) = DW_UNSND (attr);
16359     }
16360   else
16361     {
16362       TYPE_LENGTH (type) = cu_header->addr_size;
16363     }
16364   maybe_set_alignment (cu, die, type);
16365   return set_die_type (die, type, cu);
16366 }
16367
16368 /* Add the given cv-qualifiers to the element type of the array.  GCC
16369    outputs DWARF type qualifiers that apply to an array, not the
16370    element type.  But GDB relies on the array element type to carry
16371    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16372    specification.  */
16373
16374 static struct type *
16375 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16376                    struct type *base_type, int cnst, int voltl)
16377 {
16378   struct type *el_type, *inner_array;
16379
16380   base_type = copy_type (base_type);
16381   inner_array = base_type;
16382
16383   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16384     {
16385       TYPE_TARGET_TYPE (inner_array) =
16386         copy_type (TYPE_TARGET_TYPE (inner_array));
16387       inner_array = TYPE_TARGET_TYPE (inner_array);
16388     }
16389
16390   el_type = TYPE_TARGET_TYPE (inner_array);
16391   cnst |= TYPE_CONST (el_type);
16392   voltl |= TYPE_VOLATILE (el_type);
16393   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16394
16395   return set_die_type (die, base_type, cu);
16396 }
16397
16398 static struct type *
16399 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16400 {
16401   struct type *base_type, *cv_type;
16402
16403   base_type = die_type (die, cu);
16404
16405   /* The die_type call above may have already set the type for this DIE.  */
16406   cv_type = get_die_type (die, cu);
16407   if (cv_type)
16408     return cv_type;
16409
16410   /* In case the const qualifier is applied to an array type, the element type
16411      is so qualified, not the array type (section 6.7.3 of C99).  */
16412   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16413     return add_array_cv_type (die, cu, base_type, 1, 0);
16414
16415   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16416   return set_die_type (die, cv_type, cu);
16417 }
16418
16419 static struct type *
16420 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16421 {
16422   struct type *base_type, *cv_type;
16423
16424   base_type = die_type (die, cu);
16425
16426   /* The die_type call above may have already set the type for this DIE.  */
16427   cv_type = get_die_type (die, cu);
16428   if (cv_type)
16429     return cv_type;
16430
16431   /* In case the volatile qualifier is applied to an array type, the
16432      element type is so qualified, not the array type (section 6.7.3
16433      of C99).  */
16434   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16435     return add_array_cv_type (die, cu, base_type, 0, 1);
16436
16437   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
16438   return set_die_type (die, cv_type, cu);
16439 }
16440
16441 /* Handle DW_TAG_restrict_type.  */
16442
16443 static struct type *
16444 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
16445 {
16446   struct type *base_type, *cv_type;
16447
16448   base_type = die_type (die, cu);
16449
16450   /* The die_type call above may have already set the type for this DIE.  */
16451   cv_type = get_die_type (die, cu);
16452   if (cv_type)
16453     return cv_type;
16454
16455   cv_type = make_restrict_type (base_type);
16456   return set_die_type (die, cv_type, cu);
16457 }
16458
16459 /* Handle DW_TAG_atomic_type.  */
16460
16461 static struct type *
16462 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
16463 {
16464   struct type *base_type, *cv_type;
16465
16466   base_type = die_type (die, cu);
16467
16468   /* The die_type call above may have already set the type for this DIE.  */
16469   cv_type = get_die_type (die, cu);
16470   if (cv_type)
16471     return cv_type;
16472
16473   cv_type = make_atomic_type (base_type);
16474   return set_die_type (die, cv_type, cu);
16475 }
16476
16477 /* Extract all information from a DW_TAG_string_type DIE and add to
16478    the user defined type vector.  It isn't really a user defined type,
16479    but it behaves like one, with other DIE's using an AT_user_def_type
16480    attribute to reference it.  */
16481
16482 static struct type *
16483 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
16484 {
16485   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16486   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16487   struct type *type, *range_type, *index_type, *char_type;
16488   struct attribute *attr;
16489   struct dynamic_prop prop;
16490   bool length_is_constant = true;
16491   LONGEST length;
16492
16493   /* There are a couple of places where bit sizes might be made use of
16494      when parsing a DW_TAG_string_type, however, no producer that we know
16495      of make use of these.  Handling bit sizes that are a multiple of the
16496      byte size is easy enough, but what about other bit sizes?  Lets deal
16497      with that problem when we have to.  Warn about these attributes being
16498      unsupported, then parse the type and ignore them like we always
16499      have.  */
16500   if (dwarf2_attr (die, DW_AT_bit_size, cu) != nullptr
16501       || dwarf2_attr (die, DW_AT_string_length_bit_size, cu) != nullptr)
16502     {
16503       static bool warning_printed = false;
16504       if (!warning_printed)
16505         {
16506           warning (_("DW_AT_bit_size and DW_AT_string_length_bit_size not "
16507                      "currently supported on DW_TAG_string_type."));
16508           warning_printed = true;
16509         }
16510     }
16511
16512   attr = dwarf2_attr (die, DW_AT_string_length, cu);
16513   if (attr != nullptr && !attr->form_is_constant ())
16514     {
16515       /* The string length describes the location at which the length of
16516          the string can be found.  The size of the length field can be
16517          specified with one of the attributes below.  */
16518       struct type *prop_type;
16519       struct attribute *len
16520         = dwarf2_attr (die, DW_AT_string_length_byte_size, cu);
16521       if (len == nullptr)
16522         len = dwarf2_attr (die, DW_AT_byte_size, cu);
16523       if (len != nullptr && len->form_is_constant ())
16524         {
16525           /* Pass 0 as the default as we know this attribute is constant
16526              and the default value will not be returned.  */
16527           LONGEST sz = dwarf2_get_attr_constant_value (len, 0);
16528           prop_type = cu->per_cu->int_type (sz, true);
16529         }
16530       else
16531         {
16532           /* If the size is not specified then we assume it is the size of
16533              an address on this target.  */
16534           prop_type = cu->per_cu->addr_sized_int_type (true);
16535         }
16536
16537       /* Convert the attribute into a dynamic property.  */
16538       if (!attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
16539         length = 1;
16540       else
16541         length_is_constant = false;
16542     }
16543   else if (attr != nullptr)
16544     {
16545       /* This DW_AT_string_length just contains the length with no
16546          indirection.  There's no need to create a dynamic property in this
16547          case.  Pass 0 for the default value as we know it will not be
16548          returned in this case.  */
16549       length = dwarf2_get_attr_constant_value (attr, 0);
16550     }
16551   else if ((attr = dwarf2_attr (die, DW_AT_byte_size, cu)) != nullptr)
16552     {
16553       /* We don't currently support non-constant byte sizes for strings.  */
16554       length = dwarf2_get_attr_constant_value (attr, 1);
16555     }
16556   else
16557     {
16558       /* Use 1 as a fallback length if we have nothing else.  */
16559       length = 1;
16560     }
16561
16562   index_type = objfile_type (objfile)->builtin_int;
16563   if (length_is_constant)
16564     range_type = create_static_range_type (NULL, index_type, 1, length);
16565   else
16566     {
16567       struct dynamic_prop low_bound;
16568
16569       low_bound.kind = PROP_CONST;
16570       low_bound.data.const_val = 1;
16571       range_type = create_range_type (NULL, index_type, &low_bound, &prop, 0);
16572     }
16573   char_type = language_string_char_type (cu->language_defn, gdbarch);
16574   type = create_string_type (NULL, char_type, range_type);
16575
16576   return set_die_type (die, type, cu);
16577 }
16578
16579 /* Assuming that DIE corresponds to a function, returns nonzero
16580    if the function is prototyped.  */
16581
16582 static int
16583 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
16584 {
16585   struct attribute *attr;
16586
16587   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
16588   if (attr && (DW_UNSND (attr) != 0))
16589     return 1;
16590
16591   /* The DWARF standard implies that the DW_AT_prototyped attribute
16592      is only meaningful for C, but the concept also extends to other
16593      languages that allow unprototyped functions (Eg: Objective C).
16594      For all other languages, assume that functions are always
16595      prototyped.  */
16596   if (cu->language != language_c
16597       && cu->language != language_objc
16598       && cu->language != language_opencl)
16599     return 1;
16600
16601   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
16602      prototyped and unprototyped functions; default to prototyped,
16603      since that is more common in modern code (and RealView warns
16604      about unprototyped functions).  */
16605   if (producer_is_realview (cu->producer))
16606     return 1;
16607
16608   return 0;
16609 }
16610
16611 /* Handle DIES due to C code like:
16612
16613    struct foo
16614    {
16615    int (*funcp)(int a, long l);
16616    int b;
16617    };
16618
16619    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
16620
16621 static struct type *
16622 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
16623 {
16624   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16625   struct type *type;            /* Type that this function returns.  */
16626   struct type *ftype;           /* Function that returns above type.  */
16627   struct attribute *attr;
16628
16629   type = die_type (die, cu);
16630
16631   /* The die_type call above may have already set the type for this DIE.  */
16632   ftype = get_die_type (die, cu);
16633   if (ftype)
16634     return ftype;
16635
16636   ftype = lookup_function_type (type);
16637
16638   if (prototyped_function_p (die, cu))
16639     TYPE_PROTOTYPED (ftype) = 1;
16640
16641   /* Store the calling convention in the type if it's available in
16642      the subroutine die.  Otherwise set the calling convention to
16643      the default value DW_CC_normal.  */
16644   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
16645   if (attr != nullptr
16646       && is_valid_DW_AT_calling_convention_for_subroutine (DW_UNSND (attr)))
16647     TYPE_CALLING_CONVENTION (ftype)
16648       = (enum dwarf_calling_convention) (DW_UNSND (attr));
16649   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
16650     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
16651   else
16652     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
16653
16654   /* Record whether the function returns normally to its caller or not
16655      if the DWARF producer set that information.  */
16656   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
16657   if (attr && (DW_UNSND (attr) != 0))
16658     TYPE_NO_RETURN (ftype) = 1;
16659
16660   /* We need to add the subroutine type to the die immediately so
16661      we don't infinitely recurse when dealing with parameters
16662      declared as the same subroutine type.  */
16663   set_die_type (die, ftype, cu);
16664
16665   if (die->child != NULL)
16666     {
16667       struct type *void_type = objfile_type (objfile)->builtin_void;
16668       struct die_info *child_die;
16669       int nparams, iparams;
16670
16671       /* Count the number of parameters.
16672          FIXME: GDB currently ignores vararg functions, but knows about
16673          vararg member functions.  */
16674       nparams = 0;
16675       child_die = die->child;
16676       while (child_die && child_die->tag)
16677         {
16678           if (child_die->tag == DW_TAG_formal_parameter)
16679             nparams++;
16680           else if (child_die->tag == DW_TAG_unspecified_parameters)
16681             TYPE_VARARGS (ftype) = 1;
16682           child_die = sibling_die (child_die);
16683         }
16684
16685       /* Allocate storage for parameters and fill them in.  */
16686       TYPE_NFIELDS (ftype) = nparams;
16687       TYPE_FIELDS (ftype) = (struct field *)
16688         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
16689
16690       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
16691          even if we error out during the parameters reading below.  */
16692       for (iparams = 0; iparams < nparams; iparams++)
16693         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
16694
16695       iparams = 0;
16696       child_die = die->child;
16697       while (child_die && child_die->tag)
16698         {
16699           if (child_die->tag == DW_TAG_formal_parameter)
16700             {
16701               struct type *arg_type;
16702
16703               /* DWARF version 2 has no clean way to discern C++
16704                  static and non-static member functions.  G++ helps
16705                  GDB by marking the first parameter for non-static
16706                  member functions (which is the this pointer) as
16707                  artificial.  We pass this information to
16708                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
16709
16710                  DWARF version 3 added DW_AT_object_pointer, which GCC
16711                  4.5 does not yet generate.  */
16712               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
16713               if (attr != nullptr)
16714                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
16715               else
16716                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
16717               arg_type = die_type (child_die, cu);
16718
16719               /* RealView does not mark THIS as const, which the testsuite
16720                  expects.  GCC marks THIS as const in method definitions,
16721                  but not in the class specifications (GCC PR 43053).  */
16722               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
16723                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
16724                 {
16725                   int is_this = 0;
16726                   struct dwarf2_cu *arg_cu = cu;
16727                   const char *name = dwarf2_name (child_die, cu);
16728
16729                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
16730                   if (attr != nullptr)
16731                     {
16732                       /* If the compiler emits this, use it.  */
16733                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
16734                         is_this = 1;
16735                     }
16736                   else if (name && strcmp (name, "this") == 0)
16737                     /* Function definitions will have the argument names.  */
16738                     is_this = 1;
16739                   else if (name == NULL && iparams == 0)
16740                     /* Declarations may not have the names, so like
16741                        elsewhere in GDB, assume an artificial first
16742                        argument is "this".  */
16743                     is_this = 1;
16744
16745                   if (is_this)
16746                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
16747                                              arg_type, 0);
16748                 }
16749
16750               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
16751               iparams++;
16752             }
16753           child_die = sibling_die (child_die);
16754         }
16755     }
16756
16757   return ftype;
16758 }
16759
16760 static struct type *
16761 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
16762 {
16763   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16764   const char *name = NULL;
16765   struct type *this_type, *target_type;
16766
16767   name = dwarf2_full_name (NULL, die, cu);
16768   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
16769   TYPE_TARGET_STUB (this_type) = 1;
16770   set_die_type (die, this_type, cu);
16771   target_type = die_type (die, cu);
16772   if (target_type != this_type)
16773     TYPE_TARGET_TYPE (this_type) = target_type;
16774   else
16775     {
16776       /* Self-referential typedefs are, it seems, not allowed by the DWARF
16777          spec and cause infinite loops in GDB.  */
16778       complaint (_("Self-referential DW_TAG_typedef "
16779                    "- DIE at %s [in module %s]"),
16780                  sect_offset_str (die->sect_off), objfile_name (objfile));
16781       TYPE_TARGET_TYPE (this_type) = NULL;
16782     }
16783   return this_type;
16784 }
16785
16786 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
16787    (which may be different from NAME) to the architecture back-end to allow
16788    it to guess the correct format if necessary.  */
16789
16790 static struct type *
16791 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
16792                         const char *name_hint, enum bfd_endian byte_order)
16793 {
16794   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16795   const struct floatformat **format;
16796   struct type *type;
16797
16798   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
16799   if (format)
16800     type = init_float_type (objfile, bits, name, format, byte_order);
16801   else
16802     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
16803
16804   return type;
16805 }
16806
16807 /* Allocate an integer type of size BITS and name NAME.  */
16808
16809 static struct type *
16810 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
16811                           int bits, int unsigned_p, const char *name)
16812 {
16813   struct type *type;
16814
16815   /* Versions of Intel's C Compiler generate an integer type called "void"
16816      instead of using DW_TAG_unspecified_type.  This has been seen on
16817      at least versions 14, 17, and 18.  */
16818   if (bits == 0 && producer_is_icc (cu) && name != nullptr
16819       && strcmp (name, "void") == 0)
16820     type = objfile_type (objfile)->builtin_void;
16821   else
16822     type = init_integer_type (objfile, bits, unsigned_p, name);
16823
16824   return type;
16825 }
16826
16827 /* Initialise and return a floating point type of size BITS suitable for
16828    use as a component of a complex number.  The NAME_HINT is passed through
16829    when initialising the floating point type and is the name of the complex
16830    type.
16831
16832    As DWARF doesn't currently provide an explicit name for the components
16833    of a complex number, but it can be helpful to have these components
16834    named, we try to select a suitable name based on the size of the
16835    component.  */
16836 static struct type *
16837 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
16838                                  struct objfile *objfile,
16839                                  int bits, const char *name_hint,
16840                                  enum bfd_endian byte_order)
16841 {
16842   gdbarch *gdbarch = get_objfile_arch (objfile);
16843   struct type *tt = nullptr;
16844
16845   /* Try to find a suitable floating point builtin type of size BITS.
16846      We're going to use the name of this type as the name for the complex
16847      target type that we are about to create.  */
16848   switch (cu->language)
16849     {
16850     case language_fortran:
16851       switch (bits)
16852         {
16853         case 32:
16854           tt = builtin_f_type (gdbarch)->builtin_real;
16855           break;
16856         case 64:
16857           tt = builtin_f_type (gdbarch)->builtin_real_s8;
16858           break;
16859         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
16860         case 128:
16861           tt = builtin_f_type (gdbarch)->builtin_real_s16;
16862           break;
16863         }
16864       break;
16865     default:
16866       switch (bits)
16867         {
16868         case 32:
16869           tt = builtin_type (gdbarch)->builtin_float;
16870           break;
16871         case 64:
16872           tt = builtin_type (gdbarch)->builtin_double;
16873           break;
16874         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
16875         case 128:
16876           tt = builtin_type (gdbarch)->builtin_long_double;
16877           break;
16878         }
16879       break;
16880     }
16881
16882   /* If the type we found doesn't match the size we were looking for, then
16883      pretend we didn't find a type at all, the complex target type we
16884      create will then be nameless.  */
16885   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
16886     tt = nullptr;
16887
16888   const char *name = (tt == nullptr) ? nullptr : TYPE_NAME (tt);
16889   return dwarf2_init_float_type (objfile, bits, name, name_hint, byte_order);
16890 }
16891
16892 /* Find a representation of a given base type and install
16893    it in the TYPE field of the die.  */
16894
16895 static struct type *
16896 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
16897 {
16898   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16899   struct type *type;
16900   struct attribute *attr;
16901   int encoding = 0, bits = 0;
16902   const char *name;
16903   gdbarch *arch;
16904
16905   attr = dwarf2_attr (die, DW_AT_encoding, cu);
16906   if (attr != nullptr)
16907     encoding = DW_UNSND (attr);
16908   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16909   if (attr != nullptr)
16910     bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
16911   name = dwarf2_name (die, cu);
16912   if (!name)
16913     complaint (_("DW_AT_name missing from DW_TAG_base_type"));
16914
16915   arch = get_objfile_arch (objfile);
16916   enum bfd_endian byte_order = gdbarch_byte_order (arch);
16917
16918   attr = dwarf2_attr (die, DW_AT_endianity, cu);
16919   if (attr)
16920     {
16921       int endianity = DW_UNSND (attr);
16922
16923       switch (endianity)
16924         {
16925         case DW_END_big:
16926           byte_order = BFD_ENDIAN_BIG;
16927           break;
16928         case DW_END_little:
16929           byte_order = BFD_ENDIAN_LITTLE;
16930           break;
16931         default:
16932           complaint (_("DW_AT_endianity has unrecognized value %d"), endianity);
16933           break;
16934         }
16935     }
16936
16937   switch (encoding)
16938     {
16939       case DW_ATE_address:
16940         /* Turn DW_ATE_address into a void * pointer.  */
16941         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
16942         type = init_pointer_type (objfile, bits, name, type);
16943         break;
16944       case DW_ATE_boolean:
16945         type = init_boolean_type (objfile, bits, 1, name);
16946         break;
16947       case DW_ATE_complex_float:
16948         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name,
16949                                                 byte_order);
16950         type = init_complex_type (objfile, name, type);
16951         break;
16952       case DW_ATE_decimal_float:
16953         type = init_decfloat_type (objfile, bits, name);
16954         break;
16955       case DW_ATE_float:
16956         type = dwarf2_init_float_type (objfile, bits, name, name, byte_order);
16957         break;
16958       case DW_ATE_signed:
16959         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
16960         break;
16961       case DW_ATE_unsigned:
16962         if (cu->language == language_fortran
16963             && name
16964             && startswith (name, "character("))
16965           type = init_character_type (objfile, bits, 1, name);
16966         else
16967           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
16968         break;
16969       case DW_ATE_signed_char:
16970         if (cu->language == language_ada || cu->language == language_m2
16971             || cu->language == language_pascal
16972             || cu->language == language_fortran)
16973           type = init_character_type (objfile, bits, 0, name);
16974         else
16975           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
16976         break;
16977       case DW_ATE_unsigned_char:
16978         if (cu->language == language_ada || cu->language == language_m2
16979             || cu->language == language_pascal
16980             || cu->language == language_fortran
16981             || cu->language == language_rust)
16982           type = init_character_type (objfile, bits, 1, name);
16983         else
16984           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
16985         break;
16986       case DW_ATE_UTF:
16987         {
16988           if (bits == 16)
16989             type = builtin_type (arch)->builtin_char16;
16990           else if (bits == 32)
16991             type = builtin_type (arch)->builtin_char32;
16992           else
16993             {
16994               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
16995                          bits);
16996               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
16997             }
16998           return set_die_type (die, type, cu);
16999         }
17000         break;
17001
17002       default:
17003         complaint (_("unsupported DW_AT_encoding: '%s'"),
17004                    dwarf_type_encoding_name (encoding));
17005         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17006         break;
17007     }
17008
17009   if (name && strcmp (name, "char") == 0)
17010     TYPE_NOSIGN (type) = 1;
17011
17012   maybe_set_alignment (cu, die, type);
17013
17014   TYPE_ENDIANITY_NOT_DEFAULT (type) = gdbarch_byte_order (arch) != byte_order;
17015
17016   return set_die_type (die, type, cu);
17017 }
17018
17019 /* Parse dwarf attribute if it's a block, reference or constant and put the
17020    resulting value of the attribute into struct bound_prop.
17021    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17022
17023 static int
17024 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17025                       struct dwarf2_cu *cu, struct dynamic_prop *prop,
17026                       struct type *default_type)
17027 {
17028   struct dwarf2_property_baton *baton;
17029   struct obstack *obstack
17030     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17031
17032   gdb_assert (default_type != NULL);
17033
17034   if (attr == NULL || prop == NULL)
17035     return 0;
17036
17037   if (attr->form_is_block ())
17038     {
17039       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17040       baton->property_type = default_type;
17041       baton->locexpr.per_cu = cu->per_cu;
17042       baton->locexpr.size = DW_BLOCK (attr)->size;
17043       baton->locexpr.data = DW_BLOCK (attr)->data;
17044       switch (attr->name)
17045         {
17046         case DW_AT_string_length:
17047           baton->locexpr.is_reference = true;
17048           break;
17049         default:
17050           baton->locexpr.is_reference = false;
17051           break;
17052         }
17053       prop->data.baton = baton;
17054       prop->kind = PROP_LOCEXPR;
17055       gdb_assert (prop->data.baton != NULL);
17056     }
17057   else if (attr->form_is_ref ())
17058     {
17059       struct dwarf2_cu *target_cu = cu;
17060       struct die_info *target_die;
17061       struct attribute *target_attr;
17062
17063       target_die = follow_die_ref (die, attr, &target_cu);
17064       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17065       if (target_attr == NULL)
17066         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17067                                    target_cu);
17068       if (target_attr == NULL)
17069         return 0;
17070
17071       switch (target_attr->name)
17072         {
17073           case DW_AT_location:
17074             if (target_attr->form_is_section_offset ())
17075               {
17076                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17077                 baton->property_type = die_type (target_die, target_cu);
17078                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17079                 prop->data.baton = baton;
17080                 prop->kind = PROP_LOCLIST;
17081                 gdb_assert (prop->data.baton != NULL);
17082               }
17083             else if (target_attr->form_is_block ())
17084               {
17085                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17086                 baton->property_type = die_type (target_die, target_cu);
17087                 baton->locexpr.per_cu = cu->per_cu;
17088                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17089                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17090                 baton->locexpr.is_reference = true;
17091                 prop->data.baton = baton;
17092                 prop->kind = PROP_LOCEXPR;
17093                 gdb_assert (prop->data.baton != NULL);
17094               }
17095             else
17096               {
17097                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17098                                                        "dynamic property");
17099                 return 0;
17100               }
17101             break;
17102           case DW_AT_data_member_location:
17103             {
17104               LONGEST offset;
17105
17106               if (!handle_data_member_location (target_die, target_cu,
17107                                                 &offset))
17108                 return 0;
17109
17110               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17111               baton->property_type = read_type_die (target_die->parent,
17112                                                       target_cu);
17113               baton->offset_info.offset = offset;
17114               baton->offset_info.type = die_type (target_die, target_cu);
17115               prop->data.baton = baton;
17116               prop->kind = PROP_ADDR_OFFSET;
17117               break;
17118             }
17119         }
17120     }
17121   else if (attr->form_is_constant ())
17122     {
17123       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17124       prop->kind = PROP_CONST;
17125     }
17126   else
17127     {
17128       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17129                                              dwarf2_name (die, cu));
17130       return 0;
17131     }
17132
17133   return 1;
17134 }
17135
17136 /* See read.h.  */
17137
17138 struct type *
17139 dwarf2_per_cu_data::int_type (int size_in_bytes, bool unsigned_p) const
17140 {
17141   struct objfile *objfile = dwarf2_per_objfile->objfile;
17142   struct type *int_type;
17143
17144   /* Helper macro to examine the various builtin types.  */
17145 #define TRY_TYPE(F)                                                     \
17146   int_type = (unsigned_p                                                \
17147               ? objfile_type (objfile)->builtin_unsigned_ ## F          \
17148               : objfile_type (objfile)->builtin_ ## F);                 \
17149   if (int_type != NULL && TYPE_LENGTH (int_type) == size_in_bytes)      \
17150     return int_type
17151
17152   TRY_TYPE (char);
17153   TRY_TYPE (short);
17154   TRY_TYPE (int);
17155   TRY_TYPE (long);
17156   TRY_TYPE (long_long);
17157
17158 #undef TRY_TYPE
17159
17160   gdb_assert_not_reached ("unable to find suitable integer type");
17161 }
17162
17163 /* See read.h.  */
17164
17165 struct type *
17166 dwarf2_per_cu_data::addr_sized_int_type (bool unsigned_p) const
17167 {
17168   int addr_size = this->addr_size ();
17169   return int_type (addr_size, unsigned_p);
17170 }
17171
17172 /* Read the DW_AT_type attribute for a sub-range.  If this attribute is not
17173    present (which is valid) then compute the default type based on the
17174    compilation units address size.  */
17175
17176 static struct type *
17177 read_subrange_index_type (struct die_info *die, struct dwarf2_cu *cu)
17178 {
17179   struct type *index_type = die_type (die, cu);
17180
17181   /* Dwarf-2 specifications explicitly allows to create subrange types
17182      without specifying a base type.
17183      In that case, the base type must be set to the type of
17184      the lower bound, upper bound or count, in that order, if any of these
17185      three attributes references an object that has a type.
17186      If no base type is found, the Dwarf-2 specifications say that
17187      a signed integer type of size equal to the size of an address should
17188      be used.
17189      For the following C code: `extern char gdb_int [];'
17190      GCC produces an empty range DIE.
17191      FIXME: muller/2010-05-28: Possible references to object for low bound,
17192      high bound or count are not yet handled by this code.  */
17193   if (TYPE_CODE (index_type) == TYPE_CODE_VOID)
17194     index_type = cu->per_cu->addr_sized_int_type (false);
17195
17196   return index_type;
17197 }
17198
17199 /* Read the given DW_AT_subrange DIE.  */
17200
17201 static struct type *
17202 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17203 {
17204   struct type *base_type, *orig_base_type;
17205   struct type *range_type;
17206   struct attribute *attr;
17207   struct dynamic_prop low, high;
17208   int low_default_is_valid;
17209   int high_bound_is_count = 0;
17210   const char *name;
17211   ULONGEST negative_mask;
17212
17213   orig_base_type = read_subrange_index_type (die, cu);
17214
17215   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17216      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17217      creating the range type, but we use the result of check_typedef
17218      when examining properties of the type.  */
17219   base_type = check_typedef (orig_base_type);
17220
17221   /* The die_type call above may have already set the type for this DIE.  */
17222   range_type = get_die_type (die, cu);
17223   if (range_type)
17224     return range_type;
17225
17226   low.kind = PROP_CONST;
17227   high.kind = PROP_CONST;
17228   high.data.const_val = 0;
17229
17230   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17231      omitting DW_AT_lower_bound.  */
17232   switch (cu->language)
17233     {
17234     case language_c:
17235     case language_cplus:
17236       low.data.const_val = 0;
17237       low_default_is_valid = 1;
17238       break;
17239     case language_fortran:
17240       low.data.const_val = 1;
17241       low_default_is_valid = 1;
17242       break;
17243     case language_d:
17244     case language_objc:
17245     case language_rust:
17246       low.data.const_val = 0;
17247       low_default_is_valid = (cu->header.version >= 4);
17248       break;
17249     case language_ada:
17250     case language_m2:
17251     case language_pascal:
17252       low.data.const_val = 1;
17253       low_default_is_valid = (cu->header.version >= 4);
17254       break;
17255     default:
17256       low.data.const_val = 0;
17257       low_default_is_valid = 0;
17258       break;
17259     }
17260
17261   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17262   if (attr != nullptr)
17263     attr_to_dynamic_prop (attr, die, cu, &low, base_type);
17264   else if (!low_default_is_valid)
17265     complaint (_("Missing DW_AT_lower_bound "
17266                                       "- DIE at %s [in module %s]"),
17267                sect_offset_str (die->sect_off),
17268                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17269
17270   struct attribute *attr_ub, *attr_count;
17271   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17272   if (!attr_to_dynamic_prop (attr, die, cu, &high, base_type))
17273     {
17274       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17275       if (attr_to_dynamic_prop (attr, die, cu, &high, base_type))
17276         {
17277           /* If bounds are constant do the final calculation here.  */
17278           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17279             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17280           else
17281             high_bound_is_count = 1;
17282         }
17283       else
17284         {
17285           if (attr_ub != NULL)
17286             complaint (_("Unresolved DW_AT_upper_bound "
17287                          "- DIE at %s [in module %s]"),
17288                        sect_offset_str (die->sect_off),
17289                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17290           if (attr_count != NULL)
17291             complaint (_("Unresolved DW_AT_count "
17292                          "- DIE at %s [in module %s]"),
17293                        sect_offset_str (die->sect_off),
17294                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17295         }
17296     }
17297
17298   LONGEST bias = 0;
17299   struct attribute *bias_attr = dwarf2_attr (die, DW_AT_GNU_bias, cu);
17300   if (bias_attr != nullptr && bias_attr->form_is_constant ())
17301     bias = dwarf2_get_attr_constant_value (bias_attr, 0);
17302
17303   /* Normally, the DWARF producers are expected to use a signed
17304      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17305      But this is unfortunately not always the case, as witnessed
17306      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17307      is used instead.  To work around that ambiguity, we treat
17308      the bounds as signed, and thus sign-extend their values, when
17309      the base type is signed.  */
17310   negative_mask =
17311     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17312   if (low.kind == PROP_CONST
17313       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17314     low.data.const_val |= negative_mask;
17315   if (high.kind == PROP_CONST
17316       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17317     high.data.const_val |= negative_mask;
17318
17319   /* Check for bit and byte strides.  */
17320   struct dynamic_prop byte_stride_prop;
17321   attribute *attr_byte_stride = dwarf2_attr (die, DW_AT_byte_stride, cu);
17322   if (attr_byte_stride != nullptr)
17323     {
17324       struct type *prop_type = cu->per_cu->addr_sized_int_type (false);
17325       attr_to_dynamic_prop (attr_byte_stride, die, cu, &byte_stride_prop,
17326                             prop_type);
17327     }
17328
17329   struct dynamic_prop bit_stride_prop;
17330   attribute *attr_bit_stride = dwarf2_attr (die, DW_AT_bit_stride, cu);
17331   if (attr_bit_stride != nullptr)
17332     {
17333       /* It only makes sense to have either a bit or byte stride.  */
17334       if (attr_byte_stride != nullptr)
17335         {
17336           complaint (_("Found DW_AT_bit_stride and DW_AT_byte_stride "
17337                        "- DIE at %s [in module %s]"),
17338                      sect_offset_str (die->sect_off),
17339                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17340           attr_bit_stride = nullptr;
17341         }
17342       else
17343         {
17344           struct type *prop_type = cu->per_cu->addr_sized_int_type (false);
17345           attr_to_dynamic_prop (attr_bit_stride, die, cu, &bit_stride_prop,
17346                                 prop_type);
17347         }
17348     }
17349
17350   if (attr_byte_stride != nullptr
17351       || attr_bit_stride != nullptr)
17352     {
17353       bool byte_stride_p = (attr_byte_stride != nullptr);
17354       struct dynamic_prop *stride
17355         = byte_stride_p ? &byte_stride_prop : &bit_stride_prop;
17356
17357       range_type
17358         = create_range_type_with_stride (NULL, orig_base_type, &low,
17359                                          &high, bias, stride, byte_stride_p);
17360     }
17361   else
17362     range_type = create_range_type (NULL, orig_base_type, &low, &high, bias);
17363
17364   if (high_bound_is_count)
17365     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17366
17367   /* Ada expects an empty array on no boundary attributes.  */
17368   if (attr == NULL && cu->language != language_ada)
17369     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17370
17371   name = dwarf2_name (die, cu);
17372   if (name)
17373     TYPE_NAME (range_type) = name;
17374
17375   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17376   if (attr != nullptr)
17377     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17378
17379   maybe_set_alignment (cu, die, range_type);
17380
17381   set_die_type (die, range_type, cu);
17382
17383   /* set_die_type should be already done.  */
17384   set_descriptive_type (range_type, die, cu);
17385
17386   return range_type;
17387 }
17388
17389 static struct type *
17390 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17391 {
17392   struct type *type;
17393
17394   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17395                     NULL);
17396   TYPE_NAME (type) = dwarf2_name (die, cu);
17397
17398   /* In Ada, an unspecified type is typically used when the description
17399      of the type is deferred to a different unit.  When encountering
17400      such a type, we treat it as a stub, and try to resolve it later on,
17401      when needed.  */
17402   if (cu->language == language_ada)
17403     TYPE_STUB (type) = 1;
17404
17405   return set_die_type (die, type, cu);
17406 }
17407
17408 /* Read a single die and all its descendents.  Set the die's sibling
17409    field to NULL; set other fields in the die correctly, and set all
17410    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17411    location of the info_ptr after reading all of those dies.  PARENT
17412    is the parent of the die in question.  */
17413
17414 static struct die_info *
17415 read_die_and_children (const struct die_reader_specs *reader,
17416                        const gdb_byte *info_ptr,
17417                        const gdb_byte **new_info_ptr,
17418                        struct die_info *parent)
17419 {
17420   struct die_info *die;
17421   const gdb_byte *cur_ptr;
17422
17423   cur_ptr = read_full_die_1 (reader, &die, info_ptr, 0);
17424   if (die == NULL)
17425     {
17426       *new_info_ptr = cur_ptr;
17427       return NULL;
17428     }
17429   store_in_ref_table (die, reader->cu);
17430
17431   if (die->has_children)
17432     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17433   else
17434     {
17435       die->child = NULL;
17436       *new_info_ptr = cur_ptr;
17437     }
17438
17439   die->sibling = NULL;
17440   die->parent = parent;
17441   return die;
17442 }
17443
17444 /* Read a die, all of its descendents, and all of its siblings; set
17445    all of the fields of all of the dies correctly.  Arguments are as
17446    in read_die_and_children.  */
17447
17448 static struct die_info *
17449 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17450                          const gdb_byte *info_ptr,
17451                          const gdb_byte **new_info_ptr,
17452                          struct die_info *parent)
17453 {
17454   struct die_info *first_die, *last_sibling;
17455   const gdb_byte *cur_ptr;
17456
17457   cur_ptr = info_ptr;
17458   first_die = last_sibling = NULL;
17459
17460   while (1)
17461     {
17462       struct die_info *die
17463         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17464
17465       if (die == NULL)
17466         {
17467           *new_info_ptr = cur_ptr;
17468           return first_die;
17469         }
17470
17471       if (!first_die)
17472         first_die = die;
17473       else
17474         last_sibling->sibling = die;
17475
17476       last_sibling = die;
17477     }
17478 }
17479
17480 /* Read a die, all of its descendents, and all of its siblings; set
17481    all of the fields of all of the dies correctly.  Arguments are as
17482    in read_die_and_children.
17483    This the main entry point for reading a DIE and all its children.  */
17484
17485 static struct die_info *
17486 read_die_and_siblings (const struct die_reader_specs *reader,
17487                        const gdb_byte *info_ptr,
17488                        const gdb_byte **new_info_ptr,
17489                        struct die_info *parent)
17490 {
17491   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17492                                                   new_info_ptr, parent);
17493
17494   if (dwarf_die_debug)
17495     {
17496       fprintf_unfiltered (gdb_stdlog,
17497                           "Read die from %s@0x%x of %s:\n",
17498                           reader->die_section->get_name (),
17499                           (unsigned) (info_ptr - reader->die_section->buffer),
17500                           bfd_get_filename (reader->abfd));
17501       dump_die (die, dwarf_die_debug);
17502     }
17503
17504   return die;
17505 }
17506
17507 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17508    attributes.
17509    The caller is responsible for filling in the extra attributes
17510    and updating (*DIEP)->num_attrs.
17511    Set DIEP to point to a newly allocated die with its information,
17512    except for its child, sibling, and parent fields.  */
17513
17514 static const gdb_byte *
17515 read_full_die_1 (const struct die_reader_specs *reader,
17516                  struct die_info **diep, const gdb_byte *info_ptr,
17517                  int num_extra_attrs)
17518 {
17519   unsigned int abbrev_number, bytes_read, i;
17520   struct abbrev_info *abbrev;
17521   struct die_info *die;
17522   struct dwarf2_cu *cu = reader->cu;
17523   bfd *abfd = reader->abfd;
17524
17525   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17526   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17527   info_ptr += bytes_read;
17528   if (!abbrev_number)
17529     {
17530       *diep = NULL;
17531       return info_ptr;
17532     }
17533
17534   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17535   if (!abbrev)
17536     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17537            abbrev_number,
17538            bfd_get_filename (abfd));
17539
17540   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17541   die->sect_off = sect_off;
17542   die->tag = abbrev->tag;
17543   die->abbrev = abbrev_number;
17544   die->has_children = abbrev->has_children;
17545
17546   /* Make the result usable.
17547      The caller needs to update num_attrs after adding the extra
17548      attributes.  */
17549   die->num_attrs = abbrev->num_attrs;
17550
17551   std::vector<int> indexes_that_need_reprocess;
17552   for (i = 0; i < abbrev->num_attrs; ++i)
17553     {
17554       bool need_reprocess;
17555       info_ptr =
17556         read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17557                         info_ptr, &need_reprocess);
17558       if (need_reprocess)
17559         indexes_that_need_reprocess.push_back (i);
17560     }
17561
17562   struct attribute *attr = dwarf2_attr_no_follow (die, DW_AT_str_offsets_base);
17563   if (attr != nullptr)
17564     cu->str_offsets_base = DW_UNSND (attr);
17565
17566   auto maybe_addr_base = lookup_addr_base(die);
17567   if (maybe_addr_base.has_value ())
17568     cu->addr_base = *maybe_addr_base;
17569   for (int index : indexes_that_need_reprocess)
17570     read_attribute_reprocess (reader, &die->attrs[index]);
17571   *diep = die;
17572   return info_ptr;
17573 }
17574
17575 /* Read a die and all its attributes.
17576    Set DIEP to point to a newly allocated die with its information,
17577    except for its child, sibling, and parent fields.  */
17578
17579 static const gdb_byte *
17580 read_full_die (const struct die_reader_specs *reader,
17581                struct die_info **diep, const gdb_byte *info_ptr)
17582 {
17583   const gdb_byte *result;
17584
17585   result = read_full_die_1 (reader, diep, info_ptr, 0);
17586
17587   if (dwarf_die_debug)
17588     {
17589       fprintf_unfiltered (gdb_stdlog,
17590                           "Read die from %s@0x%x of %s:\n",
17591                           reader->die_section->get_name (),
17592                           (unsigned) (info_ptr - reader->die_section->buffer),
17593                           bfd_get_filename (reader->abfd));
17594       dump_die (*diep, dwarf_die_debug);
17595     }
17596
17597   return result;
17598 }
17599 \f
17600
17601 /* Returns nonzero if TAG represents a type that we might generate a partial
17602    symbol for.  */
17603
17604 static int
17605 is_type_tag_for_partial (int tag)
17606 {
17607   switch (tag)
17608     {
17609 #if 0
17610     /* Some types that would be reasonable to generate partial symbols for,
17611        that we don't at present.  */
17612     case DW_TAG_array_type:
17613     case DW_TAG_file_type:
17614     case DW_TAG_ptr_to_member_type:
17615     case DW_TAG_set_type:
17616     case DW_TAG_string_type:
17617     case DW_TAG_subroutine_type:
17618 #endif
17619     case DW_TAG_base_type:
17620     case DW_TAG_class_type:
17621     case DW_TAG_interface_type:
17622     case DW_TAG_enumeration_type:
17623     case DW_TAG_structure_type:
17624     case DW_TAG_subrange_type:
17625     case DW_TAG_typedef:
17626     case DW_TAG_union_type:
17627       return 1;
17628     default:
17629       return 0;
17630     }
17631 }
17632
17633 /* Load all DIEs that are interesting for partial symbols into memory.  */
17634
17635 static struct partial_die_info *
17636 load_partial_dies (const struct die_reader_specs *reader,
17637                    const gdb_byte *info_ptr, int building_psymtab)
17638 {
17639   struct dwarf2_cu *cu = reader->cu;
17640   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17641   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
17642   unsigned int bytes_read;
17643   unsigned int load_all = 0;
17644   int nesting_level = 1;
17645
17646   parent_die = NULL;
17647   last_die = NULL;
17648
17649   gdb_assert (cu->per_cu != NULL);
17650   if (cu->per_cu->load_all_dies)
17651     load_all = 1;
17652
17653   cu->partial_dies
17654     = htab_create_alloc_ex (cu->header.length / 12,
17655                             partial_die_hash,
17656                             partial_die_eq,
17657                             NULL,
17658                             &cu->comp_unit_obstack,
17659                             hashtab_obstack_allocate,
17660                             dummy_obstack_deallocate);
17661
17662   while (1)
17663     {
17664       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
17665
17666       /* A NULL abbrev means the end of a series of children.  */
17667       if (abbrev == NULL)
17668         {
17669           if (--nesting_level == 0)
17670             return first_die;
17671
17672           info_ptr += bytes_read;
17673           last_die = parent_die;
17674           parent_die = parent_die->die_parent;
17675           continue;
17676         }
17677
17678       /* Check for template arguments.  We never save these; if
17679          they're seen, we just mark the parent, and go on our way.  */
17680       if (parent_die != NULL
17681           && cu->language == language_cplus
17682           && (abbrev->tag == DW_TAG_template_type_param
17683               || abbrev->tag == DW_TAG_template_value_param))
17684         {
17685           parent_die->has_template_arguments = 1;
17686
17687           if (!load_all)
17688             {
17689               /* We don't need a partial DIE for the template argument.  */
17690               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17691               continue;
17692             }
17693         }
17694
17695       /* We only recurse into c++ subprograms looking for template arguments.
17696          Skip their other children.  */
17697       if (!load_all
17698           && cu->language == language_cplus
17699           && parent_die != NULL
17700           && parent_die->tag == DW_TAG_subprogram)
17701         {
17702           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17703           continue;
17704         }
17705
17706       /* Check whether this DIE is interesting enough to save.  Normally
17707          we would not be interested in members here, but there may be
17708          later variables referencing them via DW_AT_specification (for
17709          static members).  */
17710       if (!load_all
17711           && !is_type_tag_for_partial (abbrev->tag)
17712           && abbrev->tag != DW_TAG_constant
17713           && abbrev->tag != DW_TAG_enumerator
17714           && abbrev->tag != DW_TAG_subprogram
17715           && abbrev->tag != DW_TAG_inlined_subroutine
17716           && abbrev->tag != DW_TAG_lexical_block
17717           && abbrev->tag != DW_TAG_variable
17718           && abbrev->tag != DW_TAG_namespace
17719           && abbrev->tag != DW_TAG_module
17720           && abbrev->tag != DW_TAG_member
17721           && abbrev->tag != DW_TAG_imported_unit
17722           && abbrev->tag != DW_TAG_imported_declaration)
17723         {
17724           /* Otherwise we skip to the next sibling, if any.  */
17725           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17726           continue;
17727         }
17728
17729       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
17730                                    abbrev);
17731
17732       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
17733
17734       /* This two-pass algorithm for processing partial symbols has a
17735          high cost in cache pressure.  Thus, handle some simple cases
17736          here which cover the majority of C partial symbols.  DIEs
17737          which neither have specification tags in them, nor could have
17738          specification tags elsewhere pointing at them, can simply be
17739          processed and discarded.
17740
17741          This segment is also optional; scan_partial_symbols and
17742          add_partial_symbol will handle these DIEs if we chain
17743          them in normally.  When compilers which do not emit large
17744          quantities of duplicate debug information are more common,
17745          this code can probably be removed.  */
17746
17747       /* Any complete simple types at the top level (pretty much all
17748          of them, for a language without namespaces), can be processed
17749          directly.  */
17750       if (parent_die == NULL
17751           && pdi.has_specification == 0
17752           && pdi.is_declaration == 0
17753           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
17754               || pdi.tag == DW_TAG_base_type
17755               || pdi.tag == DW_TAG_subrange_type))
17756         {
17757           if (building_psymtab && pdi.name != NULL)
17758             add_psymbol_to_list (pdi.name, false,
17759                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
17760                                  psymbol_placement::STATIC,
17761                                  0, cu->language, objfile);
17762           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
17763           continue;
17764         }
17765
17766       /* The exception for DW_TAG_typedef with has_children above is
17767          a workaround of GCC PR debug/47510.  In the case of this complaint
17768          type_name_or_error will error on such types later.
17769
17770          GDB skipped children of DW_TAG_typedef by the shortcut above and then
17771          it could not find the child DIEs referenced later, this is checked
17772          above.  In correct DWARF DW_TAG_typedef should have no children.  */
17773
17774       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
17775         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
17776                      "- DIE at %s [in module %s]"),
17777                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
17778
17779       /* If we're at the second level, and we're an enumerator, and
17780          our parent has no specification (meaning possibly lives in a
17781          namespace elsewhere), then we can add the partial symbol now
17782          instead of queueing it.  */
17783       if (pdi.tag == DW_TAG_enumerator
17784           && parent_die != NULL
17785           && parent_die->die_parent == NULL
17786           && parent_die->tag == DW_TAG_enumeration_type
17787           && parent_die->has_specification == 0)
17788         {
17789           if (pdi.name == NULL)
17790             complaint (_("malformed enumerator DIE ignored"));
17791           else if (building_psymtab)
17792             add_psymbol_to_list (pdi.name, false,
17793                                  VAR_DOMAIN, LOC_CONST, -1,
17794                                  cu->language == language_cplus
17795                                  ? psymbol_placement::GLOBAL
17796                                  : psymbol_placement::STATIC,
17797                                  0, cu->language, objfile);
17798
17799           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
17800           continue;
17801         }
17802
17803       struct partial_die_info *part_die
17804         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
17805
17806       /* We'll save this DIE so link it in.  */
17807       part_die->die_parent = parent_die;
17808       part_die->die_sibling = NULL;
17809       part_die->die_child = NULL;
17810
17811       if (last_die && last_die == parent_die)
17812         last_die->die_child = part_die;
17813       else if (last_die)
17814         last_die->die_sibling = part_die;
17815
17816       last_die = part_die;
17817
17818       if (first_die == NULL)
17819         first_die = part_die;
17820
17821       /* Maybe add the DIE to the hash table.  Not all DIEs that we
17822          find interesting need to be in the hash table, because we
17823          also have the parent/sibling/child chains; only those that we
17824          might refer to by offset later during partial symbol reading.
17825
17826          For now this means things that might have be the target of a
17827          DW_AT_specification, DW_AT_abstract_origin, or
17828          DW_AT_extension.  DW_AT_extension will refer only to
17829          namespaces; DW_AT_abstract_origin refers to functions (and
17830          many things under the function DIE, but we do not recurse
17831          into function DIEs during partial symbol reading) and
17832          possibly variables as well; DW_AT_specification refers to
17833          declarations.  Declarations ought to have the DW_AT_declaration
17834          flag.  It happens that GCC forgets to put it in sometimes, but
17835          only for functions, not for types.
17836
17837          Adding more things than necessary to the hash table is harmless
17838          except for the performance cost.  Adding too few will result in
17839          wasted time in find_partial_die, when we reread the compilation
17840          unit with load_all_dies set.  */
17841
17842       if (load_all
17843           || abbrev->tag == DW_TAG_constant
17844           || abbrev->tag == DW_TAG_subprogram
17845           || abbrev->tag == DW_TAG_variable
17846           || abbrev->tag == DW_TAG_namespace
17847           || part_die->is_declaration)
17848         {
17849           void **slot;
17850
17851           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
17852                                            to_underlying (part_die->sect_off),
17853                                            INSERT);
17854           *slot = part_die;
17855         }
17856
17857       /* For some DIEs we want to follow their children (if any).  For C
17858          we have no reason to follow the children of structures; for other
17859          languages we have to, so that we can get at method physnames
17860          to infer fully qualified class names, for DW_AT_specification,
17861          and for C++ template arguments.  For C++, we also look one level
17862          inside functions to find template arguments (if the name of the
17863          function does not already contain the template arguments).
17864
17865          For Ada and Fortran, we need to scan the children of subprograms
17866          and lexical blocks as well because these languages allow the
17867          definition of nested entities that could be interesting for the
17868          debugger, such as nested subprograms for instance.  */
17869       if (last_die->has_children
17870           && (load_all
17871               || last_die->tag == DW_TAG_namespace
17872               || last_die->tag == DW_TAG_module
17873               || last_die->tag == DW_TAG_enumeration_type
17874               || (cu->language == language_cplus
17875                   && last_die->tag == DW_TAG_subprogram
17876                   && (last_die->name == NULL
17877                       || strchr (last_die->name, '<') == NULL))
17878               || (cu->language != language_c
17879                   && (last_die->tag == DW_TAG_class_type
17880                       || last_die->tag == DW_TAG_interface_type
17881                       || last_die->tag == DW_TAG_structure_type
17882                       || last_die->tag == DW_TAG_union_type))
17883               || ((cu->language == language_ada
17884                    || cu->language == language_fortran)
17885                   && (last_die->tag == DW_TAG_subprogram
17886                       || last_die->tag == DW_TAG_lexical_block))))
17887         {
17888           nesting_level++;
17889           parent_die = last_die;
17890           continue;
17891         }
17892
17893       /* Otherwise we skip to the next sibling, if any.  */
17894       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
17895
17896       /* Back to the top, do it again.  */
17897     }
17898 }
17899
17900 partial_die_info::partial_die_info (sect_offset sect_off_,
17901                                     struct abbrev_info *abbrev)
17902   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
17903 {
17904 }
17905
17906 /* Read a minimal amount of information into the minimal die structure.
17907    INFO_PTR should point just after the initial uleb128 of a DIE.  */
17908
17909 const gdb_byte *
17910 partial_die_info::read (const struct die_reader_specs *reader,
17911                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
17912 {
17913   struct dwarf2_cu *cu = reader->cu;
17914   struct dwarf2_per_objfile *dwarf2_per_objfile
17915     = cu->per_cu->dwarf2_per_objfile;
17916   unsigned int i;
17917   int has_low_pc_attr = 0;
17918   int has_high_pc_attr = 0;
17919   int high_pc_relative = 0;
17920
17921   std::vector<struct attribute> attr_vec (abbrev.num_attrs);
17922   for (i = 0; i < abbrev.num_attrs; ++i)
17923     {
17924       bool need_reprocess;
17925       info_ptr = read_attribute (reader, &attr_vec[i], &abbrev.attrs[i],
17926                                  info_ptr, &need_reprocess);
17927       /* String and address offsets that need to do the reprocessing have
17928          already been read at this point, so there is no need to wait until
17929          the loop terminates to do the reprocessing.  */
17930       if (need_reprocess)
17931         read_attribute_reprocess (reader, &attr_vec[i]);
17932       attribute &attr = attr_vec[i];
17933       /* Store the data if it is of an attribute we want to keep in a
17934          partial symbol table.  */
17935       switch (attr.name)
17936         {
17937         case DW_AT_name:
17938           switch (tag)
17939             {
17940             case DW_TAG_compile_unit:
17941             case DW_TAG_partial_unit:
17942             case DW_TAG_type_unit:
17943               /* Compilation units have a DW_AT_name that is a filename, not
17944                  a source language identifier.  */
17945             case DW_TAG_enumeration_type:
17946             case DW_TAG_enumerator:
17947               /* These tags always have simple identifiers already; no need
17948                  to canonicalize them.  */
17949               name = DW_STRING (&attr);
17950               break;
17951             default:
17952               {
17953                 struct objfile *objfile = dwarf2_per_objfile->objfile;
17954
17955                 name
17956                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
17957                                               &objfile->per_bfd->storage_obstack);
17958               }
17959               break;
17960             }
17961           break;
17962         case DW_AT_linkage_name:
17963         case DW_AT_MIPS_linkage_name:
17964           /* Note that both forms of linkage name might appear.  We
17965              assume they will be the same, and we only store the last
17966              one we see.  */
17967           linkage_name = DW_STRING (&attr);
17968           break;
17969         case DW_AT_low_pc:
17970           has_low_pc_attr = 1;
17971           lowpc = attr.value_as_address ();
17972           break;
17973         case DW_AT_high_pc:
17974           has_high_pc_attr = 1;
17975           highpc = attr.value_as_address ();
17976           if (cu->header.version >= 4 && attr.form_is_constant ())
17977                 high_pc_relative = 1;
17978           break;
17979         case DW_AT_location:
17980           /* Support the .debug_loc offsets.  */
17981           if (attr.form_is_block ())
17982             {
17983                d.locdesc = DW_BLOCK (&attr);
17984             }
17985           else if (attr.form_is_section_offset ())
17986             {
17987               dwarf2_complex_location_expr_complaint ();
17988             }
17989           else
17990             {
17991               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17992                                                      "partial symbol information");
17993             }
17994           break;
17995         case DW_AT_external:
17996           is_external = DW_UNSND (&attr);
17997           break;
17998         case DW_AT_declaration:
17999           is_declaration = DW_UNSND (&attr);
18000           break;
18001         case DW_AT_type:
18002           has_type = 1;
18003           break;
18004         case DW_AT_abstract_origin:
18005         case DW_AT_specification:
18006         case DW_AT_extension:
18007           has_specification = 1;
18008           spec_offset = dwarf2_get_ref_die_offset (&attr);
18009           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18010                                    || cu->per_cu->is_dwz);
18011           break;
18012         case DW_AT_sibling:
18013           /* Ignore absolute siblings, they might point outside of
18014              the current compile unit.  */
18015           if (attr.form == DW_FORM_ref_addr)
18016             complaint (_("ignoring absolute DW_AT_sibling"));
18017           else
18018             {
18019               const gdb_byte *buffer = reader->buffer;
18020               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18021               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18022
18023               if (sibling_ptr < info_ptr)
18024                 complaint (_("DW_AT_sibling points backwards"));
18025               else if (sibling_ptr > reader->buffer_end)
18026                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18027               else
18028                 sibling = sibling_ptr;
18029             }
18030           break;
18031         case DW_AT_byte_size:
18032           has_byte_size = 1;
18033           break;
18034         case DW_AT_const_value:
18035           has_const_value = 1;
18036           break;
18037         case DW_AT_calling_convention:
18038           /* DWARF doesn't provide a way to identify a program's source-level
18039              entry point.  DW_AT_calling_convention attributes are only meant
18040              to describe functions' calling conventions.
18041
18042              However, because it's a necessary piece of information in
18043              Fortran, and before DWARF 4 DW_CC_program was the only
18044              piece of debugging information whose definition refers to
18045              a 'main program' at all, several compilers marked Fortran
18046              main programs with DW_CC_program --- even when those
18047              functions use the standard calling conventions.
18048
18049              Although DWARF now specifies a way to provide this
18050              information, we support this practice for backward
18051              compatibility.  */
18052           if (DW_UNSND (&attr) == DW_CC_program
18053               && cu->language == language_fortran)
18054             main_subprogram = 1;
18055           break;
18056         case DW_AT_inline:
18057           if (DW_UNSND (&attr) == DW_INL_inlined
18058               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18059             may_be_inlined = 1;
18060           break;
18061
18062         case DW_AT_import:
18063           if (tag == DW_TAG_imported_unit)
18064             {
18065               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18066               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18067                                   || cu->per_cu->is_dwz);
18068             }
18069           break;
18070
18071         case DW_AT_main_subprogram:
18072           main_subprogram = DW_UNSND (&attr);
18073           break;
18074
18075         case DW_AT_ranges:
18076           {
18077             /* It would be nice to reuse dwarf2_get_pc_bounds here,
18078                but that requires a full DIE, so instead we just
18079                reimplement it.  */
18080             int need_ranges_base = tag != DW_TAG_compile_unit;
18081             unsigned int ranges_offset = (DW_UNSND (&attr)
18082                                           + (need_ranges_base
18083                                              ? cu->ranges_base
18084                                              : 0));
18085
18086             /* Value of the DW_AT_ranges attribute is the offset in the
18087                .debug_ranges section.  */
18088             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
18089                                     nullptr))
18090               has_pc_info = 1;
18091           }
18092           break;
18093
18094         default:
18095           break;
18096         }
18097     }
18098
18099   /* For Ada, if both the name and the linkage name appear, we prefer
18100      the latter.  This lets "catch exception" work better, regardless
18101      of the order in which the name and linkage name were emitted.
18102      Really, though, this is just a workaround for the fact that gdb
18103      doesn't store both the name and the linkage name.  */
18104   if (cu->language == language_ada && linkage_name != nullptr)
18105     name = linkage_name;
18106
18107   if (high_pc_relative)
18108     highpc += lowpc;
18109
18110   if (has_low_pc_attr && has_high_pc_attr)
18111     {
18112       /* When using the GNU linker, .gnu.linkonce. sections are used to
18113          eliminate duplicate copies of functions and vtables and such.
18114          The linker will arbitrarily choose one and discard the others.
18115          The AT_*_pc values for such functions refer to local labels in
18116          these sections.  If the section from that file was discarded, the
18117          labels are not in the output, so the relocs get a value of 0.
18118          If this is a discarded function, mark the pc bounds as invalid,
18119          so that GDB will ignore it.  */
18120       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18121         {
18122           struct objfile *objfile = dwarf2_per_objfile->objfile;
18123           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18124
18125           complaint (_("DW_AT_low_pc %s is zero "
18126                        "for DIE at %s [in module %s]"),
18127                      paddress (gdbarch, lowpc),
18128                      sect_offset_str (sect_off),
18129                      objfile_name (objfile));
18130         }
18131       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18132       else if (lowpc >= highpc)
18133         {
18134           struct objfile *objfile = dwarf2_per_objfile->objfile;
18135           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18136
18137           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18138                        "for DIE at %s [in module %s]"),
18139                      paddress (gdbarch, lowpc),
18140                      paddress (gdbarch, highpc),
18141                      sect_offset_str (sect_off),
18142                      objfile_name (objfile));
18143         }
18144       else
18145         has_pc_info = 1;
18146     }
18147
18148   return info_ptr;
18149 }
18150
18151 /* Find a cached partial DIE at OFFSET in CU.  */
18152
18153 struct partial_die_info *
18154 dwarf2_cu::find_partial_die (sect_offset sect_off)
18155 {
18156   struct partial_die_info *lookup_die = NULL;
18157   struct partial_die_info part_die (sect_off);
18158
18159   lookup_die = ((struct partial_die_info *)
18160                 htab_find_with_hash (partial_dies, &part_die,
18161                                      to_underlying (sect_off)));
18162
18163   return lookup_die;
18164 }
18165
18166 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18167    except in the case of .debug_types DIEs which do not reference
18168    outside their CU (they do however referencing other types via
18169    DW_FORM_ref_sig8).  */
18170
18171 static const struct cu_partial_die_info
18172 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18173 {
18174   struct dwarf2_per_objfile *dwarf2_per_objfile
18175     = cu->per_cu->dwarf2_per_objfile;
18176   struct objfile *objfile = dwarf2_per_objfile->objfile;
18177   struct dwarf2_per_cu_data *per_cu = NULL;
18178   struct partial_die_info *pd = NULL;
18179
18180   if (offset_in_dwz == cu->per_cu->is_dwz
18181       && cu->header.offset_in_cu_p (sect_off))
18182     {
18183       pd = cu->find_partial_die (sect_off);
18184       if (pd != NULL)
18185         return { cu, pd };
18186       /* We missed recording what we needed.
18187          Load all dies and try again.  */
18188       per_cu = cu->per_cu;
18189     }
18190   else
18191     {
18192       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18193       if (cu->per_cu->is_debug_types)
18194         {
18195           error (_("Dwarf Error: Type Unit at offset %s contains"
18196                    " external reference to offset %s [in module %s].\n"),
18197                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18198                  bfd_get_filename (objfile->obfd));
18199         }
18200       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18201                                                  dwarf2_per_objfile);
18202
18203       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18204         load_partial_comp_unit (per_cu);
18205
18206       per_cu->cu->last_used = 0;
18207       pd = per_cu->cu->find_partial_die (sect_off);
18208     }
18209
18210   /* If we didn't find it, and not all dies have been loaded,
18211      load them all and try again.  */
18212
18213   if (pd == NULL && per_cu->load_all_dies == 0)
18214     {
18215       per_cu->load_all_dies = 1;
18216
18217       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18218          THIS_CU->cu may already be in use.  So we can't just free it and
18219          replace its DIEs with the ones we read in.  Instead, we leave those
18220          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18221          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18222          set.  */
18223       load_partial_comp_unit (per_cu);
18224
18225       pd = per_cu->cu->find_partial_die (sect_off);
18226     }
18227
18228   if (pd == NULL)
18229     internal_error (__FILE__, __LINE__,
18230                     _("could not find partial DIE %s "
18231                       "in cache [from module %s]\n"),
18232                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18233   return { per_cu->cu, pd };
18234 }
18235
18236 /* See if we can figure out if the class lives in a namespace.  We do
18237    this by looking for a member function; its demangled name will
18238    contain namespace info, if there is any.  */
18239
18240 static void
18241 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18242                                   struct dwarf2_cu *cu)
18243 {
18244   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18245      what template types look like, because the demangler
18246      frequently doesn't give the same name as the debug info.  We
18247      could fix this by only using the demangled name to get the
18248      prefix (but see comment in read_structure_type).  */
18249
18250   struct partial_die_info *real_pdi;
18251   struct partial_die_info *child_pdi;
18252
18253   /* If this DIE (this DIE's specification, if any) has a parent, then
18254      we should not do this.  We'll prepend the parent's fully qualified
18255      name when we create the partial symbol.  */
18256
18257   real_pdi = struct_pdi;
18258   while (real_pdi->has_specification)
18259     {
18260       auto res = find_partial_die (real_pdi->spec_offset,
18261                                    real_pdi->spec_is_dwz, cu);
18262       real_pdi = res.pdi;
18263       cu = res.cu;
18264     }
18265
18266   if (real_pdi->die_parent != NULL)
18267     return;
18268
18269   for (child_pdi = struct_pdi->die_child;
18270        child_pdi != NULL;
18271        child_pdi = child_pdi->die_sibling)
18272     {
18273       if (child_pdi->tag == DW_TAG_subprogram
18274           && child_pdi->linkage_name != NULL)
18275         {
18276           gdb::unique_xmalloc_ptr<char> actual_class_name
18277             (language_class_name_from_physname (cu->language_defn,
18278                                                 child_pdi->linkage_name));
18279           if (actual_class_name != NULL)
18280             {
18281               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18282               struct_pdi->name
18283                 = obstack_strdup (&objfile->per_bfd->storage_obstack,
18284                                   actual_class_name.get ());
18285             }
18286           break;
18287         }
18288     }
18289 }
18290
18291 void
18292 partial_die_info::fixup (struct dwarf2_cu *cu)
18293 {
18294   /* Once we've fixed up a die, there's no point in doing so again.
18295      This also avoids a memory leak if we were to call
18296      guess_partial_die_structure_name multiple times.  */
18297   if (fixup_called)
18298     return;
18299
18300   /* If we found a reference attribute and the DIE has no name, try
18301      to find a name in the referred to DIE.  */
18302
18303   if (name == NULL && has_specification)
18304     {
18305       struct partial_die_info *spec_die;
18306
18307       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
18308       spec_die = res.pdi;
18309       cu = res.cu;
18310
18311       spec_die->fixup (cu);
18312
18313       if (spec_die->name)
18314         {
18315           name = spec_die->name;
18316
18317           /* Copy DW_AT_external attribute if it is set.  */
18318           if (spec_die->is_external)
18319             is_external = spec_die->is_external;
18320         }
18321     }
18322
18323   /* Set default names for some unnamed DIEs.  */
18324
18325   if (name == NULL && tag == DW_TAG_namespace)
18326     name = CP_ANONYMOUS_NAMESPACE_STR;
18327
18328   /* If there is no parent die to provide a namespace, and there are
18329      children, see if we can determine the namespace from their linkage
18330      name.  */
18331   if (cu->language == language_cplus
18332       && !cu->per_cu->dwarf2_per_objfile->types.empty ()
18333       && die_parent == NULL
18334       && has_children
18335       && (tag == DW_TAG_class_type
18336           || tag == DW_TAG_structure_type
18337           || tag == DW_TAG_union_type))
18338     guess_partial_die_structure_name (this, cu);
18339
18340   /* GCC might emit a nameless struct or union that has a linkage
18341      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18342   if (name == NULL
18343       && (tag == DW_TAG_class_type
18344           || tag == DW_TAG_interface_type
18345           || tag == DW_TAG_structure_type
18346           || tag == DW_TAG_union_type)
18347       && linkage_name != NULL)
18348     {
18349       gdb::unique_xmalloc_ptr<char> demangled
18350         (gdb_demangle (linkage_name, DMGL_TYPES));
18351       if (demangled != nullptr)
18352         {
18353           const char *base;
18354
18355           /* Strip any leading namespaces/classes, keep only the base name.
18356              DW_AT_name for named DIEs does not contain the prefixes.  */
18357           base = strrchr (demangled.get (), ':');
18358           if (base && base > demangled.get () && base[-1] == ':')
18359             base++;
18360           else
18361             base = demangled.get ();
18362
18363           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18364           name = obstack_strdup (&objfile->per_bfd->storage_obstack, base);
18365         }
18366     }
18367
18368   fixup_called = 1;
18369 }
18370
18371 /* Process the attributes that had to be skipped in the first round. These
18372    attributes are the ones that need str_offsets_base or addr_base attributes.
18373    They could not have been processed in the first round, because at the time
18374    the values of str_offsets_base or addr_base may not have been known.  */
18375 void read_attribute_reprocess (const struct die_reader_specs *reader,
18376                                struct attribute *attr)
18377 {
18378   struct dwarf2_cu *cu = reader->cu;
18379   switch (attr->form)
18380     {
18381       case DW_FORM_addrx:
18382       case DW_FORM_GNU_addr_index:
18383         DW_ADDR (attr) = read_addr_index (cu, DW_UNSND (attr));
18384         break;
18385       case DW_FORM_strx:
18386       case DW_FORM_strx1:
18387       case DW_FORM_strx2:
18388       case DW_FORM_strx3:
18389       case DW_FORM_strx4:
18390       case DW_FORM_GNU_str_index:
18391         {
18392           unsigned int str_index = DW_UNSND (attr);
18393           if (reader->dwo_file != NULL)
18394             {
18395               DW_STRING (attr) = read_dwo_str_index (reader, str_index);
18396               DW_STRING_IS_CANONICAL (attr) = 0;
18397             }
18398           else
18399             {
18400               DW_STRING (attr) = read_stub_str_index (cu, str_index);
18401               DW_STRING_IS_CANONICAL (attr) = 0;
18402             }
18403           break;
18404         }
18405       default:
18406         gdb_assert_not_reached (_("Unexpected DWARF form."));
18407     }
18408 }
18409
18410 /* Read an attribute value described by an attribute form.  */
18411
18412 static const gdb_byte *
18413 read_attribute_value (const struct die_reader_specs *reader,
18414                       struct attribute *attr, unsigned form,
18415                       LONGEST implicit_const, const gdb_byte *info_ptr,
18416                       bool *need_reprocess)
18417 {
18418   struct dwarf2_cu *cu = reader->cu;
18419   struct dwarf2_per_objfile *dwarf2_per_objfile
18420     = cu->per_cu->dwarf2_per_objfile;
18421   struct objfile *objfile = dwarf2_per_objfile->objfile;
18422   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18423   bfd *abfd = reader->abfd;
18424   struct comp_unit_head *cu_header = &cu->header;
18425   unsigned int bytes_read;
18426   struct dwarf_block *blk;
18427   *need_reprocess = false;
18428
18429   attr->form = (enum dwarf_form) form;
18430   switch (form)
18431     {
18432     case DW_FORM_ref_addr:
18433       if (cu->header.version == 2)
18434         DW_UNSND (attr) = cu->header.read_address (abfd, info_ptr,
18435                                                    &bytes_read);
18436       else
18437         DW_UNSND (attr) = cu->header.read_offset (abfd, info_ptr,
18438                                                   &bytes_read);
18439       info_ptr += bytes_read;
18440       break;
18441     case DW_FORM_GNU_ref_alt:
18442       DW_UNSND (attr) = cu->header.read_offset (abfd, info_ptr, &bytes_read);
18443       info_ptr += bytes_read;
18444       break;
18445     case DW_FORM_addr:
18446       DW_ADDR (attr) = cu->header.read_address (abfd, info_ptr, &bytes_read);
18447       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18448       info_ptr += bytes_read;
18449       break;
18450     case DW_FORM_block2:
18451       blk = dwarf_alloc_block (cu);
18452       blk->size = read_2_bytes (abfd, info_ptr);
18453       info_ptr += 2;
18454       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18455       info_ptr += blk->size;
18456       DW_BLOCK (attr) = blk;
18457       break;
18458     case DW_FORM_block4:
18459       blk = dwarf_alloc_block (cu);
18460       blk->size = read_4_bytes (abfd, info_ptr);
18461       info_ptr += 4;
18462       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18463       info_ptr += blk->size;
18464       DW_BLOCK (attr) = blk;
18465       break;
18466     case DW_FORM_data2:
18467       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18468       info_ptr += 2;
18469       break;
18470     case DW_FORM_data4:
18471       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18472       info_ptr += 4;
18473       break;
18474     case DW_FORM_data8:
18475       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18476       info_ptr += 8;
18477       break;
18478     case DW_FORM_data16:
18479       blk = dwarf_alloc_block (cu);
18480       blk->size = 16;
18481       blk->data = read_n_bytes (abfd, info_ptr, 16);
18482       info_ptr += 16;
18483       DW_BLOCK (attr) = blk;
18484       break;
18485     case DW_FORM_sec_offset:
18486       DW_UNSND (attr) = cu->header.read_offset (abfd, info_ptr, &bytes_read);
18487       info_ptr += bytes_read;
18488       break;
18489     case DW_FORM_string:
18490       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18491       DW_STRING_IS_CANONICAL (attr) = 0;
18492       info_ptr += bytes_read;
18493       break;
18494     case DW_FORM_strp:
18495       if (!cu->per_cu->is_dwz)
18496         {
18497           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18498                                                    abfd, info_ptr, cu_header,
18499                                                    &bytes_read);
18500           DW_STRING_IS_CANONICAL (attr) = 0;
18501           info_ptr += bytes_read;
18502           break;
18503         }
18504       /* FALLTHROUGH */
18505     case DW_FORM_line_strp:
18506       if (!cu->per_cu->is_dwz)
18507         {
18508           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18509                                                         abfd, info_ptr,
18510                                                         cu_header, &bytes_read);
18511           DW_STRING_IS_CANONICAL (attr) = 0;
18512           info_ptr += bytes_read;
18513           break;
18514         }
18515       /* FALLTHROUGH */
18516     case DW_FORM_GNU_strp_alt:
18517       {
18518         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18519         LONGEST str_offset = cu_header->read_offset (abfd, info_ptr,
18520                                                      &bytes_read);
18521
18522         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18523                                                           dwz, str_offset);
18524         DW_STRING_IS_CANONICAL (attr) = 0;
18525         info_ptr += bytes_read;
18526       }
18527       break;
18528     case DW_FORM_exprloc:
18529     case DW_FORM_block:
18530       blk = dwarf_alloc_block (cu);
18531       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18532       info_ptr += bytes_read;
18533       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18534       info_ptr += blk->size;
18535       DW_BLOCK (attr) = blk;
18536       break;
18537     case DW_FORM_block1:
18538       blk = dwarf_alloc_block (cu);
18539       blk->size = read_1_byte (abfd, info_ptr);
18540       info_ptr += 1;
18541       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18542       info_ptr += blk->size;
18543       DW_BLOCK (attr) = blk;
18544       break;
18545     case DW_FORM_data1:
18546       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18547       info_ptr += 1;
18548       break;
18549     case DW_FORM_flag:
18550       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18551       info_ptr += 1;
18552       break;
18553     case DW_FORM_flag_present:
18554       DW_UNSND (attr) = 1;
18555       break;
18556     case DW_FORM_sdata:
18557       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18558       info_ptr += bytes_read;
18559       break;
18560     case DW_FORM_udata:
18561     case DW_FORM_rnglistx:
18562       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18563       info_ptr += bytes_read;
18564       break;
18565     case DW_FORM_ref1:
18566       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18567                          + read_1_byte (abfd, info_ptr));
18568       info_ptr += 1;
18569       break;
18570     case DW_FORM_ref2:
18571       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18572                          + read_2_bytes (abfd, info_ptr));
18573       info_ptr += 2;
18574       break;
18575     case DW_FORM_ref4:
18576       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18577                          + read_4_bytes (abfd, info_ptr));
18578       info_ptr += 4;
18579       break;
18580     case DW_FORM_ref8:
18581       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18582                          + read_8_bytes (abfd, info_ptr));
18583       info_ptr += 8;
18584       break;
18585     case DW_FORM_ref_sig8:
18586       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
18587       info_ptr += 8;
18588       break;
18589     case DW_FORM_ref_udata:
18590       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18591                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
18592       info_ptr += bytes_read;
18593       break;
18594     case DW_FORM_indirect:
18595       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18596       info_ptr += bytes_read;
18597       if (form == DW_FORM_implicit_const)
18598         {
18599           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18600           info_ptr += bytes_read;
18601         }
18602       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
18603                                        info_ptr, need_reprocess);
18604       break;
18605     case DW_FORM_implicit_const:
18606       DW_SND (attr) = implicit_const;
18607       break;
18608     case DW_FORM_addrx:
18609     case DW_FORM_GNU_addr_index:
18610       *need_reprocess = true;
18611       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18612       info_ptr += bytes_read;
18613       break;
18614     case DW_FORM_strx:
18615     case DW_FORM_strx1:
18616     case DW_FORM_strx2:
18617     case DW_FORM_strx3:
18618     case DW_FORM_strx4:
18619     case DW_FORM_GNU_str_index:
18620       {
18621         ULONGEST str_index;
18622         if (form == DW_FORM_strx1)
18623           {
18624             str_index = read_1_byte (abfd, info_ptr);
18625             info_ptr += 1;
18626           }
18627         else if (form == DW_FORM_strx2)
18628           {
18629             str_index = read_2_bytes (abfd, info_ptr);
18630             info_ptr += 2;
18631           }
18632         else if (form == DW_FORM_strx3)
18633           {
18634             str_index = read_3_bytes (abfd, info_ptr);
18635             info_ptr += 3;
18636           }
18637         else if (form == DW_FORM_strx4)
18638           {
18639             str_index = read_4_bytes (abfd, info_ptr);
18640             info_ptr += 4;
18641           }
18642         else
18643           {
18644             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18645             info_ptr += bytes_read;
18646           }
18647         *need_reprocess = true;
18648          DW_UNSND (attr) = str_index;
18649         }
18650       break;
18651     default:
18652       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
18653              dwarf_form_name (form),
18654              bfd_get_filename (abfd));
18655     }
18656
18657   /* Super hack.  */
18658   if (cu->per_cu->is_dwz && attr->form_is_ref ())
18659     attr->form = DW_FORM_GNU_ref_alt;
18660
18661   /* We have seen instances where the compiler tried to emit a byte
18662      size attribute of -1 which ended up being encoded as an unsigned
18663      0xffffffff.  Although 0xffffffff is technically a valid size value,
18664      an object of this size seems pretty unlikely so we can relatively
18665      safely treat these cases as if the size attribute was invalid and
18666      treat them as zero by default.  */
18667   if (attr->name == DW_AT_byte_size
18668       && form == DW_FORM_data4
18669       && DW_UNSND (attr) >= 0xffffffff)
18670     {
18671       complaint
18672         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
18673          hex_string (DW_UNSND (attr)));
18674       DW_UNSND (attr) = 0;
18675     }
18676
18677   return info_ptr;
18678 }
18679
18680 /* Read an attribute described by an abbreviated attribute.  */
18681
18682 static const gdb_byte *
18683 read_attribute (const struct die_reader_specs *reader,
18684                 struct attribute *attr, struct attr_abbrev *abbrev,
18685                 const gdb_byte *info_ptr, bool *need_reprocess)
18686 {
18687   attr->name = abbrev->name;
18688   return read_attribute_value (reader, attr, abbrev->form,
18689                                abbrev->implicit_const, info_ptr,
18690                                need_reprocess);
18691 }
18692
18693 /* Cover function for read_initial_length.
18694    Returns the length of the object at BUF, and stores the size of the
18695    initial length in *BYTES_READ and stores the size that offsets will be in
18696    *OFFSET_SIZE.
18697    If the initial length size is not equivalent to that specified in
18698    CU_HEADER then issue a complaint.
18699    This is useful when reading non-comp-unit headers.  */
18700
18701 static LONGEST
18702 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
18703                                         const struct comp_unit_head *cu_header,
18704                                         unsigned int *bytes_read,
18705                                         unsigned int *offset_size)
18706 {
18707   LONGEST length = read_initial_length (abfd, buf, bytes_read);
18708
18709   gdb_assert (cu_header->initial_length_size == 4
18710               || cu_header->initial_length_size == 8
18711               || cu_header->initial_length_size == 12);
18712
18713   if (cu_header->initial_length_size != *bytes_read)
18714     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
18715
18716   *offset_size = (*bytes_read == 4) ? 4 : 8;
18717   return length;
18718 }
18719
18720 /* Return pointer to string at section SECT offset STR_OFFSET with error
18721    reporting strings FORM_NAME and SECT_NAME.  */
18722
18723 static const char *
18724 read_indirect_string_at_offset_from (struct objfile *objfile,
18725                                      bfd *abfd, LONGEST str_offset,
18726                                      struct dwarf2_section_info *sect,
18727                                      const char *form_name,
18728                                      const char *sect_name)
18729 {
18730   sect->read (objfile);
18731   if (sect->buffer == NULL)
18732     error (_("%s used without %s section [in module %s]"),
18733            form_name, sect_name, bfd_get_filename (abfd));
18734   if (str_offset >= sect->size)
18735     error (_("%s pointing outside of %s section [in module %s]"),
18736            form_name, sect_name, bfd_get_filename (abfd));
18737   gdb_assert (HOST_CHAR_BIT == 8);
18738   if (sect->buffer[str_offset] == '\0')
18739     return NULL;
18740   return (const char *) (sect->buffer + str_offset);
18741 }
18742
18743 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
18744
18745 static const char *
18746 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
18747                                 bfd *abfd, LONGEST str_offset)
18748 {
18749   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
18750                                               abfd, str_offset,
18751                                               &dwarf2_per_objfile->str,
18752                                               "DW_FORM_strp", ".debug_str");
18753 }
18754
18755 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
18756
18757 static const char *
18758 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
18759                                      bfd *abfd, LONGEST str_offset)
18760 {
18761   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
18762                                               abfd, str_offset,
18763                                               &dwarf2_per_objfile->line_str,
18764                                               "DW_FORM_line_strp",
18765                                               ".debug_line_str");
18766 }
18767
18768 /* Read a string at offset STR_OFFSET in the .debug_str section from
18769    the .dwz file DWZ.  Throw an error if the offset is too large.  If
18770    the string consists of a single NUL byte, return NULL; otherwise
18771    return a pointer to the string.  */
18772
18773 static const char *
18774 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
18775                                LONGEST str_offset)
18776 {
18777   dwz->str.read (objfile);
18778
18779   if (dwz->str.buffer == NULL)
18780     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
18781              "section [in module %s]"),
18782            bfd_get_filename (dwz->dwz_bfd.get ()));
18783   if (str_offset >= dwz->str.size)
18784     error (_("DW_FORM_GNU_strp_alt pointing outside of "
18785              ".debug_str section [in module %s]"),
18786            bfd_get_filename (dwz->dwz_bfd.get ()));
18787   gdb_assert (HOST_CHAR_BIT == 8);
18788   if (dwz->str.buffer[str_offset] == '\0')
18789     return NULL;
18790   return (const char *) (dwz->str.buffer + str_offset);
18791 }
18792
18793 /* Return pointer to string at .debug_str offset as read from BUF.
18794    BUF is assumed to be in a compilation unit described by CU_HEADER.
18795    Return *BYTES_READ_PTR count of bytes read from BUF.  */
18796
18797 static const char *
18798 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
18799                       const gdb_byte *buf,
18800                       const struct comp_unit_head *cu_header,
18801                       unsigned int *bytes_read_ptr)
18802 {
18803   LONGEST str_offset = cu_header->read_offset (abfd, buf, bytes_read_ptr);
18804
18805   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
18806 }
18807
18808 /* Return pointer to string at .debug_line_str offset as read from BUF.
18809    BUF is assumed to be in a compilation unit described by CU_HEADER.
18810    Return *BYTES_READ_PTR count of bytes read from BUF.  */
18811
18812 static const char *
18813 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
18814                            bfd *abfd, const gdb_byte *buf,
18815                            const struct comp_unit_head *cu_header,
18816                            unsigned int *bytes_read_ptr)
18817 {
18818   LONGEST str_offset = cu_header->read_offset (abfd, buf, bytes_read_ptr);
18819
18820   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
18821                                               str_offset);
18822 }
18823
18824 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
18825    ADDR_BASE is the DW_AT_addr_base (DW_AT_GNU_addr_base) attribute or zero.
18826    ADDR_SIZE is the size of addresses from the CU header.  */
18827
18828 static CORE_ADDR
18829 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
18830                    unsigned int addr_index, gdb::optional<ULONGEST> addr_base,
18831                    int addr_size)
18832 {
18833   struct objfile *objfile = dwarf2_per_objfile->objfile;
18834   bfd *abfd = objfile->obfd;
18835   const gdb_byte *info_ptr;
18836   ULONGEST addr_base_or_zero = addr_base.has_value () ? *addr_base : 0;
18837
18838   dwarf2_per_objfile->addr.read (objfile);
18839   if (dwarf2_per_objfile->addr.buffer == NULL)
18840     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
18841            objfile_name (objfile));
18842   if (addr_base_or_zero + addr_index * addr_size
18843       >= dwarf2_per_objfile->addr.size)
18844     error (_("DW_FORM_addr_index pointing outside of "
18845              ".debug_addr section [in module %s]"),
18846            objfile_name (objfile));
18847   info_ptr = (dwarf2_per_objfile->addr.buffer
18848               + addr_base_or_zero + addr_index * addr_size);
18849   if (addr_size == 4)
18850     return bfd_get_32 (abfd, info_ptr);
18851   else
18852     return bfd_get_64 (abfd, info_ptr);
18853 }
18854
18855 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
18856
18857 static CORE_ADDR
18858 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
18859 {
18860   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
18861                             cu->addr_base, cu->header.addr_size);
18862 }
18863
18864 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
18865
18866 static CORE_ADDR
18867 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
18868                              unsigned int *bytes_read)
18869 {
18870   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
18871   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
18872
18873   return read_addr_index (cu, addr_index);
18874 }
18875
18876 /* Given an index in .debug_addr, fetch the value.
18877    NOTE: This can be called during dwarf expression evaluation,
18878    long after the debug information has been read, and thus per_cu->cu
18879    may no longer exist.  */
18880
18881 CORE_ADDR
18882 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
18883                         unsigned int addr_index)
18884 {
18885   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
18886   struct dwarf2_cu *cu = per_cu->cu;
18887   gdb::optional<ULONGEST> addr_base;
18888   int addr_size;
18889
18890   /* We need addr_base and addr_size.
18891      If we don't have PER_CU->cu, we have to get it.
18892      Nasty, but the alternative is storing the needed info in PER_CU,
18893      which at this point doesn't seem justified: it's not clear how frequently
18894      it would get used and it would increase the size of every PER_CU.
18895      Entry points like dwarf2_per_cu_addr_size do a similar thing
18896      so we're not in uncharted territory here.
18897      Alas we need to be a bit more complicated as addr_base is contained
18898      in the DIE.
18899
18900      We don't need to read the entire CU(/TU).
18901      We just need the header and top level die.
18902
18903      IWBN to use the aging mechanism to let us lazily later discard the CU.
18904      For now we skip this optimization.  */
18905
18906   if (cu != NULL)
18907     {
18908       addr_base = cu->addr_base;
18909       addr_size = cu->header.addr_size;
18910     }
18911   else
18912     {
18913       cutu_reader reader (per_cu, NULL, 0, false);
18914       addr_base = reader.cu->addr_base;
18915       addr_size = reader.cu->header.addr_size;
18916     }
18917
18918   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
18919                             addr_size);
18920 }
18921
18922 /* Given a DW_FORM_GNU_str_index value STR_INDEX, fetch the string.
18923    STR_SECTION, STR_OFFSETS_SECTION can be from a Fission stub or a
18924    DWO file.  */
18925
18926 static const char *
18927 read_str_index (struct dwarf2_cu *cu,
18928                 struct dwarf2_section_info *str_section,
18929                 struct dwarf2_section_info *str_offsets_section,
18930                 ULONGEST str_offsets_base, ULONGEST str_index)
18931 {
18932   struct dwarf2_per_objfile *dwarf2_per_objfile
18933     = cu->per_cu->dwarf2_per_objfile;
18934   struct objfile *objfile = dwarf2_per_objfile->objfile;
18935   const char *objf_name = objfile_name (objfile);
18936   bfd *abfd = objfile->obfd;
18937   const gdb_byte *info_ptr;
18938   ULONGEST str_offset;
18939   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
18940
18941   str_section->read (objfile);
18942   str_offsets_section->read (objfile);
18943   if (str_section->buffer == NULL)
18944     error (_("%s used without %s section"
18945              " in CU at offset %s [in module %s]"),
18946            form_name, str_section->get_name (),
18947            sect_offset_str (cu->header.sect_off), objf_name);
18948   if (str_offsets_section->buffer == NULL)
18949     error (_("%s used without %s section"
18950              " in CU at offset %s [in module %s]"),
18951            form_name, str_section->get_name (),
18952            sect_offset_str (cu->header.sect_off), objf_name);
18953   info_ptr = (str_offsets_section->buffer
18954               + str_offsets_base
18955               + str_index * cu->header.offset_size);
18956   if (cu->header.offset_size == 4)
18957     str_offset = bfd_get_32 (abfd, info_ptr);
18958   else
18959     str_offset = bfd_get_64 (abfd, info_ptr);
18960   if (str_offset >= str_section->size)
18961     error (_("Offset from %s pointing outside of"
18962              " .debug_str.dwo section in CU at offset %s [in module %s]"),
18963            form_name, sect_offset_str (cu->header.sect_off), objf_name);
18964   return (const char *) (str_section->buffer + str_offset);
18965 }
18966
18967 /* Given a DW_FORM_GNU_str_index from a DWO file, fetch the string.  */
18968
18969 static const char *
18970 read_dwo_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
18971 {
18972   ULONGEST str_offsets_base = reader->cu->header.version >= 5
18973                               ? reader->cu->header.addr_size : 0;
18974   return read_str_index (reader->cu,
18975                          &reader->dwo_file->sections.str,
18976                          &reader->dwo_file->sections.str_offsets,
18977                          str_offsets_base, str_index);
18978 }
18979
18980 /* Given a DW_FORM_GNU_str_index from a Fission stub, fetch the string.  */
18981
18982 static const char *
18983 read_stub_str_index (struct dwarf2_cu *cu, ULONGEST str_index)
18984 {
18985   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18986   const char *objf_name = objfile_name (objfile);
18987   static const char form_name[] = "DW_FORM_GNU_str_index";
18988   static const char str_offsets_attr_name[] = "DW_AT_str_offsets";
18989
18990   if (!cu->str_offsets_base.has_value ())
18991     error (_("%s used in Fission stub without %s"
18992              " in CU at offset 0x%lx [in module %s]"),
18993            form_name, str_offsets_attr_name,
18994            (long) cu->header.offset_size, objf_name);
18995
18996   return read_str_index (cu,
18997                          &cu->per_cu->dwarf2_per_objfile->str,
18998                          &cu->per_cu->dwarf2_per_objfile->str_offsets,
18999                          *cu->str_offsets_base, str_index);
19000 }
19001
19002 /* Return the length of an LEB128 number in BUF.  */
19003
19004 static int
19005 leb128_size (const gdb_byte *buf)
19006 {
19007   const gdb_byte *begin = buf;
19008   gdb_byte byte;
19009
19010   while (1)
19011     {
19012       byte = *buf++;
19013       if ((byte & 128) == 0)
19014         return buf - begin;
19015     }
19016 }
19017
19018 static void
19019 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19020 {
19021   switch (lang)
19022     {
19023     case DW_LANG_C89:
19024     case DW_LANG_C99:
19025     case DW_LANG_C11:
19026     case DW_LANG_C:
19027     case DW_LANG_UPC:
19028       cu->language = language_c;
19029       break;
19030     case DW_LANG_Java:
19031     case DW_LANG_C_plus_plus:
19032     case DW_LANG_C_plus_plus_11:
19033     case DW_LANG_C_plus_plus_14:
19034       cu->language = language_cplus;
19035       break;
19036     case DW_LANG_D:
19037       cu->language = language_d;
19038       break;
19039     case DW_LANG_Fortran77:
19040     case DW_LANG_Fortran90:
19041     case DW_LANG_Fortran95:
19042     case DW_LANG_Fortran03:
19043     case DW_LANG_Fortran08:
19044       cu->language = language_fortran;
19045       break;
19046     case DW_LANG_Go:
19047       cu->language = language_go;
19048       break;
19049     case DW_LANG_Mips_Assembler:
19050       cu->language = language_asm;
19051       break;
19052     case DW_LANG_Ada83:
19053     case DW_LANG_Ada95:
19054       cu->language = language_ada;
19055       break;
19056     case DW_LANG_Modula2:
19057       cu->language = language_m2;
19058       break;
19059     case DW_LANG_Pascal83:
19060       cu->language = language_pascal;
19061       break;
19062     case DW_LANG_ObjC:
19063       cu->language = language_objc;
19064       break;
19065     case DW_LANG_Rust:
19066     case DW_LANG_Rust_old:
19067       cu->language = language_rust;
19068       break;
19069     case DW_LANG_Cobol74:
19070     case DW_LANG_Cobol85:
19071     default:
19072       cu->language = language_minimal;
19073       break;
19074     }
19075   cu->language_defn = language_def (cu->language);
19076 }
19077
19078 /* Return the named attribute or NULL if not there.  */
19079
19080 static struct attribute *
19081 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19082 {
19083   for (;;)
19084     {
19085       unsigned int i;
19086       struct attribute *spec = NULL;
19087
19088       for (i = 0; i < die->num_attrs; ++i)
19089         {
19090           if (die->attrs[i].name == name)
19091             return &die->attrs[i];
19092           if (die->attrs[i].name == DW_AT_specification
19093               || die->attrs[i].name == DW_AT_abstract_origin)
19094             spec = &die->attrs[i];
19095         }
19096
19097       if (!spec)
19098         break;
19099
19100       die = follow_die_ref (die, spec, &cu);
19101     }
19102
19103   return NULL;
19104 }
19105
19106 /* Return the named attribute or NULL if not there,
19107    but do not follow DW_AT_specification, etc.
19108    This is for use in contexts where we're reading .debug_types dies.
19109    Following DW_AT_specification, DW_AT_abstract_origin will take us
19110    back up the chain, and we want to go down.  */
19111
19112 static struct attribute *
19113 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19114 {
19115   unsigned int i;
19116
19117   for (i = 0; i < die->num_attrs; ++i)
19118     if (die->attrs[i].name == name)
19119       return &die->attrs[i];
19120
19121   return NULL;
19122 }
19123
19124 /* Return the string associated with a string-typed attribute, or NULL if it
19125    is either not found or is of an incorrect type.  */
19126
19127 static const char *
19128 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19129 {
19130   struct attribute *attr;
19131   const char *str = NULL;
19132
19133   attr = dwarf2_attr (die, name, cu);
19134
19135   if (attr != NULL)
19136     {
19137       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19138           || attr->form == DW_FORM_string
19139           || attr->form == DW_FORM_strx
19140           || attr->form == DW_FORM_strx1
19141           || attr->form == DW_FORM_strx2
19142           || attr->form == DW_FORM_strx3
19143           || attr->form == DW_FORM_strx4
19144           || attr->form == DW_FORM_GNU_str_index
19145           || attr->form == DW_FORM_GNU_strp_alt)
19146         str = DW_STRING (attr);
19147       else
19148         complaint (_("string type expected for attribute %s for "
19149                      "DIE at %s in module %s"),
19150                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19151                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19152     }
19153
19154   return str;
19155 }
19156
19157 /* Return the dwo name or NULL if not present. If present, it is in either
19158    DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.  */
19159 static const char *
19160 dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu)
19161 {
19162   const char *dwo_name = dwarf2_string_attr (die, DW_AT_GNU_dwo_name, cu);
19163   if (dwo_name == nullptr)
19164     dwo_name = dwarf2_string_attr (die, DW_AT_dwo_name, cu);
19165   return dwo_name;
19166 }
19167
19168 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19169    and holds a non-zero value.  This function should only be used for
19170    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19171
19172 static int
19173 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19174 {
19175   struct attribute *attr = dwarf2_attr (die, name, cu);
19176
19177   return (attr && DW_UNSND (attr));
19178 }
19179
19180 static int
19181 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19182 {
19183   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19184      which value is non-zero.  However, we have to be careful with
19185      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19186      (via dwarf2_flag_true_p) follows this attribute.  So we may
19187      end up accidently finding a declaration attribute that belongs
19188      to a different DIE referenced by the specification attribute,
19189      even though the given DIE does not have a declaration attribute.  */
19190   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19191           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19192 }
19193
19194 /* Return the die giving the specification for DIE, if there is
19195    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19196    containing the return value on output.  If there is no
19197    specification, but there is an abstract origin, that is
19198    returned.  */
19199
19200 static struct die_info *
19201 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19202 {
19203   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19204                                              *spec_cu);
19205
19206   if (spec_attr == NULL)
19207     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19208
19209   if (spec_attr == NULL)
19210     return NULL;
19211   else
19212     return follow_die_ref (die, spec_attr, spec_cu);
19213 }
19214
19215 /* Stub for free_line_header to match void * callback types.  */
19216
19217 static void
19218 free_line_header_voidp (void *arg)
19219 {
19220   struct line_header *lh = (struct line_header *) arg;
19221
19222   delete lh;
19223 }
19224
19225 /* A convenience function to find the proper .debug_line section for a CU.  */
19226
19227 static struct dwarf2_section_info *
19228 get_debug_line_section (struct dwarf2_cu *cu)
19229 {
19230   struct dwarf2_section_info *section;
19231   struct dwarf2_per_objfile *dwarf2_per_objfile
19232     = cu->per_cu->dwarf2_per_objfile;
19233
19234   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19235      DWO file.  */
19236   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19237     section = &cu->dwo_unit->dwo_file->sections.line;
19238   else if (cu->per_cu->is_dwz)
19239     {
19240       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19241
19242       section = &dwz->line;
19243     }
19244   else
19245     section = &dwarf2_per_objfile->line;
19246
19247   return section;
19248 }
19249
19250 /* Read directory or file name entry format, starting with byte of
19251    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19252    entries count and the entries themselves in the described entry
19253    format.  */
19254
19255 static void
19256 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19257                         bfd *abfd, const gdb_byte **bufp,
19258                         struct line_header *lh,
19259                         const struct comp_unit_head *cu_header,
19260                         void (*callback) (struct line_header *lh,
19261                                           const char *name,
19262                                           dir_index d_index,
19263                                           unsigned int mod_time,
19264                                           unsigned int length))
19265 {
19266   gdb_byte format_count, formati;
19267   ULONGEST data_count, datai;
19268   const gdb_byte *buf = *bufp;
19269   const gdb_byte *format_header_data;
19270   unsigned int bytes_read;
19271
19272   format_count = read_1_byte (abfd, buf);
19273   buf += 1;
19274   format_header_data = buf;
19275   for (formati = 0; formati < format_count; formati++)
19276     {
19277       read_unsigned_leb128 (abfd, buf, &bytes_read);
19278       buf += bytes_read;
19279       read_unsigned_leb128 (abfd, buf, &bytes_read);
19280       buf += bytes_read;
19281     }
19282
19283   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19284   buf += bytes_read;
19285   for (datai = 0; datai < data_count; datai++)
19286     {
19287       const gdb_byte *format = format_header_data;
19288       struct file_entry fe;
19289
19290       for (formati = 0; formati < format_count; formati++)
19291         {
19292           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19293           format += bytes_read;
19294
19295           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19296           format += bytes_read;
19297
19298           gdb::optional<const char *> string;
19299           gdb::optional<unsigned int> uint;
19300
19301           switch (form)
19302             {
19303             case DW_FORM_string:
19304               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19305               buf += bytes_read;
19306               break;
19307
19308             case DW_FORM_line_strp:
19309               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
19310                                                          abfd, buf,
19311                                                          cu_header,
19312                                                          &bytes_read));
19313               buf += bytes_read;
19314               break;
19315
19316             case DW_FORM_data1:
19317               uint.emplace (read_1_byte (abfd, buf));
19318               buf += 1;
19319               break;
19320
19321             case DW_FORM_data2:
19322               uint.emplace (read_2_bytes (abfd, buf));
19323               buf += 2;
19324               break;
19325
19326             case DW_FORM_data4:
19327               uint.emplace (read_4_bytes (abfd, buf));
19328               buf += 4;
19329               break;
19330
19331             case DW_FORM_data8:
19332               uint.emplace (read_8_bytes (abfd, buf));
19333               buf += 8;
19334               break;
19335
19336             case DW_FORM_data16:
19337               /*  This is used for MD5, but file_entry does not record MD5s. */
19338               buf += 16;
19339               break;
19340
19341             case DW_FORM_udata:
19342               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
19343               buf += bytes_read;
19344               break;
19345
19346             case DW_FORM_block:
19347               /* It is valid only for DW_LNCT_timestamp which is ignored by
19348                  current GDB.  */
19349               break;
19350             }
19351
19352           switch (content_type)
19353             {
19354             case DW_LNCT_path:
19355               if (string.has_value ())
19356                 fe.name = *string;
19357               break;
19358             case DW_LNCT_directory_index:
19359               if (uint.has_value ())
19360                 fe.d_index = (dir_index) *uint;
19361               break;
19362             case DW_LNCT_timestamp:
19363               if (uint.has_value ())
19364                 fe.mod_time = *uint;
19365               break;
19366             case DW_LNCT_size:
19367               if (uint.has_value ())
19368                 fe.length = *uint;
19369               break;
19370             case DW_LNCT_MD5:
19371               break;
19372             default:
19373               complaint (_("Unknown format content type %s"),
19374                          pulongest (content_type));
19375             }
19376         }
19377
19378       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
19379     }
19380
19381   *bufp = buf;
19382 }
19383
19384 /* Read the statement program header starting at OFFSET in
19385    .debug_line, or .debug_line.dwo.  Return a pointer
19386    to a struct line_header, allocated using xmalloc.
19387    Returns NULL if there is a problem reading the header, e.g., if it
19388    has a version we don't understand.
19389
19390    NOTE: the strings in the include directory and file name tables of
19391    the returned object point into the dwarf line section buffer,
19392    and must not be freed.  */
19393
19394 static line_header_up
19395 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
19396 {
19397   const gdb_byte *line_ptr;
19398   unsigned int bytes_read, offset_size;
19399   int i;
19400   const char *cur_dir, *cur_file;
19401   struct dwarf2_section_info *section;
19402   bfd *abfd;
19403   struct dwarf2_per_objfile *dwarf2_per_objfile
19404     = cu->per_cu->dwarf2_per_objfile;
19405
19406   section = get_debug_line_section (cu);
19407   section->read (dwarf2_per_objfile->objfile);
19408   if (section->buffer == NULL)
19409     {
19410       if (cu->dwo_unit && cu->per_cu->is_debug_types)
19411         complaint (_("missing .debug_line.dwo section"));
19412       else
19413         complaint (_("missing .debug_line section"));
19414       return 0;
19415     }
19416
19417   /* We can't do this until we know the section is non-empty.
19418      Only then do we know we have such a section.  */
19419   abfd = section->get_bfd_owner ();
19420
19421   /* Make sure that at least there's room for the total_length field.
19422      That could be 12 bytes long, but we're just going to fudge that.  */
19423   if (to_underlying (sect_off) + 4 >= section->size)
19424     {
19425       dwarf2_statement_list_fits_in_line_number_section_complaint ();
19426       return 0;
19427     }
19428
19429   line_header_up lh (new line_header ());
19430
19431   lh->sect_off = sect_off;
19432   lh->offset_in_dwz = cu->per_cu->is_dwz;
19433
19434   line_ptr = section->buffer + to_underlying (sect_off);
19435
19436   /* Read in the header.  */
19437   lh->total_length =
19438     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
19439                                             &bytes_read, &offset_size);
19440   line_ptr += bytes_read;
19441
19442   const gdb_byte *start_here = line_ptr;
19443
19444   if (line_ptr + lh->total_length > (section->buffer + section->size))
19445     {
19446       dwarf2_statement_list_fits_in_line_number_section_complaint ();
19447       return 0;
19448     }
19449   lh->statement_program_end = start_here + lh->total_length;
19450   lh->version = read_2_bytes (abfd, line_ptr);
19451   line_ptr += 2;
19452   if (lh->version > 5)
19453     {
19454       /* This is a version we don't understand.  The format could have
19455          changed in ways we don't handle properly so just punt.  */
19456       complaint (_("unsupported version in .debug_line section"));
19457       return NULL;
19458     }
19459   if (lh->version >= 5)
19460     {
19461       gdb_byte segment_selector_size;
19462
19463       /* Skip address size.  */
19464       read_1_byte (abfd, line_ptr);
19465       line_ptr += 1;
19466
19467       segment_selector_size = read_1_byte (abfd, line_ptr);
19468       line_ptr += 1;
19469       if (segment_selector_size != 0)
19470         {
19471           complaint (_("unsupported segment selector size %u "
19472                        "in .debug_line section"),
19473                      segment_selector_size);
19474           return NULL;
19475         }
19476     }
19477   lh->header_length = read_offset (abfd, line_ptr, offset_size);
19478   line_ptr += offset_size;
19479   lh->statement_program_start = line_ptr + lh->header_length;
19480   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
19481   line_ptr += 1;
19482   if (lh->version >= 4)
19483     {
19484       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
19485       line_ptr += 1;
19486     }
19487   else
19488     lh->maximum_ops_per_instruction = 1;
19489
19490   if (lh->maximum_ops_per_instruction == 0)
19491     {
19492       lh->maximum_ops_per_instruction = 1;
19493       complaint (_("invalid maximum_ops_per_instruction "
19494                    "in `.debug_line' section"));
19495     }
19496
19497   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
19498   line_ptr += 1;
19499   lh->line_base = read_1_signed_byte (abfd, line_ptr);
19500   line_ptr += 1;
19501   lh->line_range = read_1_byte (abfd, line_ptr);
19502   line_ptr += 1;
19503   lh->opcode_base = read_1_byte (abfd, line_ptr);
19504   line_ptr += 1;
19505   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
19506
19507   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
19508   for (i = 1; i < lh->opcode_base; ++i)
19509     {
19510       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
19511       line_ptr += 1;
19512     }
19513
19514   if (lh->version >= 5)
19515     {
19516       /* Read directory table.  */
19517       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
19518                               &cu->header,
19519                               [] (struct line_header *header, const char *name,
19520                                   dir_index d_index, unsigned int mod_time,
19521                                   unsigned int length)
19522         {
19523           header->add_include_dir (name);
19524         });
19525
19526       /* Read file name table.  */
19527       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
19528                               &cu->header,
19529                               [] (struct line_header *header, const char *name,
19530                                   dir_index d_index, unsigned int mod_time,
19531                                   unsigned int length)
19532         {
19533           header->add_file_name (name, d_index, mod_time, length);
19534         });
19535     }
19536   else
19537     {
19538       /* Read directory table.  */
19539       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
19540         {
19541           line_ptr += bytes_read;
19542           lh->add_include_dir (cur_dir);
19543         }
19544       line_ptr += bytes_read;
19545
19546       /* Read file name table.  */
19547       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
19548         {
19549           unsigned int mod_time, length;
19550           dir_index d_index;
19551
19552           line_ptr += bytes_read;
19553           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19554           line_ptr += bytes_read;
19555           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19556           line_ptr += bytes_read;
19557           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19558           line_ptr += bytes_read;
19559
19560           lh->add_file_name (cur_file, d_index, mod_time, length);
19561         }
19562       line_ptr += bytes_read;
19563     }
19564
19565   if (line_ptr > (section->buffer + section->size))
19566     complaint (_("line number info header doesn't "
19567                  "fit in `.debug_line' section"));
19568
19569   return lh;
19570 }
19571
19572 /* Subroutine of dwarf_decode_lines to simplify it.
19573    Return the file name of the psymtab for the given file_entry.
19574    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19575    If space for the result is malloc'd, *NAME_HOLDER will be set.
19576    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
19577
19578 static const char *
19579 psymtab_include_file_name (const struct line_header *lh, const file_entry &fe,
19580                            const dwarf2_psymtab *pst,
19581                            const char *comp_dir,
19582                            gdb::unique_xmalloc_ptr<char> *name_holder)
19583 {
19584   const char *include_name = fe.name;
19585   const char *include_name_to_compare = include_name;
19586   const char *pst_filename;
19587   int file_is_pst;
19588
19589   const char *dir_name = fe.include_dir (lh);
19590
19591   gdb::unique_xmalloc_ptr<char> hold_compare;
19592   if (!IS_ABSOLUTE_PATH (include_name)
19593       && (dir_name != NULL || comp_dir != NULL))
19594     {
19595       /* Avoid creating a duplicate psymtab for PST.
19596          We do this by comparing INCLUDE_NAME and PST_FILENAME.
19597          Before we do the comparison, however, we need to account
19598          for DIR_NAME and COMP_DIR.
19599          First prepend dir_name (if non-NULL).  If we still don't
19600          have an absolute path prepend comp_dir (if non-NULL).
19601          However, the directory we record in the include-file's
19602          psymtab does not contain COMP_DIR (to match the
19603          corresponding symtab(s)).
19604
19605          Example:
19606
19607          bash$ cd /tmp
19608          bash$ gcc -g ./hello.c
19609          include_name = "hello.c"
19610          dir_name = "."
19611          DW_AT_comp_dir = comp_dir = "/tmp"
19612          DW_AT_name = "./hello.c"
19613
19614       */
19615
19616       if (dir_name != NULL)
19617         {
19618           name_holder->reset (concat (dir_name, SLASH_STRING,
19619                                       include_name, (char *) NULL));
19620           include_name = name_holder->get ();
19621           include_name_to_compare = include_name;
19622         }
19623       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
19624         {
19625           hold_compare.reset (concat (comp_dir, SLASH_STRING,
19626                                       include_name, (char *) NULL));
19627           include_name_to_compare = hold_compare.get ();
19628         }
19629     }
19630
19631   pst_filename = pst->filename;
19632   gdb::unique_xmalloc_ptr<char> copied_name;
19633   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
19634     {
19635       copied_name.reset (concat (pst->dirname, SLASH_STRING,
19636                                  pst_filename, (char *) NULL));
19637       pst_filename = copied_name.get ();
19638     }
19639
19640   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
19641
19642   if (file_is_pst)
19643     return NULL;
19644   return include_name;
19645 }
19646
19647 /* State machine to track the state of the line number program.  */
19648
19649 class lnp_state_machine
19650 {
19651 public:
19652   /* Initialize a machine state for the start of a line number
19653      program.  */
19654   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
19655                      bool record_lines_p);
19656
19657   file_entry *current_file ()
19658   {
19659     /* lh->file_names is 0-based, but the file name numbers in the
19660        statement program are 1-based.  */
19661     return m_line_header->file_name_at (m_file);
19662   }
19663
19664   /* Record the line in the state machine.  END_SEQUENCE is true if
19665      we're processing the end of a sequence.  */
19666   void record_line (bool end_sequence);
19667
19668   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
19669      nop-out rest of the lines in this sequence.  */
19670   void check_line_address (struct dwarf2_cu *cu,
19671                            const gdb_byte *line_ptr,
19672                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
19673
19674   void handle_set_discriminator (unsigned int discriminator)
19675   {
19676     m_discriminator = discriminator;
19677     m_line_has_non_zero_discriminator |= discriminator != 0;
19678   }
19679
19680   /* Handle DW_LNE_set_address.  */
19681   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
19682   {
19683     m_op_index = 0;
19684     address += baseaddr;
19685     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
19686   }
19687
19688   /* Handle DW_LNS_advance_pc.  */
19689   void handle_advance_pc (CORE_ADDR adjust);
19690
19691   /* Handle a special opcode.  */
19692   void handle_special_opcode (unsigned char op_code);
19693
19694   /* Handle DW_LNS_advance_line.  */
19695   void handle_advance_line (int line_delta)
19696   {
19697     advance_line (line_delta);
19698   }
19699
19700   /* Handle DW_LNS_set_file.  */
19701   void handle_set_file (file_name_index file);
19702
19703   /* Handle DW_LNS_negate_stmt.  */
19704   void handle_negate_stmt ()
19705   {
19706     m_is_stmt = !m_is_stmt;
19707   }
19708
19709   /* Handle DW_LNS_const_add_pc.  */
19710   void handle_const_add_pc ();
19711
19712   /* Handle DW_LNS_fixed_advance_pc.  */
19713   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
19714   {
19715     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19716     m_op_index = 0;
19717   }
19718
19719   /* Handle DW_LNS_copy.  */
19720   void handle_copy ()
19721   {
19722     record_line (false);
19723     m_discriminator = 0;
19724   }
19725
19726   /* Handle DW_LNE_end_sequence.  */
19727   void handle_end_sequence ()
19728   {
19729     m_currently_recording_lines = true;
19730   }
19731
19732 private:
19733   /* Advance the line by LINE_DELTA.  */
19734   void advance_line (int line_delta)
19735   {
19736     m_line += line_delta;
19737
19738     if (line_delta != 0)
19739       m_line_has_non_zero_discriminator = m_discriminator != 0;
19740   }
19741
19742   struct dwarf2_cu *m_cu;
19743
19744   gdbarch *m_gdbarch;
19745
19746   /* True if we're recording lines.
19747      Otherwise we're building partial symtabs and are just interested in
19748      finding include files mentioned by the line number program.  */
19749   bool m_record_lines_p;
19750
19751   /* The line number header.  */
19752   line_header *m_line_header;
19753
19754   /* These are part of the standard DWARF line number state machine,
19755      and initialized according to the DWARF spec.  */
19756
19757   unsigned char m_op_index = 0;
19758   /* The line table index of the current file.  */
19759   file_name_index m_file = 1;
19760   unsigned int m_line = 1;
19761
19762   /* These are initialized in the constructor.  */
19763
19764   CORE_ADDR m_address;
19765   bool m_is_stmt;
19766   unsigned int m_discriminator;
19767
19768   /* Additional bits of state we need to track.  */
19769
19770   /* The last file that we called dwarf2_start_subfile for.
19771      This is only used for TLLs.  */
19772   unsigned int m_last_file = 0;
19773   /* The last file a line number was recorded for.  */
19774   struct subfile *m_last_subfile = NULL;
19775
19776   /* When true, record the lines we decode.  */
19777   bool m_currently_recording_lines = false;
19778
19779   /* The last line number that was recorded, used to coalesce
19780      consecutive entries for the same line.  This can happen, for
19781      example, when discriminators are present.  PR 17276.  */
19782   unsigned int m_last_line = 0;
19783   bool m_line_has_non_zero_discriminator = false;
19784 };
19785
19786 void
19787 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
19788 {
19789   CORE_ADDR addr_adj = (((m_op_index + adjust)
19790                          / m_line_header->maximum_ops_per_instruction)
19791                         * m_line_header->minimum_instruction_length);
19792   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19793   m_op_index = ((m_op_index + adjust)
19794                 % m_line_header->maximum_ops_per_instruction);
19795 }
19796
19797 void
19798 lnp_state_machine::handle_special_opcode (unsigned char op_code)
19799 {
19800   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
19801   unsigned char adj_opcode_d = adj_opcode / m_line_header->line_range;
19802   unsigned char adj_opcode_r = adj_opcode % m_line_header->line_range;
19803   CORE_ADDR addr_adj = (((m_op_index + adj_opcode_d)
19804                          / m_line_header->maximum_ops_per_instruction)
19805                         * m_line_header->minimum_instruction_length);
19806   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19807   m_op_index = ((m_op_index + adj_opcode_d)
19808                 % m_line_header->maximum_ops_per_instruction);
19809
19810   int line_delta = m_line_header->line_base + adj_opcode_r;
19811   advance_line (line_delta);
19812   record_line (false);
19813   m_discriminator = 0;
19814 }
19815
19816 void
19817 lnp_state_machine::handle_set_file (file_name_index file)
19818 {
19819   m_file = file;
19820
19821   const file_entry *fe = current_file ();
19822   if (fe == NULL)
19823     dwarf2_debug_line_missing_file_complaint ();
19824   else if (m_record_lines_p)
19825     {
19826       const char *dir = fe->include_dir (m_line_header);
19827
19828       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
19829       m_line_has_non_zero_discriminator = m_discriminator != 0;
19830       dwarf2_start_subfile (m_cu, fe->name, dir);
19831     }
19832 }
19833
19834 void
19835 lnp_state_machine::handle_const_add_pc ()
19836 {
19837   CORE_ADDR adjust
19838     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
19839
19840   CORE_ADDR addr_adj
19841     = (((m_op_index + adjust)
19842         / m_line_header->maximum_ops_per_instruction)
19843        * m_line_header->minimum_instruction_length);
19844
19845   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19846   m_op_index = ((m_op_index + adjust)
19847                 % m_line_header->maximum_ops_per_instruction);
19848 }
19849
19850 /* Return non-zero if we should add LINE to the line number table.
19851    LINE is the line to add, LAST_LINE is the last line that was added,
19852    LAST_SUBFILE is the subfile for LAST_LINE.
19853    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
19854    had a non-zero discriminator.
19855
19856    We have to be careful in the presence of discriminators.
19857    E.g., for this line:
19858
19859      for (i = 0; i < 100000; i++);
19860
19861    clang can emit four line number entries for that one line,
19862    each with a different discriminator.
19863    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
19864
19865    However, we want gdb to coalesce all four entries into one.
19866    Otherwise the user could stepi into the middle of the line and
19867    gdb would get confused about whether the pc really was in the
19868    middle of the line.
19869
19870    Things are further complicated by the fact that two consecutive
19871    line number entries for the same line is a heuristic used by gcc
19872    to denote the end of the prologue.  So we can't just discard duplicate
19873    entries, we have to be selective about it.  The heuristic we use is
19874    that we only collapse consecutive entries for the same line if at least
19875    one of those entries has a non-zero discriminator.  PR 17276.
19876
19877    Note: Addresses in the line number state machine can never go backwards
19878    within one sequence, thus this coalescing is ok.  */
19879
19880 static int
19881 dwarf_record_line_p (struct dwarf2_cu *cu,
19882                      unsigned int line, unsigned int last_line,
19883                      int line_has_non_zero_discriminator,
19884                      struct subfile *last_subfile)
19885 {
19886   if (cu->get_builder ()->get_current_subfile () != last_subfile)
19887     return 1;
19888   if (line != last_line)
19889     return 1;
19890   /* Same line for the same file that we've seen already.
19891      As a last check, for pr 17276, only record the line if the line
19892      has never had a non-zero discriminator.  */
19893   if (!line_has_non_zero_discriminator)
19894     return 1;
19895   return 0;
19896 }
19897
19898 /* Use the CU's builder to record line number LINE beginning at
19899    address ADDRESS in the line table of subfile SUBFILE.  */
19900
19901 static void
19902 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
19903                      unsigned int line, CORE_ADDR address,
19904                      struct dwarf2_cu *cu)
19905 {
19906   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
19907
19908   if (dwarf_line_debug)
19909     {
19910       fprintf_unfiltered (gdb_stdlog,
19911                           "Recording line %u, file %s, address %s\n",
19912                           line, lbasename (subfile->name),
19913                           paddress (gdbarch, address));
19914     }
19915
19916   if (cu != nullptr)
19917     cu->get_builder ()->record_line (subfile, line, addr);
19918 }
19919
19920 /* Subroutine of dwarf_decode_lines_1 to simplify it.
19921    Mark the end of a set of line number records.
19922    The arguments are the same as for dwarf_record_line_1.
19923    If SUBFILE is NULL the request is ignored.  */
19924
19925 static void
19926 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
19927                    CORE_ADDR address, struct dwarf2_cu *cu)
19928 {
19929   if (subfile == NULL)
19930     return;
19931
19932   if (dwarf_line_debug)
19933     {
19934       fprintf_unfiltered (gdb_stdlog,
19935                           "Finishing current line, file %s, address %s\n",
19936                           lbasename (subfile->name),
19937                           paddress (gdbarch, address));
19938     }
19939
19940   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
19941 }
19942
19943 void
19944 lnp_state_machine::record_line (bool end_sequence)
19945 {
19946   if (dwarf_line_debug)
19947     {
19948       fprintf_unfiltered (gdb_stdlog,
19949                           "Processing actual line %u: file %u,"
19950                           " address %s, is_stmt %u, discrim %u%s\n",
19951                           m_line, m_file,
19952                           paddress (m_gdbarch, m_address),
19953                           m_is_stmt, m_discriminator,
19954                           (end_sequence ? "\t(end sequence)" : ""));
19955     }
19956
19957   file_entry *fe = current_file ();
19958
19959   if (fe == NULL)
19960     dwarf2_debug_line_missing_file_complaint ();
19961   /* For now we ignore lines not starting on an instruction boundary.
19962      But not when processing end_sequence for compatibility with the
19963      previous version of the code.  */
19964   else if (m_op_index == 0 || end_sequence)
19965     {
19966       fe->included_p = 1;
19967       if (m_record_lines_p
19968           && (producer_is_codewarrior (m_cu) || m_is_stmt || end_sequence))
19969         {
19970           if (m_last_subfile != m_cu->get_builder ()->get_current_subfile ()
19971               || end_sequence)
19972             {
19973               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
19974                                  m_currently_recording_lines ? m_cu : nullptr);
19975             }
19976
19977           if (!end_sequence)
19978             {
19979               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
19980                                        m_line_has_non_zero_discriminator,
19981                                        m_last_subfile))
19982                 {
19983                   buildsym_compunit *builder = m_cu->get_builder ();
19984                   dwarf_record_line_1 (m_gdbarch,
19985                                        builder->get_current_subfile (),
19986                                        m_line, m_address,
19987                                        m_currently_recording_lines ? m_cu : nullptr);
19988                 }
19989               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
19990               m_last_line = m_line;
19991             }
19992         }
19993     }
19994 }
19995
19996 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
19997                                       line_header *lh, bool record_lines_p)
19998 {
19999   m_cu = cu;
20000   m_gdbarch = arch;
20001   m_record_lines_p = record_lines_p;
20002   m_line_header = lh;
20003
20004   m_currently_recording_lines = true;
20005
20006   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20007      was a line entry for it so that the backend has a chance to adjust it
20008      and also record it in case it needs it.  This is currently used by MIPS
20009      code, cf. `mips_adjust_dwarf2_line'.  */
20010   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20011   m_is_stmt = lh->default_is_stmt;
20012   m_discriminator = 0;
20013 }
20014
20015 void
20016 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20017                                        const gdb_byte *line_ptr,
20018                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20019 {
20020   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20021      the pc range of the CU.  However, we restrict the test to only ADDRESS
20022      values of zero to preserve GDB's previous behaviour which is to handle
20023      the specific case of a function being GC'd by the linker.  */
20024
20025   if (address == 0 && address < unrelocated_lowpc)
20026     {
20027       /* This line table is for a function which has been
20028          GCd by the linker.  Ignore it.  PR gdb/12528 */
20029
20030       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20031       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20032
20033       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20034                  line_offset, objfile_name (objfile));
20035       m_currently_recording_lines = false;
20036       /* Note: m_currently_recording_lines is left as false until we see
20037          DW_LNE_end_sequence.  */
20038     }
20039 }
20040
20041 /* Subroutine of dwarf_decode_lines to simplify it.
20042    Process the line number information in LH.
20043    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20044    program in order to set included_p for every referenced header.  */
20045
20046 static void
20047 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20048                       const int decode_for_pst_p, CORE_ADDR lowpc)
20049 {
20050   const gdb_byte *line_ptr, *extended_end;
20051   const gdb_byte *line_end;
20052   unsigned int bytes_read, extended_len;
20053   unsigned char op_code, extended_op;
20054   CORE_ADDR baseaddr;
20055   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20056   bfd *abfd = objfile->obfd;
20057   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20058   /* True if we're recording line info (as opposed to building partial
20059      symtabs and just interested in finding include files mentioned by
20060      the line number program).  */
20061   bool record_lines_p = !decode_for_pst_p;
20062
20063   baseaddr = objfile->text_section_offset ();
20064
20065   line_ptr = lh->statement_program_start;
20066   line_end = lh->statement_program_end;
20067
20068   /* Read the statement sequences until there's nothing left.  */
20069   while (line_ptr < line_end)
20070     {
20071       /* The DWARF line number program state machine.  Reset the state
20072          machine at the start of each sequence.  */
20073       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
20074       bool end_sequence = false;
20075
20076       if (record_lines_p)
20077         {
20078           /* Start a subfile for the current file of the state
20079              machine.  */
20080           const file_entry *fe = state_machine.current_file ();
20081
20082           if (fe != NULL)
20083             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
20084         }
20085
20086       /* Decode the table.  */
20087       while (line_ptr < line_end && !end_sequence)
20088         {
20089           op_code = read_1_byte (abfd, line_ptr);
20090           line_ptr += 1;
20091
20092           if (op_code >= lh->opcode_base)
20093             {
20094               /* Special opcode.  */
20095               state_machine.handle_special_opcode (op_code);
20096             }
20097           else switch (op_code)
20098             {
20099             case DW_LNS_extended_op:
20100               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20101                                                    &bytes_read);
20102               line_ptr += bytes_read;
20103               extended_end = line_ptr + extended_len;
20104               extended_op = read_1_byte (abfd, line_ptr);
20105               line_ptr += 1;
20106               switch (extended_op)
20107                 {
20108                 case DW_LNE_end_sequence:
20109                   state_machine.handle_end_sequence ();
20110                   end_sequence = true;
20111                   break;
20112                 case DW_LNE_set_address:
20113                   {
20114                     CORE_ADDR address
20115                       = cu->header.read_address (abfd, line_ptr, &bytes_read);
20116                     line_ptr += bytes_read;
20117
20118                     state_machine.check_line_address (cu, line_ptr,
20119                                                       lowpc - baseaddr, address);
20120                     state_machine.handle_set_address (baseaddr, address);
20121                   }
20122                   break;
20123                 case DW_LNE_define_file:
20124                   {
20125                     const char *cur_file;
20126                     unsigned int mod_time, length;
20127                     dir_index dindex;
20128
20129                     cur_file = read_direct_string (abfd, line_ptr,
20130                                                    &bytes_read);
20131                     line_ptr += bytes_read;
20132                     dindex = (dir_index)
20133                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20134                     line_ptr += bytes_read;
20135                     mod_time =
20136                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20137                     line_ptr += bytes_read;
20138                     length =
20139                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20140                     line_ptr += bytes_read;
20141                     lh->add_file_name (cur_file, dindex, mod_time, length);
20142                   }
20143                   break;
20144                 case DW_LNE_set_discriminator:
20145                   {
20146                     /* The discriminator is not interesting to the
20147                        debugger; just ignore it.  We still need to
20148                        check its value though:
20149                        if there are consecutive entries for the same
20150                        (non-prologue) line we want to coalesce them.
20151                        PR 17276.  */
20152                     unsigned int discr
20153                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20154                     line_ptr += bytes_read;
20155
20156                     state_machine.handle_set_discriminator (discr);
20157                   }
20158                   break;
20159                 default:
20160                   complaint (_("mangled .debug_line section"));
20161                   return;
20162                 }
20163               /* Make sure that we parsed the extended op correctly.  If e.g.
20164                  we expected a different address size than the producer used,
20165                  we may have read the wrong number of bytes.  */
20166               if (line_ptr != extended_end)
20167                 {
20168                   complaint (_("mangled .debug_line section"));
20169                   return;
20170                 }
20171               break;
20172             case DW_LNS_copy:
20173               state_machine.handle_copy ();
20174               break;
20175             case DW_LNS_advance_pc:
20176               {
20177                 CORE_ADDR adjust
20178                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20179                 line_ptr += bytes_read;
20180
20181                 state_machine.handle_advance_pc (adjust);
20182               }
20183               break;
20184             case DW_LNS_advance_line:
20185               {
20186                 int line_delta
20187                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20188                 line_ptr += bytes_read;
20189
20190                 state_machine.handle_advance_line (line_delta);
20191               }
20192               break;
20193             case DW_LNS_set_file:
20194               {
20195                 file_name_index file
20196                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20197                                                             &bytes_read);
20198                 line_ptr += bytes_read;
20199
20200                 state_machine.handle_set_file (file);
20201               }
20202               break;
20203             case DW_LNS_set_column:
20204               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20205               line_ptr += bytes_read;
20206               break;
20207             case DW_LNS_negate_stmt:
20208               state_machine.handle_negate_stmt ();
20209               break;
20210             case DW_LNS_set_basic_block:
20211               break;
20212             /* Add to the address register of the state machine the
20213                address increment value corresponding to special opcode
20214                255.  I.e., this value is scaled by the minimum
20215                instruction length since special opcode 255 would have
20216                scaled the increment.  */
20217             case DW_LNS_const_add_pc:
20218               state_machine.handle_const_add_pc ();
20219               break;
20220             case DW_LNS_fixed_advance_pc:
20221               {
20222                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20223                 line_ptr += 2;
20224
20225                 state_machine.handle_fixed_advance_pc (addr_adj);
20226               }
20227               break;
20228             default:
20229               {
20230                 /* Unknown standard opcode, ignore it.  */
20231                 int i;
20232
20233                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20234                   {
20235                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20236                     line_ptr += bytes_read;
20237                   }
20238               }
20239             }
20240         }
20241
20242       if (!end_sequence)
20243         dwarf2_debug_line_missing_end_sequence_complaint ();
20244
20245       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20246          in which case we still finish recording the last line).  */
20247       state_machine.record_line (true);
20248     }
20249 }
20250
20251 /* Decode the Line Number Program (LNP) for the given line_header
20252    structure and CU.  The actual information extracted and the type
20253    of structures created from the LNP depends on the value of PST.
20254
20255    1. If PST is NULL, then this procedure uses the data from the program
20256       to create all necessary symbol tables, and their linetables.
20257
20258    2. If PST is not NULL, this procedure reads the program to determine
20259       the list of files included by the unit represented by PST, and
20260       builds all the associated partial symbol tables.
20261
20262    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20263    It is used for relative paths in the line table.
20264    NOTE: When processing partial symtabs (pst != NULL),
20265    comp_dir == pst->dirname.
20266
20267    NOTE: It is important that psymtabs have the same file name (via strcmp)
20268    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20269    symtab we don't use it in the name of the psymtabs we create.
20270    E.g. expand_line_sal requires this when finding psymtabs to expand.
20271    A good testcase for this is mb-inline.exp.
20272
20273    LOWPC is the lowest address in CU (or 0 if not known).
20274
20275    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20276    for its PC<->lines mapping information.  Otherwise only the filename
20277    table is read in.  */
20278
20279 static void
20280 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20281                     struct dwarf2_cu *cu, dwarf2_psymtab *pst,
20282                     CORE_ADDR lowpc, int decode_mapping)
20283 {
20284   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20285   const int decode_for_pst_p = (pst != NULL);
20286
20287   if (decode_mapping)
20288     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20289
20290   if (decode_for_pst_p)
20291     {
20292       /* Now that we're done scanning the Line Header Program, we can
20293          create the psymtab of each included file.  */
20294       for (auto &file_entry : lh->file_names ())
20295         if (file_entry.included_p == 1)
20296           {
20297             gdb::unique_xmalloc_ptr<char> name_holder;
20298             const char *include_name =
20299               psymtab_include_file_name (lh, file_entry, pst,
20300                                          comp_dir, &name_holder);
20301             if (include_name != NULL)
20302               dwarf2_create_include_psymtab (include_name, pst, objfile);
20303           }
20304     }
20305   else
20306     {
20307       /* Make sure a symtab is created for every file, even files
20308          which contain only variables (i.e. no code with associated
20309          line numbers).  */
20310       buildsym_compunit *builder = cu->get_builder ();
20311       struct compunit_symtab *cust = builder->get_compunit_symtab ();
20312
20313       for (auto &fe : lh->file_names ())
20314         {
20315           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
20316           if (builder->get_current_subfile ()->symtab == NULL)
20317             {
20318               builder->get_current_subfile ()->symtab
20319                 = allocate_symtab (cust,
20320                                    builder->get_current_subfile ()->name);
20321             }
20322           fe.symtab = builder->get_current_subfile ()->symtab;
20323         }
20324     }
20325 }
20326
20327 /* Start a subfile for DWARF.  FILENAME is the name of the file and
20328    DIRNAME the name of the source directory which contains FILENAME
20329    or NULL if not known.
20330    This routine tries to keep line numbers from identical absolute and
20331    relative file names in a common subfile.
20332
20333    Using the `list' example from the GDB testsuite, which resides in
20334    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
20335    of /srcdir/list0.c yields the following debugging information for list0.c:
20336
20337    DW_AT_name:          /srcdir/list0.c
20338    DW_AT_comp_dir:      /compdir
20339    files.files[0].name: list0.h
20340    files.files[0].dir:  /srcdir
20341    files.files[1].name: list0.c
20342    files.files[1].dir:  /srcdir
20343
20344    The line number information for list0.c has to end up in a single
20345    subfile, so that `break /srcdir/list0.c:1' works as expected.
20346    start_subfile will ensure that this happens provided that we pass the
20347    concatenation of files.files[1].dir and files.files[1].name as the
20348    subfile's name.  */
20349
20350 static void
20351 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
20352                       const char *dirname)
20353 {
20354   gdb::unique_xmalloc_ptr<char> copy;
20355
20356   /* In order not to lose the line information directory,
20357      we concatenate it to the filename when it makes sense.
20358      Note that the Dwarf3 standard says (speaking of filenames in line
20359      information): ``The directory index is ignored for file names
20360      that represent full path names''.  Thus ignoring dirname in the
20361      `else' branch below isn't an issue.  */
20362
20363   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
20364     {
20365       copy.reset (concat (dirname, SLASH_STRING, filename, (char *) NULL));
20366       filename = copy.get ();
20367     }
20368
20369   cu->get_builder ()->start_subfile (filename);
20370 }
20371
20372 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
20373    buildsym_compunit constructor.  */
20374
20375 struct compunit_symtab *
20376 dwarf2_cu::start_symtab (const char *name, const char *comp_dir,
20377                          CORE_ADDR low_pc)
20378 {
20379   gdb_assert (m_builder == nullptr);
20380
20381   m_builder.reset (new struct buildsym_compunit
20382                    (per_cu->dwarf2_per_objfile->objfile,
20383                     name, comp_dir, language, low_pc));
20384
20385   list_in_scope = get_builder ()->get_file_symbols ();
20386
20387   get_builder ()->record_debugformat ("DWARF 2");
20388   get_builder ()->record_producer (producer);
20389
20390   processing_has_namespace_info = false;
20391
20392   return get_builder ()->get_compunit_symtab ();
20393 }
20394
20395 static void
20396 var_decode_location (struct attribute *attr, struct symbol *sym,
20397                      struct dwarf2_cu *cu)
20398 {
20399   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20400   struct comp_unit_head *cu_header = &cu->header;
20401
20402   /* NOTE drow/2003-01-30: There used to be a comment and some special
20403      code here to turn a symbol with DW_AT_external and a
20404      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
20405      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
20406      with some versions of binutils) where shared libraries could have
20407      relocations against symbols in their debug information - the
20408      minimal symbol would have the right address, but the debug info
20409      would not.  It's no longer necessary, because we will explicitly
20410      apply relocations when we read in the debug information now.  */
20411
20412   /* A DW_AT_location attribute with no contents indicates that a
20413      variable has been optimized away.  */
20414   if (attr->form_is_block () && DW_BLOCK (attr)->size == 0)
20415     {
20416       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
20417       return;
20418     }
20419
20420   /* Handle one degenerate form of location expression specially, to
20421      preserve GDB's previous behavior when section offsets are
20422      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
20423      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
20424
20425   if (attr->form_is_block ()
20426       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
20427            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
20428           || ((DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
20429                || DW_BLOCK (attr)->data[0] == DW_OP_addrx)
20430               && (DW_BLOCK (attr)->size
20431                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
20432     {
20433       unsigned int dummy;
20434
20435       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
20436         SET_SYMBOL_VALUE_ADDRESS
20437           (sym, cu->header.read_address (objfile->obfd,
20438                                          DW_BLOCK (attr)->data + 1,
20439                                          &dummy));
20440       else
20441         SET_SYMBOL_VALUE_ADDRESS
20442           (sym, read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1,
20443                                              &dummy));
20444       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
20445       fixup_symbol_section (sym, objfile);
20446       SET_SYMBOL_VALUE_ADDRESS
20447         (sym,
20448          SYMBOL_VALUE_ADDRESS (sym)
20449          + objfile->section_offsets[SYMBOL_SECTION (sym)]);
20450       return;
20451     }
20452
20453   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
20454      expression evaluator, and use LOC_COMPUTED only when necessary
20455      (i.e. when the value of a register or memory location is
20456      referenced, or a thread-local block, etc.).  Then again, it might
20457      not be worthwhile.  I'm assuming that it isn't unless performance
20458      or memory numbers show me otherwise.  */
20459
20460   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
20461
20462   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
20463     cu->has_loclist = true;
20464 }
20465
20466 /* Given a pointer to a DWARF information entry, figure out if we need
20467    to make a symbol table entry for it, and if so, create a new entry
20468    and return a pointer to it.
20469    If TYPE is NULL, determine symbol type from the die, otherwise
20470    used the passed type.
20471    If SPACE is not NULL, use it to hold the new symbol.  If it is
20472    NULL, allocate a new symbol on the objfile's obstack.  */
20473
20474 static struct symbol *
20475 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
20476             struct symbol *space)
20477 {
20478   struct dwarf2_per_objfile *dwarf2_per_objfile
20479     = cu->per_cu->dwarf2_per_objfile;
20480   struct objfile *objfile = dwarf2_per_objfile->objfile;
20481   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20482   struct symbol *sym = NULL;
20483   const char *name;
20484   struct attribute *attr = NULL;
20485   struct attribute *attr2 = NULL;
20486   CORE_ADDR baseaddr;
20487   struct pending **list_to_add = NULL;
20488
20489   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
20490
20491   baseaddr = objfile->text_section_offset ();
20492
20493   name = dwarf2_name (die, cu);
20494   if (name)
20495     {
20496       const char *linkagename;
20497       int suppress_add = 0;
20498
20499       if (space)
20500         sym = space;
20501       else
20502         sym = allocate_symbol (objfile);
20503       OBJSTAT (objfile, n_syms++);
20504
20505       /* Cache this symbol's name and the name's demangled form (if any).  */
20506       sym->set_language (cu->language, &objfile->objfile_obstack);
20507       linkagename = dwarf2_physname (name, die, cu);
20508       sym->compute_and_set_names (linkagename, false, objfile->per_bfd);
20509
20510       /* Fortran does not have mangling standard and the mangling does differ
20511          between gfortran, iFort etc.  */
20512       if (cu->language == language_fortran
20513           && symbol_get_demangled_name (sym) == NULL)
20514         symbol_set_demangled_name (sym,
20515                                    dwarf2_full_name (name, die, cu),
20516                                    NULL);
20517
20518       /* Default assumptions.
20519          Use the passed type or decode it from the die.  */
20520       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20521       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
20522       if (type != NULL)
20523         SYMBOL_TYPE (sym) = type;
20524       else
20525         SYMBOL_TYPE (sym) = die_type (die, cu);
20526       attr = dwarf2_attr (die,
20527                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
20528                           cu);
20529       if (attr != nullptr)
20530         {
20531           SYMBOL_LINE (sym) = DW_UNSND (attr);
20532         }
20533
20534       attr = dwarf2_attr (die,
20535                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
20536                           cu);
20537       if (attr != nullptr)
20538         {
20539           file_name_index file_index = (file_name_index) DW_UNSND (attr);
20540           struct file_entry *fe;
20541
20542           if (cu->line_header != NULL)
20543             fe = cu->line_header->file_name_at (file_index);
20544           else
20545             fe = NULL;
20546
20547           if (fe == NULL)
20548             complaint (_("file index out of range"));
20549           else
20550             symbol_set_symtab (sym, fe->symtab);
20551         }
20552
20553       switch (die->tag)
20554         {
20555         case DW_TAG_label:
20556           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
20557           if (attr != nullptr)
20558             {
20559               CORE_ADDR addr;
20560
20561               addr = attr->value_as_address ();
20562               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
20563               SET_SYMBOL_VALUE_ADDRESS (sym, addr);
20564             }
20565           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
20566           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
20567           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
20568           add_symbol_to_list (sym, cu->list_in_scope);
20569           break;
20570         case DW_TAG_subprogram:
20571           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
20572              finish_block.  */
20573           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
20574           attr2 = dwarf2_attr (die, DW_AT_external, cu);
20575           if ((attr2 && (DW_UNSND (attr2) != 0))
20576               || cu->language == language_ada
20577               || cu->language == language_fortran)
20578             {
20579               /* Subprograms marked external are stored as a global symbol.
20580                  Ada and Fortran subprograms, whether marked external or
20581                  not, are always stored as a global symbol, because we want
20582                  to be able to access them globally.  For instance, we want
20583                  to be able to break on a nested subprogram without having
20584                  to specify the context.  */
20585               list_to_add = cu->get_builder ()->get_global_symbols ();
20586             }
20587           else
20588             {
20589               list_to_add = cu->list_in_scope;
20590             }
20591           break;
20592         case DW_TAG_inlined_subroutine:
20593           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
20594              finish_block.  */
20595           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
20596           SYMBOL_INLINED (sym) = 1;
20597           list_to_add = cu->list_in_scope;
20598           break;
20599         case DW_TAG_template_value_param:
20600           suppress_add = 1;
20601           /* Fall through.  */
20602         case DW_TAG_constant:
20603         case DW_TAG_variable:
20604         case DW_TAG_member:
20605           /* Compilation with minimal debug info may result in
20606              variables with missing type entries.  Change the
20607              misleading `void' type to something sensible.  */
20608           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
20609             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
20610
20611           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20612           /* In the case of DW_TAG_member, we should only be called for
20613              static const members.  */
20614           if (die->tag == DW_TAG_member)
20615             {
20616               /* dwarf2_add_field uses die_is_declaration,
20617                  so we do the same.  */
20618               gdb_assert (die_is_declaration (die, cu));
20619               gdb_assert (attr);
20620             }
20621           if (attr != nullptr)
20622             {
20623               dwarf2_const_value (attr, sym, cu);
20624               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20625               if (!suppress_add)
20626                 {
20627                   if (attr2 && (DW_UNSND (attr2) != 0))
20628                     list_to_add = cu->get_builder ()->get_global_symbols ();
20629                   else
20630                     list_to_add = cu->list_in_scope;
20631                 }
20632               break;
20633             }
20634           attr = dwarf2_attr (die, DW_AT_location, cu);
20635           if (attr != nullptr)
20636             {
20637               var_decode_location (attr, sym, cu);
20638               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20639
20640               /* Fortran explicitly imports any global symbols to the local
20641                  scope by DW_TAG_common_block.  */
20642               if (cu->language == language_fortran && die->parent
20643                   && die->parent->tag == DW_TAG_common_block)
20644                 attr2 = NULL;
20645
20646               if (SYMBOL_CLASS (sym) == LOC_STATIC
20647                   && SYMBOL_VALUE_ADDRESS (sym) == 0
20648                   && !dwarf2_per_objfile->has_section_at_zero)
20649                 {
20650                   /* When a static variable is eliminated by the linker,
20651                      the corresponding debug information is not stripped
20652                      out, but the variable address is set to null;
20653                      do not add such variables into symbol table.  */
20654                 }
20655               else if (attr2 && (DW_UNSND (attr2) != 0))
20656                 {
20657                   if (SYMBOL_CLASS (sym) == LOC_STATIC
20658                       && (objfile->flags & OBJF_MAINLINE) == 0
20659                       && dwarf2_per_objfile->can_copy)
20660                     {
20661                       /* A global static variable might be subject to
20662                          copy relocation.  We first check for a local
20663                          minsym, though, because maybe the symbol was
20664                          marked hidden, in which case this would not
20665                          apply.  */
20666                       bound_minimal_symbol found
20667                         = (lookup_minimal_symbol_linkage
20668                            (sym->linkage_name (), objfile));
20669                       if (found.minsym != nullptr)
20670                         sym->maybe_copied = 1;
20671                     }
20672
20673                   /* A variable with DW_AT_external is never static,
20674                      but it may be block-scoped.  */
20675                   list_to_add
20676                     = ((cu->list_in_scope
20677                         == cu->get_builder ()->get_file_symbols ())
20678                        ? cu->get_builder ()->get_global_symbols ()
20679                        : cu->list_in_scope);
20680                 }
20681               else
20682                 list_to_add = cu->list_in_scope;
20683             }
20684           else
20685             {
20686               /* We do not know the address of this symbol.
20687                  If it is an external symbol and we have type information
20688                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
20689                  The address of the variable will then be determined from
20690                  the minimal symbol table whenever the variable is
20691                  referenced.  */
20692               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20693
20694               /* Fortran explicitly imports any global symbols to the local
20695                  scope by DW_TAG_common_block.  */
20696               if (cu->language == language_fortran && die->parent
20697                   && die->parent->tag == DW_TAG_common_block)
20698                 {
20699                   /* SYMBOL_CLASS doesn't matter here because
20700                      read_common_block is going to reset it.  */
20701                   if (!suppress_add)
20702                     list_to_add = cu->list_in_scope;
20703                 }
20704               else if (attr2 && (DW_UNSND (attr2) != 0)
20705                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
20706                 {
20707                   /* A variable with DW_AT_external is never static, but it
20708                      may be block-scoped.  */
20709                   list_to_add
20710                     = ((cu->list_in_scope
20711                         == cu->get_builder ()->get_file_symbols ())
20712                        ? cu->get_builder ()->get_global_symbols ()
20713                        : cu->list_in_scope);
20714
20715                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
20716                 }
20717               else if (!die_is_declaration (die, cu))
20718                 {
20719                   /* Use the default LOC_OPTIMIZED_OUT class.  */
20720                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
20721                   if (!suppress_add)
20722                     list_to_add = cu->list_in_scope;
20723                 }
20724             }
20725           break;
20726         case DW_TAG_formal_parameter:
20727           {
20728             /* If we are inside a function, mark this as an argument.  If
20729                not, we might be looking at an argument to an inlined function
20730                when we do not have enough information to show inlined frames;
20731                pretend it's a local variable in that case so that the user can
20732                still see it.  */
20733             struct context_stack *curr
20734               = cu->get_builder ()->get_current_context_stack ();
20735             if (curr != nullptr && curr->name != nullptr)
20736               SYMBOL_IS_ARGUMENT (sym) = 1;
20737             attr = dwarf2_attr (die, DW_AT_location, cu);
20738             if (attr != nullptr)
20739               {
20740                 var_decode_location (attr, sym, cu);
20741               }
20742             attr = dwarf2_attr (die, DW_AT_const_value, cu);
20743             if (attr != nullptr)
20744               {
20745                 dwarf2_const_value (attr, sym, cu);
20746               }
20747
20748             list_to_add = cu->list_in_scope;
20749           }
20750           break;
20751         case DW_TAG_unspecified_parameters:
20752           /* From varargs functions; gdb doesn't seem to have any
20753              interest in this information, so just ignore it for now.
20754              (FIXME?) */
20755           break;
20756         case DW_TAG_template_type_param:
20757           suppress_add = 1;
20758           /* Fall through.  */
20759         case DW_TAG_class_type:
20760         case DW_TAG_interface_type:
20761         case DW_TAG_structure_type:
20762         case DW_TAG_union_type:
20763         case DW_TAG_set_type:
20764         case DW_TAG_enumeration_type:
20765           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20766           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
20767
20768           {
20769             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
20770                really ever be static objects: otherwise, if you try
20771                to, say, break of a class's method and you're in a file
20772                which doesn't mention that class, it won't work unless
20773                the check for all static symbols in lookup_symbol_aux
20774                saves you.  See the OtherFileClass tests in
20775                gdb.c++/namespace.exp.  */
20776
20777             if (!suppress_add)
20778               {
20779                 buildsym_compunit *builder = cu->get_builder ();
20780                 list_to_add
20781                   = (cu->list_in_scope == builder->get_file_symbols ()
20782                      && cu->language == language_cplus
20783                      ? builder->get_global_symbols ()
20784                      : cu->list_in_scope);
20785
20786                 /* The semantics of C++ state that "struct foo {
20787                    ... }" also defines a typedef for "foo".  */
20788                 if (cu->language == language_cplus
20789                     || cu->language == language_ada
20790                     || cu->language == language_d
20791                     || cu->language == language_rust)
20792                   {
20793                     /* The symbol's name is already allocated along
20794                        with this objfile, so we don't need to
20795                        duplicate it for the type.  */
20796                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
20797                       TYPE_NAME (SYMBOL_TYPE (sym)) = sym->search_name ();
20798                   }
20799               }
20800           }
20801           break;
20802         case DW_TAG_typedef:
20803           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20804           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20805           list_to_add = cu->list_in_scope;
20806           break;
20807         case DW_TAG_base_type:
20808         case DW_TAG_subrange_type:
20809           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20810           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20811           list_to_add = cu->list_in_scope;
20812           break;
20813         case DW_TAG_enumerator:
20814           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20815           if (attr != nullptr)
20816             {
20817               dwarf2_const_value (attr, sym, cu);
20818             }
20819           {
20820             /* NOTE: carlton/2003-11-10: See comment above in the
20821                DW_TAG_class_type, etc. block.  */
20822
20823             list_to_add
20824               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
20825                  && cu->language == language_cplus
20826                  ? cu->get_builder ()->get_global_symbols ()
20827                  : cu->list_in_scope);
20828           }
20829           break;
20830         case DW_TAG_imported_declaration:
20831         case DW_TAG_namespace:
20832           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20833           list_to_add = cu->get_builder ()->get_global_symbols ();
20834           break;
20835         case DW_TAG_module:
20836           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20837           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
20838           list_to_add = cu->get_builder ()->get_global_symbols ();
20839           break;
20840         case DW_TAG_common_block:
20841           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
20842           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
20843           add_symbol_to_list (sym, cu->list_in_scope);
20844           break;
20845         default:
20846           /* Not a tag we recognize.  Hopefully we aren't processing
20847              trash data, but since we must specifically ignore things
20848              we don't recognize, there is nothing else we should do at
20849              this point.  */
20850           complaint (_("unsupported tag: '%s'"),
20851                      dwarf_tag_name (die->tag));
20852           break;
20853         }
20854
20855       if (suppress_add)
20856         {
20857           sym->hash_next = objfile->template_symbols;
20858           objfile->template_symbols = sym;
20859           list_to_add = NULL;
20860         }
20861
20862       if (list_to_add != NULL)
20863         add_symbol_to_list (sym, list_to_add);
20864
20865       /* For the benefit of old versions of GCC, check for anonymous
20866          namespaces based on the demangled name.  */
20867       if (!cu->processing_has_namespace_info
20868           && cu->language == language_cplus)
20869         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
20870     }
20871   return (sym);
20872 }
20873
20874 /* Given an attr with a DW_FORM_dataN value in host byte order,
20875    zero-extend it as appropriate for the symbol's type.  The DWARF
20876    standard (v4) is not entirely clear about the meaning of using
20877    DW_FORM_dataN for a constant with a signed type, where the type is
20878    wider than the data.  The conclusion of a discussion on the DWARF
20879    list was that this is unspecified.  We choose to always zero-extend
20880    because that is the interpretation long in use by GCC.  */
20881
20882 static gdb_byte *
20883 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
20884                          struct dwarf2_cu *cu, LONGEST *value, int bits)
20885 {
20886   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20887   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
20888                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
20889   LONGEST l = DW_UNSND (attr);
20890
20891   if (bits < sizeof (*value) * 8)
20892     {
20893       l &= ((LONGEST) 1 << bits) - 1;
20894       *value = l;
20895     }
20896   else if (bits == sizeof (*value) * 8)
20897     *value = l;
20898   else
20899     {
20900       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
20901       store_unsigned_integer (bytes, bits / 8, byte_order, l);
20902       return bytes;
20903     }
20904
20905   return NULL;
20906 }
20907
20908 /* Read a constant value from an attribute.  Either set *VALUE, or if
20909    the value does not fit in *VALUE, set *BYTES - either already
20910    allocated on the objfile obstack, or newly allocated on OBSTACK,
20911    or, set *BATON, if we translated the constant to a location
20912    expression.  */
20913
20914 static void
20915 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
20916                          const char *name, struct obstack *obstack,
20917                          struct dwarf2_cu *cu,
20918                          LONGEST *value, const gdb_byte **bytes,
20919                          struct dwarf2_locexpr_baton **baton)
20920 {
20921   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20922   struct comp_unit_head *cu_header = &cu->header;
20923   struct dwarf_block *blk;
20924   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
20925                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20926
20927   *value = 0;
20928   *bytes = NULL;
20929   *baton = NULL;
20930
20931   switch (attr->form)
20932     {
20933     case DW_FORM_addr:
20934     case DW_FORM_addrx:
20935     case DW_FORM_GNU_addr_index:
20936       {
20937         gdb_byte *data;
20938
20939         if (TYPE_LENGTH (type) != cu_header->addr_size)
20940           dwarf2_const_value_length_mismatch_complaint (name,
20941                                                         cu_header->addr_size,
20942                                                         TYPE_LENGTH (type));
20943         /* Symbols of this form are reasonably rare, so we just
20944            piggyback on the existing location code rather than writing
20945            a new implementation of symbol_computed_ops.  */
20946         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
20947         (*baton)->per_cu = cu->per_cu;
20948         gdb_assert ((*baton)->per_cu);
20949
20950         (*baton)->size = 2 + cu_header->addr_size;
20951         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
20952         (*baton)->data = data;
20953
20954         data[0] = DW_OP_addr;
20955         store_unsigned_integer (&data[1], cu_header->addr_size,
20956                                 byte_order, DW_ADDR (attr));
20957         data[cu_header->addr_size + 1] = DW_OP_stack_value;
20958       }
20959       break;
20960     case DW_FORM_string:
20961     case DW_FORM_strp:
20962     case DW_FORM_strx:
20963     case DW_FORM_GNU_str_index:
20964     case DW_FORM_GNU_strp_alt:
20965       /* DW_STRING is already allocated on the objfile obstack, point
20966          directly to it.  */
20967       *bytes = (const gdb_byte *) DW_STRING (attr);
20968       break;
20969     case DW_FORM_block1:
20970     case DW_FORM_block2:
20971     case DW_FORM_block4:
20972     case DW_FORM_block:
20973     case DW_FORM_exprloc:
20974     case DW_FORM_data16:
20975       blk = DW_BLOCK (attr);
20976       if (TYPE_LENGTH (type) != blk->size)
20977         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
20978                                                       TYPE_LENGTH (type));
20979       *bytes = blk->data;
20980       break;
20981
20982       /* The DW_AT_const_value attributes are supposed to carry the
20983          symbol's value "represented as it would be on the target
20984          architecture."  By the time we get here, it's already been
20985          converted to host endianness, so we just need to sign- or
20986          zero-extend it as appropriate.  */
20987     case DW_FORM_data1:
20988       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
20989       break;
20990     case DW_FORM_data2:
20991       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
20992       break;
20993     case DW_FORM_data4:
20994       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
20995       break;
20996     case DW_FORM_data8:
20997       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
20998       break;
20999
21000     case DW_FORM_sdata:
21001     case DW_FORM_implicit_const:
21002       *value = DW_SND (attr);
21003       break;
21004
21005     case DW_FORM_udata:
21006       *value = DW_UNSND (attr);
21007       break;
21008
21009     default:
21010       complaint (_("unsupported const value attribute form: '%s'"),
21011                  dwarf_form_name (attr->form));
21012       *value = 0;
21013       break;
21014     }
21015 }
21016
21017
21018 /* Copy constant value from an attribute to a symbol.  */
21019
21020 static void
21021 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21022                     struct dwarf2_cu *cu)
21023 {
21024   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21025   LONGEST value;
21026   const gdb_byte *bytes;
21027   struct dwarf2_locexpr_baton *baton;
21028
21029   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21030                            sym->print_name (),
21031                            &objfile->objfile_obstack, cu,
21032                            &value, &bytes, &baton);
21033
21034   if (baton != NULL)
21035     {
21036       SYMBOL_LOCATION_BATON (sym) = baton;
21037       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21038     }
21039   else if (bytes != NULL)
21040      {
21041       SYMBOL_VALUE_BYTES (sym) = bytes;
21042       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21043     }
21044   else
21045     {
21046       SYMBOL_VALUE (sym) = value;
21047       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21048     }
21049 }
21050
21051 /* Return the type of the die in question using its DW_AT_type attribute.  */
21052
21053 static struct type *
21054 die_type (struct die_info *die, struct dwarf2_cu *cu)
21055 {
21056   struct attribute *type_attr;
21057
21058   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21059   if (!type_attr)
21060     {
21061       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21062       /* A missing DW_AT_type represents a void type.  */
21063       return objfile_type (objfile)->builtin_void;
21064     }
21065
21066   return lookup_die_type (die, type_attr, cu);
21067 }
21068
21069 /* True iff CU's producer generates GNAT Ada auxiliary information
21070    that allows to find parallel types through that information instead
21071    of having to do expensive parallel lookups by type name.  */
21072
21073 static int
21074 need_gnat_info (struct dwarf2_cu *cu)
21075 {
21076   /* Assume that the Ada compiler was GNAT, which always produces
21077      the auxiliary information.  */
21078   return (cu->language == language_ada);
21079 }
21080
21081 /* Return the auxiliary type of the die in question using its
21082    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21083    attribute is not present.  */
21084
21085 static struct type *
21086 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21087 {
21088   struct attribute *type_attr;
21089
21090   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21091   if (!type_attr)
21092     return NULL;
21093
21094   return lookup_die_type (die, type_attr, cu);
21095 }
21096
21097 /* If DIE has a descriptive_type attribute, then set the TYPE's
21098    descriptive type accordingly.  */
21099
21100 static void
21101 set_descriptive_type (struct type *type, struct die_info *die,
21102                       struct dwarf2_cu *cu)
21103 {
21104   struct type *descriptive_type = die_descriptive_type (die, cu);
21105
21106   if (descriptive_type)
21107     {
21108       ALLOCATE_GNAT_AUX_TYPE (type);
21109       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21110     }
21111 }
21112
21113 /* Return the containing type of the die in question using its
21114    DW_AT_containing_type attribute.  */
21115
21116 static struct type *
21117 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21118 {
21119   struct attribute *type_attr;
21120   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21121
21122   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21123   if (!type_attr)
21124     error (_("Dwarf Error: Problem turning containing type into gdb type "
21125              "[in module %s]"), objfile_name (objfile));
21126
21127   return lookup_die_type (die, type_attr, cu);
21128 }
21129
21130 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21131
21132 static struct type *
21133 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21134 {
21135   struct dwarf2_per_objfile *dwarf2_per_objfile
21136     = cu->per_cu->dwarf2_per_objfile;
21137   struct objfile *objfile = dwarf2_per_objfile->objfile;
21138   char *saved;
21139
21140   std::string message
21141     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
21142                      objfile_name (objfile),
21143                      sect_offset_str (cu->header.sect_off),
21144                      sect_offset_str (die->sect_off));
21145   saved = obstack_strdup (&objfile->objfile_obstack, message);
21146
21147   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21148 }
21149
21150 /* Look up the type of DIE in CU using its type attribute ATTR.
21151    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21152    DW_AT_containing_type.
21153    If there is no type substitute an error marker.  */
21154
21155 static struct type *
21156 lookup_die_type (struct die_info *die, const struct attribute *attr,
21157                  struct dwarf2_cu *cu)
21158 {
21159   struct dwarf2_per_objfile *dwarf2_per_objfile
21160     = cu->per_cu->dwarf2_per_objfile;
21161   struct objfile *objfile = dwarf2_per_objfile->objfile;
21162   struct type *this_type;
21163
21164   gdb_assert (attr->name == DW_AT_type
21165               || attr->name == DW_AT_GNAT_descriptive_type
21166               || attr->name == DW_AT_containing_type);
21167
21168   /* First see if we have it cached.  */
21169
21170   if (attr->form == DW_FORM_GNU_ref_alt)
21171     {
21172       struct dwarf2_per_cu_data *per_cu;
21173       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21174
21175       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21176                                                  dwarf2_per_objfile);
21177       this_type = get_die_type_at_offset (sect_off, per_cu);
21178     }
21179   else if (attr->form_is_ref ())
21180     {
21181       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21182
21183       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21184     }
21185   else if (attr->form == DW_FORM_ref_sig8)
21186     {
21187       ULONGEST signature = DW_SIGNATURE (attr);
21188
21189       return get_signatured_type (die, signature, cu);
21190     }
21191   else
21192     {
21193       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21194                    " at %s [in module %s]"),
21195                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21196                  objfile_name (objfile));
21197       return build_error_marker_type (cu, die);
21198     }
21199
21200   /* If not cached we need to read it in.  */
21201
21202   if (this_type == NULL)
21203     {
21204       struct die_info *type_die = NULL;
21205       struct dwarf2_cu *type_cu = cu;
21206
21207       if (attr->form_is_ref ())
21208         type_die = follow_die_ref (die, attr, &type_cu);
21209       if (type_die == NULL)
21210         return build_error_marker_type (cu, die);
21211       /* If we find the type now, it's probably because the type came
21212          from an inter-CU reference and the type's CU got expanded before
21213          ours.  */
21214       this_type = read_type_die (type_die, type_cu);
21215     }
21216
21217   /* If we still don't have a type use an error marker.  */
21218
21219   if (this_type == NULL)
21220     return build_error_marker_type (cu, die);
21221
21222   return this_type;
21223 }
21224
21225 /* Return the type in DIE, CU.
21226    Returns NULL for invalid types.
21227
21228    This first does a lookup in die_type_hash,
21229    and only reads the die in if necessary.
21230
21231    NOTE: This can be called when reading in partial or full symbols.  */
21232
21233 static struct type *
21234 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21235 {
21236   struct type *this_type;
21237
21238   this_type = get_die_type (die, cu);
21239   if (this_type)
21240     return this_type;
21241
21242   return read_type_die_1 (die, cu);
21243 }
21244
21245 /* Read the type in DIE, CU.
21246    Returns NULL for invalid types.  */
21247
21248 static struct type *
21249 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21250 {
21251   struct type *this_type = NULL;
21252
21253   switch (die->tag)
21254     {
21255     case DW_TAG_class_type:
21256     case DW_TAG_interface_type:
21257     case DW_TAG_structure_type:
21258     case DW_TAG_union_type:
21259       this_type = read_structure_type (die, cu);
21260       break;
21261     case DW_TAG_enumeration_type:
21262       this_type = read_enumeration_type (die, cu);
21263       break;
21264     case DW_TAG_subprogram:
21265     case DW_TAG_subroutine_type:
21266     case DW_TAG_inlined_subroutine:
21267       this_type = read_subroutine_type (die, cu);
21268       break;
21269     case DW_TAG_array_type:
21270       this_type = read_array_type (die, cu);
21271       break;
21272     case DW_TAG_set_type:
21273       this_type = read_set_type (die, cu);
21274       break;
21275     case DW_TAG_pointer_type:
21276       this_type = read_tag_pointer_type (die, cu);
21277       break;
21278     case DW_TAG_ptr_to_member_type:
21279       this_type = read_tag_ptr_to_member_type (die, cu);
21280       break;
21281     case DW_TAG_reference_type:
21282       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21283       break;
21284     case DW_TAG_rvalue_reference_type:
21285       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21286       break;
21287     case DW_TAG_const_type:
21288       this_type = read_tag_const_type (die, cu);
21289       break;
21290     case DW_TAG_volatile_type:
21291       this_type = read_tag_volatile_type (die, cu);
21292       break;
21293     case DW_TAG_restrict_type:
21294       this_type = read_tag_restrict_type (die, cu);
21295       break;
21296     case DW_TAG_string_type:
21297       this_type = read_tag_string_type (die, cu);
21298       break;
21299     case DW_TAG_typedef:
21300       this_type = read_typedef (die, cu);
21301       break;
21302     case DW_TAG_subrange_type:
21303       this_type = read_subrange_type (die, cu);
21304       break;
21305     case DW_TAG_base_type:
21306       this_type = read_base_type (die, cu);
21307       break;
21308     case DW_TAG_unspecified_type:
21309       this_type = read_unspecified_type (die, cu);
21310       break;
21311     case DW_TAG_namespace:
21312       this_type = read_namespace_type (die, cu);
21313       break;
21314     case DW_TAG_module:
21315       this_type = read_module_type (die, cu);
21316       break;
21317     case DW_TAG_atomic_type:
21318       this_type = read_tag_atomic_type (die, cu);
21319       break;
21320     default:
21321       complaint (_("unexpected tag in read_type_die: '%s'"),
21322                  dwarf_tag_name (die->tag));
21323       break;
21324     }
21325
21326   return this_type;
21327 }
21328
21329 /* See if we can figure out if the class lives in a namespace.  We do
21330    this by looking for a member function; its demangled name will
21331    contain namespace info, if there is any.
21332    Return the computed name or NULL.
21333    Space for the result is allocated on the objfile's obstack.
21334    This is the full-die version of guess_partial_die_structure_name.
21335    In this case we know DIE has no useful parent.  */
21336
21337 static const char *
21338 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
21339 {
21340   struct die_info *spec_die;
21341   struct dwarf2_cu *spec_cu;
21342   struct die_info *child;
21343   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21344
21345   spec_cu = cu;
21346   spec_die = die_specification (die, &spec_cu);
21347   if (spec_die != NULL)
21348     {
21349       die = spec_die;
21350       cu = spec_cu;
21351     }
21352
21353   for (child = die->child;
21354        child != NULL;
21355        child = child->sibling)
21356     {
21357       if (child->tag == DW_TAG_subprogram)
21358         {
21359           const char *linkage_name = dw2_linkage_name (child, cu);
21360
21361           if (linkage_name != NULL)
21362             {
21363               gdb::unique_xmalloc_ptr<char> actual_name
21364                 (language_class_name_from_physname (cu->language_defn,
21365                                                     linkage_name));
21366               const char *name = NULL;
21367
21368               if (actual_name != NULL)
21369                 {
21370                   const char *die_name = dwarf2_name (die, cu);
21371
21372                   if (die_name != NULL
21373                       && strcmp (die_name, actual_name.get ()) != 0)
21374                     {
21375                       /* Strip off the class name from the full name.
21376                          We want the prefix.  */
21377                       int die_name_len = strlen (die_name);
21378                       int actual_name_len = strlen (actual_name.get ());
21379                       const char *ptr = actual_name.get ();
21380
21381                       /* Test for '::' as a sanity check.  */
21382                       if (actual_name_len > die_name_len + 2
21383                           && ptr[actual_name_len - die_name_len - 1] == ':')
21384                         name = obstack_strndup (
21385                           &objfile->per_bfd->storage_obstack,
21386                           ptr, actual_name_len - die_name_len - 2);
21387                     }
21388                 }
21389               return name;
21390             }
21391         }
21392     }
21393
21394   return NULL;
21395 }
21396
21397 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
21398    prefix part in such case.  See
21399    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
21400
21401 static const char *
21402 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
21403 {
21404   struct attribute *attr;
21405   const char *base;
21406
21407   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
21408       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
21409     return NULL;
21410
21411   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
21412     return NULL;
21413
21414   attr = dw2_linkage_name_attr (die, cu);
21415   if (attr == NULL || DW_STRING (attr) == NULL)
21416     return NULL;
21417
21418   /* dwarf2_name had to be already called.  */
21419   gdb_assert (DW_STRING_IS_CANONICAL (attr));
21420
21421   /* Strip the base name, keep any leading namespaces/classes.  */
21422   base = strrchr (DW_STRING (attr), ':');
21423   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
21424     return "";
21425
21426   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21427   return obstack_strndup (&objfile->per_bfd->storage_obstack,
21428                           DW_STRING (attr),
21429                           &base[-1] - DW_STRING (attr));
21430 }
21431
21432 /* Return the name of the namespace/class that DIE is defined within,
21433    or "" if we can't tell.  The caller should not xfree the result.
21434
21435    For example, if we're within the method foo() in the following
21436    code:
21437
21438    namespace N {
21439      class C {
21440        void foo () {
21441        }
21442      };
21443    }
21444
21445    then determine_prefix on foo's die will return "N::C".  */
21446
21447 static const char *
21448 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
21449 {
21450   struct dwarf2_per_objfile *dwarf2_per_objfile
21451     = cu->per_cu->dwarf2_per_objfile;
21452   struct die_info *parent, *spec_die;
21453   struct dwarf2_cu *spec_cu;
21454   struct type *parent_type;
21455   const char *retval;
21456
21457   if (cu->language != language_cplus
21458       && cu->language != language_fortran && cu->language != language_d
21459       && cu->language != language_rust)
21460     return "";
21461
21462   retval = anonymous_struct_prefix (die, cu);
21463   if (retval)
21464     return retval;
21465
21466   /* We have to be careful in the presence of DW_AT_specification.
21467      For example, with GCC 3.4, given the code
21468
21469      namespace N {
21470        void foo() {
21471          // Definition of N::foo.
21472        }
21473      }
21474
21475      then we'll have a tree of DIEs like this:
21476
21477      1: DW_TAG_compile_unit
21478        2: DW_TAG_namespace        // N
21479          3: DW_TAG_subprogram     // declaration of N::foo
21480        4: DW_TAG_subprogram       // definition of N::foo
21481             DW_AT_specification   // refers to die #3
21482
21483      Thus, when processing die #4, we have to pretend that we're in
21484      the context of its DW_AT_specification, namely the contex of die
21485      #3.  */
21486   spec_cu = cu;
21487   spec_die = die_specification (die, &spec_cu);
21488   if (spec_die == NULL)
21489     parent = die->parent;
21490   else
21491     {
21492       parent = spec_die->parent;
21493       cu = spec_cu;
21494     }
21495
21496   if (parent == NULL)
21497     return "";
21498   else if (parent->building_fullname)
21499     {
21500       const char *name;
21501       const char *parent_name;
21502
21503       /* It has been seen on RealView 2.2 built binaries,
21504          DW_TAG_template_type_param types actually _defined_ as
21505          children of the parent class:
21506
21507          enum E {};
21508          template class <class Enum> Class{};
21509          Class<enum E> class_e;
21510
21511          1: DW_TAG_class_type (Class)
21512            2: DW_TAG_enumeration_type (E)
21513              3: DW_TAG_enumerator (enum1:0)
21514              3: DW_TAG_enumerator (enum2:1)
21515              ...
21516            2: DW_TAG_template_type_param
21517               DW_AT_type  DW_FORM_ref_udata (E)
21518
21519          Besides being broken debug info, it can put GDB into an
21520          infinite loop.  Consider:
21521
21522          When we're building the full name for Class<E>, we'll start
21523          at Class, and go look over its template type parameters,
21524          finding E.  We'll then try to build the full name of E, and
21525          reach here.  We're now trying to build the full name of E,
21526          and look over the parent DIE for containing scope.  In the
21527          broken case, if we followed the parent DIE of E, we'd again
21528          find Class, and once again go look at its template type
21529          arguments, etc., etc.  Simply don't consider such parent die
21530          as source-level parent of this die (it can't be, the language
21531          doesn't allow it), and break the loop here.  */
21532       name = dwarf2_name (die, cu);
21533       parent_name = dwarf2_name (parent, cu);
21534       complaint (_("template param type '%s' defined within parent '%s'"),
21535                  name ? name : "<unknown>",
21536                  parent_name ? parent_name : "<unknown>");
21537       return "";
21538     }
21539   else
21540     switch (parent->tag)
21541       {
21542       case DW_TAG_namespace:
21543         parent_type = read_type_die (parent, cu);
21544         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
21545            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
21546            Work around this problem here.  */
21547         if (cu->language == language_cplus
21548             && strcmp (TYPE_NAME (parent_type), "::") == 0)
21549           return "";
21550         /* We give a name to even anonymous namespaces.  */
21551         return TYPE_NAME (parent_type);
21552       case DW_TAG_class_type:
21553       case DW_TAG_interface_type:
21554       case DW_TAG_structure_type:
21555       case DW_TAG_union_type:
21556       case DW_TAG_module:
21557         parent_type = read_type_die (parent, cu);
21558         if (TYPE_NAME (parent_type) != NULL)
21559           return TYPE_NAME (parent_type);
21560         else
21561           /* An anonymous structure is only allowed non-static data
21562              members; no typedefs, no member functions, et cetera.
21563              So it does not need a prefix.  */
21564           return "";
21565       case DW_TAG_compile_unit:
21566       case DW_TAG_partial_unit:
21567         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
21568         if (cu->language == language_cplus
21569             && !dwarf2_per_objfile->types.empty ()
21570             && die->child != NULL
21571             && (die->tag == DW_TAG_class_type
21572                 || die->tag == DW_TAG_structure_type
21573                 || die->tag == DW_TAG_union_type))
21574           {
21575             const char *name = guess_full_die_structure_name (die, cu);
21576             if (name != NULL)
21577               return name;
21578           }
21579         return "";
21580       case DW_TAG_subprogram:
21581         /* Nested subroutines in Fortran get a prefix with the name
21582            of the parent's subroutine.  */
21583         if (cu->language == language_fortran)
21584           {
21585             if ((die->tag ==  DW_TAG_subprogram)
21586                 && (dwarf2_name (parent, cu) != NULL))
21587               return dwarf2_name (parent, cu);
21588           }
21589         return determine_prefix (parent, cu);
21590       case DW_TAG_enumeration_type:
21591         parent_type = read_type_die (parent, cu);
21592         if (TYPE_DECLARED_CLASS (parent_type))
21593           {
21594             if (TYPE_NAME (parent_type) != NULL)
21595               return TYPE_NAME (parent_type);
21596             return "";
21597           }
21598         /* Fall through.  */
21599       default:
21600         return determine_prefix (parent, cu);
21601       }
21602 }
21603
21604 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
21605    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
21606    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
21607    an obconcat, otherwise allocate storage for the result.  The CU argument is
21608    used to determine the language and hence, the appropriate separator.  */
21609
21610 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
21611
21612 static char *
21613 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
21614                  int physname, struct dwarf2_cu *cu)
21615 {
21616   const char *lead = "";
21617   const char *sep;
21618
21619   if (suffix == NULL || suffix[0] == '\0'
21620       || prefix == NULL || prefix[0] == '\0')
21621     sep = "";
21622   else if (cu->language == language_d)
21623     {
21624       /* For D, the 'main' function could be defined in any module, but it
21625          should never be prefixed.  */
21626       if (strcmp (suffix, "D main") == 0)
21627         {
21628           prefix = "";
21629           sep = "";
21630         }
21631       else
21632         sep = ".";
21633     }
21634   else if (cu->language == language_fortran && physname)
21635     {
21636       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
21637          DW_AT_MIPS_linkage_name is preferred and used instead.  */
21638
21639       lead = "__";
21640       sep = "_MOD_";
21641     }
21642   else
21643     sep = "::";
21644
21645   if (prefix == NULL)
21646     prefix = "";
21647   if (suffix == NULL)
21648     suffix = "";
21649
21650   if (obs == NULL)
21651     {
21652       char *retval
21653         = ((char *)
21654            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
21655
21656       strcpy (retval, lead);
21657       strcat (retval, prefix);
21658       strcat (retval, sep);
21659       strcat (retval, suffix);
21660       return retval;
21661     }
21662   else
21663     {
21664       /* We have an obstack.  */
21665       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
21666     }
21667 }
21668
21669 /* Return sibling of die, NULL if no sibling.  */
21670
21671 static struct die_info *
21672 sibling_die (struct die_info *die)
21673 {
21674   return die->sibling;
21675 }
21676
21677 /* Get name of a die, return NULL if not found.  */
21678
21679 static const char *
21680 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
21681                           struct obstack *obstack)
21682 {
21683   if (name && cu->language == language_cplus)
21684     {
21685       std::string canon_name = cp_canonicalize_string (name);
21686
21687       if (!canon_name.empty ())
21688         {
21689           if (canon_name != name)
21690             name = obstack_strdup (obstack, canon_name);
21691         }
21692     }
21693
21694   return name;
21695 }
21696
21697 /* Get name of a die, return NULL if not found.
21698    Anonymous namespaces are converted to their magic string.  */
21699
21700 static const char *
21701 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
21702 {
21703   struct attribute *attr;
21704   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21705
21706   attr = dwarf2_attr (die, DW_AT_name, cu);
21707   if ((!attr || !DW_STRING (attr))
21708       && die->tag != DW_TAG_namespace
21709       && die->tag != DW_TAG_class_type
21710       && die->tag != DW_TAG_interface_type
21711       && die->tag != DW_TAG_structure_type
21712       && die->tag != DW_TAG_union_type)
21713     return NULL;
21714
21715   switch (die->tag)
21716     {
21717     case DW_TAG_compile_unit:
21718     case DW_TAG_partial_unit:
21719       /* Compilation units have a DW_AT_name that is a filename, not
21720          a source language identifier.  */
21721     case DW_TAG_enumeration_type:
21722     case DW_TAG_enumerator:
21723       /* These tags always have simple identifiers already; no need
21724          to canonicalize them.  */
21725       return DW_STRING (attr);
21726
21727     case DW_TAG_namespace:
21728       if (attr != NULL && DW_STRING (attr) != NULL)
21729         return DW_STRING (attr);
21730       return CP_ANONYMOUS_NAMESPACE_STR;
21731
21732     case DW_TAG_class_type:
21733     case DW_TAG_interface_type:
21734     case DW_TAG_structure_type:
21735     case DW_TAG_union_type:
21736       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
21737          structures or unions.  These were of the form "._%d" in GCC 4.1,
21738          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
21739          and GCC 4.4.  We work around this problem by ignoring these.  */
21740       if (attr && DW_STRING (attr)
21741           && (startswith (DW_STRING (attr), "._")
21742               || startswith (DW_STRING (attr), "<anonymous")))
21743         return NULL;
21744
21745       /* GCC might emit a nameless typedef that has a linkage name.  See
21746          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
21747       if (!attr || DW_STRING (attr) == NULL)
21748         {
21749           attr = dw2_linkage_name_attr (die, cu);
21750           if (attr == NULL || DW_STRING (attr) == NULL)
21751             return NULL;
21752
21753           /* Avoid demangling DW_STRING (attr) the second time on a second
21754              call for the same DIE.  */
21755           if (!DW_STRING_IS_CANONICAL (attr))
21756             {
21757               gdb::unique_xmalloc_ptr<char> demangled
21758                 (gdb_demangle (DW_STRING (attr), DMGL_TYPES));
21759               if (demangled == nullptr)
21760                 return nullptr;
21761
21762               const char *base;
21763
21764               /* FIXME: we already did this for the partial symbol... */
21765               DW_STRING (attr)
21766                 = obstack_strdup (&objfile->per_bfd->storage_obstack,
21767                                   demangled.get ());
21768               DW_STRING_IS_CANONICAL (attr) = 1;
21769
21770               /* Strip any leading namespaces/classes, keep only the base name.
21771                  DW_AT_name for named DIEs does not contain the prefixes.  */
21772               base = strrchr (DW_STRING (attr), ':');
21773               if (base && base > DW_STRING (attr) && base[-1] == ':')
21774                 return &base[1];
21775               else
21776                 return DW_STRING (attr);
21777             }
21778         }
21779       break;
21780
21781     default:
21782       break;
21783     }
21784
21785   if (!DW_STRING_IS_CANONICAL (attr))
21786     {
21787       DW_STRING (attr)
21788         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
21789                                     &objfile->per_bfd->storage_obstack);
21790       DW_STRING_IS_CANONICAL (attr) = 1;
21791     }
21792   return DW_STRING (attr);
21793 }
21794
21795 /* Return the die that this die in an extension of, or NULL if there
21796    is none.  *EXT_CU is the CU containing DIE on input, and the CU
21797    containing the return value on output.  */
21798
21799 static struct die_info *
21800 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
21801 {
21802   struct attribute *attr;
21803
21804   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
21805   if (attr == NULL)
21806     return NULL;
21807
21808   return follow_die_ref (die, attr, ext_cu);
21809 }
21810
21811 /* A convenience function that returns an "unknown" DWARF name,
21812    including the value of V.  STR is the name of the entity being
21813    printed, e.g., "TAG".  */
21814
21815 static const char *
21816 dwarf_unknown (const char *str, unsigned v)
21817 {
21818   char *cell = get_print_cell ();
21819   xsnprintf (cell, PRINT_CELL_SIZE, "DW_%s_<unknown: %u>", str, v);
21820   return cell;
21821 }
21822
21823 /* Convert a DIE tag into its string name.  */
21824
21825 static const char *
21826 dwarf_tag_name (unsigned tag)
21827 {
21828   const char *name = get_DW_TAG_name (tag);
21829
21830   if (name == NULL)
21831     return dwarf_unknown ("TAG", tag);
21832
21833   return name;
21834 }
21835
21836 /* Convert a DWARF attribute code into its string name.  */
21837
21838 static const char *
21839 dwarf_attr_name (unsigned attr)
21840 {
21841   const char *name;
21842
21843 #ifdef MIPS /* collides with DW_AT_HP_block_index */
21844   if (attr == DW_AT_MIPS_fde)
21845     return "DW_AT_MIPS_fde";
21846 #else
21847   if (attr == DW_AT_HP_block_index)
21848     return "DW_AT_HP_block_index";
21849 #endif
21850
21851   name = get_DW_AT_name (attr);
21852
21853   if (name == NULL)
21854     return dwarf_unknown ("AT", attr);
21855
21856   return name;
21857 }
21858
21859 /* Convert a DWARF value form code into its string name.  */
21860
21861 static const char *
21862 dwarf_form_name (unsigned form)
21863 {
21864   const char *name = get_DW_FORM_name (form);
21865
21866   if (name == NULL)
21867     return dwarf_unknown ("FORM", form);
21868
21869   return name;
21870 }
21871
21872 static const char *
21873 dwarf_bool_name (unsigned mybool)
21874 {
21875   if (mybool)
21876     return "TRUE";
21877   else
21878     return "FALSE";
21879 }
21880
21881 /* Convert a DWARF type code into its string name.  */
21882
21883 static const char *
21884 dwarf_type_encoding_name (unsigned enc)
21885 {
21886   const char *name = get_DW_ATE_name (enc);
21887
21888   if (name == NULL)
21889     return dwarf_unknown ("ATE", enc);
21890
21891   return name;
21892 }
21893
21894 static void
21895 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
21896 {
21897   unsigned int i;
21898
21899   print_spaces (indent, f);
21900   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
21901                       dwarf_tag_name (die->tag), die->abbrev,
21902                       sect_offset_str (die->sect_off));
21903
21904   if (die->parent != NULL)
21905     {
21906       print_spaces (indent, f);
21907       fprintf_unfiltered (f, "  parent at offset: %s\n",
21908                           sect_offset_str (die->parent->sect_off));
21909     }
21910
21911   print_spaces (indent, f);
21912   fprintf_unfiltered (f, "  has children: %s\n",
21913            dwarf_bool_name (die->child != NULL));
21914
21915   print_spaces (indent, f);
21916   fprintf_unfiltered (f, "  attributes:\n");
21917
21918   for (i = 0; i < die->num_attrs; ++i)
21919     {
21920       print_spaces (indent, f);
21921       fprintf_unfiltered (f, "    %s (%s) ",
21922                dwarf_attr_name (die->attrs[i].name),
21923                dwarf_form_name (die->attrs[i].form));
21924
21925       switch (die->attrs[i].form)
21926         {
21927         case DW_FORM_addr:
21928         case DW_FORM_addrx:
21929         case DW_FORM_GNU_addr_index:
21930           fprintf_unfiltered (f, "address: ");
21931           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
21932           break;
21933         case DW_FORM_block2:
21934         case DW_FORM_block4:
21935         case DW_FORM_block:
21936         case DW_FORM_block1:
21937           fprintf_unfiltered (f, "block: size %s",
21938                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21939           break;
21940         case DW_FORM_exprloc:
21941           fprintf_unfiltered (f, "expression: size %s",
21942                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21943           break;
21944         case DW_FORM_data16:
21945           fprintf_unfiltered (f, "constant of 16 bytes");
21946           break;
21947         case DW_FORM_ref_addr:
21948           fprintf_unfiltered (f, "ref address: ");
21949           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21950           break;
21951         case DW_FORM_GNU_ref_alt:
21952           fprintf_unfiltered (f, "alt ref address: ");
21953           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21954           break;
21955         case DW_FORM_ref1:
21956         case DW_FORM_ref2:
21957         case DW_FORM_ref4:
21958         case DW_FORM_ref8:
21959         case DW_FORM_ref_udata:
21960           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
21961                               (long) (DW_UNSND (&die->attrs[i])));
21962           break;
21963         case DW_FORM_data1:
21964         case DW_FORM_data2:
21965         case DW_FORM_data4:
21966         case DW_FORM_data8:
21967         case DW_FORM_udata:
21968         case DW_FORM_sdata:
21969           fprintf_unfiltered (f, "constant: %s",
21970                               pulongest (DW_UNSND (&die->attrs[i])));
21971           break;
21972         case DW_FORM_sec_offset:
21973           fprintf_unfiltered (f, "section offset: %s",
21974                               pulongest (DW_UNSND (&die->attrs[i])));
21975           break;
21976         case DW_FORM_ref_sig8:
21977           fprintf_unfiltered (f, "signature: %s",
21978                               hex_string (DW_SIGNATURE (&die->attrs[i])));
21979           break;
21980         case DW_FORM_string:
21981         case DW_FORM_strp:
21982         case DW_FORM_line_strp:
21983         case DW_FORM_strx:
21984         case DW_FORM_GNU_str_index:
21985         case DW_FORM_GNU_strp_alt:
21986           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
21987                    DW_STRING (&die->attrs[i])
21988                    ? DW_STRING (&die->attrs[i]) : "",
21989                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
21990           break;
21991         case DW_FORM_flag:
21992           if (DW_UNSND (&die->attrs[i]))
21993             fprintf_unfiltered (f, "flag: TRUE");
21994           else
21995             fprintf_unfiltered (f, "flag: FALSE");
21996           break;
21997         case DW_FORM_flag_present:
21998           fprintf_unfiltered (f, "flag: TRUE");
21999           break;
22000         case DW_FORM_indirect:
22001           /* The reader will have reduced the indirect form to
22002              the "base form" so this form should not occur.  */
22003           fprintf_unfiltered (f,
22004                               "unexpected attribute form: DW_FORM_indirect");
22005           break;
22006         case DW_FORM_implicit_const:
22007           fprintf_unfiltered (f, "constant: %s",
22008                               plongest (DW_SND (&die->attrs[i])));
22009           break;
22010         default:
22011           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22012                    die->attrs[i].form);
22013           break;
22014         }
22015       fprintf_unfiltered (f, "\n");
22016     }
22017 }
22018
22019 static void
22020 dump_die_for_error (struct die_info *die)
22021 {
22022   dump_die_shallow (gdb_stderr, 0, die);
22023 }
22024
22025 static void
22026 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22027 {
22028   int indent = level * 4;
22029
22030   gdb_assert (die != NULL);
22031
22032   if (level >= max_level)
22033     return;
22034
22035   dump_die_shallow (f, indent, die);
22036
22037   if (die->child != NULL)
22038     {
22039       print_spaces (indent, f);
22040       fprintf_unfiltered (f, "  Children:");
22041       if (level + 1 < max_level)
22042         {
22043           fprintf_unfiltered (f, "\n");
22044           dump_die_1 (f, level + 1, max_level, die->child);
22045         }
22046       else
22047         {
22048           fprintf_unfiltered (f,
22049                               " [not printed, max nesting level reached]\n");
22050         }
22051     }
22052
22053   if (die->sibling != NULL && level > 0)
22054     {
22055       dump_die_1 (f, level, max_level, die->sibling);
22056     }
22057 }
22058
22059 /* This is called from the pdie macro in gdbinit.in.
22060    It's not static so gcc will keep a copy callable from gdb.  */
22061
22062 void
22063 dump_die (struct die_info *die, int max_level)
22064 {
22065   dump_die_1 (gdb_stdlog, 0, max_level, die);
22066 }
22067
22068 static void
22069 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22070 {
22071   void **slot;
22072
22073   slot = htab_find_slot_with_hash (cu->die_hash, die,
22074                                    to_underlying (die->sect_off),
22075                                    INSERT);
22076
22077   *slot = die;
22078 }
22079
22080 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22081    required kind.  */
22082
22083 static sect_offset
22084 dwarf2_get_ref_die_offset (const struct attribute *attr)
22085 {
22086   if (attr->form_is_ref ())
22087     return (sect_offset) DW_UNSND (attr);
22088
22089   complaint (_("unsupported die ref attribute form: '%s'"),
22090              dwarf_form_name (attr->form));
22091   return {};
22092 }
22093
22094 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22095  * the value held by the attribute is not constant.  */
22096
22097 static LONGEST
22098 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22099 {
22100   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22101     return DW_SND (attr);
22102   else if (attr->form == DW_FORM_udata
22103            || attr->form == DW_FORM_data1
22104            || attr->form == DW_FORM_data2
22105            || attr->form == DW_FORM_data4
22106            || attr->form == DW_FORM_data8)
22107     return DW_UNSND (attr);
22108   else
22109     {
22110       /* For DW_FORM_data16 see attribute::form_is_constant.  */
22111       complaint (_("Attribute value is not a constant (%s)"),
22112                  dwarf_form_name (attr->form));
22113       return default_value;
22114     }
22115 }
22116
22117 /* Follow reference or signature attribute ATTR of SRC_DIE.
22118    On entry *REF_CU is the CU of SRC_DIE.
22119    On exit *REF_CU is the CU of the result.  */
22120
22121 static struct die_info *
22122 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22123                        struct dwarf2_cu **ref_cu)
22124 {
22125   struct die_info *die;
22126
22127   if (attr->form_is_ref ())
22128     die = follow_die_ref (src_die, attr, ref_cu);
22129   else if (attr->form == DW_FORM_ref_sig8)
22130     die = follow_die_sig (src_die, attr, ref_cu);
22131   else
22132     {
22133       dump_die_for_error (src_die);
22134       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22135              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22136     }
22137
22138   return die;
22139 }
22140
22141 /* Follow reference OFFSET.
22142    On entry *REF_CU is the CU of the source die referencing OFFSET.
22143    On exit *REF_CU is the CU of the result.
22144    Returns NULL if OFFSET is invalid.  */
22145
22146 static struct die_info *
22147 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22148                    struct dwarf2_cu **ref_cu)
22149 {
22150   struct die_info temp_die;
22151   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22152   struct dwarf2_per_objfile *dwarf2_per_objfile
22153     = cu->per_cu->dwarf2_per_objfile;
22154
22155   gdb_assert (cu->per_cu != NULL);
22156
22157   target_cu = cu;
22158
22159   if (cu->per_cu->is_debug_types)
22160     {
22161       /* .debug_types CUs cannot reference anything outside their CU.
22162          If they need to, they have to reference a signatured type via
22163          DW_FORM_ref_sig8.  */
22164       if (!cu->header.offset_in_cu_p (sect_off))
22165         return NULL;
22166     }
22167   else if (offset_in_dwz != cu->per_cu->is_dwz
22168            || !cu->header.offset_in_cu_p (sect_off))
22169     {
22170       struct dwarf2_per_cu_data *per_cu;
22171
22172       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22173                                                  dwarf2_per_objfile);
22174
22175       /* If necessary, add it to the queue and load its DIEs.  */
22176       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22177         load_full_comp_unit (per_cu, false, cu->language);
22178
22179       target_cu = per_cu->cu;
22180     }
22181   else if (cu->dies == NULL)
22182     {
22183       /* We're loading full DIEs during partial symbol reading.  */
22184       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22185       load_full_comp_unit (cu->per_cu, false, language_minimal);
22186     }
22187
22188   *ref_cu = target_cu;
22189   temp_die.sect_off = sect_off;
22190
22191   if (target_cu != cu)
22192     target_cu->ancestor = cu;
22193
22194   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22195                                                   &temp_die,
22196                                                   to_underlying (sect_off));
22197 }
22198
22199 /* Follow reference attribute ATTR of SRC_DIE.
22200    On entry *REF_CU is the CU of SRC_DIE.
22201    On exit *REF_CU is the CU of the result.  */
22202
22203 static struct die_info *
22204 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22205                 struct dwarf2_cu **ref_cu)
22206 {
22207   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22208   struct dwarf2_cu *cu = *ref_cu;
22209   struct die_info *die;
22210
22211   die = follow_die_offset (sect_off,
22212                            (attr->form == DW_FORM_GNU_ref_alt
22213                             || cu->per_cu->is_dwz),
22214                            ref_cu);
22215   if (!die)
22216     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22217            "at %s [in module %s]"),
22218            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22219            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22220
22221   return die;
22222 }
22223
22224 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22225    Returned value is intended for DW_OP_call*.  Returned
22226    dwarf2_locexpr_baton->data has lifetime of
22227    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22228
22229 struct dwarf2_locexpr_baton
22230 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22231                                struct dwarf2_per_cu_data *per_cu,
22232                                CORE_ADDR (*get_frame_pc) (void *baton),
22233                                void *baton, bool resolve_abstract_p)
22234 {
22235   struct dwarf2_cu *cu;
22236   struct die_info *die;
22237   struct attribute *attr;
22238   struct dwarf2_locexpr_baton retval;
22239   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22240   struct objfile *objfile = dwarf2_per_objfile->objfile;
22241
22242   if (per_cu->cu == NULL)
22243     load_cu (per_cu, false);
22244   cu = per_cu->cu;
22245   if (cu == NULL)
22246     {
22247       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22248          Instead just throw an error, not much else we can do.  */
22249       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22250              sect_offset_str (sect_off), objfile_name (objfile));
22251     }
22252
22253   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22254   if (!die)
22255     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22256            sect_offset_str (sect_off), objfile_name (objfile));
22257
22258   attr = dwarf2_attr (die, DW_AT_location, cu);
22259   if (!attr && resolve_abstract_p
22260       && (dwarf2_per_objfile->abstract_to_concrete.find (die->sect_off)
22261           != dwarf2_per_objfile->abstract_to_concrete.end ()))
22262     {
22263       CORE_ADDR pc = (*get_frame_pc) (baton);
22264       CORE_ADDR baseaddr = objfile->text_section_offset ();
22265       struct gdbarch *gdbarch = get_objfile_arch (objfile);
22266
22267       for (const auto &cand_off
22268              : dwarf2_per_objfile->abstract_to_concrete[die->sect_off])
22269         {
22270           struct dwarf2_cu *cand_cu = cu;
22271           struct die_info *cand
22272             = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
22273           if (!cand
22274               || !cand->parent
22275               || cand->parent->tag != DW_TAG_subprogram)
22276             continue;
22277
22278           CORE_ADDR pc_low, pc_high;
22279           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
22280           if (pc_low == ((CORE_ADDR) -1))
22281             continue;
22282           pc_low = gdbarch_adjust_dwarf2_addr (gdbarch, pc_low + baseaddr);
22283           pc_high = gdbarch_adjust_dwarf2_addr (gdbarch, pc_high + baseaddr);
22284           if (!(pc_low <= pc && pc < pc_high))
22285             continue;
22286
22287           die = cand;
22288           attr = dwarf2_attr (die, DW_AT_location, cu);
22289           break;
22290         }
22291     }
22292
22293   if (!attr)
22294     {
22295       /* DWARF: "If there is no such attribute, then there is no effect.".
22296          DATA is ignored if SIZE is 0.  */
22297
22298       retval.data = NULL;
22299       retval.size = 0;
22300     }
22301   else if (attr->form_is_section_offset ())
22302     {
22303       struct dwarf2_loclist_baton loclist_baton;
22304       CORE_ADDR pc = (*get_frame_pc) (baton);
22305       size_t size;
22306
22307       fill_in_loclist_baton (cu, &loclist_baton, attr);
22308
22309       retval.data = dwarf2_find_location_expression (&loclist_baton,
22310                                                      &size, pc);
22311       retval.size = size;
22312     }
22313   else
22314     {
22315       if (!attr->form_is_block ())
22316         error (_("Dwarf Error: DIE at %s referenced in module %s "
22317                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22318                sect_offset_str (sect_off), objfile_name (objfile));
22319
22320       retval.data = DW_BLOCK (attr)->data;
22321       retval.size = DW_BLOCK (attr)->size;
22322     }
22323   retval.per_cu = cu->per_cu;
22324
22325   age_cached_comp_units (dwarf2_per_objfile);
22326
22327   return retval;
22328 }
22329
22330 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22331    offset.  */
22332
22333 struct dwarf2_locexpr_baton
22334 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22335                              struct dwarf2_per_cu_data *per_cu,
22336                              CORE_ADDR (*get_frame_pc) (void *baton),
22337                              void *baton)
22338 {
22339   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22340
22341   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22342 }
22343
22344 /* Write a constant of a given type as target-ordered bytes into
22345    OBSTACK.  */
22346
22347 static const gdb_byte *
22348 write_constant_as_bytes (struct obstack *obstack,
22349                          enum bfd_endian byte_order,
22350                          struct type *type,
22351                          ULONGEST value,
22352                          LONGEST *len)
22353 {
22354   gdb_byte *result;
22355
22356   *len = TYPE_LENGTH (type);
22357   result = (gdb_byte *) obstack_alloc (obstack, *len);
22358   store_unsigned_integer (result, *len, byte_order, value);
22359
22360   return result;
22361 }
22362
22363 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22364    pointer to the constant bytes and set LEN to the length of the
22365    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22366    does not have a DW_AT_const_value, return NULL.  */
22367
22368 const gdb_byte *
22369 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22370                              struct dwarf2_per_cu_data *per_cu,
22371                              struct obstack *obstack,
22372                              LONGEST *len)
22373 {
22374   struct dwarf2_cu *cu;
22375   struct die_info *die;
22376   struct attribute *attr;
22377   const gdb_byte *result = NULL;
22378   struct type *type;
22379   LONGEST value;
22380   enum bfd_endian byte_order;
22381   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22382
22383   if (per_cu->cu == NULL)
22384     load_cu (per_cu, false);
22385   cu = per_cu->cu;
22386   if (cu == NULL)
22387     {
22388       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22389          Instead just throw an error, not much else we can do.  */
22390       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22391              sect_offset_str (sect_off), objfile_name (objfile));
22392     }
22393
22394   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22395   if (!die)
22396     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22397            sect_offset_str (sect_off), objfile_name (objfile));
22398
22399   attr = dwarf2_attr (die, DW_AT_const_value, cu);
22400   if (attr == NULL)
22401     return NULL;
22402
22403   byte_order = (bfd_big_endian (objfile->obfd)
22404                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22405
22406   switch (attr->form)
22407     {
22408     case DW_FORM_addr:
22409     case DW_FORM_addrx:
22410     case DW_FORM_GNU_addr_index:
22411       {
22412         gdb_byte *tem;
22413
22414         *len = cu->header.addr_size;
22415         tem = (gdb_byte *) obstack_alloc (obstack, *len);
22416         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
22417         result = tem;
22418       }
22419       break;
22420     case DW_FORM_string:
22421     case DW_FORM_strp:
22422     case DW_FORM_strx:
22423     case DW_FORM_GNU_str_index:
22424     case DW_FORM_GNU_strp_alt:
22425       /* DW_STRING is already allocated on the objfile obstack, point
22426          directly to it.  */
22427       result = (const gdb_byte *) DW_STRING (attr);
22428       *len = strlen (DW_STRING (attr));
22429       break;
22430     case DW_FORM_block1:
22431     case DW_FORM_block2:
22432     case DW_FORM_block4:
22433     case DW_FORM_block:
22434     case DW_FORM_exprloc:
22435     case DW_FORM_data16:
22436       result = DW_BLOCK (attr)->data;
22437       *len = DW_BLOCK (attr)->size;
22438       break;
22439
22440       /* The DW_AT_const_value attributes are supposed to carry the
22441          symbol's value "represented as it would be on the target
22442          architecture."  By the time we get here, it's already been
22443          converted to host endianness, so we just need to sign- or
22444          zero-extend it as appropriate.  */
22445     case DW_FORM_data1:
22446       type = die_type (die, cu);
22447       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
22448       if (result == NULL)
22449         result = write_constant_as_bytes (obstack, byte_order,
22450                                           type, value, len);
22451       break;
22452     case DW_FORM_data2:
22453       type = die_type (die, cu);
22454       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
22455       if (result == NULL)
22456         result = write_constant_as_bytes (obstack, byte_order,
22457                                           type, value, len);
22458       break;
22459     case DW_FORM_data4:
22460       type = die_type (die, cu);
22461       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
22462       if (result == NULL)
22463         result = write_constant_as_bytes (obstack, byte_order,
22464                                           type, value, len);
22465       break;
22466     case DW_FORM_data8:
22467       type = die_type (die, cu);
22468       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
22469       if (result == NULL)
22470         result = write_constant_as_bytes (obstack, byte_order,
22471                                           type, value, len);
22472       break;
22473
22474     case DW_FORM_sdata:
22475     case DW_FORM_implicit_const:
22476       type = die_type (die, cu);
22477       result = write_constant_as_bytes (obstack, byte_order,
22478                                         type, DW_SND (attr), len);
22479       break;
22480
22481     case DW_FORM_udata:
22482       type = die_type (die, cu);
22483       result = write_constant_as_bytes (obstack, byte_order,
22484                                         type, DW_UNSND (attr), len);
22485       break;
22486
22487     default:
22488       complaint (_("unsupported const value attribute form: '%s'"),
22489                  dwarf_form_name (attr->form));
22490       break;
22491     }
22492
22493   return result;
22494 }
22495
22496 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
22497    valid type for this die is found.  */
22498
22499 struct type *
22500 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
22501                                 struct dwarf2_per_cu_data *per_cu)
22502 {
22503   struct dwarf2_cu *cu;
22504   struct die_info *die;
22505
22506   if (per_cu->cu == NULL)
22507     load_cu (per_cu, false);
22508   cu = per_cu->cu;
22509   if (!cu)
22510     return NULL;
22511
22512   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22513   if (!die)
22514     return NULL;
22515
22516   return die_type (die, cu);
22517 }
22518
22519 /* Return the type of the DIE at DIE_OFFSET in the CU named by
22520    PER_CU.  */
22521
22522 struct type *
22523 dwarf2_get_die_type (cu_offset die_offset,
22524                      struct dwarf2_per_cu_data *per_cu)
22525 {
22526   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
22527   return get_die_type_at_offset (die_offset_sect, per_cu);
22528 }
22529
22530 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
22531    On entry *REF_CU is the CU of SRC_DIE.
22532    On exit *REF_CU is the CU of the result.
22533    Returns NULL if the referenced DIE isn't found.  */
22534
22535 static struct die_info *
22536 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
22537                   struct dwarf2_cu **ref_cu)
22538 {
22539   struct die_info temp_die;
22540   struct dwarf2_cu *sig_cu, *cu = *ref_cu;
22541   struct die_info *die;
22542
22543   /* While it might be nice to assert sig_type->type == NULL here,
22544      we can get here for DW_AT_imported_declaration where we need
22545      the DIE not the type.  */
22546
22547   /* If necessary, add it to the queue and load its DIEs.  */
22548
22549   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
22550     read_signatured_type (sig_type);
22551
22552   sig_cu = sig_type->per_cu.cu;
22553   gdb_assert (sig_cu != NULL);
22554   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
22555   temp_die.sect_off = sig_type->type_offset_in_section;
22556   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
22557                                                  to_underlying (temp_die.sect_off));
22558   if (die)
22559     {
22560       struct dwarf2_per_objfile *dwarf2_per_objfile
22561         = (*ref_cu)->per_cu->dwarf2_per_objfile;
22562
22563       /* For .gdb_index version 7 keep track of included TUs.
22564          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
22565       if (dwarf2_per_objfile->index_table != NULL
22566           && dwarf2_per_objfile->index_table->version <= 7)
22567         {
22568           (*ref_cu)->per_cu->imported_symtabs_push (sig_cu->per_cu);
22569         }
22570
22571       *ref_cu = sig_cu;
22572       if (sig_cu != cu)
22573         sig_cu->ancestor = cu;
22574
22575       return die;
22576     }
22577
22578   return NULL;
22579 }
22580
22581 /* Follow signatured type referenced by ATTR in SRC_DIE.
22582    On entry *REF_CU is the CU of SRC_DIE.
22583    On exit *REF_CU is the CU of the result.
22584    The result is the DIE of the type.
22585    If the referenced type cannot be found an error is thrown.  */
22586
22587 static struct die_info *
22588 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
22589                 struct dwarf2_cu **ref_cu)
22590 {
22591   ULONGEST signature = DW_SIGNATURE (attr);
22592   struct signatured_type *sig_type;
22593   struct die_info *die;
22594
22595   gdb_assert (attr->form == DW_FORM_ref_sig8);
22596
22597   sig_type = lookup_signatured_type (*ref_cu, signature);
22598   /* sig_type will be NULL if the signatured type is missing from
22599      the debug info.  */
22600   if (sig_type == NULL)
22601     {
22602       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
22603                " from DIE at %s [in module %s]"),
22604              hex_string (signature), sect_offset_str (src_die->sect_off),
22605              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22606     }
22607
22608   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
22609   if (die == NULL)
22610     {
22611       dump_die_for_error (src_die);
22612       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
22613                " from DIE at %s [in module %s]"),
22614              hex_string (signature), sect_offset_str (src_die->sect_off),
22615              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22616     }
22617
22618   return die;
22619 }
22620
22621 /* Get the type specified by SIGNATURE referenced in DIE/CU,
22622    reading in and processing the type unit if necessary.  */
22623
22624 static struct type *
22625 get_signatured_type (struct die_info *die, ULONGEST signature,
22626                      struct dwarf2_cu *cu)
22627 {
22628   struct dwarf2_per_objfile *dwarf2_per_objfile
22629     = cu->per_cu->dwarf2_per_objfile;
22630   struct signatured_type *sig_type;
22631   struct dwarf2_cu *type_cu;
22632   struct die_info *type_die;
22633   struct type *type;
22634
22635   sig_type = lookup_signatured_type (cu, signature);
22636   /* sig_type will be NULL if the signatured type is missing from
22637      the debug info.  */
22638   if (sig_type == NULL)
22639     {
22640       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
22641                    " from DIE at %s [in module %s]"),
22642                  hex_string (signature), sect_offset_str (die->sect_off),
22643                  objfile_name (dwarf2_per_objfile->objfile));
22644       return build_error_marker_type (cu, die);
22645     }
22646
22647   /* If we already know the type we're done.  */
22648   if (sig_type->type != NULL)
22649     return sig_type->type;
22650
22651   type_cu = cu;
22652   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
22653   if (type_die != NULL)
22654     {
22655       /* N.B. We need to call get_die_type to ensure only one type for this DIE
22656          is created.  This is important, for example, because for c++ classes
22657          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
22658       type = read_type_die (type_die, type_cu);
22659       if (type == NULL)
22660         {
22661           complaint (_("Dwarf Error: Cannot build signatured type %s"
22662                        " referenced from DIE at %s [in module %s]"),
22663                      hex_string (signature), sect_offset_str (die->sect_off),
22664                      objfile_name (dwarf2_per_objfile->objfile));
22665           type = build_error_marker_type (cu, die);
22666         }
22667     }
22668   else
22669     {
22670       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
22671                    " from DIE at %s [in module %s]"),
22672                  hex_string (signature), sect_offset_str (die->sect_off),
22673                  objfile_name (dwarf2_per_objfile->objfile));
22674       type = build_error_marker_type (cu, die);
22675     }
22676   sig_type->type = type;
22677
22678   return type;
22679 }
22680
22681 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
22682    reading in and processing the type unit if necessary.  */
22683
22684 static struct type *
22685 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
22686                           struct dwarf2_cu *cu) /* ARI: editCase function */
22687 {
22688   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
22689   if (attr->form_is_ref ())
22690     {
22691       struct dwarf2_cu *type_cu = cu;
22692       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
22693
22694       return read_type_die (type_die, type_cu);
22695     }
22696   else if (attr->form == DW_FORM_ref_sig8)
22697     {
22698       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
22699     }
22700   else
22701     {
22702       struct dwarf2_per_objfile *dwarf2_per_objfile
22703         = cu->per_cu->dwarf2_per_objfile;
22704
22705       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
22706                    " at %s [in module %s]"),
22707                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
22708                  objfile_name (dwarf2_per_objfile->objfile));
22709       return build_error_marker_type (cu, die);
22710     }
22711 }
22712
22713 /* Load the DIEs associated with type unit PER_CU into memory.  */
22714
22715 static void
22716 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
22717 {
22718   struct signatured_type *sig_type;
22719
22720   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
22721   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
22722
22723   /* We have the per_cu, but we need the signatured_type.
22724      Fortunately this is an easy translation.  */
22725   gdb_assert (per_cu->is_debug_types);
22726   sig_type = (struct signatured_type *) per_cu;
22727
22728   gdb_assert (per_cu->cu == NULL);
22729
22730   read_signatured_type (sig_type);
22731
22732   gdb_assert (per_cu->cu != NULL);
22733 }
22734
22735 /* Read in a signatured type and build its CU and DIEs.
22736    If the type is a stub for the real type in a DWO file,
22737    read in the real type from the DWO file as well.  */
22738
22739 static void
22740 read_signatured_type (struct signatured_type *sig_type)
22741 {
22742   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
22743
22744   gdb_assert (per_cu->is_debug_types);
22745   gdb_assert (per_cu->cu == NULL);
22746
22747   cutu_reader reader (per_cu, NULL, 0, false);
22748
22749   if (!reader.dummy_p)
22750     {
22751       struct dwarf2_cu *cu = reader.cu;
22752       const gdb_byte *info_ptr = reader.info_ptr;
22753
22754       gdb_assert (cu->die_hash == NULL);
22755       cu->die_hash =
22756         htab_create_alloc_ex (cu->header.length / 12,
22757                               die_hash,
22758                               die_eq,
22759                               NULL,
22760                               &cu->comp_unit_obstack,
22761                               hashtab_obstack_allocate,
22762                               dummy_obstack_deallocate);
22763
22764       if (reader.comp_unit_die->has_children)
22765         reader.comp_unit_die->child
22766           = read_die_and_siblings (&reader, info_ptr, &info_ptr,
22767                                    reader.comp_unit_die);
22768       cu->dies = reader.comp_unit_die;
22769       /* comp_unit_die is not stored in die_hash, no need.  */
22770
22771       /* We try not to read any attributes in this function, because
22772          not all CUs needed for references have been loaded yet, and
22773          symbol table processing isn't initialized.  But we have to
22774          set the CU language, or we won't be able to build types
22775          correctly.  Similarly, if we do not read the producer, we can
22776          not apply producer-specific interpretation.  */
22777       prepare_one_comp_unit (cu, cu->dies, language_minimal);
22778
22779       reader.keep ();
22780     }
22781
22782   sig_type->per_cu.tu_read = 1;
22783 }
22784
22785 /* Decode simple location descriptions.
22786    Given a pointer to a dwarf block that defines a location, compute
22787    the location and return the value.
22788
22789    NOTE drow/2003-11-18: This function is called in two situations
22790    now: for the address of static or global variables (partial symbols
22791    only) and for offsets into structures which are expected to be
22792    (more or less) constant.  The partial symbol case should go away,
22793    and only the constant case should remain.  That will let this
22794    function complain more accurately.  A few special modes are allowed
22795    without complaint for global variables (for instance, global
22796    register values and thread-local values).
22797
22798    A location description containing no operations indicates that the
22799    object is optimized out.  The return value is 0 for that case.
22800    FIXME drow/2003-11-16: No callers check for this case any more; soon all
22801    callers will only want a very basic result and this can become a
22802    complaint.
22803
22804    Note that stack[0] is unused except as a default error return.  */
22805
22806 static CORE_ADDR
22807 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
22808 {
22809   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22810   size_t i;
22811   size_t size = blk->size;
22812   const gdb_byte *data = blk->data;
22813   CORE_ADDR stack[64];
22814   int stacki;
22815   unsigned int bytes_read, unsnd;
22816   gdb_byte op;
22817
22818   i = 0;
22819   stacki = 0;
22820   stack[stacki] = 0;
22821   stack[++stacki] = 0;
22822
22823   while (i < size)
22824     {
22825       op = data[i++];
22826       switch (op)
22827         {
22828         case DW_OP_lit0:
22829         case DW_OP_lit1:
22830         case DW_OP_lit2:
22831         case DW_OP_lit3:
22832         case DW_OP_lit4:
22833         case DW_OP_lit5:
22834         case DW_OP_lit6:
22835         case DW_OP_lit7:
22836         case DW_OP_lit8:
22837         case DW_OP_lit9:
22838         case DW_OP_lit10:
22839         case DW_OP_lit11:
22840         case DW_OP_lit12:
22841         case DW_OP_lit13:
22842         case DW_OP_lit14:
22843         case DW_OP_lit15:
22844         case DW_OP_lit16:
22845         case DW_OP_lit17:
22846         case DW_OP_lit18:
22847         case DW_OP_lit19:
22848         case DW_OP_lit20:
22849         case DW_OP_lit21:
22850         case DW_OP_lit22:
22851         case DW_OP_lit23:
22852         case DW_OP_lit24:
22853         case DW_OP_lit25:
22854         case DW_OP_lit26:
22855         case DW_OP_lit27:
22856         case DW_OP_lit28:
22857         case DW_OP_lit29:
22858         case DW_OP_lit30:
22859         case DW_OP_lit31:
22860           stack[++stacki] = op - DW_OP_lit0;
22861           break;
22862
22863         case DW_OP_reg0:
22864         case DW_OP_reg1:
22865         case DW_OP_reg2:
22866         case DW_OP_reg3:
22867         case DW_OP_reg4:
22868         case DW_OP_reg5:
22869         case DW_OP_reg6:
22870         case DW_OP_reg7:
22871         case DW_OP_reg8:
22872         case DW_OP_reg9:
22873         case DW_OP_reg10:
22874         case DW_OP_reg11:
22875         case DW_OP_reg12:
22876         case DW_OP_reg13:
22877         case DW_OP_reg14:
22878         case DW_OP_reg15:
22879         case DW_OP_reg16:
22880         case DW_OP_reg17:
22881         case DW_OP_reg18:
22882         case DW_OP_reg19:
22883         case DW_OP_reg20:
22884         case DW_OP_reg21:
22885         case DW_OP_reg22:
22886         case DW_OP_reg23:
22887         case DW_OP_reg24:
22888         case DW_OP_reg25:
22889         case DW_OP_reg26:
22890         case DW_OP_reg27:
22891         case DW_OP_reg28:
22892         case DW_OP_reg29:
22893         case DW_OP_reg30:
22894         case DW_OP_reg31:
22895           stack[++stacki] = op - DW_OP_reg0;
22896           if (i < size)
22897             dwarf2_complex_location_expr_complaint ();
22898           break;
22899
22900         case DW_OP_regx:
22901           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
22902           i += bytes_read;
22903           stack[++stacki] = unsnd;
22904           if (i < size)
22905             dwarf2_complex_location_expr_complaint ();
22906           break;
22907
22908         case DW_OP_addr:
22909           stack[++stacki] = cu->header.read_address (objfile->obfd, &data[i],
22910                                                      &bytes_read);
22911           i += bytes_read;
22912           break;
22913
22914         case DW_OP_const1u:
22915           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
22916           i += 1;
22917           break;
22918
22919         case DW_OP_const1s:
22920           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
22921           i += 1;
22922           break;
22923
22924         case DW_OP_const2u:
22925           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
22926           i += 2;
22927           break;
22928
22929         case DW_OP_const2s:
22930           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
22931           i += 2;
22932           break;
22933
22934         case DW_OP_const4u:
22935           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
22936           i += 4;
22937           break;
22938
22939         case DW_OP_const4s:
22940           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
22941           i += 4;
22942           break;
22943
22944         case DW_OP_const8u:
22945           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
22946           i += 8;
22947           break;
22948
22949         case DW_OP_constu:
22950           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
22951                                                   &bytes_read);
22952           i += bytes_read;
22953           break;
22954
22955         case DW_OP_consts:
22956           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
22957           i += bytes_read;
22958           break;
22959
22960         case DW_OP_dup:
22961           stack[stacki + 1] = stack[stacki];
22962           stacki++;
22963           break;
22964
22965         case DW_OP_plus:
22966           stack[stacki - 1] += stack[stacki];
22967           stacki--;
22968           break;
22969
22970         case DW_OP_plus_uconst:
22971           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
22972                                                  &bytes_read);
22973           i += bytes_read;
22974           break;
22975
22976         case DW_OP_minus:
22977           stack[stacki - 1] -= stack[stacki];
22978           stacki--;
22979           break;
22980
22981         case DW_OP_deref:
22982           /* If we're not the last op, then we definitely can't encode
22983              this using GDB's address_class enum.  This is valid for partial
22984              global symbols, although the variable's address will be bogus
22985              in the psymtab.  */
22986           if (i < size)
22987             dwarf2_complex_location_expr_complaint ();
22988           break;
22989
22990         case DW_OP_GNU_push_tls_address:
22991         case DW_OP_form_tls_address:
22992           /* The top of the stack has the offset from the beginning
22993              of the thread control block at which the variable is located.  */
22994           /* Nothing should follow this operator, so the top of stack would
22995              be returned.  */
22996           /* This is valid for partial global symbols, but the variable's
22997              address will be bogus in the psymtab.  Make it always at least
22998              non-zero to not look as a variable garbage collected by linker
22999              which have DW_OP_addr 0.  */
23000           if (i < size)
23001             dwarf2_complex_location_expr_complaint ();
23002           stack[stacki]++;
23003           break;
23004
23005         case DW_OP_GNU_uninit:
23006           break;
23007
23008         case DW_OP_addrx:
23009         case DW_OP_GNU_addr_index:
23010         case DW_OP_GNU_const_index:
23011           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23012                                                          &bytes_read);
23013           i += bytes_read;
23014           break;
23015
23016         default:
23017           {
23018             const char *name = get_DW_OP_name (op);
23019
23020             if (name)
23021               complaint (_("unsupported stack op: '%s'"),
23022                          name);
23023             else
23024               complaint (_("unsupported stack op: '%02x'"),
23025                          op);
23026           }
23027
23028           return (stack[stacki]);
23029         }
23030
23031       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23032          outside of the allocated space.  Also enforce minimum>0.  */
23033       if (stacki >= ARRAY_SIZE (stack) - 1)
23034         {
23035           complaint (_("location description stack overflow"));
23036           return 0;
23037         }
23038
23039       if (stacki <= 0)
23040         {
23041           complaint (_("location description stack underflow"));
23042           return 0;
23043         }
23044     }
23045   return (stack[stacki]);
23046 }
23047
23048 /* memory allocation interface */
23049
23050 static struct dwarf_block *
23051 dwarf_alloc_block (struct dwarf2_cu *cu)
23052 {
23053   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23054 }
23055
23056 static struct die_info *
23057 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23058 {
23059   struct die_info *die;
23060   size_t size = sizeof (struct die_info);
23061
23062   if (num_attrs > 1)
23063     size += (num_attrs - 1) * sizeof (struct attribute);
23064
23065   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23066   memset (die, 0, sizeof (struct die_info));
23067   return (die);
23068 }
23069
23070 \f
23071 /* Macro support.  */
23072
23073 static struct macro_source_file *
23074 macro_start_file (struct dwarf2_cu *cu,
23075                   int file, int line,
23076                   struct macro_source_file *current_file,
23077                   struct line_header *lh)
23078 {
23079   /* File name relative to the compilation directory of this source file.  */
23080   gdb::unique_xmalloc_ptr<char> file_name = lh->file_file_name (file);
23081
23082   if (! current_file)
23083     {
23084       /* Note: We don't create a macro table for this compilation unit
23085          at all until we actually get a filename.  */
23086       struct macro_table *macro_table = cu->get_builder ()->get_macro_table ();
23087
23088       /* If we have no current file, then this must be the start_file
23089          directive for the compilation unit's main source file.  */
23090       current_file = macro_set_main (macro_table, file_name.get ());
23091       macro_define_special (macro_table);
23092     }
23093   else
23094     current_file = macro_include (current_file, line, file_name.get ());
23095
23096   return current_file;
23097 }
23098
23099 static const char *
23100 consume_improper_spaces (const char *p, const char *body)
23101 {
23102   if (*p == ' ')
23103     {
23104       complaint (_("macro definition contains spaces "
23105                    "in formal argument list:\n`%s'"),
23106                  body);
23107
23108       while (*p == ' ')
23109         p++;
23110     }
23111
23112   return p;
23113 }
23114
23115
23116 static void
23117 parse_macro_definition (struct macro_source_file *file, int line,
23118                         const char *body)
23119 {
23120   const char *p;
23121
23122   /* The body string takes one of two forms.  For object-like macro
23123      definitions, it should be:
23124
23125         <macro name> " " <definition>
23126
23127      For function-like macro definitions, it should be:
23128
23129         <macro name> "() " <definition>
23130      or
23131         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23132
23133      Spaces may appear only where explicitly indicated, and in the
23134      <definition>.
23135
23136      The Dwarf 2 spec says that an object-like macro's name is always
23137      followed by a space, but versions of GCC around March 2002 omit
23138      the space when the macro's definition is the empty string.
23139
23140      The Dwarf 2 spec says that there should be no spaces between the
23141      formal arguments in a function-like macro's formal argument list,
23142      but versions of GCC around March 2002 include spaces after the
23143      commas.  */
23144
23145
23146   /* Find the extent of the macro name.  The macro name is terminated
23147      by either a space or null character (for an object-like macro) or
23148      an opening paren (for a function-like macro).  */
23149   for (p = body; *p; p++)
23150     if (*p == ' ' || *p == '(')
23151       break;
23152
23153   if (*p == ' ' || *p == '\0')
23154     {
23155       /* It's an object-like macro.  */
23156       int name_len = p - body;
23157       std::string name (body, name_len);
23158       const char *replacement;
23159
23160       if (*p == ' ')
23161         replacement = body + name_len + 1;
23162       else
23163         {
23164           dwarf2_macro_malformed_definition_complaint (body);
23165           replacement = body + name_len;
23166         }
23167
23168       macro_define_object (file, line, name.c_str (), replacement);
23169     }
23170   else if (*p == '(')
23171     {
23172       /* It's a function-like macro.  */
23173       std::string name (body, p - body);
23174       int argc = 0;
23175       int argv_size = 1;
23176       char **argv = XNEWVEC (char *, argv_size);
23177
23178       p++;
23179
23180       p = consume_improper_spaces (p, body);
23181
23182       /* Parse the formal argument list.  */
23183       while (*p && *p != ')')
23184         {
23185           /* Find the extent of the current argument name.  */
23186           const char *arg_start = p;
23187
23188           while (*p && *p != ',' && *p != ')' && *p != ' ')
23189             p++;
23190
23191           if (! *p || p == arg_start)
23192             dwarf2_macro_malformed_definition_complaint (body);
23193           else
23194             {
23195               /* Make sure argv has room for the new argument.  */
23196               if (argc >= argv_size)
23197                 {
23198                   argv_size *= 2;
23199                   argv = XRESIZEVEC (char *, argv, argv_size);
23200                 }
23201
23202               argv[argc++] = savestring (arg_start, p - arg_start);
23203             }
23204
23205           p = consume_improper_spaces (p, body);
23206
23207           /* Consume the comma, if present.  */
23208           if (*p == ',')
23209             {
23210               p++;
23211
23212               p = consume_improper_spaces (p, body);
23213             }
23214         }
23215
23216       if (*p == ')')
23217         {
23218           p++;
23219
23220           if (*p == ' ')
23221             /* Perfectly formed definition, no complaints.  */
23222             macro_define_function (file, line, name.c_str (),
23223                                    argc, (const char **) argv,
23224                                    p + 1);
23225           else if (*p == '\0')
23226             {
23227               /* Complain, but do define it.  */
23228               dwarf2_macro_malformed_definition_complaint (body);
23229               macro_define_function (file, line, name.c_str (),
23230                                      argc, (const char **) argv,
23231                                      p);
23232             }
23233           else
23234             /* Just complain.  */
23235             dwarf2_macro_malformed_definition_complaint (body);
23236         }
23237       else
23238         /* Just complain.  */
23239         dwarf2_macro_malformed_definition_complaint (body);
23240
23241       {
23242         int i;
23243
23244         for (i = 0; i < argc; i++)
23245           xfree (argv[i]);
23246       }
23247       xfree (argv);
23248     }
23249   else
23250     dwarf2_macro_malformed_definition_complaint (body);
23251 }
23252
23253 /* Skip some bytes from BYTES according to the form given in FORM.
23254    Returns the new pointer.  */
23255
23256 static const gdb_byte *
23257 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23258                  enum dwarf_form form,
23259                  unsigned int offset_size,
23260                  struct dwarf2_section_info *section)
23261 {
23262   unsigned int bytes_read;
23263
23264   switch (form)
23265     {
23266     case DW_FORM_data1:
23267     case DW_FORM_flag:
23268       ++bytes;
23269       break;
23270
23271     case DW_FORM_data2:
23272       bytes += 2;
23273       break;
23274
23275     case DW_FORM_data4:
23276       bytes += 4;
23277       break;
23278
23279     case DW_FORM_data8:
23280       bytes += 8;
23281       break;
23282
23283     case DW_FORM_data16:
23284       bytes += 16;
23285       break;
23286
23287     case DW_FORM_string:
23288       read_direct_string (abfd, bytes, &bytes_read);
23289       bytes += bytes_read;
23290       break;
23291
23292     case DW_FORM_sec_offset:
23293     case DW_FORM_strp:
23294     case DW_FORM_GNU_strp_alt:
23295       bytes += offset_size;
23296       break;
23297
23298     case DW_FORM_block:
23299       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23300       bytes += bytes_read;
23301       break;
23302
23303     case DW_FORM_block1:
23304       bytes += 1 + read_1_byte (abfd, bytes);
23305       break;
23306     case DW_FORM_block2:
23307       bytes += 2 + read_2_bytes (abfd, bytes);
23308       break;
23309     case DW_FORM_block4:
23310       bytes += 4 + read_4_bytes (abfd, bytes);
23311       break;
23312
23313     case DW_FORM_addrx:
23314     case DW_FORM_sdata:
23315     case DW_FORM_strx:
23316     case DW_FORM_udata:
23317     case DW_FORM_GNU_addr_index:
23318     case DW_FORM_GNU_str_index:
23319       bytes = gdb_skip_leb128 (bytes, buffer_end);
23320       if (bytes == NULL)
23321         {
23322           dwarf2_section_buffer_overflow_complaint (section);
23323           return NULL;
23324         }
23325       break;
23326
23327     case DW_FORM_implicit_const:
23328       break;
23329
23330     default:
23331       {
23332         complaint (_("invalid form 0x%x in `%s'"),
23333                    form, section->get_name ());
23334         return NULL;
23335       }
23336     }
23337
23338   return bytes;
23339 }
23340
23341 /* A helper for dwarf_decode_macros that handles skipping an unknown
23342    opcode.  Returns an updated pointer to the macro data buffer; or,
23343    on error, issues a complaint and returns NULL.  */
23344
23345 static const gdb_byte *
23346 skip_unknown_opcode (unsigned int opcode,
23347                      const gdb_byte **opcode_definitions,
23348                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
23349                      bfd *abfd,
23350                      unsigned int offset_size,
23351                      struct dwarf2_section_info *section)
23352 {
23353   unsigned int bytes_read, i;
23354   unsigned long arg;
23355   const gdb_byte *defn;
23356
23357   if (opcode_definitions[opcode] == NULL)
23358     {
23359       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
23360                  opcode);
23361       return NULL;
23362     }
23363
23364   defn = opcode_definitions[opcode];
23365   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
23366   defn += bytes_read;
23367
23368   for (i = 0; i < arg; ++i)
23369     {
23370       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
23371                                  (enum dwarf_form) defn[i], offset_size,
23372                                  section);
23373       if (mac_ptr == NULL)
23374         {
23375           /* skip_form_bytes already issued the complaint.  */
23376           return NULL;
23377         }
23378     }
23379
23380   return mac_ptr;
23381 }
23382
23383 /* A helper function which parses the header of a macro section.
23384    If the macro section is the extended (for now called "GNU") type,
23385    then this updates *OFFSET_SIZE.  Returns a pointer to just after
23386    the header, or issues a complaint and returns NULL on error.  */
23387
23388 static const gdb_byte *
23389 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
23390                           bfd *abfd,
23391                           const gdb_byte *mac_ptr,
23392                           unsigned int *offset_size,
23393                           int section_is_gnu)
23394 {
23395   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
23396
23397   if (section_is_gnu)
23398     {
23399       unsigned int version, flags;
23400
23401       version = read_2_bytes (abfd, mac_ptr);
23402       if (version != 4 && version != 5)
23403         {
23404           complaint (_("unrecognized version `%d' in .debug_macro section"),
23405                      version);
23406           return NULL;
23407         }
23408       mac_ptr += 2;
23409
23410       flags = read_1_byte (abfd, mac_ptr);
23411       ++mac_ptr;
23412       *offset_size = (flags & 1) ? 8 : 4;
23413
23414       if ((flags & 2) != 0)
23415         /* We don't need the line table offset.  */
23416         mac_ptr += *offset_size;
23417
23418       /* Vendor opcode descriptions.  */
23419       if ((flags & 4) != 0)
23420         {
23421           unsigned int i, count;
23422
23423           count = read_1_byte (abfd, mac_ptr);
23424           ++mac_ptr;
23425           for (i = 0; i < count; ++i)
23426             {
23427               unsigned int opcode, bytes_read;
23428               unsigned long arg;
23429
23430               opcode = read_1_byte (abfd, mac_ptr);
23431               ++mac_ptr;
23432               opcode_definitions[opcode] = mac_ptr;
23433               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23434               mac_ptr += bytes_read;
23435               mac_ptr += arg;
23436             }
23437         }
23438     }
23439
23440   return mac_ptr;
23441 }
23442
23443 /* A helper for dwarf_decode_macros that handles the GNU extensions,
23444    including DW_MACRO_import.  */
23445
23446 static void
23447 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
23448                           bfd *abfd,
23449                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
23450                           struct macro_source_file *current_file,
23451                           struct line_header *lh,
23452                           struct dwarf2_section_info *section,
23453                           int section_is_gnu, int section_is_dwz,
23454                           unsigned int offset_size,
23455                           htab_t include_hash)
23456 {
23457   struct dwarf2_per_objfile *dwarf2_per_objfile
23458     = cu->per_cu->dwarf2_per_objfile;
23459   struct objfile *objfile = dwarf2_per_objfile->objfile;
23460   enum dwarf_macro_record_type macinfo_type;
23461   int at_commandline;
23462   const gdb_byte *opcode_definitions[256];
23463
23464   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
23465                                       &offset_size, section_is_gnu);
23466   if (mac_ptr == NULL)
23467     {
23468       /* We already issued a complaint.  */
23469       return;
23470     }
23471
23472   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
23473      GDB is still reading the definitions from command line.  First
23474      DW_MACINFO_start_file will need to be ignored as it was already executed
23475      to create CURRENT_FILE for the main source holding also the command line
23476      definitions.  On first met DW_MACINFO_start_file this flag is reset to
23477      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
23478
23479   at_commandline = 1;
23480
23481   do
23482     {
23483       /* Do we at least have room for a macinfo type byte?  */
23484       if (mac_ptr >= mac_end)
23485         {
23486           dwarf2_section_buffer_overflow_complaint (section);
23487           break;
23488         }
23489
23490       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
23491       mac_ptr++;
23492
23493       /* Note that we rely on the fact that the corresponding GNU and
23494          DWARF constants are the same.  */
23495       DIAGNOSTIC_PUSH
23496       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
23497       switch (macinfo_type)
23498         {
23499           /* A zero macinfo type indicates the end of the macro
23500              information.  */
23501         case 0:
23502           break;
23503
23504         case DW_MACRO_define:
23505         case DW_MACRO_undef:
23506         case DW_MACRO_define_strp:
23507         case DW_MACRO_undef_strp:
23508         case DW_MACRO_define_sup:
23509         case DW_MACRO_undef_sup:
23510           {
23511             unsigned int bytes_read;
23512             int line;
23513             const char *body;
23514             int is_define;
23515
23516             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23517             mac_ptr += bytes_read;
23518
23519             if (macinfo_type == DW_MACRO_define
23520                 || macinfo_type == DW_MACRO_undef)
23521               {
23522                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
23523                 mac_ptr += bytes_read;
23524               }
23525             else
23526               {
23527                 LONGEST str_offset;
23528
23529                 str_offset = read_offset (abfd, mac_ptr, offset_size);
23530                 mac_ptr += offset_size;
23531
23532                 if (macinfo_type == DW_MACRO_define_sup
23533                     || macinfo_type == DW_MACRO_undef_sup
23534                     || section_is_dwz)
23535                   {
23536                     struct dwz_file *dwz
23537                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
23538
23539                     body = read_indirect_string_from_dwz (objfile,
23540                                                           dwz, str_offset);
23541                   }
23542                 else
23543                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
23544                                                          abfd, str_offset);
23545               }
23546
23547             is_define = (macinfo_type == DW_MACRO_define
23548                          || macinfo_type == DW_MACRO_define_strp
23549                          || macinfo_type == DW_MACRO_define_sup);
23550             if (! current_file)
23551               {
23552                 /* DWARF violation as no main source is present.  */
23553                 complaint (_("debug info with no main source gives macro %s "
23554                              "on line %d: %s"),
23555                            is_define ? _("definition") : _("undefinition"),
23556                            line, body);
23557                 break;
23558               }
23559             if ((line == 0 && !at_commandline)
23560                 || (line != 0 && at_commandline))
23561               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
23562                          at_commandline ? _("command-line") : _("in-file"),
23563                          is_define ? _("definition") : _("undefinition"),
23564                          line == 0 ? _("zero") : _("non-zero"), line, body);
23565
23566             if (body == NULL)
23567               {
23568                 /* Fedora's rpm-build's "debugedit" binary
23569                    corrupted .debug_macro sections.
23570
23571                    For more info, see
23572                    https://bugzilla.redhat.com/show_bug.cgi?id=1708786 */
23573                 complaint (_("debug info gives %s invalid macro %s "
23574                              "without body (corrupted?) at line %d "
23575                              "on file %s"),
23576                            at_commandline ? _("command-line") : _("in-file"),
23577                            is_define ? _("definition") : _("undefinition"),
23578                            line, current_file->filename);
23579               }
23580             else if (is_define)
23581               parse_macro_definition (current_file, line, body);
23582             else
23583               {
23584                 gdb_assert (macinfo_type == DW_MACRO_undef
23585                             || macinfo_type == DW_MACRO_undef_strp
23586                             || macinfo_type == DW_MACRO_undef_sup);
23587                 macro_undef (current_file, line, body);
23588               }
23589           }
23590           break;
23591
23592         case DW_MACRO_start_file:
23593           {
23594             unsigned int bytes_read;
23595             int line, file;
23596
23597             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23598             mac_ptr += bytes_read;
23599             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23600             mac_ptr += bytes_read;
23601
23602             if ((line == 0 && !at_commandline)
23603                 || (line != 0 && at_commandline))
23604               complaint (_("debug info gives source %d included "
23605                            "from %s at %s line %d"),
23606                          file, at_commandline ? _("command-line") : _("file"),
23607                          line == 0 ? _("zero") : _("non-zero"), line);
23608
23609             if (at_commandline)
23610               {
23611                 /* This DW_MACRO_start_file was executed in the
23612                    pass one.  */
23613                 at_commandline = 0;
23614               }
23615             else
23616               current_file = macro_start_file (cu, file, line, current_file,
23617                                                lh);
23618           }
23619           break;
23620
23621         case DW_MACRO_end_file:
23622           if (! current_file)
23623             complaint (_("macro debug info has an unmatched "
23624                          "`close_file' directive"));
23625           else
23626             {
23627               current_file = current_file->included_by;
23628               if (! current_file)
23629                 {
23630                   enum dwarf_macro_record_type next_type;
23631
23632                   /* GCC circa March 2002 doesn't produce the zero
23633                      type byte marking the end of the compilation
23634                      unit.  Complain if it's not there, but exit no
23635                      matter what.  */
23636
23637                   /* Do we at least have room for a macinfo type byte?  */
23638                   if (mac_ptr >= mac_end)
23639                     {
23640                       dwarf2_section_buffer_overflow_complaint (section);
23641                       return;
23642                     }
23643
23644                   /* We don't increment mac_ptr here, so this is just
23645                      a look-ahead.  */
23646                   next_type
23647                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
23648                                                                   mac_ptr);
23649                   if (next_type != 0)
23650                     complaint (_("no terminating 0-type entry for "
23651                                  "macros in `.debug_macinfo' section"));
23652
23653                   return;
23654                 }
23655             }
23656           break;
23657
23658         case DW_MACRO_import:
23659         case DW_MACRO_import_sup:
23660           {
23661             LONGEST offset;
23662             void **slot;
23663             bfd *include_bfd = abfd;
23664             struct dwarf2_section_info *include_section = section;
23665             const gdb_byte *include_mac_end = mac_end;
23666             int is_dwz = section_is_dwz;
23667             const gdb_byte *new_mac_ptr;
23668
23669             offset = read_offset (abfd, mac_ptr, offset_size);
23670             mac_ptr += offset_size;
23671
23672             if (macinfo_type == DW_MACRO_import_sup)
23673               {
23674                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
23675
23676                 dwz->macro.read (objfile);
23677
23678                 include_section = &dwz->macro;
23679                 include_bfd = include_section->get_bfd_owner ();
23680                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
23681                 is_dwz = 1;
23682               }
23683
23684             new_mac_ptr = include_section->buffer + offset;
23685             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
23686
23687             if (*slot != NULL)
23688               {
23689                 /* This has actually happened; see
23690                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
23691                 complaint (_("recursive DW_MACRO_import in "
23692                              ".debug_macro section"));
23693               }
23694             else
23695               {
23696                 *slot = (void *) new_mac_ptr;
23697
23698                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
23699                                           include_mac_end, current_file, lh,
23700                                           section, section_is_gnu, is_dwz,
23701                                           offset_size, include_hash);
23702
23703                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
23704               }
23705           }
23706           break;
23707
23708         case DW_MACINFO_vendor_ext:
23709           if (!section_is_gnu)
23710             {
23711               unsigned int bytes_read;
23712
23713               /* This reads the constant, but since we don't recognize
23714                  any vendor extensions, we ignore it.  */
23715               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23716               mac_ptr += bytes_read;
23717               read_direct_string (abfd, mac_ptr, &bytes_read);
23718               mac_ptr += bytes_read;
23719
23720               /* We don't recognize any vendor extensions.  */
23721               break;
23722             }
23723           /* FALLTHROUGH */
23724
23725         default:
23726           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23727                                          mac_ptr, mac_end, abfd, offset_size,
23728                                          section);
23729           if (mac_ptr == NULL)
23730             return;
23731           break;
23732         }
23733       DIAGNOSTIC_POP
23734     } while (macinfo_type != 0);
23735 }
23736
23737 static void
23738 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
23739                      int section_is_gnu)
23740 {
23741   struct dwarf2_per_objfile *dwarf2_per_objfile
23742     = cu->per_cu->dwarf2_per_objfile;
23743   struct objfile *objfile = dwarf2_per_objfile->objfile;
23744   struct line_header *lh = cu->line_header;
23745   bfd *abfd;
23746   const gdb_byte *mac_ptr, *mac_end;
23747   struct macro_source_file *current_file = 0;
23748   enum dwarf_macro_record_type macinfo_type;
23749   unsigned int offset_size = cu->header.offset_size;
23750   const gdb_byte *opcode_definitions[256];
23751   void **slot;
23752   struct dwarf2_section_info *section;
23753   const char *section_name;
23754
23755   if (cu->dwo_unit != NULL)
23756     {
23757       if (section_is_gnu)
23758         {
23759           section = &cu->dwo_unit->dwo_file->sections.macro;
23760           section_name = ".debug_macro.dwo";
23761         }
23762       else
23763         {
23764           section = &cu->dwo_unit->dwo_file->sections.macinfo;
23765           section_name = ".debug_macinfo.dwo";
23766         }
23767     }
23768   else
23769     {
23770       if (section_is_gnu)
23771         {
23772           section = &dwarf2_per_objfile->macro;
23773           section_name = ".debug_macro";
23774         }
23775       else
23776         {
23777           section = &dwarf2_per_objfile->macinfo;
23778           section_name = ".debug_macinfo";
23779         }
23780     }
23781
23782   section->read (objfile);
23783   if (section->buffer == NULL)
23784     {
23785       complaint (_("missing %s section"), section_name);
23786       return;
23787     }
23788   abfd = section->get_bfd_owner ();
23789
23790   /* First pass: Find the name of the base filename.
23791      This filename is needed in order to process all macros whose definition
23792      (or undefinition) comes from the command line.  These macros are defined
23793      before the first DW_MACINFO_start_file entry, and yet still need to be
23794      associated to the base file.
23795
23796      To determine the base file name, we scan the macro definitions until we
23797      reach the first DW_MACINFO_start_file entry.  We then initialize
23798      CURRENT_FILE accordingly so that any macro definition found before the
23799      first DW_MACINFO_start_file can still be associated to the base file.  */
23800
23801   mac_ptr = section->buffer + offset;
23802   mac_end = section->buffer + section->size;
23803
23804   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
23805                                       &offset_size, section_is_gnu);
23806   if (mac_ptr == NULL)
23807     {
23808       /* We already issued a complaint.  */
23809       return;
23810     }
23811
23812   do
23813     {
23814       /* Do we at least have room for a macinfo type byte?  */
23815       if (mac_ptr >= mac_end)
23816         {
23817           /* Complaint is printed during the second pass as GDB will probably
23818              stop the first pass earlier upon finding
23819              DW_MACINFO_start_file.  */
23820           break;
23821         }
23822
23823       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
23824       mac_ptr++;
23825
23826       /* Note that we rely on the fact that the corresponding GNU and
23827          DWARF constants are the same.  */
23828       DIAGNOSTIC_PUSH
23829       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
23830       switch (macinfo_type)
23831         {
23832           /* A zero macinfo type indicates the end of the macro
23833              information.  */
23834         case 0:
23835           break;
23836
23837         case DW_MACRO_define:
23838         case DW_MACRO_undef:
23839           /* Only skip the data by MAC_PTR.  */
23840           {
23841             unsigned int bytes_read;
23842
23843             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23844             mac_ptr += bytes_read;
23845             read_direct_string (abfd, mac_ptr, &bytes_read);
23846             mac_ptr += bytes_read;
23847           }
23848           break;
23849
23850         case DW_MACRO_start_file:
23851           {
23852             unsigned int bytes_read;
23853             int line, file;
23854
23855             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23856             mac_ptr += bytes_read;
23857             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23858             mac_ptr += bytes_read;
23859
23860             current_file = macro_start_file (cu, file, line, current_file, lh);
23861           }
23862           break;
23863
23864         case DW_MACRO_end_file:
23865           /* No data to skip by MAC_PTR.  */
23866           break;
23867
23868         case DW_MACRO_define_strp:
23869         case DW_MACRO_undef_strp:
23870         case DW_MACRO_define_sup:
23871         case DW_MACRO_undef_sup:
23872           {
23873             unsigned int bytes_read;
23874
23875             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23876             mac_ptr += bytes_read;
23877             mac_ptr += offset_size;
23878           }
23879           break;
23880
23881         case DW_MACRO_import:
23882         case DW_MACRO_import_sup:
23883           /* Note that, according to the spec, a transparent include
23884              chain cannot call DW_MACRO_start_file.  So, we can just
23885              skip this opcode.  */
23886           mac_ptr += offset_size;
23887           break;
23888
23889         case DW_MACINFO_vendor_ext:
23890           /* Only skip the data by MAC_PTR.  */
23891           if (!section_is_gnu)
23892             {
23893               unsigned int bytes_read;
23894
23895               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23896               mac_ptr += bytes_read;
23897               read_direct_string (abfd, mac_ptr, &bytes_read);
23898               mac_ptr += bytes_read;
23899             }
23900           /* FALLTHROUGH */
23901
23902         default:
23903           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23904                                          mac_ptr, mac_end, abfd, offset_size,
23905                                          section);
23906           if (mac_ptr == NULL)
23907             return;
23908           break;
23909         }
23910       DIAGNOSTIC_POP
23911     } while (macinfo_type != 0 && current_file == NULL);
23912
23913   /* Second pass: Process all entries.
23914
23915      Use the AT_COMMAND_LINE flag to determine whether we are still processing
23916      command-line macro definitions/undefinitions.  This flag is unset when we
23917      reach the first DW_MACINFO_start_file entry.  */
23918
23919   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
23920                                            htab_eq_pointer,
23921                                            NULL, xcalloc, xfree));
23922   mac_ptr = section->buffer + offset;
23923   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
23924   *slot = (void *) mac_ptr;
23925   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
23926                             current_file, lh, section,
23927                             section_is_gnu, 0, offset_size,
23928                             include_hash.get ());
23929 }
23930
23931 /* Return the .debug_loc section to use for CU.
23932    For DWO files use .debug_loc.dwo.  */
23933
23934 static struct dwarf2_section_info *
23935 cu_debug_loc_section (struct dwarf2_cu *cu)
23936 {
23937   struct dwarf2_per_objfile *dwarf2_per_objfile
23938     = cu->per_cu->dwarf2_per_objfile;
23939
23940   if (cu->dwo_unit)
23941     {
23942       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
23943
23944       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
23945     }
23946   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
23947                                   : &dwarf2_per_objfile->loc);
23948 }
23949
23950 /* A helper function that fills in a dwarf2_loclist_baton.  */
23951
23952 static void
23953 fill_in_loclist_baton (struct dwarf2_cu *cu,
23954                        struct dwarf2_loclist_baton *baton,
23955                        const struct attribute *attr)
23956 {
23957   struct dwarf2_per_objfile *dwarf2_per_objfile
23958     = cu->per_cu->dwarf2_per_objfile;
23959   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23960
23961   section->read (dwarf2_per_objfile->objfile);
23962
23963   baton->per_cu = cu->per_cu;
23964   gdb_assert (baton->per_cu);
23965   /* We don't know how long the location list is, but make sure we
23966      don't run off the edge of the section.  */
23967   baton->size = section->size - DW_UNSND (attr);
23968   baton->data = section->buffer + DW_UNSND (attr);
23969   baton->base_address = cu->base_address;
23970   baton->from_dwo = cu->dwo_unit != NULL;
23971 }
23972
23973 static void
23974 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
23975                              struct dwarf2_cu *cu, int is_block)
23976 {
23977   struct dwarf2_per_objfile *dwarf2_per_objfile
23978     = cu->per_cu->dwarf2_per_objfile;
23979   struct objfile *objfile = dwarf2_per_objfile->objfile;
23980   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23981
23982   if (attr->form_is_section_offset ()
23983       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
23984          the section.  If so, fall through to the complaint in the
23985          other branch.  */
23986       && DW_UNSND (attr) < section->get_size (objfile))
23987     {
23988       struct dwarf2_loclist_baton *baton;
23989
23990       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
23991
23992       fill_in_loclist_baton (cu, baton, attr);
23993
23994       if (cu->base_known == 0)
23995         complaint (_("Location list used without "
23996                      "specifying the CU base address."));
23997
23998       SYMBOL_ACLASS_INDEX (sym) = (is_block
23999                                    ? dwarf2_loclist_block_index
24000                                    : dwarf2_loclist_index);
24001       SYMBOL_LOCATION_BATON (sym) = baton;
24002     }
24003   else
24004     {
24005       struct dwarf2_locexpr_baton *baton;
24006
24007       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24008       baton->per_cu = cu->per_cu;
24009       gdb_assert (baton->per_cu);
24010
24011       if (attr->form_is_block ())
24012         {
24013           /* Note that we're just copying the block's data pointer
24014              here, not the actual data.  We're still pointing into the
24015              info_buffer for SYM's objfile; right now we never release
24016              that buffer, but when we do clean up properly this may
24017              need to change.  */
24018           baton->size = DW_BLOCK (attr)->size;
24019           baton->data = DW_BLOCK (attr)->data;
24020         }
24021       else
24022         {
24023           dwarf2_invalid_attrib_class_complaint ("location description",
24024                                                  sym->natural_name ());
24025           baton->size = 0;
24026         }
24027
24028       SYMBOL_ACLASS_INDEX (sym) = (is_block
24029                                    ? dwarf2_locexpr_block_index
24030                                    : dwarf2_locexpr_index);
24031       SYMBOL_LOCATION_BATON (sym) = baton;
24032     }
24033 }
24034
24035 /* See read.h.  */
24036
24037 struct objfile *
24038 dwarf2_per_cu_data::objfile () const
24039 {
24040   struct objfile *objfile = dwarf2_per_objfile->objfile;
24041
24042   /* Return the master objfile, so that we can report and look up the
24043      correct file containing this variable.  */
24044   if (objfile->separate_debug_objfile_backlink)
24045     objfile = objfile->separate_debug_objfile_backlink;
24046
24047   return objfile;
24048 }
24049
24050 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24051    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24052    CU_HEADERP first.  */
24053
24054 static const struct comp_unit_head *
24055 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24056                        const struct dwarf2_per_cu_data *per_cu)
24057 {
24058   const gdb_byte *info_ptr;
24059
24060   if (per_cu->cu)
24061     return &per_cu->cu->header;
24062
24063   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24064
24065   memset (cu_headerp, 0, sizeof (*cu_headerp));
24066   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24067                        rcuh_kind::COMPILE);
24068
24069   return cu_headerp;
24070 }
24071
24072 /* See read.h.  */
24073
24074 int
24075 dwarf2_per_cu_data::addr_size () const
24076 {
24077   struct comp_unit_head cu_header_local;
24078   const struct comp_unit_head *cu_headerp;
24079
24080   cu_headerp = per_cu_header_read_in (&cu_header_local, this);
24081
24082   return cu_headerp->addr_size;
24083 }
24084
24085 /* See read.h.  */
24086
24087 int
24088 dwarf2_per_cu_data::offset_size () const
24089 {
24090   struct comp_unit_head cu_header_local;
24091   const struct comp_unit_head *cu_headerp;
24092
24093   cu_headerp = per_cu_header_read_in (&cu_header_local, this);
24094
24095   return cu_headerp->offset_size;
24096 }
24097
24098 /* See read.h.  */
24099
24100 int
24101 dwarf2_per_cu_data::ref_addr_size () const
24102 {
24103   struct comp_unit_head cu_header_local;
24104   const struct comp_unit_head *cu_headerp;
24105
24106   cu_headerp = per_cu_header_read_in (&cu_header_local, this);
24107
24108   if (cu_headerp->version == 2)
24109     return cu_headerp->addr_size;
24110   else
24111     return cu_headerp->offset_size;
24112 }
24113
24114 /* See read.h.  */
24115
24116 CORE_ADDR
24117 dwarf2_per_cu_data::text_offset () const
24118 {
24119   struct objfile *objfile = dwarf2_per_objfile->objfile;
24120
24121   return objfile->text_section_offset ();
24122 }
24123
24124 /* See read.h.  */
24125
24126 struct type *
24127 dwarf2_per_cu_data::addr_type () const
24128 {
24129   struct objfile *objfile = dwarf2_per_objfile->objfile;
24130   struct type *void_type = objfile_type (objfile)->builtin_void;
24131   struct type *addr_type = lookup_pointer_type (void_type);
24132   int addr_size = this->addr_size ();
24133
24134   if (TYPE_LENGTH (addr_type) == addr_size)
24135     return addr_type;
24136
24137   addr_type = addr_sized_int_type (TYPE_UNSIGNED (addr_type));
24138   return addr_type;
24139 }
24140
24141 /* A helper function for dwarf2_find_containing_comp_unit that returns
24142    the index of the result, and that searches a vector.  It will
24143    return a result even if the offset in question does not actually
24144    occur in any CU.  This is separate so that it can be unit
24145    tested.  */
24146
24147 static int
24148 dwarf2_find_containing_comp_unit
24149   (sect_offset sect_off,
24150    unsigned int offset_in_dwz,
24151    const std::vector<dwarf2_per_cu_data *> &all_comp_units)
24152 {
24153   int low, high;
24154
24155   low = 0;
24156   high = all_comp_units.size () - 1;
24157   while (high > low)
24158     {
24159       struct dwarf2_per_cu_data *mid_cu;
24160       int mid = low + (high - low) / 2;
24161
24162       mid_cu = all_comp_units[mid];
24163       if (mid_cu->is_dwz > offset_in_dwz
24164           || (mid_cu->is_dwz == offset_in_dwz
24165               && mid_cu->sect_off + mid_cu->length > sect_off))
24166         high = mid;
24167       else
24168         low = mid + 1;
24169     }
24170   gdb_assert (low == high);
24171   return low;
24172 }
24173
24174 /* Locate the .debug_info compilation unit from CU's objfile which contains
24175    the DIE at OFFSET.  Raises an error on failure.  */
24176
24177 static struct dwarf2_per_cu_data *
24178 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24179                                   unsigned int offset_in_dwz,
24180                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24181 {
24182   int low
24183     = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
24184                                         dwarf2_per_objfile->all_comp_units);
24185   struct dwarf2_per_cu_data *this_cu
24186     = dwarf2_per_objfile->all_comp_units[low];
24187
24188   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
24189     {
24190       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24191         error (_("Dwarf Error: could not find partial DIE containing "
24192                "offset %s [in module %s]"),
24193                sect_offset_str (sect_off),
24194                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24195
24196       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24197                   <= sect_off);
24198       return dwarf2_per_objfile->all_comp_units[low-1];
24199     }
24200   else
24201     {
24202       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24203           && sect_off >= this_cu->sect_off + this_cu->length)
24204         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24205       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24206       return this_cu;
24207     }
24208 }
24209
24210 #if GDB_SELF_TEST
24211
24212 namespace selftests {
24213 namespace find_containing_comp_unit {
24214
24215 static void
24216 run_test ()
24217 {
24218   struct dwarf2_per_cu_data one {};
24219   struct dwarf2_per_cu_data two {};
24220   struct dwarf2_per_cu_data three {};
24221   struct dwarf2_per_cu_data four {};
24222
24223   one.length = 5;
24224   two.sect_off = sect_offset (one.length);
24225   two.length = 7;
24226
24227   three.length = 5;
24228   three.is_dwz = 1;
24229   four.sect_off = sect_offset (three.length);
24230   four.length = 7;
24231   four.is_dwz = 1;
24232
24233   std::vector<dwarf2_per_cu_data *> units;
24234   units.push_back (&one);
24235   units.push_back (&two);
24236   units.push_back (&three);
24237   units.push_back (&four);
24238
24239   int result;
24240
24241   result = dwarf2_find_containing_comp_unit (sect_offset (0), 0, units);
24242   SELF_CHECK (units[result] == &one);
24243   result = dwarf2_find_containing_comp_unit (sect_offset (3), 0, units);
24244   SELF_CHECK (units[result] == &one);
24245   result = dwarf2_find_containing_comp_unit (sect_offset (5), 0, units);
24246   SELF_CHECK (units[result] == &two);
24247
24248   result = dwarf2_find_containing_comp_unit (sect_offset (0), 1, units);
24249   SELF_CHECK (units[result] == &three);
24250   result = dwarf2_find_containing_comp_unit (sect_offset (3), 1, units);
24251   SELF_CHECK (units[result] == &three);
24252   result = dwarf2_find_containing_comp_unit (sect_offset (5), 1, units);
24253   SELF_CHECK (units[result] == &four);
24254 }
24255
24256 }
24257 }
24258
24259 #endif /* GDB_SELF_TEST */
24260
24261 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24262
24263 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24264   : per_cu (per_cu_),
24265     mark (false),
24266     has_loclist (false),
24267     checked_producer (false),
24268     producer_is_gxx_lt_4_6 (false),
24269     producer_is_gcc_lt_4_3 (false),
24270     producer_is_icc (false),
24271     producer_is_icc_lt_14 (false),
24272     producer_is_codewarrior (false),
24273     processing_has_namespace_info (false)
24274 {
24275   per_cu->cu = this;
24276 }
24277
24278 /* Destroy a dwarf2_cu.  */
24279
24280 dwarf2_cu::~dwarf2_cu ()
24281 {
24282   per_cu->cu = NULL;
24283 }
24284
24285 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24286
24287 static void
24288 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24289                        enum language pretend_language)
24290 {
24291   struct attribute *attr;
24292
24293   /* Set the language we're debugging.  */
24294   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24295   if (attr != nullptr)
24296     set_cu_language (DW_UNSND (attr), cu);
24297   else
24298     {
24299       cu->language = pretend_language;
24300       cu->language_defn = language_def (cu->language);
24301     }
24302
24303   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24304 }
24305
24306 /* Increase the age counter on each cached compilation unit, and free
24307    any that are too old.  */
24308
24309 static void
24310 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
24311 {
24312   struct dwarf2_per_cu_data *per_cu, **last_chain;
24313
24314   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24315   per_cu = dwarf2_per_objfile->read_in_chain;
24316   while (per_cu != NULL)
24317     {
24318       per_cu->cu->last_used ++;
24319       if (per_cu->cu->last_used <= dwarf_max_cache_age)
24320         dwarf2_mark (per_cu->cu);
24321       per_cu = per_cu->cu->read_in_chain;
24322     }
24323
24324   per_cu = dwarf2_per_objfile->read_in_chain;
24325   last_chain = &dwarf2_per_objfile->read_in_chain;
24326   while (per_cu != NULL)
24327     {
24328       struct dwarf2_per_cu_data *next_cu;
24329
24330       next_cu = per_cu->cu->read_in_chain;
24331
24332       if (!per_cu->cu->mark)
24333         {
24334           delete per_cu->cu;
24335           *last_chain = next_cu;
24336         }
24337       else
24338         last_chain = &per_cu->cu->read_in_chain;
24339
24340       per_cu = next_cu;
24341     }
24342 }
24343
24344 /* Remove a single compilation unit from the cache.  */
24345
24346 static void
24347 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
24348 {
24349   struct dwarf2_per_cu_data *per_cu, **last_chain;
24350   struct dwarf2_per_objfile *dwarf2_per_objfile
24351     = target_per_cu->dwarf2_per_objfile;
24352
24353   per_cu = dwarf2_per_objfile->read_in_chain;
24354   last_chain = &dwarf2_per_objfile->read_in_chain;
24355   while (per_cu != NULL)
24356     {
24357       struct dwarf2_per_cu_data *next_cu;
24358
24359       next_cu = per_cu->cu->read_in_chain;
24360
24361       if (per_cu == target_per_cu)
24362         {
24363           delete per_cu->cu;
24364           per_cu->cu = NULL;
24365           *last_chain = next_cu;
24366           break;
24367         }
24368       else
24369         last_chain = &per_cu->cu->read_in_chain;
24370
24371       per_cu = next_cu;
24372     }
24373 }
24374
24375 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
24376    We store these in a hash table separate from the DIEs, and preserve them
24377    when the DIEs are flushed out of cache.
24378
24379    The CU "per_cu" pointer is needed because offset alone is not enough to
24380    uniquely identify the type.  A file may have multiple .debug_types sections,
24381    or the type may come from a DWO file.  Furthermore, while it's more logical
24382    to use per_cu->section+offset, with Fission the section with the data is in
24383    the DWO file but we don't know that section at the point we need it.
24384    We have to use something in dwarf2_per_cu_data (or the pointer to it)
24385    because we can enter the lookup routine, get_die_type_at_offset, from
24386    outside this file, and thus won't necessarily have PER_CU->cu.
24387    Fortunately, PER_CU is stable for the life of the objfile.  */
24388
24389 struct dwarf2_per_cu_offset_and_type
24390 {
24391   const struct dwarf2_per_cu_data *per_cu;
24392   sect_offset sect_off;
24393   struct type *type;
24394 };
24395
24396 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
24397
24398 static hashval_t
24399 per_cu_offset_and_type_hash (const void *item)
24400 {
24401   const struct dwarf2_per_cu_offset_and_type *ofs
24402     = (const struct dwarf2_per_cu_offset_and_type *) item;
24403
24404   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
24405 }
24406
24407 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
24408
24409 static int
24410 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
24411 {
24412   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
24413     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
24414   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
24415     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
24416
24417   return (ofs_lhs->per_cu == ofs_rhs->per_cu
24418           && ofs_lhs->sect_off == ofs_rhs->sect_off);
24419 }
24420
24421 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
24422    table if necessary.  For convenience, return TYPE.
24423
24424    The DIEs reading must have careful ordering to:
24425     * Not cause infinite loops trying to read in DIEs as a prerequisite for
24426       reading current DIE.
24427     * Not trying to dereference contents of still incompletely read in types
24428       while reading in other DIEs.
24429     * Enable referencing still incompletely read in types just by a pointer to
24430       the type without accessing its fields.
24431
24432    Therefore caller should follow these rules:
24433      * Try to fetch any prerequisite types we may need to build this DIE type
24434        before building the type and calling set_die_type.
24435      * After building type call set_die_type for current DIE as soon as
24436        possible before fetching more types to complete the current type.
24437      * Make the type as complete as possible before fetching more types.  */
24438
24439 static struct type *
24440 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
24441 {
24442   struct dwarf2_per_objfile *dwarf2_per_objfile
24443     = cu->per_cu->dwarf2_per_objfile;
24444   struct dwarf2_per_cu_offset_and_type **slot, ofs;
24445   struct objfile *objfile = dwarf2_per_objfile->objfile;
24446   struct attribute *attr;
24447   struct dynamic_prop prop;
24448
24449   /* For Ada types, make sure that the gnat-specific data is always
24450      initialized (if not already set).  There are a few types where
24451      we should not be doing so, because the type-specific area is
24452      already used to hold some other piece of info (eg: TYPE_CODE_FLT
24453      where the type-specific area is used to store the floatformat).
24454      But this is not a problem, because the gnat-specific information
24455      is actually not needed for these types.  */
24456   if (need_gnat_info (cu)
24457       && TYPE_CODE (type) != TYPE_CODE_FUNC
24458       && TYPE_CODE (type) != TYPE_CODE_FLT
24459       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
24460       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
24461       && TYPE_CODE (type) != TYPE_CODE_METHOD
24462       && !HAVE_GNAT_AUX_INFO (type))
24463     INIT_GNAT_SPECIFIC (type);
24464
24465   /* Read DW_AT_allocated and set in type.  */
24466   attr = dwarf2_attr (die, DW_AT_allocated, cu);
24467   if (attr != NULL && attr->form_is_block ())
24468     {
24469       struct type *prop_type = cu->per_cu->addr_sized_int_type (false);
24470       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
24471         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
24472     }
24473   else if (attr != NULL)
24474     {
24475       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
24476                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
24477                  sect_offset_str (die->sect_off));
24478     }
24479
24480   /* Read DW_AT_associated and set in type.  */
24481   attr = dwarf2_attr (die, DW_AT_associated, cu);
24482   if (attr != NULL && attr->form_is_block ())
24483     {
24484       struct type *prop_type = cu->per_cu->addr_sized_int_type (false);
24485       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
24486         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
24487     }
24488   else if (attr != NULL)
24489     {
24490       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
24491                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
24492                  sect_offset_str (die->sect_off));
24493     }
24494
24495   /* Read DW_AT_data_location and set in type.  */
24496   attr = dwarf2_attr (die, DW_AT_data_location, cu);
24497   if (attr_to_dynamic_prop (attr, die, cu, &prop,
24498                             cu->per_cu->addr_type ()))
24499     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
24500
24501   if (dwarf2_per_objfile->die_type_hash == NULL)
24502     dwarf2_per_objfile->die_type_hash
24503       = htab_up (htab_create_alloc (127,
24504                                     per_cu_offset_and_type_hash,
24505                                     per_cu_offset_and_type_eq,
24506                                     NULL, xcalloc, xfree));
24507
24508   ofs.per_cu = cu->per_cu;
24509   ofs.sect_off = die->sect_off;
24510   ofs.type = type;
24511   slot = (struct dwarf2_per_cu_offset_and_type **)
24512     htab_find_slot (dwarf2_per_objfile->die_type_hash.get (), &ofs, INSERT);
24513   if (*slot)
24514     complaint (_("A problem internal to GDB: DIE %s has type already set"),
24515                sect_offset_str (die->sect_off));
24516   *slot = XOBNEW (&objfile->objfile_obstack,
24517                   struct dwarf2_per_cu_offset_and_type);
24518   **slot = ofs;
24519   return type;
24520 }
24521
24522 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
24523    or return NULL if the die does not have a saved type.  */
24524
24525 static struct type *
24526 get_die_type_at_offset (sect_offset sect_off,
24527                         struct dwarf2_per_cu_data *per_cu)
24528 {
24529   struct dwarf2_per_cu_offset_and_type *slot, ofs;
24530   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
24531
24532   if (dwarf2_per_objfile->die_type_hash == NULL)
24533     return NULL;
24534
24535   ofs.per_cu = per_cu;
24536   ofs.sect_off = sect_off;
24537   slot = ((struct dwarf2_per_cu_offset_and_type *)
24538           htab_find (dwarf2_per_objfile->die_type_hash.get (), &ofs));
24539   if (slot)
24540     return slot->type;
24541   else
24542     return NULL;
24543 }
24544
24545 /* Look up the type for DIE in CU in die_type_hash,
24546    or return NULL if DIE does not have a saved type.  */
24547
24548 static struct type *
24549 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
24550 {
24551   return get_die_type_at_offset (die->sect_off, cu->per_cu);
24552 }
24553
24554 /* Add a dependence relationship from CU to REF_PER_CU.  */
24555
24556 static void
24557 dwarf2_add_dependence (struct dwarf2_cu *cu,
24558                        struct dwarf2_per_cu_data *ref_per_cu)
24559 {
24560   void **slot;
24561
24562   if (cu->dependencies == NULL)
24563     cu->dependencies
24564       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
24565                               NULL, &cu->comp_unit_obstack,
24566                               hashtab_obstack_allocate,
24567                               dummy_obstack_deallocate);
24568
24569   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
24570   if (*slot == NULL)
24571     *slot = ref_per_cu;
24572 }
24573
24574 /* Subroutine of dwarf2_mark to pass to htab_traverse.
24575    Set the mark field in every compilation unit in the
24576    cache that we must keep because we are keeping CU.  */
24577
24578 static int
24579 dwarf2_mark_helper (void **slot, void *data)
24580 {
24581   struct dwarf2_per_cu_data *per_cu;
24582
24583   per_cu = (struct dwarf2_per_cu_data *) *slot;
24584
24585   /* cu->dependencies references may not yet have been ever read if QUIT aborts
24586      reading of the chain.  As such dependencies remain valid it is not much
24587      useful to track and undo them during QUIT cleanups.  */
24588   if (per_cu->cu == NULL)
24589     return 1;
24590
24591   if (per_cu->cu->mark)
24592     return 1;
24593   per_cu->cu->mark = true;
24594
24595   if (per_cu->cu->dependencies != NULL)
24596     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
24597
24598   return 1;
24599 }
24600
24601 /* Set the mark field in CU and in every other compilation unit in the
24602    cache that we must keep because we are keeping CU.  */
24603
24604 static void
24605 dwarf2_mark (struct dwarf2_cu *cu)
24606 {
24607   if (cu->mark)
24608     return;
24609   cu->mark = true;
24610   if (cu->dependencies != NULL)
24611     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
24612 }
24613
24614 static void
24615 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
24616 {
24617   while (per_cu)
24618     {
24619       per_cu->cu->mark = false;
24620       per_cu = per_cu->cu->read_in_chain;
24621     }
24622 }
24623
24624 /* Trivial hash function for partial_die_info: the hash value of a DIE
24625    is its offset in .debug_info for this objfile.  */
24626
24627 static hashval_t
24628 partial_die_hash (const void *item)
24629 {
24630   const struct partial_die_info *part_die
24631     = (const struct partial_die_info *) item;
24632
24633   return to_underlying (part_die->sect_off);
24634 }
24635
24636 /* Trivial comparison function for partial_die_info structures: two DIEs
24637    are equal if they have the same offset.  */
24638
24639 static int
24640 partial_die_eq (const void *item_lhs, const void *item_rhs)
24641 {
24642   const struct partial_die_info *part_die_lhs
24643     = (const struct partial_die_info *) item_lhs;
24644   const struct partial_die_info *part_die_rhs
24645     = (const struct partial_die_info *) item_rhs;
24646
24647   return part_die_lhs->sect_off == part_die_rhs->sect_off;
24648 }
24649
24650 struct cmd_list_element *set_dwarf_cmdlist;
24651 struct cmd_list_element *show_dwarf_cmdlist;
24652
24653 static void
24654 set_dwarf_cmd (const char *args, int from_tty)
24655 {
24656   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
24657              gdb_stdout);
24658 }
24659
24660 static void
24661 show_dwarf_cmd (const char *args, int from_tty)
24662 {
24663   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
24664 }
24665
24666 static void
24667 show_check_physname (struct ui_file *file, int from_tty,
24668                      struct cmd_list_element *c, const char *value)
24669 {
24670   fprintf_filtered (file,
24671                     _("Whether to check \"physname\" is %s.\n"),
24672                     value);
24673 }
24674
24675 void _initialize_dwarf2_read ();
24676 void
24677 _initialize_dwarf2_read ()
24678 {
24679   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24680 Set DWARF specific variables.\n\
24681 Configure DWARF variables such as the cache size."),
24682                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24683                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24684
24685   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24686 Show DWARF specific variables.\n\
24687 Show DWARF variables such as the cache size."),
24688                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24689                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24690
24691   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24692                             &dwarf_max_cache_age, _("\
24693 Set the upper bound on the age of cached DWARF compilation units."), _("\
24694 Show the upper bound on the age of cached DWARF compilation units."), _("\
24695 A higher limit means that cached compilation units will be stored\n\
24696 in memory longer, and more total memory will be used.  Zero disables\n\
24697 caching, which can slow down startup."),
24698                             NULL,
24699                             show_dwarf_max_cache_age,
24700                             &set_dwarf_cmdlist,
24701                             &show_dwarf_cmdlist);
24702
24703   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24704 Set debugging of the DWARF reader."), _("\
24705 Show debugging of the DWARF reader."), _("\
24706 When enabled (non-zero), debugging messages are printed during DWARF\n\
24707 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24708 information.  A value greater than 1 provides more verbose information."),
24709                             NULL,
24710                             NULL,
24711                             &setdebuglist, &showdebuglist);
24712
24713   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24714 Set debugging of the DWARF DIE reader."), _("\
24715 Show debugging of the DWARF DIE reader."), _("\
24716 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24717 The value is the maximum depth to print."),
24718                              NULL,
24719                              NULL,
24720                              &setdebuglist, &showdebuglist);
24721
24722   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24723 Set debugging of the dwarf line reader."), _("\
24724 Show debugging of the dwarf line reader."), _("\
24725 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24726 A value of 1 (one) provides basic information.\n\
24727 A value greater than 1 provides more verbose information."),
24728                              NULL,
24729                              NULL,
24730                              &setdebuglist, &showdebuglist);
24731
24732   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24733 Set cross-checking of \"physname\" code against demangler."), _("\
24734 Show cross-checking of \"physname\" code against demangler."), _("\
24735 When enabled, GDB's internal \"physname\" code is checked against\n\
24736 the demangler."),
24737                            NULL, show_check_physname,
24738                            &setdebuglist, &showdebuglist);
24739
24740   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24741                            no_class, &use_deprecated_index_sections, _("\
24742 Set whether to use deprecated gdb_index sections."), _("\
24743 Show whether to use deprecated gdb_index sections."), _("\
24744 When enabled, deprecated .gdb_index sections are used anyway.\n\
24745 Normally they are ignored either because of a missing feature or\n\
24746 performance issue.\n\
24747 Warning: This option must be enabled before gdb reads the file."),
24748                            NULL,
24749                            NULL,
24750                            &setlist, &showlist);
24751
24752   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24753                                                         &dwarf2_locexpr_funcs);
24754   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24755                                                         &dwarf2_loclist_funcs);
24756
24757   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24758                                         &dwarf2_block_frame_base_locexpr_funcs);
24759   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24760                                         &dwarf2_block_frame_base_loclist_funcs);
24761
24762 #if GDB_SELF_TEST
24763   selftests::register_test ("dw2_expand_symtabs_matching",
24764                             selftests::dw2_expand_symtabs_matching::run_test);
24765   selftests::register_test ("dwarf2_find_containing_comp_unit",
24766                             selftests::find_containing_comp_unit::run_test);
24767 #endif
24768 }
This page took 1.515389 seconds and 4 git commands to generate.