dwarf2read: Use bool for dwarf2_section_info fields
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2019 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "dwarf2read.h"
33 #include "dwarf-index-cache.h"
34 #include "dwarf-index-common.h"
35 #include "bfd.h"
36 #include "elf-bfd.h"
37 #include "symtab.h"
38 #include "gdbtypes.h"
39 #include "objfiles.h"
40 #include "dwarf2.h"
41 #include "buildsym.h"
42 #include "demangle.h"
43 #include "gdb-demangle.h"
44 #include "expression.h"
45 #include "filenames.h"  /* for DOSish file names */
46 #include "macrotab.h"
47 #include "language.h"
48 #include "complaints.h"
49 #include "dwarf2expr.h"
50 #include "dwarf2loc.h"
51 #include "cp-support.h"
52 #include "hashtab.h"
53 #include "command.h"
54 #include "gdbcmd.h"
55 #include "block.h"
56 #include "addrmap.h"
57 #include "typeprint.h"
58 #include "psympriv.h"
59 #include <sys/stat.h>
60 #include "completer.h"
61 #include "common/vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "common/filestuff.h"
72 #include "build-id.h"
73 #include "namespace.h"
74 #include "common/gdb_unlinker.h"
75 #include "common/function-view.h"
76 #include "common/gdb_optional.h"
77 #include "common/underlying.h"
78 #include "common/byte-vector.h"
79 #include "common/hash_enum.h"
80 #include "filename-seen-cache.h"
81 #include "producer.h"
82 #include <fcntl.h>
83 #include <sys/types.h>
84 #include <algorithm>
85 #include <unordered_set>
86 #include <unordered_map>
87 #include "common/selftest.h"
88 #include <cmath>
89 #include <set>
90 #include <forward_list>
91 #include "rust-lang.h"
92 #include "common/pathstuff.h"
93
94 /* When == 1, print basic high level tracing messages.
95    When > 1, be more verbose.
96    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
97 static unsigned int dwarf_read_debug = 0;
98
99 /* When non-zero, dump DIEs after they are read in.  */
100 static unsigned int dwarf_die_debug = 0;
101
102 /* When non-zero, dump line number entries as they are read in.  */
103 static unsigned int dwarf_line_debug = 0;
104
105 /* When non-zero, cross-check physname against demangler.  */
106 static int check_physname = 0;
107
108 /* When non-zero, do not reject deprecated .gdb_index sections.  */
109 static int use_deprecated_index_sections = 0;
110
111 static const struct objfile_key<dwarf2_per_objfile> dwarf2_objfile_data_key;
112
113 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
114
115 static int dwarf2_locexpr_index;
116 static int dwarf2_loclist_index;
117 static int dwarf2_locexpr_block_index;
118 static int dwarf2_loclist_block_index;
119
120 /* An index into a (C++) symbol name component in a symbol name as
121    recorded in the mapped_index's symbol table.  For each C++ symbol
122    in the symbol table, we record one entry for the start of each
123    component in the symbol in a table of name components, and then
124    sort the table, in order to be able to binary search symbol names,
125    ignoring leading namespaces, both completion and regular look up.
126    For example, for symbol "A::B::C", we'll have an entry that points
127    to "A::B::C", another that points to "B::C", and another for "C".
128    Note that function symbols in GDB index have no parameter
129    information, just the function/method names.  You can convert a
130    name_component to a "const char *" using the
131    'mapped_index::symbol_name_at(offset_type)' method.  */
132
133 struct name_component
134 {
135   /* Offset in the symbol name where the component starts.  Stored as
136      a (32-bit) offset instead of a pointer to save memory and improve
137      locality on 64-bit architectures.  */
138   offset_type name_offset;
139
140   /* The symbol's index in the symbol and constant pool tables of a
141      mapped_index.  */
142   offset_type idx;
143 };
144
145 /* Base class containing bits shared by both .gdb_index and
146    .debug_name indexes.  */
147
148 struct mapped_index_base
149 {
150   mapped_index_base () = default;
151   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
152
153   /* The name_component table (a sorted vector).  See name_component's
154      description above.  */
155   std::vector<name_component> name_components;
156
157   /* How NAME_COMPONENTS is sorted.  */
158   enum case_sensitivity name_components_casing;
159
160   /* Return the number of names in the symbol table.  */
161   virtual size_t symbol_name_count () const = 0;
162
163   /* Get the name of the symbol at IDX in the symbol table.  */
164   virtual const char *symbol_name_at (offset_type idx) const = 0;
165
166   /* Return whether the name at IDX in the symbol table should be
167      ignored.  */
168   virtual bool symbol_name_slot_invalid (offset_type idx) const
169   {
170     return false;
171   }
172
173   /* Build the symbol name component sorted vector, if we haven't
174      yet.  */
175   void build_name_components ();
176
177   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
178      possible matches for LN_NO_PARAMS in the name component
179      vector.  */
180   std::pair<std::vector<name_component>::const_iterator,
181             std::vector<name_component>::const_iterator>
182     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
183
184   /* Prevent deleting/destroying via a base class pointer.  */
185 protected:
186   ~mapped_index_base() = default;
187 };
188
189 /* A description of the mapped index.  The file format is described in
190    a comment by the code that writes the index.  */
191 struct mapped_index final : public mapped_index_base
192 {
193   /* A slot/bucket in the symbol table hash.  */
194   struct symbol_table_slot
195   {
196     const offset_type name;
197     const offset_type vec;
198   };
199
200   /* Index data format version.  */
201   int version = 0;
202
203   /* The address table data.  */
204   gdb::array_view<const gdb_byte> address_table;
205
206   /* The symbol table, implemented as a hash table.  */
207   gdb::array_view<symbol_table_slot> symbol_table;
208
209   /* A pointer to the constant pool.  */
210   const char *constant_pool = nullptr;
211
212   bool symbol_name_slot_invalid (offset_type idx) const override
213   {
214     const auto &bucket = this->symbol_table[idx];
215     return bucket.name == 0 && bucket.vec == 0;
216   }
217
218   /* Convenience method to get at the name of the symbol at IDX in the
219      symbol table.  */
220   const char *symbol_name_at (offset_type idx) const override
221   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
222
223   size_t symbol_name_count () const override
224   { return this->symbol_table.size (); }
225 };
226
227 /* A description of the mapped .debug_names.
228    Uninitialized map has CU_COUNT 0.  */
229 struct mapped_debug_names final : public mapped_index_base
230 {
231   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
232   : dwarf2_per_objfile (dwarf2_per_objfile_)
233   {}
234
235   struct dwarf2_per_objfile *dwarf2_per_objfile;
236   bfd_endian dwarf5_byte_order;
237   bool dwarf5_is_dwarf64;
238   bool augmentation_is_gdb;
239   uint8_t offset_size;
240   uint32_t cu_count = 0;
241   uint32_t tu_count, bucket_count, name_count;
242   const gdb_byte *cu_table_reordered, *tu_table_reordered;
243   const uint32_t *bucket_table_reordered, *hash_table_reordered;
244   const gdb_byte *name_table_string_offs_reordered;
245   const gdb_byte *name_table_entry_offs_reordered;
246   const gdb_byte *entry_pool;
247
248   struct index_val
249   {
250     ULONGEST dwarf_tag;
251     struct attr
252     {
253       /* Attribute name DW_IDX_*.  */
254       ULONGEST dw_idx;
255
256       /* Attribute form DW_FORM_*.  */
257       ULONGEST form;
258
259       /* Value if FORM is DW_FORM_implicit_const.  */
260       LONGEST implicit_const;
261     };
262     std::vector<attr> attr_vec;
263   };
264
265   std::unordered_map<ULONGEST, index_val> abbrev_map;
266
267   const char *namei_to_name (uint32_t namei) const;
268
269   /* Implementation of the mapped_index_base virtual interface, for
270      the name_components cache.  */
271
272   const char *symbol_name_at (offset_type idx) const override
273   { return namei_to_name (idx); }
274
275   size_t symbol_name_count () const override
276   { return this->name_count; }
277 };
278
279 /* See dwarf2read.h.  */
280
281 dwarf2_per_objfile *
282 get_dwarf2_per_objfile (struct objfile *objfile)
283 {
284   return dwarf2_objfile_data_key.get (objfile);
285 }
286
287 /* Default names of the debugging sections.  */
288
289 /* Note that if the debugging section has been compressed, it might
290    have a name like .zdebug_info.  */
291
292 static const struct dwarf2_debug_sections dwarf2_elf_names =
293 {
294   { ".debug_info", ".zdebug_info" },
295   { ".debug_abbrev", ".zdebug_abbrev" },
296   { ".debug_line", ".zdebug_line" },
297   { ".debug_loc", ".zdebug_loc" },
298   { ".debug_loclists", ".zdebug_loclists" },
299   { ".debug_macinfo", ".zdebug_macinfo" },
300   { ".debug_macro", ".zdebug_macro" },
301   { ".debug_str", ".zdebug_str" },
302   { ".debug_line_str", ".zdebug_line_str" },
303   { ".debug_ranges", ".zdebug_ranges" },
304   { ".debug_rnglists", ".zdebug_rnglists" },
305   { ".debug_types", ".zdebug_types" },
306   { ".debug_addr", ".zdebug_addr" },
307   { ".debug_frame", ".zdebug_frame" },
308   { ".eh_frame", NULL },
309   { ".gdb_index", ".zgdb_index" },
310   { ".debug_names", ".zdebug_names" },
311   { ".debug_aranges", ".zdebug_aranges" },
312   23
313 };
314
315 /* List of DWO/DWP sections.  */
316
317 static const struct dwop_section_names
318 {
319   struct dwarf2_section_names abbrev_dwo;
320   struct dwarf2_section_names info_dwo;
321   struct dwarf2_section_names line_dwo;
322   struct dwarf2_section_names loc_dwo;
323   struct dwarf2_section_names loclists_dwo;
324   struct dwarf2_section_names macinfo_dwo;
325   struct dwarf2_section_names macro_dwo;
326   struct dwarf2_section_names str_dwo;
327   struct dwarf2_section_names str_offsets_dwo;
328   struct dwarf2_section_names types_dwo;
329   struct dwarf2_section_names cu_index;
330   struct dwarf2_section_names tu_index;
331 }
332 dwop_section_names =
333 {
334   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
335   { ".debug_info.dwo", ".zdebug_info.dwo" },
336   { ".debug_line.dwo", ".zdebug_line.dwo" },
337   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
338   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
339   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
340   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
341   { ".debug_str.dwo", ".zdebug_str.dwo" },
342   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
343   { ".debug_types.dwo", ".zdebug_types.dwo" },
344   { ".debug_cu_index", ".zdebug_cu_index" },
345   { ".debug_tu_index", ".zdebug_tu_index" },
346 };
347
348 /* local data types */
349
350 /* The data in a compilation unit header, after target2host
351    translation, looks like this.  */
352 struct comp_unit_head
353 {
354   unsigned int length;
355   short version;
356   unsigned char addr_size;
357   unsigned char signed_addr_p;
358   sect_offset abbrev_sect_off;
359
360   /* Size of file offsets; either 4 or 8.  */
361   unsigned int offset_size;
362
363   /* Size of the length field; either 4 or 12.  */
364   unsigned int initial_length_size;
365
366   enum dwarf_unit_type unit_type;
367
368   /* Offset to the first byte of this compilation unit header in the
369      .debug_info section, for resolving relative reference dies.  */
370   sect_offset sect_off;
371
372   /* Offset to first die in this cu from the start of the cu.
373      This will be the first byte following the compilation unit header.  */
374   cu_offset first_die_cu_offset;
375
376   /* 64-bit signature of this type unit - it is valid only for
377      UNIT_TYPE DW_UT_type.  */
378   ULONGEST signature;
379
380   /* For types, offset in the type's DIE of the type defined by this TU.  */
381   cu_offset type_cu_offset_in_tu;
382 };
383
384 /* Type used for delaying computation of method physnames.
385    See comments for compute_delayed_physnames.  */
386 struct delayed_method_info
387 {
388   /* The type to which the method is attached, i.e., its parent class.  */
389   struct type *type;
390
391   /* The index of the method in the type's function fieldlists.  */
392   int fnfield_index;
393
394   /* The index of the method in the fieldlist.  */
395   int index;
396
397   /* The name of the DIE.  */
398   const char *name;
399
400   /*  The DIE associated with this method.  */
401   struct die_info *die;
402 };
403
404 /* Internal state when decoding a particular compilation unit.  */
405 struct dwarf2_cu
406 {
407   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
408   ~dwarf2_cu ();
409
410   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
411
412   /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
413      Create the set of symtabs used by this TU, or if this TU is sharing
414      symtabs with another TU and the symtabs have already been created
415      then restore those symtabs in the line header.
416      We don't need the pc/line-number mapping for type units.  */
417   void setup_type_unit_groups (struct die_info *die);
418
419   /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
420      buildsym_compunit constructor.  */
421   struct compunit_symtab *start_symtab (const char *name,
422                                         const char *comp_dir,
423                                         CORE_ADDR low_pc);
424
425   /* Reset the builder.  */
426   void reset_builder () { m_builder.reset (); }
427
428   /* The header of the compilation unit.  */
429   struct comp_unit_head header {};
430
431   /* Base address of this compilation unit.  */
432   CORE_ADDR base_address = 0;
433
434   /* Non-zero if base_address has been set.  */
435   int base_known = 0;
436
437   /* The language we are debugging.  */
438   enum language language = language_unknown;
439   const struct language_defn *language_defn = nullptr;
440
441   const char *producer = nullptr;
442
443 private:
444   /* The symtab builder for this CU.  This is only non-NULL when full
445      symbols are being read.  */
446   std::unique_ptr<buildsym_compunit> m_builder;
447
448 public:
449   /* The generic symbol table building routines have separate lists for
450      file scope symbols and all all other scopes (local scopes).  So
451      we need to select the right one to pass to add_symbol_to_list().
452      We do it by keeping a pointer to the correct list in list_in_scope.
453
454      FIXME: The original dwarf code just treated the file scope as the
455      first local scope, and all other local scopes as nested local
456      scopes, and worked fine.  Check to see if we really need to
457      distinguish these in buildsym.c.  */
458   struct pending **list_in_scope = nullptr;
459
460   /* Hash table holding all the loaded partial DIEs
461      with partial_die->offset.SECT_OFF as hash.  */
462   htab_t partial_dies = nullptr;
463
464   /* Storage for things with the same lifetime as this read-in compilation
465      unit, including partial DIEs.  */
466   auto_obstack comp_unit_obstack;
467
468   /* When multiple dwarf2_cu structures are living in memory, this field
469      chains them all together, so that they can be released efficiently.
470      We will probably also want a generation counter so that most-recently-used
471      compilation units are cached...  */
472   struct dwarf2_per_cu_data *read_in_chain = nullptr;
473
474   /* Backlink to our per_cu entry.  */
475   struct dwarf2_per_cu_data *per_cu;
476
477   /* How many compilation units ago was this CU last referenced?  */
478   int last_used = 0;
479
480   /* A hash table of DIE cu_offset for following references with
481      die_info->offset.sect_off as hash.  */
482   htab_t die_hash = nullptr;
483
484   /* Full DIEs if read in.  */
485   struct die_info *dies = nullptr;
486
487   /* A set of pointers to dwarf2_per_cu_data objects for compilation
488      units referenced by this one.  Only set during full symbol processing;
489      partial symbol tables do not have dependencies.  */
490   htab_t dependencies = nullptr;
491
492   /* Header data from the line table, during full symbol processing.  */
493   struct line_header *line_header = nullptr;
494   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
495      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
496      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
497      to the line header as long as this DIE is being processed.  See
498      process_die_scope.  */
499   die_info *line_header_die_owner = nullptr;
500
501   /* A list of methods which need to have physnames computed
502      after all type information has been read.  */
503   std::vector<delayed_method_info> method_list;
504
505   /* To be copied to symtab->call_site_htab.  */
506   htab_t call_site_htab = nullptr;
507
508   /* Non-NULL if this CU came from a DWO file.
509      There is an invariant here that is important to remember:
510      Except for attributes copied from the top level DIE in the "main"
511      (or "stub") file in preparation for reading the DWO file
512      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
513      Either there isn't a DWO file (in which case this is NULL and the point
514      is moot), or there is and either we're not going to read it (in which
515      case this is NULL) or there is and we are reading it (in which case this
516      is non-NULL).  */
517   struct dwo_unit *dwo_unit = nullptr;
518
519   /* The DW_AT_addr_base attribute if present, zero otherwise
520      (zero is a valid value though).
521      Note this value comes from the Fission stub CU/TU's DIE.  */
522   ULONGEST addr_base = 0;
523
524   /* The DW_AT_ranges_base attribute if present, zero otherwise
525      (zero is a valid value though).
526      Note this value comes from the Fission stub CU/TU's DIE.
527      Also note that the value is zero in the non-DWO case so this value can
528      be used without needing to know whether DWO files are in use or not.
529      N.B. This does not apply to DW_AT_ranges appearing in
530      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
531      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
532      DW_AT_ranges_base *would* have to be applied, and we'd have to care
533      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
534   ULONGEST ranges_base = 0;
535
536   /* When reading debug info generated by older versions of rustc, we
537      have to rewrite some union types to be struct types with a
538      variant part.  This rewriting must be done after the CU is fully
539      read in, because otherwise at the point of rewriting some struct
540      type might not have been fully processed.  So, we keep a list of
541      all such types here and process them after expansion.  */
542   std::vector<struct type *> rust_unions;
543
544   /* Mark used when releasing cached dies.  */
545   bool mark : 1;
546
547   /* This CU references .debug_loc.  See the symtab->locations_valid field.
548      This test is imperfect as there may exist optimized debug code not using
549      any location list and still facing inlining issues if handled as
550      unoptimized code.  For a future better test see GCC PR other/32998.  */
551   bool has_loclist : 1;
552
553   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is true
554      if all the producer_is_* fields are valid.  This information is cached
555      because profiling CU expansion showed excessive time spent in
556      producer_is_gxx_lt_4_6.  */
557   bool checked_producer : 1;
558   bool producer_is_gxx_lt_4_6 : 1;
559   bool producer_is_gcc_lt_4_3 : 1;
560   bool producer_is_icc : 1;
561   bool producer_is_icc_lt_14 : 1;
562   bool producer_is_codewarrior : 1;
563
564   /* When true, the file that we're processing is known to have
565      debugging info for C++ namespaces.  GCC 3.3.x did not produce
566      this information, but later versions do.  */
567
568   bool processing_has_namespace_info : 1;
569
570   struct partial_die_info *find_partial_die (sect_offset sect_off);
571
572   /* If this CU was inherited by another CU (via specification,
573      abstract_origin, etc), this is the ancestor CU.  */
574   dwarf2_cu *ancestor;
575
576   /* Get the buildsym_compunit for this CU.  */
577   buildsym_compunit *get_builder ()
578   {
579     /* If this CU has a builder associated with it, use that.  */
580     if (m_builder != nullptr)
581       return m_builder.get ();
582
583     /* Otherwise, search ancestors for a valid builder.  */
584     if (ancestor != nullptr)
585       return ancestor->get_builder ();
586
587     return nullptr;
588   }
589 };
590
591 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
592    This includes type_unit_group and quick_file_names.  */
593
594 struct stmt_list_hash
595 {
596   /* The DWO unit this table is from or NULL if there is none.  */
597   struct dwo_unit *dwo_unit;
598
599   /* Offset in .debug_line or .debug_line.dwo.  */
600   sect_offset line_sect_off;
601 };
602
603 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
604    an object of this type.  */
605
606 struct type_unit_group
607 {
608   /* dwarf2read.c's main "handle" on a TU symtab.
609      To simplify things we create an artificial CU that "includes" all the
610      type units using this stmt_list so that the rest of the code still has
611      a "per_cu" handle on the symtab.
612      This PER_CU is recognized by having no section.  */
613 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
614   struct dwarf2_per_cu_data per_cu;
615
616   /* The TUs that share this DW_AT_stmt_list entry.
617      This is added to while parsing type units to build partial symtabs,
618      and is deleted afterwards and not used again.  */
619   VEC (sig_type_ptr) *tus;
620
621   /* The compunit symtab.
622      Type units in a group needn't all be defined in the same source file,
623      so we create an essentially anonymous symtab as the compunit symtab.  */
624   struct compunit_symtab *compunit_symtab;
625
626   /* The data used to construct the hash key.  */
627   struct stmt_list_hash hash;
628
629   /* The number of symtabs from the line header.
630      The value here must match line_header.num_file_names.  */
631   unsigned int num_symtabs;
632
633   /* The symbol tables for this TU (obtained from the files listed in
634      DW_AT_stmt_list).
635      WARNING: The order of entries here must match the order of entries
636      in the line header.  After the first TU using this type_unit_group, the
637      line header for the subsequent TUs is recreated from this.  This is done
638      because we need to use the same symtabs for each TU using the same
639      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
640      there's no guarantee the line header doesn't have duplicate entries.  */
641   struct symtab **symtabs;
642 };
643
644 /* These sections are what may appear in a (real or virtual) DWO file.  */
645
646 struct dwo_sections
647 {
648   struct dwarf2_section_info abbrev;
649   struct dwarf2_section_info line;
650   struct dwarf2_section_info loc;
651   struct dwarf2_section_info loclists;
652   struct dwarf2_section_info macinfo;
653   struct dwarf2_section_info macro;
654   struct dwarf2_section_info str;
655   struct dwarf2_section_info str_offsets;
656   /* In the case of a virtual DWO file, these two are unused.  */
657   struct dwarf2_section_info info;
658   VEC (dwarf2_section_info_def) *types;
659 };
660
661 /* CUs/TUs in DWP/DWO files.  */
662
663 struct dwo_unit
664 {
665   /* Backlink to the containing struct dwo_file.  */
666   struct dwo_file *dwo_file;
667
668   /* The "id" that distinguishes this CU/TU.
669      .debug_info calls this "dwo_id", .debug_types calls this "signature".
670      Since signatures came first, we stick with it for consistency.  */
671   ULONGEST signature;
672
673   /* The section this CU/TU lives in, in the DWO file.  */
674   struct dwarf2_section_info *section;
675
676   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
677   sect_offset sect_off;
678   unsigned int length;
679
680   /* For types, offset in the type's DIE of the type defined by this TU.  */
681   cu_offset type_offset_in_tu;
682 };
683
684 /* include/dwarf2.h defines the DWP section codes.
685    It defines a max value but it doesn't define a min value, which we
686    use for error checking, so provide one.  */
687
688 enum dwp_v2_section_ids
689 {
690   DW_SECT_MIN = 1
691 };
692
693 /* Data for one DWO file.
694
695    This includes virtual DWO files (a virtual DWO file is a DWO file as it
696    appears in a DWP file).  DWP files don't really have DWO files per se -
697    comdat folding of types "loses" the DWO file they came from, and from
698    a high level view DWP files appear to contain a mass of random types.
699    However, to maintain consistency with the non-DWP case we pretend DWP
700    files contain virtual DWO files, and we assign each TU with one virtual
701    DWO file (generally based on the line and abbrev section offsets -
702    a heuristic that seems to work in practice).  */
703
704 struct dwo_file
705 {
706   /* The DW_AT_GNU_dwo_name attribute.
707      For virtual DWO files the name is constructed from the section offsets
708      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
709      from related CU+TUs.  */
710   const char *dwo_name;
711
712   /* The DW_AT_comp_dir attribute.  */
713   const char *comp_dir;
714
715   /* The bfd, when the file is open.  Otherwise this is NULL.
716      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
717   bfd *dbfd;
718
719   /* The sections that make up this DWO file.
720      Remember that for virtual DWO files in DWP V2, these are virtual
721      sections (for lack of a better name).  */
722   struct dwo_sections sections;
723
724   /* The CUs in the file.
725      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
726      an extension to handle LLVM's Link Time Optimization output (where
727      multiple source files may be compiled into a single object/dwo pair). */
728   htab_t cus;
729
730   /* Table of TUs in the file.
731      Each element is a struct dwo_unit.  */
732   htab_t tus;
733 };
734
735 /* These sections are what may appear in a DWP file.  */
736
737 struct dwp_sections
738 {
739   /* These are used by both DWP version 1 and 2.  */
740   struct dwarf2_section_info str;
741   struct dwarf2_section_info cu_index;
742   struct dwarf2_section_info tu_index;
743
744   /* These are only used by DWP version 2 files.
745      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
746      sections are referenced by section number, and are not recorded here.
747      In DWP version 2 there is at most one copy of all these sections, each
748      section being (effectively) comprised of the concatenation of all of the
749      individual sections that exist in the version 1 format.
750      To keep the code simple we treat each of these concatenated pieces as a
751      section itself (a virtual section?).  */
752   struct dwarf2_section_info abbrev;
753   struct dwarf2_section_info info;
754   struct dwarf2_section_info line;
755   struct dwarf2_section_info loc;
756   struct dwarf2_section_info macinfo;
757   struct dwarf2_section_info macro;
758   struct dwarf2_section_info str_offsets;
759   struct dwarf2_section_info types;
760 };
761
762 /* These sections are what may appear in a virtual DWO file in DWP version 1.
763    A virtual DWO file is a DWO file as it appears in a DWP file.  */
764
765 struct virtual_v1_dwo_sections
766 {
767   struct dwarf2_section_info abbrev;
768   struct dwarf2_section_info line;
769   struct dwarf2_section_info loc;
770   struct dwarf2_section_info macinfo;
771   struct dwarf2_section_info macro;
772   struct dwarf2_section_info str_offsets;
773   /* Each DWP hash table entry records one CU or one TU.
774      That is recorded here, and copied to dwo_unit.section.  */
775   struct dwarf2_section_info info_or_types;
776 };
777
778 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
779    In version 2, the sections of the DWO files are concatenated together
780    and stored in one section of that name.  Thus each ELF section contains
781    several "virtual" sections.  */
782
783 struct virtual_v2_dwo_sections
784 {
785   bfd_size_type abbrev_offset;
786   bfd_size_type abbrev_size;
787
788   bfd_size_type line_offset;
789   bfd_size_type line_size;
790
791   bfd_size_type loc_offset;
792   bfd_size_type loc_size;
793
794   bfd_size_type macinfo_offset;
795   bfd_size_type macinfo_size;
796
797   bfd_size_type macro_offset;
798   bfd_size_type macro_size;
799
800   bfd_size_type str_offsets_offset;
801   bfd_size_type str_offsets_size;
802
803   /* Each DWP hash table entry records one CU or one TU.
804      That is recorded here, and copied to dwo_unit.section.  */
805   bfd_size_type info_or_types_offset;
806   bfd_size_type info_or_types_size;
807 };
808
809 /* Contents of DWP hash tables.  */
810
811 struct dwp_hash_table
812 {
813   uint32_t version, nr_columns;
814   uint32_t nr_units, nr_slots;
815   const gdb_byte *hash_table, *unit_table;
816   union
817   {
818     struct
819     {
820       const gdb_byte *indices;
821     } v1;
822     struct
823     {
824       /* This is indexed by column number and gives the id of the section
825          in that column.  */
826 #define MAX_NR_V2_DWO_SECTIONS \
827   (1 /* .debug_info or .debug_types */ \
828    + 1 /* .debug_abbrev */ \
829    + 1 /* .debug_line */ \
830    + 1 /* .debug_loc */ \
831    + 1 /* .debug_str_offsets */ \
832    + 1 /* .debug_macro or .debug_macinfo */)
833       int section_ids[MAX_NR_V2_DWO_SECTIONS];
834       const gdb_byte *offsets;
835       const gdb_byte *sizes;
836     } v2;
837   } section_pool;
838 };
839
840 /* Data for one DWP file.  */
841
842 struct dwp_file
843 {
844   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
845     : name (name_),
846       dbfd (std::move (abfd))
847   {
848   }
849
850   /* Name of the file.  */
851   const char *name;
852
853   /* File format version.  */
854   int version = 0;
855
856   /* The bfd.  */
857   gdb_bfd_ref_ptr dbfd;
858
859   /* Section info for this file.  */
860   struct dwp_sections sections {};
861
862   /* Table of CUs in the file.  */
863   const struct dwp_hash_table *cus = nullptr;
864
865   /* Table of TUs in the file.  */
866   const struct dwp_hash_table *tus = nullptr;
867
868   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
869   htab_t loaded_cus {};
870   htab_t loaded_tus {};
871
872   /* Table to map ELF section numbers to their sections.
873      This is only needed for the DWP V1 file format.  */
874   unsigned int num_sections = 0;
875   asection **elf_sections = nullptr;
876 };
877
878 /* Struct used to pass misc. parameters to read_die_and_children, et
879    al.  which are used for both .debug_info and .debug_types dies.
880    All parameters here are unchanging for the life of the call.  This
881    struct exists to abstract away the constant parameters of die reading.  */
882
883 struct die_reader_specs
884 {
885   /* The bfd of die_section.  */
886   bfd* abfd;
887
888   /* The CU of the DIE we are parsing.  */
889   struct dwarf2_cu *cu;
890
891   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
892   struct dwo_file *dwo_file;
893
894   /* The section the die comes from.
895      This is either .debug_info or .debug_types, or the .dwo variants.  */
896   struct dwarf2_section_info *die_section;
897
898   /* die_section->buffer.  */
899   const gdb_byte *buffer;
900
901   /* The end of the buffer.  */
902   const gdb_byte *buffer_end;
903
904   /* The value of the DW_AT_comp_dir attribute.  */
905   const char *comp_dir;
906
907   /* The abbreviation table to use when reading the DIEs.  */
908   struct abbrev_table *abbrev_table;
909 };
910
911 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
912 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
913                                       const gdb_byte *info_ptr,
914                                       struct die_info *comp_unit_die,
915                                       int has_children,
916                                       void *data);
917
918 /* A 1-based directory index.  This is a strong typedef to prevent
919    accidentally using a directory index as a 0-based index into an
920    array/vector.  */
921 enum class dir_index : unsigned int {};
922
923 /* Likewise, a 1-based file name index.  */
924 enum class file_name_index : unsigned int {};
925
926 struct file_entry
927 {
928   file_entry () = default;
929
930   file_entry (const char *name_, dir_index d_index_,
931               unsigned int mod_time_, unsigned int length_)
932     : name (name_),
933       d_index (d_index_),
934       mod_time (mod_time_),
935       length (length_)
936   {}
937
938   /* Return the include directory at D_INDEX stored in LH.  Returns
939      NULL if D_INDEX is out of bounds.  */
940   const char *include_dir (const line_header *lh) const;
941
942   /* The file name.  Note this is an observing pointer.  The memory is
943      owned by debug_line_buffer.  */
944   const char *name {};
945
946   /* The directory index (1-based).  */
947   dir_index d_index {};
948
949   unsigned int mod_time {};
950
951   unsigned int length {};
952
953   /* True if referenced by the Line Number Program.  */
954   bool included_p {};
955
956   /* The associated symbol table, if any.  */
957   struct symtab *symtab {};
958 };
959
960 /* The line number information for a compilation unit (found in the
961    .debug_line section) begins with a "statement program header",
962    which contains the following information.  */
963 struct line_header
964 {
965   line_header ()
966     : offset_in_dwz {}
967   {}
968
969   /* Add an entry to the include directory table.  */
970   void add_include_dir (const char *include_dir);
971
972   /* Add an entry to the file name table.  */
973   void add_file_name (const char *name, dir_index d_index,
974                       unsigned int mod_time, unsigned int length);
975
976   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
977      is out of bounds.  */
978   const char *include_dir_at (dir_index index) const
979   {
980     /* Convert directory index number (1-based) to vector index
981        (0-based).  */
982     size_t vec_index = to_underlying (index) - 1;
983
984     if (vec_index >= include_dirs.size ())
985       return NULL;
986     return include_dirs[vec_index];
987   }
988
989   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
990      is out of bounds.  */
991   file_entry *file_name_at (file_name_index index)
992   {
993     /* Convert file name index number (1-based) to vector index
994        (0-based).  */
995     size_t vec_index = to_underlying (index) - 1;
996
997     if (vec_index >= file_names.size ())
998       return NULL;
999     return &file_names[vec_index];
1000   }
1001
1002   /* Offset of line number information in .debug_line section.  */
1003   sect_offset sect_off {};
1004
1005   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1006   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1007
1008   unsigned int total_length {};
1009   unsigned short version {};
1010   unsigned int header_length {};
1011   unsigned char minimum_instruction_length {};
1012   unsigned char maximum_ops_per_instruction {};
1013   unsigned char default_is_stmt {};
1014   int line_base {};
1015   unsigned char line_range {};
1016   unsigned char opcode_base {};
1017
1018   /* standard_opcode_lengths[i] is the number of operands for the
1019      standard opcode whose value is i.  This means that
1020      standard_opcode_lengths[0] is unused, and the last meaningful
1021      element is standard_opcode_lengths[opcode_base - 1].  */
1022   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1023
1024   /* The include_directories table.  Note these are observing
1025      pointers.  The memory is owned by debug_line_buffer.  */
1026   std::vector<const char *> include_dirs;
1027
1028   /* The file_names table.  */
1029   std::vector<file_entry> file_names;
1030
1031   /* The start and end of the statement program following this
1032      header.  These point into dwarf2_per_objfile->line_buffer.  */
1033   const gdb_byte *statement_program_start {}, *statement_program_end {};
1034 };
1035
1036 typedef std::unique_ptr<line_header> line_header_up;
1037
1038 const char *
1039 file_entry::include_dir (const line_header *lh) const
1040 {
1041   return lh->include_dir_at (d_index);
1042 }
1043
1044 /* When we construct a partial symbol table entry we only
1045    need this much information.  */
1046 struct partial_die_info : public allocate_on_obstack
1047   {
1048     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1049
1050     /* Disable assign but still keep copy ctor, which is needed
1051        load_partial_dies.   */
1052     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1053
1054     /* Adjust the partial die before generating a symbol for it.  This
1055        function may set the is_external flag or change the DIE's
1056        name.  */
1057     void fixup (struct dwarf2_cu *cu);
1058
1059     /* Read a minimal amount of information into the minimal die
1060        structure.  */
1061     const gdb_byte *read (const struct die_reader_specs *reader,
1062                           const struct abbrev_info &abbrev,
1063                           const gdb_byte *info_ptr);
1064
1065     /* Offset of this DIE.  */
1066     const sect_offset sect_off;
1067
1068     /* DWARF-2 tag for this DIE.  */
1069     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1070
1071     /* Assorted flags describing the data found in this DIE.  */
1072     const unsigned int has_children : 1;
1073
1074     unsigned int is_external : 1;
1075     unsigned int is_declaration : 1;
1076     unsigned int has_type : 1;
1077     unsigned int has_specification : 1;
1078     unsigned int has_pc_info : 1;
1079     unsigned int may_be_inlined : 1;
1080
1081     /* This DIE has been marked DW_AT_main_subprogram.  */
1082     unsigned int main_subprogram : 1;
1083
1084     /* Flag set if the SCOPE field of this structure has been
1085        computed.  */
1086     unsigned int scope_set : 1;
1087
1088     /* Flag set if the DIE has a byte_size attribute.  */
1089     unsigned int has_byte_size : 1;
1090
1091     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1092     unsigned int has_const_value : 1;
1093
1094     /* Flag set if any of the DIE's children are template arguments.  */
1095     unsigned int has_template_arguments : 1;
1096
1097     /* Flag set if fixup has been called on this die.  */
1098     unsigned int fixup_called : 1;
1099
1100     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1101     unsigned int is_dwz : 1;
1102
1103     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1104     unsigned int spec_is_dwz : 1;
1105
1106     /* The name of this DIE.  Normally the value of DW_AT_name, but
1107        sometimes a default name for unnamed DIEs.  */
1108     const char *name = nullptr;
1109
1110     /* The linkage name, if present.  */
1111     const char *linkage_name = nullptr;
1112
1113     /* The scope to prepend to our children.  This is generally
1114        allocated on the comp_unit_obstack, so will disappear
1115        when this compilation unit leaves the cache.  */
1116     const char *scope = nullptr;
1117
1118     /* Some data associated with the partial DIE.  The tag determines
1119        which field is live.  */
1120     union
1121     {
1122       /* The location description associated with this DIE, if any.  */
1123       struct dwarf_block *locdesc;
1124       /* The offset of an import, for DW_TAG_imported_unit.  */
1125       sect_offset sect_off;
1126     } d {};
1127
1128     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1129     CORE_ADDR lowpc = 0;
1130     CORE_ADDR highpc = 0;
1131
1132     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1133        DW_AT_sibling, if any.  */
1134     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1135        could return DW_AT_sibling values to its caller load_partial_dies.  */
1136     const gdb_byte *sibling = nullptr;
1137
1138     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1139        DW_AT_specification (or DW_AT_abstract_origin or
1140        DW_AT_extension).  */
1141     sect_offset spec_offset {};
1142
1143     /* Pointers to this DIE's parent, first child, and next sibling,
1144        if any.  */
1145     struct partial_die_info *die_parent = nullptr;
1146     struct partial_die_info *die_child = nullptr;
1147     struct partial_die_info *die_sibling = nullptr;
1148
1149     friend struct partial_die_info *
1150     dwarf2_cu::find_partial_die (sect_offset sect_off);
1151
1152   private:
1153     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1154     partial_die_info (sect_offset sect_off)
1155       : partial_die_info (sect_off, DW_TAG_padding, 0)
1156     {
1157     }
1158
1159     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1160                       int has_children_)
1161       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1162     {
1163       is_external = 0;
1164       is_declaration = 0;
1165       has_type = 0;
1166       has_specification = 0;
1167       has_pc_info = 0;
1168       may_be_inlined = 0;
1169       main_subprogram = 0;
1170       scope_set = 0;
1171       has_byte_size = 0;
1172       has_const_value = 0;
1173       has_template_arguments = 0;
1174       fixup_called = 0;
1175       is_dwz = 0;
1176       spec_is_dwz = 0;
1177     }
1178   };
1179
1180 /* This data structure holds the information of an abbrev.  */
1181 struct abbrev_info
1182   {
1183     unsigned int number;        /* number identifying abbrev */
1184     enum dwarf_tag tag;         /* dwarf tag */
1185     unsigned short has_children;                /* boolean */
1186     unsigned short num_attrs;   /* number of attributes */
1187     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1188     struct abbrev_info *next;   /* next in chain */
1189   };
1190
1191 struct attr_abbrev
1192   {
1193     ENUM_BITFIELD(dwarf_attribute) name : 16;
1194     ENUM_BITFIELD(dwarf_form) form : 16;
1195
1196     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1197     LONGEST implicit_const;
1198   };
1199
1200 /* Size of abbrev_table.abbrev_hash_table.  */
1201 #define ABBREV_HASH_SIZE 121
1202
1203 /* Top level data structure to contain an abbreviation table.  */
1204
1205 struct abbrev_table
1206 {
1207   explicit abbrev_table (sect_offset off)
1208     : sect_off (off)
1209   {
1210     m_abbrevs =
1211       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1212     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1213   }
1214
1215   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1216
1217   /* Allocate space for a struct abbrev_info object in
1218      ABBREV_TABLE.  */
1219   struct abbrev_info *alloc_abbrev ();
1220
1221   /* Add an abbreviation to the table.  */
1222   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1223
1224   /* Look up an abbrev in the table.
1225      Returns NULL if the abbrev is not found.  */
1226
1227   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1228
1229
1230   /* Where the abbrev table came from.
1231      This is used as a sanity check when the table is used.  */
1232   const sect_offset sect_off;
1233
1234   /* Storage for the abbrev table.  */
1235   auto_obstack abbrev_obstack;
1236
1237 private:
1238
1239   /* Hash table of abbrevs.
1240      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1241      It could be statically allocated, but the previous code didn't so we
1242      don't either.  */
1243   struct abbrev_info **m_abbrevs;
1244 };
1245
1246 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1247
1248 /* Attributes have a name and a value.  */
1249 struct attribute
1250   {
1251     ENUM_BITFIELD(dwarf_attribute) name : 16;
1252     ENUM_BITFIELD(dwarf_form) form : 15;
1253
1254     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1255        field should be in u.str (existing only for DW_STRING) but it is kept
1256        here for better struct attribute alignment.  */
1257     unsigned int string_is_canonical : 1;
1258
1259     union
1260       {
1261         const char *str;
1262         struct dwarf_block *blk;
1263         ULONGEST unsnd;
1264         LONGEST snd;
1265         CORE_ADDR addr;
1266         ULONGEST signature;
1267       }
1268     u;
1269   };
1270
1271 /* This data structure holds a complete die structure.  */
1272 struct die_info
1273   {
1274     /* DWARF-2 tag for this DIE.  */
1275     ENUM_BITFIELD(dwarf_tag) tag : 16;
1276
1277     /* Number of attributes */
1278     unsigned char num_attrs;
1279
1280     /* True if we're presently building the full type name for the
1281        type derived from this DIE.  */
1282     unsigned char building_fullname : 1;
1283
1284     /* True if this die is in process.  PR 16581.  */
1285     unsigned char in_process : 1;
1286
1287     /* Abbrev number */
1288     unsigned int abbrev;
1289
1290     /* Offset in .debug_info or .debug_types section.  */
1291     sect_offset sect_off;
1292
1293     /* The dies in a compilation unit form an n-ary tree.  PARENT
1294        points to this die's parent; CHILD points to the first child of
1295        this node; and all the children of a given node are chained
1296        together via their SIBLING fields.  */
1297     struct die_info *child;     /* Its first child, if any.  */
1298     struct die_info *sibling;   /* Its next sibling, if any.  */
1299     struct die_info *parent;    /* Its parent, if any.  */
1300
1301     /* An array of attributes, with NUM_ATTRS elements.  There may be
1302        zero, but it's not common and zero-sized arrays are not
1303        sufficiently portable C.  */
1304     struct attribute attrs[1];
1305   };
1306
1307 /* Get at parts of an attribute structure.  */
1308
1309 #define DW_STRING(attr)    ((attr)->u.str)
1310 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1311 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1312 #define DW_BLOCK(attr)     ((attr)->u.blk)
1313 #define DW_SND(attr)       ((attr)->u.snd)
1314 #define DW_ADDR(attr)      ((attr)->u.addr)
1315 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1316
1317 /* Blocks are a bunch of untyped bytes.  */
1318 struct dwarf_block
1319   {
1320     size_t size;
1321
1322     /* Valid only if SIZE is not zero.  */
1323     const gdb_byte *data;
1324   };
1325
1326 #ifndef ATTR_ALLOC_CHUNK
1327 #define ATTR_ALLOC_CHUNK 4
1328 #endif
1329
1330 /* Allocate fields for structs, unions and enums in this size.  */
1331 #ifndef DW_FIELD_ALLOC_CHUNK
1332 #define DW_FIELD_ALLOC_CHUNK 4
1333 #endif
1334
1335 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1336    but this would require a corresponding change in unpack_field_as_long
1337    and friends.  */
1338 static int bits_per_byte = 8;
1339
1340 /* When reading a variant or variant part, we track a bit more
1341    information about the field, and store it in an object of this
1342    type.  */
1343
1344 struct variant_field
1345 {
1346   /* If we see a DW_TAG_variant, then this will be the discriminant
1347      value.  */
1348   ULONGEST discriminant_value;
1349   /* If we see a DW_TAG_variant, then this will be set if this is the
1350      default branch.  */
1351   bool default_branch;
1352   /* While reading a DW_TAG_variant_part, this will be set if this
1353      field is the discriminant.  */
1354   bool is_discriminant;
1355 };
1356
1357 struct nextfield
1358 {
1359   int accessibility = 0;
1360   int virtuality = 0;
1361   /* Extra information to describe a variant or variant part.  */
1362   struct variant_field variant {};
1363   struct field field {};
1364 };
1365
1366 struct fnfieldlist
1367 {
1368   const char *name = nullptr;
1369   std::vector<struct fn_field> fnfields;
1370 };
1371
1372 /* The routines that read and process dies for a C struct or C++ class
1373    pass lists of data member fields and lists of member function fields
1374    in an instance of a field_info structure, as defined below.  */
1375 struct field_info
1376   {
1377     /* List of data member and baseclasses fields.  */
1378     std::vector<struct nextfield> fields;
1379     std::vector<struct nextfield> baseclasses;
1380
1381     /* Number of fields (including baseclasses).  */
1382     int nfields = 0;
1383
1384     /* Set if the accesibility of one of the fields is not public.  */
1385     int non_public_fields = 0;
1386
1387     /* Member function fieldlist array, contains name of possibly overloaded
1388        member function, number of overloaded member functions and a pointer
1389        to the head of the member function field chain.  */
1390     std::vector<struct fnfieldlist> fnfieldlists;
1391
1392     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1393        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1394     std::vector<struct decl_field> typedef_field_list;
1395
1396     /* Nested types defined by this class and the number of elements in this
1397        list.  */
1398     std::vector<struct decl_field> nested_types_list;
1399   };
1400
1401 /* One item on the queue of compilation units to read in full symbols
1402    for.  */
1403 struct dwarf2_queue_item
1404 {
1405   struct dwarf2_per_cu_data *per_cu;
1406   enum language pretend_language;
1407   struct dwarf2_queue_item *next;
1408 };
1409
1410 /* The current queue.  */
1411 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1412
1413 /* Loaded secondary compilation units are kept in memory until they
1414    have not been referenced for the processing of this many
1415    compilation units.  Set this to zero to disable caching.  Cache
1416    sizes of up to at least twenty will improve startup time for
1417    typical inter-CU-reference binaries, at an obvious memory cost.  */
1418 static int dwarf_max_cache_age = 5;
1419 static void
1420 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1421                           struct cmd_list_element *c, const char *value)
1422 {
1423   fprintf_filtered (file, _("The upper bound on the age of cached "
1424                             "DWARF compilation units is %s.\n"),
1425                     value);
1426 }
1427 \f
1428 /* local function prototypes */
1429
1430 static const char *get_section_name (const struct dwarf2_section_info *);
1431
1432 static const char *get_section_file_name (const struct dwarf2_section_info *);
1433
1434 static void dwarf2_find_base_address (struct die_info *die,
1435                                       struct dwarf2_cu *cu);
1436
1437 static struct partial_symtab *create_partial_symtab
1438   (struct dwarf2_per_cu_data *per_cu, const char *name);
1439
1440 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1441                                         const gdb_byte *info_ptr,
1442                                         struct die_info *type_unit_die,
1443                                         int has_children, void *data);
1444
1445 static void dwarf2_build_psymtabs_hard
1446   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1447
1448 static void scan_partial_symbols (struct partial_die_info *,
1449                                   CORE_ADDR *, CORE_ADDR *,
1450                                   int, struct dwarf2_cu *);
1451
1452 static void add_partial_symbol (struct partial_die_info *,
1453                                 struct dwarf2_cu *);
1454
1455 static void add_partial_namespace (struct partial_die_info *pdi,
1456                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1457                                    int set_addrmap, struct dwarf2_cu *cu);
1458
1459 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1460                                 CORE_ADDR *highpc, int set_addrmap,
1461                                 struct dwarf2_cu *cu);
1462
1463 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1464                                      struct dwarf2_cu *cu);
1465
1466 static void add_partial_subprogram (struct partial_die_info *pdi,
1467                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1468                                     int need_pc, struct dwarf2_cu *cu);
1469
1470 static void dwarf2_read_symtab (struct partial_symtab *,
1471                                 struct objfile *);
1472
1473 static void psymtab_to_symtab_1 (struct partial_symtab *);
1474
1475 static abbrev_table_up abbrev_table_read_table
1476   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1477    sect_offset);
1478
1479 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1480
1481 static struct partial_die_info *load_partial_dies
1482   (const struct die_reader_specs *, const gdb_byte *, int);
1483
1484 /* A pair of partial_die_info and compilation unit.  */
1485 struct cu_partial_die_info
1486 {
1487   /* The compilation unit of the partial_die_info.  */
1488   struct dwarf2_cu *cu;
1489   /* A partial_die_info.  */
1490   struct partial_die_info *pdi;
1491
1492   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1493     : cu (cu),
1494       pdi (pdi)
1495   { /* Nothhing.  */ }
1496
1497 private:
1498   cu_partial_die_info () = delete;
1499 };
1500
1501 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1502                                                           struct dwarf2_cu *);
1503
1504 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1505                                        struct attribute *, struct attr_abbrev *,
1506                                        const gdb_byte *);
1507
1508 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1509
1510 static int read_1_signed_byte (bfd *, const gdb_byte *);
1511
1512 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1513
1514 /* Read the next three bytes (little-endian order) as an unsigned integer.  */
1515 static unsigned int read_3_bytes (bfd *, const gdb_byte *);
1516
1517 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1518
1519 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1520
1521 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1522                                unsigned int *);
1523
1524 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1525
1526 static LONGEST read_checked_initial_length_and_offset
1527   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1528    unsigned int *, unsigned int *);
1529
1530 static LONGEST read_offset (bfd *, const gdb_byte *,
1531                             const struct comp_unit_head *,
1532                             unsigned int *);
1533
1534 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1535
1536 static sect_offset read_abbrev_offset
1537   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1538    struct dwarf2_section_info *, sect_offset);
1539
1540 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1541
1542 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1543
1544 static const char *read_indirect_string
1545   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1546    const struct comp_unit_head *, unsigned int *);
1547
1548 static const char *read_indirect_line_string
1549   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1550    const struct comp_unit_head *, unsigned int *);
1551
1552 static const char *read_indirect_string_at_offset
1553   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1554    LONGEST str_offset);
1555
1556 static const char *read_indirect_string_from_dwz
1557   (struct objfile *objfile, struct dwz_file *, LONGEST);
1558
1559 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1560
1561 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1562                                               const gdb_byte *,
1563                                               unsigned int *);
1564
1565 static const char *read_str_index (const struct die_reader_specs *reader,
1566                                    ULONGEST str_index);
1567
1568 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1569
1570 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1571                                       struct dwarf2_cu *);
1572
1573 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1574                                                 unsigned int);
1575
1576 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1577                                        struct dwarf2_cu *cu);
1578
1579 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1580                                struct dwarf2_cu *cu);
1581
1582 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1583
1584 static struct die_info *die_specification (struct die_info *die,
1585                                            struct dwarf2_cu **);
1586
1587 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1588                                                 struct dwarf2_cu *cu);
1589
1590 static void dwarf_decode_lines (struct line_header *, const char *,
1591                                 struct dwarf2_cu *, struct partial_symtab *,
1592                                 CORE_ADDR, int decode_mapping);
1593
1594 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1595                                   const char *);
1596
1597 static struct symbol *new_symbol (struct die_info *, struct type *,
1598                                   struct dwarf2_cu *, struct symbol * = NULL);
1599
1600 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1601                                 struct dwarf2_cu *);
1602
1603 static void dwarf2_const_value_attr (const struct attribute *attr,
1604                                      struct type *type,
1605                                      const char *name,
1606                                      struct obstack *obstack,
1607                                      struct dwarf2_cu *cu, LONGEST *value,
1608                                      const gdb_byte **bytes,
1609                                      struct dwarf2_locexpr_baton **baton);
1610
1611 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1612
1613 static int need_gnat_info (struct dwarf2_cu *);
1614
1615 static struct type *die_descriptive_type (struct die_info *,
1616                                           struct dwarf2_cu *);
1617
1618 static void set_descriptive_type (struct type *, struct die_info *,
1619                                   struct dwarf2_cu *);
1620
1621 static struct type *die_containing_type (struct die_info *,
1622                                          struct dwarf2_cu *);
1623
1624 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1625                                      struct dwarf2_cu *);
1626
1627 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1628
1629 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1630
1631 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1632
1633 static char *typename_concat (struct obstack *obs, const char *prefix,
1634                               const char *suffix, int physname,
1635                               struct dwarf2_cu *cu);
1636
1637 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1638
1639 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1640
1641 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1642
1643 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1644
1645 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1646
1647 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1648
1649 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1650                                struct dwarf2_cu *, struct partial_symtab *);
1651
1652 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1653    values.  Keep the items ordered with increasing constraints compliance.  */
1654 enum pc_bounds_kind
1655 {
1656   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1657   PC_BOUNDS_NOT_PRESENT,
1658
1659   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1660      were present but they do not form a valid range of PC addresses.  */
1661   PC_BOUNDS_INVALID,
1662
1663   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1664   PC_BOUNDS_RANGES,
1665
1666   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1667   PC_BOUNDS_HIGH_LOW,
1668 };
1669
1670 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1671                                                  CORE_ADDR *, CORE_ADDR *,
1672                                                  struct dwarf2_cu *,
1673                                                  struct partial_symtab *);
1674
1675 static void get_scope_pc_bounds (struct die_info *,
1676                                  CORE_ADDR *, CORE_ADDR *,
1677                                  struct dwarf2_cu *);
1678
1679 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1680                                         CORE_ADDR, struct dwarf2_cu *);
1681
1682 static void dwarf2_add_field (struct field_info *, struct die_info *,
1683                               struct dwarf2_cu *);
1684
1685 static void dwarf2_attach_fields_to_type (struct field_info *,
1686                                           struct type *, struct dwarf2_cu *);
1687
1688 static void dwarf2_add_member_fn (struct field_info *,
1689                                   struct die_info *, struct type *,
1690                                   struct dwarf2_cu *);
1691
1692 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1693                                              struct type *,
1694                                              struct dwarf2_cu *);
1695
1696 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1697
1698 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1699
1700 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1701
1702 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1703
1704 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1705
1706 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1707
1708 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1709
1710 static struct type *read_module_type (struct die_info *die,
1711                                       struct dwarf2_cu *cu);
1712
1713 static const char *namespace_name (struct die_info *die,
1714                                    int *is_anonymous, struct dwarf2_cu *);
1715
1716 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1717
1718 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1719
1720 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1721                                                        struct dwarf2_cu *);
1722
1723 static struct die_info *read_die_and_siblings_1
1724   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1725    struct die_info *);
1726
1727 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1728                                                const gdb_byte *info_ptr,
1729                                                const gdb_byte **new_info_ptr,
1730                                                struct die_info *parent);
1731
1732 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1733                                         struct die_info **, const gdb_byte *,
1734                                         int *, int);
1735
1736 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1737                                       struct die_info **, const gdb_byte *,
1738                                       int *);
1739
1740 static void process_die (struct die_info *, struct dwarf2_cu *);
1741
1742 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1743                                              struct obstack *);
1744
1745 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1746
1747 static const char *dwarf2_full_name (const char *name,
1748                                      struct die_info *die,
1749                                      struct dwarf2_cu *cu);
1750
1751 static const char *dwarf2_physname (const char *name, struct die_info *die,
1752                                     struct dwarf2_cu *cu);
1753
1754 static struct die_info *dwarf2_extension (struct die_info *die,
1755                                           struct dwarf2_cu **);
1756
1757 static const char *dwarf_tag_name (unsigned int);
1758
1759 static const char *dwarf_attr_name (unsigned int);
1760
1761 static const char *dwarf_form_name (unsigned int);
1762
1763 static const char *dwarf_bool_name (unsigned int);
1764
1765 static const char *dwarf_type_encoding_name (unsigned int);
1766
1767 static struct die_info *sibling_die (struct die_info *);
1768
1769 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1770
1771 static void dump_die_for_error (struct die_info *);
1772
1773 static void dump_die_1 (struct ui_file *, int level, int max_level,
1774                         struct die_info *);
1775
1776 /*static*/ void dump_die (struct die_info *, int max_level);
1777
1778 static void store_in_ref_table (struct die_info *,
1779                                 struct dwarf2_cu *);
1780
1781 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1782
1783 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1784
1785 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1786                                                const struct attribute *,
1787                                                struct dwarf2_cu **);
1788
1789 static struct die_info *follow_die_ref (struct die_info *,
1790                                         const struct attribute *,
1791                                         struct dwarf2_cu **);
1792
1793 static struct die_info *follow_die_sig (struct die_info *,
1794                                         const struct attribute *,
1795                                         struct dwarf2_cu **);
1796
1797 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1798                                          struct dwarf2_cu *);
1799
1800 static struct type *get_DW_AT_signature_type (struct die_info *,
1801                                               const struct attribute *,
1802                                               struct dwarf2_cu *);
1803
1804 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1805
1806 static void read_signatured_type (struct signatured_type *);
1807
1808 static int attr_to_dynamic_prop (const struct attribute *attr,
1809                                  struct die_info *die, struct dwarf2_cu *cu,
1810                                  struct dynamic_prop *prop);
1811
1812 /* memory allocation interface */
1813
1814 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1815
1816 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1817
1818 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1819
1820 static int attr_form_is_block (const struct attribute *);
1821
1822 static int attr_form_is_section_offset (const struct attribute *);
1823
1824 static int attr_form_is_constant (const struct attribute *);
1825
1826 static int attr_form_is_ref (const struct attribute *);
1827
1828 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1829                                    struct dwarf2_loclist_baton *baton,
1830                                    const struct attribute *attr);
1831
1832 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1833                                          struct symbol *sym,
1834                                          struct dwarf2_cu *cu,
1835                                          int is_block);
1836
1837 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1838                                      const gdb_byte *info_ptr,
1839                                      struct abbrev_info *abbrev);
1840
1841 static hashval_t partial_die_hash (const void *item);
1842
1843 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1844
1845 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1846   (sect_offset sect_off, unsigned int offset_in_dwz,
1847    struct dwarf2_per_objfile *dwarf2_per_objfile);
1848
1849 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1850                                    struct die_info *comp_unit_die,
1851                                    enum language pretend_language);
1852
1853 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1854
1855 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1856
1857 static struct type *set_die_type (struct die_info *, struct type *,
1858                                   struct dwarf2_cu *);
1859
1860 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1861
1862 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1863
1864 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1865                                  enum language);
1866
1867 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1868                                     enum language);
1869
1870 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1871                                     enum language);
1872
1873 static void dwarf2_add_dependence (struct dwarf2_cu *,
1874                                    struct dwarf2_per_cu_data *);
1875
1876 static void dwarf2_mark (struct dwarf2_cu *);
1877
1878 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1879
1880 static struct type *get_die_type_at_offset (sect_offset,
1881                                             struct dwarf2_per_cu_data *);
1882
1883 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1884
1885 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1886                              enum language pretend_language);
1887
1888 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1889
1890 /* Class, the destructor of which frees all allocated queue entries.  This
1891    will only have work to do if an error was thrown while processing the
1892    dwarf.  If no error was thrown then the queue entries should have all
1893    been processed, and freed, as we went along.  */
1894
1895 class dwarf2_queue_guard
1896 {
1897 public:
1898   dwarf2_queue_guard () = default;
1899
1900   /* Free any entries remaining on the queue.  There should only be
1901      entries left if we hit an error while processing the dwarf.  */
1902   ~dwarf2_queue_guard ()
1903   {
1904     struct dwarf2_queue_item *item, *last;
1905
1906     item = dwarf2_queue;
1907     while (item)
1908       {
1909         /* Anything still marked queued is likely to be in an
1910            inconsistent state, so discard it.  */
1911         if (item->per_cu->queued)
1912           {
1913             if (item->per_cu->cu != NULL)
1914               free_one_cached_comp_unit (item->per_cu);
1915             item->per_cu->queued = 0;
1916           }
1917
1918         last = item;
1919         item = item->next;
1920         xfree (last);
1921       }
1922
1923     dwarf2_queue = dwarf2_queue_tail = NULL;
1924   }
1925 };
1926
1927 /* The return type of find_file_and_directory.  Note, the enclosed
1928    string pointers are only valid while this object is valid.  */
1929
1930 struct file_and_directory
1931 {
1932   /* The filename.  This is never NULL.  */
1933   const char *name;
1934
1935   /* The compilation directory.  NULL if not known.  If we needed to
1936      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1937      points directly to the DW_AT_comp_dir string attribute owned by
1938      the obstack that owns the DIE.  */
1939   const char *comp_dir;
1940
1941   /* If we needed to build a new string for comp_dir, this is what
1942      owns the storage.  */
1943   std::string comp_dir_storage;
1944 };
1945
1946 static file_and_directory find_file_and_directory (struct die_info *die,
1947                                                    struct dwarf2_cu *cu);
1948
1949 static char *file_full_name (int file, struct line_header *lh,
1950                              const char *comp_dir);
1951
1952 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1953 enum class rcuh_kind { COMPILE, TYPE };
1954
1955 static const gdb_byte *read_and_check_comp_unit_head
1956   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1957    struct comp_unit_head *header,
1958    struct dwarf2_section_info *section,
1959    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1960    rcuh_kind section_kind);
1961
1962 static void init_cutu_and_read_dies
1963   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1964    int use_existing_cu, int keep, bool skip_partial,
1965    die_reader_func_ftype *die_reader_func, void *data);
1966
1967 static void init_cutu_and_read_dies_simple
1968   (struct dwarf2_per_cu_data *this_cu,
1969    die_reader_func_ftype *die_reader_func, void *data);
1970
1971 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1972
1973 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1974
1975 static struct dwo_unit *lookup_dwo_unit_in_dwp
1976   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1977    struct dwp_file *dwp_file, const char *comp_dir,
1978    ULONGEST signature, int is_debug_types);
1979
1980 static struct dwp_file *get_dwp_file
1981   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1982
1983 static struct dwo_unit *lookup_dwo_comp_unit
1984   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1985
1986 static struct dwo_unit *lookup_dwo_type_unit
1987   (struct signatured_type *, const char *, const char *);
1988
1989 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1990
1991 static void free_dwo_file (struct dwo_file *);
1992
1993 /* A unique_ptr helper to free a dwo_file.  */
1994
1995 struct dwo_file_deleter
1996 {
1997   void operator() (struct dwo_file *df) const
1998   {
1999     free_dwo_file (df);
2000   }
2001 };
2002
2003 /* A unique pointer to a dwo_file.  */
2004
2005 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
2006
2007 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2008
2009 static void check_producer (struct dwarf2_cu *cu);
2010
2011 static void free_line_header_voidp (void *arg);
2012 \f
2013 /* Various complaints about symbol reading that don't abort the process.  */
2014
2015 static void
2016 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2017 {
2018   complaint (_("statement list doesn't fit in .debug_line section"));
2019 }
2020
2021 static void
2022 dwarf2_debug_line_missing_file_complaint (void)
2023 {
2024   complaint (_(".debug_line section has line data without a file"));
2025 }
2026
2027 static void
2028 dwarf2_debug_line_missing_end_sequence_complaint (void)
2029 {
2030   complaint (_(".debug_line section has line "
2031                "program sequence without an end"));
2032 }
2033
2034 static void
2035 dwarf2_complex_location_expr_complaint (void)
2036 {
2037   complaint (_("location expression too complex"));
2038 }
2039
2040 static void
2041 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2042                                               int arg3)
2043 {
2044   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2045              arg1, arg2, arg3);
2046 }
2047
2048 static void
2049 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2050 {
2051   complaint (_("debug info runs off end of %s section"
2052                " [in module %s]"),
2053              get_section_name (section),
2054              get_section_file_name (section));
2055 }
2056
2057 static void
2058 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2059 {
2060   complaint (_("macro debug info contains a "
2061                "malformed macro definition:\n`%s'"),
2062              arg1);
2063 }
2064
2065 static void
2066 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2067 {
2068   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2069              arg1, arg2);
2070 }
2071
2072 /* Hash function for line_header_hash.  */
2073
2074 static hashval_t
2075 line_header_hash (const struct line_header *ofs)
2076 {
2077   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2078 }
2079
2080 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2081
2082 static hashval_t
2083 line_header_hash_voidp (const void *item)
2084 {
2085   const struct line_header *ofs = (const struct line_header *) item;
2086
2087   return line_header_hash (ofs);
2088 }
2089
2090 /* Equality function for line_header_hash.  */
2091
2092 static int
2093 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2094 {
2095   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2096   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2097
2098   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2099           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2100 }
2101
2102 \f
2103
2104 /* Read the given attribute value as an address, taking the attribute's
2105    form into account.  */
2106
2107 static CORE_ADDR
2108 attr_value_as_address (struct attribute *attr)
2109 {
2110   CORE_ADDR addr;
2111
2112   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_addrx
2113       && attr->form != DW_FORM_GNU_addr_index)
2114     {
2115       /* Aside from a few clearly defined exceptions, attributes that
2116          contain an address must always be in DW_FORM_addr form.
2117          Unfortunately, some compilers happen to be violating this
2118          requirement by encoding addresses using other forms, such
2119          as DW_FORM_data4 for example.  For those broken compilers,
2120          we try to do our best, without any guarantee of success,
2121          to interpret the address correctly.  It would also be nice
2122          to generate a complaint, but that would require us to maintain
2123          a list of legitimate cases where a non-address form is allowed,
2124          as well as update callers to pass in at least the CU's DWARF
2125          version.  This is more overhead than what we're willing to
2126          expand for a pretty rare case.  */
2127       addr = DW_UNSND (attr);
2128     }
2129   else
2130     addr = DW_ADDR (attr);
2131
2132   return addr;
2133 }
2134
2135 /* See declaration.  */
2136
2137 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2138                                         const dwarf2_debug_sections *names)
2139   : objfile (objfile_)
2140 {
2141   if (names == NULL)
2142     names = &dwarf2_elf_names;
2143
2144   bfd *obfd = objfile->obfd;
2145
2146   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2147     locate_sections (obfd, sec, *names);
2148 }
2149
2150 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2151
2152 dwarf2_per_objfile::~dwarf2_per_objfile ()
2153 {
2154   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2155   free_cached_comp_units ();
2156
2157   if (quick_file_names_table)
2158     htab_delete (quick_file_names_table);
2159
2160   if (line_header_hash)
2161     htab_delete (line_header_hash);
2162
2163   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2164     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2165
2166   for (signatured_type *sig_type : all_type_units)
2167     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2168
2169   VEC_free (dwarf2_section_info_def, types);
2170
2171   if (dwo_files != NULL)
2172     free_dwo_files (dwo_files, objfile);
2173
2174   /* Everything else should be on the objfile obstack.  */
2175 }
2176
2177 /* See declaration.  */
2178
2179 void
2180 dwarf2_per_objfile::free_cached_comp_units ()
2181 {
2182   dwarf2_per_cu_data *per_cu = read_in_chain;
2183   dwarf2_per_cu_data **last_chain = &read_in_chain;
2184   while (per_cu != NULL)
2185     {
2186       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2187
2188       delete per_cu->cu;
2189       *last_chain = next_cu;
2190       per_cu = next_cu;
2191     }
2192 }
2193
2194 /* A helper class that calls free_cached_comp_units on
2195    destruction.  */
2196
2197 class free_cached_comp_units
2198 {
2199 public:
2200
2201   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2202     : m_per_objfile (per_objfile)
2203   {
2204   }
2205
2206   ~free_cached_comp_units ()
2207   {
2208     m_per_objfile->free_cached_comp_units ();
2209   }
2210
2211   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2212
2213 private:
2214
2215   dwarf2_per_objfile *m_per_objfile;
2216 };
2217
2218 /* Try to locate the sections we need for DWARF 2 debugging
2219    information and return true if we have enough to do something.
2220    NAMES points to the dwarf2 section names, or is NULL if the standard
2221    ELF names are used.  */
2222
2223 int
2224 dwarf2_has_info (struct objfile *objfile,
2225                  const struct dwarf2_debug_sections *names)
2226 {
2227   if (objfile->flags & OBJF_READNEVER)
2228     return 0;
2229
2230   struct dwarf2_per_objfile *dwarf2_per_objfile
2231     = get_dwarf2_per_objfile (objfile);
2232
2233   if (dwarf2_per_objfile == NULL)
2234     dwarf2_per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile,
2235                                                           names);
2236
2237   return (!dwarf2_per_objfile->info.is_virtual
2238           && dwarf2_per_objfile->info.s.section != NULL
2239           && !dwarf2_per_objfile->abbrev.is_virtual
2240           && dwarf2_per_objfile->abbrev.s.section != NULL);
2241 }
2242
2243 /* Return the containing section of virtual section SECTION.  */
2244
2245 static struct dwarf2_section_info *
2246 get_containing_section (const struct dwarf2_section_info *section)
2247 {
2248   gdb_assert (section->is_virtual);
2249   return section->s.containing_section;
2250 }
2251
2252 /* Return the bfd owner of SECTION.  */
2253
2254 static struct bfd *
2255 get_section_bfd_owner (const struct dwarf2_section_info *section)
2256 {
2257   if (section->is_virtual)
2258     {
2259       section = get_containing_section (section);
2260       gdb_assert (!section->is_virtual);
2261     }
2262   return section->s.section->owner;
2263 }
2264
2265 /* Return the bfd section of SECTION.
2266    Returns NULL if the section is not present.  */
2267
2268 static asection *
2269 get_section_bfd_section (const struct dwarf2_section_info *section)
2270 {
2271   if (section->is_virtual)
2272     {
2273       section = get_containing_section (section);
2274       gdb_assert (!section->is_virtual);
2275     }
2276   return section->s.section;
2277 }
2278
2279 /* Return the name of SECTION.  */
2280
2281 static const char *
2282 get_section_name (const struct dwarf2_section_info *section)
2283 {
2284   asection *sectp = get_section_bfd_section (section);
2285
2286   gdb_assert (sectp != NULL);
2287   return bfd_section_name (get_section_bfd_owner (section), sectp);
2288 }
2289
2290 /* Return the name of the file SECTION is in.  */
2291
2292 static const char *
2293 get_section_file_name (const struct dwarf2_section_info *section)
2294 {
2295   bfd *abfd = get_section_bfd_owner (section);
2296
2297   return bfd_get_filename (abfd);
2298 }
2299
2300 /* Return the id of SECTION.
2301    Returns 0 if SECTION doesn't exist.  */
2302
2303 static int
2304 get_section_id (const struct dwarf2_section_info *section)
2305 {
2306   asection *sectp = get_section_bfd_section (section);
2307
2308   if (sectp == NULL)
2309     return 0;
2310   return sectp->id;
2311 }
2312
2313 /* Return the flags of SECTION.
2314    SECTION (or containing section if this is a virtual section) must exist.  */
2315
2316 static int
2317 get_section_flags (const struct dwarf2_section_info *section)
2318 {
2319   asection *sectp = get_section_bfd_section (section);
2320
2321   gdb_assert (sectp != NULL);
2322   return bfd_get_section_flags (sectp->owner, sectp);
2323 }
2324
2325 /* When loading sections, we look either for uncompressed section or for
2326    compressed section names.  */
2327
2328 static int
2329 section_is_p (const char *section_name,
2330               const struct dwarf2_section_names *names)
2331 {
2332   if (names->normal != NULL
2333       && strcmp (section_name, names->normal) == 0)
2334     return 1;
2335   if (names->compressed != NULL
2336       && strcmp (section_name, names->compressed) == 0)
2337     return 1;
2338   return 0;
2339 }
2340
2341 /* See declaration.  */
2342
2343 void
2344 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2345                                      const dwarf2_debug_sections &names)
2346 {
2347   flagword aflag = bfd_get_section_flags (abfd, sectp);
2348
2349   if ((aflag & SEC_HAS_CONTENTS) == 0)
2350     {
2351     }
2352   else if (section_is_p (sectp->name, &names.info))
2353     {
2354       this->info.s.section = sectp;
2355       this->info.size = bfd_get_section_size (sectp);
2356     }
2357   else if (section_is_p (sectp->name, &names.abbrev))
2358     {
2359       this->abbrev.s.section = sectp;
2360       this->abbrev.size = bfd_get_section_size (sectp);
2361     }
2362   else if (section_is_p (sectp->name, &names.line))
2363     {
2364       this->line.s.section = sectp;
2365       this->line.size = bfd_get_section_size (sectp);
2366     }
2367   else if (section_is_p (sectp->name, &names.loc))
2368     {
2369       this->loc.s.section = sectp;
2370       this->loc.size = bfd_get_section_size (sectp);
2371     }
2372   else if (section_is_p (sectp->name, &names.loclists))
2373     {
2374       this->loclists.s.section = sectp;
2375       this->loclists.size = bfd_get_section_size (sectp);
2376     }
2377   else if (section_is_p (sectp->name, &names.macinfo))
2378     {
2379       this->macinfo.s.section = sectp;
2380       this->macinfo.size = bfd_get_section_size (sectp);
2381     }
2382   else if (section_is_p (sectp->name, &names.macro))
2383     {
2384       this->macro.s.section = sectp;
2385       this->macro.size = bfd_get_section_size (sectp);
2386     }
2387   else if (section_is_p (sectp->name, &names.str))
2388     {
2389       this->str.s.section = sectp;
2390       this->str.size = bfd_get_section_size (sectp);
2391     }
2392   else if (section_is_p (sectp->name, &names.line_str))
2393     {
2394       this->line_str.s.section = sectp;
2395       this->line_str.size = bfd_get_section_size (sectp);
2396     }
2397   else if (section_is_p (sectp->name, &names.addr))
2398     {
2399       this->addr.s.section = sectp;
2400       this->addr.size = bfd_get_section_size (sectp);
2401     }
2402   else if (section_is_p (sectp->name, &names.frame))
2403     {
2404       this->frame.s.section = sectp;
2405       this->frame.size = bfd_get_section_size (sectp);
2406     }
2407   else if (section_is_p (sectp->name, &names.eh_frame))
2408     {
2409       this->eh_frame.s.section = sectp;
2410       this->eh_frame.size = bfd_get_section_size (sectp);
2411     }
2412   else if (section_is_p (sectp->name, &names.ranges))
2413     {
2414       this->ranges.s.section = sectp;
2415       this->ranges.size = bfd_get_section_size (sectp);
2416     }
2417   else if (section_is_p (sectp->name, &names.rnglists))
2418     {
2419       this->rnglists.s.section = sectp;
2420       this->rnglists.size = bfd_get_section_size (sectp);
2421     }
2422   else if (section_is_p (sectp->name, &names.types))
2423     {
2424       struct dwarf2_section_info type_section;
2425
2426       memset (&type_section, 0, sizeof (type_section));
2427       type_section.s.section = sectp;
2428       type_section.size = bfd_get_section_size (sectp);
2429
2430       VEC_safe_push (dwarf2_section_info_def, this->types,
2431                      &type_section);
2432     }
2433   else if (section_is_p (sectp->name, &names.gdb_index))
2434     {
2435       this->gdb_index.s.section = sectp;
2436       this->gdb_index.size = bfd_get_section_size (sectp);
2437     }
2438   else if (section_is_p (sectp->name, &names.debug_names))
2439     {
2440       this->debug_names.s.section = sectp;
2441       this->debug_names.size = bfd_get_section_size (sectp);
2442     }
2443   else if (section_is_p (sectp->name, &names.debug_aranges))
2444     {
2445       this->debug_aranges.s.section = sectp;
2446       this->debug_aranges.size = bfd_get_section_size (sectp);
2447     }
2448
2449   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2450       && bfd_section_vma (abfd, sectp) == 0)
2451     this->has_section_at_zero = true;
2452 }
2453
2454 /* A helper function that decides whether a section is empty,
2455    or not present.  */
2456
2457 static int
2458 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2459 {
2460   if (section->is_virtual)
2461     return section->size == 0;
2462   return section->s.section == NULL || section->size == 0;
2463 }
2464
2465 /* See dwarf2read.h.  */
2466
2467 void
2468 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2469 {
2470   asection *sectp;
2471   bfd *abfd;
2472   gdb_byte *buf, *retbuf;
2473
2474   if (info->readin)
2475     return;
2476   info->buffer = NULL;
2477   info->readin = true;
2478
2479   if (dwarf2_section_empty_p (info))
2480     return;
2481
2482   sectp = get_section_bfd_section (info);
2483
2484   /* If this is a virtual section we need to read in the real one first.  */
2485   if (info->is_virtual)
2486     {
2487       struct dwarf2_section_info *containing_section =
2488         get_containing_section (info);
2489
2490       gdb_assert (sectp != NULL);
2491       if ((sectp->flags & SEC_RELOC) != 0)
2492         {
2493           error (_("Dwarf Error: DWP format V2 with relocations is not"
2494                    " supported in section %s [in module %s]"),
2495                  get_section_name (info), get_section_file_name (info));
2496         }
2497       dwarf2_read_section (objfile, containing_section);
2498       /* Other code should have already caught virtual sections that don't
2499          fit.  */
2500       gdb_assert (info->virtual_offset + info->size
2501                   <= containing_section->size);
2502       /* If the real section is empty or there was a problem reading the
2503          section we shouldn't get here.  */
2504       gdb_assert (containing_section->buffer != NULL);
2505       info->buffer = containing_section->buffer + info->virtual_offset;
2506       return;
2507     }
2508
2509   /* If the section has relocations, we must read it ourselves.
2510      Otherwise we attach it to the BFD.  */
2511   if ((sectp->flags & SEC_RELOC) == 0)
2512     {
2513       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2514       return;
2515     }
2516
2517   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2518   info->buffer = buf;
2519
2520   /* When debugging .o files, we may need to apply relocations; see
2521      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2522      We never compress sections in .o files, so we only need to
2523      try this when the section is not compressed.  */
2524   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2525   if (retbuf != NULL)
2526     {
2527       info->buffer = retbuf;
2528       return;
2529     }
2530
2531   abfd = get_section_bfd_owner (info);
2532   gdb_assert (abfd != NULL);
2533
2534   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2535       || bfd_bread (buf, info->size, abfd) != info->size)
2536     {
2537       error (_("Dwarf Error: Can't read DWARF data"
2538                " in section %s [in module %s]"),
2539              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2540     }
2541 }
2542
2543 /* A helper function that returns the size of a section in a safe way.
2544    If you are positive that the section has been read before using the
2545    size, then it is safe to refer to the dwarf2_section_info object's
2546    "size" field directly.  In other cases, you must call this
2547    function, because for compressed sections the size field is not set
2548    correctly until the section has been read.  */
2549
2550 static bfd_size_type
2551 dwarf2_section_size (struct objfile *objfile,
2552                      struct dwarf2_section_info *info)
2553 {
2554   if (!info->readin)
2555     dwarf2_read_section (objfile, info);
2556   return info->size;
2557 }
2558
2559 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2560    SECTION_NAME.  */
2561
2562 void
2563 dwarf2_get_section_info (struct objfile *objfile,
2564                          enum dwarf2_section_enum sect,
2565                          asection **sectp, const gdb_byte **bufp,
2566                          bfd_size_type *sizep)
2567 {
2568   struct dwarf2_per_objfile *data = dwarf2_objfile_data_key.get (objfile);
2569   struct dwarf2_section_info *info;
2570
2571   /* We may see an objfile without any DWARF, in which case we just
2572      return nothing.  */
2573   if (data == NULL)
2574     {
2575       *sectp = NULL;
2576       *bufp = NULL;
2577       *sizep = 0;
2578       return;
2579     }
2580   switch (sect)
2581     {
2582     case DWARF2_DEBUG_FRAME:
2583       info = &data->frame;
2584       break;
2585     case DWARF2_EH_FRAME:
2586       info = &data->eh_frame;
2587       break;
2588     default:
2589       gdb_assert_not_reached ("unexpected section");
2590     }
2591
2592   dwarf2_read_section (objfile, info);
2593
2594   *sectp = get_section_bfd_section (info);
2595   *bufp = info->buffer;
2596   *sizep = info->size;
2597 }
2598
2599 /* A helper function to find the sections for a .dwz file.  */
2600
2601 static void
2602 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2603 {
2604   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2605
2606   /* Note that we only support the standard ELF names, because .dwz
2607      is ELF-only (at the time of writing).  */
2608   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2609     {
2610       dwz_file->abbrev.s.section = sectp;
2611       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2612     }
2613   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2614     {
2615       dwz_file->info.s.section = sectp;
2616       dwz_file->info.size = bfd_get_section_size (sectp);
2617     }
2618   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2619     {
2620       dwz_file->str.s.section = sectp;
2621       dwz_file->str.size = bfd_get_section_size (sectp);
2622     }
2623   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2624     {
2625       dwz_file->line.s.section = sectp;
2626       dwz_file->line.size = bfd_get_section_size (sectp);
2627     }
2628   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2629     {
2630       dwz_file->macro.s.section = sectp;
2631       dwz_file->macro.size = bfd_get_section_size (sectp);
2632     }
2633   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2634     {
2635       dwz_file->gdb_index.s.section = sectp;
2636       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2637     }
2638   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2639     {
2640       dwz_file->debug_names.s.section = sectp;
2641       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2642     }
2643 }
2644
2645 /* See dwarf2read.h.  */
2646
2647 struct dwz_file *
2648 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2649 {
2650   const char *filename;
2651   bfd_size_type buildid_len_arg;
2652   size_t buildid_len;
2653   bfd_byte *buildid;
2654
2655   if (dwarf2_per_objfile->dwz_file != NULL)
2656     return dwarf2_per_objfile->dwz_file.get ();
2657
2658   bfd_set_error (bfd_error_no_error);
2659   gdb::unique_xmalloc_ptr<char> data
2660     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2661                                   &buildid_len_arg, &buildid));
2662   if (data == NULL)
2663     {
2664       if (bfd_get_error () == bfd_error_no_error)
2665         return NULL;
2666       error (_("could not read '.gnu_debugaltlink' section: %s"),
2667              bfd_errmsg (bfd_get_error ()));
2668     }
2669
2670   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2671
2672   buildid_len = (size_t) buildid_len_arg;
2673
2674   filename = data.get ();
2675
2676   std::string abs_storage;
2677   if (!IS_ABSOLUTE_PATH (filename))
2678     {
2679       gdb::unique_xmalloc_ptr<char> abs
2680         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2681
2682       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2683       filename = abs_storage.c_str ();
2684     }
2685
2686   /* First try the file name given in the section.  If that doesn't
2687      work, try to use the build-id instead.  */
2688   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2689   if (dwz_bfd != NULL)
2690     {
2691       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2692         dwz_bfd.reset (nullptr);
2693     }
2694
2695   if (dwz_bfd == NULL)
2696     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2697
2698   if (dwz_bfd == NULL)
2699     error (_("could not find '.gnu_debugaltlink' file for %s"),
2700            objfile_name (dwarf2_per_objfile->objfile));
2701
2702   std::unique_ptr<struct dwz_file> result
2703     (new struct dwz_file (std::move (dwz_bfd)));
2704
2705   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2706                          result.get ());
2707
2708   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2709                             result->dwz_bfd.get ());
2710   dwarf2_per_objfile->dwz_file = std::move (result);
2711   return dwarf2_per_objfile->dwz_file.get ();
2712 }
2713 \f
2714 /* DWARF quick_symbols_functions support.  */
2715
2716 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2717    unique line tables, so we maintain a separate table of all .debug_line
2718    derived entries to support the sharing.
2719    All the quick functions need is the list of file names.  We discard the
2720    line_header when we're done and don't need to record it here.  */
2721 struct quick_file_names
2722 {
2723   /* The data used to construct the hash key.  */
2724   struct stmt_list_hash hash;
2725
2726   /* The number of entries in file_names, real_names.  */
2727   unsigned int num_file_names;
2728
2729   /* The file names from the line table, after being run through
2730      file_full_name.  */
2731   const char **file_names;
2732
2733   /* The file names from the line table after being run through
2734      gdb_realpath.  These are computed lazily.  */
2735   const char **real_names;
2736 };
2737
2738 /* When using the index (and thus not using psymtabs), each CU has an
2739    object of this type.  This is used to hold information needed by
2740    the various "quick" methods.  */
2741 struct dwarf2_per_cu_quick_data
2742 {
2743   /* The file table.  This can be NULL if there was no file table
2744      or it's currently not read in.
2745      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2746   struct quick_file_names *file_names;
2747
2748   /* The corresponding symbol table.  This is NULL if symbols for this
2749      CU have not yet been read.  */
2750   struct compunit_symtab *compunit_symtab;
2751
2752   /* A temporary mark bit used when iterating over all CUs in
2753      expand_symtabs_matching.  */
2754   unsigned int mark : 1;
2755
2756   /* True if we've tried to read the file table and found there isn't one.
2757      There will be no point in trying to read it again next time.  */
2758   unsigned int no_file_data : 1;
2759 };
2760
2761 /* Utility hash function for a stmt_list_hash.  */
2762
2763 static hashval_t
2764 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2765 {
2766   hashval_t v = 0;
2767
2768   if (stmt_list_hash->dwo_unit != NULL)
2769     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2770   v += to_underlying (stmt_list_hash->line_sect_off);
2771   return v;
2772 }
2773
2774 /* Utility equality function for a stmt_list_hash.  */
2775
2776 static int
2777 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2778                     const struct stmt_list_hash *rhs)
2779 {
2780   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2781     return 0;
2782   if (lhs->dwo_unit != NULL
2783       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2784     return 0;
2785
2786   return lhs->line_sect_off == rhs->line_sect_off;
2787 }
2788
2789 /* Hash function for a quick_file_names.  */
2790
2791 static hashval_t
2792 hash_file_name_entry (const void *e)
2793 {
2794   const struct quick_file_names *file_data
2795     = (const struct quick_file_names *) e;
2796
2797   return hash_stmt_list_entry (&file_data->hash);
2798 }
2799
2800 /* Equality function for a quick_file_names.  */
2801
2802 static int
2803 eq_file_name_entry (const void *a, const void *b)
2804 {
2805   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2806   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2807
2808   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2809 }
2810
2811 /* Delete function for a quick_file_names.  */
2812
2813 static void
2814 delete_file_name_entry (void *e)
2815 {
2816   struct quick_file_names *file_data = (struct quick_file_names *) e;
2817   int i;
2818
2819   for (i = 0; i < file_data->num_file_names; ++i)
2820     {
2821       xfree ((void*) file_data->file_names[i]);
2822       if (file_data->real_names)
2823         xfree ((void*) file_data->real_names[i]);
2824     }
2825
2826   /* The space for the struct itself lives on objfile_obstack,
2827      so we don't free it here.  */
2828 }
2829
2830 /* Create a quick_file_names hash table.  */
2831
2832 static htab_t
2833 create_quick_file_names_table (unsigned int nr_initial_entries)
2834 {
2835   return htab_create_alloc (nr_initial_entries,
2836                             hash_file_name_entry, eq_file_name_entry,
2837                             delete_file_name_entry, xcalloc, xfree);
2838 }
2839
2840 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2841    have to be created afterwards.  You should call age_cached_comp_units after
2842    processing PER_CU->CU.  dw2_setup must have been already called.  */
2843
2844 static void
2845 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2846 {
2847   if (per_cu->is_debug_types)
2848     load_full_type_unit (per_cu);
2849   else
2850     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2851
2852   if (per_cu->cu == NULL)
2853     return;  /* Dummy CU.  */
2854
2855   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2856 }
2857
2858 /* Read in the symbols for PER_CU.  */
2859
2860 static void
2861 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2862 {
2863   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2864
2865   /* Skip type_unit_groups, reading the type units they contain
2866      is handled elsewhere.  */
2867   if (IS_TYPE_UNIT_GROUP (per_cu))
2868     return;
2869
2870   /* The destructor of dwarf2_queue_guard frees any entries left on
2871      the queue.  After this point we're guaranteed to leave this function
2872      with the dwarf queue empty.  */
2873   dwarf2_queue_guard q_guard;
2874
2875   if (dwarf2_per_objfile->using_index
2876       ? per_cu->v.quick->compunit_symtab == NULL
2877       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2878     {
2879       queue_comp_unit (per_cu, language_minimal);
2880       load_cu (per_cu, skip_partial);
2881
2882       /* If we just loaded a CU from a DWO, and we're working with an index
2883          that may badly handle TUs, load all the TUs in that DWO as well.
2884          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2885       if (!per_cu->is_debug_types
2886           && per_cu->cu != NULL
2887           && per_cu->cu->dwo_unit != NULL
2888           && dwarf2_per_objfile->index_table != NULL
2889           && dwarf2_per_objfile->index_table->version <= 7
2890           /* DWP files aren't supported yet.  */
2891           && get_dwp_file (dwarf2_per_objfile) == NULL)
2892         queue_and_load_all_dwo_tus (per_cu);
2893     }
2894
2895   process_queue (dwarf2_per_objfile);
2896
2897   /* Age the cache, releasing compilation units that have not
2898      been used recently.  */
2899   age_cached_comp_units (dwarf2_per_objfile);
2900 }
2901
2902 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2903    the objfile from which this CU came.  Returns the resulting symbol
2904    table.  */
2905
2906 static struct compunit_symtab *
2907 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2908 {
2909   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2910
2911   gdb_assert (dwarf2_per_objfile->using_index);
2912   if (!per_cu->v.quick->compunit_symtab)
2913     {
2914       free_cached_comp_units freer (dwarf2_per_objfile);
2915       scoped_restore decrementer = increment_reading_symtab ();
2916       dw2_do_instantiate_symtab (per_cu, skip_partial);
2917       process_cu_includes (dwarf2_per_objfile);
2918     }
2919
2920   return per_cu->v.quick->compunit_symtab;
2921 }
2922
2923 /* See declaration.  */
2924
2925 dwarf2_per_cu_data *
2926 dwarf2_per_objfile::get_cutu (int index)
2927 {
2928   if (index >= this->all_comp_units.size ())
2929     {
2930       index -= this->all_comp_units.size ();
2931       gdb_assert (index < this->all_type_units.size ());
2932       return &this->all_type_units[index]->per_cu;
2933     }
2934
2935   return this->all_comp_units[index];
2936 }
2937
2938 /* See declaration.  */
2939
2940 dwarf2_per_cu_data *
2941 dwarf2_per_objfile::get_cu (int index)
2942 {
2943   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2944
2945   return this->all_comp_units[index];
2946 }
2947
2948 /* See declaration.  */
2949
2950 signatured_type *
2951 dwarf2_per_objfile::get_tu (int index)
2952 {
2953   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2954
2955   return this->all_type_units[index];
2956 }
2957
2958 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2959    objfile_obstack, and constructed with the specified field
2960    values.  */
2961
2962 static dwarf2_per_cu_data *
2963 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2964                           struct dwarf2_section_info *section,
2965                           int is_dwz,
2966                           sect_offset sect_off, ULONGEST length)
2967 {
2968   struct objfile *objfile = dwarf2_per_objfile->objfile;
2969   dwarf2_per_cu_data *the_cu
2970     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2971                      struct dwarf2_per_cu_data);
2972   the_cu->sect_off = sect_off;
2973   the_cu->length = length;
2974   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2975   the_cu->section = section;
2976   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2977                                    struct dwarf2_per_cu_quick_data);
2978   the_cu->is_dwz = is_dwz;
2979   return the_cu;
2980 }
2981
2982 /* A helper for create_cus_from_index that handles a given list of
2983    CUs.  */
2984
2985 static void
2986 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2987                             const gdb_byte *cu_list, offset_type n_elements,
2988                             struct dwarf2_section_info *section,
2989                             int is_dwz)
2990 {
2991   for (offset_type i = 0; i < n_elements; i += 2)
2992     {
2993       gdb_static_assert (sizeof (ULONGEST) >= 8);
2994
2995       sect_offset sect_off
2996         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2997       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2998       cu_list += 2 * 8;
2999
3000       dwarf2_per_cu_data *per_cu
3001         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3002                                      sect_off, length);
3003       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
3004     }
3005 }
3006
3007 /* Read the CU list from the mapped index, and use it to create all
3008    the CU objects for this objfile.  */
3009
3010 static void
3011 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3012                        const gdb_byte *cu_list, offset_type cu_list_elements,
3013                        const gdb_byte *dwz_list, offset_type dwz_elements)
3014 {
3015   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3016   dwarf2_per_objfile->all_comp_units.reserve
3017     ((cu_list_elements + dwz_elements) / 2);
3018
3019   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3020                               &dwarf2_per_objfile->info, 0);
3021
3022   if (dwz_elements == 0)
3023     return;
3024
3025   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3026   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3027                               &dwz->info, 1);
3028 }
3029
3030 /* Create the signatured type hash table from the index.  */
3031
3032 static void
3033 create_signatured_type_table_from_index
3034   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3035    struct dwarf2_section_info *section,
3036    const gdb_byte *bytes,
3037    offset_type elements)
3038 {
3039   struct objfile *objfile = dwarf2_per_objfile->objfile;
3040
3041   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3042   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3043
3044   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3045
3046   for (offset_type i = 0; i < elements; i += 3)
3047     {
3048       struct signatured_type *sig_type;
3049       ULONGEST signature;
3050       void **slot;
3051       cu_offset type_offset_in_tu;
3052
3053       gdb_static_assert (sizeof (ULONGEST) >= 8);
3054       sect_offset sect_off
3055         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3056       type_offset_in_tu
3057         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3058                                                 BFD_ENDIAN_LITTLE);
3059       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3060       bytes += 3 * 8;
3061
3062       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3063                                  struct signatured_type);
3064       sig_type->signature = signature;
3065       sig_type->type_offset_in_tu = type_offset_in_tu;
3066       sig_type->per_cu.is_debug_types = 1;
3067       sig_type->per_cu.section = section;
3068       sig_type->per_cu.sect_off = sect_off;
3069       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3070       sig_type->per_cu.v.quick
3071         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3072                           struct dwarf2_per_cu_quick_data);
3073
3074       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3075       *slot = sig_type;
3076
3077       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3078     }
3079
3080   dwarf2_per_objfile->signatured_types = sig_types_hash;
3081 }
3082
3083 /* Create the signatured type hash table from .debug_names.  */
3084
3085 static void
3086 create_signatured_type_table_from_debug_names
3087   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3088    const mapped_debug_names &map,
3089    struct dwarf2_section_info *section,
3090    struct dwarf2_section_info *abbrev_section)
3091 {
3092   struct objfile *objfile = dwarf2_per_objfile->objfile;
3093
3094   dwarf2_read_section (objfile, section);
3095   dwarf2_read_section (objfile, abbrev_section);
3096
3097   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3098   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3099
3100   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3101
3102   for (uint32_t i = 0; i < map.tu_count; ++i)
3103     {
3104       struct signatured_type *sig_type;
3105       void **slot;
3106
3107       sect_offset sect_off
3108         = (sect_offset) (extract_unsigned_integer
3109                          (map.tu_table_reordered + i * map.offset_size,
3110                           map.offset_size,
3111                           map.dwarf5_byte_order));
3112
3113       comp_unit_head cu_header;
3114       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3115                                      abbrev_section,
3116                                      section->buffer + to_underlying (sect_off),
3117                                      rcuh_kind::TYPE);
3118
3119       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3120                                  struct signatured_type);
3121       sig_type->signature = cu_header.signature;
3122       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3123       sig_type->per_cu.is_debug_types = 1;
3124       sig_type->per_cu.section = section;
3125       sig_type->per_cu.sect_off = sect_off;
3126       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3127       sig_type->per_cu.v.quick
3128         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3129                           struct dwarf2_per_cu_quick_data);
3130
3131       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3132       *slot = sig_type;
3133
3134       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3135     }
3136
3137   dwarf2_per_objfile->signatured_types = sig_types_hash;
3138 }
3139
3140 /* Read the address map data from the mapped index, and use it to
3141    populate the objfile's psymtabs_addrmap.  */
3142
3143 static void
3144 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3145                            struct mapped_index *index)
3146 {
3147   struct objfile *objfile = dwarf2_per_objfile->objfile;
3148   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3149   const gdb_byte *iter, *end;
3150   struct addrmap *mutable_map;
3151   CORE_ADDR baseaddr;
3152
3153   auto_obstack temp_obstack;
3154
3155   mutable_map = addrmap_create_mutable (&temp_obstack);
3156
3157   iter = index->address_table.data ();
3158   end = iter + index->address_table.size ();
3159
3160   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3161
3162   while (iter < end)
3163     {
3164       ULONGEST hi, lo, cu_index;
3165       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3166       iter += 8;
3167       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3168       iter += 8;
3169       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3170       iter += 4;
3171
3172       if (lo > hi)
3173         {
3174           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3175                      hex_string (lo), hex_string (hi));
3176           continue;
3177         }
3178
3179       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3180         {
3181           complaint (_(".gdb_index address table has invalid CU number %u"),
3182                      (unsigned) cu_index);
3183           continue;
3184         }
3185
3186       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
3187       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
3188       addrmap_set_empty (mutable_map, lo, hi - 1,
3189                          dwarf2_per_objfile->get_cu (cu_index));
3190     }
3191
3192   objfile->partial_symtabs->psymtabs_addrmap
3193     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3194 }
3195
3196 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3197    populate the objfile's psymtabs_addrmap.  */
3198
3199 static void
3200 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3201                              struct dwarf2_section_info *section)
3202 {
3203   struct objfile *objfile = dwarf2_per_objfile->objfile;
3204   bfd *abfd = objfile->obfd;
3205   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3206   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3207                                        SECT_OFF_TEXT (objfile));
3208
3209   auto_obstack temp_obstack;
3210   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3211
3212   std::unordered_map<sect_offset,
3213                      dwarf2_per_cu_data *,
3214                      gdb::hash_enum<sect_offset>>
3215     debug_info_offset_to_per_cu;
3216   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3217     {
3218       const auto insertpair
3219         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3220       if (!insertpair.second)
3221         {
3222           warning (_("Section .debug_aranges in %s has duplicate "
3223                      "debug_info_offset %s, ignoring .debug_aranges."),
3224                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3225           return;
3226         }
3227     }
3228
3229   dwarf2_read_section (objfile, section);
3230
3231   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3232
3233   const gdb_byte *addr = section->buffer;
3234
3235   while (addr < section->buffer + section->size)
3236     {
3237       const gdb_byte *const entry_addr = addr;
3238       unsigned int bytes_read;
3239
3240       const LONGEST entry_length = read_initial_length (abfd, addr,
3241                                                         &bytes_read);
3242       addr += bytes_read;
3243
3244       const gdb_byte *const entry_end = addr + entry_length;
3245       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3246       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3247       if (addr + entry_length > section->buffer + section->size)
3248         {
3249           warning (_("Section .debug_aranges in %s entry at offset %zu "
3250                      "length %s exceeds section length %s, "
3251                      "ignoring .debug_aranges."),
3252                    objfile_name (objfile), entry_addr - section->buffer,
3253                    plongest (bytes_read + entry_length),
3254                    pulongest (section->size));
3255           return;
3256         }
3257
3258       /* The version number.  */
3259       const uint16_t version = read_2_bytes (abfd, addr);
3260       addr += 2;
3261       if (version != 2)
3262         {
3263           warning (_("Section .debug_aranges in %s entry at offset %zu "
3264                      "has unsupported version %d, ignoring .debug_aranges."),
3265                    objfile_name (objfile), entry_addr - section->buffer,
3266                    version);
3267           return;
3268         }
3269
3270       const uint64_t debug_info_offset
3271         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3272       addr += offset_size;
3273       const auto per_cu_it
3274         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3275       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3276         {
3277           warning (_("Section .debug_aranges in %s entry at offset %zu "
3278                      "debug_info_offset %s does not exists, "
3279                      "ignoring .debug_aranges."),
3280                    objfile_name (objfile), entry_addr - section->buffer,
3281                    pulongest (debug_info_offset));
3282           return;
3283         }
3284       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3285
3286       const uint8_t address_size = *addr++;
3287       if (address_size < 1 || address_size > 8)
3288         {
3289           warning (_("Section .debug_aranges in %s entry at offset %zu "
3290                      "address_size %u is invalid, ignoring .debug_aranges."),
3291                    objfile_name (objfile), entry_addr - section->buffer,
3292                    address_size);
3293           return;
3294         }
3295
3296       const uint8_t segment_selector_size = *addr++;
3297       if (segment_selector_size != 0)
3298         {
3299           warning (_("Section .debug_aranges in %s entry at offset %zu "
3300                      "segment_selector_size %u is not supported, "
3301                      "ignoring .debug_aranges."),
3302                    objfile_name (objfile), entry_addr - section->buffer,
3303                    segment_selector_size);
3304           return;
3305         }
3306
3307       /* Must pad to an alignment boundary that is twice the address
3308          size.  It is undocumented by the DWARF standard but GCC does
3309          use it.  */
3310       for (size_t padding = ((-(addr - section->buffer))
3311                              & (2 * address_size - 1));
3312            padding > 0; padding--)
3313         if (*addr++ != 0)
3314           {
3315             warning (_("Section .debug_aranges in %s entry at offset %zu "
3316                        "padding is not zero, ignoring .debug_aranges."),
3317                      objfile_name (objfile), entry_addr - section->buffer);
3318             return;
3319           }
3320
3321       for (;;)
3322         {
3323           if (addr + 2 * address_size > entry_end)
3324             {
3325               warning (_("Section .debug_aranges in %s entry at offset %zu "
3326                          "address list is not properly terminated, "
3327                          "ignoring .debug_aranges."),
3328                        objfile_name (objfile), entry_addr - section->buffer);
3329               return;
3330             }
3331           ULONGEST start = extract_unsigned_integer (addr, address_size,
3332                                                      dwarf5_byte_order);
3333           addr += address_size;
3334           ULONGEST length = extract_unsigned_integer (addr, address_size,
3335                                                       dwarf5_byte_order);
3336           addr += address_size;
3337           if (start == 0 && length == 0)
3338             break;
3339           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3340             {
3341               /* Symbol was eliminated due to a COMDAT group.  */
3342               continue;
3343             }
3344           ULONGEST end = start + length;
3345           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
3346                    - baseaddr);
3347           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3348                  - baseaddr);
3349           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3350         }
3351     }
3352
3353   objfile->partial_symtabs->psymtabs_addrmap
3354     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3355 }
3356
3357 /* Find a slot in the mapped index INDEX for the object named NAME.
3358    If NAME is found, set *VEC_OUT to point to the CU vector in the
3359    constant pool and return true.  If NAME cannot be found, return
3360    false.  */
3361
3362 static bool
3363 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3364                           offset_type **vec_out)
3365 {
3366   offset_type hash;
3367   offset_type slot, step;
3368   int (*cmp) (const char *, const char *);
3369
3370   gdb::unique_xmalloc_ptr<char> without_params;
3371   if (current_language->la_language == language_cplus
3372       || current_language->la_language == language_fortran
3373       || current_language->la_language == language_d)
3374     {
3375       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3376          not contain any.  */
3377
3378       if (strchr (name, '(') != NULL)
3379         {
3380           without_params = cp_remove_params (name);
3381
3382           if (without_params != NULL)
3383             name = without_params.get ();
3384         }
3385     }
3386
3387   /* Index version 4 did not support case insensitive searches.  But the
3388      indices for case insensitive languages are built in lowercase, therefore
3389      simulate our NAME being searched is also lowercased.  */
3390   hash = mapped_index_string_hash ((index->version == 4
3391                                     && case_sensitivity == case_sensitive_off
3392                                     ? 5 : index->version),
3393                                    name);
3394
3395   slot = hash & (index->symbol_table.size () - 1);
3396   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3397   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3398
3399   for (;;)
3400     {
3401       const char *str;
3402
3403       const auto &bucket = index->symbol_table[slot];
3404       if (bucket.name == 0 && bucket.vec == 0)
3405         return false;
3406
3407       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3408       if (!cmp (name, str))
3409         {
3410           *vec_out = (offset_type *) (index->constant_pool
3411                                       + MAYBE_SWAP (bucket.vec));
3412           return true;
3413         }
3414
3415       slot = (slot + step) & (index->symbol_table.size () - 1);
3416     }
3417 }
3418
3419 /* A helper function that reads the .gdb_index from BUFFER and fills
3420    in MAP.  FILENAME is the name of the file containing the data;
3421    it is used for error reporting.  DEPRECATED_OK is true if it is
3422    ok to use deprecated sections.
3423
3424    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3425    out parameters that are filled in with information about the CU and
3426    TU lists in the section.
3427
3428    Returns true if all went well, false otherwise.  */
3429
3430 static bool
3431 read_gdb_index_from_buffer (struct objfile *objfile,
3432                             const char *filename,
3433                             bool deprecated_ok,
3434                             gdb::array_view<const gdb_byte> buffer,
3435                             struct mapped_index *map,
3436                             const gdb_byte **cu_list,
3437                             offset_type *cu_list_elements,
3438                             const gdb_byte **types_list,
3439                             offset_type *types_list_elements)
3440 {
3441   const gdb_byte *addr = &buffer[0];
3442
3443   /* Version check.  */
3444   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3445   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3446      causes the index to behave very poorly for certain requests.  Version 3
3447      contained incomplete addrmap.  So, it seems better to just ignore such
3448      indices.  */
3449   if (version < 4)
3450     {
3451       static int warning_printed = 0;
3452       if (!warning_printed)
3453         {
3454           warning (_("Skipping obsolete .gdb_index section in %s."),
3455                    filename);
3456           warning_printed = 1;
3457         }
3458       return 0;
3459     }
3460   /* Index version 4 uses a different hash function than index version
3461      5 and later.
3462
3463      Versions earlier than 6 did not emit psymbols for inlined
3464      functions.  Using these files will cause GDB not to be able to
3465      set breakpoints on inlined functions by name, so we ignore these
3466      indices unless the user has done
3467      "set use-deprecated-index-sections on".  */
3468   if (version < 6 && !deprecated_ok)
3469     {
3470       static int warning_printed = 0;
3471       if (!warning_printed)
3472         {
3473           warning (_("\
3474 Skipping deprecated .gdb_index section in %s.\n\
3475 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3476 to use the section anyway."),
3477                    filename);
3478           warning_printed = 1;
3479         }
3480       return 0;
3481     }
3482   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3483      of the TU (for symbols coming from TUs),
3484      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3485      Plus gold-generated indices can have duplicate entries for global symbols,
3486      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3487      These are just performance bugs, and we can't distinguish gdb-generated
3488      indices from gold-generated ones, so issue no warning here.  */
3489
3490   /* Indexes with higher version than the one supported by GDB may be no
3491      longer backward compatible.  */
3492   if (version > 8)
3493     return 0;
3494
3495   map->version = version;
3496
3497   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3498
3499   int i = 0;
3500   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3501   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3502                        / 8);
3503   ++i;
3504
3505   *types_list = addr + MAYBE_SWAP (metadata[i]);
3506   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3507                            - MAYBE_SWAP (metadata[i]))
3508                           / 8);
3509   ++i;
3510
3511   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3512   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3513   map->address_table
3514     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3515   ++i;
3516
3517   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3518   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3519   map->symbol_table
3520     = gdb::array_view<mapped_index::symbol_table_slot>
3521        ((mapped_index::symbol_table_slot *) symbol_table,
3522         (mapped_index::symbol_table_slot *) symbol_table_end);
3523
3524   ++i;
3525   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3526
3527   return 1;
3528 }
3529
3530 /* Callback types for dwarf2_read_gdb_index.  */
3531
3532 typedef gdb::function_view
3533     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
3534     get_gdb_index_contents_ftype;
3535 typedef gdb::function_view
3536     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3537     get_gdb_index_contents_dwz_ftype;
3538
3539 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3540    elements of all the CUs and return 1.  Otherwise, return 0.  */
3541
3542 static int
3543 dwarf2_read_gdb_index
3544   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3545    get_gdb_index_contents_ftype get_gdb_index_contents,
3546    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3547 {
3548   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3549   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3550   struct dwz_file *dwz;
3551   struct objfile *objfile = dwarf2_per_objfile->objfile;
3552
3553   gdb::array_view<const gdb_byte> main_index_contents
3554     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3555
3556   if (main_index_contents.empty ())
3557     return 0;
3558
3559   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3560   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3561                                    use_deprecated_index_sections,
3562                                    main_index_contents, map.get (), &cu_list,
3563                                    &cu_list_elements, &types_list,
3564                                    &types_list_elements))
3565     return 0;
3566
3567   /* Don't use the index if it's empty.  */
3568   if (map->symbol_table.empty ())
3569     return 0;
3570
3571   /* If there is a .dwz file, read it so we can get its CU list as
3572      well.  */
3573   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3574   if (dwz != NULL)
3575     {
3576       struct mapped_index dwz_map;
3577       const gdb_byte *dwz_types_ignore;
3578       offset_type dwz_types_elements_ignore;
3579
3580       gdb::array_view<const gdb_byte> dwz_index_content
3581         = get_gdb_index_contents_dwz (objfile, dwz);
3582
3583       if (dwz_index_content.empty ())
3584         return 0;
3585
3586       if (!read_gdb_index_from_buffer (objfile,
3587                                        bfd_get_filename (dwz->dwz_bfd), 1,
3588                                        dwz_index_content, &dwz_map,
3589                                        &dwz_list, &dwz_list_elements,
3590                                        &dwz_types_ignore,
3591                                        &dwz_types_elements_ignore))
3592         {
3593           warning (_("could not read '.gdb_index' section from %s; skipping"),
3594                    bfd_get_filename (dwz->dwz_bfd));
3595           return 0;
3596         }
3597     }
3598
3599   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3600                          dwz_list, dwz_list_elements);
3601
3602   if (types_list_elements)
3603     {
3604       struct dwarf2_section_info *section;
3605
3606       /* We can only handle a single .debug_types when we have an
3607          index.  */
3608       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3609         return 0;
3610
3611       section = VEC_index (dwarf2_section_info_def,
3612                            dwarf2_per_objfile->types, 0);
3613
3614       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3615                                                types_list, types_list_elements);
3616     }
3617
3618   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3619
3620   dwarf2_per_objfile->index_table = std::move (map);
3621   dwarf2_per_objfile->using_index = 1;
3622   dwarf2_per_objfile->quick_file_names_table =
3623     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3624
3625   return 1;
3626 }
3627
3628 /* die_reader_func for dw2_get_file_names.  */
3629
3630 static void
3631 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3632                            const gdb_byte *info_ptr,
3633                            struct die_info *comp_unit_die,
3634                            int has_children,
3635                            void *data)
3636 {
3637   struct dwarf2_cu *cu = reader->cu;
3638   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3639   struct dwarf2_per_objfile *dwarf2_per_objfile
3640     = cu->per_cu->dwarf2_per_objfile;
3641   struct objfile *objfile = dwarf2_per_objfile->objfile;
3642   struct dwarf2_per_cu_data *lh_cu;
3643   struct attribute *attr;
3644   int i;
3645   void **slot;
3646   struct quick_file_names *qfn;
3647
3648   gdb_assert (! this_cu->is_debug_types);
3649
3650   /* Our callers never want to match partial units -- instead they
3651      will match the enclosing full CU.  */
3652   if (comp_unit_die->tag == DW_TAG_partial_unit)
3653     {
3654       this_cu->v.quick->no_file_data = 1;
3655       return;
3656     }
3657
3658   lh_cu = this_cu;
3659   slot = NULL;
3660
3661   line_header_up lh;
3662   sect_offset line_offset {};
3663
3664   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3665   if (attr)
3666     {
3667       struct quick_file_names find_entry;
3668
3669       line_offset = (sect_offset) DW_UNSND (attr);
3670
3671       /* We may have already read in this line header (TU line header sharing).
3672          If we have we're done.  */
3673       find_entry.hash.dwo_unit = cu->dwo_unit;
3674       find_entry.hash.line_sect_off = line_offset;
3675       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3676                              &find_entry, INSERT);
3677       if (*slot != NULL)
3678         {
3679           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3680           return;
3681         }
3682
3683       lh = dwarf_decode_line_header (line_offset, cu);
3684     }
3685   if (lh == NULL)
3686     {
3687       lh_cu->v.quick->no_file_data = 1;
3688       return;
3689     }
3690
3691   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3692   qfn->hash.dwo_unit = cu->dwo_unit;
3693   qfn->hash.line_sect_off = line_offset;
3694   gdb_assert (slot != NULL);
3695   *slot = qfn;
3696
3697   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3698
3699   qfn->num_file_names = lh->file_names.size ();
3700   qfn->file_names =
3701     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3702   for (i = 0; i < lh->file_names.size (); ++i)
3703     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3704   qfn->real_names = NULL;
3705
3706   lh_cu->v.quick->file_names = qfn;
3707 }
3708
3709 /* A helper for the "quick" functions which attempts to read the line
3710    table for THIS_CU.  */
3711
3712 static struct quick_file_names *
3713 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3714 {
3715   /* This should never be called for TUs.  */
3716   gdb_assert (! this_cu->is_debug_types);
3717   /* Nor type unit groups.  */
3718   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3719
3720   if (this_cu->v.quick->file_names != NULL)
3721     return this_cu->v.quick->file_names;
3722   /* If we know there is no line data, no point in looking again.  */
3723   if (this_cu->v.quick->no_file_data)
3724     return NULL;
3725
3726   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3727
3728   if (this_cu->v.quick->no_file_data)
3729     return NULL;
3730   return this_cu->v.quick->file_names;
3731 }
3732
3733 /* A helper for the "quick" functions which computes and caches the
3734    real path for a given file name from the line table.  */
3735
3736 static const char *
3737 dw2_get_real_path (struct objfile *objfile,
3738                    struct quick_file_names *qfn, int index)
3739 {
3740   if (qfn->real_names == NULL)
3741     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3742                                       qfn->num_file_names, const char *);
3743
3744   if (qfn->real_names[index] == NULL)
3745     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3746
3747   return qfn->real_names[index];
3748 }
3749
3750 static struct symtab *
3751 dw2_find_last_source_symtab (struct objfile *objfile)
3752 {
3753   struct dwarf2_per_objfile *dwarf2_per_objfile
3754     = get_dwarf2_per_objfile (objfile);
3755   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3756   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3757
3758   if (cust == NULL)
3759     return NULL;
3760
3761   return compunit_primary_filetab (cust);
3762 }
3763
3764 /* Traversal function for dw2_forget_cached_source_info.  */
3765
3766 static int
3767 dw2_free_cached_file_names (void **slot, void *info)
3768 {
3769   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3770
3771   if (file_data->real_names)
3772     {
3773       int i;
3774
3775       for (i = 0; i < file_data->num_file_names; ++i)
3776         {
3777           xfree ((void*) file_data->real_names[i]);
3778           file_data->real_names[i] = NULL;
3779         }
3780     }
3781
3782   return 1;
3783 }
3784
3785 static void
3786 dw2_forget_cached_source_info (struct objfile *objfile)
3787 {
3788   struct dwarf2_per_objfile *dwarf2_per_objfile
3789     = get_dwarf2_per_objfile (objfile);
3790
3791   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3792                           dw2_free_cached_file_names, NULL);
3793 }
3794
3795 /* Helper function for dw2_map_symtabs_matching_filename that expands
3796    the symtabs and calls the iterator.  */
3797
3798 static int
3799 dw2_map_expand_apply (struct objfile *objfile,
3800                       struct dwarf2_per_cu_data *per_cu,
3801                       const char *name, const char *real_path,
3802                       gdb::function_view<bool (symtab *)> callback)
3803 {
3804   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3805
3806   /* Don't visit already-expanded CUs.  */
3807   if (per_cu->v.quick->compunit_symtab)
3808     return 0;
3809
3810   /* This may expand more than one symtab, and we want to iterate over
3811      all of them.  */
3812   dw2_instantiate_symtab (per_cu, false);
3813
3814   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3815                                     last_made, callback);
3816 }
3817
3818 /* Implementation of the map_symtabs_matching_filename method.  */
3819
3820 static bool
3821 dw2_map_symtabs_matching_filename
3822   (struct objfile *objfile, const char *name, const char *real_path,
3823    gdb::function_view<bool (symtab *)> callback)
3824 {
3825   const char *name_basename = lbasename (name);
3826   struct dwarf2_per_objfile *dwarf2_per_objfile
3827     = get_dwarf2_per_objfile (objfile);
3828
3829   /* The rule is CUs specify all the files, including those used by
3830      any TU, so there's no need to scan TUs here.  */
3831
3832   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3833     {
3834       /* We only need to look at symtabs not already expanded.  */
3835       if (per_cu->v.quick->compunit_symtab)
3836         continue;
3837
3838       quick_file_names *file_data = dw2_get_file_names (per_cu);
3839       if (file_data == NULL)
3840         continue;
3841
3842       for (int j = 0; j < file_data->num_file_names; ++j)
3843         {
3844           const char *this_name = file_data->file_names[j];
3845           const char *this_real_name;
3846
3847           if (compare_filenames_for_search (this_name, name))
3848             {
3849               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3850                                         callback))
3851                 return true;
3852               continue;
3853             }
3854
3855           /* Before we invoke realpath, which can get expensive when many
3856              files are involved, do a quick comparison of the basenames.  */
3857           if (! basenames_may_differ
3858               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3859             continue;
3860
3861           this_real_name = dw2_get_real_path (objfile, file_data, j);
3862           if (compare_filenames_for_search (this_real_name, name))
3863             {
3864               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3865                                         callback))
3866                 return true;
3867               continue;
3868             }
3869
3870           if (real_path != NULL)
3871             {
3872               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3873               gdb_assert (IS_ABSOLUTE_PATH (name));
3874               if (this_real_name != NULL
3875                   && FILENAME_CMP (real_path, this_real_name) == 0)
3876                 {
3877                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3878                                             callback))
3879                     return true;
3880                   continue;
3881                 }
3882             }
3883         }
3884     }
3885
3886   return false;
3887 }
3888
3889 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3890
3891 struct dw2_symtab_iterator
3892 {
3893   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3894   struct dwarf2_per_objfile *dwarf2_per_objfile;
3895   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3896   int want_specific_block;
3897   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3898      Unused if !WANT_SPECIFIC_BLOCK.  */
3899   int block_index;
3900   /* The kind of symbol we're looking for.  */
3901   domain_enum domain;
3902   /* The list of CUs from the index entry of the symbol,
3903      or NULL if not found.  */
3904   offset_type *vec;
3905   /* The next element in VEC to look at.  */
3906   int next;
3907   /* The number of elements in VEC, or zero if there is no match.  */
3908   int length;
3909   /* Have we seen a global version of the symbol?
3910      If so we can ignore all further global instances.
3911      This is to work around gold/15646, inefficient gold-generated
3912      indices.  */
3913   int global_seen;
3914 };
3915
3916 /* Initialize the index symtab iterator ITER.
3917    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3918    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3919
3920 static void
3921 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3922                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3923                       int want_specific_block,
3924                       int block_index,
3925                       domain_enum domain,
3926                       const char *name)
3927 {
3928   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3929   iter->want_specific_block = want_specific_block;
3930   iter->block_index = block_index;
3931   iter->domain = domain;
3932   iter->next = 0;
3933   iter->global_seen = 0;
3934
3935   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3936
3937   /* index is NULL if OBJF_READNOW.  */
3938   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3939     iter->length = MAYBE_SWAP (*iter->vec);
3940   else
3941     {
3942       iter->vec = NULL;
3943       iter->length = 0;
3944     }
3945 }
3946
3947 /* Return the next matching CU or NULL if there are no more.  */
3948
3949 static struct dwarf2_per_cu_data *
3950 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3951 {
3952   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3953
3954   for ( ; iter->next < iter->length; ++iter->next)
3955     {
3956       offset_type cu_index_and_attrs =
3957         MAYBE_SWAP (iter->vec[iter->next + 1]);
3958       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3959       int want_static = iter->block_index != GLOBAL_BLOCK;
3960       /* This value is only valid for index versions >= 7.  */
3961       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3962       gdb_index_symbol_kind symbol_kind =
3963         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3964       /* Only check the symbol attributes if they're present.
3965          Indices prior to version 7 don't record them,
3966          and indices >= 7 may elide them for certain symbols
3967          (gold does this).  */
3968       int attrs_valid =
3969         (dwarf2_per_objfile->index_table->version >= 7
3970          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3971
3972       /* Don't crash on bad data.  */
3973       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3974                        + dwarf2_per_objfile->all_type_units.size ()))
3975         {
3976           complaint (_(".gdb_index entry has bad CU index"
3977                        " [in module %s]"),
3978                      objfile_name (dwarf2_per_objfile->objfile));
3979           continue;
3980         }
3981
3982       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3983
3984       /* Skip if already read in.  */
3985       if (per_cu->v.quick->compunit_symtab)
3986         continue;
3987
3988       /* Check static vs global.  */
3989       if (attrs_valid)
3990         {
3991           if (iter->want_specific_block
3992               && want_static != is_static)
3993             continue;
3994           /* Work around gold/15646.  */
3995           if (!is_static && iter->global_seen)
3996             continue;
3997           if (!is_static)
3998             iter->global_seen = 1;
3999         }
4000
4001       /* Only check the symbol's kind if it has one.  */
4002       if (attrs_valid)
4003         {
4004           switch (iter->domain)
4005             {
4006             case VAR_DOMAIN:
4007               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4008                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4009                   /* Some types are also in VAR_DOMAIN.  */
4010                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4011                 continue;
4012               break;
4013             case STRUCT_DOMAIN:
4014               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4015                 continue;
4016               break;
4017             case LABEL_DOMAIN:
4018               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4019                 continue;
4020               break;
4021             default:
4022               break;
4023             }
4024         }
4025
4026       ++iter->next;
4027       return per_cu;
4028     }
4029
4030   return NULL;
4031 }
4032
4033 static struct compunit_symtab *
4034 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4035                    const char *name, domain_enum domain)
4036 {
4037   struct compunit_symtab *stab_best = NULL;
4038   struct dwarf2_per_objfile *dwarf2_per_objfile
4039     = get_dwarf2_per_objfile (objfile);
4040
4041   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4042
4043   struct dw2_symtab_iterator iter;
4044   struct dwarf2_per_cu_data *per_cu;
4045
4046   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4047
4048   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4049     {
4050       struct symbol *sym, *with_opaque = NULL;
4051       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4052       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4053       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4054
4055       sym = block_find_symbol (block, name, domain,
4056                                block_find_non_opaque_type_preferred,
4057                                &with_opaque);
4058
4059       /* Some caution must be observed with overloaded functions
4060          and methods, since the index will not contain any overload
4061          information (but NAME might contain it).  */
4062
4063       if (sym != NULL
4064           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4065         return stab;
4066       if (with_opaque != NULL
4067           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4068         stab_best = stab;
4069
4070       /* Keep looking through other CUs.  */
4071     }
4072
4073   return stab_best;
4074 }
4075
4076 static void
4077 dw2_print_stats (struct objfile *objfile)
4078 {
4079   struct dwarf2_per_objfile *dwarf2_per_objfile
4080     = get_dwarf2_per_objfile (objfile);
4081   int total = (dwarf2_per_objfile->all_comp_units.size ()
4082                + dwarf2_per_objfile->all_type_units.size ());
4083   int count = 0;
4084
4085   for (int i = 0; i < total; ++i)
4086     {
4087       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4088
4089       if (!per_cu->v.quick->compunit_symtab)
4090         ++count;
4091     }
4092   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4093   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4094 }
4095
4096 /* This dumps minimal information about the index.
4097    It is called via "mt print objfiles".
4098    One use is to verify .gdb_index has been loaded by the
4099    gdb.dwarf2/gdb-index.exp testcase.  */
4100
4101 static void
4102 dw2_dump (struct objfile *objfile)
4103 {
4104   struct dwarf2_per_objfile *dwarf2_per_objfile
4105     = get_dwarf2_per_objfile (objfile);
4106
4107   gdb_assert (dwarf2_per_objfile->using_index);
4108   printf_filtered (".gdb_index:");
4109   if (dwarf2_per_objfile->index_table != NULL)
4110     {
4111       printf_filtered (" version %d\n",
4112                        dwarf2_per_objfile->index_table->version);
4113     }
4114   else
4115     printf_filtered (" faked for \"readnow\"\n");
4116   printf_filtered ("\n");
4117 }
4118
4119 static void
4120 dw2_expand_symtabs_for_function (struct objfile *objfile,
4121                                  const char *func_name)
4122 {
4123   struct dwarf2_per_objfile *dwarf2_per_objfile
4124     = get_dwarf2_per_objfile (objfile);
4125
4126   struct dw2_symtab_iterator iter;
4127   struct dwarf2_per_cu_data *per_cu;
4128
4129   /* Note: It doesn't matter what we pass for block_index here.  */
4130   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4131                         func_name);
4132
4133   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4134     dw2_instantiate_symtab (per_cu, false);
4135
4136 }
4137
4138 static void
4139 dw2_expand_all_symtabs (struct objfile *objfile)
4140 {
4141   struct dwarf2_per_objfile *dwarf2_per_objfile
4142     = get_dwarf2_per_objfile (objfile);
4143   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4144                      + dwarf2_per_objfile->all_type_units.size ());
4145
4146   for (int i = 0; i < total_units; ++i)
4147     {
4148       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4149
4150       /* We don't want to directly expand a partial CU, because if we
4151          read it with the wrong language, then assertion failures can
4152          be triggered later on.  See PR symtab/23010.  So, tell
4153          dw2_instantiate_symtab to skip partial CUs -- any important
4154          partial CU will be read via DW_TAG_imported_unit anyway.  */
4155       dw2_instantiate_symtab (per_cu, true);
4156     }
4157 }
4158
4159 static void
4160 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4161                                   const char *fullname)
4162 {
4163   struct dwarf2_per_objfile *dwarf2_per_objfile
4164     = get_dwarf2_per_objfile (objfile);
4165
4166   /* We don't need to consider type units here.
4167      This is only called for examining code, e.g. expand_line_sal.
4168      There can be an order of magnitude (or more) more type units
4169      than comp units, and we avoid them if we can.  */
4170
4171   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4172     {
4173       /* We only need to look at symtabs not already expanded.  */
4174       if (per_cu->v.quick->compunit_symtab)
4175         continue;
4176
4177       quick_file_names *file_data = dw2_get_file_names (per_cu);
4178       if (file_data == NULL)
4179         continue;
4180
4181       for (int j = 0; j < file_data->num_file_names; ++j)
4182         {
4183           const char *this_fullname = file_data->file_names[j];
4184
4185           if (filename_cmp (this_fullname, fullname) == 0)
4186             {
4187               dw2_instantiate_symtab (per_cu, false);
4188               break;
4189             }
4190         }
4191     }
4192 }
4193
4194 static void
4195 dw2_map_matching_symbols (struct objfile *objfile,
4196                           const char * name, domain_enum domain,
4197                           int global,
4198                           int (*callback) (const struct block *,
4199                                            struct symbol *, void *),
4200                           void *data, symbol_name_match_type match,
4201                           symbol_compare_ftype *ordered_compare)
4202 {
4203   /* Currently unimplemented; used for Ada.  The function can be called if the
4204      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4205      does not look for non-Ada symbols this function should just return.  */
4206 }
4207
4208 /* Symbol name matcher for .gdb_index names.
4209
4210    Symbol names in .gdb_index have a few particularities:
4211
4212    - There's no indication of which is the language of each symbol.
4213
4214      Since each language has its own symbol name matching algorithm,
4215      and we don't know which language is the right one, we must match
4216      each symbol against all languages.  This would be a potential
4217      performance problem if it were not mitigated by the
4218      mapped_index::name_components lookup table, which significantly
4219      reduces the number of times we need to call into this matcher,
4220      making it a non-issue.
4221
4222    - Symbol names in the index have no overload (parameter)
4223      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4224      appear as "foo" in the index, for example.
4225
4226      This means that the lookup names passed to the symbol name
4227      matcher functions must have no parameter information either
4228      because (e.g.) symbol search name "foo" does not match
4229      lookup-name "foo(int)" [while swapping search name for lookup
4230      name would match].
4231 */
4232 class gdb_index_symbol_name_matcher
4233 {
4234 public:
4235   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4236   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4237
4238   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4239      Returns true if any matcher matches.  */
4240   bool matches (const char *symbol_name);
4241
4242 private:
4243   /* A reference to the lookup name we're matching against.  */
4244   const lookup_name_info &m_lookup_name;
4245
4246   /* A vector holding all the different symbol name matchers, for all
4247      languages.  */
4248   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4249 };
4250
4251 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4252   (const lookup_name_info &lookup_name)
4253     : m_lookup_name (lookup_name)
4254 {
4255   /* Prepare the vector of comparison functions upfront, to avoid
4256      doing the same work for each symbol.  Care is taken to avoid
4257      matching with the same matcher more than once if/when multiple
4258      languages use the same matcher function.  */
4259   auto &matchers = m_symbol_name_matcher_funcs;
4260   matchers.reserve (nr_languages);
4261
4262   matchers.push_back (default_symbol_name_matcher);
4263
4264   for (int i = 0; i < nr_languages; i++)
4265     {
4266       const language_defn *lang = language_def ((enum language) i);
4267       symbol_name_matcher_ftype *name_matcher
4268         = get_symbol_name_matcher (lang, m_lookup_name);
4269
4270       /* Don't insert the same comparison routine more than once.
4271          Note that we do this linear walk instead of a seemingly
4272          cheaper sorted insert, or use a std::set or something like
4273          that, because relative order of function addresses is not
4274          stable.  This is not a problem in practice because the number
4275          of supported languages is low, and the cost here is tiny
4276          compared to the number of searches we'll do afterwards using
4277          this object.  */
4278       if (name_matcher != default_symbol_name_matcher
4279           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4280               == matchers.end ()))
4281         matchers.push_back (name_matcher);
4282     }
4283 }
4284
4285 bool
4286 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4287 {
4288   for (auto matches_name : m_symbol_name_matcher_funcs)
4289     if (matches_name (symbol_name, m_lookup_name, NULL))
4290       return true;
4291
4292   return false;
4293 }
4294
4295 /* Starting from a search name, return the string that finds the upper
4296    bound of all strings that start with SEARCH_NAME in a sorted name
4297    list.  Returns the empty string to indicate that the upper bound is
4298    the end of the list.  */
4299
4300 static std::string
4301 make_sort_after_prefix_name (const char *search_name)
4302 {
4303   /* When looking to complete "func", we find the upper bound of all
4304      symbols that start with "func" by looking for where we'd insert
4305      the closest string that would follow "func" in lexicographical
4306      order.  Usually, that's "func"-with-last-character-incremented,
4307      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4308      will be UTF-8 multi-byte sequences, but we can't be certain.
4309      Especially mind the 0xff character, which is a valid character in
4310      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4311      rule out compilers allowing it in identifiers.  Note that
4312      conveniently, strcmp/strcasecmp are specified to compare
4313      characters interpreted as unsigned char.  So what we do is treat
4314      the whole string as a base 256 number composed of a sequence of
4315      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4316      to 0, and carries 1 to the following more-significant position.
4317      If the very first character in SEARCH_NAME ends up incremented
4318      and carries/overflows, then the upper bound is the end of the
4319      list.  The string after the empty string is also the empty
4320      string.
4321
4322      Some examples of this operation:
4323
4324        SEARCH_NAME  => "+1" RESULT
4325
4326        "abc"              => "abd"
4327        "ab\xff"           => "ac"
4328        "\xff" "a" "\xff"  => "\xff" "b"
4329        "\xff"             => ""
4330        "\xff\xff"         => ""
4331        ""                 => ""
4332
4333      Then, with these symbols for example:
4334
4335       func
4336       func1
4337       fund
4338
4339      completing "func" looks for symbols between "func" and
4340      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4341      which finds "func" and "func1", but not "fund".
4342
4343      And with:
4344
4345       funcÿ     (Latin1 'ÿ' [0xff])
4346       funcÿ1
4347       fund
4348
4349      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4350      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4351
4352      And with:
4353
4354       ÿÿ        (Latin1 'ÿ' [0xff])
4355       ÿÿ1
4356
4357      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4358      the end of the list.
4359   */
4360   std::string after = search_name;
4361   while (!after.empty () && (unsigned char) after.back () == 0xff)
4362     after.pop_back ();
4363   if (!after.empty ())
4364     after.back () = (unsigned char) after.back () + 1;
4365   return after;
4366 }
4367
4368 /* See declaration.  */
4369
4370 std::pair<std::vector<name_component>::const_iterator,
4371           std::vector<name_component>::const_iterator>
4372 mapped_index_base::find_name_components_bounds
4373   (const lookup_name_info &lookup_name_without_params) const
4374 {
4375   auto *name_cmp
4376     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4377
4378   const char *cplus
4379     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4380
4381   /* Comparison function object for lower_bound that matches against a
4382      given symbol name.  */
4383   auto lookup_compare_lower = [&] (const name_component &elem,
4384                                    const char *name)
4385     {
4386       const char *elem_qualified = this->symbol_name_at (elem.idx);
4387       const char *elem_name = elem_qualified + elem.name_offset;
4388       return name_cmp (elem_name, name) < 0;
4389     };
4390
4391   /* Comparison function object for upper_bound that matches against a
4392      given symbol name.  */
4393   auto lookup_compare_upper = [&] (const char *name,
4394                                    const name_component &elem)
4395     {
4396       const char *elem_qualified = this->symbol_name_at (elem.idx);
4397       const char *elem_name = elem_qualified + elem.name_offset;
4398       return name_cmp (name, elem_name) < 0;
4399     };
4400
4401   auto begin = this->name_components.begin ();
4402   auto end = this->name_components.end ();
4403
4404   /* Find the lower bound.  */
4405   auto lower = [&] ()
4406     {
4407       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4408         return begin;
4409       else
4410         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4411     } ();
4412
4413   /* Find the upper bound.  */
4414   auto upper = [&] ()
4415     {
4416       if (lookup_name_without_params.completion_mode ())
4417         {
4418           /* In completion mode, we want UPPER to point past all
4419              symbols names that have the same prefix.  I.e., with
4420              these symbols, and completing "func":
4421
4422               function        << lower bound
4423               function1
4424               other_function  << upper bound
4425
4426              We find the upper bound by looking for the insertion
4427              point of "func"-with-last-character-incremented,
4428              i.e. "fund".  */
4429           std::string after = make_sort_after_prefix_name (cplus);
4430           if (after.empty ())
4431             return end;
4432           return std::lower_bound (lower, end, after.c_str (),
4433                                    lookup_compare_lower);
4434         }
4435       else
4436         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4437     } ();
4438
4439   return {lower, upper};
4440 }
4441
4442 /* See declaration.  */
4443
4444 void
4445 mapped_index_base::build_name_components ()
4446 {
4447   if (!this->name_components.empty ())
4448     return;
4449
4450   this->name_components_casing = case_sensitivity;
4451   auto *name_cmp
4452     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4453
4454   /* The code below only knows how to break apart components of C++
4455      symbol names (and other languages that use '::' as
4456      namespace/module separator).  If we add support for wild matching
4457      to some language that uses some other operator (E.g., Ada, Go and
4458      D use '.'), then we'll need to try splitting the symbol name
4459      according to that language too.  Note that Ada does support wild
4460      matching, but doesn't currently support .gdb_index.  */
4461   auto count = this->symbol_name_count ();
4462   for (offset_type idx = 0; idx < count; idx++)
4463     {
4464       if (this->symbol_name_slot_invalid (idx))
4465         continue;
4466
4467       const char *name = this->symbol_name_at (idx);
4468
4469       /* Add each name component to the name component table.  */
4470       unsigned int previous_len = 0;
4471       for (unsigned int current_len = cp_find_first_component (name);
4472            name[current_len] != '\0';
4473            current_len += cp_find_first_component (name + current_len))
4474         {
4475           gdb_assert (name[current_len] == ':');
4476           this->name_components.push_back ({previous_len, idx});
4477           /* Skip the '::'.  */
4478           current_len += 2;
4479           previous_len = current_len;
4480         }
4481       this->name_components.push_back ({previous_len, idx});
4482     }
4483
4484   /* Sort name_components elements by name.  */
4485   auto name_comp_compare = [&] (const name_component &left,
4486                                 const name_component &right)
4487     {
4488       const char *left_qualified = this->symbol_name_at (left.idx);
4489       const char *right_qualified = this->symbol_name_at (right.idx);
4490
4491       const char *left_name = left_qualified + left.name_offset;
4492       const char *right_name = right_qualified + right.name_offset;
4493
4494       return name_cmp (left_name, right_name) < 0;
4495     };
4496
4497   std::sort (this->name_components.begin (),
4498              this->name_components.end (),
4499              name_comp_compare);
4500 }
4501
4502 /* Helper for dw2_expand_symtabs_matching that works with a
4503    mapped_index_base instead of the containing objfile.  This is split
4504    to a separate function in order to be able to unit test the
4505    name_components matching using a mock mapped_index_base.  For each
4506    symbol name that matches, calls MATCH_CALLBACK, passing it the
4507    symbol's index in the mapped_index_base symbol table.  */
4508
4509 static void
4510 dw2_expand_symtabs_matching_symbol
4511   (mapped_index_base &index,
4512    const lookup_name_info &lookup_name_in,
4513    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4514    enum search_domain kind,
4515    gdb::function_view<void (offset_type)> match_callback)
4516 {
4517   lookup_name_info lookup_name_without_params
4518     = lookup_name_in.make_ignore_params ();
4519   gdb_index_symbol_name_matcher lookup_name_matcher
4520     (lookup_name_without_params);
4521
4522   /* Build the symbol name component sorted vector, if we haven't
4523      yet.  */
4524   index.build_name_components ();
4525
4526   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4527
4528   /* Now for each symbol name in range, check to see if we have a name
4529      match, and if so, call the MATCH_CALLBACK callback.  */
4530
4531   /* The same symbol may appear more than once in the range though.
4532      E.g., if we're looking for symbols that complete "w", and we have
4533      a symbol named "w1::w2", we'll find the two name components for
4534      that same symbol in the range.  To be sure we only call the
4535      callback once per symbol, we first collect the symbol name
4536      indexes that matched in a temporary vector and ignore
4537      duplicates.  */
4538   std::vector<offset_type> matches;
4539   matches.reserve (std::distance (bounds.first, bounds.second));
4540
4541   for (; bounds.first != bounds.second; ++bounds.first)
4542     {
4543       const char *qualified = index.symbol_name_at (bounds.first->idx);
4544
4545       if (!lookup_name_matcher.matches (qualified)
4546           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4547         continue;
4548
4549       matches.push_back (bounds.first->idx);
4550     }
4551
4552   std::sort (matches.begin (), matches.end ());
4553
4554   /* Finally call the callback, once per match.  */
4555   ULONGEST prev = -1;
4556   for (offset_type idx : matches)
4557     {
4558       if (prev != idx)
4559         {
4560           match_callback (idx);
4561           prev = idx;
4562         }
4563     }
4564
4565   /* Above we use a type wider than idx's for 'prev', since 0 and
4566      (offset_type)-1 are both possible values.  */
4567   static_assert (sizeof (prev) > sizeof (offset_type), "");
4568 }
4569
4570 #if GDB_SELF_TEST
4571
4572 namespace selftests { namespace dw2_expand_symtabs_matching {
4573
4574 /* A mock .gdb_index/.debug_names-like name index table, enough to
4575    exercise dw2_expand_symtabs_matching_symbol, which works with the
4576    mapped_index_base interface.  Builds an index from the symbol list
4577    passed as parameter to the constructor.  */
4578 class mock_mapped_index : public mapped_index_base
4579 {
4580 public:
4581   mock_mapped_index (gdb::array_view<const char *> symbols)
4582     : m_symbol_table (symbols)
4583   {}
4584
4585   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4586
4587   /* Return the number of names in the symbol table.  */
4588   size_t symbol_name_count () const override
4589   {
4590     return m_symbol_table.size ();
4591   }
4592
4593   /* Get the name of the symbol at IDX in the symbol table.  */
4594   const char *symbol_name_at (offset_type idx) const override
4595   {
4596     return m_symbol_table[idx];
4597   }
4598
4599 private:
4600   gdb::array_view<const char *> m_symbol_table;
4601 };
4602
4603 /* Convenience function that converts a NULL pointer to a "<null>"
4604    string, to pass to print routines.  */
4605
4606 static const char *
4607 string_or_null (const char *str)
4608 {
4609   return str != NULL ? str : "<null>";
4610 }
4611
4612 /* Check if a lookup_name_info built from
4613    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4614    index.  EXPECTED_LIST is the list of expected matches, in expected
4615    matching order.  If no match expected, then an empty list is
4616    specified.  Returns true on success.  On failure prints a warning
4617    indicating the file:line that failed, and returns false.  */
4618
4619 static bool
4620 check_match (const char *file, int line,
4621              mock_mapped_index &mock_index,
4622              const char *name, symbol_name_match_type match_type,
4623              bool completion_mode,
4624              std::initializer_list<const char *> expected_list)
4625 {
4626   lookup_name_info lookup_name (name, match_type, completion_mode);
4627
4628   bool matched = true;
4629
4630   auto mismatch = [&] (const char *expected_str,
4631                        const char *got)
4632   {
4633     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4634                "expected=\"%s\", got=\"%s\"\n"),
4635              file, line,
4636              (match_type == symbol_name_match_type::FULL
4637               ? "FULL" : "WILD"),
4638              name, string_or_null (expected_str), string_or_null (got));
4639     matched = false;
4640   };
4641
4642   auto expected_it = expected_list.begin ();
4643   auto expected_end = expected_list.end ();
4644
4645   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4646                                       NULL, ALL_DOMAIN,
4647                                       [&] (offset_type idx)
4648   {
4649     const char *matched_name = mock_index.symbol_name_at (idx);
4650     const char *expected_str
4651       = expected_it == expected_end ? NULL : *expected_it++;
4652
4653     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4654       mismatch (expected_str, matched_name);
4655   });
4656
4657   const char *expected_str
4658   = expected_it == expected_end ? NULL : *expected_it++;
4659   if (expected_str != NULL)
4660     mismatch (expected_str, NULL);
4661
4662   return matched;
4663 }
4664
4665 /* The symbols added to the mock mapped_index for testing (in
4666    canonical form).  */
4667 static const char *test_symbols[] = {
4668   "function",
4669   "std::bar",
4670   "std::zfunction",
4671   "std::zfunction2",
4672   "w1::w2",
4673   "ns::foo<char*>",
4674   "ns::foo<int>",
4675   "ns::foo<long>",
4676   "ns2::tmpl<int>::foo2",
4677   "(anonymous namespace)::A::B::C",
4678
4679   /* These are used to check that the increment-last-char in the
4680      matching algorithm for completion doesn't match "t1_fund" when
4681      completing "t1_func".  */
4682   "t1_func",
4683   "t1_func1",
4684   "t1_fund",
4685   "t1_fund1",
4686
4687   /* A UTF-8 name with multi-byte sequences to make sure that
4688      cp-name-parser understands this as a single identifier ("função"
4689      is "function" in PT).  */
4690   u8"u8função",
4691
4692   /* \377 (0xff) is Latin1 'ÿ'.  */
4693   "yfunc\377",
4694
4695   /* \377 (0xff) is Latin1 'ÿ'.  */
4696   "\377",
4697   "\377\377123",
4698
4699   /* A name with all sorts of complications.  Starts with "z" to make
4700      it easier for the completion tests below.  */
4701 #define Z_SYM_NAME \
4702   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4703     "::tuple<(anonymous namespace)::ui*, " \
4704     "std::default_delete<(anonymous namespace)::ui>, void>"
4705
4706   Z_SYM_NAME
4707 };
4708
4709 /* Returns true if the mapped_index_base::find_name_component_bounds
4710    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4711    in completion mode.  */
4712
4713 static bool
4714 check_find_bounds_finds (mapped_index_base &index,
4715                          const char *search_name,
4716                          gdb::array_view<const char *> expected_syms)
4717 {
4718   lookup_name_info lookup_name (search_name,
4719                                 symbol_name_match_type::FULL, true);
4720
4721   auto bounds = index.find_name_components_bounds (lookup_name);
4722
4723   size_t distance = std::distance (bounds.first, bounds.second);
4724   if (distance != expected_syms.size ())
4725     return false;
4726
4727   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4728     {
4729       auto nc_elem = bounds.first + exp_elem;
4730       const char *qualified = index.symbol_name_at (nc_elem->idx);
4731       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4732         return false;
4733     }
4734
4735   return true;
4736 }
4737
4738 /* Test the lower-level mapped_index::find_name_component_bounds
4739    method.  */
4740
4741 static void
4742 test_mapped_index_find_name_component_bounds ()
4743 {
4744   mock_mapped_index mock_index (test_symbols);
4745
4746   mock_index.build_name_components ();
4747
4748   /* Test the lower-level mapped_index::find_name_component_bounds
4749      method in completion mode.  */
4750   {
4751     static const char *expected_syms[] = {
4752       "t1_func",
4753       "t1_func1",
4754     };
4755
4756     SELF_CHECK (check_find_bounds_finds (mock_index,
4757                                          "t1_func", expected_syms));
4758   }
4759
4760   /* Check that the increment-last-char in the name matching algorithm
4761      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4762   {
4763     static const char *expected_syms1[] = {
4764       "\377",
4765       "\377\377123",
4766     };
4767     SELF_CHECK (check_find_bounds_finds (mock_index,
4768                                          "\377", expected_syms1));
4769
4770     static const char *expected_syms2[] = {
4771       "\377\377123",
4772     };
4773     SELF_CHECK (check_find_bounds_finds (mock_index,
4774                                          "\377\377", expected_syms2));
4775   }
4776 }
4777
4778 /* Test dw2_expand_symtabs_matching_symbol.  */
4779
4780 static void
4781 test_dw2_expand_symtabs_matching_symbol ()
4782 {
4783   mock_mapped_index mock_index (test_symbols);
4784
4785   /* We let all tests run until the end even if some fails, for debug
4786      convenience.  */
4787   bool any_mismatch = false;
4788
4789   /* Create the expected symbols list (an initializer_list).  Needed
4790      because lists have commas, and we need to pass them to CHECK,
4791      which is a macro.  */
4792 #define EXPECT(...) { __VA_ARGS__ }
4793
4794   /* Wrapper for check_match that passes down the current
4795      __FILE__/__LINE__.  */
4796 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4797   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4798                                 mock_index,                             \
4799                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4800                                 EXPECTED_LIST)
4801
4802   /* Identity checks.  */
4803   for (const char *sym : test_symbols)
4804     {
4805       /* Should be able to match all existing symbols.  */
4806       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4807                    EXPECT (sym));
4808
4809       /* Should be able to match all existing symbols with
4810          parameters.  */
4811       std::string with_params = std::string (sym) + "(int)";
4812       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4813                    EXPECT (sym));
4814
4815       /* Should be able to match all existing symbols with
4816          parameters and qualifiers.  */
4817       with_params = std::string (sym) + " ( int ) const";
4818       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4819                    EXPECT (sym));
4820
4821       /* This should really find sym, but cp-name-parser.y doesn't
4822          know about lvalue/rvalue qualifiers yet.  */
4823       with_params = std::string (sym) + " ( int ) &&";
4824       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4825                    {});
4826     }
4827
4828   /* Check that the name matching algorithm for completion doesn't get
4829      confused with Latin1 'ÿ' / 0xff.  */
4830   {
4831     static const char str[] = "\377";
4832     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4833                  EXPECT ("\377", "\377\377123"));
4834   }
4835
4836   /* Check that the increment-last-char in the matching algorithm for
4837      completion doesn't match "t1_fund" when completing "t1_func".  */
4838   {
4839     static const char str[] = "t1_func";
4840     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4841                  EXPECT ("t1_func", "t1_func1"));
4842   }
4843
4844   /* Check that completion mode works at each prefix of the expected
4845      symbol name.  */
4846   {
4847     static const char str[] = "function(int)";
4848     size_t len = strlen (str);
4849     std::string lookup;
4850
4851     for (size_t i = 1; i < len; i++)
4852       {
4853         lookup.assign (str, i);
4854         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4855                      EXPECT ("function"));
4856       }
4857   }
4858
4859   /* While "w" is a prefix of both components, the match function
4860      should still only be called once.  */
4861   {
4862     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4863                  EXPECT ("w1::w2"));
4864     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4865                  EXPECT ("w1::w2"));
4866   }
4867
4868   /* Same, with a "complicated" symbol.  */
4869   {
4870     static const char str[] = Z_SYM_NAME;
4871     size_t len = strlen (str);
4872     std::string lookup;
4873
4874     for (size_t i = 1; i < len; i++)
4875       {
4876         lookup.assign (str, i);
4877         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4878                      EXPECT (Z_SYM_NAME));
4879       }
4880   }
4881
4882   /* In FULL mode, an incomplete symbol doesn't match.  */
4883   {
4884     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4885                  {});
4886   }
4887
4888   /* A complete symbol with parameters matches any overload, since the
4889      index has no overload info.  */
4890   {
4891     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4892                  EXPECT ("std::zfunction", "std::zfunction2"));
4893     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4894                  EXPECT ("std::zfunction", "std::zfunction2"));
4895     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4896                  EXPECT ("std::zfunction", "std::zfunction2"));
4897   }
4898
4899   /* Check that whitespace is ignored appropriately.  A symbol with a
4900      template argument list. */
4901   {
4902     static const char expected[] = "ns::foo<int>";
4903     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4904                  EXPECT (expected));
4905     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4906                  EXPECT (expected));
4907   }
4908
4909   /* Check that whitespace is ignored appropriately.  A symbol with a
4910      template argument list that includes a pointer.  */
4911   {
4912     static const char expected[] = "ns::foo<char*>";
4913     /* Try both completion and non-completion modes.  */
4914     static const bool completion_mode[2] = {false, true};
4915     for (size_t i = 0; i < 2; i++)
4916       {
4917         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4918                      completion_mode[i], EXPECT (expected));
4919         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4920                      completion_mode[i], EXPECT (expected));
4921
4922         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4923                      completion_mode[i], EXPECT (expected));
4924         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4925                      completion_mode[i], EXPECT (expected));
4926       }
4927   }
4928
4929   {
4930     /* Check method qualifiers are ignored.  */
4931     static const char expected[] = "ns::foo<char*>";
4932     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4933                  symbol_name_match_type::FULL, true, EXPECT (expected));
4934     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4935                  symbol_name_match_type::FULL, true, EXPECT (expected));
4936     CHECK_MATCH ("foo < char * >  ( int ) const",
4937                  symbol_name_match_type::WILD, true, EXPECT (expected));
4938     CHECK_MATCH ("foo < char * >  ( int ) &&",
4939                  symbol_name_match_type::WILD, true, EXPECT (expected));
4940   }
4941
4942   /* Test lookup names that don't match anything.  */
4943   {
4944     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4945                  {});
4946
4947     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4948                  {});
4949   }
4950
4951   /* Some wild matching tests, exercising "(anonymous namespace)",
4952      which should not be confused with a parameter list.  */
4953   {
4954     static const char *syms[] = {
4955       "A::B::C",
4956       "B::C",
4957       "C",
4958       "A :: B :: C ( int )",
4959       "B :: C ( int )",
4960       "C ( int )",
4961     };
4962
4963     for (const char *s : syms)
4964       {
4965         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4966                      EXPECT ("(anonymous namespace)::A::B::C"));
4967       }
4968   }
4969
4970   {
4971     static const char expected[] = "ns2::tmpl<int>::foo2";
4972     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4973                  EXPECT (expected));
4974     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4975                  EXPECT (expected));
4976   }
4977
4978   SELF_CHECK (!any_mismatch);
4979
4980 #undef EXPECT
4981 #undef CHECK_MATCH
4982 }
4983
4984 static void
4985 run_test ()
4986 {
4987   test_mapped_index_find_name_component_bounds ();
4988   test_dw2_expand_symtabs_matching_symbol ();
4989 }
4990
4991 }} // namespace selftests::dw2_expand_symtabs_matching
4992
4993 #endif /* GDB_SELF_TEST */
4994
4995 /* If FILE_MATCHER is NULL or if PER_CU has
4996    dwarf2_per_cu_quick_data::MARK set (see
4997    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4998    EXPANSION_NOTIFY on it.  */
4999
5000 static void
5001 dw2_expand_symtabs_matching_one
5002   (struct dwarf2_per_cu_data *per_cu,
5003    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5004    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5005 {
5006   if (file_matcher == NULL || per_cu->v.quick->mark)
5007     {
5008       bool symtab_was_null
5009         = (per_cu->v.quick->compunit_symtab == NULL);
5010
5011       dw2_instantiate_symtab (per_cu, false);
5012
5013       if (expansion_notify != NULL
5014           && symtab_was_null
5015           && per_cu->v.quick->compunit_symtab != NULL)
5016         expansion_notify (per_cu->v.quick->compunit_symtab);
5017     }
5018 }
5019
5020 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5021    matched, to expand corresponding CUs that were marked.  IDX is the
5022    index of the symbol name that matched.  */
5023
5024 static void
5025 dw2_expand_marked_cus
5026   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5027    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5028    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5029    search_domain kind)
5030 {
5031   offset_type *vec, vec_len, vec_idx;
5032   bool global_seen = false;
5033   mapped_index &index = *dwarf2_per_objfile->index_table;
5034
5035   vec = (offset_type *) (index.constant_pool
5036                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5037   vec_len = MAYBE_SWAP (vec[0]);
5038   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5039     {
5040       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5041       /* This value is only valid for index versions >= 7.  */
5042       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5043       gdb_index_symbol_kind symbol_kind =
5044         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5045       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5046       /* Only check the symbol attributes if they're present.
5047          Indices prior to version 7 don't record them,
5048          and indices >= 7 may elide them for certain symbols
5049          (gold does this).  */
5050       int attrs_valid =
5051         (index.version >= 7
5052          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5053
5054       /* Work around gold/15646.  */
5055       if (attrs_valid)
5056         {
5057           if (!is_static && global_seen)
5058             continue;
5059           if (!is_static)
5060             global_seen = true;
5061         }
5062
5063       /* Only check the symbol's kind if it has one.  */
5064       if (attrs_valid)
5065         {
5066           switch (kind)
5067             {
5068             case VARIABLES_DOMAIN:
5069               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5070                 continue;
5071               break;
5072             case FUNCTIONS_DOMAIN:
5073               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5074                 continue;
5075               break;
5076             case TYPES_DOMAIN:
5077               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5078                 continue;
5079               break;
5080             default:
5081               break;
5082             }
5083         }
5084
5085       /* Don't crash on bad data.  */
5086       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5087                        + dwarf2_per_objfile->all_type_units.size ()))
5088         {
5089           complaint (_(".gdb_index entry has bad CU index"
5090                        " [in module %s]"),
5091                        objfile_name (dwarf2_per_objfile->objfile));
5092           continue;
5093         }
5094
5095       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5096       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5097                                        expansion_notify);
5098     }
5099 }
5100
5101 /* If FILE_MATCHER is non-NULL, set all the
5102    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5103    that match FILE_MATCHER.  */
5104
5105 static void
5106 dw_expand_symtabs_matching_file_matcher
5107   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5108    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5109 {
5110   if (file_matcher == NULL)
5111     return;
5112
5113   objfile *const objfile = dwarf2_per_objfile->objfile;
5114
5115   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5116                                             htab_eq_pointer,
5117                                             NULL, xcalloc, xfree));
5118   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5119                                                 htab_eq_pointer,
5120                                                 NULL, xcalloc, xfree));
5121
5122   /* The rule is CUs specify all the files, including those used by
5123      any TU, so there's no need to scan TUs here.  */
5124
5125   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5126     {
5127       QUIT;
5128
5129       per_cu->v.quick->mark = 0;
5130
5131       /* We only need to look at symtabs not already expanded.  */
5132       if (per_cu->v.quick->compunit_symtab)
5133         continue;
5134
5135       quick_file_names *file_data = dw2_get_file_names (per_cu);
5136       if (file_data == NULL)
5137         continue;
5138
5139       if (htab_find (visited_not_found.get (), file_data) != NULL)
5140         continue;
5141       else if (htab_find (visited_found.get (), file_data) != NULL)
5142         {
5143           per_cu->v.quick->mark = 1;
5144           continue;
5145         }
5146
5147       for (int j = 0; j < file_data->num_file_names; ++j)
5148         {
5149           const char *this_real_name;
5150
5151           if (file_matcher (file_data->file_names[j], false))
5152             {
5153               per_cu->v.quick->mark = 1;
5154               break;
5155             }
5156
5157           /* Before we invoke realpath, which can get expensive when many
5158              files are involved, do a quick comparison of the basenames.  */
5159           if (!basenames_may_differ
5160               && !file_matcher (lbasename (file_data->file_names[j]),
5161                                 true))
5162             continue;
5163
5164           this_real_name = dw2_get_real_path (objfile, file_data, j);
5165           if (file_matcher (this_real_name, false))
5166             {
5167               per_cu->v.quick->mark = 1;
5168               break;
5169             }
5170         }
5171
5172       void **slot = htab_find_slot (per_cu->v.quick->mark
5173                                     ? visited_found.get ()
5174                                     : visited_not_found.get (),
5175                                     file_data, INSERT);
5176       *slot = file_data;
5177     }
5178 }
5179
5180 static void
5181 dw2_expand_symtabs_matching
5182   (struct objfile *objfile,
5183    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5184    const lookup_name_info &lookup_name,
5185    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5186    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5187    enum search_domain kind)
5188 {
5189   struct dwarf2_per_objfile *dwarf2_per_objfile
5190     = get_dwarf2_per_objfile (objfile);
5191
5192   /* index_table is NULL if OBJF_READNOW.  */
5193   if (!dwarf2_per_objfile->index_table)
5194     return;
5195
5196   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5197
5198   mapped_index &index = *dwarf2_per_objfile->index_table;
5199
5200   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5201                                       symbol_matcher,
5202                                       kind, [&] (offset_type idx)
5203     {
5204       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5205                              expansion_notify, kind);
5206     });
5207 }
5208
5209 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5210    symtab.  */
5211
5212 static struct compunit_symtab *
5213 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5214                                           CORE_ADDR pc)
5215 {
5216   int i;
5217
5218   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5219       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5220     return cust;
5221
5222   if (cust->includes == NULL)
5223     return NULL;
5224
5225   for (i = 0; cust->includes[i]; ++i)
5226     {
5227       struct compunit_symtab *s = cust->includes[i];
5228
5229       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5230       if (s != NULL)
5231         return s;
5232     }
5233
5234   return NULL;
5235 }
5236
5237 static struct compunit_symtab *
5238 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5239                                   struct bound_minimal_symbol msymbol,
5240                                   CORE_ADDR pc,
5241                                   struct obj_section *section,
5242                                   int warn_if_readin)
5243 {
5244   struct dwarf2_per_cu_data *data;
5245   struct compunit_symtab *result;
5246
5247   if (!objfile->partial_symtabs->psymtabs_addrmap)
5248     return NULL;
5249
5250   CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
5251                                  SECT_OFF_TEXT (objfile));
5252   data = (struct dwarf2_per_cu_data *) addrmap_find
5253     (objfile->partial_symtabs->psymtabs_addrmap, pc - baseaddr);
5254   if (!data)
5255     return NULL;
5256
5257   if (warn_if_readin && data->v.quick->compunit_symtab)
5258     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5259              paddress (get_objfile_arch (objfile), pc));
5260
5261   result
5262     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5263                                                                         false),
5264                                                 pc);
5265   gdb_assert (result != NULL);
5266   return result;
5267 }
5268
5269 static void
5270 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5271                           void *data, int need_fullname)
5272 {
5273   struct dwarf2_per_objfile *dwarf2_per_objfile
5274     = get_dwarf2_per_objfile (objfile);
5275
5276   if (!dwarf2_per_objfile->filenames_cache)
5277     {
5278       dwarf2_per_objfile->filenames_cache.emplace ();
5279
5280       htab_up visited (htab_create_alloc (10,
5281                                           htab_hash_pointer, htab_eq_pointer,
5282                                           NULL, xcalloc, xfree));
5283
5284       /* The rule is CUs specify all the files, including those used
5285          by any TU, so there's no need to scan TUs here.  We can
5286          ignore file names coming from already-expanded CUs.  */
5287
5288       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5289         {
5290           if (per_cu->v.quick->compunit_symtab)
5291             {
5292               void **slot = htab_find_slot (visited.get (),
5293                                             per_cu->v.quick->file_names,
5294                                             INSERT);
5295
5296               *slot = per_cu->v.quick->file_names;
5297             }
5298         }
5299
5300       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5301         {
5302           /* We only need to look at symtabs not already expanded.  */
5303           if (per_cu->v.quick->compunit_symtab)
5304             continue;
5305
5306           quick_file_names *file_data = dw2_get_file_names (per_cu);
5307           if (file_data == NULL)
5308             continue;
5309
5310           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5311           if (*slot)
5312             {
5313               /* Already visited.  */
5314               continue;
5315             }
5316           *slot = file_data;
5317
5318           for (int j = 0; j < file_data->num_file_names; ++j)
5319             {
5320               const char *filename = file_data->file_names[j];
5321               dwarf2_per_objfile->filenames_cache->seen (filename);
5322             }
5323         }
5324     }
5325
5326   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5327     {
5328       gdb::unique_xmalloc_ptr<char> this_real_name;
5329
5330       if (need_fullname)
5331         this_real_name = gdb_realpath (filename);
5332       (*fun) (filename, this_real_name.get (), data);
5333     });
5334 }
5335
5336 static int
5337 dw2_has_symbols (struct objfile *objfile)
5338 {
5339   return 1;
5340 }
5341
5342 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5343 {
5344   dw2_has_symbols,
5345   dw2_find_last_source_symtab,
5346   dw2_forget_cached_source_info,
5347   dw2_map_symtabs_matching_filename,
5348   dw2_lookup_symbol,
5349   dw2_print_stats,
5350   dw2_dump,
5351   dw2_expand_symtabs_for_function,
5352   dw2_expand_all_symtabs,
5353   dw2_expand_symtabs_with_fullname,
5354   dw2_map_matching_symbols,
5355   dw2_expand_symtabs_matching,
5356   dw2_find_pc_sect_compunit_symtab,
5357   NULL,
5358   dw2_map_symbol_filenames
5359 };
5360
5361 /* DWARF-5 debug_names reader.  */
5362
5363 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5364 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5365
5366 /* A helper function that reads the .debug_names section in SECTION
5367    and fills in MAP.  FILENAME is the name of the file containing the
5368    section; it is used for error reporting.
5369
5370    Returns true if all went well, false otherwise.  */
5371
5372 static bool
5373 read_debug_names_from_section (struct objfile *objfile,
5374                                const char *filename,
5375                                struct dwarf2_section_info *section,
5376                                mapped_debug_names &map)
5377 {
5378   if (dwarf2_section_empty_p (section))
5379     return false;
5380
5381   /* Older elfutils strip versions could keep the section in the main
5382      executable while splitting it for the separate debug info file.  */
5383   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5384     return false;
5385
5386   dwarf2_read_section (objfile, section);
5387
5388   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5389
5390   const gdb_byte *addr = section->buffer;
5391
5392   bfd *const abfd = get_section_bfd_owner (section);
5393
5394   unsigned int bytes_read;
5395   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5396   addr += bytes_read;
5397
5398   map.dwarf5_is_dwarf64 = bytes_read != 4;
5399   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5400   if (bytes_read + length != section->size)
5401     {
5402       /* There may be multiple per-CU indices.  */
5403       warning (_("Section .debug_names in %s length %s does not match "
5404                  "section length %s, ignoring .debug_names."),
5405                filename, plongest (bytes_read + length),
5406                pulongest (section->size));
5407       return false;
5408     }
5409
5410   /* The version number.  */
5411   uint16_t version = read_2_bytes (abfd, addr);
5412   addr += 2;
5413   if (version != 5)
5414     {
5415       warning (_("Section .debug_names in %s has unsupported version %d, "
5416                  "ignoring .debug_names."),
5417                filename, version);
5418       return false;
5419     }
5420
5421   /* Padding.  */
5422   uint16_t padding = read_2_bytes (abfd, addr);
5423   addr += 2;
5424   if (padding != 0)
5425     {
5426       warning (_("Section .debug_names in %s has unsupported padding %d, "
5427                  "ignoring .debug_names."),
5428                filename, padding);
5429       return false;
5430     }
5431
5432   /* comp_unit_count - The number of CUs in the CU list.  */
5433   map.cu_count = read_4_bytes (abfd, addr);
5434   addr += 4;
5435
5436   /* local_type_unit_count - The number of TUs in the local TU
5437      list.  */
5438   map.tu_count = read_4_bytes (abfd, addr);
5439   addr += 4;
5440
5441   /* foreign_type_unit_count - The number of TUs in the foreign TU
5442      list.  */
5443   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5444   addr += 4;
5445   if (foreign_tu_count != 0)
5446     {
5447       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5448                  "ignoring .debug_names."),
5449                filename, static_cast<unsigned long> (foreign_tu_count));
5450       return false;
5451     }
5452
5453   /* bucket_count - The number of hash buckets in the hash lookup
5454      table.  */
5455   map.bucket_count = read_4_bytes (abfd, addr);
5456   addr += 4;
5457
5458   /* name_count - The number of unique names in the index.  */
5459   map.name_count = read_4_bytes (abfd, addr);
5460   addr += 4;
5461
5462   /* abbrev_table_size - The size in bytes of the abbreviations
5463      table.  */
5464   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5465   addr += 4;
5466
5467   /* augmentation_string_size - The size in bytes of the augmentation
5468      string.  This value is rounded up to a multiple of 4.  */
5469   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5470   addr += 4;
5471   map.augmentation_is_gdb = ((augmentation_string_size
5472                               == sizeof (dwarf5_augmentation))
5473                              && memcmp (addr, dwarf5_augmentation,
5474                                         sizeof (dwarf5_augmentation)) == 0);
5475   augmentation_string_size += (-augmentation_string_size) & 3;
5476   addr += augmentation_string_size;
5477
5478   /* List of CUs */
5479   map.cu_table_reordered = addr;
5480   addr += map.cu_count * map.offset_size;
5481
5482   /* List of Local TUs */
5483   map.tu_table_reordered = addr;
5484   addr += map.tu_count * map.offset_size;
5485
5486   /* Hash Lookup Table */
5487   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5488   addr += map.bucket_count * 4;
5489   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5490   addr += map.name_count * 4;
5491
5492   /* Name Table */
5493   map.name_table_string_offs_reordered = addr;
5494   addr += map.name_count * map.offset_size;
5495   map.name_table_entry_offs_reordered = addr;
5496   addr += map.name_count * map.offset_size;
5497
5498   const gdb_byte *abbrev_table_start = addr;
5499   for (;;)
5500     {
5501       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5502       addr += bytes_read;
5503       if (index_num == 0)
5504         break;
5505
5506       const auto insertpair
5507         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5508       if (!insertpair.second)
5509         {
5510           warning (_("Section .debug_names in %s has duplicate index %s, "
5511                      "ignoring .debug_names."),
5512                    filename, pulongest (index_num));
5513           return false;
5514         }
5515       mapped_debug_names::index_val &indexval = insertpair.first->second;
5516       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5517       addr += bytes_read;
5518
5519       for (;;)
5520         {
5521           mapped_debug_names::index_val::attr attr;
5522           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5523           addr += bytes_read;
5524           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5525           addr += bytes_read;
5526           if (attr.form == DW_FORM_implicit_const)
5527             {
5528               attr.implicit_const = read_signed_leb128 (abfd, addr,
5529                                                         &bytes_read);
5530               addr += bytes_read;
5531             }
5532           if (attr.dw_idx == 0 && attr.form == 0)
5533             break;
5534           indexval.attr_vec.push_back (std::move (attr));
5535         }
5536     }
5537   if (addr != abbrev_table_start + abbrev_table_size)
5538     {
5539       warning (_("Section .debug_names in %s has abbreviation_table "
5540                  "of size %zu vs. written as %u, ignoring .debug_names."),
5541                filename, addr - abbrev_table_start, abbrev_table_size);
5542       return false;
5543     }
5544   map.entry_pool = addr;
5545
5546   return true;
5547 }
5548
5549 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5550    list.  */
5551
5552 static void
5553 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5554                                   const mapped_debug_names &map,
5555                                   dwarf2_section_info &section,
5556                                   bool is_dwz)
5557 {
5558   sect_offset sect_off_prev;
5559   for (uint32_t i = 0; i <= map.cu_count; ++i)
5560     {
5561       sect_offset sect_off_next;
5562       if (i < map.cu_count)
5563         {
5564           sect_off_next
5565             = (sect_offset) (extract_unsigned_integer
5566                              (map.cu_table_reordered + i * map.offset_size,
5567                               map.offset_size,
5568                               map.dwarf5_byte_order));
5569         }
5570       else
5571         sect_off_next = (sect_offset) section.size;
5572       if (i >= 1)
5573         {
5574           const ULONGEST length = sect_off_next - sect_off_prev;
5575           dwarf2_per_cu_data *per_cu
5576             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5577                                          sect_off_prev, length);
5578           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5579         }
5580       sect_off_prev = sect_off_next;
5581     }
5582 }
5583
5584 /* Read the CU list from the mapped index, and use it to create all
5585    the CU objects for this dwarf2_per_objfile.  */
5586
5587 static void
5588 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5589                              const mapped_debug_names &map,
5590                              const mapped_debug_names &dwz_map)
5591 {
5592   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5593   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5594
5595   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5596                                     dwarf2_per_objfile->info,
5597                                     false /* is_dwz */);
5598
5599   if (dwz_map.cu_count == 0)
5600     return;
5601
5602   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5603   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5604                                     true /* is_dwz */);
5605 }
5606
5607 /* Read .debug_names.  If everything went ok, initialize the "quick"
5608    elements of all the CUs and return true.  Otherwise, return false.  */
5609
5610 static bool
5611 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5612 {
5613   std::unique_ptr<mapped_debug_names> map
5614     (new mapped_debug_names (dwarf2_per_objfile));
5615   mapped_debug_names dwz_map (dwarf2_per_objfile);
5616   struct objfile *objfile = dwarf2_per_objfile->objfile;
5617
5618   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5619                                       &dwarf2_per_objfile->debug_names,
5620                                       *map))
5621     return false;
5622
5623   /* Don't use the index if it's empty.  */
5624   if (map->name_count == 0)
5625     return false;
5626
5627   /* If there is a .dwz file, read it so we can get its CU list as
5628      well.  */
5629   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5630   if (dwz != NULL)
5631     {
5632       if (!read_debug_names_from_section (objfile,
5633                                           bfd_get_filename (dwz->dwz_bfd),
5634                                           &dwz->debug_names, dwz_map))
5635         {
5636           warning (_("could not read '.debug_names' section from %s; skipping"),
5637                    bfd_get_filename (dwz->dwz_bfd));
5638           return false;
5639         }
5640     }
5641
5642   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5643
5644   if (map->tu_count != 0)
5645     {
5646       /* We can only handle a single .debug_types when we have an
5647          index.  */
5648       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5649         return false;
5650
5651       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5652                                                 dwarf2_per_objfile->types, 0);
5653
5654       create_signatured_type_table_from_debug_names
5655         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5656     }
5657
5658   create_addrmap_from_aranges (dwarf2_per_objfile,
5659                                &dwarf2_per_objfile->debug_aranges);
5660
5661   dwarf2_per_objfile->debug_names_table = std::move (map);
5662   dwarf2_per_objfile->using_index = 1;
5663   dwarf2_per_objfile->quick_file_names_table =
5664     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5665
5666   return true;
5667 }
5668
5669 /* Type used to manage iterating over all CUs looking for a symbol for
5670    .debug_names.  */
5671
5672 class dw2_debug_names_iterator
5673 {
5674 public:
5675   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5676      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5677   dw2_debug_names_iterator (const mapped_debug_names &map,
5678                             bool want_specific_block,
5679                             block_enum block_index, domain_enum domain,
5680                             const char *name)
5681     : m_map (map), m_want_specific_block (want_specific_block),
5682       m_block_index (block_index), m_domain (domain),
5683       m_addr (find_vec_in_debug_names (map, name))
5684   {}
5685
5686   dw2_debug_names_iterator (const mapped_debug_names &map,
5687                             search_domain search, uint32_t namei)
5688     : m_map (map),
5689       m_search (search),
5690       m_addr (find_vec_in_debug_names (map, namei))
5691   {}
5692
5693   /* Return the next matching CU or NULL if there are no more.  */
5694   dwarf2_per_cu_data *next ();
5695
5696 private:
5697   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5698                                                   const char *name);
5699   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5700                                                   uint32_t namei);
5701
5702   /* The internalized form of .debug_names.  */
5703   const mapped_debug_names &m_map;
5704
5705   /* If true, only look for symbols that match BLOCK_INDEX.  */
5706   const bool m_want_specific_block = false;
5707
5708   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5709      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5710      value.  */
5711   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5712
5713   /* The kind of symbol we're looking for.  */
5714   const domain_enum m_domain = UNDEF_DOMAIN;
5715   const search_domain m_search = ALL_DOMAIN;
5716
5717   /* The list of CUs from the index entry of the symbol, or NULL if
5718      not found.  */
5719   const gdb_byte *m_addr;
5720 };
5721
5722 const char *
5723 mapped_debug_names::namei_to_name (uint32_t namei) const
5724 {
5725   const ULONGEST namei_string_offs
5726     = extract_unsigned_integer ((name_table_string_offs_reordered
5727                                  + namei * offset_size),
5728                                 offset_size,
5729                                 dwarf5_byte_order);
5730   return read_indirect_string_at_offset
5731     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5732 }
5733
5734 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5735    found, return pointer to its pool data.  If NAME cannot be found,
5736    return NULL.  */
5737
5738 const gdb_byte *
5739 dw2_debug_names_iterator::find_vec_in_debug_names
5740   (const mapped_debug_names &map, const char *name)
5741 {
5742   int (*cmp) (const char *, const char *);
5743
5744   if (current_language->la_language == language_cplus
5745       || current_language->la_language == language_fortran
5746       || current_language->la_language == language_d)
5747     {
5748       /* NAME is already canonical.  Drop any qualifiers as
5749          .debug_names does not contain any.  */
5750
5751       if (strchr (name, '(') != NULL)
5752         {
5753           gdb::unique_xmalloc_ptr<char> without_params
5754             = cp_remove_params (name);
5755
5756           if (without_params != NULL)
5757             {
5758               name = without_params.get();
5759             }
5760         }
5761     }
5762
5763   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5764
5765   const uint32_t full_hash = dwarf5_djb_hash (name);
5766   uint32_t namei
5767     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5768                                 (map.bucket_table_reordered
5769                                  + (full_hash % map.bucket_count)), 4,
5770                                 map.dwarf5_byte_order);
5771   if (namei == 0)
5772     return NULL;
5773   --namei;
5774   if (namei >= map.name_count)
5775     {
5776       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5777                    "[in module %s]"),
5778                  namei, map.name_count,
5779                  objfile_name (map.dwarf2_per_objfile->objfile));
5780       return NULL;
5781     }
5782
5783   for (;;)
5784     {
5785       const uint32_t namei_full_hash
5786         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5787                                     (map.hash_table_reordered + namei), 4,
5788                                     map.dwarf5_byte_order);
5789       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5790         return NULL;
5791
5792       if (full_hash == namei_full_hash)
5793         {
5794           const char *const namei_string = map.namei_to_name (namei);
5795
5796 #if 0 /* An expensive sanity check.  */
5797           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5798             {
5799               complaint (_("Wrong .debug_names hash for string at index %u "
5800                            "[in module %s]"),
5801                          namei, objfile_name (dwarf2_per_objfile->objfile));
5802               return NULL;
5803             }
5804 #endif
5805
5806           if (cmp (namei_string, name) == 0)
5807             {
5808               const ULONGEST namei_entry_offs
5809                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5810                                              + namei * map.offset_size),
5811                                             map.offset_size, map.dwarf5_byte_order);
5812               return map.entry_pool + namei_entry_offs;
5813             }
5814         }
5815
5816       ++namei;
5817       if (namei >= map.name_count)
5818         return NULL;
5819     }
5820 }
5821
5822 const gdb_byte *
5823 dw2_debug_names_iterator::find_vec_in_debug_names
5824   (const mapped_debug_names &map, uint32_t namei)
5825 {
5826   if (namei >= map.name_count)
5827     {
5828       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5829                    "[in module %s]"),
5830                  namei, map.name_count,
5831                  objfile_name (map.dwarf2_per_objfile->objfile));
5832       return NULL;
5833     }
5834
5835   const ULONGEST namei_entry_offs
5836     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5837                                  + namei * map.offset_size),
5838                                 map.offset_size, map.dwarf5_byte_order);
5839   return map.entry_pool + namei_entry_offs;
5840 }
5841
5842 /* See dw2_debug_names_iterator.  */
5843
5844 dwarf2_per_cu_data *
5845 dw2_debug_names_iterator::next ()
5846 {
5847   if (m_addr == NULL)
5848     return NULL;
5849
5850   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5851   struct objfile *objfile = dwarf2_per_objfile->objfile;
5852   bfd *const abfd = objfile->obfd;
5853
5854  again:
5855
5856   unsigned int bytes_read;
5857   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5858   m_addr += bytes_read;
5859   if (abbrev == 0)
5860     return NULL;
5861
5862   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5863   if (indexval_it == m_map.abbrev_map.cend ())
5864     {
5865       complaint (_("Wrong .debug_names undefined abbrev code %s "
5866                    "[in module %s]"),
5867                  pulongest (abbrev), objfile_name (objfile));
5868       return NULL;
5869     }
5870   const mapped_debug_names::index_val &indexval = indexval_it->second;
5871   bool have_is_static = false;
5872   bool is_static;
5873   dwarf2_per_cu_data *per_cu = NULL;
5874   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5875     {
5876       ULONGEST ull;
5877       switch (attr.form)
5878         {
5879         case DW_FORM_implicit_const:
5880           ull = attr.implicit_const;
5881           break;
5882         case DW_FORM_flag_present:
5883           ull = 1;
5884           break;
5885         case DW_FORM_udata:
5886           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5887           m_addr += bytes_read;
5888           break;
5889         default:
5890           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5891                      dwarf_form_name (attr.form),
5892                      objfile_name (objfile));
5893           return NULL;
5894         }
5895       switch (attr.dw_idx)
5896         {
5897         case DW_IDX_compile_unit:
5898           /* Don't crash on bad data.  */
5899           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5900             {
5901               complaint (_(".debug_names entry has bad CU index %s"
5902                            " [in module %s]"),
5903                          pulongest (ull),
5904                          objfile_name (dwarf2_per_objfile->objfile));
5905               continue;
5906             }
5907           per_cu = dwarf2_per_objfile->get_cutu (ull);
5908           break;
5909         case DW_IDX_type_unit:
5910           /* Don't crash on bad data.  */
5911           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5912             {
5913               complaint (_(".debug_names entry has bad TU index %s"
5914                            " [in module %s]"),
5915                          pulongest (ull),
5916                          objfile_name (dwarf2_per_objfile->objfile));
5917               continue;
5918             }
5919           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5920           break;
5921         case DW_IDX_GNU_internal:
5922           if (!m_map.augmentation_is_gdb)
5923             break;
5924           have_is_static = true;
5925           is_static = true;
5926           break;
5927         case DW_IDX_GNU_external:
5928           if (!m_map.augmentation_is_gdb)
5929             break;
5930           have_is_static = true;
5931           is_static = false;
5932           break;
5933         }
5934     }
5935
5936   /* Skip if already read in.  */
5937   if (per_cu->v.quick->compunit_symtab)
5938     goto again;
5939
5940   /* Check static vs global.  */
5941   if (have_is_static)
5942     {
5943       const bool want_static = m_block_index != GLOBAL_BLOCK;
5944       if (m_want_specific_block && want_static != is_static)
5945         goto again;
5946     }
5947
5948   /* Match dw2_symtab_iter_next, symbol_kind
5949      and debug_names::psymbol_tag.  */
5950   switch (m_domain)
5951     {
5952     case VAR_DOMAIN:
5953       switch (indexval.dwarf_tag)
5954         {
5955         case DW_TAG_variable:
5956         case DW_TAG_subprogram:
5957         /* Some types are also in VAR_DOMAIN.  */
5958         case DW_TAG_typedef:
5959         case DW_TAG_structure_type:
5960           break;
5961         default:
5962           goto again;
5963         }
5964       break;
5965     case STRUCT_DOMAIN:
5966       switch (indexval.dwarf_tag)
5967         {
5968         case DW_TAG_typedef:
5969         case DW_TAG_structure_type:
5970           break;
5971         default:
5972           goto again;
5973         }
5974       break;
5975     case LABEL_DOMAIN:
5976       switch (indexval.dwarf_tag)
5977         {
5978         case 0:
5979         case DW_TAG_variable:
5980           break;
5981         default:
5982           goto again;
5983         }
5984       break;
5985     default:
5986       break;
5987     }
5988
5989   /* Match dw2_expand_symtabs_matching, symbol_kind and
5990      debug_names::psymbol_tag.  */
5991   switch (m_search)
5992     {
5993     case VARIABLES_DOMAIN:
5994       switch (indexval.dwarf_tag)
5995         {
5996         case DW_TAG_variable:
5997           break;
5998         default:
5999           goto again;
6000         }
6001       break;
6002     case FUNCTIONS_DOMAIN:
6003       switch (indexval.dwarf_tag)
6004         {
6005         case DW_TAG_subprogram:
6006           break;
6007         default:
6008           goto again;
6009         }
6010       break;
6011     case TYPES_DOMAIN:
6012       switch (indexval.dwarf_tag)
6013         {
6014         case DW_TAG_typedef:
6015         case DW_TAG_structure_type:
6016           break;
6017         default:
6018           goto again;
6019         }
6020       break;
6021     default:
6022       break;
6023     }
6024
6025   return per_cu;
6026 }
6027
6028 static struct compunit_symtab *
6029 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6030                                const char *name, domain_enum domain)
6031 {
6032   const block_enum block_index = static_cast<block_enum> (block_index_int);
6033   struct dwarf2_per_objfile *dwarf2_per_objfile
6034     = get_dwarf2_per_objfile (objfile);
6035
6036   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6037   if (!mapp)
6038     {
6039       /* index is NULL if OBJF_READNOW.  */
6040       return NULL;
6041     }
6042   const auto &map = *mapp;
6043
6044   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6045                                  block_index, domain, name);
6046
6047   struct compunit_symtab *stab_best = NULL;
6048   struct dwarf2_per_cu_data *per_cu;
6049   while ((per_cu = iter.next ()) != NULL)
6050     {
6051       struct symbol *sym, *with_opaque = NULL;
6052       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6053       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6054       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6055
6056       sym = block_find_symbol (block, name, domain,
6057                                block_find_non_opaque_type_preferred,
6058                                &with_opaque);
6059
6060       /* Some caution must be observed with overloaded functions and
6061          methods, since the index will not contain any overload
6062          information (but NAME might contain it).  */
6063
6064       if (sym != NULL
6065           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6066         return stab;
6067       if (with_opaque != NULL
6068           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6069         stab_best = stab;
6070
6071       /* Keep looking through other CUs.  */
6072     }
6073
6074   return stab_best;
6075 }
6076
6077 /* This dumps minimal information about .debug_names.  It is called
6078    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6079    uses this to verify that .debug_names has been loaded.  */
6080
6081 static void
6082 dw2_debug_names_dump (struct objfile *objfile)
6083 {
6084   struct dwarf2_per_objfile *dwarf2_per_objfile
6085     = get_dwarf2_per_objfile (objfile);
6086
6087   gdb_assert (dwarf2_per_objfile->using_index);
6088   printf_filtered (".debug_names:");
6089   if (dwarf2_per_objfile->debug_names_table)
6090     printf_filtered (" exists\n");
6091   else
6092     printf_filtered (" faked for \"readnow\"\n");
6093   printf_filtered ("\n");
6094 }
6095
6096 static void
6097 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6098                                              const char *func_name)
6099 {
6100   struct dwarf2_per_objfile *dwarf2_per_objfile
6101     = get_dwarf2_per_objfile (objfile);
6102
6103   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6104   if (dwarf2_per_objfile->debug_names_table)
6105     {
6106       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6107
6108       /* Note: It doesn't matter what we pass for block_index here.  */
6109       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6110                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6111
6112       struct dwarf2_per_cu_data *per_cu;
6113       while ((per_cu = iter.next ()) != NULL)
6114         dw2_instantiate_symtab (per_cu, false);
6115     }
6116 }
6117
6118 static void
6119 dw2_debug_names_expand_symtabs_matching
6120   (struct objfile *objfile,
6121    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6122    const lookup_name_info &lookup_name,
6123    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6124    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6125    enum search_domain kind)
6126 {
6127   struct dwarf2_per_objfile *dwarf2_per_objfile
6128     = get_dwarf2_per_objfile (objfile);
6129
6130   /* debug_names_table is NULL if OBJF_READNOW.  */
6131   if (!dwarf2_per_objfile->debug_names_table)
6132     return;
6133
6134   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6135
6136   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6137
6138   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6139                                       symbol_matcher,
6140                                       kind, [&] (offset_type namei)
6141     {
6142       /* The name was matched, now expand corresponding CUs that were
6143          marked.  */
6144       dw2_debug_names_iterator iter (map, kind, namei);
6145
6146       struct dwarf2_per_cu_data *per_cu;
6147       while ((per_cu = iter.next ()) != NULL)
6148         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6149                                          expansion_notify);
6150     });
6151 }
6152
6153 const struct quick_symbol_functions dwarf2_debug_names_functions =
6154 {
6155   dw2_has_symbols,
6156   dw2_find_last_source_symtab,
6157   dw2_forget_cached_source_info,
6158   dw2_map_symtabs_matching_filename,
6159   dw2_debug_names_lookup_symbol,
6160   dw2_print_stats,
6161   dw2_debug_names_dump,
6162   dw2_debug_names_expand_symtabs_for_function,
6163   dw2_expand_all_symtabs,
6164   dw2_expand_symtabs_with_fullname,
6165   dw2_map_matching_symbols,
6166   dw2_debug_names_expand_symtabs_matching,
6167   dw2_find_pc_sect_compunit_symtab,
6168   NULL,
6169   dw2_map_symbol_filenames
6170 };
6171
6172 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
6173    to either a dwarf2_per_objfile or dwz_file object.  */
6174
6175 template <typename T>
6176 static gdb::array_view<const gdb_byte>
6177 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
6178 {
6179   dwarf2_section_info *section = &section_owner->gdb_index;
6180
6181   if (dwarf2_section_empty_p (section))
6182     return {};
6183
6184   /* Older elfutils strip versions could keep the section in the main
6185      executable while splitting it for the separate debug info file.  */
6186   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
6187     return {};
6188
6189   dwarf2_read_section (obj, section);
6190
6191   /* dwarf2_section_info::size is a bfd_size_type, while
6192      gdb::array_view works with size_t.  On 32-bit hosts, with
6193      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
6194      is 32-bit.  So we need an explicit narrowing conversion here.
6195      This is fine, because it's impossible to allocate or mmap an
6196      array/buffer larger than what size_t can represent.  */
6197   return gdb::make_array_view (section->buffer, section->size);
6198 }
6199
6200 /* Lookup the index cache for the contents of the index associated to
6201    DWARF2_OBJ.  */
6202
6203 static gdb::array_view<const gdb_byte>
6204 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_objfile *dwarf2_obj)
6205 {
6206   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
6207   if (build_id == nullptr)
6208     return {};
6209
6210   return global_index_cache.lookup_gdb_index (build_id,
6211                                               &dwarf2_obj->index_cache_res);
6212 }
6213
6214 /* Same as the above, but for DWZ.  */
6215
6216 static gdb::array_view<const gdb_byte>
6217 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
6218 {
6219   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
6220   if (build_id == nullptr)
6221     return {};
6222
6223   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
6224 }
6225
6226 /* See symfile.h.  */
6227
6228 bool
6229 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6230 {
6231   struct dwarf2_per_objfile *dwarf2_per_objfile
6232     = get_dwarf2_per_objfile (objfile);
6233
6234   /* If we're about to read full symbols, don't bother with the
6235      indices.  In this case we also don't care if some other debug
6236      format is making psymtabs, because they are all about to be
6237      expanded anyway.  */
6238   if ((objfile->flags & OBJF_READNOW))
6239     {
6240       dwarf2_per_objfile->using_index = 1;
6241       create_all_comp_units (dwarf2_per_objfile);
6242       create_all_type_units (dwarf2_per_objfile);
6243       dwarf2_per_objfile->quick_file_names_table
6244         = create_quick_file_names_table
6245             (dwarf2_per_objfile->all_comp_units.size ());
6246
6247       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6248                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6249         {
6250           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6251
6252           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6253                                             struct dwarf2_per_cu_quick_data);
6254         }
6255
6256       /* Return 1 so that gdb sees the "quick" functions.  However,
6257          these functions will be no-ops because we will have expanded
6258          all symtabs.  */
6259       *index_kind = dw_index_kind::GDB_INDEX;
6260       return true;
6261     }
6262
6263   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6264     {
6265       *index_kind = dw_index_kind::DEBUG_NAMES;
6266       return true;
6267     }
6268
6269   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6270                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
6271                              get_gdb_index_contents_from_section<dwz_file>))
6272     {
6273       *index_kind = dw_index_kind::GDB_INDEX;
6274       return true;
6275     }
6276
6277   /* ... otherwise, try to find the index in the index cache.  */
6278   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6279                              get_gdb_index_contents_from_cache,
6280                              get_gdb_index_contents_from_cache_dwz))
6281     {
6282       global_index_cache.hit ();
6283       *index_kind = dw_index_kind::GDB_INDEX;
6284       return true;
6285     }
6286
6287   global_index_cache.miss ();
6288   return false;
6289 }
6290
6291 \f
6292
6293 /* Build a partial symbol table.  */
6294
6295 void
6296 dwarf2_build_psymtabs (struct objfile *objfile)
6297 {
6298   struct dwarf2_per_objfile *dwarf2_per_objfile
6299     = get_dwarf2_per_objfile (objfile);
6300
6301   init_psymbol_list (objfile, 1024);
6302
6303   try
6304     {
6305       /* This isn't really ideal: all the data we allocate on the
6306          objfile's obstack is still uselessly kept around.  However,
6307          freeing it seems unsafe.  */
6308       psymtab_discarder psymtabs (objfile);
6309       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6310       psymtabs.keep ();
6311
6312       /* (maybe) store an index in the cache.  */
6313       global_index_cache.store (dwarf2_per_objfile);
6314     }
6315   catch (const gdb_exception_error &except)
6316     {
6317       exception_print (gdb_stderr, except);
6318     }
6319 }
6320
6321 /* Return the total length of the CU described by HEADER.  */
6322
6323 static unsigned int
6324 get_cu_length (const struct comp_unit_head *header)
6325 {
6326   return header->initial_length_size + header->length;
6327 }
6328
6329 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6330
6331 static inline bool
6332 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6333 {
6334   sect_offset bottom = cu_header->sect_off;
6335   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6336
6337   return sect_off >= bottom && sect_off < top;
6338 }
6339
6340 /* Find the base address of the compilation unit for range lists and
6341    location lists.  It will normally be specified by DW_AT_low_pc.
6342    In DWARF-3 draft 4, the base address could be overridden by
6343    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6344    compilation units with discontinuous ranges.  */
6345
6346 static void
6347 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6348 {
6349   struct attribute *attr;
6350
6351   cu->base_known = 0;
6352   cu->base_address = 0;
6353
6354   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6355   if (attr)
6356     {
6357       cu->base_address = attr_value_as_address (attr);
6358       cu->base_known = 1;
6359     }
6360   else
6361     {
6362       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6363       if (attr)
6364         {
6365           cu->base_address = attr_value_as_address (attr);
6366           cu->base_known = 1;
6367         }
6368     }
6369 }
6370
6371 /* Read in the comp unit header information from the debug_info at info_ptr.
6372    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6373    NOTE: This leaves members offset, first_die_offset to be filled in
6374    by the caller.  */
6375
6376 static const gdb_byte *
6377 read_comp_unit_head (struct comp_unit_head *cu_header,
6378                      const gdb_byte *info_ptr,
6379                      struct dwarf2_section_info *section,
6380                      rcuh_kind section_kind)
6381 {
6382   int signed_addr;
6383   unsigned int bytes_read;
6384   const char *filename = get_section_file_name (section);
6385   bfd *abfd = get_section_bfd_owner (section);
6386
6387   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6388   cu_header->initial_length_size = bytes_read;
6389   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6390   info_ptr += bytes_read;
6391   cu_header->version = read_2_bytes (abfd, info_ptr);
6392   if (cu_header->version < 2 || cu_header->version > 5)
6393     error (_("Dwarf Error: wrong version in compilation unit header "
6394            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6395            cu_header->version, filename);
6396   info_ptr += 2;
6397   if (cu_header->version < 5)
6398     switch (section_kind)
6399       {
6400       case rcuh_kind::COMPILE:
6401         cu_header->unit_type = DW_UT_compile;
6402         break;
6403       case rcuh_kind::TYPE:
6404         cu_header->unit_type = DW_UT_type;
6405         break;
6406       default:
6407         internal_error (__FILE__, __LINE__,
6408                         _("read_comp_unit_head: invalid section_kind"));
6409       }
6410   else
6411     {
6412       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6413                                                  (read_1_byte (abfd, info_ptr));
6414       info_ptr += 1;
6415       switch (cu_header->unit_type)
6416         {
6417         case DW_UT_compile:
6418           if (section_kind != rcuh_kind::COMPILE)
6419             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6420                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6421                    filename);
6422           break;
6423         case DW_UT_type:
6424           section_kind = rcuh_kind::TYPE;
6425           break;
6426         default:
6427           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6428                  "(is %d, should be %d or %d) [in module %s]"),
6429                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6430         }
6431
6432       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6433       info_ptr += 1;
6434     }
6435   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6436                                                           cu_header,
6437                                                           &bytes_read);
6438   info_ptr += bytes_read;
6439   if (cu_header->version < 5)
6440     {
6441       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6442       info_ptr += 1;
6443     }
6444   signed_addr = bfd_get_sign_extend_vma (abfd);
6445   if (signed_addr < 0)
6446     internal_error (__FILE__, __LINE__,
6447                     _("read_comp_unit_head: dwarf from non elf file"));
6448   cu_header->signed_addr_p = signed_addr;
6449
6450   if (section_kind == rcuh_kind::TYPE)
6451     {
6452       LONGEST type_offset;
6453
6454       cu_header->signature = read_8_bytes (abfd, info_ptr);
6455       info_ptr += 8;
6456
6457       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6458       info_ptr += bytes_read;
6459       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6460       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6461         error (_("Dwarf Error: Too big type_offset in compilation unit "
6462                "header (is %s) [in module %s]"), plongest (type_offset),
6463                filename);
6464     }
6465
6466   return info_ptr;
6467 }
6468
6469 /* Helper function that returns the proper abbrev section for
6470    THIS_CU.  */
6471
6472 static struct dwarf2_section_info *
6473 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6474 {
6475   struct dwarf2_section_info *abbrev;
6476   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6477
6478   if (this_cu->is_dwz)
6479     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6480   else
6481     abbrev = &dwarf2_per_objfile->abbrev;
6482
6483   return abbrev;
6484 }
6485
6486 /* Subroutine of read_and_check_comp_unit_head and
6487    read_and_check_type_unit_head to simplify them.
6488    Perform various error checking on the header.  */
6489
6490 static void
6491 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6492                             struct comp_unit_head *header,
6493                             struct dwarf2_section_info *section,
6494                             struct dwarf2_section_info *abbrev_section)
6495 {
6496   const char *filename = get_section_file_name (section);
6497
6498   if (to_underlying (header->abbrev_sect_off)
6499       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6500     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6501            "(offset %s + 6) [in module %s]"),
6502            sect_offset_str (header->abbrev_sect_off),
6503            sect_offset_str (header->sect_off),
6504            filename);
6505
6506   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6507      avoid potential 32-bit overflow.  */
6508   if (((ULONGEST) header->sect_off + get_cu_length (header))
6509       > section->size)
6510     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6511            "(offset %s + 0) [in module %s]"),
6512            header->length, sect_offset_str (header->sect_off),
6513            filename);
6514 }
6515
6516 /* Read in a CU/TU header and perform some basic error checking.
6517    The contents of the header are stored in HEADER.
6518    The result is a pointer to the start of the first DIE.  */
6519
6520 static const gdb_byte *
6521 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6522                                struct comp_unit_head *header,
6523                                struct dwarf2_section_info *section,
6524                                struct dwarf2_section_info *abbrev_section,
6525                                const gdb_byte *info_ptr,
6526                                rcuh_kind section_kind)
6527 {
6528   const gdb_byte *beg_of_comp_unit = info_ptr;
6529
6530   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6531
6532   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6533
6534   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6535
6536   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6537                               abbrev_section);
6538
6539   return info_ptr;
6540 }
6541
6542 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6543
6544 static sect_offset
6545 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6546                     struct dwarf2_section_info *section,
6547                     sect_offset sect_off)
6548 {
6549   bfd *abfd = get_section_bfd_owner (section);
6550   const gdb_byte *info_ptr;
6551   unsigned int initial_length_size, offset_size;
6552   uint16_t version;
6553
6554   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6555   info_ptr = section->buffer + to_underlying (sect_off);
6556   read_initial_length (abfd, info_ptr, &initial_length_size);
6557   offset_size = initial_length_size == 4 ? 4 : 8;
6558   info_ptr += initial_length_size;
6559
6560   version = read_2_bytes (abfd, info_ptr);
6561   info_ptr += 2;
6562   if (version >= 5)
6563     {
6564       /* Skip unit type and address size.  */
6565       info_ptr += 2;
6566     }
6567
6568   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6569 }
6570
6571 /* Allocate a new partial symtab for file named NAME and mark this new
6572    partial symtab as being an include of PST.  */
6573
6574 static void
6575 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6576                                struct objfile *objfile)
6577 {
6578   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6579
6580   if (!IS_ABSOLUTE_PATH (subpst->filename))
6581     {
6582       /* It shares objfile->objfile_obstack.  */
6583       subpst->dirname = pst->dirname;
6584     }
6585
6586   subpst->dependencies = objfile->partial_symtabs->allocate_dependencies (1);
6587   subpst->dependencies[0] = pst;
6588   subpst->number_of_dependencies = 1;
6589
6590   subpst->read_symtab = pst->read_symtab;
6591
6592   /* No private part is necessary for include psymtabs.  This property
6593      can be used to differentiate between such include psymtabs and
6594      the regular ones.  */
6595   subpst->read_symtab_private = NULL;
6596 }
6597
6598 /* Read the Line Number Program data and extract the list of files
6599    included by the source file represented by PST.  Build an include
6600    partial symtab for each of these included files.  */
6601
6602 static void
6603 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6604                                struct die_info *die,
6605                                struct partial_symtab *pst)
6606 {
6607   line_header_up lh;
6608   struct attribute *attr;
6609
6610   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6611   if (attr)
6612     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6613   if (lh == NULL)
6614     return;  /* No linetable, so no includes.  */
6615
6616   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6617      that we pass in the raw text_low here; that is ok because we're
6618      only decoding the line table to make include partial symtabs, and
6619      so the addresses aren't really used.  */
6620   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6621                       pst->raw_text_low (), 1);
6622 }
6623
6624 static hashval_t
6625 hash_signatured_type (const void *item)
6626 {
6627   const struct signatured_type *sig_type
6628     = (const struct signatured_type *) item;
6629
6630   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6631   return sig_type->signature;
6632 }
6633
6634 static int
6635 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6636 {
6637   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6638   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6639
6640   return lhs->signature == rhs->signature;
6641 }
6642
6643 /* Allocate a hash table for signatured types.  */
6644
6645 static htab_t
6646 allocate_signatured_type_table (struct objfile *objfile)
6647 {
6648   return htab_create_alloc_ex (41,
6649                                hash_signatured_type,
6650                                eq_signatured_type,
6651                                NULL,
6652                                &objfile->objfile_obstack,
6653                                hashtab_obstack_allocate,
6654                                dummy_obstack_deallocate);
6655 }
6656
6657 /* A helper function to add a signatured type CU to a table.  */
6658
6659 static int
6660 add_signatured_type_cu_to_table (void **slot, void *datum)
6661 {
6662   struct signatured_type *sigt = (struct signatured_type *) *slot;
6663   std::vector<signatured_type *> *all_type_units
6664     = (std::vector<signatured_type *> *) datum;
6665
6666   all_type_units->push_back (sigt);
6667
6668   return 1;
6669 }
6670
6671 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6672    and fill them into TYPES_HTAB.  It will process only type units,
6673    therefore DW_UT_type.  */
6674
6675 static void
6676 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6677                               struct dwo_file *dwo_file,
6678                               dwarf2_section_info *section, htab_t &types_htab,
6679                               rcuh_kind section_kind)
6680 {
6681   struct objfile *objfile = dwarf2_per_objfile->objfile;
6682   struct dwarf2_section_info *abbrev_section;
6683   bfd *abfd;
6684   const gdb_byte *info_ptr, *end_ptr;
6685
6686   abbrev_section = (dwo_file != NULL
6687                     ? &dwo_file->sections.abbrev
6688                     : &dwarf2_per_objfile->abbrev);
6689
6690   if (dwarf_read_debug)
6691     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6692                         get_section_name (section),
6693                         get_section_file_name (abbrev_section));
6694
6695   dwarf2_read_section (objfile, section);
6696   info_ptr = section->buffer;
6697
6698   if (info_ptr == NULL)
6699     return;
6700
6701   /* We can't set abfd until now because the section may be empty or
6702      not present, in which case the bfd is unknown.  */
6703   abfd = get_section_bfd_owner (section);
6704
6705   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6706      because we don't need to read any dies: the signature is in the
6707      header.  */
6708
6709   end_ptr = info_ptr + section->size;
6710   while (info_ptr < end_ptr)
6711     {
6712       struct signatured_type *sig_type;
6713       struct dwo_unit *dwo_tu;
6714       void **slot;
6715       const gdb_byte *ptr = info_ptr;
6716       struct comp_unit_head header;
6717       unsigned int length;
6718
6719       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6720
6721       /* Initialize it due to a false compiler warning.  */
6722       header.signature = -1;
6723       header.type_cu_offset_in_tu = (cu_offset) -1;
6724
6725       /* We need to read the type's signature in order to build the hash
6726          table, but we don't need anything else just yet.  */
6727
6728       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6729                                            abbrev_section, ptr, section_kind);
6730
6731       length = get_cu_length (&header);
6732
6733       /* Skip dummy type units.  */
6734       if (ptr >= info_ptr + length
6735           || peek_abbrev_code (abfd, ptr) == 0
6736           || header.unit_type != DW_UT_type)
6737         {
6738           info_ptr += length;
6739           continue;
6740         }
6741
6742       if (types_htab == NULL)
6743         {
6744           if (dwo_file)
6745             types_htab = allocate_dwo_unit_table (objfile);
6746           else
6747             types_htab = allocate_signatured_type_table (objfile);
6748         }
6749
6750       if (dwo_file)
6751         {
6752           sig_type = NULL;
6753           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6754                                    struct dwo_unit);
6755           dwo_tu->dwo_file = dwo_file;
6756           dwo_tu->signature = header.signature;
6757           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6758           dwo_tu->section = section;
6759           dwo_tu->sect_off = sect_off;
6760           dwo_tu->length = length;
6761         }
6762       else
6763         {
6764           /* N.B.: type_offset is not usable if this type uses a DWO file.
6765              The real type_offset is in the DWO file.  */
6766           dwo_tu = NULL;
6767           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6768                                      struct signatured_type);
6769           sig_type->signature = header.signature;
6770           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6771           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6772           sig_type->per_cu.is_debug_types = 1;
6773           sig_type->per_cu.section = section;
6774           sig_type->per_cu.sect_off = sect_off;
6775           sig_type->per_cu.length = length;
6776         }
6777
6778       slot = htab_find_slot (types_htab,
6779                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6780                              INSERT);
6781       gdb_assert (slot != NULL);
6782       if (*slot != NULL)
6783         {
6784           sect_offset dup_sect_off;
6785
6786           if (dwo_file)
6787             {
6788               const struct dwo_unit *dup_tu
6789                 = (const struct dwo_unit *) *slot;
6790
6791               dup_sect_off = dup_tu->sect_off;
6792             }
6793           else
6794             {
6795               const struct signatured_type *dup_tu
6796                 = (const struct signatured_type *) *slot;
6797
6798               dup_sect_off = dup_tu->per_cu.sect_off;
6799             }
6800
6801           complaint (_("debug type entry at offset %s is duplicate to"
6802                        " the entry at offset %s, signature %s"),
6803                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6804                      hex_string (header.signature));
6805         }
6806       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6807
6808       if (dwarf_read_debug > 1)
6809         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6810                             sect_offset_str (sect_off),
6811                             hex_string (header.signature));
6812
6813       info_ptr += length;
6814     }
6815 }
6816
6817 /* Create the hash table of all entries in the .debug_types
6818    (or .debug_types.dwo) section(s).
6819    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6820    otherwise it is NULL.
6821
6822    The result is a pointer to the hash table or NULL if there are no types.
6823
6824    Note: This function processes DWO files only, not DWP files.  */
6825
6826 static void
6827 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6828                                struct dwo_file *dwo_file,
6829                                VEC (dwarf2_section_info_def) *types,
6830                                htab_t &types_htab)
6831 {
6832   int ix;
6833   struct dwarf2_section_info *section;
6834
6835   if (VEC_empty (dwarf2_section_info_def, types))
6836     return;
6837
6838   for (ix = 0;
6839        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6840        ++ix)
6841     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6842                                   types_htab, rcuh_kind::TYPE);
6843 }
6844
6845 /* Create the hash table of all entries in the .debug_types section,
6846    and initialize all_type_units.
6847    The result is zero if there is an error (e.g. missing .debug_types section),
6848    otherwise non-zero.  */
6849
6850 static int
6851 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6852 {
6853   htab_t types_htab = NULL;
6854
6855   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6856                                 &dwarf2_per_objfile->info, types_htab,
6857                                 rcuh_kind::COMPILE);
6858   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6859                                  dwarf2_per_objfile->types, types_htab);
6860   if (types_htab == NULL)
6861     {
6862       dwarf2_per_objfile->signatured_types = NULL;
6863       return 0;
6864     }
6865
6866   dwarf2_per_objfile->signatured_types = types_htab;
6867
6868   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6869   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6870
6871   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6872                           &dwarf2_per_objfile->all_type_units);
6873
6874   return 1;
6875 }
6876
6877 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6878    If SLOT is non-NULL, it is the entry to use in the hash table.
6879    Otherwise we find one.  */
6880
6881 static struct signatured_type *
6882 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6883                void **slot)
6884 {
6885   struct objfile *objfile = dwarf2_per_objfile->objfile;
6886
6887   if (dwarf2_per_objfile->all_type_units.size ()
6888       == dwarf2_per_objfile->all_type_units.capacity ())
6889     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6890
6891   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6892                                               struct signatured_type);
6893
6894   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6895   sig_type->signature = sig;
6896   sig_type->per_cu.is_debug_types = 1;
6897   if (dwarf2_per_objfile->using_index)
6898     {
6899       sig_type->per_cu.v.quick =
6900         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6901                         struct dwarf2_per_cu_quick_data);
6902     }
6903
6904   if (slot == NULL)
6905     {
6906       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6907                              sig_type, INSERT);
6908     }
6909   gdb_assert (*slot == NULL);
6910   *slot = sig_type;
6911   /* The rest of sig_type must be filled in by the caller.  */
6912   return sig_type;
6913 }
6914
6915 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6916    Fill in SIG_ENTRY with DWO_ENTRY.  */
6917
6918 static void
6919 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6920                                   struct signatured_type *sig_entry,
6921                                   struct dwo_unit *dwo_entry)
6922 {
6923   /* Make sure we're not clobbering something we don't expect to.  */
6924   gdb_assert (! sig_entry->per_cu.queued);
6925   gdb_assert (sig_entry->per_cu.cu == NULL);
6926   if (dwarf2_per_objfile->using_index)
6927     {
6928       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6929       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6930     }
6931   else
6932       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6933   gdb_assert (sig_entry->signature == dwo_entry->signature);
6934   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6935   gdb_assert (sig_entry->type_unit_group == NULL);
6936   gdb_assert (sig_entry->dwo_unit == NULL);
6937
6938   sig_entry->per_cu.section = dwo_entry->section;
6939   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6940   sig_entry->per_cu.length = dwo_entry->length;
6941   sig_entry->per_cu.reading_dwo_directly = 1;
6942   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6943   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6944   sig_entry->dwo_unit = dwo_entry;
6945 }
6946
6947 /* Subroutine of lookup_signatured_type.
6948    If we haven't read the TU yet, create the signatured_type data structure
6949    for a TU to be read in directly from a DWO file, bypassing the stub.
6950    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6951    using .gdb_index, then when reading a CU we want to stay in the DWO file
6952    containing that CU.  Otherwise we could end up reading several other DWO
6953    files (due to comdat folding) to process the transitive closure of all the
6954    mentioned TUs, and that can be slow.  The current DWO file will have every
6955    type signature that it needs.
6956    We only do this for .gdb_index because in the psymtab case we already have
6957    to read all the DWOs to build the type unit groups.  */
6958
6959 static struct signatured_type *
6960 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6961 {
6962   struct dwarf2_per_objfile *dwarf2_per_objfile
6963     = cu->per_cu->dwarf2_per_objfile;
6964   struct objfile *objfile = dwarf2_per_objfile->objfile;
6965   struct dwo_file *dwo_file;
6966   struct dwo_unit find_dwo_entry, *dwo_entry;
6967   struct signatured_type find_sig_entry, *sig_entry;
6968   void **slot;
6969
6970   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6971
6972   /* If TU skeletons have been removed then we may not have read in any
6973      TUs yet.  */
6974   if (dwarf2_per_objfile->signatured_types == NULL)
6975     {
6976       dwarf2_per_objfile->signatured_types
6977         = allocate_signatured_type_table (objfile);
6978     }
6979
6980   /* We only ever need to read in one copy of a signatured type.
6981      Use the global signatured_types array to do our own comdat-folding
6982      of types.  If this is the first time we're reading this TU, and
6983      the TU has an entry in .gdb_index, replace the recorded data from
6984      .gdb_index with this TU.  */
6985
6986   find_sig_entry.signature = sig;
6987   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6988                          &find_sig_entry, INSERT);
6989   sig_entry = (struct signatured_type *) *slot;
6990
6991   /* We can get here with the TU already read, *or* in the process of being
6992      read.  Don't reassign the global entry to point to this DWO if that's
6993      the case.  Also note that if the TU is already being read, it may not
6994      have come from a DWO, the program may be a mix of Fission-compiled
6995      code and non-Fission-compiled code.  */
6996
6997   /* Have we already tried to read this TU?
6998      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6999      needn't exist in the global table yet).  */
7000   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7001     return sig_entry;
7002
7003   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7004      dwo_unit of the TU itself.  */
7005   dwo_file = cu->dwo_unit->dwo_file;
7006
7007   /* Ok, this is the first time we're reading this TU.  */
7008   if (dwo_file->tus == NULL)
7009     return NULL;
7010   find_dwo_entry.signature = sig;
7011   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7012   if (dwo_entry == NULL)
7013     return NULL;
7014
7015   /* If the global table doesn't have an entry for this TU, add one.  */
7016   if (sig_entry == NULL)
7017     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7018
7019   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7020   sig_entry->per_cu.tu_read = 1;
7021   return sig_entry;
7022 }
7023
7024 /* Subroutine of lookup_signatured_type.
7025    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7026    then try the DWP file.  If the TU stub (skeleton) has been removed then
7027    it won't be in .gdb_index.  */
7028
7029 static struct signatured_type *
7030 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7031 {
7032   struct dwarf2_per_objfile *dwarf2_per_objfile
7033     = cu->per_cu->dwarf2_per_objfile;
7034   struct objfile *objfile = dwarf2_per_objfile->objfile;
7035   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7036   struct dwo_unit *dwo_entry;
7037   struct signatured_type find_sig_entry, *sig_entry;
7038   void **slot;
7039
7040   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7041   gdb_assert (dwp_file != NULL);
7042
7043   /* If TU skeletons have been removed then we may not have read in any
7044      TUs yet.  */
7045   if (dwarf2_per_objfile->signatured_types == NULL)
7046     {
7047       dwarf2_per_objfile->signatured_types
7048         = allocate_signatured_type_table (objfile);
7049     }
7050
7051   find_sig_entry.signature = sig;
7052   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7053                          &find_sig_entry, INSERT);
7054   sig_entry = (struct signatured_type *) *slot;
7055
7056   /* Have we already tried to read this TU?
7057      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7058      needn't exist in the global table yet).  */
7059   if (sig_entry != NULL)
7060     return sig_entry;
7061
7062   if (dwp_file->tus == NULL)
7063     return NULL;
7064   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7065                                       sig, 1 /* is_debug_types */);
7066   if (dwo_entry == NULL)
7067     return NULL;
7068
7069   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7070   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7071
7072   return sig_entry;
7073 }
7074
7075 /* Lookup a signature based type for DW_FORM_ref_sig8.
7076    Returns NULL if signature SIG is not present in the table.
7077    It is up to the caller to complain about this.  */
7078
7079 static struct signatured_type *
7080 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7081 {
7082   struct dwarf2_per_objfile *dwarf2_per_objfile
7083     = cu->per_cu->dwarf2_per_objfile;
7084
7085   if (cu->dwo_unit
7086       && dwarf2_per_objfile->using_index)
7087     {
7088       /* We're in a DWO/DWP file, and we're using .gdb_index.
7089          These cases require special processing.  */
7090       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7091         return lookup_dwo_signatured_type (cu, sig);
7092       else
7093         return lookup_dwp_signatured_type (cu, sig);
7094     }
7095   else
7096     {
7097       struct signatured_type find_entry, *entry;
7098
7099       if (dwarf2_per_objfile->signatured_types == NULL)
7100         return NULL;
7101       find_entry.signature = sig;
7102       entry = ((struct signatured_type *)
7103                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7104       return entry;
7105     }
7106 }
7107 \f
7108 /* Low level DIE reading support.  */
7109
7110 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7111
7112 static void
7113 init_cu_die_reader (struct die_reader_specs *reader,
7114                     struct dwarf2_cu *cu,
7115                     struct dwarf2_section_info *section,
7116                     struct dwo_file *dwo_file,
7117                     struct abbrev_table *abbrev_table)
7118 {
7119   gdb_assert (section->readin && section->buffer != NULL);
7120   reader->abfd = get_section_bfd_owner (section);
7121   reader->cu = cu;
7122   reader->dwo_file = dwo_file;
7123   reader->die_section = section;
7124   reader->buffer = section->buffer;
7125   reader->buffer_end = section->buffer + section->size;
7126   reader->comp_dir = NULL;
7127   reader->abbrev_table = abbrev_table;
7128 }
7129
7130 /* Subroutine of init_cutu_and_read_dies to simplify it.
7131    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7132    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7133    already.
7134
7135    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7136    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7137    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7138    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7139    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7140    STUB_COMP_DIR may be non-NULL.
7141    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7142    are filled in with the info of the DIE from the DWO file.
7143    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7144    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7145    kept around for at least as long as *RESULT_READER.
7146
7147    The result is non-zero if a valid (non-dummy) DIE was found.  */
7148
7149 static int
7150 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7151                         struct dwo_unit *dwo_unit,
7152                         struct die_info *stub_comp_unit_die,
7153                         const char *stub_comp_dir,
7154                         struct die_reader_specs *result_reader,
7155                         const gdb_byte **result_info_ptr,
7156                         struct die_info **result_comp_unit_die,
7157                         int *result_has_children,
7158                         abbrev_table_up *result_dwo_abbrev_table)
7159 {
7160   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7161   struct objfile *objfile = dwarf2_per_objfile->objfile;
7162   struct dwarf2_cu *cu = this_cu->cu;
7163   bfd *abfd;
7164   const gdb_byte *begin_info_ptr, *info_ptr;
7165   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7166   int i,num_extra_attrs;
7167   struct dwarf2_section_info *dwo_abbrev_section;
7168   struct attribute *attr;
7169   struct die_info *comp_unit_die;
7170
7171   /* At most one of these may be provided.  */
7172   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7173
7174   /* These attributes aren't processed until later:
7175      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7176      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7177      referenced later.  However, these attributes are found in the stub
7178      which we won't have later.  In order to not impose this complication
7179      on the rest of the code, we read them here and copy them to the
7180      DWO CU/TU die.  */
7181
7182   stmt_list = NULL;
7183   low_pc = NULL;
7184   high_pc = NULL;
7185   ranges = NULL;
7186   comp_dir = NULL;
7187
7188   if (stub_comp_unit_die != NULL)
7189     {
7190       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7191          DWO file.  */
7192       if (! this_cu->is_debug_types)
7193         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7194       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7195       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7196       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7197       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7198
7199       /* There should be a DW_AT_addr_base attribute here (if needed).
7200          We need the value before we can process DW_FORM_GNU_addr_index
7201          or DW_FORM_addrx.  */
7202       cu->addr_base = 0;
7203       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7204       if (attr)
7205         cu->addr_base = DW_UNSND (attr);
7206
7207       /* There should be a DW_AT_ranges_base attribute here (if needed).
7208          We need the value before we can process DW_AT_ranges.  */
7209       cu->ranges_base = 0;
7210       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7211       if (attr)
7212         cu->ranges_base = DW_UNSND (attr);
7213     }
7214   else if (stub_comp_dir != NULL)
7215     {
7216       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7217       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7218       comp_dir->name = DW_AT_comp_dir;
7219       comp_dir->form = DW_FORM_string;
7220       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7221       DW_STRING (comp_dir) = stub_comp_dir;
7222     }
7223
7224   /* Set up for reading the DWO CU/TU.  */
7225   cu->dwo_unit = dwo_unit;
7226   dwarf2_section_info *section = dwo_unit->section;
7227   dwarf2_read_section (objfile, section);
7228   abfd = get_section_bfd_owner (section);
7229   begin_info_ptr = info_ptr = (section->buffer
7230                                + to_underlying (dwo_unit->sect_off));
7231   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7232
7233   if (this_cu->is_debug_types)
7234     {
7235       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7236
7237       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7238                                                 &cu->header, section,
7239                                                 dwo_abbrev_section,
7240                                                 info_ptr, rcuh_kind::TYPE);
7241       /* This is not an assert because it can be caused by bad debug info.  */
7242       if (sig_type->signature != cu->header.signature)
7243         {
7244           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7245                    " TU at offset %s [in module %s]"),
7246                  hex_string (sig_type->signature),
7247                  hex_string (cu->header.signature),
7248                  sect_offset_str (dwo_unit->sect_off),
7249                  bfd_get_filename (abfd));
7250         }
7251       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7252       /* For DWOs coming from DWP files, we don't know the CU length
7253          nor the type's offset in the TU until now.  */
7254       dwo_unit->length = get_cu_length (&cu->header);
7255       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7256
7257       /* Establish the type offset that can be used to lookup the type.
7258          For DWO files, we don't know it until now.  */
7259       sig_type->type_offset_in_section
7260         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7261     }
7262   else
7263     {
7264       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7265                                                 &cu->header, section,
7266                                                 dwo_abbrev_section,
7267                                                 info_ptr, rcuh_kind::COMPILE);
7268       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7269       /* For DWOs coming from DWP files, we don't know the CU length
7270          until now.  */
7271       dwo_unit->length = get_cu_length (&cu->header);
7272     }
7273
7274   *result_dwo_abbrev_table
7275     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7276                                cu->header.abbrev_sect_off);
7277   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7278                       result_dwo_abbrev_table->get ());
7279
7280   /* Read in the die, but leave space to copy over the attributes
7281      from the stub.  This has the benefit of simplifying the rest of
7282      the code - all the work to maintain the illusion of a single
7283      DW_TAG_{compile,type}_unit DIE is done here.  */
7284   num_extra_attrs = ((stmt_list != NULL)
7285                      + (low_pc != NULL)
7286                      + (high_pc != NULL)
7287                      + (ranges != NULL)
7288                      + (comp_dir != NULL));
7289   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7290                               result_has_children, num_extra_attrs);
7291
7292   /* Copy over the attributes from the stub to the DIE we just read in.  */
7293   comp_unit_die = *result_comp_unit_die;
7294   i = comp_unit_die->num_attrs;
7295   if (stmt_list != NULL)
7296     comp_unit_die->attrs[i++] = *stmt_list;
7297   if (low_pc != NULL)
7298     comp_unit_die->attrs[i++] = *low_pc;
7299   if (high_pc != NULL)
7300     comp_unit_die->attrs[i++] = *high_pc;
7301   if (ranges != NULL)
7302     comp_unit_die->attrs[i++] = *ranges;
7303   if (comp_dir != NULL)
7304     comp_unit_die->attrs[i++] = *comp_dir;
7305   comp_unit_die->num_attrs += num_extra_attrs;
7306
7307   if (dwarf_die_debug)
7308     {
7309       fprintf_unfiltered (gdb_stdlog,
7310                           "Read die from %s@0x%x of %s:\n",
7311                           get_section_name (section),
7312                           (unsigned) (begin_info_ptr - section->buffer),
7313                           bfd_get_filename (abfd));
7314       dump_die (comp_unit_die, dwarf_die_debug);
7315     }
7316
7317   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7318      TUs by skipping the stub and going directly to the entry in the DWO file.
7319      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7320      to get it via circuitous means.  Blech.  */
7321   if (comp_dir != NULL)
7322     result_reader->comp_dir = DW_STRING (comp_dir);
7323
7324   /* Skip dummy compilation units.  */
7325   if (info_ptr >= begin_info_ptr + dwo_unit->length
7326       || peek_abbrev_code (abfd, info_ptr) == 0)
7327     return 0;
7328
7329   *result_info_ptr = info_ptr;
7330   return 1;
7331 }
7332
7333 /* Subroutine of init_cutu_and_read_dies to simplify it.
7334    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7335    Returns NULL if the specified DWO unit cannot be found.  */
7336
7337 static struct dwo_unit *
7338 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7339                  struct die_info *comp_unit_die)
7340 {
7341   struct dwarf2_cu *cu = this_cu->cu;
7342   ULONGEST signature;
7343   struct dwo_unit *dwo_unit;
7344   const char *comp_dir, *dwo_name;
7345
7346   gdb_assert (cu != NULL);
7347
7348   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7349   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7350   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7351
7352   if (this_cu->is_debug_types)
7353     {
7354       struct signatured_type *sig_type;
7355
7356       /* Since this_cu is the first member of struct signatured_type,
7357          we can go from a pointer to one to a pointer to the other.  */
7358       sig_type = (struct signatured_type *) this_cu;
7359       signature = sig_type->signature;
7360       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7361     }
7362   else
7363     {
7364       struct attribute *attr;
7365
7366       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7367       if (! attr)
7368         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7369                  " [in module %s]"),
7370                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7371       signature = DW_UNSND (attr);
7372       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7373                                        signature);
7374     }
7375
7376   return dwo_unit;
7377 }
7378
7379 /* Subroutine of init_cutu_and_read_dies to simplify it.
7380    See it for a description of the parameters.
7381    Read a TU directly from a DWO file, bypassing the stub.  */
7382
7383 static void
7384 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7385                            int use_existing_cu, int keep,
7386                            die_reader_func_ftype *die_reader_func,
7387                            void *data)
7388 {
7389   std::unique_ptr<dwarf2_cu> new_cu;
7390   struct signatured_type *sig_type;
7391   struct die_reader_specs reader;
7392   const gdb_byte *info_ptr;
7393   struct die_info *comp_unit_die;
7394   int has_children;
7395   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7396
7397   /* Verify we can do the following downcast, and that we have the
7398      data we need.  */
7399   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7400   sig_type = (struct signatured_type *) this_cu;
7401   gdb_assert (sig_type->dwo_unit != NULL);
7402
7403   if (use_existing_cu && this_cu->cu != NULL)
7404     {
7405       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7406       /* There's no need to do the rereading_dwo_cu handling that
7407          init_cutu_and_read_dies does since we don't read the stub.  */
7408     }
7409   else
7410     {
7411       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7412       gdb_assert (this_cu->cu == NULL);
7413       new_cu.reset (new dwarf2_cu (this_cu));
7414     }
7415
7416   /* A future optimization, if needed, would be to use an existing
7417      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7418      could share abbrev tables.  */
7419
7420   /* The abbreviation table used by READER, this must live at least as long as
7421      READER.  */
7422   abbrev_table_up dwo_abbrev_table;
7423
7424   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7425                               NULL /* stub_comp_unit_die */,
7426                               sig_type->dwo_unit->dwo_file->comp_dir,
7427                               &reader, &info_ptr,
7428                               &comp_unit_die, &has_children,
7429                               &dwo_abbrev_table) == 0)
7430     {
7431       /* Dummy die.  */
7432       return;
7433     }
7434
7435   /* All the "real" work is done here.  */
7436   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7437
7438   /* This duplicates the code in init_cutu_and_read_dies,
7439      but the alternative is making the latter more complex.
7440      This function is only for the special case of using DWO files directly:
7441      no point in overly complicating the general case just to handle this.  */
7442   if (new_cu != NULL && keep)
7443     {
7444       /* Link this CU into read_in_chain.  */
7445       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7446       dwarf2_per_objfile->read_in_chain = this_cu;
7447       /* The chain owns it now.  */
7448       new_cu.release ();
7449     }
7450 }
7451
7452 /* Initialize a CU (or TU) and read its DIEs.
7453    If the CU defers to a DWO file, read the DWO file as well.
7454
7455    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7456    Otherwise the table specified in the comp unit header is read in and used.
7457    This is an optimization for when we already have the abbrev table.
7458
7459    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7460    Otherwise, a new CU is allocated with xmalloc.
7461
7462    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7463    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7464
7465    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7466    linker) then DIE_READER_FUNC will not get called.  */
7467
7468 static void
7469 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7470                          struct abbrev_table *abbrev_table,
7471                          int use_existing_cu, int keep,
7472                          bool skip_partial,
7473                          die_reader_func_ftype *die_reader_func,
7474                          void *data)
7475 {
7476   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7477   struct objfile *objfile = dwarf2_per_objfile->objfile;
7478   struct dwarf2_section_info *section = this_cu->section;
7479   bfd *abfd = get_section_bfd_owner (section);
7480   struct dwarf2_cu *cu;
7481   const gdb_byte *begin_info_ptr, *info_ptr;
7482   struct die_reader_specs reader;
7483   struct die_info *comp_unit_die;
7484   int has_children;
7485   struct attribute *attr;
7486   struct signatured_type *sig_type = NULL;
7487   struct dwarf2_section_info *abbrev_section;
7488   /* Non-zero if CU currently points to a DWO file and we need to
7489      reread it.  When this happens we need to reread the skeleton die
7490      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7491   int rereading_dwo_cu = 0;
7492
7493   if (dwarf_die_debug)
7494     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7495                         this_cu->is_debug_types ? "type" : "comp",
7496                         sect_offset_str (this_cu->sect_off));
7497
7498   if (use_existing_cu)
7499     gdb_assert (keep);
7500
7501   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7502      file (instead of going through the stub), short-circuit all of this.  */
7503   if (this_cu->reading_dwo_directly)
7504     {
7505       /* Narrow down the scope of possibilities to have to understand.  */
7506       gdb_assert (this_cu->is_debug_types);
7507       gdb_assert (abbrev_table == NULL);
7508       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7509                                  die_reader_func, data);
7510       return;
7511     }
7512
7513   /* This is cheap if the section is already read in.  */
7514   dwarf2_read_section (objfile, section);
7515
7516   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7517
7518   abbrev_section = get_abbrev_section_for_cu (this_cu);
7519
7520   std::unique_ptr<dwarf2_cu> new_cu;
7521   if (use_existing_cu && this_cu->cu != NULL)
7522     {
7523       cu = this_cu->cu;
7524       /* If this CU is from a DWO file we need to start over, we need to
7525          refetch the attributes from the skeleton CU.
7526          This could be optimized by retrieving those attributes from when we
7527          were here the first time: the previous comp_unit_die was stored in
7528          comp_unit_obstack.  But there's no data yet that we need this
7529          optimization.  */
7530       if (cu->dwo_unit != NULL)
7531         rereading_dwo_cu = 1;
7532     }
7533   else
7534     {
7535       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7536       gdb_assert (this_cu->cu == NULL);
7537       new_cu.reset (new dwarf2_cu (this_cu));
7538       cu = new_cu.get ();
7539     }
7540
7541   /* Get the header.  */
7542   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7543     {
7544       /* We already have the header, there's no need to read it in again.  */
7545       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7546     }
7547   else
7548     {
7549       if (this_cu->is_debug_types)
7550         {
7551           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7552                                                     &cu->header, section,
7553                                                     abbrev_section, info_ptr,
7554                                                     rcuh_kind::TYPE);
7555
7556           /* Since per_cu is the first member of struct signatured_type,
7557              we can go from a pointer to one to a pointer to the other.  */
7558           sig_type = (struct signatured_type *) this_cu;
7559           gdb_assert (sig_type->signature == cu->header.signature);
7560           gdb_assert (sig_type->type_offset_in_tu
7561                       == cu->header.type_cu_offset_in_tu);
7562           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7563
7564           /* LENGTH has not been set yet for type units if we're
7565              using .gdb_index.  */
7566           this_cu->length = get_cu_length (&cu->header);
7567
7568           /* Establish the type offset that can be used to lookup the type.  */
7569           sig_type->type_offset_in_section =
7570             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7571
7572           this_cu->dwarf_version = cu->header.version;
7573         }
7574       else
7575         {
7576           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7577                                                     &cu->header, section,
7578                                                     abbrev_section,
7579                                                     info_ptr,
7580                                                     rcuh_kind::COMPILE);
7581
7582           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7583           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7584           this_cu->dwarf_version = cu->header.version;
7585         }
7586     }
7587
7588   /* Skip dummy compilation units.  */
7589   if (info_ptr >= begin_info_ptr + this_cu->length
7590       || peek_abbrev_code (abfd, info_ptr) == 0)
7591     return;
7592
7593   /* If we don't have them yet, read the abbrevs for this compilation unit.
7594      And if we need to read them now, make sure they're freed when we're
7595      done (own the table through ABBREV_TABLE_HOLDER).  */
7596   abbrev_table_up abbrev_table_holder;
7597   if (abbrev_table != NULL)
7598     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7599   else
7600     {
7601       abbrev_table_holder
7602         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7603                                    cu->header.abbrev_sect_off);
7604       abbrev_table = abbrev_table_holder.get ();
7605     }
7606
7607   /* Read the top level CU/TU die.  */
7608   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7609   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7610
7611   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7612     return;
7613
7614   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7615      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7616      table from the DWO file and pass the ownership over to us.  It will be
7617      referenced from READER, so we must make sure to free it after we're done
7618      with READER.
7619
7620      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7621      DWO CU, that this test will fail (the attribute will not be present).  */
7622   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7623   abbrev_table_up dwo_abbrev_table;
7624   if (attr)
7625     {
7626       struct dwo_unit *dwo_unit;
7627       struct die_info *dwo_comp_unit_die;
7628
7629       if (has_children)
7630         {
7631           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7632                        " has children (offset %s) [in module %s]"),
7633                      sect_offset_str (this_cu->sect_off),
7634                      bfd_get_filename (abfd));
7635         }
7636       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7637       if (dwo_unit != NULL)
7638         {
7639           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7640                                       comp_unit_die, NULL,
7641                                       &reader, &info_ptr,
7642                                       &dwo_comp_unit_die, &has_children,
7643                                       &dwo_abbrev_table) == 0)
7644             {
7645               /* Dummy die.  */
7646               return;
7647             }
7648           comp_unit_die = dwo_comp_unit_die;
7649         }
7650       else
7651         {
7652           /* Yikes, we couldn't find the rest of the DIE, we only have
7653              the stub.  A complaint has already been logged.  There's
7654              not much more we can do except pass on the stub DIE to
7655              die_reader_func.  We don't want to throw an error on bad
7656              debug info.  */
7657         }
7658     }
7659
7660   /* All of the above is setup for this call.  Yikes.  */
7661   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7662
7663   /* Done, clean up.  */
7664   if (new_cu != NULL && keep)
7665     {
7666       /* Link this CU into read_in_chain.  */
7667       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7668       dwarf2_per_objfile->read_in_chain = this_cu;
7669       /* The chain owns it now.  */
7670       new_cu.release ();
7671     }
7672 }
7673
7674 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7675    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7676    to have already done the lookup to find the DWO file).
7677
7678    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7679    THIS_CU->is_debug_types, but nothing else.
7680
7681    We fill in THIS_CU->length.
7682
7683    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7684    linker) then DIE_READER_FUNC will not get called.
7685
7686    THIS_CU->cu is always freed when done.
7687    This is done in order to not leave THIS_CU->cu in a state where we have
7688    to care whether it refers to the "main" CU or the DWO CU.  */
7689
7690 static void
7691 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7692                                    struct dwo_file *dwo_file,
7693                                    die_reader_func_ftype *die_reader_func,
7694                                    void *data)
7695 {
7696   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7697   struct objfile *objfile = dwarf2_per_objfile->objfile;
7698   struct dwarf2_section_info *section = this_cu->section;
7699   bfd *abfd = get_section_bfd_owner (section);
7700   struct dwarf2_section_info *abbrev_section;
7701   const gdb_byte *begin_info_ptr, *info_ptr;
7702   struct die_reader_specs reader;
7703   struct die_info *comp_unit_die;
7704   int has_children;
7705
7706   if (dwarf_die_debug)
7707     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7708                         this_cu->is_debug_types ? "type" : "comp",
7709                         sect_offset_str (this_cu->sect_off));
7710
7711   gdb_assert (this_cu->cu == NULL);
7712
7713   abbrev_section = (dwo_file != NULL
7714                     ? &dwo_file->sections.abbrev
7715                     : get_abbrev_section_for_cu (this_cu));
7716
7717   /* This is cheap if the section is already read in.  */
7718   dwarf2_read_section (objfile, section);
7719
7720   struct dwarf2_cu cu (this_cu);
7721
7722   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7723   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7724                                             &cu.header, section,
7725                                             abbrev_section, info_ptr,
7726                                             (this_cu->is_debug_types
7727                                              ? rcuh_kind::TYPE
7728                                              : rcuh_kind::COMPILE));
7729
7730   this_cu->length = get_cu_length (&cu.header);
7731
7732   /* Skip dummy compilation units.  */
7733   if (info_ptr >= begin_info_ptr + this_cu->length
7734       || peek_abbrev_code (abfd, info_ptr) == 0)
7735     return;
7736
7737   abbrev_table_up abbrev_table
7738     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7739                                cu.header.abbrev_sect_off);
7740
7741   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7742   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7743
7744   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7745 }
7746
7747 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7748    does not lookup the specified DWO file.
7749    This cannot be used to read DWO files.
7750
7751    THIS_CU->cu is always freed when done.
7752    This is done in order to not leave THIS_CU->cu in a state where we have
7753    to care whether it refers to the "main" CU or the DWO CU.
7754    We can revisit this if the data shows there's a performance issue.  */
7755
7756 static void
7757 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7758                                 die_reader_func_ftype *die_reader_func,
7759                                 void *data)
7760 {
7761   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7762 }
7763 \f
7764 /* Type Unit Groups.
7765
7766    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7767    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7768    so that all types coming from the same compilation (.o file) are grouped
7769    together.  A future step could be to put the types in the same symtab as
7770    the CU the types ultimately came from.  */
7771
7772 static hashval_t
7773 hash_type_unit_group (const void *item)
7774 {
7775   const struct type_unit_group *tu_group
7776     = (const struct type_unit_group *) item;
7777
7778   return hash_stmt_list_entry (&tu_group->hash);
7779 }
7780
7781 static int
7782 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7783 {
7784   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7785   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7786
7787   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7788 }
7789
7790 /* Allocate a hash table for type unit groups.  */
7791
7792 static htab_t
7793 allocate_type_unit_groups_table (struct objfile *objfile)
7794 {
7795   return htab_create_alloc_ex (3,
7796                                hash_type_unit_group,
7797                                eq_type_unit_group,
7798                                NULL,
7799                                &objfile->objfile_obstack,
7800                                hashtab_obstack_allocate,
7801                                dummy_obstack_deallocate);
7802 }
7803
7804 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7805    partial symtabs.  We combine several TUs per psymtab to not let the size
7806    of any one psymtab grow too big.  */
7807 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7808 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7809
7810 /* Helper routine for get_type_unit_group.
7811    Create the type_unit_group object used to hold one or more TUs.  */
7812
7813 static struct type_unit_group *
7814 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7815 {
7816   struct dwarf2_per_objfile *dwarf2_per_objfile
7817     = cu->per_cu->dwarf2_per_objfile;
7818   struct objfile *objfile = dwarf2_per_objfile->objfile;
7819   struct dwarf2_per_cu_data *per_cu;
7820   struct type_unit_group *tu_group;
7821
7822   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7823                              struct type_unit_group);
7824   per_cu = &tu_group->per_cu;
7825   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7826
7827   if (dwarf2_per_objfile->using_index)
7828     {
7829       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7830                                         struct dwarf2_per_cu_quick_data);
7831     }
7832   else
7833     {
7834       unsigned int line_offset = to_underlying (line_offset_struct);
7835       struct partial_symtab *pst;
7836       std::string name;
7837
7838       /* Give the symtab a useful name for debug purposes.  */
7839       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7840         name = string_printf ("<type_units_%d>",
7841                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7842       else
7843         name = string_printf ("<type_units_at_0x%x>", line_offset);
7844
7845       pst = create_partial_symtab (per_cu, name.c_str ());
7846       pst->anonymous = 1;
7847     }
7848
7849   tu_group->hash.dwo_unit = cu->dwo_unit;
7850   tu_group->hash.line_sect_off = line_offset_struct;
7851
7852   return tu_group;
7853 }
7854
7855 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7856    STMT_LIST is a DW_AT_stmt_list attribute.  */
7857
7858 static struct type_unit_group *
7859 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7860 {
7861   struct dwarf2_per_objfile *dwarf2_per_objfile
7862     = cu->per_cu->dwarf2_per_objfile;
7863   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7864   struct type_unit_group *tu_group;
7865   void **slot;
7866   unsigned int line_offset;
7867   struct type_unit_group type_unit_group_for_lookup;
7868
7869   if (dwarf2_per_objfile->type_unit_groups == NULL)
7870     {
7871       dwarf2_per_objfile->type_unit_groups =
7872         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7873     }
7874
7875   /* Do we need to create a new group, or can we use an existing one?  */
7876
7877   if (stmt_list)
7878     {
7879       line_offset = DW_UNSND (stmt_list);
7880       ++tu_stats->nr_symtab_sharers;
7881     }
7882   else
7883     {
7884       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7885          We can do various things here like create one group per TU or
7886          spread them over multiple groups to split up the expansion work.
7887          To avoid worst case scenarios (too many groups or too large groups)
7888          we, umm, group them in bunches.  */
7889       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7890                      | (tu_stats->nr_stmt_less_type_units
7891                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7892       ++tu_stats->nr_stmt_less_type_units;
7893     }
7894
7895   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7896   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7897   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7898                          &type_unit_group_for_lookup, INSERT);
7899   if (*slot != NULL)
7900     {
7901       tu_group = (struct type_unit_group *) *slot;
7902       gdb_assert (tu_group != NULL);
7903     }
7904   else
7905     {
7906       sect_offset line_offset_struct = (sect_offset) line_offset;
7907       tu_group = create_type_unit_group (cu, line_offset_struct);
7908       *slot = tu_group;
7909       ++tu_stats->nr_symtabs;
7910     }
7911
7912   return tu_group;
7913 }
7914 \f
7915 /* Partial symbol tables.  */
7916
7917 /* Create a psymtab named NAME and assign it to PER_CU.
7918
7919    The caller must fill in the following details:
7920    dirname, textlow, texthigh.  */
7921
7922 static struct partial_symtab *
7923 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7924 {
7925   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7926   struct partial_symtab *pst;
7927
7928   pst = start_psymtab_common (objfile, name, 0);
7929
7930   pst->psymtabs_addrmap_supported = 1;
7931
7932   /* This is the glue that links PST into GDB's symbol API.  */
7933   pst->read_symtab_private = per_cu;
7934   pst->read_symtab = dwarf2_read_symtab;
7935   per_cu->v.psymtab = pst;
7936
7937   return pst;
7938 }
7939
7940 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7941    type.  */
7942
7943 struct process_psymtab_comp_unit_data
7944 {
7945   /* True if we are reading a DW_TAG_partial_unit.  */
7946
7947   int want_partial_unit;
7948
7949   /* The "pretend" language that is used if the CU doesn't declare a
7950      language.  */
7951
7952   enum language pretend_language;
7953 };
7954
7955 /* die_reader_func for process_psymtab_comp_unit.  */
7956
7957 static void
7958 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7959                                   const gdb_byte *info_ptr,
7960                                   struct die_info *comp_unit_die,
7961                                   int has_children,
7962                                   void *data)
7963 {
7964   struct dwarf2_cu *cu = reader->cu;
7965   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7966   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7967   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7968   CORE_ADDR baseaddr;
7969   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7970   struct partial_symtab *pst;
7971   enum pc_bounds_kind cu_bounds_kind;
7972   const char *filename;
7973   struct process_psymtab_comp_unit_data *info
7974     = (struct process_psymtab_comp_unit_data *) data;
7975
7976   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7977     return;
7978
7979   gdb_assert (! per_cu->is_debug_types);
7980
7981   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7982
7983   /* Allocate a new partial symbol table structure.  */
7984   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7985   if (filename == NULL)
7986     filename = "";
7987
7988   pst = create_partial_symtab (per_cu, filename);
7989
7990   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7991   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7992
7993   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7994
7995   dwarf2_find_base_address (comp_unit_die, cu);
7996
7997   /* Possibly set the default values of LOWPC and HIGHPC from
7998      `DW_AT_ranges'.  */
7999   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8000                                          &best_highpc, cu, pst);
8001   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8002     {
8003       CORE_ADDR low
8004         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
8005            - baseaddr);
8006       CORE_ADDR high
8007         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
8008            - baseaddr - 1);
8009       /* Store the contiguous range if it is not empty; it can be
8010          empty for CUs with no code.  */
8011       addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
8012                          low, high, pst);
8013     }
8014
8015   /* Check if comp unit has_children.
8016      If so, read the rest of the partial symbols from this comp unit.
8017      If not, there's no more debug_info for this comp unit.  */
8018   if (has_children)
8019     {
8020       struct partial_die_info *first_die;
8021       CORE_ADDR lowpc, highpc;
8022
8023       lowpc = ((CORE_ADDR) -1);
8024       highpc = ((CORE_ADDR) 0);
8025
8026       first_die = load_partial_dies (reader, info_ptr, 1);
8027
8028       scan_partial_symbols (first_die, &lowpc, &highpc,
8029                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8030
8031       /* If we didn't find a lowpc, set it to highpc to avoid
8032          complaints from `maint check'.  */
8033       if (lowpc == ((CORE_ADDR) -1))
8034         lowpc = highpc;
8035
8036       /* If the compilation unit didn't have an explicit address range,
8037          then use the information extracted from its child dies.  */
8038       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8039         {
8040           best_lowpc = lowpc;
8041           best_highpc = highpc;
8042         }
8043     }
8044   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
8045                                                  best_lowpc + baseaddr)
8046                      - baseaddr);
8047   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
8048                                                   best_highpc + baseaddr)
8049                       - baseaddr);
8050
8051   end_psymtab_common (objfile, pst);
8052
8053   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8054     {
8055       int i;
8056       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8057       struct dwarf2_per_cu_data *iter;
8058
8059       /* Fill in 'dependencies' here; we fill in 'users' in a
8060          post-pass.  */
8061       pst->number_of_dependencies = len;
8062       pst->dependencies
8063         = objfile->partial_symtabs->allocate_dependencies (len);
8064       for (i = 0;
8065            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8066                         i, iter);
8067            ++i)
8068         pst->dependencies[i] = iter->v.psymtab;
8069
8070       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8071     }
8072
8073   /* Get the list of files included in the current compilation unit,
8074      and build a psymtab for each of them.  */
8075   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8076
8077   if (dwarf_read_debug)
8078     fprintf_unfiltered (gdb_stdlog,
8079                         "Psymtab for %s unit @%s: %s - %s"
8080                         ", %d global, %d static syms\n",
8081                         per_cu->is_debug_types ? "type" : "comp",
8082                         sect_offset_str (per_cu->sect_off),
8083                         paddress (gdbarch, pst->text_low (objfile)),
8084                         paddress (gdbarch, pst->text_high (objfile)),
8085                         pst->n_global_syms, pst->n_static_syms);
8086 }
8087
8088 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8089    Process compilation unit THIS_CU for a psymtab.  */
8090
8091 static void
8092 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8093                            int want_partial_unit,
8094                            enum language pretend_language)
8095 {
8096   /* If this compilation unit was already read in, free the
8097      cached copy in order to read it in again.  This is
8098      necessary because we skipped some symbols when we first
8099      read in the compilation unit (see load_partial_dies).
8100      This problem could be avoided, but the benefit is unclear.  */
8101   if (this_cu->cu != NULL)
8102     free_one_cached_comp_unit (this_cu);
8103
8104   if (this_cu->is_debug_types)
8105     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8106                              build_type_psymtabs_reader, NULL);
8107   else
8108     {
8109       process_psymtab_comp_unit_data info;
8110       info.want_partial_unit = want_partial_unit;
8111       info.pretend_language = pretend_language;
8112       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8113                                process_psymtab_comp_unit_reader, &info);
8114     }
8115
8116   /* Age out any secondary CUs.  */
8117   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8118 }
8119
8120 /* Reader function for build_type_psymtabs.  */
8121
8122 static void
8123 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8124                             const gdb_byte *info_ptr,
8125                             struct die_info *type_unit_die,
8126                             int has_children,
8127                             void *data)
8128 {
8129   struct dwarf2_per_objfile *dwarf2_per_objfile
8130     = reader->cu->per_cu->dwarf2_per_objfile;
8131   struct objfile *objfile = dwarf2_per_objfile->objfile;
8132   struct dwarf2_cu *cu = reader->cu;
8133   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8134   struct signatured_type *sig_type;
8135   struct type_unit_group *tu_group;
8136   struct attribute *attr;
8137   struct partial_die_info *first_die;
8138   CORE_ADDR lowpc, highpc;
8139   struct partial_symtab *pst;
8140
8141   gdb_assert (data == NULL);
8142   gdb_assert (per_cu->is_debug_types);
8143   sig_type = (struct signatured_type *) per_cu;
8144
8145   if (! has_children)
8146     return;
8147
8148   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8149   tu_group = get_type_unit_group (cu, attr);
8150
8151   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8152
8153   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8154   pst = create_partial_symtab (per_cu, "");
8155   pst->anonymous = 1;
8156
8157   first_die = load_partial_dies (reader, info_ptr, 1);
8158
8159   lowpc = (CORE_ADDR) -1;
8160   highpc = (CORE_ADDR) 0;
8161   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8162
8163   end_psymtab_common (objfile, pst);
8164 }
8165
8166 /* Struct used to sort TUs by their abbreviation table offset.  */
8167
8168 struct tu_abbrev_offset
8169 {
8170   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8171   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8172   {}
8173
8174   signatured_type *sig_type;
8175   sect_offset abbrev_offset;
8176 };
8177
8178 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8179
8180 static bool
8181 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8182                           const struct tu_abbrev_offset &b)
8183 {
8184   return a.abbrev_offset < b.abbrev_offset;
8185 }
8186
8187 /* Efficiently read all the type units.
8188    This does the bulk of the work for build_type_psymtabs.
8189
8190    The efficiency is because we sort TUs by the abbrev table they use and
8191    only read each abbrev table once.  In one program there are 200K TUs
8192    sharing 8K abbrev tables.
8193
8194    The main purpose of this function is to support building the
8195    dwarf2_per_objfile->type_unit_groups table.
8196    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8197    can collapse the search space by grouping them by stmt_list.
8198    The savings can be significant, in the same program from above the 200K TUs
8199    share 8K stmt_list tables.
8200
8201    FUNC is expected to call get_type_unit_group, which will create the
8202    struct type_unit_group if necessary and add it to
8203    dwarf2_per_objfile->type_unit_groups.  */
8204
8205 static void
8206 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8207 {
8208   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8209   abbrev_table_up abbrev_table;
8210   sect_offset abbrev_offset;
8211
8212   /* It's up to the caller to not call us multiple times.  */
8213   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8214
8215   if (dwarf2_per_objfile->all_type_units.empty ())
8216     return;
8217
8218   /* TUs typically share abbrev tables, and there can be way more TUs than
8219      abbrev tables.  Sort by abbrev table to reduce the number of times we
8220      read each abbrev table in.
8221      Alternatives are to punt or to maintain a cache of abbrev tables.
8222      This is simpler and efficient enough for now.
8223
8224      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8225      symtab to use).  Typically TUs with the same abbrev offset have the same
8226      stmt_list value too so in practice this should work well.
8227
8228      The basic algorithm here is:
8229
8230       sort TUs by abbrev table
8231       for each TU with same abbrev table:
8232         read abbrev table if first user
8233         read TU top level DIE
8234           [IWBN if DWO skeletons had DW_AT_stmt_list]
8235         call FUNC  */
8236
8237   if (dwarf_read_debug)
8238     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8239
8240   /* Sort in a separate table to maintain the order of all_type_units
8241      for .gdb_index: TU indices directly index all_type_units.  */
8242   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8243   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8244
8245   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8246     sorted_by_abbrev.emplace_back
8247       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8248                                      sig_type->per_cu.section,
8249                                      sig_type->per_cu.sect_off));
8250
8251   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8252              sort_tu_by_abbrev_offset);
8253
8254   abbrev_offset = (sect_offset) ~(unsigned) 0;
8255
8256   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8257     {
8258       /* Switch to the next abbrev table if necessary.  */
8259       if (abbrev_table == NULL
8260           || tu.abbrev_offset != abbrev_offset)
8261         {
8262           abbrev_offset = tu.abbrev_offset;
8263           abbrev_table =
8264             abbrev_table_read_table (dwarf2_per_objfile,
8265                                      &dwarf2_per_objfile->abbrev,
8266                                      abbrev_offset);
8267           ++tu_stats->nr_uniq_abbrev_tables;
8268         }
8269
8270       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8271                                0, 0, false, build_type_psymtabs_reader, NULL);
8272     }
8273 }
8274
8275 /* Print collected type unit statistics.  */
8276
8277 static void
8278 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8279 {
8280   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8281
8282   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8283   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8284                       dwarf2_per_objfile->all_type_units.size ());
8285   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8286                       tu_stats->nr_uniq_abbrev_tables);
8287   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8288                       tu_stats->nr_symtabs);
8289   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8290                       tu_stats->nr_symtab_sharers);
8291   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8292                       tu_stats->nr_stmt_less_type_units);
8293   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8294                       tu_stats->nr_all_type_units_reallocs);
8295 }
8296
8297 /* Traversal function for build_type_psymtabs.  */
8298
8299 static int
8300 build_type_psymtab_dependencies (void **slot, void *info)
8301 {
8302   struct dwarf2_per_objfile *dwarf2_per_objfile
8303     = (struct dwarf2_per_objfile *) info;
8304   struct objfile *objfile = dwarf2_per_objfile->objfile;
8305   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8306   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8307   struct partial_symtab *pst = per_cu->v.psymtab;
8308   int len = VEC_length (sig_type_ptr, tu_group->tus);
8309   struct signatured_type *iter;
8310   int i;
8311
8312   gdb_assert (len > 0);
8313   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8314
8315   pst->number_of_dependencies = len;
8316   pst->dependencies = objfile->partial_symtabs->allocate_dependencies (len);
8317   for (i = 0;
8318        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8319        ++i)
8320     {
8321       gdb_assert (iter->per_cu.is_debug_types);
8322       pst->dependencies[i] = iter->per_cu.v.psymtab;
8323       iter->type_unit_group = tu_group;
8324     }
8325
8326   VEC_free (sig_type_ptr, tu_group->tus);
8327
8328   return 1;
8329 }
8330
8331 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8332    Build partial symbol tables for the .debug_types comp-units.  */
8333
8334 static void
8335 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8336 {
8337   if (! create_all_type_units (dwarf2_per_objfile))
8338     return;
8339
8340   build_type_psymtabs_1 (dwarf2_per_objfile);
8341 }
8342
8343 /* Traversal function for process_skeletonless_type_unit.
8344    Read a TU in a DWO file and build partial symbols for it.  */
8345
8346 static int
8347 process_skeletonless_type_unit (void **slot, void *info)
8348 {
8349   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8350   struct dwarf2_per_objfile *dwarf2_per_objfile
8351     = (struct dwarf2_per_objfile *) info;
8352   struct signatured_type find_entry, *entry;
8353
8354   /* If this TU doesn't exist in the global table, add it and read it in.  */
8355
8356   if (dwarf2_per_objfile->signatured_types == NULL)
8357     {
8358       dwarf2_per_objfile->signatured_types
8359         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8360     }
8361
8362   find_entry.signature = dwo_unit->signature;
8363   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8364                          INSERT);
8365   /* If we've already seen this type there's nothing to do.  What's happening
8366      is we're doing our own version of comdat-folding here.  */
8367   if (*slot != NULL)
8368     return 1;
8369
8370   /* This does the job that create_all_type_units would have done for
8371      this TU.  */
8372   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8373   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8374   *slot = entry;
8375
8376   /* This does the job that build_type_psymtabs_1 would have done.  */
8377   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8378                            build_type_psymtabs_reader, NULL);
8379
8380   return 1;
8381 }
8382
8383 /* Traversal function for process_skeletonless_type_units.  */
8384
8385 static int
8386 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8387 {
8388   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8389
8390   if (dwo_file->tus != NULL)
8391     {
8392       htab_traverse_noresize (dwo_file->tus,
8393                               process_skeletonless_type_unit, info);
8394     }
8395
8396   return 1;
8397 }
8398
8399 /* Scan all TUs of DWO files, verifying we've processed them.
8400    This is needed in case a TU was emitted without its skeleton.
8401    Note: This can't be done until we know what all the DWO files are.  */
8402
8403 static void
8404 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8405 {
8406   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8407   if (get_dwp_file (dwarf2_per_objfile) == NULL
8408       && dwarf2_per_objfile->dwo_files != NULL)
8409     {
8410       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8411                               process_dwo_file_for_skeletonless_type_units,
8412                               dwarf2_per_objfile);
8413     }
8414 }
8415
8416 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8417
8418 static void
8419 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8420 {
8421   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8422     {
8423       struct partial_symtab *pst = per_cu->v.psymtab;
8424
8425       if (pst == NULL)
8426         continue;
8427
8428       for (int j = 0; j < pst->number_of_dependencies; ++j)
8429         {
8430           /* Set the 'user' field only if it is not already set.  */
8431           if (pst->dependencies[j]->user == NULL)
8432             pst->dependencies[j]->user = pst;
8433         }
8434     }
8435 }
8436
8437 /* Build the partial symbol table by doing a quick pass through the
8438    .debug_info and .debug_abbrev sections.  */
8439
8440 static void
8441 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8442 {
8443   struct objfile *objfile = dwarf2_per_objfile->objfile;
8444
8445   if (dwarf_read_debug)
8446     {
8447       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8448                           objfile_name (objfile));
8449     }
8450
8451   dwarf2_per_objfile->reading_partial_symbols = 1;
8452
8453   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8454
8455   /* Any cached compilation units will be linked by the per-objfile
8456      read_in_chain.  Make sure to free them when we're done.  */
8457   free_cached_comp_units freer (dwarf2_per_objfile);
8458
8459   build_type_psymtabs (dwarf2_per_objfile);
8460
8461   create_all_comp_units (dwarf2_per_objfile);
8462
8463   /* Create a temporary address map on a temporary obstack.  We later
8464      copy this to the final obstack.  */
8465   auto_obstack temp_obstack;
8466
8467   scoped_restore save_psymtabs_addrmap
8468     = make_scoped_restore (&objfile->partial_symtabs->psymtabs_addrmap,
8469                            addrmap_create_mutable (&temp_obstack));
8470
8471   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8472     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8473
8474   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8475   process_skeletonless_type_units (dwarf2_per_objfile);
8476
8477   /* Now that all TUs have been processed we can fill in the dependencies.  */
8478   if (dwarf2_per_objfile->type_unit_groups != NULL)
8479     {
8480       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8481                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8482     }
8483
8484   if (dwarf_read_debug)
8485     print_tu_stats (dwarf2_per_objfile);
8486
8487   set_partial_user (dwarf2_per_objfile);
8488
8489   objfile->partial_symtabs->psymtabs_addrmap
8490     = addrmap_create_fixed (objfile->partial_symtabs->psymtabs_addrmap,
8491                             objfile->partial_symtabs->obstack ());
8492   /* At this point we want to keep the address map.  */
8493   save_psymtabs_addrmap.release ();
8494
8495   if (dwarf_read_debug)
8496     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8497                         objfile_name (objfile));
8498 }
8499
8500 /* die_reader_func for load_partial_comp_unit.  */
8501
8502 static void
8503 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8504                                const gdb_byte *info_ptr,
8505                                struct die_info *comp_unit_die,
8506                                int has_children,
8507                                void *data)
8508 {
8509   struct dwarf2_cu *cu = reader->cu;
8510
8511   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8512
8513   /* Check if comp unit has_children.
8514      If so, read the rest of the partial symbols from this comp unit.
8515      If not, there's no more debug_info for this comp unit.  */
8516   if (has_children)
8517     load_partial_dies (reader, info_ptr, 0);
8518 }
8519
8520 /* Load the partial DIEs for a secondary CU into memory.
8521    This is also used when rereading a primary CU with load_all_dies.  */
8522
8523 static void
8524 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8525 {
8526   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8527                            load_partial_comp_unit_reader, NULL);
8528 }
8529
8530 static void
8531 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8532                               struct dwarf2_section_info *section,
8533                               struct dwarf2_section_info *abbrev_section,
8534                               unsigned int is_dwz)
8535 {
8536   const gdb_byte *info_ptr;
8537   struct objfile *objfile = dwarf2_per_objfile->objfile;
8538
8539   if (dwarf_read_debug)
8540     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8541                         get_section_name (section),
8542                         get_section_file_name (section));
8543
8544   dwarf2_read_section (objfile, section);
8545
8546   info_ptr = section->buffer;
8547
8548   while (info_ptr < section->buffer + section->size)
8549     {
8550       struct dwarf2_per_cu_data *this_cu;
8551
8552       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8553
8554       comp_unit_head cu_header;
8555       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8556                                      abbrev_section, info_ptr,
8557                                      rcuh_kind::COMPILE);
8558
8559       /* Save the compilation unit for later lookup.  */
8560       if (cu_header.unit_type != DW_UT_type)
8561         {
8562           this_cu = XOBNEW (&objfile->objfile_obstack,
8563                             struct dwarf2_per_cu_data);
8564           memset (this_cu, 0, sizeof (*this_cu));
8565         }
8566       else
8567         {
8568           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8569                                   struct signatured_type);
8570           memset (sig_type, 0, sizeof (*sig_type));
8571           sig_type->signature = cu_header.signature;
8572           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8573           this_cu = &sig_type->per_cu;
8574         }
8575       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8576       this_cu->sect_off = sect_off;
8577       this_cu->length = cu_header.length + cu_header.initial_length_size;
8578       this_cu->is_dwz = is_dwz;
8579       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8580       this_cu->section = section;
8581
8582       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8583
8584       info_ptr = info_ptr + this_cu->length;
8585     }
8586 }
8587
8588 /* Create a list of all compilation units in OBJFILE.
8589    This is only done for -readnow and building partial symtabs.  */
8590
8591 static void
8592 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8593 {
8594   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8595   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8596                                 &dwarf2_per_objfile->abbrev, 0);
8597
8598   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8599   if (dwz != NULL)
8600     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8601                                   1);
8602 }
8603
8604 /* Process all loaded DIEs for compilation unit CU, starting at
8605    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8606    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8607    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8608    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8609
8610 static void
8611 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8612                       CORE_ADDR *highpc, int set_addrmap,
8613                       struct dwarf2_cu *cu)
8614 {
8615   struct partial_die_info *pdi;
8616
8617   /* Now, march along the PDI's, descending into ones which have
8618      interesting children but skipping the children of the other ones,
8619      until we reach the end of the compilation unit.  */
8620
8621   pdi = first_die;
8622
8623   while (pdi != NULL)
8624     {
8625       pdi->fixup (cu);
8626
8627       /* Anonymous namespaces or modules have no name but have interesting
8628          children, so we need to look at them.  Ditto for anonymous
8629          enums.  */
8630
8631       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8632           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8633           || pdi->tag == DW_TAG_imported_unit
8634           || pdi->tag == DW_TAG_inlined_subroutine)
8635         {
8636           switch (pdi->tag)
8637             {
8638             case DW_TAG_subprogram:
8639             case DW_TAG_inlined_subroutine:
8640               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8641               break;
8642             case DW_TAG_constant:
8643             case DW_TAG_variable:
8644             case DW_TAG_typedef:
8645             case DW_TAG_union_type:
8646               if (!pdi->is_declaration)
8647                 {
8648                   add_partial_symbol (pdi, cu);
8649                 }
8650               break;
8651             case DW_TAG_class_type:
8652             case DW_TAG_interface_type:
8653             case DW_TAG_structure_type:
8654               if (!pdi->is_declaration)
8655                 {
8656                   add_partial_symbol (pdi, cu);
8657                 }
8658               if ((cu->language == language_rust
8659                    || cu->language == language_cplus) && pdi->has_children)
8660                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8661                                       set_addrmap, cu);
8662               break;
8663             case DW_TAG_enumeration_type:
8664               if (!pdi->is_declaration)
8665                 add_partial_enumeration (pdi, cu);
8666               break;
8667             case DW_TAG_base_type:
8668             case DW_TAG_subrange_type:
8669               /* File scope base type definitions are added to the partial
8670                  symbol table.  */
8671               add_partial_symbol (pdi, cu);
8672               break;
8673             case DW_TAG_namespace:
8674               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8675               break;
8676             case DW_TAG_module:
8677               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8678               break;
8679             case DW_TAG_imported_unit:
8680               {
8681                 struct dwarf2_per_cu_data *per_cu;
8682
8683                 /* For now we don't handle imported units in type units.  */
8684                 if (cu->per_cu->is_debug_types)
8685                   {
8686                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8687                              " supported in type units [in module %s]"),
8688                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8689                   }
8690
8691                 per_cu = dwarf2_find_containing_comp_unit
8692                            (pdi->d.sect_off, pdi->is_dwz,
8693                             cu->per_cu->dwarf2_per_objfile);
8694
8695                 /* Go read the partial unit, if needed.  */
8696                 if (per_cu->v.psymtab == NULL)
8697                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8698
8699                 VEC_safe_push (dwarf2_per_cu_ptr,
8700                                cu->per_cu->imported_symtabs, per_cu);
8701               }
8702               break;
8703             case DW_TAG_imported_declaration:
8704               add_partial_symbol (pdi, cu);
8705               break;
8706             default:
8707               break;
8708             }
8709         }
8710
8711       /* If the die has a sibling, skip to the sibling.  */
8712
8713       pdi = pdi->die_sibling;
8714     }
8715 }
8716
8717 /* Functions used to compute the fully scoped name of a partial DIE.
8718
8719    Normally, this is simple.  For C++, the parent DIE's fully scoped
8720    name is concatenated with "::" and the partial DIE's name.
8721    Enumerators are an exception; they use the scope of their parent
8722    enumeration type, i.e. the name of the enumeration type is not
8723    prepended to the enumerator.
8724
8725    There are two complexities.  One is DW_AT_specification; in this
8726    case "parent" means the parent of the target of the specification,
8727    instead of the direct parent of the DIE.  The other is compilers
8728    which do not emit DW_TAG_namespace; in this case we try to guess
8729    the fully qualified name of structure types from their members'
8730    linkage names.  This must be done using the DIE's children rather
8731    than the children of any DW_AT_specification target.  We only need
8732    to do this for structures at the top level, i.e. if the target of
8733    any DW_AT_specification (if any; otherwise the DIE itself) does not
8734    have a parent.  */
8735
8736 /* Compute the scope prefix associated with PDI's parent, in
8737    compilation unit CU.  The result will be allocated on CU's
8738    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8739    field.  NULL is returned if no prefix is necessary.  */
8740 static const char *
8741 partial_die_parent_scope (struct partial_die_info *pdi,
8742                           struct dwarf2_cu *cu)
8743 {
8744   const char *grandparent_scope;
8745   struct partial_die_info *parent, *real_pdi;
8746
8747   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8748      then this means the parent of the specification DIE.  */
8749
8750   real_pdi = pdi;
8751   while (real_pdi->has_specification)
8752     {
8753       auto res = find_partial_die (real_pdi->spec_offset,
8754                                    real_pdi->spec_is_dwz, cu);
8755       real_pdi = res.pdi;
8756       cu = res.cu;
8757     }
8758
8759   parent = real_pdi->die_parent;
8760   if (parent == NULL)
8761     return NULL;
8762
8763   if (parent->scope_set)
8764     return parent->scope;
8765
8766   parent->fixup (cu);
8767
8768   grandparent_scope = partial_die_parent_scope (parent, cu);
8769
8770   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8771      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8772      Work around this problem here.  */
8773   if (cu->language == language_cplus
8774       && parent->tag == DW_TAG_namespace
8775       && strcmp (parent->name, "::") == 0
8776       && grandparent_scope == NULL)
8777     {
8778       parent->scope = NULL;
8779       parent->scope_set = 1;
8780       return NULL;
8781     }
8782
8783   if (pdi->tag == DW_TAG_enumerator)
8784     /* Enumerators should not get the name of the enumeration as a prefix.  */
8785     parent->scope = grandparent_scope;
8786   else if (parent->tag == DW_TAG_namespace
8787       || parent->tag == DW_TAG_module
8788       || parent->tag == DW_TAG_structure_type
8789       || parent->tag == DW_TAG_class_type
8790       || parent->tag == DW_TAG_interface_type
8791       || parent->tag == DW_TAG_union_type
8792       || parent->tag == DW_TAG_enumeration_type)
8793     {
8794       if (grandparent_scope == NULL)
8795         parent->scope = parent->name;
8796       else
8797         parent->scope = typename_concat (&cu->comp_unit_obstack,
8798                                          grandparent_scope,
8799                                          parent->name, 0, cu);
8800     }
8801   else
8802     {
8803       /* FIXME drow/2004-04-01: What should we be doing with
8804          function-local names?  For partial symbols, we should probably be
8805          ignoring them.  */
8806       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
8807                  dwarf_tag_name (parent->tag),
8808                  sect_offset_str (pdi->sect_off));
8809       parent->scope = grandparent_scope;
8810     }
8811
8812   parent->scope_set = 1;
8813   return parent->scope;
8814 }
8815
8816 /* Return the fully scoped name associated with PDI, from compilation unit
8817    CU.  The result will be allocated with malloc.  */
8818
8819 static char *
8820 partial_die_full_name (struct partial_die_info *pdi,
8821                        struct dwarf2_cu *cu)
8822 {
8823   const char *parent_scope;
8824
8825   /* If this is a template instantiation, we can not work out the
8826      template arguments from partial DIEs.  So, unfortunately, we have
8827      to go through the full DIEs.  At least any work we do building
8828      types here will be reused if full symbols are loaded later.  */
8829   if (pdi->has_template_arguments)
8830     {
8831       pdi->fixup (cu);
8832
8833       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8834         {
8835           struct die_info *die;
8836           struct attribute attr;
8837           struct dwarf2_cu *ref_cu = cu;
8838
8839           /* DW_FORM_ref_addr is using section offset.  */
8840           attr.name = (enum dwarf_attribute) 0;
8841           attr.form = DW_FORM_ref_addr;
8842           attr.u.unsnd = to_underlying (pdi->sect_off);
8843           die = follow_die_ref (NULL, &attr, &ref_cu);
8844
8845           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8846         }
8847     }
8848
8849   parent_scope = partial_die_parent_scope (pdi, cu);
8850   if (parent_scope == NULL)
8851     return NULL;
8852   else
8853     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8854 }
8855
8856 static void
8857 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8858 {
8859   struct dwarf2_per_objfile *dwarf2_per_objfile
8860     = cu->per_cu->dwarf2_per_objfile;
8861   struct objfile *objfile = dwarf2_per_objfile->objfile;
8862   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8863   CORE_ADDR addr = 0;
8864   const char *actual_name = NULL;
8865   CORE_ADDR baseaddr;
8866   char *built_actual_name;
8867
8868   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8869
8870   built_actual_name = partial_die_full_name (pdi, cu);
8871   if (built_actual_name != NULL)
8872     actual_name = built_actual_name;
8873
8874   if (actual_name == NULL)
8875     actual_name = pdi->name;
8876
8877   switch (pdi->tag)
8878     {
8879     case DW_TAG_inlined_subroutine:
8880     case DW_TAG_subprogram:
8881       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8882               - baseaddr);
8883       if (pdi->is_external || cu->language == language_ada)
8884         {
8885           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8886              of the global scope.  But in Ada, we want to be able to access
8887              nested procedures globally.  So all Ada subprograms are stored
8888              in the global scope.  */
8889           add_psymbol_to_list (actual_name, strlen (actual_name),
8890                                built_actual_name != NULL,
8891                                VAR_DOMAIN, LOC_BLOCK,
8892                                SECT_OFF_TEXT (objfile),
8893                                psymbol_placement::GLOBAL,
8894                                addr,
8895                                cu->language, objfile);
8896         }
8897       else
8898         {
8899           add_psymbol_to_list (actual_name, strlen (actual_name),
8900                                built_actual_name != NULL,
8901                                VAR_DOMAIN, LOC_BLOCK,
8902                                SECT_OFF_TEXT (objfile),
8903                                psymbol_placement::STATIC,
8904                                addr, cu->language, objfile);
8905         }
8906
8907       if (pdi->main_subprogram && actual_name != NULL)
8908         set_objfile_main_name (objfile, actual_name, cu->language);
8909       break;
8910     case DW_TAG_constant:
8911       add_psymbol_to_list (actual_name, strlen (actual_name),
8912                            built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8913                            -1, (pdi->is_external
8914                                 ? psymbol_placement::GLOBAL
8915                                 : psymbol_placement::STATIC),
8916                            0, cu->language, objfile);
8917       break;
8918     case DW_TAG_variable:
8919       if (pdi->d.locdesc)
8920         addr = decode_locdesc (pdi->d.locdesc, cu);
8921
8922       if (pdi->d.locdesc
8923           && addr == 0
8924           && !dwarf2_per_objfile->has_section_at_zero)
8925         {
8926           /* A global or static variable may also have been stripped
8927              out by the linker if unused, in which case its address
8928              will be nullified; do not add such variables into partial
8929              symbol table then.  */
8930         }
8931       else if (pdi->is_external)
8932         {
8933           /* Global Variable.
8934              Don't enter into the minimal symbol tables as there is
8935              a minimal symbol table entry from the ELF symbols already.
8936              Enter into partial symbol table if it has a location
8937              descriptor or a type.
8938              If the location descriptor is missing, new_symbol will create
8939              a LOC_UNRESOLVED symbol, the address of the variable will then
8940              be determined from the minimal symbol table whenever the variable
8941              is referenced.
8942              The address for the partial symbol table entry is not
8943              used by GDB, but it comes in handy for debugging partial symbol
8944              table building.  */
8945
8946           if (pdi->d.locdesc || pdi->has_type)
8947             add_psymbol_to_list (actual_name, strlen (actual_name),
8948                                  built_actual_name != NULL,
8949                                  VAR_DOMAIN, LOC_STATIC,
8950                                  SECT_OFF_TEXT (objfile),
8951                                  psymbol_placement::GLOBAL,
8952                                  addr, cu->language, objfile);
8953         }
8954       else
8955         {
8956           int has_loc = pdi->d.locdesc != NULL;
8957
8958           /* Static Variable.  Skip symbols whose value we cannot know (those
8959              without location descriptors or constant values).  */
8960           if (!has_loc && !pdi->has_const_value)
8961             {
8962               xfree (built_actual_name);
8963               return;
8964             }
8965
8966           add_psymbol_to_list (actual_name, strlen (actual_name),
8967                                built_actual_name != NULL,
8968                                VAR_DOMAIN, LOC_STATIC,
8969                                SECT_OFF_TEXT (objfile),
8970                                psymbol_placement::STATIC,
8971                                has_loc ? addr : 0,
8972                                cu->language, objfile);
8973         }
8974       break;
8975     case DW_TAG_typedef:
8976     case DW_TAG_base_type:
8977     case DW_TAG_subrange_type:
8978       add_psymbol_to_list (actual_name, strlen (actual_name),
8979                            built_actual_name != NULL,
8980                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8981                            psymbol_placement::STATIC,
8982                            0, cu->language, objfile);
8983       break;
8984     case DW_TAG_imported_declaration:
8985     case DW_TAG_namespace:
8986       add_psymbol_to_list (actual_name, strlen (actual_name),
8987                            built_actual_name != NULL,
8988                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8989                            psymbol_placement::GLOBAL,
8990                            0, cu->language, objfile);
8991       break;
8992     case DW_TAG_module:
8993       /* With Fortran 77 there might be a "BLOCK DATA" module
8994          available without any name.  If so, we skip the module as it
8995          doesn't bring any value.  */
8996       if (actual_name != nullptr)
8997         add_psymbol_to_list (actual_name, strlen (actual_name),
8998                              built_actual_name != NULL,
8999                              MODULE_DOMAIN, LOC_TYPEDEF, -1,
9000                              psymbol_placement::GLOBAL,
9001                              0, cu->language, objfile);
9002       break;
9003     case DW_TAG_class_type:
9004     case DW_TAG_interface_type:
9005     case DW_TAG_structure_type:
9006     case DW_TAG_union_type:
9007     case DW_TAG_enumeration_type:
9008       /* Skip external references.  The DWARF standard says in the section
9009          about "Structure, Union, and Class Type Entries": "An incomplete
9010          structure, union or class type is represented by a structure,
9011          union or class entry that does not have a byte size attribute
9012          and that has a DW_AT_declaration attribute."  */
9013       if (!pdi->has_byte_size && pdi->is_declaration)
9014         {
9015           xfree (built_actual_name);
9016           return;
9017         }
9018
9019       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9020          static vs. global.  */
9021       add_psymbol_to_list (actual_name, strlen (actual_name),
9022                            built_actual_name != NULL,
9023                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
9024                            cu->language == language_cplus
9025                            ? psymbol_placement::GLOBAL
9026                            : psymbol_placement::STATIC,
9027                            0, cu->language, objfile);
9028
9029       break;
9030     case DW_TAG_enumerator:
9031       add_psymbol_to_list (actual_name, strlen (actual_name),
9032                            built_actual_name != NULL,
9033                            VAR_DOMAIN, LOC_CONST, -1,
9034                            cu->language == language_cplus
9035                            ? psymbol_placement::GLOBAL
9036                            : psymbol_placement::STATIC,
9037                            0, cu->language, objfile);
9038       break;
9039     default:
9040       break;
9041     }
9042
9043   xfree (built_actual_name);
9044 }
9045
9046 /* Read a partial die corresponding to a namespace; also, add a symbol
9047    corresponding to that namespace to the symbol table.  NAMESPACE is
9048    the name of the enclosing namespace.  */
9049
9050 static void
9051 add_partial_namespace (struct partial_die_info *pdi,
9052                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9053                        int set_addrmap, struct dwarf2_cu *cu)
9054 {
9055   /* Add a symbol for the namespace.  */
9056
9057   add_partial_symbol (pdi, cu);
9058
9059   /* Now scan partial symbols in that namespace.  */
9060
9061   if (pdi->has_children)
9062     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9063 }
9064
9065 /* Read a partial die corresponding to a Fortran module.  */
9066
9067 static void
9068 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9069                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9070 {
9071   /* Add a symbol for the namespace.  */
9072
9073   add_partial_symbol (pdi, cu);
9074
9075   /* Now scan partial symbols in that module.  */
9076
9077   if (pdi->has_children)
9078     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9079 }
9080
9081 /* Read a partial die corresponding to a subprogram or an inlined
9082    subprogram and create a partial symbol for that subprogram.
9083    When the CU language allows it, this routine also defines a partial
9084    symbol for each nested subprogram that this subprogram contains.
9085    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9086    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9087
9088    PDI may also be a lexical block, in which case we simply search
9089    recursively for subprograms defined inside that lexical block.
9090    Again, this is only performed when the CU language allows this
9091    type of definitions.  */
9092
9093 static void
9094 add_partial_subprogram (struct partial_die_info *pdi,
9095                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9096                         int set_addrmap, struct dwarf2_cu *cu)
9097 {
9098   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9099     {
9100       if (pdi->has_pc_info)
9101         {
9102           if (pdi->lowpc < *lowpc)
9103             *lowpc = pdi->lowpc;
9104           if (pdi->highpc > *highpc)
9105             *highpc = pdi->highpc;
9106           if (set_addrmap)
9107             {
9108               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9109               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9110               CORE_ADDR baseaddr;
9111               CORE_ADDR this_highpc;
9112               CORE_ADDR this_lowpc;
9113
9114               baseaddr = ANOFFSET (objfile->section_offsets,
9115                                    SECT_OFF_TEXT (objfile));
9116               this_lowpc
9117                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9118                                                pdi->lowpc + baseaddr)
9119                    - baseaddr);
9120               this_highpc
9121                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9122                                                pdi->highpc + baseaddr)
9123                    - baseaddr);
9124               addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
9125                                  this_lowpc, this_highpc - 1,
9126                                  cu->per_cu->v.psymtab);
9127             }
9128         }
9129
9130       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9131         {
9132           if (!pdi->is_declaration)
9133             /* Ignore subprogram DIEs that do not have a name, they are
9134                illegal.  Do not emit a complaint at this point, we will
9135                do so when we convert this psymtab into a symtab.  */
9136             if (pdi->name)
9137               add_partial_symbol (pdi, cu);
9138         }
9139     }
9140
9141   if (! pdi->has_children)
9142     return;
9143
9144   if (cu->language == language_ada)
9145     {
9146       pdi = pdi->die_child;
9147       while (pdi != NULL)
9148         {
9149           pdi->fixup (cu);
9150           if (pdi->tag == DW_TAG_subprogram
9151               || pdi->tag == DW_TAG_inlined_subroutine
9152               || pdi->tag == DW_TAG_lexical_block)
9153             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9154           pdi = pdi->die_sibling;
9155         }
9156     }
9157 }
9158
9159 /* Read a partial die corresponding to an enumeration type.  */
9160
9161 static void
9162 add_partial_enumeration (struct partial_die_info *enum_pdi,
9163                          struct dwarf2_cu *cu)
9164 {
9165   struct partial_die_info *pdi;
9166
9167   if (enum_pdi->name != NULL)
9168     add_partial_symbol (enum_pdi, cu);
9169
9170   pdi = enum_pdi->die_child;
9171   while (pdi)
9172     {
9173       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9174         complaint (_("malformed enumerator DIE ignored"));
9175       else
9176         add_partial_symbol (pdi, cu);
9177       pdi = pdi->die_sibling;
9178     }
9179 }
9180
9181 /* Return the initial uleb128 in the die at INFO_PTR.  */
9182
9183 static unsigned int
9184 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9185 {
9186   unsigned int bytes_read;
9187
9188   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9189 }
9190
9191 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9192    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9193
9194    Return the corresponding abbrev, or NULL if the number is zero (indicating
9195    an empty DIE).  In either case *BYTES_READ will be set to the length of
9196    the initial number.  */
9197
9198 static struct abbrev_info *
9199 peek_die_abbrev (const die_reader_specs &reader,
9200                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9201 {
9202   dwarf2_cu *cu = reader.cu;
9203   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9204   unsigned int abbrev_number
9205     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9206
9207   if (abbrev_number == 0)
9208     return NULL;
9209
9210   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9211   if (!abbrev)
9212     {
9213       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9214                " at offset %s [in module %s]"),
9215              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9216              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9217     }
9218
9219   return abbrev;
9220 }
9221
9222 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9223    Returns a pointer to the end of a series of DIEs, terminated by an empty
9224    DIE.  Any children of the skipped DIEs will also be skipped.  */
9225
9226 static const gdb_byte *
9227 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9228 {
9229   while (1)
9230     {
9231       unsigned int bytes_read;
9232       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9233
9234       if (abbrev == NULL)
9235         return info_ptr + bytes_read;
9236       else
9237         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9238     }
9239 }
9240
9241 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9242    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9243    abbrev corresponding to that skipped uleb128 should be passed in
9244    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9245    children.  */
9246
9247 static const gdb_byte *
9248 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9249               struct abbrev_info *abbrev)
9250 {
9251   unsigned int bytes_read;
9252   struct attribute attr;
9253   bfd *abfd = reader->abfd;
9254   struct dwarf2_cu *cu = reader->cu;
9255   const gdb_byte *buffer = reader->buffer;
9256   const gdb_byte *buffer_end = reader->buffer_end;
9257   unsigned int form, i;
9258
9259   for (i = 0; i < abbrev->num_attrs; i++)
9260     {
9261       /* The only abbrev we care about is DW_AT_sibling.  */
9262       if (abbrev->attrs[i].name == DW_AT_sibling)
9263         {
9264           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9265           if (attr.form == DW_FORM_ref_addr)
9266             complaint (_("ignoring absolute DW_AT_sibling"));
9267           else
9268             {
9269               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9270               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9271
9272               if (sibling_ptr < info_ptr)
9273                 complaint (_("DW_AT_sibling points backwards"));
9274               else if (sibling_ptr > reader->buffer_end)
9275                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9276               else
9277                 return sibling_ptr;
9278             }
9279         }
9280
9281       /* If it isn't DW_AT_sibling, skip this attribute.  */
9282       form = abbrev->attrs[i].form;
9283     skip_attribute:
9284       switch (form)
9285         {
9286         case DW_FORM_ref_addr:
9287           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9288              and later it is offset sized.  */
9289           if (cu->header.version == 2)
9290             info_ptr += cu->header.addr_size;
9291           else
9292             info_ptr += cu->header.offset_size;
9293           break;
9294         case DW_FORM_GNU_ref_alt:
9295           info_ptr += cu->header.offset_size;
9296           break;
9297         case DW_FORM_addr:
9298           info_ptr += cu->header.addr_size;
9299           break;
9300         case DW_FORM_data1:
9301         case DW_FORM_ref1:
9302         case DW_FORM_flag:
9303           info_ptr += 1;
9304           break;
9305         case DW_FORM_flag_present:
9306         case DW_FORM_implicit_const:
9307           break;
9308         case DW_FORM_data2:
9309         case DW_FORM_ref2:
9310           info_ptr += 2;
9311           break;
9312         case DW_FORM_data4:
9313         case DW_FORM_ref4:
9314           info_ptr += 4;
9315           break;
9316         case DW_FORM_data8:
9317         case DW_FORM_ref8:
9318         case DW_FORM_ref_sig8:
9319           info_ptr += 8;
9320           break;
9321         case DW_FORM_data16:
9322           info_ptr += 16;
9323           break;
9324         case DW_FORM_string:
9325           read_direct_string (abfd, info_ptr, &bytes_read);
9326           info_ptr += bytes_read;
9327           break;
9328         case DW_FORM_sec_offset:
9329         case DW_FORM_strp:
9330         case DW_FORM_GNU_strp_alt:
9331           info_ptr += cu->header.offset_size;
9332           break;
9333         case DW_FORM_exprloc:
9334         case DW_FORM_block:
9335           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9336           info_ptr += bytes_read;
9337           break;
9338         case DW_FORM_block1:
9339           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9340           break;
9341         case DW_FORM_block2:
9342           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9343           break;
9344         case DW_FORM_block4:
9345           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9346           break;
9347         case DW_FORM_addrx:
9348         case DW_FORM_strx:
9349         case DW_FORM_sdata:
9350         case DW_FORM_udata:
9351         case DW_FORM_ref_udata:
9352         case DW_FORM_GNU_addr_index:
9353         case DW_FORM_GNU_str_index:
9354           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9355           break;
9356         case DW_FORM_indirect:
9357           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9358           info_ptr += bytes_read;
9359           /* We need to continue parsing from here, so just go back to
9360              the top.  */
9361           goto skip_attribute;
9362
9363         default:
9364           error (_("Dwarf Error: Cannot handle %s "
9365                    "in DWARF reader [in module %s]"),
9366                  dwarf_form_name (form),
9367                  bfd_get_filename (abfd));
9368         }
9369     }
9370
9371   if (abbrev->has_children)
9372     return skip_children (reader, info_ptr);
9373   else
9374     return info_ptr;
9375 }
9376
9377 /* Locate ORIG_PDI's sibling.
9378    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9379
9380 static const gdb_byte *
9381 locate_pdi_sibling (const struct die_reader_specs *reader,
9382                     struct partial_die_info *orig_pdi,
9383                     const gdb_byte *info_ptr)
9384 {
9385   /* Do we know the sibling already?  */
9386
9387   if (orig_pdi->sibling)
9388     return orig_pdi->sibling;
9389
9390   /* Are there any children to deal with?  */
9391
9392   if (!orig_pdi->has_children)
9393     return info_ptr;
9394
9395   /* Skip the children the long way.  */
9396
9397   return skip_children (reader, info_ptr);
9398 }
9399
9400 /* Expand this partial symbol table into a full symbol table.  SELF is
9401    not NULL.  */
9402
9403 static void
9404 dwarf2_read_symtab (struct partial_symtab *self,
9405                     struct objfile *objfile)
9406 {
9407   struct dwarf2_per_objfile *dwarf2_per_objfile
9408     = get_dwarf2_per_objfile (objfile);
9409
9410   if (self->readin)
9411     {
9412       warning (_("bug: psymtab for %s is already read in."),
9413                self->filename);
9414     }
9415   else
9416     {
9417       if (info_verbose)
9418         {
9419           printf_filtered (_("Reading in symbols for %s..."),
9420                            self->filename);
9421           gdb_flush (gdb_stdout);
9422         }
9423
9424       /* If this psymtab is constructed from a debug-only objfile, the
9425          has_section_at_zero flag will not necessarily be correct.  We
9426          can get the correct value for this flag by looking at the data
9427          associated with the (presumably stripped) associated objfile.  */
9428       if (objfile->separate_debug_objfile_backlink)
9429         {
9430           struct dwarf2_per_objfile *dpo_backlink
9431             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9432
9433           dwarf2_per_objfile->has_section_at_zero
9434             = dpo_backlink->has_section_at_zero;
9435         }
9436
9437       dwarf2_per_objfile->reading_partial_symbols = 0;
9438
9439       psymtab_to_symtab_1 (self);
9440
9441       /* Finish up the debug error message.  */
9442       if (info_verbose)
9443         printf_filtered (_("done.\n"));
9444     }
9445
9446   process_cu_includes (dwarf2_per_objfile);
9447 }
9448 \f
9449 /* Reading in full CUs.  */
9450
9451 /* Add PER_CU to the queue.  */
9452
9453 static void
9454 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9455                  enum language pretend_language)
9456 {
9457   struct dwarf2_queue_item *item;
9458
9459   per_cu->queued = 1;
9460   item = XNEW (struct dwarf2_queue_item);
9461   item->per_cu = per_cu;
9462   item->pretend_language = pretend_language;
9463   item->next = NULL;
9464
9465   if (dwarf2_queue == NULL)
9466     dwarf2_queue = item;
9467   else
9468     dwarf2_queue_tail->next = item;
9469
9470   dwarf2_queue_tail = item;
9471 }
9472
9473 /* If PER_CU is not yet queued, add it to the queue.
9474    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9475    dependency.
9476    The result is non-zero if PER_CU was queued, otherwise the result is zero
9477    meaning either PER_CU is already queued or it is already loaded.
9478
9479    N.B. There is an invariant here that if a CU is queued then it is loaded.
9480    The caller is required to load PER_CU if we return non-zero.  */
9481
9482 static int
9483 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9484                        struct dwarf2_per_cu_data *per_cu,
9485                        enum language pretend_language)
9486 {
9487   /* We may arrive here during partial symbol reading, if we need full
9488      DIEs to process an unusual case (e.g. template arguments).  Do
9489      not queue PER_CU, just tell our caller to load its DIEs.  */
9490   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9491     {
9492       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9493         return 1;
9494       return 0;
9495     }
9496
9497   /* Mark the dependence relation so that we don't flush PER_CU
9498      too early.  */
9499   if (dependent_cu != NULL)
9500     dwarf2_add_dependence (dependent_cu, per_cu);
9501
9502   /* If it's already on the queue, we have nothing to do.  */
9503   if (per_cu->queued)
9504     return 0;
9505
9506   /* If the compilation unit is already loaded, just mark it as
9507      used.  */
9508   if (per_cu->cu != NULL)
9509     {
9510       per_cu->cu->last_used = 0;
9511       return 0;
9512     }
9513
9514   /* Add it to the queue.  */
9515   queue_comp_unit (per_cu, pretend_language);
9516
9517   return 1;
9518 }
9519
9520 /* Process the queue.  */
9521
9522 static void
9523 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9524 {
9525   struct dwarf2_queue_item *item, *next_item;
9526
9527   if (dwarf_read_debug)
9528     {
9529       fprintf_unfiltered (gdb_stdlog,
9530                           "Expanding one or more symtabs of objfile %s ...\n",
9531                           objfile_name (dwarf2_per_objfile->objfile));
9532     }
9533
9534   /* The queue starts out with one item, but following a DIE reference
9535      may load a new CU, adding it to the end of the queue.  */
9536   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9537     {
9538       if ((dwarf2_per_objfile->using_index
9539            ? !item->per_cu->v.quick->compunit_symtab
9540            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9541           /* Skip dummy CUs.  */
9542           && item->per_cu->cu != NULL)
9543         {
9544           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9545           unsigned int debug_print_threshold;
9546           char buf[100];
9547
9548           if (per_cu->is_debug_types)
9549             {
9550               struct signatured_type *sig_type =
9551                 (struct signatured_type *) per_cu;
9552
9553               sprintf (buf, "TU %s at offset %s",
9554                        hex_string (sig_type->signature),
9555                        sect_offset_str (per_cu->sect_off));
9556               /* There can be 100s of TUs.
9557                  Only print them in verbose mode.  */
9558               debug_print_threshold = 2;
9559             }
9560           else
9561             {
9562               sprintf (buf, "CU at offset %s",
9563                        sect_offset_str (per_cu->sect_off));
9564               debug_print_threshold = 1;
9565             }
9566
9567           if (dwarf_read_debug >= debug_print_threshold)
9568             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9569
9570           if (per_cu->is_debug_types)
9571             process_full_type_unit (per_cu, item->pretend_language);
9572           else
9573             process_full_comp_unit (per_cu, item->pretend_language);
9574
9575           if (dwarf_read_debug >= debug_print_threshold)
9576             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9577         }
9578
9579       item->per_cu->queued = 0;
9580       next_item = item->next;
9581       xfree (item);
9582     }
9583
9584   dwarf2_queue_tail = NULL;
9585
9586   if (dwarf_read_debug)
9587     {
9588       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9589                           objfile_name (dwarf2_per_objfile->objfile));
9590     }
9591 }
9592
9593 /* Read in full symbols for PST, and anything it depends on.  */
9594
9595 static void
9596 psymtab_to_symtab_1 (struct partial_symtab *pst)
9597 {
9598   struct dwarf2_per_cu_data *per_cu;
9599   int i;
9600
9601   if (pst->readin)
9602     return;
9603
9604   for (i = 0; i < pst->number_of_dependencies; i++)
9605     if (!pst->dependencies[i]->readin
9606         && pst->dependencies[i]->user == NULL)
9607       {
9608         /* Inform about additional files that need to be read in.  */
9609         if (info_verbose)
9610           {
9611             /* FIXME: i18n: Need to make this a single string.  */
9612             fputs_filtered (" ", gdb_stdout);
9613             wrap_here ("");
9614             fputs_filtered ("and ", gdb_stdout);
9615             wrap_here ("");
9616             printf_filtered ("%s...", pst->dependencies[i]->filename);
9617             wrap_here ("");     /* Flush output.  */
9618             gdb_flush (gdb_stdout);
9619           }
9620         psymtab_to_symtab_1 (pst->dependencies[i]);
9621       }
9622
9623   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9624
9625   if (per_cu == NULL)
9626     {
9627       /* It's an include file, no symbols to read for it.
9628          Everything is in the parent symtab.  */
9629       pst->readin = 1;
9630       return;
9631     }
9632
9633   dw2_do_instantiate_symtab (per_cu, false);
9634 }
9635
9636 /* Trivial hash function for die_info: the hash value of a DIE
9637    is its offset in .debug_info for this objfile.  */
9638
9639 static hashval_t
9640 die_hash (const void *item)
9641 {
9642   const struct die_info *die = (const struct die_info *) item;
9643
9644   return to_underlying (die->sect_off);
9645 }
9646
9647 /* Trivial comparison function for die_info structures: two DIEs
9648    are equal if they have the same offset.  */
9649
9650 static int
9651 die_eq (const void *item_lhs, const void *item_rhs)
9652 {
9653   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9654   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9655
9656   return die_lhs->sect_off == die_rhs->sect_off;
9657 }
9658
9659 /* die_reader_func for load_full_comp_unit.
9660    This is identical to read_signatured_type_reader,
9661    but is kept separate for now.  */
9662
9663 static void
9664 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9665                             const gdb_byte *info_ptr,
9666                             struct die_info *comp_unit_die,
9667                             int has_children,
9668                             void *data)
9669 {
9670   struct dwarf2_cu *cu = reader->cu;
9671   enum language *language_ptr = (enum language *) data;
9672
9673   gdb_assert (cu->die_hash == NULL);
9674   cu->die_hash =
9675     htab_create_alloc_ex (cu->header.length / 12,
9676                           die_hash,
9677                           die_eq,
9678                           NULL,
9679                           &cu->comp_unit_obstack,
9680                           hashtab_obstack_allocate,
9681                           dummy_obstack_deallocate);
9682
9683   if (has_children)
9684     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9685                                                   &info_ptr, comp_unit_die);
9686   cu->dies = comp_unit_die;
9687   /* comp_unit_die is not stored in die_hash, no need.  */
9688
9689   /* We try not to read any attributes in this function, because not
9690      all CUs needed for references have been loaded yet, and symbol
9691      table processing isn't initialized.  But we have to set the CU language,
9692      or we won't be able to build types correctly.
9693      Similarly, if we do not read the producer, we can not apply
9694      producer-specific interpretation.  */
9695   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9696 }
9697
9698 /* Load the DIEs associated with PER_CU into memory.  */
9699
9700 static void
9701 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9702                      bool skip_partial,
9703                      enum language pretend_language)
9704 {
9705   gdb_assert (! this_cu->is_debug_types);
9706
9707   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9708                            load_full_comp_unit_reader, &pretend_language);
9709 }
9710
9711 /* Add a DIE to the delayed physname list.  */
9712
9713 static void
9714 add_to_method_list (struct type *type, int fnfield_index, int index,
9715                     const char *name, struct die_info *die,
9716                     struct dwarf2_cu *cu)
9717 {
9718   struct delayed_method_info mi;
9719   mi.type = type;
9720   mi.fnfield_index = fnfield_index;
9721   mi.index = index;
9722   mi.name = name;
9723   mi.die = die;
9724   cu->method_list.push_back (mi);
9725 }
9726
9727 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9728    "const" / "volatile".  If so, decrements LEN by the length of the
9729    modifier and return true.  Otherwise return false.  */
9730
9731 template<size_t N>
9732 static bool
9733 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9734 {
9735   size_t mod_len = sizeof (mod) - 1;
9736   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9737     {
9738       len -= mod_len;
9739       return true;
9740     }
9741   return false;
9742 }
9743
9744 /* Compute the physnames of any methods on the CU's method list.
9745
9746    The computation of method physnames is delayed in order to avoid the
9747    (bad) condition that one of the method's formal parameters is of an as yet
9748    incomplete type.  */
9749
9750 static void
9751 compute_delayed_physnames (struct dwarf2_cu *cu)
9752 {
9753   /* Only C++ delays computing physnames.  */
9754   if (cu->method_list.empty ())
9755     return;
9756   gdb_assert (cu->language == language_cplus);
9757
9758   for (const delayed_method_info &mi : cu->method_list)
9759     {
9760       const char *physname;
9761       struct fn_fieldlist *fn_flp
9762         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9763       physname = dwarf2_physname (mi.name, mi.die, cu);
9764       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9765         = physname ? physname : "";
9766
9767       /* Since there's no tag to indicate whether a method is a
9768          const/volatile overload, extract that information out of the
9769          demangled name.  */
9770       if (physname != NULL)
9771         {
9772           size_t len = strlen (physname);
9773
9774           while (1)
9775             {
9776               if (physname[len] == ')') /* shortcut */
9777                 break;
9778               else if (check_modifier (physname, len, " const"))
9779                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9780               else if (check_modifier (physname, len, " volatile"))
9781                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9782               else
9783                 break;
9784             }
9785         }
9786     }
9787
9788   /* The list is no longer needed.  */
9789   cu->method_list.clear ();
9790 }
9791
9792 /* Go objects should be embedded in a DW_TAG_module DIE,
9793    and it's not clear if/how imported objects will appear.
9794    To keep Go support simple until that's worked out,
9795    go back through what we've read and create something usable.
9796    We could do this while processing each DIE, and feels kinda cleaner,
9797    but that way is more invasive.
9798    This is to, for example, allow the user to type "p var" or "b main"
9799    without having to specify the package name, and allow lookups
9800    of module.object to work in contexts that use the expression
9801    parser.  */
9802
9803 static void
9804 fixup_go_packaging (struct dwarf2_cu *cu)
9805 {
9806   char *package_name = NULL;
9807   struct pending *list;
9808   int i;
9809
9810   for (list = *cu->get_builder ()->get_global_symbols ();
9811        list != NULL;
9812        list = list->next)
9813     {
9814       for (i = 0; i < list->nsyms; ++i)
9815         {
9816           struct symbol *sym = list->symbol[i];
9817
9818           if (SYMBOL_LANGUAGE (sym) == language_go
9819               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9820             {
9821               char *this_package_name = go_symbol_package_name (sym);
9822
9823               if (this_package_name == NULL)
9824                 continue;
9825               if (package_name == NULL)
9826                 package_name = this_package_name;
9827               else
9828                 {
9829                   struct objfile *objfile
9830                     = cu->per_cu->dwarf2_per_objfile->objfile;
9831                   if (strcmp (package_name, this_package_name) != 0)
9832                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9833                                (symbol_symtab (sym) != NULL
9834                                 ? symtab_to_filename_for_display
9835                                     (symbol_symtab (sym))
9836                                 : objfile_name (objfile)),
9837                                this_package_name, package_name);
9838                   xfree (this_package_name);
9839                 }
9840             }
9841         }
9842     }
9843
9844   if (package_name != NULL)
9845     {
9846       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9847       const char *saved_package_name
9848         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9849                                         package_name,
9850                                         strlen (package_name));
9851       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9852                                      saved_package_name);
9853       struct symbol *sym;
9854
9855       sym = allocate_symbol (objfile);
9856       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9857       SYMBOL_SET_NAMES (sym, saved_package_name,
9858                         strlen (saved_package_name), 0, objfile);
9859       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9860          e.g., "main" finds the "main" module and not C's main().  */
9861       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9862       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9863       SYMBOL_TYPE (sym) = type;
9864
9865       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
9866
9867       xfree (package_name);
9868     }
9869 }
9870
9871 /* Allocate a fully-qualified name consisting of the two parts on the
9872    obstack.  */
9873
9874 static const char *
9875 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9876 {
9877   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9878 }
9879
9880 /* A helper that allocates a struct discriminant_info to attach to a
9881    union type.  */
9882
9883 static struct discriminant_info *
9884 alloc_discriminant_info (struct type *type, int discriminant_index,
9885                          int default_index)
9886 {
9887   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9888   gdb_assert (discriminant_index == -1
9889               || (discriminant_index >= 0
9890                   && discriminant_index < TYPE_NFIELDS (type)));
9891   gdb_assert (default_index == -1
9892               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9893
9894   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9895
9896   struct discriminant_info *disc
9897     = ((struct discriminant_info *)
9898        TYPE_ZALLOC (type,
9899                     offsetof (struct discriminant_info, discriminants)
9900                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9901   disc->default_index = default_index;
9902   disc->discriminant_index = discriminant_index;
9903
9904   struct dynamic_prop prop;
9905   prop.kind = PROP_UNDEFINED;
9906   prop.data.baton = disc;
9907
9908   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9909
9910   return disc;
9911 }
9912
9913 /* Some versions of rustc emitted enums in an unusual way.
9914
9915    Ordinary enums were emitted as unions.  The first element of each
9916    structure in the union was named "RUST$ENUM$DISR".  This element
9917    held the discriminant.
9918
9919    These versions of Rust also implemented the "non-zero"
9920    optimization.  When the enum had two values, and one is empty and
9921    the other holds a pointer that cannot be zero, the pointer is used
9922    as the discriminant, with a zero value meaning the empty variant.
9923    Here, the union's first member is of the form
9924    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9925    where the fieldnos are the indices of the fields that should be
9926    traversed in order to find the field (which may be several fields deep)
9927    and the variantname is the name of the variant of the case when the
9928    field is zero.
9929
9930    This function recognizes whether TYPE is of one of these forms,
9931    and, if so, smashes it to be a variant type.  */
9932
9933 static void
9934 quirk_rust_enum (struct type *type, struct objfile *objfile)
9935 {
9936   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9937
9938   /* We don't need to deal with empty enums.  */
9939   if (TYPE_NFIELDS (type) == 0)
9940     return;
9941
9942 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9943   if (TYPE_NFIELDS (type) == 1
9944       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9945     {
9946       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9947
9948       /* Decode the field name to find the offset of the
9949          discriminant.  */
9950       ULONGEST bit_offset = 0;
9951       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9952       while (name[0] >= '0' && name[0] <= '9')
9953         {
9954           char *tail;
9955           unsigned long index = strtoul (name, &tail, 10);
9956           name = tail;
9957           if (*name != '$'
9958               || index >= TYPE_NFIELDS (field_type)
9959               || (TYPE_FIELD_LOC_KIND (field_type, index)
9960                   != FIELD_LOC_KIND_BITPOS))
9961             {
9962               complaint (_("Could not parse Rust enum encoding string \"%s\""
9963                            "[in module %s]"),
9964                          TYPE_FIELD_NAME (type, 0),
9965                          objfile_name (objfile));
9966               return;
9967             }
9968           ++name;
9969
9970           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9971           field_type = TYPE_FIELD_TYPE (field_type, index);
9972         }
9973
9974       /* Make a union to hold the variants.  */
9975       struct type *union_type = alloc_type (objfile);
9976       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9977       TYPE_NFIELDS (union_type) = 3;
9978       TYPE_FIELDS (union_type)
9979         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9980       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9981       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9982
9983       /* Put the discriminant must at index 0.  */
9984       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9985       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9986       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9987       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9988
9989       /* The order of fields doesn't really matter, so put the real
9990          field at index 1 and the data-less field at index 2.  */
9991       struct discriminant_info *disc
9992         = alloc_discriminant_info (union_type, 0, 1);
9993       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9994       TYPE_FIELD_NAME (union_type, 1)
9995         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9996       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9997         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9998                               TYPE_FIELD_NAME (union_type, 1));
9999
10000       const char *dataless_name
10001         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10002                               name);
10003       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
10004                                               dataless_name);
10005       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
10006       /* NAME points into the original discriminant name, which
10007          already has the correct lifetime.  */
10008       TYPE_FIELD_NAME (union_type, 2) = name;
10009       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
10010       disc->discriminants[2] = 0;
10011
10012       /* Smash this type to be a structure type.  We have to do this
10013          because the type has already been recorded.  */
10014       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10015       TYPE_NFIELDS (type) = 1;
10016       TYPE_FIELDS (type)
10017         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
10018
10019       /* Install the variant part.  */
10020       TYPE_FIELD_TYPE (type, 0) = union_type;
10021       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10022       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10023     }
10024   else if (TYPE_NFIELDS (type) == 1)
10025     {
10026       /* We assume that a union with a single field is a univariant
10027          enum.  */
10028       /* Smash this type to be a structure type.  We have to do this
10029          because the type has already been recorded.  */
10030       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10031
10032       /* Make a union to hold the variants.  */
10033       struct type *union_type = alloc_type (objfile);
10034       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10035       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10036       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10037       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10038       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10039
10040       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10041       const char *variant_name
10042         = rust_last_path_segment (TYPE_NAME (field_type));
10043       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10044       TYPE_NAME (field_type)
10045         = rust_fully_qualify (&objfile->objfile_obstack,
10046                               TYPE_NAME (type), variant_name);
10047
10048       /* Install the union in the outer struct type.  */
10049       TYPE_NFIELDS (type) = 1;
10050       TYPE_FIELDS (type)
10051         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10052       TYPE_FIELD_TYPE (type, 0) = union_type;
10053       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10054       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10055
10056       alloc_discriminant_info (union_type, -1, 0);
10057     }
10058   else
10059     {
10060       struct type *disr_type = nullptr;
10061       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10062         {
10063           disr_type = TYPE_FIELD_TYPE (type, i);
10064
10065           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
10066             {
10067               /* All fields of a true enum will be structs.  */
10068               return;
10069             }
10070           else if (TYPE_NFIELDS (disr_type) == 0)
10071             {
10072               /* Could be data-less variant, so keep going.  */
10073               disr_type = nullptr;
10074             }
10075           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10076                            "RUST$ENUM$DISR") != 0)
10077             {
10078               /* Not a Rust enum.  */
10079               return;
10080             }
10081           else
10082             {
10083               /* Found one.  */
10084               break;
10085             }
10086         }
10087
10088       /* If we got here without a discriminant, then it's probably
10089          just a union.  */
10090       if (disr_type == nullptr)
10091         return;
10092
10093       /* Smash this type to be a structure type.  We have to do this
10094          because the type has already been recorded.  */
10095       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10096
10097       /* Make a union to hold the variants.  */
10098       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10099       struct type *union_type = alloc_type (objfile);
10100       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10101       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10102       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10103       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10104       TYPE_FIELDS (union_type)
10105         = (struct field *) TYPE_ZALLOC (union_type,
10106                                         (TYPE_NFIELDS (union_type)
10107                                          * sizeof (struct field)));
10108
10109       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10110               TYPE_NFIELDS (type) * sizeof (struct field));
10111
10112       /* Install the discriminant at index 0 in the union.  */
10113       TYPE_FIELD (union_type, 0) = *disr_field;
10114       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10115       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10116
10117       /* Install the union in the outer struct type.  */
10118       TYPE_FIELD_TYPE (type, 0) = union_type;
10119       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10120       TYPE_NFIELDS (type) = 1;
10121
10122       /* Set the size and offset of the union type.  */
10123       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10124
10125       /* We need a way to find the correct discriminant given a
10126          variant name.  For convenience we build a map here.  */
10127       struct type *enum_type = FIELD_TYPE (*disr_field);
10128       std::unordered_map<std::string, ULONGEST> discriminant_map;
10129       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10130         {
10131           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10132             {
10133               const char *name
10134                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10135               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10136             }
10137         }
10138
10139       int n_fields = TYPE_NFIELDS (union_type);
10140       struct discriminant_info *disc
10141         = alloc_discriminant_info (union_type, 0, -1);
10142       /* Skip the discriminant here.  */
10143       for (int i = 1; i < n_fields; ++i)
10144         {
10145           /* Find the final word in the name of this variant's type.
10146              That name can be used to look up the correct
10147              discriminant.  */
10148           const char *variant_name
10149             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10150                                                                   i)));
10151
10152           auto iter = discriminant_map.find (variant_name);
10153           if (iter != discriminant_map.end ())
10154             disc->discriminants[i] = iter->second;
10155
10156           /* Remove the discriminant field, if it exists.  */
10157           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10158           if (TYPE_NFIELDS (sub_type) > 0)
10159             {
10160               --TYPE_NFIELDS (sub_type);
10161               ++TYPE_FIELDS (sub_type);
10162             }
10163           TYPE_FIELD_NAME (union_type, i) = variant_name;
10164           TYPE_NAME (sub_type)
10165             = rust_fully_qualify (&objfile->objfile_obstack,
10166                                   TYPE_NAME (type), variant_name);
10167         }
10168     }
10169 }
10170
10171 /* Rewrite some Rust unions to be structures with variants parts.  */
10172
10173 static void
10174 rust_union_quirks (struct dwarf2_cu *cu)
10175 {
10176   gdb_assert (cu->language == language_rust);
10177   for (type *type_ : cu->rust_unions)
10178     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10179   /* We don't need this any more.  */
10180   cu->rust_unions.clear ();
10181 }
10182
10183 /* Return the symtab for PER_CU.  This works properly regardless of
10184    whether we're using the index or psymtabs.  */
10185
10186 static struct compunit_symtab *
10187 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10188 {
10189   return (per_cu->dwarf2_per_objfile->using_index
10190           ? per_cu->v.quick->compunit_symtab
10191           : per_cu->v.psymtab->compunit_symtab);
10192 }
10193
10194 /* A helper function for computing the list of all symbol tables
10195    included by PER_CU.  */
10196
10197 static void
10198 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
10199                                 htab_t all_children, htab_t all_type_symtabs,
10200                                 struct dwarf2_per_cu_data *per_cu,
10201                                 struct compunit_symtab *immediate_parent)
10202 {
10203   void **slot;
10204   int ix;
10205   struct compunit_symtab *cust;
10206   struct dwarf2_per_cu_data *iter;
10207
10208   slot = htab_find_slot (all_children, per_cu, INSERT);
10209   if (*slot != NULL)
10210     {
10211       /* This inclusion and its children have been processed.  */
10212       return;
10213     }
10214
10215   *slot = per_cu;
10216   /* Only add a CU if it has a symbol table.  */
10217   cust = get_compunit_symtab (per_cu);
10218   if (cust != NULL)
10219     {
10220       /* If this is a type unit only add its symbol table if we haven't
10221          seen it yet (type unit per_cu's can share symtabs).  */
10222       if (per_cu->is_debug_types)
10223         {
10224           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10225           if (*slot == NULL)
10226             {
10227               *slot = cust;
10228               result->push_back (cust);
10229               if (cust->user == NULL)
10230                 cust->user = immediate_parent;
10231             }
10232         }
10233       else
10234         {
10235           result->push_back (cust);
10236           if (cust->user == NULL)
10237             cust->user = immediate_parent;
10238         }
10239     }
10240
10241   for (ix = 0;
10242        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10243        ++ix)
10244     {
10245       recursively_compute_inclusions (result, all_children,
10246                                       all_type_symtabs, iter, cust);
10247     }
10248 }
10249
10250 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10251    PER_CU.  */
10252
10253 static void
10254 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10255 {
10256   gdb_assert (! per_cu->is_debug_types);
10257
10258   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10259     {
10260       int ix, len;
10261       struct dwarf2_per_cu_data *per_cu_iter;
10262       std::vector<compunit_symtab *> result_symtabs;
10263       htab_t all_children, all_type_symtabs;
10264       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10265
10266       /* If we don't have a symtab, we can just skip this case.  */
10267       if (cust == NULL)
10268         return;
10269
10270       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10271                                         NULL, xcalloc, xfree);
10272       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10273                                             NULL, xcalloc, xfree);
10274
10275       for (ix = 0;
10276            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10277                         ix, per_cu_iter);
10278            ++ix)
10279         {
10280           recursively_compute_inclusions (&result_symtabs, all_children,
10281                                           all_type_symtabs, per_cu_iter,
10282                                           cust);
10283         }
10284
10285       /* Now we have a transitive closure of all the included symtabs.  */
10286       len = result_symtabs.size ();
10287       cust->includes
10288         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10289                      struct compunit_symtab *, len + 1);
10290       memcpy (cust->includes, result_symtabs.data (),
10291               len * sizeof (compunit_symtab *));
10292       cust->includes[len] = NULL;
10293
10294       htab_delete (all_children);
10295       htab_delete (all_type_symtabs);
10296     }
10297 }
10298
10299 /* Compute the 'includes' field for the symtabs of all the CUs we just
10300    read.  */
10301
10302 static void
10303 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10304 {
10305   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10306     {
10307       if (! iter->is_debug_types)
10308         compute_compunit_symtab_includes (iter);
10309     }
10310
10311   dwarf2_per_objfile->just_read_cus.clear ();
10312 }
10313
10314 /* Generate full symbol information for PER_CU, whose DIEs have
10315    already been loaded into memory.  */
10316
10317 static void
10318 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10319                         enum language pretend_language)
10320 {
10321   struct dwarf2_cu *cu = per_cu->cu;
10322   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10323   struct objfile *objfile = dwarf2_per_objfile->objfile;
10324   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10325   CORE_ADDR lowpc, highpc;
10326   struct compunit_symtab *cust;
10327   CORE_ADDR baseaddr;
10328   struct block *static_block;
10329   CORE_ADDR addr;
10330
10331   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10332
10333   /* Clear the list here in case something was left over.  */
10334   cu->method_list.clear ();
10335
10336   cu->language = pretend_language;
10337   cu->language_defn = language_def (cu->language);
10338
10339   /* Do line number decoding in read_file_scope () */
10340   process_die (cu->dies, cu);
10341
10342   /* For now fudge the Go package.  */
10343   if (cu->language == language_go)
10344     fixup_go_packaging (cu);
10345
10346   /* Now that we have processed all the DIEs in the CU, all the types 
10347      should be complete, and it should now be safe to compute all of the
10348      physnames.  */
10349   compute_delayed_physnames (cu);
10350
10351   if (cu->language == language_rust)
10352     rust_union_quirks (cu);
10353
10354   /* Some compilers don't define a DW_AT_high_pc attribute for the
10355      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10356      it, by scanning the DIE's below the compilation unit.  */
10357   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10358
10359   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10360   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
10361
10362   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10363      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10364      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10365      addrmap to help ensure it has an accurate map of pc values belonging to
10366      this comp unit.  */
10367   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10368
10369   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
10370                                                     SECT_OFF_TEXT (objfile),
10371                                                     0);
10372
10373   if (cust != NULL)
10374     {
10375       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10376
10377       /* Set symtab language to language from DW_AT_language.  If the
10378          compilation is from a C file generated by language preprocessors, do
10379          not set the language if it was already deduced by start_subfile.  */
10380       if (!(cu->language == language_c
10381             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10382         COMPUNIT_FILETABS (cust)->language = cu->language;
10383
10384       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10385          produce DW_AT_location with location lists but it can be possibly
10386          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10387          there were bugs in prologue debug info, fixed later in GCC-4.5
10388          by "unwind info for epilogues" patch (which is not directly related).
10389
10390          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10391          needed, it would be wrong due to missing DW_AT_producer there.
10392
10393          Still one can confuse GDB by using non-standard GCC compilation
10394          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10395          */ 
10396       if (cu->has_loclist && gcc_4_minor >= 5)
10397         cust->locations_valid = 1;
10398
10399       if (gcc_4_minor >= 5)
10400         cust->epilogue_unwind_valid = 1;
10401
10402       cust->call_site_htab = cu->call_site_htab;
10403     }
10404
10405   if (dwarf2_per_objfile->using_index)
10406     per_cu->v.quick->compunit_symtab = cust;
10407   else
10408     {
10409       struct partial_symtab *pst = per_cu->v.psymtab;
10410       pst->compunit_symtab = cust;
10411       pst->readin = 1;
10412     }
10413
10414   /* Push it for inclusion processing later.  */
10415   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10416
10417   /* Not needed any more.  */
10418   cu->reset_builder ();
10419 }
10420
10421 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10422    already been loaded into memory.  */
10423
10424 static void
10425 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10426                         enum language pretend_language)
10427 {
10428   struct dwarf2_cu *cu = per_cu->cu;
10429   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10430   struct objfile *objfile = dwarf2_per_objfile->objfile;
10431   struct compunit_symtab *cust;
10432   struct signatured_type *sig_type;
10433
10434   gdb_assert (per_cu->is_debug_types);
10435   sig_type = (struct signatured_type *) per_cu;
10436
10437   /* Clear the list here in case something was left over.  */
10438   cu->method_list.clear ();
10439
10440   cu->language = pretend_language;
10441   cu->language_defn = language_def (cu->language);
10442
10443   /* The symbol tables are set up in read_type_unit_scope.  */
10444   process_die (cu->dies, cu);
10445
10446   /* For now fudge the Go package.  */
10447   if (cu->language == language_go)
10448     fixup_go_packaging (cu);
10449
10450   /* Now that we have processed all the DIEs in the CU, all the types 
10451      should be complete, and it should now be safe to compute all of the
10452      physnames.  */
10453   compute_delayed_physnames (cu);
10454
10455   if (cu->language == language_rust)
10456     rust_union_quirks (cu);
10457
10458   /* TUs share symbol tables.
10459      If this is the first TU to use this symtab, complete the construction
10460      of it with end_expandable_symtab.  Otherwise, complete the addition of
10461      this TU's symbols to the existing symtab.  */
10462   if (sig_type->type_unit_group->compunit_symtab == NULL)
10463     {
10464       buildsym_compunit *builder = cu->get_builder ();
10465       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10466       sig_type->type_unit_group->compunit_symtab = cust;
10467
10468       if (cust != NULL)
10469         {
10470           /* Set symtab language to language from DW_AT_language.  If the
10471              compilation is from a C file generated by language preprocessors,
10472              do not set the language if it was already deduced by
10473              start_subfile.  */
10474           if (!(cu->language == language_c
10475                 && COMPUNIT_FILETABS (cust)->language != language_c))
10476             COMPUNIT_FILETABS (cust)->language = cu->language;
10477         }
10478     }
10479   else
10480     {
10481       cu->get_builder ()->augment_type_symtab ();
10482       cust = sig_type->type_unit_group->compunit_symtab;
10483     }
10484
10485   if (dwarf2_per_objfile->using_index)
10486     per_cu->v.quick->compunit_symtab = cust;
10487   else
10488     {
10489       struct partial_symtab *pst = per_cu->v.psymtab;
10490       pst->compunit_symtab = cust;
10491       pst->readin = 1;
10492     }
10493
10494   /* Not needed any more.  */
10495   cu->reset_builder ();
10496 }
10497
10498 /* Process an imported unit DIE.  */
10499
10500 static void
10501 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10502 {
10503   struct attribute *attr;
10504
10505   /* For now we don't handle imported units in type units.  */
10506   if (cu->per_cu->is_debug_types)
10507     {
10508       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10509                " supported in type units [in module %s]"),
10510              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10511     }
10512
10513   attr = dwarf2_attr (die, DW_AT_import, cu);
10514   if (attr != NULL)
10515     {
10516       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10517       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10518       dwarf2_per_cu_data *per_cu
10519         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10520                                             cu->per_cu->dwarf2_per_objfile);
10521
10522       /* If necessary, add it to the queue and load its DIEs.  */
10523       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10524         load_full_comp_unit (per_cu, false, cu->language);
10525
10526       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10527                      per_cu);
10528     }
10529 }
10530
10531 /* RAII object that represents a process_die scope: i.e.,
10532    starts/finishes processing a DIE.  */
10533 class process_die_scope
10534 {
10535 public:
10536   process_die_scope (die_info *die, dwarf2_cu *cu)
10537     : m_die (die), m_cu (cu)
10538   {
10539     /* We should only be processing DIEs not already in process.  */
10540     gdb_assert (!m_die->in_process);
10541     m_die->in_process = true;
10542   }
10543
10544   ~process_die_scope ()
10545   {
10546     m_die->in_process = false;
10547
10548     /* If we're done processing the DIE for the CU that owns the line
10549        header, we don't need the line header anymore.  */
10550     if (m_cu->line_header_die_owner == m_die)
10551       {
10552         delete m_cu->line_header;
10553         m_cu->line_header = NULL;
10554         m_cu->line_header_die_owner = NULL;
10555       }
10556   }
10557
10558 private:
10559   die_info *m_die;
10560   dwarf2_cu *m_cu;
10561 };
10562
10563 /* Process a die and its children.  */
10564
10565 static void
10566 process_die (struct die_info *die, struct dwarf2_cu *cu)
10567 {
10568   process_die_scope scope (die, cu);
10569
10570   switch (die->tag)
10571     {
10572     case DW_TAG_padding:
10573       break;
10574     case DW_TAG_compile_unit:
10575     case DW_TAG_partial_unit:
10576       read_file_scope (die, cu);
10577       break;
10578     case DW_TAG_type_unit:
10579       read_type_unit_scope (die, cu);
10580       break;
10581     case DW_TAG_subprogram:
10582     case DW_TAG_inlined_subroutine:
10583       read_func_scope (die, cu);
10584       break;
10585     case DW_TAG_lexical_block:
10586     case DW_TAG_try_block:
10587     case DW_TAG_catch_block:
10588       read_lexical_block_scope (die, cu);
10589       break;
10590     case DW_TAG_call_site:
10591     case DW_TAG_GNU_call_site:
10592       read_call_site_scope (die, cu);
10593       break;
10594     case DW_TAG_class_type:
10595     case DW_TAG_interface_type:
10596     case DW_TAG_structure_type:
10597     case DW_TAG_union_type:
10598       process_structure_scope (die, cu);
10599       break;
10600     case DW_TAG_enumeration_type:
10601       process_enumeration_scope (die, cu);
10602       break;
10603
10604     /* These dies have a type, but processing them does not create
10605        a symbol or recurse to process the children.  Therefore we can
10606        read them on-demand through read_type_die.  */
10607     case DW_TAG_subroutine_type:
10608     case DW_TAG_set_type:
10609     case DW_TAG_array_type:
10610     case DW_TAG_pointer_type:
10611     case DW_TAG_ptr_to_member_type:
10612     case DW_TAG_reference_type:
10613     case DW_TAG_rvalue_reference_type:
10614     case DW_TAG_string_type:
10615       break;
10616
10617     case DW_TAG_base_type:
10618     case DW_TAG_subrange_type:
10619     case DW_TAG_typedef:
10620       /* Add a typedef symbol for the type definition, if it has a
10621          DW_AT_name.  */
10622       new_symbol (die, read_type_die (die, cu), cu);
10623       break;
10624     case DW_TAG_common_block:
10625       read_common_block (die, cu);
10626       break;
10627     case DW_TAG_common_inclusion:
10628       break;
10629     case DW_TAG_namespace:
10630       cu->processing_has_namespace_info = true;
10631       read_namespace (die, cu);
10632       break;
10633     case DW_TAG_module:
10634       cu->processing_has_namespace_info = true;
10635       read_module (die, cu);
10636       break;
10637     case DW_TAG_imported_declaration:
10638       cu->processing_has_namespace_info = true;
10639       if (read_namespace_alias (die, cu))
10640         break;
10641       /* The declaration is not a global namespace alias.  */
10642       /* Fall through.  */
10643     case DW_TAG_imported_module:
10644       cu->processing_has_namespace_info = true;
10645       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10646                                  || cu->language != language_fortran))
10647         complaint (_("Tag '%s' has unexpected children"),
10648                    dwarf_tag_name (die->tag));
10649       read_import_statement (die, cu);
10650       break;
10651
10652     case DW_TAG_imported_unit:
10653       process_imported_unit_die (die, cu);
10654       break;
10655
10656     case DW_TAG_variable:
10657       read_variable (die, cu);
10658       break;
10659
10660     default:
10661       new_symbol (die, NULL, cu);
10662       break;
10663     }
10664 }
10665 \f
10666 /* DWARF name computation.  */
10667
10668 /* A helper function for dwarf2_compute_name which determines whether DIE
10669    needs to have the name of the scope prepended to the name listed in the
10670    die.  */
10671
10672 static int
10673 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10674 {
10675   struct attribute *attr;
10676
10677   switch (die->tag)
10678     {
10679     case DW_TAG_namespace:
10680     case DW_TAG_typedef:
10681     case DW_TAG_class_type:
10682     case DW_TAG_interface_type:
10683     case DW_TAG_structure_type:
10684     case DW_TAG_union_type:
10685     case DW_TAG_enumeration_type:
10686     case DW_TAG_enumerator:
10687     case DW_TAG_subprogram:
10688     case DW_TAG_inlined_subroutine:
10689     case DW_TAG_member:
10690     case DW_TAG_imported_declaration:
10691       return 1;
10692
10693     case DW_TAG_variable:
10694     case DW_TAG_constant:
10695       /* We only need to prefix "globally" visible variables.  These include
10696          any variable marked with DW_AT_external or any variable that
10697          lives in a namespace.  [Variables in anonymous namespaces
10698          require prefixing, but they are not DW_AT_external.]  */
10699
10700       if (dwarf2_attr (die, DW_AT_specification, cu))
10701         {
10702           struct dwarf2_cu *spec_cu = cu;
10703
10704           return die_needs_namespace (die_specification (die, &spec_cu),
10705                                       spec_cu);
10706         }
10707
10708       attr = dwarf2_attr (die, DW_AT_external, cu);
10709       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10710           && die->parent->tag != DW_TAG_module)
10711         return 0;
10712       /* A variable in a lexical block of some kind does not need a
10713          namespace, even though in C++ such variables may be external
10714          and have a mangled name.  */
10715       if (die->parent->tag ==  DW_TAG_lexical_block
10716           || die->parent->tag ==  DW_TAG_try_block
10717           || die->parent->tag ==  DW_TAG_catch_block
10718           || die->parent->tag == DW_TAG_subprogram)
10719         return 0;
10720       return 1;
10721
10722     default:
10723       return 0;
10724     }
10725 }
10726
10727 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10728    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10729    defined for the given DIE.  */
10730
10731 static struct attribute *
10732 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10733 {
10734   struct attribute *attr;
10735
10736   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10737   if (attr == NULL)
10738     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10739
10740   return attr;
10741 }
10742
10743 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10744    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10745    defined for the given DIE.  */
10746
10747 static const char *
10748 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10749 {
10750   const char *linkage_name;
10751
10752   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10753   if (linkage_name == NULL)
10754     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10755
10756   return linkage_name;
10757 }
10758
10759 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10760    compute the physname for the object, which include a method's:
10761    - formal parameters (C++),
10762    - receiver type (Go),
10763
10764    The term "physname" is a bit confusing.
10765    For C++, for example, it is the demangled name.
10766    For Go, for example, it's the mangled name.
10767
10768    For Ada, return the DIE's linkage name rather than the fully qualified
10769    name.  PHYSNAME is ignored..
10770
10771    The result is allocated on the objfile_obstack and canonicalized.  */
10772
10773 static const char *
10774 dwarf2_compute_name (const char *name,
10775                      struct die_info *die, struct dwarf2_cu *cu,
10776                      int physname)
10777 {
10778   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10779
10780   if (name == NULL)
10781     name = dwarf2_name (die, cu);
10782
10783   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10784      but otherwise compute it by typename_concat inside GDB.
10785      FIXME: Actually this is not really true, or at least not always true.
10786      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10787      Fortran names because there is no mangling standard.  So new_symbol
10788      will set the demangled name to the result of dwarf2_full_name, and it is
10789      the demangled name that GDB uses if it exists.  */
10790   if (cu->language == language_ada
10791       || (cu->language == language_fortran && physname))
10792     {
10793       /* For Ada unit, we prefer the linkage name over the name, as
10794          the former contains the exported name, which the user expects
10795          to be able to reference.  Ideally, we want the user to be able
10796          to reference this entity using either natural or linkage name,
10797          but we haven't started looking at this enhancement yet.  */
10798       const char *linkage_name = dw2_linkage_name (die, cu);
10799
10800       if (linkage_name != NULL)
10801         return linkage_name;
10802     }
10803
10804   /* These are the only languages we know how to qualify names in.  */
10805   if (name != NULL
10806       && (cu->language == language_cplus
10807           || cu->language == language_fortran || cu->language == language_d
10808           || cu->language == language_rust))
10809     {
10810       if (die_needs_namespace (die, cu))
10811         {
10812           const char *prefix;
10813           const char *canonical_name = NULL;
10814
10815           string_file buf;
10816
10817           prefix = determine_prefix (die, cu);
10818           if (*prefix != '\0')
10819             {
10820               char *prefixed_name = typename_concat (NULL, prefix, name,
10821                                                      physname, cu);
10822
10823               buf.puts (prefixed_name);
10824               xfree (prefixed_name);
10825             }
10826           else
10827             buf.puts (name);
10828
10829           /* Template parameters may be specified in the DIE's DW_AT_name, or
10830              as children with DW_TAG_template_type_param or
10831              DW_TAG_value_type_param.  If the latter, add them to the name
10832              here.  If the name already has template parameters, then
10833              skip this step; some versions of GCC emit both, and
10834              it is more efficient to use the pre-computed name.
10835
10836              Something to keep in mind about this process: it is very
10837              unlikely, or in some cases downright impossible, to produce
10838              something that will match the mangled name of a function.
10839              If the definition of the function has the same debug info,
10840              we should be able to match up with it anyway.  But fallbacks
10841              using the minimal symbol, for instance to find a method
10842              implemented in a stripped copy of libstdc++, will not work.
10843              If we do not have debug info for the definition, we will have to
10844              match them up some other way.
10845
10846              When we do name matching there is a related problem with function
10847              templates; two instantiated function templates are allowed to
10848              differ only by their return types, which we do not add here.  */
10849
10850           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10851             {
10852               struct attribute *attr;
10853               struct die_info *child;
10854               int first = 1;
10855
10856               die->building_fullname = 1;
10857
10858               for (child = die->child; child != NULL; child = child->sibling)
10859                 {
10860                   struct type *type;
10861                   LONGEST value;
10862                   const gdb_byte *bytes;
10863                   struct dwarf2_locexpr_baton *baton;
10864                   struct value *v;
10865
10866                   if (child->tag != DW_TAG_template_type_param
10867                       && child->tag != DW_TAG_template_value_param)
10868                     continue;
10869
10870                   if (first)
10871                     {
10872                       buf.puts ("<");
10873                       first = 0;
10874                     }
10875                   else
10876                     buf.puts (", ");
10877
10878                   attr = dwarf2_attr (child, DW_AT_type, cu);
10879                   if (attr == NULL)
10880                     {
10881                       complaint (_("template parameter missing DW_AT_type"));
10882                       buf.puts ("UNKNOWN_TYPE");
10883                       continue;
10884                     }
10885                   type = die_type (child, cu);
10886
10887                   if (child->tag == DW_TAG_template_type_param)
10888                     {
10889                       c_print_type (type, "", &buf, -1, 0, cu->language,
10890                                     &type_print_raw_options);
10891                       continue;
10892                     }
10893
10894                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10895                   if (attr == NULL)
10896                     {
10897                       complaint (_("template parameter missing "
10898                                    "DW_AT_const_value"));
10899                       buf.puts ("UNKNOWN_VALUE");
10900                       continue;
10901                     }
10902
10903                   dwarf2_const_value_attr (attr, type, name,
10904                                            &cu->comp_unit_obstack, cu,
10905                                            &value, &bytes, &baton);
10906
10907                   if (TYPE_NOSIGN (type))
10908                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10909                        changed, this can use value_print instead.  */
10910                     c_printchar (value, type, &buf);
10911                   else
10912                     {
10913                       struct value_print_options opts;
10914
10915                       if (baton != NULL)
10916                         v = dwarf2_evaluate_loc_desc (type, NULL,
10917                                                       baton->data,
10918                                                       baton->size,
10919                                                       baton->per_cu);
10920                       else if (bytes != NULL)
10921                         {
10922                           v = allocate_value (type);
10923                           memcpy (value_contents_writeable (v), bytes,
10924                                   TYPE_LENGTH (type));
10925                         }
10926                       else
10927                         v = value_from_longest (type, value);
10928
10929                       /* Specify decimal so that we do not depend on
10930                          the radix.  */
10931                       get_formatted_print_options (&opts, 'd');
10932                       opts.raw = 1;
10933                       value_print (v, &buf, &opts);
10934                       release_value (v);
10935                     }
10936                 }
10937
10938               die->building_fullname = 0;
10939
10940               if (!first)
10941                 {
10942                   /* Close the argument list, with a space if necessary
10943                      (nested templates).  */
10944                   if (!buf.empty () && buf.string ().back () == '>')
10945                     buf.puts (" >");
10946                   else
10947                     buf.puts (">");
10948                 }
10949             }
10950
10951           /* For C++ methods, append formal parameter type
10952              information, if PHYSNAME.  */
10953
10954           if (physname && die->tag == DW_TAG_subprogram
10955               && cu->language == language_cplus)
10956             {
10957               struct type *type = read_type_die (die, cu);
10958
10959               c_type_print_args (type, &buf, 1, cu->language,
10960                                  &type_print_raw_options);
10961
10962               if (cu->language == language_cplus)
10963                 {
10964                   /* Assume that an artificial first parameter is
10965                      "this", but do not crash if it is not.  RealView
10966                      marks unnamed (and thus unused) parameters as
10967                      artificial; there is no way to differentiate
10968                      the two cases.  */
10969                   if (TYPE_NFIELDS (type) > 0
10970                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10971                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10972                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10973                                                                         0))))
10974                     buf.puts (" const");
10975                 }
10976             }
10977
10978           const std::string &intermediate_name = buf.string ();
10979
10980           if (cu->language == language_cplus)
10981             canonical_name
10982               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10983                                           &objfile->per_bfd->storage_obstack);
10984
10985           /* If we only computed INTERMEDIATE_NAME, or if
10986              INTERMEDIATE_NAME is already canonical, then we need to
10987              copy it to the appropriate obstack.  */
10988           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10989             name = ((const char *)
10990                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10991                                    intermediate_name.c_str (),
10992                                    intermediate_name.length ()));
10993           else
10994             name = canonical_name;
10995         }
10996     }
10997
10998   return name;
10999 }
11000
11001 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11002    If scope qualifiers are appropriate they will be added.  The result
11003    will be allocated on the storage_obstack, or NULL if the DIE does
11004    not have a name.  NAME may either be from a previous call to
11005    dwarf2_name or NULL.
11006
11007    The output string will be canonicalized (if C++).  */
11008
11009 static const char *
11010 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11011 {
11012   return dwarf2_compute_name (name, die, cu, 0);
11013 }
11014
11015 /* Construct a physname for the given DIE in CU.  NAME may either be
11016    from a previous call to dwarf2_name or NULL.  The result will be
11017    allocated on the objfile_objstack or NULL if the DIE does not have a
11018    name.
11019
11020    The output string will be canonicalized (if C++).  */
11021
11022 static const char *
11023 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11024 {
11025   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11026   const char *retval, *mangled = NULL, *canon = NULL;
11027   int need_copy = 1;
11028
11029   /* In this case dwarf2_compute_name is just a shortcut not building anything
11030      on its own.  */
11031   if (!die_needs_namespace (die, cu))
11032     return dwarf2_compute_name (name, die, cu, 1);
11033
11034   mangled = dw2_linkage_name (die, cu);
11035
11036   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11037      See https://github.com/rust-lang/rust/issues/32925.  */
11038   if (cu->language == language_rust && mangled != NULL
11039       && strchr (mangled, '{') != NULL)
11040     mangled = NULL;
11041
11042   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11043      has computed.  */
11044   gdb::unique_xmalloc_ptr<char> demangled;
11045   if (mangled != NULL)
11046     {
11047
11048       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
11049         {
11050           /* Do nothing (do not demangle the symbol name).  */
11051         }
11052       else if (cu->language == language_go)
11053         {
11054           /* This is a lie, but we already lie to the caller new_symbol.
11055              new_symbol assumes we return the mangled name.
11056              This just undoes that lie until things are cleaned up.  */
11057         }
11058       else
11059         {
11060           /* Use DMGL_RET_DROP for C++ template functions to suppress
11061              their return type.  It is easier for GDB users to search
11062              for such functions as `name(params)' than `long name(params)'.
11063              In such case the minimal symbol names do not match the full
11064              symbol names but for template functions there is never a need
11065              to look up their definition from their declaration so
11066              the only disadvantage remains the minimal symbol variant
11067              `long name(params)' does not have the proper inferior type.  */
11068           demangled.reset (gdb_demangle (mangled,
11069                                          (DMGL_PARAMS | DMGL_ANSI
11070                                           | DMGL_RET_DROP)));
11071         }
11072       if (demangled)
11073         canon = demangled.get ();
11074       else
11075         {
11076           canon = mangled;
11077           need_copy = 0;
11078         }
11079     }
11080
11081   if (canon == NULL || check_physname)
11082     {
11083       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11084
11085       if (canon != NULL && strcmp (physname, canon) != 0)
11086         {
11087           /* It may not mean a bug in GDB.  The compiler could also
11088              compute DW_AT_linkage_name incorrectly.  But in such case
11089              GDB would need to be bug-to-bug compatible.  */
11090
11091           complaint (_("Computed physname <%s> does not match demangled <%s> "
11092                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11093                      physname, canon, mangled, sect_offset_str (die->sect_off),
11094                      objfile_name (objfile));
11095
11096           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11097              is available here - over computed PHYSNAME.  It is safer
11098              against both buggy GDB and buggy compilers.  */
11099
11100           retval = canon;
11101         }
11102       else
11103         {
11104           retval = physname;
11105           need_copy = 0;
11106         }
11107     }
11108   else
11109     retval = canon;
11110
11111   if (need_copy)
11112     retval = ((const char *)
11113               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11114                              retval, strlen (retval)));
11115
11116   return retval;
11117 }
11118
11119 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11120    a new symbol for it.
11121
11122    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11123
11124 static int
11125 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11126 {
11127   struct attribute *attr;
11128
11129   /* If the die does not have a name, this is not a namespace
11130      alias.  */
11131   attr = dwarf2_attr (die, DW_AT_name, cu);
11132   if (attr != NULL)
11133     {
11134       int num;
11135       struct die_info *d = die;
11136       struct dwarf2_cu *imported_cu = cu;
11137
11138       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11139          keep inspecting DIEs until we hit the underlying import.  */
11140 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11141       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11142         {
11143           attr = dwarf2_attr (d, DW_AT_import, cu);
11144           if (attr == NULL)
11145             break;
11146
11147           d = follow_die_ref (d, attr, &imported_cu);
11148           if (d->tag != DW_TAG_imported_declaration)
11149             break;
11150         }
11151
11152       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11153         {
11154           complaint (_("DIE at %s has too many recursively imported "
11155                        "declarations"), sect_offset_str (d->sect_off));
11156           return 0;
11157         }
11158
11159       if (attr != NULL)
11160         {
11161           struct type *type;
11162           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11163
11164           type = get_die_type_at_offset (sect_off, cu->per_cu);
11165           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11166             {
11167               /* This declaration is a global namespace alias.  Add
11168                  a symbol for it whose type is the aliased namespace.  */
11169               new_symbol (die, type, cu);
11170               return 1;
11171             }
11172         }
11173     }
11174
11175   return 0;
11176 }
11177
11178 /* Return the using directives repository (global or local?) to use in the
11179    current context for CU.
11180
11181    For Ada, imported declarations can materialize renamings, which *may* be
11182    global.  However it is impossible (for now?) in DWARF to distinguish
11183    "external" imported declarations and "static" ones.  As all imported
11184    declarations seem to be static in all other languages, make them all CU-wide
11185    global only in Ada.  */
11186
11187 static struct using_direct **
11188 using_directives (struct dwarf2_cu *cu)
11189 {
11190   if (cu->language == language_ada
11191       && cu->get_builder ()->outermost_context_p ())
11192     return cu->get_builder ()->get_global_using_directives ();
11193   else
11194     return cu->get_builder ()->get_local_using_directives ();
11195 }
11196
11197 /* Read the import statement specified by the given die and record it.  */
11198
11199 static void
11200 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11201 {
11202   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11203   struct attribute *import_attr;
11204   struct die_info *imported_die, *child_die;
11205   struct dwarf2_cu *imported_cu;
11206   const char *imported_name;
11207   const char *imported_name_prefix;
11208   const char *canonical_name;
11209   const char *import_alias;
11210   const char *imported_declaration = NULL;
11211   const char *import_prefix;
11212   std::vector<const char *> excludes;
11213
11214   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11215   if (import_attr == NULL)
11216     {
11217       complaint (_("Tag '%s' has no DW_AT_import"),
11218                  dwarf_tag_name (die->tag));
11219       return;
11220     }
11221
11222   imported_cu = cu;
11223   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11224   imported_name = dwarf2_name (imported_die, imported_cu);
11225   if (imported_name == NULL)
11226     {
11227       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11228
11229         The import in the following code:
11230         namespace A
11231           {
11232             typedef int B;
11233           }
11234
11235         int main ()
11236           {
11237             using A::B;
11238             B b;
11239             return b;
11240           }
11241
11242         ...
11243          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11244             <52>   DW_AT_decl_file   : 1
11245             <53>   DW_AT_decl_line   : 6
11246             <54>   DW_AT_import      : <0x75>
11247          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11248             <59>   DW_AT_name        : B
11249             <5b>   DW_AT_decl_file   : 1
11250             <5c>   DW_AT_decl_line   : 2
11251             <5d>   DW_AT_type        : <0x6e>
11252         ...
11253          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11254             <76>   DW_AT_byte_size   : 4
11255             <77>   DW_AT_encoding    : 5        (signed)
11256
11257         imports the wrong die ( 0x75 instead of 0x58 ).
11258         This case will be ignored until the gcc bug is fixed.  */
11259       return;
11260     }
11261
11262   /* Figure out the local name after import.  */
11263   import_alias = dwarf2_name (die, cu);
11264
11265   /* Figure out where the statement is being imported to.  */
11266   import_prefix = determine_prefix (die, cu);
11267
11268   /* Figure out what the scope of the imported die is and prepend it
11269      to the name of the imported die.  */
11270   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11271
11272   if (imported_die->tag != DW_TAG_namespace
11273       && imported_die->tag != DW_TAG_module)
11274     {
11275       imported_declaration = imported_name;
11276       canonical_name = imported_name_prefix;
11277     }
11278   else if (strlen (imported_name_prefix) > 0)
11279     canonical_name = obconcat (&objfile->objfile_obstack,
11280                                imported_name_prefix,
11281                                (cu->language == language_d ? "." : "::"),
11282                                imported_name, (char *) NULL);
11283   else
11284     canonical_name = imported_name;
11285
11286   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11287     for (child_die = die->child; child_die && child_die->tag;
11288          child_die = sibling_die (child_die))
11289       {
11290         /* DWARF-4: A Fortran use statement with a “rename list” may be
11291            represented by an imported module entry with an import attribute
11292            referring to the module and owned entries corresponding to those
11293            entities that are renamed as part of being imported.  */
11294
11295         if (child_die->tag != DW_TAG_imported_declaration)
11296           {
11297             complaint (_("child DW_TAG_imported_declaration expected "
11298                          "- DIE at %s [in module %s]"),
11299                        sect_offset_str (child_die->sect_off),
11300                        objfile_name (objfile));
11301             continue;
11302           }
11303
11304         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11305         if (import_attr == NULL)
11306           {
11307             complaint (_("Tag '%s' has no DW_AT_import"),
11308                        dwarf_tag_name (child_die->tag));
11309             continue;
11310           }
11311
11312         imported_cu = cu;
11313         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11314                                               &imported_cu);
11315         imported_name = dwarf2_name (imported_die, imported_cu);
11316         if (imported_name == NULL)
11317           {
11318             complaint (_("child DW_TAG_imported_declaration has unknown "
11319                          "imported name - DIE at %s [in module %s]"),
11320                        sect_offset_str (child_die->sect_off),
11321                        objfile_name (objfile));
11322             continue;
11323           }
11324
11325         excludes.push_back (imported_name);
11326
11327         process_die (child_die, cu);
11328       }
11329
11330   add_using_directive (using_directives (cu),
11331                        import_prefix,
11332                        canonical_name,
11333                        import_alias,
11334                        imported_declaration,
11335                        excludes,
11336                        0,
11337                        &objfile->objfile_obstack);
11338 }
11339
11340 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11341    types, but gives them a size of zero.  Starting with version 14,
11342    ICC is compatible with GCC.  */
11343
11344 static bool
11345 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11346 {
11347   if (!cu->checked_producer)
11348     check_producer (cu);
11349
11350   return cu->producer_is_icc_lt_14;
11351 }
11352
11353 /* ICC generates a DW_AT_type for C void functions.  This was observed on
11354    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
11355    which says that void functions should not have a DW_AT_type.  */
11356
11357 static bool
11358 producer_is_icc (struct dwarf2_cu *cu)
11359 {
11360   if (!cu->checked_producer)
11361     check_producer (cu);
11362
11363   return cu->producer_is_icc;
11364 }
11365
11366 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11367    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11368    this, it was first present in GCC release 4.3.0.  */
11369
11370 static bool
11371 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11372 {
11373   if (!cu->checked_producer)
11374     check_producer (cu);
11375
11376   return cu->producer_is_gcc_lt_4_3;
11377 }
11378
11379 static file_and_directory
11380 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11381 {
11382   file_and_directory res;
11383
11384   /* Find the filename.  Do not use dwarf2_name here, since the filename
11385      is not a source language identifier.  */
11386   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11387   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11388
11389   if (res.comp_dir == NULL
11390       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11391       && IS_ABSOLUTE_PATH (res.name))
11392     {
11393       res.comp_dir_storage = ldirname (res.name);
11394       if (!res.comp_dir_storage.empty ())
11395         res.comp_dir = res.comp_dir_storage.c_str ();
11396     }
11397   if (res.comp_dir != NULL)
11398     {
11399       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11400          directory, get rid of it.  */
11401       const char *cp = strchr (res.comp_dir, ':');
11402
11403       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11404         res.comp_dir = cp + 1;
11405     }
11406
11407   if (res.name == NULL)
11408     res.name = "<unknown>";
11409
11410   return res;
11411 }
11412
11413 /* Handle DW_AT_stmt_list for a compilation unit.
11414    DIE is the DW_TAG_compile_unit die for CU.
11415    COMP_DIR is the compilation directory.  LOWPC is passed to
11416    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11417
11418 static void
11419 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11420                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11421 {
11422   struct dwarf2_per_objfile *dwarf2_per_objfile
11423     = cu->per_cu->dwarf2_per_objfile;
11424   struct objfile *objfile = dwarf2_per_objfile->objfile;
11425   struct attribute *attr;
11426   struct line_header line_header_local;
11427   hashval_t line_header_local_hash;
11428   void **slot;
11429   int decode_mapping;
11430
11431   gdb_assert (! cu->per_cu->is_debug_types);
11432
11433   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11434   if (attr == NULL)
11435     return;
11436
11437   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11438
11439   /* The line header hash table is only created if needed (it exists to
11440      prevent redundant reading of the line table for partial_units).
11441      If we're given a partial_unit, we'll need it.  If we're given a
11442      compile_unit, then use the line header hash table if it's already
11443      created, but don't create one just yet.  */
11444
11445   if (dwarf2_per_objfile->line_header_hash == NULL
11446       && die->tag == DW_TAG_partial_unit)
11447     {
11448       dwarf2_per_objfile->line_header_hash
11449         = htab_create_alloc_ex (127, line_header_hash_voidp,
11450                                 line_header_eq_voidp,
11451                                 free_line_header_voidp,
11452                                 &objfile->objfile_obstack,
11453                                 hashtab_obstack_allocate,
11454                                 dummy_obstack_deallocate);
11455     }
11456
11457   line_header_local.sect_off = line_offset;
11458   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11459   line_header_local_hash = line_header_hash (&line_header_local);
11460   if (dwarf2_per_objfile->line_header_hash != NULL)
11461     {
11462       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11463                                        &line_header_local,
11464                                        line_header_local_hash, NO_INSERT);
11465
11466       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11467          is not present in *SLOT (since if there is something in *SLOT then
11468          it will be for a partial_unit).  */
11469       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11470         {
11471           gdb_assert (*slot != NULL);
11472           cu->line_header = (struct line_header *) *slot;
11473           return;
11474         }
11475     }
11476
11477   /* dwarf_decode_line_header does not yet provide sufficient information.
11478      We always have to call also dwarf_decode_lines for it.  */
11479   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11480   if (lh == NULL)
11481     return;
11482
11483   cu->line_header = lh.release ();
11484   cu->line_header_die_owner = die;
11485
11486   if (dwarf2_per_objfile->line_header_hash == NULL)
11487     slot = NULL;
11488   else
11489     {
11490       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11491                                        &line_header_local,
11492                                        line_header_local_hash, INSERT);
11493       gdb_assert (slot != NULL);
11494     }
11495   if (slot != NULL && *slot == NULL)
11496     {
11497       /* This newly decoded line number information unit will be owned
11498          by line_header_hash hash table.  */
11499       *slot = cu->line_header;
11500       cu->line_header_die_owner = NULL;
11501     }
11502   else
11503     {
11504       /* We cannot free any current entry in (*slot) as that struct line_header
11505          may be already used by multiple CUs.  Create only temporary decoded
11506          line_header for this CU - it may happen at most once for each line
11507          number information unit.  And if we're not using line_header_hash
11508          then this is what we want as well.  */
11509       gdb_assert (die->tag != DW_TAG_partial_unit);
11510     }
11511   decode_mapping = (die->tag != DW_TAG_partial_unit);
11512   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11513                       decode_mapping);
11514
11515 }
11516
11517 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11518
11519 static void
11520 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11521 {
11522   struct dwarf2_per_objfile *dwarf2_per_objfile
11523     = cu->per_cu->dwarf2_per_objfile;
11524   struct objfile *objfile = dwarf2_per_objfile->objfile;
11525   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11526   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11527   CORE_ADDR highpc = ((CORE_ADDR) 0);
11528   struct attribute *attr;
11529   struct die_info *child_die;
11530   CORE_ADDR baseaddr;
11531
11532   prepare_one_comp_unit (cu, die, cu->language);
11533   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11534
11535   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11536
11537   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11538      from finish_block.  */
11539   if (lowpc == ((CORE_ADDR) -1))
11540     lowpc = highpc;
11541   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11542
11543   file_and_directory fnd = find_file_and_directory (die, cu);
11544
11545   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11546      standardised yet.  As a workaround for the language detection we fall
11547      back to the DW_AT_producer string.  */
11548   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11549     cu->language = language_opencl;
11550
11551   /* Similar hack for Go.  */
11552   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11553     set_cu_language (DW_LANG_Go, cu);
11554
11555   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
11556
11557   /* Decode line number information if present.  We do this before
11558      processing child DIEs, so that the line header table is available
11559      for DW_AT_decl_file.  */
11560   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11561
11562   /* Process all dies in compilation unit.  */
11563   if (die->child != NULL)
11564     {
11565       child_die = die->child;
11566       while (child_die && child_die->tag)
11567         {
11568           process_die (child_die, cu);
11569           child_die = sibling_die (child_die);
11570         }
11571     }
11572
11573   /* Decode macro information, if present.  Dwarf 2 macro information
11574      refers to information in the line number info statement program
11575      header, so we can only read it if we've read the header
11576      successfully.  */
11577   attr = dwarf2_attr (die, DW_AT_macros, cu);
11578   if (attr == NULL)
11579     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11580   if (attr && cu->line_header)
11581     {
11582       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11583         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11584
11585       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11586     }
11587   else
11588     {
11589       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11590       if (attr && cu->line_header)
11591         {
11592           unsigned int macro_offset = DW_UNSND (attr);
11593
11594           dwarf_decode_macros (cu, macro_offset, 0);
11595         }
11596     }
11597 }
11598
11599 void
11600 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
11601 {
11602   struct type_unit_group *tu_group;
11603   int first_time;
11604   struct attribute *attr;
11605   unsigned int i;
11606   struct signatured_type *sig_type;
11607
11608   gdb_assert (per_cu->is_debug_types);
11609   sig_type = (struct signatured_type *) per_cu;
11610
11611   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
11612
11613   /* If we're using .gdb_index (includes -readnow) then
11614      per_cu->type_unit_group may not have been set up yet.  */
11615   if (sig_type->type_unit_group == NULL)
11616     sig_type->type_unit_group = get_type_unit_group (this, attr);
11617   tu_group = sig_type->type_unit_group;
11618
11619   /* If we've already processed this stmt_list there's no real need to
11620      do it again, we could fake it and just recreate the part we need
11621      (file name,index -> symtab mapping).  If data shows this optimization
11622      is useful we can do it then.  */
11623   first_time = tu_group->compunit_symtab == NULL;
11624
11625   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11626      debug info.  */
11627   line_header_up lh;
11628   if (attr != NULL)
11629     {
11630       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11631       lh = dwarf_decode_line_header (line_offset, this);
11632     }
11633   if (lh == NULL)
11634     {
11635       if (first_time)
11636         start_symtab ("", NULL, 0);
11637       else
11638         {
11639           gdb_assert (tu_group->symtabs == NULL);
11640           gdb_assert (m_builder == nullptr);
11641           struct compunit_symtab *cust = tu_group->compunit_symtab;
11642           m_builder.reset (new struct buildsym_compunit
11643                            (COMPUNIT_OBJFILE (cust), "",
11644                             COMPUNIT_DIRNAME (cust),
11645                             compunit_language (cust),
11646                             0, cust));
11647         }
11648       return;
11649     }
11650
11651   line_header = lh.release ();
11652   line_header_die_owner = die;
11653
11654   if (first_time)
11655     {
11656       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
11657
11658       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11659          still initializing it, and our caller (a few levels up)
11660          process_full_type_unit still needs to know if this is the first
11661          time.  */
11662
11663       tu_group->num_symtabs = line_header->file_names.size ();
11664       tu_group->symtabs = XNEWVEC (struct symtab *,
11665                                    line_header->file_names.size ());
11666
11667       for (i = 0; i < line_header->file_names.size (); ++i)
11668         {
11669           file_entry &fe = line_header->file_names[i];
11670
11671           dwarf2_start_subfile (this, fe.name,
11672                                 fe.include_dir (line_header));
11673           buildsym_compunit *b = get_builder ();
11674           if (b->get_current_subfile ()->symtab == NULL)
11675             {
11676               /* NOTE: start_subfile will recognize when it's been
11677                  passed a file it has already seen.  So we can't
11678                  assume there's a simple mapping from
11679                  cu->line_header->file_names to subfiles, plus
11680                  cu->line_header->file_names may contain dups.  */
11681               b->get_current_subfile ()->symtab
11682                 = allocate_symtab (cust, b->get_current_subfile ()->name);
11683             }
11684
11685           fe.symtab = b->get_current_subfile ()->symtab;
11686           tu_group->symtabs[i] = fe.symtab;
11687         }
11688     }
11689   else
11690     {
11691       gdb_assert (m_builder == nullptr);
11692       struct compunit_symtab *cust = tu_group->compunit_symtab;
11693       m_builder.reset (new struct buildsym_compunit
11694                        (COMPUNIT_OBJFILE (cust), "",
11695                         COMPUNIT_DIRNAME (cust),
11696                         compunit_language (cust),
11697                         0, cust));
11698
11699       for (i = 0; i < line_header->file_names.size (); ++i)
11700         {
11701           file_entry &fe = line_header->file_names[i];
11702
11703           fe.symtab = tu_group->symtabs[i];
11704         }
11705     }
11706
11707   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11708      so they don't have a "real" (so to speak) symtab anyway.
11709      There is later code that will assign the main symtab to all symbols
11710      that don't have one.  We need to handle the case of a symbol with a
11711      missing symtab (DW_AT_decl_file) anyway.  */
11712 }
11713
11714 /* Process DW_TAG_type_unit.
11715    For TUs we want to skip the first top level sibling if it's not the
11716    actual type being defined by this TU.  In this case the first top
11717    level sibling is there to provide context only.  */
11718
11719 static void
11720 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11721 {
11722   struct die_info *child_die;
11723
11724   prepare_one_comp_unit (cu, die, language_minimal);
11725
11726   /* Initialize (or reinitialize) the machinery for building symtabs.
11727      We do this before processing child DIEs, so that the line header table
11728      is available for DW_AT_decl_file.  */
11729   cu->setup_type_unit_groups (die);
11730
11731   if (die->child != NULL)
11732     {
11733       child_die = die->child;
11734       while (child_die && child_die->tag)
11735         {
11736           process_die (child_die, cu);
11737           child_die = sibling_die (child_die);
11738         }
11739     }
11740 }
11741 \f
11742 /* DWO/DWP files.
11743
11744    http://gcc.gnu.org/wiki/DebugFission
11745    http://gcc.gnu.org/wiki/DebugFissionDWP
11746
11747    To simplify handling of both DWO files ("object" files with the DWARF info)
11748    and DWP files (a file with the DWOs packaged up into one file), we treat
11749    DWP files as having a collection of virtual DWO files.  */
11750
11751 static hashval_t
11752 hash_dwo_file (const void *item)
11753 {
11754   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11755   hashval_t hash;
11756
11757   hash = htab_hash_string (dwo_file->dwo_name);
11758   if (dwo_file->comp_dir != NULL)
11759     hash += htab_hash_string (dwo_file->comp_dir);
11760   return hash;
11761 }
11762
11763 static int
11764 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11765 {
11766   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11767   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11768
11769   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11770     return 0;
11771   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11772     return lhs->comp_dir == rhs->comp_dir;
11773   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11774 }
11775
11776 /* Allocate a hash table for DWO files.  */
11777
11778 static htab_t
11779 allocate_dwo_file_hash_table (struct objfile *objfile)
11780 {
11781   return htab_create_alloc_ex (41,
11782                                hash_dwo_file,
11783                                eq_dwo_file,
11784                                NULL,
11785                                &objfile->objfile_obstack,
11786                                hashtab_obstack_allocate,
11787                                dummy_obstack_deallocate);
11788 }
11789
11790 /* Lookup DWO file DWO_NAME.  */
11791
11792 static void **
11793 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11794                       const char *dwo_name,
11795                       const char *comp_dir)
11796 {
11797   struct dwo_file find_entry;
11798   void **slot;
11799
11800   if (dwarf2_per_objfile->dwo_files == NULL)
11801     dwarf2_per_objfile->dwo_files
11802       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11803
11804   memset (&find_entry, 0, sizeof (find_entry));
11805   find_entry.dwo_name = dwo_name;
11806   find_entry.comp_dir = comp_dir;
11807   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11808
11809   return slot;
11810 }
11811
11812 static hashval_t
11813 hash_dwo_unit (const void *item)
11814 {
11815   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11816
11817   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11818   return dwo_unit->signature;
11819 }
11820
11821 static int
11822 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11823 {
11824   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11825   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11826
11827   /* The signature is assumed to be unique within the DWO file.
11828      So while object file CU dwo_id's always have the value zero,
11829      that's OK, assuming each object file DWO file has only one CU,
11830      and that's the rule for now.  */
11831   return lhs->signature == rhs->signature;
11832 }
11833
11834 /* Allocate a hash table for DWO CUs,TUs.
11835    There is one of these tables for each of CUs,TUs for each DWO file.  */
11836
11837 static htab_t
11838 allocate_dwo_unit_table (struct objfile *objfile)
11839 {
11840   /* Start out with a pretty small number.
11841      Generally DWO files contain only one CU and maybe some TUs.  */
11842   return htab_create_alloc_ex (3,
11843                                hash_dwo_unit,
11844                                eq_dwo_unit,
11845                                NULL,
11846                                &objfile->objfile_obstack,
11847                                hashtab_obstack_allocate,
11848                                dummy_obstack_deallocate);
11849 }
11850
11851 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11852
11853 struct create_dwo_cu_data
11854 {
11855   struct dwo_file *dwo_file;
11856   struct dwo_unit dwo_unit;
11857 };
11858
11859 /* die_reader_func for create_dwo_cu.  */
11860
11861 static void
11862 create_dwo_cu_reader (const struct die_reader_specs *reader,
11863                       const gdb_byte *info_ptr,
11864                       struct die_info *comp_unit_die,
11865                       int has_children,
11866                       void *datap)
11867 {
11868   struct dwarf2_cu *cu = reader->cu;
11869   sect_offset sect_off = cu->per_cu->sect_off;
11870   struct dwarf2_section_info *section = cu->per_cu->section;
11871   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11872   struct dwo_file *dwo_file = data->dwo_file;
11873   struct dwo_unit *dwo_unit = &data->dwo_unit;
11874   struct attribute *attr;
11875
11876   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11877   if (attr == NULL)
11878     {
11879       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11880                    " its dwo_id [in module %s]"),
11881                  sect_offset_str (sect_off), dwo_file->dwo_name);
11882       return;
11883     }
11884
11885   dwo_unit->dwo_file = dwo_file;
11886   dwo_unit->signature = DW_UNSND (attr);
11887   dwo_unit->section = section;
11888   dwo_unit->sect_off = sect_off;
11889   dwo_unit->length = cu->per_cu->length;
11890
11891   if (dwarf_read_debug)
11892     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11893                         sect_offset_str (sect_off),
11894                         hex_string (dwo_unit->signature));
11895 }
11896
11897 /* Create the dwo_units for the CUs in a DWO_FILE.
11898    Note: This function processes DWO files only, not DWP files.  */
11899
11900 static void
11901 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11902                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11903                        htab_t &cus_htab)
11904 {
11905   struct objfile *objfile = dwarf2_per_objfile->objfile;
11906   const gdb_byte *info_ptr, *end_ptr;
11907
11908   dwarf2_read_section (objfile, &section);
11909   info_ptr = section.buffer;
11910
11911   if (info_ptr == NULL)
11912     return;
11913
11914   if (dwarf_read_debug)
11915     {
11916       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11917                           get_section_name (&section),
11918                           get_section_file_name (&section));
11919     }
11920
11921   end_ptr = info_ptr + section.size;
11922   while (info_ptr < end_ptr)
11923     {
11924       struct dwarf2_per_cu_data per_cu;
11925       struct create_dwo_cu_data create_dwo_cu_data;
11926       struct dwo_unit *dwo_unit;
11927       void **slot;
11928       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11929
11930       memset (&create_dwo_cu_data.dwo_unit, 0,
11931               sizeof (create_dwo_cu_data.dwo_unit));
11932       memset (&per_cu, 0, sizeof (per_cu));
11933       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11934       per_cu.is_debug_types = 0;
11935       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11936       per_cu.section = &section;
11937       create_dwo_cu_data.dwo_file = &dwo_file;
11938
11939       init_cutu_and_read_dies_no_follow (
11940           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11941       info_ptr += per_cu.length;
11942
11943       // If the unit could not be parsed, skip it.
11944       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11945         continue;
11946
11947       if (cus_htab == NULL)
11948         cus_htab = allocate_dwo_unit_table (objfile);
11949
11950       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11951       *dwo_unit = create_dwo_cu_data.dwo_unit;
11952       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11953       gdb_assert (slot != NULL);
11954       if (*slot != NULL)
11955         {
11956           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11957           sect_offset dup_sect_off = dup_cu->sect_off;
11958
11959           complaint (_("debug cu entry at offset %s is duplicate to"
11960                        " the entry at offset %s, signature %s"),
11961                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11962                      hex_string (dwo_unit->signature));
11963         }
11964       *slot = (void *)dwo_unit;
11965     }
11966 }
11967
11968 /* DWP file .debug_{cu,tu}_index section format:
11969    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11970
11971    DWP Version 1:
11972
11973    Both index sections have the same format, and serve to map a 64-bit
11974    signature to a set of section numbers.  Each section begins with a header,
11975    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11976    indexes, and a pool of 32-bit section numbers.  The index sections will be
11977    aligned at 8-byte boundaries in the file.
11978
11979    The index section header consists of:
11980
11981     V, 32 bit version number
11982     -, 32 bits unused
11983     N, 32 bit number of compilation units or type units in the index
11984     M, 32 bit number of slots in the hash table
11985
11986    Numbers are recorded using the byte order of the application binary.
11987
11988    The hash table begins at offset 16 in the section, and consists of an array
11989    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11990    order of the application binary).  Unused slots in the hash table are 0.
11991    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11992
11993    The parallel table begins immediately after the hash table
11994    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11995    array of 32-bit indexes (using the byte order of the application binary),
11996    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11997    table contains a 32-bit index into the pool of section numbers.  For unused
11998    hash table slots, the corresponding entry in the parallel table will be 0.
11999
12000    The pool of section numbers begins immediately following the hash table
12001    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12002    section numbers consists of an array of 32-bit words (using the byte order
12003    of the application binary).  Each item in the array is indexed starting
12004    from 0.  The hash table entry provides the index of the first section
12005    number in the set.  Additional section numbers in the set follow, and the
12006    set is terminated by a 0 entry (section number 0 is not used in ELF).
12007
12008    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12009    section must be the first entry in the set, and the .debug_abbrev.dwo must
12010    be the second entry. Other members of the set may follow in any order.
12011
12012    ---
12013
12014    DWP Version 2:
12015
12016    DWP Version 2 combines all the .debug_info, etc. sections into one,
12017    and the entries in the index tables are now offsets into these sections.
12018    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12019    section.
12020
12021    Index Section Contents:
12022     Header
12023     Hash Table of Signatures   dwp_hash_table.hash_table
12024     Parallel Table of Indices  dwp_hash_table.unit_table
12025     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12026     Table of Section Sizes     dwp_hash_table.v2.sizes
12027
12028    The index section header consists of:
12029
12030     V, 32 bit version number
12031     L, 32 bit number of columns in the table of section offsets
12032     N, 32 bit number of compilation units or type units in the index
12033     M, 32 bit number of slots in the hash table
12034
12035    Numbers are recorded using the byte order of the application binary.
12036
12037    The hash table has the same format as version 1.
12038    The parallel table of indices has the same format as version 1,
12039    except that the entries are origin-1 indices into the table of sections
12040    offsets and the table of section sizes.
12041
12042    The table of offsets begins immediately following the parallel table
12043    (at offset 16 + 12 * M from the beginning of the section).  The table is
12044    a two-dimensional array of 32-bit words (using the byte order of the
12045    application binary), with L columns and N+1 rows, in row-major order.
12046    Each row in the array is indexed starting from 0.  The first row provides
12047    a key to the remaining rows: each column in this row provides an identifier
12048    for a debug section, and the offsets in the same column of subsequent rows
12049    refer to that section.  The section identifiers are:
12050
12051     DW_SECT_INFO         1  .debug_info.dwo
12052     DW_SECT_TYPES        2  .debug_types.dwo
12053     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12054     DW_SECT_LINE         4  .debug_line.dwo
12055     DW_SECT_LOC          5  .debug_loc.dwo
12056     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12057     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12058     DW_SECT_MACRO        8  .debug_macro.dwo
12059
12060    The offsets provided by the CU and TU index sections are the base offsets
12061    for the contributions made by each CU or TU to the corresponding section
12062    in the package file.  Each CU and TU header contains an abbrev_offset
12063    field, used to find the abbreviations table for that CU or TU within the
12064    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12065    be interpreted as relative to the base offset given in the index section.
12066    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12067    should be interpreted as relative to the base offset for .debug_line.dwo,
12068    and offsets into other debug sections obtained from DWARF attributes should
12069    also be interpreted as relative to the corresponding base offset.
12070
12071    The table of sizes begins immediately following the table of offsets.
12072    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12073    with L columns and N rows, in row-major order.  Each row in the array is
12074    indexed starting from 1 (row 0 is shared by the two tables).
12075
12076    ---
12077
12078    Hash table lookup is handled the same in version 1 and 2:
12079
12080    We assume that N and M will not exceed 2^32 - 1.
12081    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12082
12083    Given a 64-bit compilation unit signature or a type signature S, an entry
12084    in the hash table is located as follows:
12085
12086    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12087       the low-order k bits all set to 1.
12088
12089    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12090
12091    3) If the hash table entry at index H matches the signature, use that
12092       entry.  If the hash table entry at index H is unused (all zeroes),
12093       terminate the search: the signature is not present in the table.
12094
12095    4) Let H = (H + H') modulo M. Repeat at Step 3.
12096
12097    Because M > N and H' and M are relatively prime, the search is guaranteed
12098    to stop at an unused slot or find the match.  */
12099
12100 /* Create a hash table to map DWO IDs to their CU/TU entry in
12101    .debug_{info,types}.dwo in DWP_FILE.
12102    Returns NULL if there isn't one.
12103    Note: This function processes DWP files only, not DWO files.  */
12104
12105 static struct dwp_hash_table *
12106 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12107                        struct dwp_file *dwp_file, int is_debug_types)
12108 {
12109   struct objfile *objfile = dwarf2_per_objfile->objfile;
12110   bfd *dbfd = dwp_file->dbfd.get ();
12111   const gdb_byte *index_ptr, *index_end;
12112   struct dwarf2_section_info *index;
12113   uint32_t version, nr_columns, nr_units, nr_slots;
12114   struct dwp_hash_table *htab;
12115
12116   if (is_debug_types)
12117     index = &dwp_file->sections.tu_index;
12118   else
12119     index = &dwp_file->sections.cu_index;
12120
12121   if (dwarf2_section_empty_p (index))
12122     return NULL;
12123   dwarf2_read_section (objfile, index);
12124
12125   index_ptr = index->buffer;
12126   index_end = index_ptr + index->size;
12127
12128   version = read_4_bytes (dbfd, index_ptr);
12129   index_ptr += 4;
12130   if (version == 2)
12131     nr_columns = read_4_bytes (dbfd, index_ptr);
12132   else
12133     nr_columns = 0;
12134   index_ptr += 4;
12135   nr_units = read_4_bytes (dbfd, index_ptr);
12136   index_ptr += 4;
12137   nr_slots = read_4_bytes (dbfd, index_ptr);
12138   index_ptr += 4;
12139
12140   if (version != 1 && version != 2)
12141     {
12142       error (_("Dwarf Error: unsupported DWP file version (%s)"
12143                " [in module %s]"),
12144              pulongest (version), dwp_file->name);
12145     }
12146   if (nr_slots != (nr_slots & -nr_slots))
12147     {
12148       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12149                " is not power of 2 [in module %s]"),
12150              pulongest (nr_slots), dwp_file->name);
12151     }
12152
12153   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12154   htab->version = version;
12155   htab->nr_columns = nr_columns;
12156   htab->nr_units = nr_units;
12157   htab->nr_slots = nr_slots;
12158   htab->hash_table = index_ptr;
12159   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12160
12161   /* Exit early if the table is empty.  */
12162   if (nr_slots == 0 || nr_units == 0
12163       || (version == 2 && nr_columns == 0))
12164     {
12165       /* All must be zero.  */
12166       if (nr_slots != 0 || nr_units != 0
12167           || (version == 2 && nr_columns != 0))
12168         {
12169           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12170                        " all zero [in modules %s]"),
12171                      dwp_file->name);
12172         }
12173       return htab;
12174     }
12175
12176   if (version == 1)
12177     {
12178       htab->section_pool.v1.indices =
12179         htab->unit_table + sizeof (uint32_t) * nr_slots;
12180       /* It's harder to decide whether the section is too small in v1.
12181          V1 is deprecated anyway so we punt.  */
12182     }
12183   else
12184     {
12185       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12186       int *ids = htab->section_pool.v2.section_ids;
12187       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
12188       /* Reverse map for error checking.  */
12189       int ids_seen[DW_SECT_MAX + 1];
12190       int i;
12191
12192       if (nr_columns < 2)
12193         {
12194           error (_("Dwarf Error: bad DWP hash table, too few columns"
12195                    " in section table [in module %s]"),
12196                  dwp_file->name);
12197         }
12198       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12199         {
12200           error (_("Dwarf Error: bad DWP hash table, too many columns"
12201                    " in section table [in module %s]"),
12202                  dwp_file->name);
12203         }
12204       memset (ids, 255, sizeof_ids);
12205       memset (ids_seen, 255, sizeof (ids_seen));
12206       for (i = 0; i < nr_columns; ++i)
12207         {
12208           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12209
12210           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12211             {
12212               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12213                        " in section table [in module %s]"),
12214                      id, dwp_file->name);
12215             }
12216           if (ids_seen[id] != -1)
12217             {
12218               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12219                        " id %d in section table [in module %s]"),
12220                      id, dwp_file->name);
12221             }
12222           ids_seen[id] = i;
12223           ids[i] = id;
12224         }
12225       /* Must have exactly one info or types section.  */
12226       if (((ids_seen[DW_SECT_INFO] != -1)
12227            + (ids_seen[DW_SECT_TYPES] != -1))
12228           != 1)
12229         {
12230           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12231                    " DWO info/types section [in module %s]"),
12232                  dwp_file->name);
12233         }
12234       /* Must have an abbrev section.  */
12235       if (ids_seen[DW_SECT_ABBREV] == -1)
12236         {
12237           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12238                    " section [in module %s]"),
12239                  dwp_file->name);
12240         }
12241       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12242       htab->section_pool.v2.sizes =
12243         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12244                                          * nr_units * nr_columns);
12245       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12246                                           * nr_units * nr_columns))
12247           > index_end)
12248         {
12249           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12250                    " [in module %s]"),
12251                  dwp_file->name);
12252         }
12253     }
12254
12255   return htab;
12256 }
12257
12258 /* Update SECTIONS with the data from SECTP.
12259
12260    This function is like the other "locate" section routines that are
12261    passed to bfd_map_over_sections, but in this context the sections to
12262    read comes from the DWP V1 hash table, not the full ELF section table.
12263
12264    The result is non-zero for success, or zero if an error was found.  */
12265
12266 static int
12267 locate_v1_virtual_dwo_sections (asection *sectp,
12268                                 struct virtual_v1_dwo_sections *sections)
12269 {
12270   const struct dwop_section_names *names = &dwop_section_names;
12271
12272   if (section_is_p (sectp->name, &names->abbrev_dwo))
12273     {
12274       /* There can be only one.  */
12275       if (sections->abbrev.s.section != NULL)
12276         return 0;
12277       sections->abbrev.s.section = sectp;
12278       sections->abbrev.size = bfd_get_section_size (sectp);
12279     }
12280   else if (section_is_p (sectp->name, &names->info_dwo)
12281            || section_is_p (sectp->name, &names->types_dwo))
12282     {
12283       /* There can be only one.  */
12284       if (sections->info_or_types.s.section != NULL)
12285         return 0;
12286       sections->info_or_types.s.section = sectp;
12287       sections->info_or_types.size = bfd_get_section_size (sectp);
12288     }
12289   else if (section_is_p (sectp->name, &names->line_dwo))
12290     {
12291       /* There can be only one.  */
12292       if (sections->line.s.section != NULL)
12293         return 0;
12294       sections->line.s.section = sectp;
12295       sections->line.size = bfd_get_section_size (sectp);
12296     }
12297   else if (section_is_p (sectp->name, &names->loc_dwo))
12298     {
12299       /* There can be only one.  */
12300       if (sections->loc.s.section != NULL)
12301         return 0;
12302       sections->loc.s.section = sectp;
12303       sections->loc.size = bfd_get_section_size (sectp);
12304     }
12305   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12306     {
12307       /* There can be only one.  */
12308       if (sections->macinfo.s.section != NULL)
12309         return 0;
12310       sections->macinfo.s.section = sectp;
12311       sections->macinfo.size = bfd_get_section_size (sectp);
12312     }
12313   else if (section_is_p (sectp->name, &names->macro_dwo))
12314     {
12315       /* There can be only one.  */
12316       if (sections->macro.s.section != NULL)
12317         return 0;
12318       sections->macro.s.section = sectp;
12319       sections->macro.size = bfd_get_section_size (sectp);
12320     }
12321   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12322     {
12323       /* There can be only one.  */
12324       if (sections->str_offsets.s.section != NULL)
12325         return 0;
12326       sections->str_offsets.s.section = sectp;
12327       sections->str_offsets.size = bfd_get_section_size (sectp);
12328     }
12329   else
12330     {
12331       /* No other kind of section is valid.  */
12332       return 0;
12333     }
12334
12335   return 1;
12336 }
12337
12338 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12339    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12340    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12341    This is for DWP version 1 files.  */
12342
12343 static struct dwo_unit *
12344 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12345                            struct dwp_file *dwp_file,
12346                            uint32_t unit_index,
12347                            const char *comp_dir,
12348                            ULONGEST signature, int is_debug_types)
12349 {
12350   struct objfile *objfile = dwarf2_per_objfile->objfile;
12351   const struct dwp_hash_table *dwp_htab =
12352     is_debug_types ? dwp_file->tus : dwp_file->cus;
12353   bfd *dbfd = dwp_file->dbfd.get ();
12354   const char *kind = is_debug_types ? "TU" : "CU";
12355   struct dwo_file *dwo_file;
12356   struct dwo_unit *dwo_unit;
12357   struct virtual_v1_dwo_sections sections;
12358   void **dwo_file_slot;
12359   int i;
12360
12361   gdb_assert (dwp_file->version == 1);
12362
12363   if (dwarf_read_debug)
12364     {
12365       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12366                           kind,
12367                           pulongest (unit_index), hex_string (signature),
12368                           dwp_file->name);
12369     }
12370
12371   /* Fetch the sections of this DWO unit.
12372      Put a limit on the number of sections we look for so that bad data
12373      doesn't cause us to loop forever.  */
12374
12375 #define MAX_NR_V1_DWO_SECTIONS \
12376   (1 /* .debug_info or .debug_types */ \
12377    + 1 /* .debug_abbrev */ \
12378    + 1 /* .debug_line */ \
12379    + 1 /* .debug_loc */ \
12380    + 1 /* .debug_str_offsets */ \
12381    + 1 /* .debug_macro or .debug_macinfo */ \
12382    + 1 /* trailing zero */)
12383
12384   memset (&sections, 0, sizeof (sections));
12385
12386   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12387     {
12388       asection *sectp;
12389       uint32_t section_nr =
12390         read_4_bytes (dbfd,
12391                       dwp_htab->section_pool.v1.indices
12392                       + (unit_index + i) * sizeof (uint32_t));
12393
12394       if (section_nr == 0)
12395         break;
12396       if (section_nr >= dwp_file->num_sections)
12397         {
12398           error (_("Dwarf Error: bad DWP hash table, section number too large"
12399                    " [in module %s]"),
12400                  dwp_file->name);
12401         }
12402
12403       sectp = dwp_file->elf_sections[section_nr];
12404       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12405         {
12406           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12407                    " [in module %s]"),
12408                  dwp_file->name);
12409         }
12410     }
12411
12412   if (i < 2
12413       || dwarf2_section_empty_p (&sections.info_or_types)
12414       || dwarf2_section_empty_p (&sections.abbrev))
12415     {
12416       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12417                " [in module %s]"),
12418              dwp_file->name);
12419     }
12420   if (i == MAX_NR_V1_DWO_SECTIONS)
12421     {
12422       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12423                " [in module %s]"),
12424              dwp_file->name);
12425     }
12426
12427   /* It's easier for the rest of the code if we fake a struct dwo_file and
12428      have dwo_unit "live" in that.  At least for now.
12429
12430      The DWP file can be made up of a random collection of CUs and TUs.
12431      However, for each CU + set of TUs that came from the same original DWO
12432      file, we can combine them back into a virtual DWO file to save space
12433      (fewer struct dwo_file objects to allocate).  Remember that for really
12434      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12435
12436   std::string virtual_dwo_name =
12437     string_printf ("virtual-dwo/%d-%d-%d-%d",
12438                    get_section_id (&sections.abbrev),
12439                    get_section_id (&sections.line),
12440                    get_section_id (&sections.loc),
12441                    get_section_id (&sections.str_offsets));
12442   /* Can we use an existing virtual DWO file?  */
12443   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12444                                         virtual_dwo_name.c_str (),
12445                                         comp_dir);
12446   /* Create one if necessary.  */
12447   if (*dwo_file_slot == NULL)
12448     {
12449       if (dwarf_read_debug)
12450         {
12451           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12452                               virtual_dwo_name.c_str ());
12453         }
12454       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12455       dwo_file->dwo_name
12456         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12457                                         virtual_dwo_name.c_str (),
12458                                         virtual_dwo_name.size ());
12459       dwo_file->comp_dir = comp_dir;
12460       dwo_file->sections.abbrev = sections.abbrev;
12461       dwo_file->sections.line = sections.line;
12462       dwo_file->sections.loc = sections.loc;
12463       dwo_file->sections.macinfo = sections.macinfo;
12464       dwo_file->sections.macro = sections.macro;
12465       dwo_file->sections.str_offsets = sections.str_offsets;
12466       /* The "str" section is global to the entire DWP file.  */
12467       dwo_file->sections.str = dwp_file->sections.str;
12468       /* The info or types section is assigned below to dwo_unit,
12469          there's no need to record it in dwo_file.
12470          Also, we can't simply record type sections in dwo_file because
12471          we record a pointer into the vector in dwo_unit.  As we collect more
12472          types we'll grow the vector and eventually have to reallocate space
12473          for it, invalidating all copies of pointers into the previous
12474          contents.  */
12475       *dwo_file_slot = dwo_file;
12476     }
12477   else
12478     {
12479       if (dwarf_read_debug)
12480         {
12481           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12482                               virtual_dwo_name.c_str ());
12483         }
12484       dwo_file = (struct dwo_file *) *dwo_file_slot;
12485     }
12486
12487   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12488   dwo_unit->dwo_file = dwo_file;
12489   dwo_unit->signature = signature;
12490   dwo_unit->section =
12491     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12492   *dwo_unit->section = sections.info_or_types;
12493   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12494
12495   return dwo_unit;
12496 }
12497
12498 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12499    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12500    piece within that section used by a TU/CU, return a virtual section
12501    of just that piece.  */
12502
12503 static struct dwarf2_section_info
12504 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12505                        struct dwarf2_section_info *section,
12506                        bfd_size_type offset, bfd_size_type size)
12507 {
12508   struct dwarf2_section_info result;
12509   asection *sectp;
12510
12511   gdb_assert (section != NULL);
12512   gdb_assert (!section->is_virtual);
12513
12514   memset (&result, 0, sizeof (result));
12515   result.s.containing_section = section;
12516   result.is_virtual = true;
12517
12518   if (size == 0)
12519     return result;
12520
12521   sectp = get_section_bfd_section (section);
12522
12523   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12524      bounds of the real section.  This is a pretty-rare event, so just
12525      flag an error (easier) instead of a warning and trying to cope.  */
12526   if (sectp == NULL
12527       || offset + size > bfd_get_section_size (sectp))
12528     {
12529       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12530                " in section %s [in module %s]"),
12531              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12532              objfile_name (dwarf2_per_objfile->objfile));
12533     }
12534
12535   result.virtual_offset = offset;
12536   result.size = size;
12537   return result;
12538 }
12539
12540 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12541    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12542    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12543    This is for DWP version 2 files.  */
12544
12545 static struct dwo_unit *
12546 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12547                            struct dwp_file *dwp_file,
12548                            uint32_t unit_index,
12549                            const char *comp_dir,
12550                            ULONGEST signature, int is_debug_types)
12551 {
12552   struct objfile *objfile = dwarf2_per_objfile->objfile;
12553   const struct dwp_hash_table *dwp_htab =
12554     is_debug_types ? dwp_file->tus : dwp_file->cus;
12555   bfd *dbfd = dwp_file->dbfd.get ();
12556   const char *kind = is_debug_types ? "TU" : "CU";
12557   struct dwo_file *dwo_file;
12558   struct dwo_unit *dwo_unit;
12559   struct virtual_v2_dwo_sections sections;
12560   void **dwo_file_slot;
12561   int i;
12562
12563   gdb_assert (dwp_file->version == 2);
12564
12565   if (dwarf_read_debug)
12566     {
12567       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12568                           kind,
12569                           pulongest (unit_index), hex_string (signature),
12570                           dwp_file->name);
12571     }
12572
12573   /* Fetch the section offsets of this DWO unit.  */
12574
12575   memset (&sections, 0, sizeof (sections));
12576
12577   for (i = 0; i < dwp_htab->nr_columns; ++i)
12578     {
12579       uint32_t offset = read_4_bytes (dbfd,
12580                                       dwp_htab->section_pool.v2.offsets
12581                                       + (((unit_index - 1) * dwp_htab->nr_columns
12582                                           + i)
12583                                          * sizeof (uint32_t)));
12584       uint32_t size = read_4_bytes (dbfd,
12585                                     dwp_htab->section_pool.v2.sizes
12586                                     + (((unit_index - 1) * dwp_htab->nr_columns
12587                                         + i)
12588                                        * sizeof (uint32_t)));
12589
12590       switch (dwp_htab->section_pool.v2.section_ids[i])
12591         {
12592         case DW_SECT_INFO:
12593         case DW_SECT_TYPES:
12594           sections.info_or_types_offset = offset;
12595           sections.info_or_types_size = size;
12596           break;
12597         case DW_SECT_ABBREV:
12598           sections.abbrev_offset = offset;
12599           sections.abbrev_size = size;
12600           break;
12601         case DW_SECT_LINE:
12602           sections.line_offset = offset;
12603           sections.line_size = size;
12604           break;
12605         case DW_SECT_LOC:
12606           sections.loc_offset = offset;
12607           sections.loc_size = size;
12608           break;
12609         case DW_SECT_STR_OFFSETS:
12610           sections.str_offsets_offset = offset;
12611           sections.str_offsets_size = size;
12612           break;
12613         case DW_SECT_MACINFO:
12614           sections.macinfo_offset = offset;
12615           sections.macinfo_size = size;
12616           break;
12617         case DW_SECT_MACRO:
12618           sections.macro_offset = offset;
12619           sections.macro_size = size;
12620           break;
12621         }
12622     }
12623
12624   /* It's easier for the rest of the code if we fake a struct dwo_file and
12625      have dwo_unit "live" in that.  At least for now.
12626
12627      The DWP file can be made up of a random collection of CUs and TUs.
12628      However, for each CU + set of TUs that came from the same original DWO
12629      file, we can combine them back into a virtual DWO file to save space
12630      (fewer struct dwo_file objects to allocate).  Remember that for really
12631      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12632
12633   std::string virtual_dwo_name =
12634     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12635                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12636                    (long) (sections.line_size ? sections.line_offset : 0),
12637                    (long) (sections.loc_size ? sections.loc_offset : 0),
12638                    (long) (sections.str_offsets_size
12639                            ? sections.str_offsets_offset : 0));
12640   /* Can we use an existing virtual DWO file?  */
12641   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12642                                         virtual_dwo_name.c_str (),
12643                                         comp_dir);
12644   /* Create one if necessary.  */
12645   if (*dwo_file_slot == NULL)
12646     {
12647       if (dwarf_read_debug)
12648         {
12649           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12650                               virtual_dwo_name.c_str ());
12651         }
12652       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12653       dwo_file->dwo_name
12654         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12655                                         virtual_dwo_name.c_str (),
12656                                         virtual_dwo_name.size ());
12657       dwo_file->comp_dir = comp_dir;
12658       dwo_file->sections.abbrev =
12659         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12660                                sections.abbrev_offset, sections.abbrev_size);
12661       dwo_file->sections.line =
12662         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12663                                sections.line_offset, sections.line_size);
12664       dwo_file->sections.loc =
12665         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12666                                sections.loc_offset, sections.loc_size);
12667       dwo_file->sections.macinfo =
12668         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12669                                sections.macinfo_offset, sections.macinfo_size);
12670       dwo_file->sections.macro =
12671         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12672                                sections.macro_offset, sections.macro_size);
12673       dwo_file->sections.str_offsets =
12674         create_dwp_v2_section (dwarf2_per_objfile,
12675                                &dwp_file->sections.str_offsets,
12676                                sections.str_offsets_offset,
12677                                sections.str_offsets_size);
12678       /* The "str" section is global to the entire DWP file.  */
12679       dwo_file->sections.str = dwp_file->sections.str;
12680       /* The info or types section is assigned below to dwo_unit,
12681          there's no need to record it in dwo_file.
12682          Also, we can't simply record type sections in dwo_file because
12683          we record a pointer into the vector in dwo_unit.  As we collect more
12684          types we'll grow the vector and eventually have to reallocate space
12685          for it, invalidating all copies of pointers into the previous
12686          contents.  */
12687       *dwo_file_slot = dwo_file;
12688     }
12689   else
12690     {
12691       if (dwarf_read_debug)
12692         {
12693           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12694                               virtual_dwo_name.c_str ());
12695         }
12696       dwo_file = (struct dwo_file *) *dwo_file_slot;
12697     }
12698
12699   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12700   dwo_unit->dwo_file = dwo_file;
12701   dwo_unit->signature = signature;
12702   dwo_unit->section =
12703     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12704   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12705                                               is_debug_types
12706                                               ? &dwp_file->sections.types
12707                                               : &dwp_file->sections.info,
12708                                               sections.info_or_types_offset,
12709                                               sections.info_or_types_size);
12710   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12711
12712   return dwo_unit;
12713 }
12714
12715 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12716    Returns NULL if the signature isn't found.  */
12717
12718 static struct dwo_unit *
12719 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12720                         struct dwp_file *dwp_file, const char *comp_dir,
12721                         ULONGEST signature, int is_debug_types)
12722 {
12723   const struct dwp_hash_table *dwp_htab =
12724     is_debug_types ? dwp_file->tus : dwp_file->cus;
12725   bfd *dbfd = dwp_file->dbfd.get ();
12726   uint32_t mask = dwp_htab->nr_slots - 1;
12727   uint32_t hash = signature & mask;
12728   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12729   unsigned int i;
12730   void **slot;
12731   struct dwo_unit find_dwo_cu;
12732
12733   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12734   find_dwo_cu.signature = signature;
12735   slot = htab_find_slot (is_debug_types
12736                          ? dwp_file->loaded_tus
12737                          : dwp_file->loaded_cus,
12738                          &find_dwo_cu, INSERT);
12739
12740   if (*slot != NULL)
12741     return (struct dwo_unit *) *slot;
12742
12743   /* Use a for loop so that we don't loop forever on bad debug info.  */
12744   for (i = 0; i < dwp_htab->nr_slots; ++i)
12745     {
12746       ULONGEST signature_in_table;
12747
12748       signature_in_table =
12749         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12750       if (signature_in_table == signature)
12751         {
12752           uint32_t unit_index =
12753             read_4_bytes (dbfd,
12754                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12755
12756           if (dwp_file->version == 1)
12757             {
12758               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12759                                                  dwp_file, unit_index,
12760                                                  comp_dir, signature,
12761                                                  is_debug_types);
12762             }
12763           else
12764             {
12765               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12766                                                  dwp_file, unit_index,
12767                                                  comp_dir, signature,
12768                                                  is_debug_types);
12769             }
12770           return (struct dwo_unit *) *slot;
12771         }
12772       if (signature_in_table == 0)
12773         return NULL;
12774       hash = (hash + hash2) & mask;
12775     }
12776
12777   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12778            " [in module %s]"),
12779          dwp_file->name);
12780 }
12781
12782 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12783    Open the file specified by FILE_NAME and hand it off to BFD for
12784    preliminary analysis.  Return a newly initialized bfd *, which
12785    includes a canonicalized copy of FILE_NAME.
12786    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12787    SEARCH_CWD is true if the current directory is to be searched.
12788    It will be searched before debug-file-directory.
12789    If successful, the file is added to the bfd include table of the
12790    objfile's bfd (see gdb_bfd_record_inclusion).
12791    If unable to find/open the file, return NULL.
12792    NOTE: This function is derived from symfile_bfd_open.  */
12793
12794 static gdb_bfd_ref_ptr
12795 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12796                     const char *file_name, int is_dwp, int search_cwd)
12797 {
12798   int desc;
12799   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12800      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12801      to debug_file_directory.  */
12802   const char *search_path;
12803   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12804
12805   gdb::unique_xmalloc_ptr<char> search_path_holder;
12806   if (search_cwd)
12807     {
12808       if (*debug_file_directory != '\0')
12809         {
12810           search_path_holder.reset (concat (".", dirname_separator_string,
12811                                             debug_file_directory,
12812                                             (char *) NULL));
12813           search_path = search_path_holder.get ();
12814         }
12815       else
12816         search_path = ".";
12817     }
12818   else
12819     search_path = debug_file_directory;
12820
12821   openp_flags flags = OPF_RETURN_REALPATH;
12822   if (is_dwp)
12823     flags |= OPF_SEARCH_IN_PATH;
12824
12825   gdb::unique_xmalloc_ptr<char> absolute_name;
12826   desc = openp (search_path, flags, file_name,
12827                 O_RDONLY | O_BINARY, &absolute_name);
12828   if (desc < 0)
12829     return NULL;
12830
12831   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12832                                          gnutarget, desc));
12833   if (sym_bfd == NULL)
12834     return NULL;
12835   bfd_set_cacheable (sym_bfd.get (), 1);
12836
12837   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12838     return NULL;
12839
12840   /* Success.  Record the bfd as having been included by the objfile's bfd.
12841      This is important because things like demangled_names_hash lives in the
12842      objfile's per_bfd space and may have references to things like symbol
12843      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12844   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12845
12846   return sym_bfd;
12847 }
12848
12849 /* Try to open DWO file FILE_NAME.
12850    COMP_DIR is the DW_AT_comp_dir attribute.
12851    The result is the bfd handle of the file.
12852    If there is a problem finding or opening the file, return NULL.
12853    Upon success, the canonicalized path of the file is stored in the bfd,
12854    same as symfile_bfd_open.  */
12855
12856 static gdb_bfd_ref_ptr
12857 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12858                const char *file_name, const char *comp_dir)
12859 {
12860   if (IS_ABSOLUTE_PATH (file_name))
12861     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12862                                0 /*is_dwp*/, 0 /*search_cwd*/);
12863
12864   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12865
12866   if (comp_dir != NULL)
12867     {
12868       char *path_to_try = concat (comp_dir, SLASH_STRING,
12869                                   file_name, (char *) NULL);
12870
12871       /* NOTE: If comp_dir is a relative path, this will also try the
12872          search path, which seems useful.  */
12873       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12874                                                 path_to_try,
12875                                                 0 /*is_dwp*/,
12876                                                 1 /*search_cwd*/));
12877       xfree (path_to_try);
12878       if (abfd != NULL)
12879         return abfd;
12880     }
12881
12882   /* That didn't work, try debug-file-directory, which, despite its name,
12883      is a list of paths.  */
12884
12885   if (*debug_file_directory == '\0')
12886     return NULL;
12887
12888   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12889                              0 /*is_dwp*/, 1 /*search_cwd*/);
12890 }
12891
12892 /* This function is mapped across the sections and remembers the offset and
12893    size of each of the DWO debugging sections we are interested in.  */
12894
12895 static void
12896 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12897 {
12898   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12899   const struct dwop_section_names *names = &dwop_section_names;
12900
12901   if (section_is_p (sectp->name, &names->abbrev_dwo))
12902     {
12903       dwo_sections->abbrev.s.section = sectp;
12904       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12905     }
12906   else if (section_is_p (sectp->name, &names->info_dwo))
12907     {
12908       dwo_sections->info.s.section = sectp;
12909       dwo_sections->info.size = bfd_get_section_size (sectp);
12910     }
12911   else if (section_is_p (sectp->name, &names->line_dwo))
12912     {
12913       dwo_sections->line.s.section = sectp;
12914       dwo_sections->line.size = bfd_get_section_size (sectp);
12915     }
12916   else if (section_is_p (sectp->name, &names->loc_dwo))
12917     {
12918       dwo_sections->loc.s.section = sectp;
12919       dwo_sections->loc.size = bfd_get_section_size (sectp);
12920     }
12921   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12922     {
12923       dwo_sections->macinfo.s.section = sectp;
12924       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12925     }
12926   else if (section_is_p (sectp->name, &names->macro_dwo))
12927     {
12928       dwo_sections->macro.s.section = sectp;
12929       dwo_sections->macro.size = bfd_get_section_size (sectp);
12930     }
12931   else if (section_is_p (sectp->name, &names->str_dwo))
12932     {
12933       dwo_sections->str.s.section = sectp;
12934       dwo_sections->str.size = bfd_get_section_size (sectp);
12935     }
12936   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12937     {
12938       dwo_sections->str_offsets.s.section = sectp;
12939       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12940     }
12941   else if (section_is_p (sectp->name, &names->types_dwo))
12942     {
12943       struct dwarf2_section_info type_section;
12944
12945       memset (&type_section, 0, sizeof (type_section));
12946       type_section.s.section = sectp;
12947       type_section.size = bfd_get_section_size (sectp);
12948       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12949                      &type_section);
12950     }
12951 }
12952
12953 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12954    by PER_CU.  This is for the non-DWP case.
12955    The result is NULL if DWO_NAME can't be found.  */
12956
12957 static struct dwo_file *
12958 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12959                         const char *dwo_name, const char *comp_dir)
12960 {
12961   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12962   struct objfile *objfile = dwarf2_per_objfile->objfile;
12963
12964   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12965   if (dbfd == NULL)
12966     {
12967       if (dwarf_read_debug)
12968         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12969       return NULL;
12970     }
12971
12972   /* We use a unique pointer here, despite the obstack allocation,
12973      because a dwo_file needs some cleanup if it is abandoned.  */
12974   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12975                                         struct dwo_file));
12976   dwo_file->dwo_name = dwo_name;
12977   dwo_file->comp_dir = comp_dir;
12978   dwo_file->dbfd = dbfd.release ();
12979
12980   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12981                          &dwo_file->sections);
12982
12983   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12984                          dwo_file->cus);
12985
12986   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12987                                  dwo_file->sections.types, dwo_file->tus);
12988
12989   if (dwarf_read_debug)
12990     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12991
12992   return dwo_file.release ();
12993 }
12994
12995 /* This function is mapped across the sections and remembers the offset and
12996    size of each of the DWP debugging sections common to version 1 and 2 that
12997    we are interested in.  */
12998
12999 static void
13000 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13001                                    void *dwp_file_ptr)
13002 {
13003   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13004   const struct dwop_section_names *names = &dwop_section_names;
13005   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13006
13007   /* Record the ELF section number for later lookup: this is what the
13008      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13009   gdb_assert (elf_section_nr < dwp_file->num_sections);
13010   dwp_file->elf_sections[elf_section_nr] = sectp;
13011
13012   /* Look for specific sections that we need.  */
13013   if (section_is_p (sectp->name, &names->str_dwo))
13014     {
13015       dwp_file->sections.str.s.section = sectp;
13016       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13017     }
13018   else if (section_is_p (sectp->name, &names->cu_index))
13019     {
13020       dwp_file->sections.cu_index.s.section = sectp;
13021       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13022     }
13023   else if (section_is_p (sectp->name, &names->tu_index))
13024     {
13025       dwp_file->sections.tu_index.s.section = sectp;
13026       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13027     }
13028 }
13029
13030 /* This function is mapped across the sections and remembers the offset and
13031    size of each of the DWP version 2 debugging sections that we are interested
13032    in.  This is split into a separate function because we don't know if we
13033    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13034
13035 static void
13036 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13037 {
13038   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13039   const struct dwop_section_names *names = &dwop_section_names;
13040   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13041
13042   /* Record the ELF section number for later lookup: this is what the
13043      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13044   gdb_assert (elf_section_nr < dwp_file->num_sections);
13045   dwp_file->elf_sections[elf_section_nr] = sectp;
13046
13047   /* Look for specific sections that we need.  */
13048   if (section_is_p (sectp->name, &names->abbrev_dwo))
13049     {
13050       dwp_file->sections.abbrev.s.section = sectp;
13051       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13052     }
13053   else if (section_is_p (sectp->name, &names->info_dwo))
13054     {
13055       dwp_file->sections.info.s.section = sectp;
13056       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13057     }
13058   else if (section_is_p (sectp->name, &names->line_dwo))
13059     {
13060       dwp_file->sections.line.s.section = sectp;
13061       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13062     }
13063   else if (section_is_p (sectp->name, &names->loc_dwo))
13064     {
13065       dwp_file->sections.loc.s.section = sectp;
13066       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13067     }
13068   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13069     {
13070       dwp_file->sections.macinfo.s.section = sectp;
13071       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13072     }
13073   else if (section_is_p (sectp->name, &names->macro_dwo))
13074     {
13075       dwp_file->sections.macro.s.section = sectp;
13076       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13077     }
13078   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13079     {
13080       dwp_file->sections.str_offsets.s.section = sectp;
13081       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13082     }
13083   else if (section_is_p (sectp->name, &names->types_dwo))
13084     {
13085       dwp_file->sections.types.s.section = sectp;
13086       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13087     }
13088 }
13089
13090 /* Hash function for dwp_file loaded CUs/TUs.  */
13091
13092 static hashval_t
13093 hash_dwp_loaded_cutus (const void *item)
13094 {
13095   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13096
13097   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13098   return dwo_unit->signature;
13099 }
13100
13101 /* Equality function for dwp_file loaded CUs/TUs.  */
13102
13103 static int
13104 eq_dwp_loaded_cutus (const void *a, const void *b)
13105 {
13106   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13107   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13108
13109   return dua->signature == dub->signature;
13110 }
13111
13112 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13113
13114 static htab_t
13115 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13116 {
13117   return htab_create_alloc_ex (3,
13118                                hash_dwp_loaded_cutus,
13119                                eq_dwp_loaded_cutus,
13120                                NULL,
13121                                &objfile->objfile_obstack,
13122                                hashtab_obstack_allocate,
13123                                dummy_obstack_deallocate);
13124 }
13125
13126 /* Try to open DWP file FILE_NAME.
13127    The result is the bfd handle of the file.
13128    If there is a problem finding or opening the file, return NULL.
13129    Upon success, the canonicalized path of the file is stored in the bfd,
13130    same as symfile_bfd_open.  */
13131
13132 static gdb_bfd_ref_ptr
13133 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13134                const char *file_name)
13135 {
13136   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13137                                             1 /*is_dwp*/,
13138                                             1 /*search_cwd*/));
13139   if (abfd != NULL)
13140     return abfd;
13141
13142   /* Work around upstream bug 15652.
13143      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13144      [Whether that's a "bug" is debatable, but it is getting in our way.]
13145      We have no real idea where the dwp file is, because gdb's realpath-ing
13146      of the executable's path may have discarded the needed info.
13147      [IWBN if the dwp file name was recorded in the executable, akin to
13148      .gnu_debuglink, but that doesn't exist yet.]
13149      Strip the directory from FILE_NAME and search again.  */
13150   if (*debug_file_directory != '\0')
13151     {
13152       /* Don't implicitly search the current directory here.
13153          If the user wants to search "." to handle this case,
13154          it must be added to debug-file-directory.  */
13155       return try_open_dwop_file (dwarf2_per_objfile,
13156                                  lbasename (file_name), 1 /*is_dwp*/,
13157                                  0 /*search_cwd*/);
13158     }
13159
13160   return NULL;
13161 }
13162
13163 /* Initialize the use of the DWP file for the current objfile.
13164    By convention the name of the DWP file is ${objfile}.dwp.
13165    The result is NULL if it can't be found.  */
13166
13167 static std::unique_ptr<struct dwp_file>
13168 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13169 {
13170   struct objfile *objfile = dwarf2_per_objfile->objfile;
13171
13172   /* Try to find first .dwp for the binary file before any symbolic links
13173      resolving.  */
13174
13175   /* If the objfile is a debug file, find the name of the real binary
13176      file and get the name of dwp file from there.  */
13177   std::string dwp_name;
13178   if (objfile->separate_debug_objfile_backlink != NULL)
13179     {
13180       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13181       const char *backlink_basename = lbasename (backlink->original_name);
13182
13183       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13184     }
13185   else
13186     dwp_name = objfile->original_name;
13187
13188   dwp_name += ".dwp";
13189
13190   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13191   if (dbfd == NULL
13192       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13193     {
13194       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13195       dwp_name = objfile_name (objfile);
13196       dwp_name += ".dwp";
13197       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13198     }
13199
13200   if (dbfd == NULL)
13201     {
13202       if (dwarf_read_debug)
13203         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13204       return std::unique_ptr<dwp_file> ();
13205     }
13206
13207   const char *name = bfd_get_filename (dbfd.get ());
13208   std::unique_ptr<struct dwp_file> dwp_file
13209     (new struct dwp_file (name, std::move (dbfd)));
13210
13211   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
13212   dwp_file->elf_sections =
13213     OBSTACK_CALLOC (&objfile->objfile_obstack,
13214                     dwp_file->num_sections, asection *);
13215
13216   bfd_map_over_sections (dwp_file->dbfd.get (),
13217                          dwarf2_locate_common_dwp_sections,
13218                          dwp_file.get ());
13219
13220   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13221                                          0);
13222
13223   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13224                                          1);
13225
13226   /* The DWP file version is stored in the hash table.  Oh well.  */
13227   if (dwp_file->cus && dwp_file->tus
13228       && dwp_file->cus->version != dwp_file->tus->version)
13229     {
13230       /* Technically speaking, we should try to limp along, but this is
13231          pretty bizarre.  We use pulongest here because that's the established
13232          portability solution (e.g, we cannot use %u for uint32_t).  */
13233       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13234                " TU version %s [in DWP file %s]"),
13235              pulongest (dwp_file->cus->version),
13236              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13237     }
13238
13239   if (dwp_file->cus)
13240     dwp_file->version = dwp_file->cus->version;
13241   else if (dwp_file->tus)
13242     dwp_file->version = dwp_file->tus->version;
13243   else
13244     dwp_file->version = 2;
13245
13246   if (dwp_file->version == 2)
13247     bfd_map_over_sections (dwp_file->dbfd.get (),
13248                            dwarf2_locate_v2_dwp_sections,
13249                            dwp_file.get ());
13250
13251   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13252   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13253
13254   if (dwarf_read_debug)
13255     {
13256       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13257       fprintf_unfiltered (gdb_stdlog,
13258                           "    %s CUs, %s TUs\n",
13259                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13260                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13261     }
13262
13263   return dwp_file;
13264 }
13265
13266 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13267
13268 static struct dwp_file *
13269 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13270 {
13271   if (! dwarf2_per_objfile->dwp_checked)
13272     {
13273       dwarf2_per_objfile->dwp_file
13274         = open_and_init_dwp_file (dwarf2_per_objfile);
13275       dwarf2_per_objfile->dwp_checked = 1;
13276     }
13277   return dwarf2_per_objfile->dwp_file.get ();
13278 }
13279
13280 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13281    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13282    or in the DWP file for the objfile, referenced by THIS_UNIT.
13283    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13284    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13285
13286    This is called, for example, when wanting to read a variable with a
13287    complex location.  Therefore we don't want to do file i/o for every call.
13288    Therefore we don't want to look for a DWO file on every call.
13289    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13290    then we check if we've already seen DWO_NAME, and only THEN do we check
13291    for a DWO file.
13292
13293    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13294    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13295
13296 static struct dwo_unit *
13297 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13298                  const char *dwo_name, const char *comp_dir,
13299                  ULONGEST signature, int is_debug_types)
13300 {
13301   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13302   struct objfile *objfile = dwarf2_per_objfile->objfile;
13303   const char *kind = is_debug_types ? "TU" : "CU";
13304   void **dwo_file_slot;
13305   struct dwo_file *dwo_file;
13306   struct dwp_file *dwp_file;
13307
13308   /* First see if there's a DWP file.
13309      If we have a DWP file but didn't find the DWO inside it, don't
13310      look for the original DWO file.  It makes gdb behave differently
13311      depending on whether one is debugging in the build tree.  */
13312
13313   dwp_file = get_dwp_file (dwarf2_per_objfile);
13314   if (dwp_file != NULL)
13315     {
13316       const struct dwp_hash_table *dwp_htab =
13317         is_debug_types ? dwp_file->tus : dwp_file->cus;
13318
13319       if (dwp_htab != NULL)
13320         {
13321           struct dwo_unit *dwo_cutu =
13322             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13323                                     signature, is_debug_types);
13324
13325           if (dwo_cutu != NULL)
13326             {
13327               if (dwarf_read_debug)
13328                 {
13329                   fprintf_unfiltered (gdb_stdlog,
13330                                       "Virtual DWO %s %s found: @%s\n",
13331                                       kind, hex_string (signature),
13332                                       host_address_to_string (dwo_cutu));
13333                 }
13334               return dwo_cutu;
13335             }
13336         }
13337     }
13338   else
13339     {
13340       /* No DWP file, look for the DWO file.  */
13341
13342       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13343                                             dwo_name, comp_dir);
13344       if (*dwo_file_slot == NULL)
13345         {
13346           /* Read in the file and build a table of the CUs/TUs it contains.  */
13347           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13348         }
13349       /* NOTE: This will be NULL if unable to open the file.  */
13350       dwo_file = (struct dwo_file *) *dwo_file_slot;
13351
13352       if (dwo_file != NULL)
13353         {
13354           struct dwo_unit *dwo_cutu = NULL;
13355
13356           if (is_debug_types && dwo_file->tus)
13357             {
13358               struct dwo_unit find_dwo_cutu;
13359
13360               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13361               find_dwo_cutu.signature = signature;
13362               dwo_cutu
13363                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13364             }
13365           else if (!is_debug_types && dwo_file->cus)
13366             {
13367               struct dwo_unit find_dwo_cutu;
13368
13369               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13370               find_dwo_cutu.signature = signature;
13371               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13372                                                        &find_dwo_cutu);
13373             }
13374
13375           if (dwo_cutu != NULL)
13376             {
13377               if (dwarf_read_debug)
13378                 {
13379                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13380                                       kind, dwo_name, hex_string (signature),
13381                                       host_address_to_string (dwo_cutu));
13382                 }
13383               return dwo_cutu;
13384             }
13385         }
13386     }
13387
13388   /* We didn't find it.  This could mean a dwo_id mismatch, or
13389      someone deleted the DWO/DWP file, or the search path isn't set up
13390      correctly to find the file.  */
13391
13392   if (dwarf_read_debug)
13393     {
13394       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13395                           kind, dwo_name, hex_string (signature));
13396     }
13397
13398   /* This is a warning and not a complaint because it can be caused by
13399      pilot error (e.g., user accidentally deleting the DWO).  */
13400   {
13401     /* Print the name of the DWP file if we looked there, helps the user
13402        better diagnose the problem.  */
13403     std::string dwp_text;
13404
13405     if (dwp_file != NULL)
13406       dwp_text = string_printf (" [in DWP file %s]",
13407                                 lbasename (dwp_file->name));
13408
13409     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13410                " [in module %s]"),
13411              kind, dwo_name, hex_string (signature),
13412              dwp_text.c_str (),
13413              this_unit->is_debug_types ? "TU" : "CU",
13414              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13415   }
13416   return NULL;
13417 }
13418
13419 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13420    See lookup_dwo_cutu_unit for details.  */
13421
13422 static struct dwo_unit *
13423 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13424                       const char *dwo_name, const char *comp_dir,
13425                       ULONGEST signature)
13426 {
13427   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13428 }
13429
13430 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13431    See lookup_dwo_cutu_unit for details.  */
13432
13433 static struct dwo_unit *
13434 lookup_dwo_type_unit (struct signatured_type *this_tu,
13435                       const char *dwo_name, const char *comp_dir)
13436 {
13437   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13438 }
13439
13440 /* Traversal function for queue_and_load_all_dwo_tus.  */
13441
13442 static int
13443 queue_and_load_dwo_tu (void **slot, void *info)
13444 {
13445   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13446   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13447   ULONGEST signature = dwo_unit->signature;
13448   struct signatured_type *sig_type =
13449     lookup_dwo_signatured_type (per_cu->cu, signature);
13450
13451   if (sig_type != NULL)
13452     {
13453       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13454
13455       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13456          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13457          while processing PER_CU.  */
13458       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13459         load_full_type_unit (sig_cu);
13460       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13461     }
13462
13463   return 1;
13464 }
13465
13466 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13467    The DWO may have the only definition of the type, though it may not be
13468    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13469    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13470
13471 static void
13472 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13473 {
13474   struct dwo_unit *dwo_unit;
13475   struct dwo_file *dwo_file;
13476
13477   gdb_assert (!per_cu->is_debug_types);
13478   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13479   gdb_assert (per_cu->cu != NULL);
13480
13481   dwo_unit = per_cu->cu->dwo_unit;
13482   gdb_assert (dwo_unit != NULL);
13483
13484   dwo_file = dwo_unit->dwo_file;
13485   if (dwo_file->tus != NULL)
13486     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13487 }
13488
13489 /* Free all resources associated with DWO_FILE.
13490    Close the DWO file and munmap the sections.  */
13491
13492 static void
13493 free_dwo_file (struct dwo_file *dwo_file)
13494 {
13495   /* Note: dbfd is NULL for virtual DWO files.  */
13496   gdb_bfd_unref (dwo_file->dbfd);
13497
13498   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13499 }
13500
13501 /* Traversal function for free_dwo_files.  */
13502
13503 static int
13504 free_dwo_file_from_slot (void **slot, void *info)
13505 {
13506   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13507
13508   free_dwo_file (dwo_file);
13509
13510   return 1;
13511 }
13512
13513 /* Free all resources associated with DWO_FILES.  */
13514
13515 static void
13516 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13517 {
13518   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13519 }
13520 \f
13521 /* Read in various DIEs.  */
13522
13523 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13524    Inherit only the children of the DW_AT_abstract_origin DIE not being
13525    already referenced by DW_AT_abstract_origin from the children of the
13526    current DIE.  */
13527
13528 static void
13529 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13530 {
13531   struct die_info *child_die;
13532   sect_offset *offsetp;
13533   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13534   struct die_info *origin_die;
13535   /* Iterator of the ORIGIN_DIE children.  */
13536   struct die_info *origin_child_die;
13537   struct attribute *attr;
13538   struct dwarf2_cu *origin_cu;
13539   struct pending **origin_previous_list_in_scope;
13540
13541   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13542   if (!attr)
13543     return;
13544
13545   /* Note that following die references may follow to a die in a
13546      different cu.  */
13547
13548   origin_cu = cu;
13549   origin_die = follow_die_ref (die, attr, &origin_cu);
13550
13551   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13552      symbols in.  */
13553   origin_previous_list_in_scope = origin_cu->list_in_scope;
13554   origin_cu->list_in_scope = cu->list_in_scope;
13555
13556   if (die->tag != origin_die->tag
13557       && !(die->tag == DW_TAG_inlined_subroutine
13558            && origin_die->tag == DW_TAG_subprogram))
13559     complaint (_("DIE %s and its abstract origin %s have different tags"),
13560                sect_offset_str (die->sect_off),
13561                sect_offset_str (origin_die->sect_off));
13562
13563   std::vector<sect_offset> offsets;
13564
13565   for (child_die = die->child;
13566        child_die && child_die->tag;
13567        child_die = sibling_die (child_die))
13568     {
13569       struct die_info *child_origin_die;
13570       struct dwarf2_cu *child_origin_cu;
13571
13572       /* We are trying to process concrete instance entries:
13573          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13574          it's not relevant to our analysis here. i.e. detecting DIEs that are
13575          present in the abstract instance but not referenced in the concrete
13576          one.  */
13577       if (child_die->tag == DW_TAG_call_site
13578           || child_die->tag == DW_TAG_GNU_call_site)
13579         continue;
13580
13581       /* For each CHILD_DIE, find the corresponding child of
13582          ORIGIN_DIE.  If there is more than one layer of
13583          DW_AT_abstract_origin, follow them all; there shouldn't be,
13584          but GCC versions at least through 4.4 generate this (GCC PR
13585          40573).  */
13586       child_origin_die = child_die;
13587       child_origin_cu = cu;
13588       while (1)
13589         {
13590           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13591                               child_origin_cu);
13592           if (attr == NULL)
13593             break;
13594           child_origin_die = follow_die_ref (child_origin_die, attr,
13595                                              &child_origin_cu);
13596         }
13597
13598       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13599          counterpart may exist.  */
13600       if (child_origin_die != child_die)
13601         {
13602           if (child_die->tag != child_origin_die->tag
13603               && !(child_die->tag == DW_TAG_inlined_subroutine
13604                    && child_origin_die->tag == DW_TAG_subprogram))
13605             complaint (_("Child DIE %s and its abstract origin %s have "
13606                          "different tags"),
13607                        sect_offset_str (child_die->sect_off),
13608                        sect_offset_str (child_origin_die->sect_off));
13609           if (child_origin_die->parent != origin_die)
13610             complaint (_("Child DIE %s and its abstract origin %s have "
13611                          "different parents"),
13612                        sect_offset_str (child_die->sect_off),
13613                        sect_offset_str (child_origin_die->sect_off));
13614           else
13615             offsets.push_back (child_origin_die->sect_off);
13616         }
13617     }
13618   std::sort (offsets.begin (), offsets.end ());
13619   sect_offset *offsets_end = offsets.data () + offsets.size ();
13620   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13621     if (offsetp[-1] == *offsetp)
13622       complaint (_("Multiple children of DIE %s refer "
13623                    "to DIE %s as their abstract origin"),
13624                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13625
13626   offsetp = offsets.data ();
13627   origin_child_die = origin_die->child;
13628   while (origin_child_die && origin_child_die->tag)
13629     {
13630       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13631       while (offsetp < offsets_end
13632              && *offsetp < origin_child_die->sect_off)
13633         offsetp++;
13634       if (offsetp >= offsets_end
13635           || *offsetp > origin_child_die->sect_off)
13636         {
13637           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13638              Check whether we're already processing ORIGIN_CHILD_DIE.
13639              This can happen with mutually referenced abstract_origins.
13640              PR 16581.  */
13641           if (!origin_child_die->in_process)
13642             process_die (origin_child_die, origin_cu);
13643         }
13644       origin_child_die = sibling_die (origin_child_die);
13645     }
13646   origin_cu->list_in_scope = origin_previous_list_in_scope;
13647 }
13648
13649 static void
13650 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13651 {
13652   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13653   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13654   struct context_stack *newobj;
13655   CORE_ADDR lowpc;
13656   CORE_ADDR highpc;
13657   struct die_info *child_die;
13658   struct attribute *attr, *call_line, *call_file;
13659   const char *name;
13660   CORE_ADDR baseaddr;
13661   struct block *block;
13662   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13663   std::vector<struct symbol *> template_args;
13664   struct template_symbol *templ_func = NULL;
13665
13666   if (inlined_func)
13667     {
13668       /* If we do not have call site information, we can't show the
13669          caller of this inlined function.  That's too confusing, so
13670          only use the scope for local variables.  */
13671       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13672       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13673       if (call_line == NULL || call_file == NULL)
13674         {
13675           read_lexical_block_scope (die, cu);
13676           return;
13677         }
13678     }
13679
13680   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13681
13682   name = dwarf2_name (die, cu);
13683
13684   /* Ignore functions with missing or empty names.  These are actually
13685      illegal according to the DWARF standard.  */
13686   if (name == NULL)
13687     {
13688       complaint (_("missing name for subprogram DIE at %s"),
13689                  sect_offset_str (die->sect_off));
13690       return;
13691     }
13692
13693   /* Ignore functions with missing or invalid low and high pc attributes.  */
13694   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13695       <= PC_BOUNDS_INVALID)
13696     {
13697       attr = dwarf2_attr (die, DW_AT_external, cu);
13698       if (!attr || !DW_UNSND (attr))
13699         complaint (_("cannot get low and high bounds "
13700                      "for subprogram DIE at %s"),
13701                    sect_offset_str (die->sect_off));
13702       return;
13703     }
13704
13705   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13706   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13707
13708   /* If we have any template arguments, then we must allocate a
13709      different sort of symbol.  */
13710   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13711     {
13712       if (child_die->tag == DW_TAG_template_type_param
13713           || child_die->tag == DW_TAG_template_value_param)
13714         {
13715           templ_func = allocate_template_symbol (objfile);
13716           templ_func->subclass = SYMBOL_TEMPLATE;
13717           break;
13718         }
13719     }
13720
13721   newobj = cu->get_builder ()->push_context (0, lowpc);
13722   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13723                              (struct symbol *) templ_func);
13724
13725   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
13726     set_objfile_main_name (objfile, SYMBOL_LINKAGE_NAME (newobj->name),
13727                            cu->language);
13728
13729   /* If there is a location expression for DW_AT_frame_base, record
13730      it.  */
13731   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13732   if (attr)
13733     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13734
13735   /* If there is a location for the static link, record it.  */
13736   newobj->static_link = NULL;
13737   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13738   if (attr)
13739     {
13740       newobj->static_link
13741         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13742       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13743     }
13744
13745   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13746
13747   if (die->child != NULL)
13748     {
13749       child_die = die->child;
13750       while (child_die && child_die->tag)
13751         {
13752           if (child_die->tag == DW_TAG_template_type_param
13753               || child_die->tag == DW_TAG_template_value_param)
13754             {
13755               struct symbol *arg = new_symbol (child_die, NULL, cu);
13756
13757               if (arg != NULL)
13758                 template_args.push_back (arg);
13759             }
13760           else
13761             process_die (child_die, cu);
13762           child_die = sibling_die (child_die);
13763         }
13764     }
13765
13766   inherit_abstract_dies (die, cu);
13767
13768   /* If we have a DW_AT_specification, we might need to import using
13769      directives from the context of the specification DIE.  See the
13770      comment in determine_prefix.  */
13771   if (cu->language == language_cplus
13772       && dwarf2_attr (die, DW_AT_specification, cu))
13773     {
13774       struct dwarf2_cu *spec_cu = cu;
13775       struct die_info *spec_die = die_specification (die, &spec_cu);
13776
13777       while (spec_die)
13778         {
13779           child_die = spec_die->child;
13780           while (child_die && child_die->tag)
13781             {
13782               if (child_die->tag == DW_TAG_imported_module)
13783                 process_die (child_die, spec_cu);
13784               child_die = sibling_die (child_die);
13785             }
13786
13787           /* In some cases, GCC generates specification DIEs that
13788              themselves contain DW_AT_specification attributes.  */
13789           spec_die = die_specification (spec_die, &spec_cu);
13790         }
13791     }
13792
13793   struct context_stack cstk = cu->get_builder ()->pop_context ();
13794   /* Make a block for the local symbols within.  */
13795   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13796                                      cstk.static_link, lowpc, highpc);
13797
13798   /* For C++, set the block's scope.  */
13799   if ((cu->language == language_cplus
13800        || cu->language == language_fortran
13801        || cu->language == language_d
13802        || cu->language == language_rust)
13803       && cu->processing_has_namespace_info)
13804     block_set_scope (block, determine_prefix (die, cu),
13805                      &objfile->objfile_obstack);
13806
13807   /* If we have address ranges, record them.  */
13808   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13809
13810   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13811
13812   /* Attach template arguments to function.  */
13813   if (!template_args.empty ())
13814     {
13815       gdb_assert (templ_func != NULL);
13816
13817       templ_func->n_template_arguments = template_args.size ();
13818       templ_func->template_arguments
13819         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13820                      templ_func->n_template_arguments);
13821       memcpy (templ_func->template_arguments,
13822               template_args.data (),
13823               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13824
13825       /* Make sure that the symtab is set on the new symbols.  Even
13826          though they don't appear in this symtab directly, other parts
13827          of gdb assume that symbols do, and this is reasonably
13828          true.  */
13829       for (symbol *sym : template_args)
13830         symbol_set_symtab (sym, symbol_symtab (templ_func));
13831     }
13832
13833   /* In C++, we can have functions nested inside functions (e.g., when
13834      a function declares a class that has methods).  This means that
13835      when we finish processing a function scope, we may need to go
13836      back to building a containing block's symbol lists.  */
13837   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13838   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13839
13840   /* If we've finished processing a top-level function, subsequent
13841      symbols go in the file symbol list.  */
13842   if (cu->get_builder ()->outermost_context_p ())
13843     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13844 }
13845
13846 /* Process all the DIES contained within a lexical block scope.  Start
13847    a new scope, process the dies, and then close the scope.  */
13848
13849 static void
13850 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13851 {
13852   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13853   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13854   CORE_ADDR lowpc, highpc;
13855   struct die_info *child_die;
13856   CORE_ADDR baseaddr;
13857
13858   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13859
13860   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13861   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13862      as multiple lexical blocks?  Handling children in a sane way would
13863      be nasty.  Might be easier to properly extend generic blocks to
13864      describe ranges.  */
13865   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13866     {
13867     case PC_BOUNDS_NOT_PRESENT:
13868       /* DW_TAG_lexical_block has no attributes, process its children as if
13869          there was no wrapping by that DW_TAG_lexical_block.
13870          GCC does no longer produces such DWARF since GCC r224161.  */
13871       for (child_die = die->child;
13872            child_die != NULL && child_die->tag;
13873            child_die = sibling_die (child_die))
13874         process_die (child_die, cu);
13875       return;
13876     case PC_BOUNDS_INVALID:
13877       return;
13878     }
13879   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13880   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13881
13882   cu->get_builder ()->push_context (0, lowpc);
13883   if (die->child != NULL)
13884     {
13885       child_die = die->child;
13886       while (child_die && child_die->tag)
13887         {
13888           process_die (child_die, cu);
13889           child_die = sibling_die (child_die);
13890         }
13891     }
13892   inherit_abstract_dies (die, cu);
13893   struct context_stack cstk = cu->get_builder ()->pop_context ();
13894
13895   if (*cu->get_builder ()->get_local_symbols () != NULL
13896       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13897     {
13898       struct block *block
13899         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13900                                      cstk.start_addr, highpc);
13901
13902       /* Note that recording ranges after traversing children, as we
13903          do here, means that recording a parent's ranges entails
13904          walking across all its children's ranges as they appear in
13905          the address map, which is quadratic behavior.
13906
13907          It would be nicer to record the parent's ranges before
13908          traversing its children, simply overriding whatever you find
13909          there.  But since we don't even decide whether to create a
13910          block until after we've traversed its children, that's hard
13911          to do.  */
13912       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13913     }
13914   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13915   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13916 }
13917
13918 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13919
13920 static void
13921 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13922 {
13923   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13924   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13925   CORE_ADDR pc, baseaddr;
13926   struct attribute *attr;
13927   struct call_site *call_site, call_site_local;
13928   void **slot;
13929   int nparams;
13930   struct die_info *child_die;
13931
13932   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13933
13934   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13935   if (attr == NULL)
13936     {
13937       /* This was a pre-DWARF-5 GNU extension alias
13938          for DW_AT_call_return_pc.  */
13939       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13940     }
13941   if (!attr)
13942     {
13943       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13944                    "DIE %s [in module %s]"),
13945                  sect_offset_str (die->sect_off), objfile_name (objfile));
13946       return;
13947     }
13948   pc = attr_value_as_address (attr) + baseaddr;
13949   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13950
13951   if (cu->call_site_htab == NULL)
13952     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13953                                                NULL, &objfile->objfile_obstack,
13954                                                hashtab_obstack_allocate, NULL);
13955   call_site_local.pc = pc;
13956   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13957   if (*slot != NULL)
13958     {
13959       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13960                    "DIE %s [in module %s]"),
13961                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13962                  objfile_name (objfile));
13963       return;
13964     }
13965
13966   /* Count parameters at the caller.  */
13967
13968   nparams = 0;
13969   for (child_die = die->child; child_die && child_die->tag;
13970        child_die = sibling_die (child_die))
13971     {
13972       if (child_die->tag != DW_TAG_call_site_parameter
13973           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13974         {
13975           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13976                        "DW_TAG_call_site child DIE %s [in module %s]"),
13977                      child_die->tag, sect_offset_str (child_die->sect_off),
13978                      objfile_name (objfile));
13979           continue;
13980         }
13981
13982       nparams++;
13983     }
13984
13985   call_site
13986     = ((struct call_site *)
13987        obstack_alloc (&objfile->objfile_obstack,
13988                       sizeof (*call_site)
13989                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13990   *slot = call_site;
13991   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13992   call_site->pc = pc;
13993
13994   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13995       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13996     {
13997       struct die_info *func_die;
13998
13999       /* Skip also over DW_TAG_inlined_subroutine.  */
14000       for (func_die = die->parent;
14001            func_die && func_die->tag != DW_TAG_subprogram
14002            && func_die->tag != DW_TAG_subroutine_type;
14003            func_die = func_die->parent);
14004
14005       /* DW_AT_call_all_calls is a superset
14006          of DW_AT_call_all_tail_calls.  */
14007       if (func_die
14008           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14009           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14010           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14011           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14012         {
14013           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14014              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14015              both the initial caller containing the real return address PC and
14016              the final callee containing the current PC of a chain of tail
14017              calls do not need to have the tail call list complete.  But any
14018              function candidate for a virtual tail call frame searched via
14019              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14020              determined unambiguously.  */
14021         }
14022       else
14023         {
14024           struct type *func_type = NULL;
14025
14026           if (func_die)
14027             func_type = get_die_type (func_die, cu);
14028           if (func_type != NULL)
14029             {
14030               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14031
14032               /* Enlist this call site to the function.  */
14033               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14034               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14035             }
14036           else
14037             complaint (_("Cannot find function owning DW_TAG_call_site "
14038                          "DIE %s [in module %s]"),
14039                        sect_offset_str (die->sect_off), objfile_name (objfile));
14040         }
14041     }
14042
14043   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14044   if (attr == NULL)
14045     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14046   if (attr == NULL)
14047     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14048   if (attr == NULL)
14049     {
14050       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14051       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14052     }
14053   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14054   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14055     /* Keep NULL DWARF_BLOCK.  */;
14056   else if (attr_form_is_block (attr))
14057     {
14058       struct dwarf2_locexpr_baton *dlbaton;
14059
14060       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14061       dlbaton->data = DW_BLOCK (attr)->data;
14062       dlbaton->size = DW_BLOCK (attr)->size;
14063       dlbaton->per_cu = cu->per_cu;
14064
14065       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14066     }
14067   else if (attr_form_is_ref (attr))
14068     {
14069       struct dwarf2_cu *target_cu = cu;
14070       struct die_info *target_die;
14071
14072       target_die = follow_die_ref (die, attr, &target_cu);
14073       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14074       if (die_is_declaration (target_die, target_cu))
14075         {
14076           const char *target_physname;
14077
14078           /* Prefer the mangled name; otherwise compute the demangled one.  */
14079           target_physname = dw2_linkage_name (target_die, target_cu);
14080           if (target_physname == NULL)
14081             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14082           if (target_physname == NULL)
14083             complaint (_("DW_AT_call_target target DIE has invalid "
14084                          "physname, for referencing DIE %s [in module %s]"),
14085                        sect_offset_str (die->sect_off), objfile_name (objfile));
14086           else
14087             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14088         }
14089       else
14090         {
14091           CORE_ADDR lowpc;
14092
14093           /* DW_AT_entry_pc should be preferred.  */
14094           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14095               <= PC_BOUNDS_INVALID)
14096             complaint (_("DW_AT_call_target target DIE has invalid "
14097                          "low pc, for referencing DIE %s [in module %s]"),
14098                        sect_offset_str (die->sect_off), objfile_name (objfile));
14099           else
14100             {
14101               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14102               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14103             }
14104         }
14105     }
14106   else
14107     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14108                  "block nor reference, for DIE %s [in module %s]"),
14109                sect_offset_str (die->sect_off), objfile_name (objfile));
14110
14111   call_site->per_cu = cu->per_cu;
14112
14113   for (child_die = die->child;
14114        child_die && child_die->tag;
14115        child_die = sibling_die (child_die))
14116     {
14117       struct call_site_parameter *parameter;
14118       struct attribute *loc, *origin;
14119
14120       if (child_die->tag != DW_TAG_call_site_parameter
14121           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14122         {
14123           /* Already printed the complaint above.  */
14124           continue;
14125         }
14126
14127       gdb_assert (call_site->parameter_count < nparams);
14128       parameter = &call_site->parameter[call_site->parameter_count];
14129
14130       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14131          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14132          register is contained in DW_AT_call_value.  */
14133
14134       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14135       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14136       if (origin == NULL)
14137         {
14138           /* This was a pre-DWARF-5 GNU extension alias
14139              for DW_AT_call_parameter.  */
14140           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14141         }
14142       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14143         {
14144           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14145
14146           sect_offset sect_off
14147             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14148           if (!offset_in_cu_p (&cu->header, sect_off))
14149             {
14150               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14151                  binding can be done only inside one CU.  Such referenced DIE
14152                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14153               complaint (_("DW_AT_call_parameter offset is not in CU for "
14154                            "DW_TAG_call_site child DIE %s [in module %s]"),
14155                          sect_offset_str (child_die->sect_off),
14156                          objfile_name (objfile));
14157               continue;
14158             }
14159           parameter->u.param_cu_off
14160             = (cu_offset) (sect_off - cu->header.sect_off);
14161         }
14162       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14163         {
14164           complaint (_("No DW_FORM_block* DW_AT_location for "
14165                        "DW_TAG_call_site child DIE %s [in module %s]"),
14166                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14167           continue;
14168         }
14169       else
14170         {
14171           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14172             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14173           if (parameter->u.dwarf_reg != -1)
14174             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14175           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14176                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14177                                              &parameter->u.fb_offset))
14178             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14179           else
14180             {
14181               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14182                            "for DW_FORM_block* DW_AT_location is supported for "
14183                            "DW_TAG_call_site child DIE %s "
14184                            "[in module %s]"),
14185                          sect_offset_str (child_die->sect_off),
14186                          objfile_name (objfile));
14187               continue;
14188             }
14189         }
14190
14191       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14192       if (attr == NULL)
14193         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14194       if (!attr_form_is_block (attr))
14195         {
14196           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14197                        "DW_TAG_call_site child DIE %s [in module %s]"),
14198                      sect_offset_str (child_die->sect_off),
14199                      objfile_name (objfile));
14200           continue;
14201         }
14202       parameter->value = DW_BLOCK (attr)->data;
14203       parameter->value_size = DW_BLOCK (attr)->size;
14204
14205       /* Parameters are not pre-cleared by memset above.  */
14206       parameter->data_value = NULL;
14207       parameter->data_value_size = 0;
14208       call_site->parameter_count++;
14209
14210       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14211       if (attr == NULL)
14212         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14213       if (attr)
14214         {
14215           if (!attr_form_is_block (attr))
14216             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14217                          "DW_TAG_call_site child DIE %s [in module %s]"),
14218                        sect_offset_str (child_die->sect_off),
14219                        objfile_name (objfile));
14220           else
14221             {
14222               parameter->data_value = DW_BLOCK (attr)->data;
14223               parameter->data_value_size = DW_BLOCK (attr)->size;
14224             }
14225         }
14226     }
14227 }
14228
14229 /* Helper function for read_variable.  If DIE represents a virtual
14230    table, then return the type of the concrete object that is
14231    associated with the virtual table.  Otherwise, return NULL.  */
14232
14233 static struct type *
14234 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14235 {
14236   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14237   if (attr == NULL)
14238     return NULL;
14239
14240   /* Find the type DIE.  */
14241   struct die_info *type_die = NULL;
14242   struct dwarf2_cu *type_cu = cu;
14243
14244   if (attr_form_is_ref (attr))
14245     type_die = follow_die_ref (die, attr, &type_cu);
14246   if (type_die == NULL)
14247     return NULL;
14248
14249   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14250     return NULL;
14251   return die_containing_type (type_die, type_cu);
14252 }
14253
14254 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14255
14256 static void
14257 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14258 {
14259   struct rust_vtable_symbol *storage = NULL;
14260
14261   if (cu->language == language_rust)
14262     {
14263       struct type *containing_type = rust_containing_type (die, cu);
14264
14265       if (containing_type != NULL)
14266         {
14267           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14268
14269           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14270                                     struct rust_vtable_symbol);
14271           initialize_objfile_symbol (storage);
14272           storage->concrete_type = containing_type;
14273           storage->subclass = SYMBOL_RUST_VTABLE;
14274         }
14275     }
14276
14277   struct symbol *res = new_symbol (die, NULL, cu, storage);
14278   struct attribute *abstract_origin
14279     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14280   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
14281   if (res == NULL && loc && abstract_origin)
14282     {
14283       /* We have a variable without a name, but with a location and an abstract
14284          origin.  This may be a concrete instance of an abstract variable
14285          referenced from an DW_OP_GNU_variable_value, so save it to find it back
14286          later.  */
14287       struct dwarf2_cu *origin_cu = cu;
14288       struct die_info *origin_die
14289         = follow_die_ref (die, abstract_origin, &origin_cu);
14290       dwarf2_per_objfile *dpo = cu->per_cu->dwarf2_per_objfile;
14291       dpo->abstract_to_concrete[origin_die->sect_off].push_back (die->sect_off);
14292     }
14293 }
14294
14295 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14296    reading .debug_rnglists.
14297    Callback's type should be:
14298     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14299    Return true if the attributes are present and valid, otherwise,
14300    return false.  */
14301
14302 template <typename Callback>
14303 static bool
14304 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14305                          Callback &&callback)
14306 {
14307   struct dwarf2_per_objfile *dwarf2_per_objfile
14308     = cu->per_cu->dwarf2_per_objfile;
14309   struct objfile *objfile = dwarf2_per_objfile->objfile;
14310   bfd *obfd = objfile->obfd;
14311   /* Base address selection entry.  */
14312   CORE_ADDR base;
14313   int found_base;
14314   const gdb_byte *buffer;
14315   CORE_ADDR baseaddr;
14316   bool overflow = false;
14317
14318   found_base = cu->base_known;
14319   base = cu->base_address;
14320
14321   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14322   if (offset >= dwarf2_per_objfile->rnglists.size)
14323     {
14324       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14325                  offset);
14326       return false;
14327     }
14328   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14329
14330   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14331
14332   while (1)
14333     {
14334       /* Initialize it due to a false compiler warning.  */
14335       CORE_ADDR range_beginning = 0, range_end = 0;
14336       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14337                                  + dwarf2_per_objfile->rnglists.size);
14338       unsigned int bytes_read;
14339
14340       if (buffer == buf_end)
14341         {
14342           overflow = true;
14343           break;
14344         }
14345       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14346       switch (rlet)
14347         {
14348         case DW_RLE_end_of_list:
14349           break;
14350         case DW_RLE_base_address:
14351           if (buffer + cu->header.addr_size > buf_end)
14352             {
14353               overflow = true;
14354               break;
14355             }
14356           base = read_address (obfd, buffer, cu, &bytes_read);
14357           found_base = 1;
14358           buffer += bytes_read;
14359           break;
14360         case DW_RLE_start_length:
14361           if (buffer + cu->header.addr_size > buf_end)
14362             {
14363               overflow = true;
14364               break;
14365             }
14366           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14367           buffer += bytes_read;
14368           range_end = (range_beginning
14369                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14370           buffer += bytes_read;
14371           if (buffer > buf_end)
14372             {
14373               overflow = true;
14374               break;
14375             }
14376           break;
14377         case DW_RLE_offset_pair:
14378           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14379           buffer += bytes_read;
14380           if (buffer > buf_end)
14381             {
14382               overflow = true;
14383               break;
14384             }
14385           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14386           buffer += bytes_read;
14387           if (buffer > buf_end)
14388             {
14389               overflow = true;
14390               break;
14391             }
14392           break;
14393         case DW_RLE_start_end:
14394           if (buffer + 2 * cu->header.addr_size > buf_end)
14395             {
14396               overflow = true;
14397               break;
14398             }
14399           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14400           buffer += bytes_read;
14401           range_end = read_address (obfd, buffer, cu, &bytes_read);
14402           buffer += bytes_read;
14403           break;
14404         default:
14405           complaint (_("Invalid .debug_rnglists data (no base address)"));
14406           return false;
14407         }
14408       if (rlet == DW_RLE_end_of_list || overflow)
14409         break;
14410       if (rlet == DW_RLE_base_address)
14411         continue;
14412
14413       if (!found_base)
14414         {
14415           /* We have no valid base address for the ranges
14416              data.  */
14417           complaint (_("Invalid .debug_rnglists data (no base address)"));
14418           return false;
14419         }
14420
14421       if (range_beginning > range_end)
14422         {
14423           /* Inverted range entries are invalid.  */
14424           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14425           return false;
14426         }
14427
14428       /* Empty range entries have no effect.  */
14429       if (range_beginning == range_end)
14430         continue;
14431
14432       range_beginning += base;
14433       range_end += base;
14434
14435       /* A not-uncommon case of bad debug info.
14436          Don't pollute the addrmap with bad data.  */
14437       if (range_beginning + baseaddr == 0
14438           && !dwarf2_per_objfile->has_section_at_zero)
14439         {
14440           complaint (_(".debug_rnglists entry has start address of zero"
14441                        " [in module %s]"), objfile_name (objfile));
14442           continue;
14443         }
14444
14445       callback (range_beginning, range_end);
14446     }
14447
14448   if (overflow)
14449     {
14450       complaint (_("Offset %d is not terminated "
14451                    "for DW_AT_ranges attribute"),
14452                  offset);
14453       return false;
14454     }
14455
14456   return true;
14457 }
14458
14459 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14460    Callback's type should be:
14461     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14462    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14463
14464 template <typename Callback>
14465 static int
14466 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14467                        Callback &&callback)
14468 {
14469   struct dwarf2_per_objfile *dwarf2_per_objfile
14470       = cu->per_cu->dwarf2_per_objfile;
14471   struct objfile *objfile = dwarf2_per_objfile->objfile;
14472   struct comp_unit_head *cu_header = &cu->header;
14473   bfd *obfd = objfile->obfd;
14474   unsigned int addr_size = cu_header->addr_size;
14475   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14476   /* Base address selection entry.  */
14477   CORE_ADDR base;
14478   int found_base;
14479   unsigned int dummy;
14480   const gdb_byte *buffer;
14481   CORE_ADDR baseaddr;
14482
14483   if (cu_header->version >= 5)
14484     return dwarf2_rnglists_process (offset, cu, callback);
14485
14486   found_base = cu->base_known;
14487   base = cu->base_address;
14488
14489   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14490   if (offset >= dwarf2_per_objfile->ranges.size)
14491     {
14492       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14493                  offset);
14494       return 0;
14495     }
14496   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14497
14498   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14499
14500   while (1)
14501     {
14502       CORE_ADDR range_beginning, range_end;
14503
14504       range_beginning = read_address (obfd, buffer, cu, &dummy);
14505       buffer += addr_size;
14506       range_end = read_address (obfd, buffer, cu, &dummy);
14507       buffer += addr_size;
14508       offset += 2 * addr_size;
14509
14510       /* An end of list marker is a pair of zero addresses.  */
14511       if (range_beginning == 0 && range_end == 0)
14512         /* Found the end of list entry.  */
14513         break;
14514
14515       /* Each base address selection entry is a pair of 2 values.
14516          The first is the largest possible address, the second is
14517          the base address.  Check for a base address here.  */
14518       if ((range_beginning & mask) == mask)
14519         {
14520           /* If we found the largest possible address, then we already
14521              have the base address in range_end.  */
14522           base = range_end;
14523           found_base = 1;
14524           continue;
14525         }
14526
14527       if (!found_base)
14528         {
14529           /* We have no valid base address for the ranges
14530              data.  */
14531           complaint (_("Invalid .debug_ranges data (no base address)"));
14532           return 0;
14533         }
14534
14535       if (range_beginning > range_end)
14536         {
14537           /* Inverted range entries are invalid.  */
14538           complaint (_("Invalid .debug_ranges data (inverted range)"));
14539           return 0;
14540         }
14541
14542       /* Empty range entries have no effect.  */
14543       if (range_beginning == range_end)
14544         continue;
14545
14546       range_beginning += base;
14547       range_end += base;
14548
14549       /* A not-uncommon case of bad debug info.
14550          Don't pollute the addrmap with bad data.  */
14551       if (range_beginning + baseaddr == 0
14552           && !dwarf2_per_objfile->has_section_at_zero)
14553         {
14554           complaint (_(".debug_ranges entry has start address of zero"
14555                        " [in module %s]"), objfile_name (objfile));
14556           continue;
14557         }
14558
14559       callback (range_beginning, range_end);
14560     }
14561
14562   return 1;
14563 }
14564
14565 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14566    Return 1 if the attributes are present and valid, otherwise, return 0.
14567    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14568
14569 static int
14570 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14571                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14572                     struct partial_symtab *ranges_pst)
14573 {
14574   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14575   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14576   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14577                                        SECT_OFF_TEXT (objfile));
14578   int low_set = 0;
14579   CORE_ADDR low = 0;
14580   CORE_ADDR high = 0;
14581   int retval;
14582
14583   retval = dwarf2_ranges_process (offset, cu,
14584     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14585     {
14586       if (ranges_pst != NULL)
14587         {
14588           CORE_ADDR lowpc;
14589           CORE_ADDR highpc;
14590
14591           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14592                                                range_beginning + baseaddr)
14593                    - baseaddr);
14594           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14595                                                 range_end + baseaddr)
14596                     - baseaddr);
14597           addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
14598                              lowpc, highpc - 1, ranges_pst);
14599         }
14600
14601       /* FIXME: This is recording everything as a low-high
14602          segment of consecutive addresses.  We should have a
14603          data structure for discontiguous block ranges
14604          instead.  */
14605       if (! low_set)
14606         {
14607           low = range_beginning;
14608           high = range_end;
14609           low_set = 1;
14610         }
14611       else
14612         {
14613           if (range_beginning < low)
14614             low = range_beginning;
14615           if (range_end > high)
14616             high = range_end;
14617         }
14618     });
14619   if (!retval)
14620     return 0;
14621
14622   if (! low_set)
14623     /* If the first entry is an end-of-list marker, the range
14624        describes an empty scope, i.e. no instructions.  */
14625     return 0;
14626
14627   if (low_return)
14628     *low_return = low;
14629   if (high_return)
14630     *high_return = high;
14631   return 1;
14632 }
14633
14634 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14635    definition for the return value.  *LOWPC and *HIGHPC are set iff
14636    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14637
14638 static enum pc_bounds_kind
14639 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14640                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14641                       struct partial_symtab *pst)
14642 {
14643   struct dwarf2_per_objfile *dwarf2_per_objfile
14644     = cu->per_cu->dwarf2_per_objfile;
14645   struct attribute *attr;
14646   struct attribute *attr_high;
14647   CORE_ADDR low = 0;
14648   CORE_ADDR high = 0;
14649   enum pc_bounds_kind ret;
14650
14651   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14652   if (attr_high)
14653     {
14654       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14655       if (attr)
14656         {
14657           low = attr_value_as_address (attr);
14658           high = attr_value_as_address (attr_high);
14659           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14660             high += low;
14661         }
14662       else
14663         /* Found high w/o low attribute.  */
14664         return PC_BOUNDS_INVALID;
14665
14666       /* Found consecutive range of addresses.  */
14667       ret = PC_BOUNDS_HIGH_LOW;
14668     }
14669   else
14670     {
14671       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14672       if (attr != NULL)
14673         {
14674           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14675              We take advantage of the fact that DW_AT_ranges does not appear
14676              in DW_TAG_compile_unit of DWO files.  */
14677           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14678           unsigned int ranges_offset = (DW_UNSND (attr)
14679                                         + (need_ranges_base
14680                                            ? cu->ranges_base
14681                                            : 0));
14682
14683           /* Value of the DW_AT_ranges attribute is the offset in the
14684              .debug_ranges section.  */
14685           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14686             return PC_BOUNDS_INVALID;
14687           /* Found discontinuous range of addresses.  */
14688           ret = PC_BOUNDS_RANGES;
14689         }
14690       else
14691         return PC_BOUNDS_NOT_PRESENT;
14692     }
14693
14694   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14695   if (high <= low)
14696     return PC_BOUNDS_INVALID;
14697
14698   /* When using the GNU linker, .gnu.linkonce. sections are used to
14699      eliminate duplicate copies of functions and vtables and such.
14700      The linker will arbitrarily choose one and discard the others.
14701      The AT_*_pc values for such functions refer to local labels in
14702      these sections.  If the section from that file was discarded, the
14703      labels are not in the output, so the relocs get a value of 0.
14704      If this is a discarded function, mark the pc bounds as invalid,
14705      so that GDB will ignore it.  */
14706   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14707     return PC_BOUNDS_INVALID;
14708
14709   *lowpc = low;
14710   if (highpc)
14711     *highpc = high;
14712   return ret;
14713 }
14714
14715 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14716    its low and high PC addresses.  Do nothing if these addresses could not
14717    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14718    and HIGHPC to the high address if greater than HIGHPC.  */
14719
14720 static void
14721 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14722                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14723                                  struct dwarf2_cu *cu)
14724 {
14725   CORE_ADDR low, high;
14726   struct die_info *child = die->child;
14727
14728   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14729     {
14730       *lowpc = std::min (*lowpc, low);
14731       *highpc = std::max (*highpc, high);
14732     }
14733
14734   /* If the language does not allow nested subprograms (either inside
14735      subprograms or lexical blocks), we're done.  */
14736   if (cu->language != language_ada)
14737     return;
14738
14739   /* Check all the children of the given DIE.  If it contains nested
14740      subprograms, then check their pc bounds.  Likewise, we need to
14741      check lexical blocks as well, as they may also contain subprogram
14742      definitions.  */
14743   while (child && child->tag)
14744     {
14745       if (child->tag == DW_TAG_subprogram
14746           || child->tag == DW_TAG_lexical_block)
14747         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14748       child = sibling_die (child);
14749     }
14750 }
14751
14752 /* Get the low and high pc's represented by the scope DIE, and store
14753    them in *LOWPC and *HIGHPC.  If the correct values can't be
14754    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14755
14756 static void
14757 get_scope_pc_bounds (struct die_info *die,
14758                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14759                      struct dwarf2_cu *cu)
14760 {
14761   CORE_ADDR best_low = (CORE_ADDR) -1;
14762   CORE_ADDR best_high = (CORE_ADDR) 0;
14763   CORE_ADDR current_low, current_high;
14764
14765   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14766       >= PC_BOUNDS_RANGES)
14767     {
14768       best_low = current_low;
14769       best_high = current_high;
14770     }
14771   else
14772     {
14773       struct die_info *child = die->child;
14774
14775       while (child && child->tag)
14776         {
14777           switch (child->tag) {
14778           case DW_TAG_subprogram:
14779             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14780             break;
14781           case DW_TAG_namespace:
14782           case DW_TAG_module:
14783             /* FIXME: carlton/2004-01-16: Should we do this for
14784                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14785                that current GCC's always emit the DIEs corresponding
14786                to definitions of methods of classes as children of a
14787                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14788                the DIEs giving the declarations, which could be
14789                anywhere).  But I don't see any reason why the
14790                standards says that they have to be there.  */
14791             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14792
14793             if (current_low != ((CORE_ADDR) -1))
14794               {
14795                 best_low = std::min (best_low, current_low);
14796                 best_high = std::max (best_high, current_high);
14797               }
14798             break;
14799           default:
14800             /* Ignore.  */
14801             break;
14802           }
14803
14804           child = sibling_die (child);
14805         }
14806     }
14807
14808   *lowpc = best_low;
14809   *highpc = best_high;
14810 }
14811
14812 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14813    in DIE.  */
14814
14815 static void
14816 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14817                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14818 {
14819   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14820   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14821   struct attribute *attr;
14822   struct attribute *attr_high;
14823
14824   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14825   if (attr_high)
14826     {
14827       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14828       if (attr)
14829         {
14830           CORE_ADDR low = attr_value_as_address (attr);
14831           CORE_ADDR high = attr_value_as_address (attr_high);
14832
14833           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14834             high += low;
14835
14836           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14837           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14838           cu->get_builder ()->record_block_range (block, low, high - 1);
14839         }
14840     }
14841
14842   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14843   if (attr)
14844     {
14845       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14846          We take advantage of the fact that DW_AT_ranges does not appear
14847          in DW_TAG_compile_unit of DWO files.  */
14848       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14849
14850       /* The value of the DW_AT_ranges attribute is the offset of the
14851          address range list in the .debug_ranges section.  */
14852       unsigned long offset = (DW_UNSND (attr)
14853                               + (need_ranges_base ? cu->ranges_base : 0));
14854
14855       std::vector<blockrange> blockvec;
14856       dwarf2_ranges_process (offset, cu,
14857         [&] (CORE_ADDR start, CORE_ADDR end)
14858         {
14859           start += baseaddr;
14860           end += baseaddr;
14861           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14862           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14863           cu->get_builder ()->record_block_range (block, start, end - 1);
14864           blockvec.emplace_back (start, end);
14865         });
14866
14867       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14868     }
14869 }
14870
14871 /* Check whether the producer field indicates either of GCC < 4.6, or the
14872    Intel C/C++ compiler, and cache the result in CU.  */
14873
14874 static void
14875 check_producer (struct dwarf2_cu *cu)
14876 {
14877   int major, minor;
14878
14879   if (cu->producer == NULL)
14880     {
14881       /* For unknown compilers expect their behavior is DWARF version
14882          compliant.
14883
14884          GCC started to support .debug_types sections by -gdwarf-4 since
14885          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14886          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14887          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14888          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14889     }
14890   else if (producer_is_gcc (cu->producer, &major, &minor))
14891     {
14892       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14893       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14894     }
14895   else if (producer_is_icc (cu->producer, &major, &minor))
14896     {
14897       cu->producer_is_icc = true;
14898       cu->producer_is_icc_lt_14 = major < 14;
14899     }
14900   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14901     cu->producer_is_codewarrior = true;
14902   else
14903     {
14904       /* For other non-GCC compilers, expect their behavior is DWARF version
14905          compliant.  */
14906     }
14907
14908   cu->checked_producer = true;
14909 }
14910
14911 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14912    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14913    during 4.6.0 experimental.  */
14914
14915 static bool
14916 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14917 {
14918   if (!cu->checked_producer)
14919     check_producer (cu);
14920
14921   return cu->producer_is_gxx_lt_4_6;
14922 }
14923
14924
14925 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14926    with incorrect is_stmt attributes.  */
14927
14928 static bool
14929 producer_is_codewarrior (struct dwarf2_cu *cu)
14930 {
14931   if (!cu->checked_producer)
14932     check_producer (cu);
14933
14934   return cu->producer_is_codewarrior;
14935 }
14936
14937 /* Return the default accessibility type if it is not overriden by
14938    DW_AT_accessibility.  */
14939
14940 static enum dwarf_access_attribute
14941 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14942 {
14943   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14944     {
14945       /* The default DWARF 2 accessibility for members is public, the default
14946          accessibility for inheritance is private.  */
14947
14948       if (die->tag != DW_TAG_inheritance)
14949         return DW_ACCESS_public;
14950       else
14951         return DW_ACCESS_private;
14952     }
14953   else
14954     {
14955       /* DWARF 3+ defines the default accessibility a different way.  The same
14956          rules apply now for DW_TAG_inheritance as for the members and it only
14957          depends on the container kind.  */
14958
14959       if (die->parent->tag == DW_TAG_class_type)
14960         return DW_ACCESS_private;
14961       else
14962         return DW_ACCESS_public;
14963     }
14964 }
14965
14966 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14967    offset.  If the attribute was not found return 0, otherwise return
14968    1.  If it was found but could not properly be handled, set *OFFSET
14969    to 0.  */
14970
14971 static int
14972 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14973                              LONGEST *offset)
14974 {
14975   struct attribute *attr;
14976
14977   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14978   if (attr != NULL)
14979     {
14980       *offset = 0;
14981
14982       /* Note that we do not check for a section offset first here.
14983          This is because DW_AT_data_member_location is new in DWARF 4,
14984          so if we see it, we can assume that a constant form is really
14985          a constant and not a section offset.  */
14986       if (attr_form_is_constant (attr))
14987         *offset = dwarf2_get_attr_constant_value (attr, 0);
14988       else if (attr_form_is_section_offset (attr))
14989         dwarf2_complex_location_expr_complaint ();
14990       else if (attr_form_is_block (attr))
14991         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14992       else
14993         dwarf2_complex_location_expr_complaint ();
14994
14995       return 1;
14996     }
14997
14998   return 0;
14999 }
15000
15001 /* Add an aggregate field to the field list.  */
15002
15003 static void
15004 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15005                   struct dwarf2_cu *cu)
15006 {
15007   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15008   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15009   struct nextfield *new_field;
15010   struct attribute *attr;
15011   struct field *fp;
15012   const char *fieldname = "";
15013
15014   if (die->tag == DW_TAG_inheritance)
15015     {
15016       fip->baseclasses.emplace_back ();
15017       new_field = &fip->baseclasses.back ();
15018     }
15019   else
15020     {
15021       fip->fields.emplace_back ();
15022       new_field = &fip->fields.back ();
15023     }
15024
15025   fip->nfields++;
15026
15027   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15028   if (attr)
15029     new_field->accessibility = DW_UNSND (attr);
15030   else
15031     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15032   if (new_field->accessibility != DW_ACCESS_public)
15033     fip->non_public_fields = 1;
15034
15035   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15036   if (attr)
15037     new_field->virtuality = DW_UNSND (attr);
15038   else
15039     new_field->virtuality = DW_VIRTUALITY_none;
15040
15041   fp = &new_field->field;
15042
15043   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15044     {
15045       LONGEST offset;
15046
15047       /* Data member other than a C++ static data member.  */
15048
15049       /* Get type of field.  */
15050       fp->type = die_type (die, cu);
15051
15052       SET_FIELD_BITPOS (*fp, 0);
15053
15054       /* Get bit size of field (zero if none).  */
15055       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15056       if (attr)
15057         {
15058           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15059         }
15060       else
15061         {
15062           FIELD_BITSIZE (*fp) = 0;
15063         }
15064
15065       /* Get bit offset of field.  */
15066       if (handle_data_member_location (die, cu, &offset))
15067         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15068       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15069       if (attr)
15070         {
15071           if (gdbarch_bits_big_endian (gdbarch))
15072             {
15073               /* For big endian bits, the DW_AT_bit_offset gives the
15074                  additional bit offset from the MSB of the containing
15075                  anonymous object to the MSB of the field.  We don't
15076                  have to do anything special since we don't need to
15077                  know the size of the anonymous object.  */
15078               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15079             }
15080           else
15081             {
15082               /* For little endian bits, compute the bit offset to the
15083                  MSB of the anonymous object, subtract off the number of
15084                  bits from the MSB of the field to the MSB of the
15085                  object, and then subtract off the number of bits of
15086                  the field itself.  The result is the bit offset of
15087                  the LSB of the field.  */
15088               int anonymous_size;
15089               int bit_offset = DW_UNSND (attr);
15090
15091               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15092               if (attr)
15093                 {
15094                   /* The size of the anonymous object containing
15095                      the bit field is explicit, so use the
15096                      indicated size (in bytes).  */
15097                   anonymous_size = DW_UNSND (attr);
15098                 }
15099               else
15100                 {
15101                   /* The size of the anonymous object containing
15102                      the bit field must be inferred from the type
15103                      attribute of the data member containing the
15104                      bit field.  */
15105                   anonymous_size = TYPE_LENGTH (fp->type);
15106                 }
15107               SET_FIELD_BITPOS (*fp,
15108                                 (FIELD_BITPOS (*fp)
15109                                  + anonymous_size * bits_per_byte
15110                                  - bit_offset - FIELD_BITSIZE (*fp)));
15111             }
15112         }
15113       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15114       if (attr != NULL)
15115         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15116                                 + dwarf2_get_attr_constant_value (attr, 0)));
15117
15118       /* Get name of field.  */
15119       fieldname = dwarf2_name (die, cu);
15120       if (fieldname == NULL)
15121         fieldname = "";
15122
15123       /* The name is already allocated along with this objfile, so we don't
15124          need to duplicate it for the type.  */
15125       fp->name = fieldname;
15126
15127       /* Change accessibility for artificial fields (e.g. virtual table
15128          pointer or virtual base class pointer) to private.  */
15129       if (dwarf2_attr (die, DW_AT_artificial, cu))
15130         {
15131           FIELD_ARTIFICIAL (*fp) = 1;
15132           new_field->accessibility = DW_ACCESS_private;
15133           fip->non_public_fields = 1;
15134         }
15135     }
15136   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15137     {
15138       /* C++ static member.  */
15139
15140       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15141          is a declaration, but all versions of G++ as of this writing
15142          (so through at least 3.2.1) incorrectly generate
15143          DW_TAG_variable tags.  */
15144
15145       const char *physname;
15146
15147       /* Get name of field.  */
15148       fieldname = dwarf2_name (die, cu);
15149       if (fieldname == NULL)
15150         return;
15151
15152       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15153       if (attr
15154           /* Only create a symbol if this is an external value.
15155              new_symbol checks this and puts the value in the global symbol
15156              table, which we want.  If it is not external, new_symbol
15157              will try to put the value in cu->list_in_scope which is wrong.  */
15158           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15159         {
15160           /* A static const member, not much different than an enum as far as
15161              we're concerned, except that we can support more types.  */
15162           new_symbol (die, NULL, cu);
15163         }
15164
15165       /* Get physical name.  */
15166       physname = dwarf2_physname (fieldname, die, cu);
15167
15168       /* The name is already allocated along with this objfile, so we don't
15169          need to duplicate it for the type.  */
15170       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15171       FIELD_TYPE (*fp) = die_type (die, cu);
15172       FIELD_NAME (*fp) = fieldname;
15173     }
15174   else if (die->tag == DW_TAG_inheritance)
15175     {
15176       LONGEST offset;
15177
15178       /* C++ base class field.  */
15179       if (handle_data_member_location (die, cu, &offset))
15180         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15181       FIELD_BITSIZE (*fp) = 0;
15182       FIELD_TYPE (*fp) = die_type (die, cu);
15183       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15184     }
15185   else if (die->tag == DW_TAG_variant_part)
15186     {
15187       /* process_structure_scope will treat this DIE as a union.  */
15188       process_structure_scope (die, cu);
15189
15190       /* The variant part is relative to the start of the enclosing
15191          structure.  */
15192       SET_FIELD_BITPOS (*fp, 0);
15193       fp->type = get_die_type (die, cu);
15194       fp->artificial = 1;
15195       fp->name = "<<variant>>";
15196
15197       /* Normally a DW_TAG_variant_part won't have a size, but our
15198          representation requires one, so set it to the maximum of the
15199          child sizes.  */
15200       if (TYPE_LENGTH (fp->type) == 0)
15201         {
15202           unsigned max = 0;
15203           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
15204             if (TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)) > max)
15205               max = TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i));
15206           TYPE_LENGTH (fp->type) = max;
15207         }
15208     }
15209   else
15210     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15211 }
15212
15213 /* Can the type given by DIE define another type?  */
15214
15215 static bool
15216 type_can_define_types (const struct die_info *die)
15217 {
15218   switch (die->tag)
15219     {
15220     case DW_TAG_typedef:
15221     case DW_TAG_class_type:
15222     case DW_TAG_structure_type:
15223     case DW_TAG_union_type:
15224     case DW_TAG_enumeration_type:
15225       return true;
15226
15227     default:
15228       return false;
15229     }
15230 }
15231
15232 /* Add a type definition defined in the scope of the FIP's class.  */
15233
15234 static void
15235 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15236                       struct dwarf2_cu *cu)
15237 {
15238   struct decl_field fp;
15239   memset (&fp, 0, sizeof (fp));
15240
15241   gdb_assert (type_can_define_types (die));
15242
15243   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15244   fp.name = dwarf2_name (die, cu);
15245   fp.type = read_type_die (die, cu);
15246
15247   /* Save accessibility.  */
15248   enum dwarf_access_attribute accessibility;
15249   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15250   if (attr != NULL)
15251     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15252   else
15253     accessibility = dwarf2_default_access_attribute (die, cu);
15254   switch (accessibility)
15255     {
15256     case DW_ACCESS_public:
15257       /* The assumed value if neither private nor protected.  */
15258       break;
15259     case DW_ACCESS_private:
15260       fp.is_private = 1;
15261       break;
15262     case DW_ACCESS_protected:
15263       fp.is_protected = 1;
15264       break;
15265     default:
15266       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15267     }
15268
15269   if (die->tag == DW_TAG_typedef)
15270     fip->typedef_field_list.push_back (fp);
15271   else
15272     fip->nested_types_list.push_back (fp);
15273 }
15274
15275 /* Create the vector of fields, and attach it to the type.  */
15276
15277 static void
15278 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15279                               struct dwarf2_cu *cu)
15280 {
15281   int nfields = fip->nfields;
15282
15283   /* Record the field count, allocate space for the array of fields,
15284      and create blank accessibility bitfields if necessary.  */
15285   TYPE_NFIELDS (type) = nfields;
15286   TYPE_FIELDS (type) = (struct field *)
15287     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15288
15289   if (fip->non_public_fields && cu->language != language_ada)
15290     {
15291       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15292
15293       TYPE_FIELD_PRIVATE_BITS (type) =
15294         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15295       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15296
15297       TYPE_FIELD_PROTECTED_BITS (type) =
15298         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15299       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15300
15301       TYPE_FIELD_IGNORE_BITS (type) =
15302         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15303       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15304     }
15305
15306   /* If the type has baseclasses, allocate and clear a bit vector for
15307      TYPE_FIELD_VIRTUAL_BITS.  */
15308   if (!fip->baseclasses.empty () && cu->language != language_ada)
15309     {
15310       int num_bytes = B_BYTES (fip->baseclasses.size ());
15311       unsigned char *pointer;
15312
15313       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15314       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15315       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15316       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15317       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15318     }
15319
15320   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15321     {
15322       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15323
15324       for (int index = 0; index < nfields; ++index)
15325         {
15326           struct nextfield &field = fip->fields[index];
15327
15328           if (field.variant.is_discriminant)
15329             di->discriminant_index = index;
15330           else if (field.variant.default_branch)
15331             di->default_index = index;
15332           else
15333             di->discriminants[index] = field.variant.discriminant_value;
15334         }
15335     }
15336
15337   /* Copy the saved-up fields into the field vector.  */
15338   for (int i = 0; i < nfields; ++i)
15339     {
15340       struct nextfield &field
15341         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15342            : fip->fields[i - fip->baseclasses.size ()]);
15343
15344       TYPE_FIELD (type, i) = field.field;
15345       switch (field.accessibility)
15346         {
15347         case DW_ACCESS_private:
15348           if (cu->language != language_ada)
15349             SET_TYPE_FIELD_PRIVATE (type, i);
15350           break;
15351
15352         case DW_ACCESS_protected:
15353           if (cu->language != language_ada)
15354             SET_TYPE_FIELD_PROTECTED (type, i);
15355           break;
15356
15357         case DW_ACCESS_public:
15358           break;
15359
15360         default:
15361           /* Unknown accessibility.  Complain and treat it as public.  */
15362           {
15363             complaint (_("unsupported accessibility %d"),
15364                        field.accessibility);
15365           }
15366           break;
15367         }
15368       if (i < fip->baseclasses.size ())
15369         {
15370           switch (field.virtuality)
15371             {
15372             case DW_VIRTUALITY_virtual:
15373             case DW_VIRTUALITY_pure_virtual:
15374               if (cu->language == language_ada)
15375                 error (_("unexpected virtuality in component of Ada type"));
15376               SET_TYPE_FIELD_VIRTUAL (type, i);
15377               break;
15378             }
15379         }
15380     }
15381 }
15382
15383 /* Return true if this member function is a constructor, false
15384    otherwise.  */
15385
15386 static int
15387 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15388 {
15389   const char *fieldname;
15390   const char *type_name;
15391   int len;
15392
15393   if (die->parent == NULL)
15394     return 0;
15395
15396   if (die->parent->tag != DW_TAG_structure_type
15397       && die->parent->tag != DW_TAG_union_type
15398       && die->parent->tag != DW_TAG_class_type)
15399     return 0;
15400
15401   fieldname = dwarf2_name (die, cu);
15402   type_name = dwarf2_name (die->parent, cu);
15403   if (fieldname == NULL || type_name == NULL)
15404     return 0;
15405
15406   len = strlen (fieldname);
15407   return (strncmp (fieldname, type_name, len) == 0
15408           && (type_name[len] == '\0' || type_name[len] == '<'));
15409 }
15410
15411 /* Add a member function to the proper fieldlist.  */
15412
15413 static void
15414 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15415                       struct type *type, struct dwarf2_cu *cu)
15416 {
15417   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15418   struct attribute *attr;
15419   int i;
15420   struct fnfieldlist *flp = nullptr;
15421   struct fn_field *fnp;
15422   const char *fieldname;
15423   struct type *this_type;
15424   enum dwarf_access_attribute accessibility;
15425
15426   if (cu->language == language_ada)
15427     error (_("unexpected member function in Ada type"));
15428
15429   /* Get name of member function.  */
15430   fieldname = dwarf2_name (die, cu);
15431   if (fieldname == NULL)
15432     return;
15433
15434   /* Look up member function name in fieldlist.  */
15435   for (i = 0; i < fip->fnfieldlists.size (); i++)
15436     {
15437       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15438         {
15439           flp = &fip->fnfieldlists[i];
15440           break;
15441         }
15442     }
15443
15444   /* Create a new fnfieldlist if necessary.  */
15445   if (flp == nullptr)
15446     {
15447       fip->fnfieldlists.emplace_back ();
15448       flp = &fip->fnfieldlists.back ();
15449       flp->name = fieldname;
15450       i = fip->fnfieldlists.size () - 1;
15451     }
15452
15453   /* Create a new member function field and add it to the vector of
15454      fnfieldlists.  */
15455   flp->fnfields.emplace_back ();
15456   fnp = &flp->fnfields.back ();
15457
15458   /* Delay processing of the physname until later.  */
15459   if (cu->language == language_cplus)
15460     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15461                         die, cu);
15462   else
15463     {
15464       const char *physname = dwarf2_physname (fieldname, die, cu);
15465       fnp->physname = physname ? physname : "";
15466     }
15467
15468   fnp->type = alloc_type (objfile);
15469   this_type = read_type_die (die, cu);
15470   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15471     {
15472       int nparams = TYPE_NFIELDS (this_type);
15473
15474       /* TYPE is the domain of this method, and THIS_TYPE is the type
15475            of the method itself (TYPE_CODE_METHOD).  */
15476       smash_to_method_type (fnp->type, type,
15477                             TYPE_TARGET_TYPE (this_type),
15478                             TYPE_FIELDS (this_type),
15479                             TYPE_NFIELDS (this_type),
15480                             TYPE_VARARGS (this_type));
15481
15482       /* Handle static member functions.
15483          Dwarf2 has no clean way to discern C++ static and non-static
15484          member functions.  G++ helps GDB by marking the first
15485          parameter for non-static member functions (which is the this
15486          pointer) as artificial.  We obtain this information from
15487          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15488       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15489         fnp->voffset = VOFFSET_STATIC;
15490     }
15491   else
15492     complaint (_("member function type missing for '%s'"),
15493                dwarf2_full_name (fieldname, die, cu));
15494
15495   /* Get fcontext from DW_AT_containing_type if present.  */
15496   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15497     fnp->fcontext = die_containing_type (die, cu);
15498
15499   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15500      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15501
15502   /* Get accessibility.  */
15503   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15504   if (attr)
15505     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15506   else
15507     accessibility = dwarf2_default_access_attribute (die, cu);
15508   switch (accessibility)
15509     {
15510     case DW_ACCESS_private:
15511       fnp->is_private = 1;
15512       break;
15513     case DW_ACCESS_protected:
15514       fnp->is_protected = 1;
15515       break;
15516     }
15517
15518   /* Check for artificial methods.  */
15519   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15520   if (attr && DW_UNSND (attr) != 0)
15521     fnp->is_artificial = 1;
15522
15523   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15524
15525   /* Get index in virtual function table if it is a virtual member
15526      function.  For older versions of GCC, this is an offset in the
15527      appropriate virtual table, as specified by DW_AT_containing_type.
15528      For everyone else, it is an expression to be evaluated relative
15529      to the object address.  */
15530
15531   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15532   if (attr)
15533     {
15534       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15535         {
15536           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15537             {
15538               /* Old-style GCC.  */
15539               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15540             }
15541           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15542                    || (DW_BLOCK (attr)->size > 1
15543                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15544                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15545             {
15546               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15547               if ((fnp->voffset % cu->header.addr_size) != 0)
15548                 dwarf2_complex_location_expr_complaint ();
15549               else
15550                 fnp->voffset /= cu->header.addr_size;
15551               fnp->voffset += 2;
15552             }
15553           else
15554             dwarf2_complex_location_expr_complaint ();
15555
15556           if (!fnp->fcontext)
15557             {
15558               /* If there is no `this' field and no DW_AT_containing_type,
15559                  we cannot actually find a base class context for the
15560                  vtable!  */
15561               if (TYPE_NFIELDS (this_type) == 0
15562                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15563                 {
15564                   complaint (_("cannot determine context for virtual member "
15565                                "function \"%s\" (offset %s)"),
15566                              fieldname, sect_offset_str (die->sect_off));
15567                 }
15568               else
15569                 {
15570                   fnp->fcontext
15571                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15572                 }
15573             }
15574         }
15575       else if (attr_form_is_section_offset (attr))
15576         {
15577           dwarf2_complex_location_expr_complaint ();
15578         }
15579       else
15580         {
15581           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15582                                                  fieldname);
15583         }
15584     }
15585   else
15586     {
15587       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15588       if (attr && DW_UNSND (attr))
15589         {
15590           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15591           complaint (_("Member function \"%s\" (offset %s) is virtual "
15592                        "but the vtable offset is not specified"),
15593                      fieldname, sect_offset_str (die->sect_off));
15594           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15595           TYPE_CPLUS_DYNAMIC (type) = 1;
15596         }
15597     }
15598 }
15599
15600 /* Create the vector of member function fields, and attach it to the type.  */
15601
15602 static void
15603 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15604                                  struct dwarf2_cu *cu)
15605 {
15606   if (cu->language == language_ada)
15607     error (_("unexpected member functions in Ada type"));
15608
15609   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15610   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15611     TYPE_ALLOC (type,
15612                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15613
15614   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15615     {
15616       struct fnfieldlist &nf = fip->fnfieldlists[i];
15617       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15618
15619       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15620       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15621       fn_flp->fn_fields = (struct fn_field *)
15622         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15623
15624       for (int k = 0; k < nf.fnfields.size (); ++k)
15625         fn_flp->fn_fields[k] = nf.fnfields[k];
15626     }
15627
15628   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15629 }
15630
15631 /* Returns non-zero if NAME is the name of a vtable member in CU's
15632    language, zero otherwise.  */
15633 static int
15634 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15635 {
15636   static const char vptr[] = "_vptr";
15637
15638   /* Look for the C++ form of the vtable.  */
15639   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15640     return 1;
15641
15642   return 0;
15643 }
15644
15645 /* GCC outputs unnamed structures that are really pointers to member
15646    functions, with the ABI-specified layout.  If TYPE describes
15647    such a structure, smash it into a member function type.
15648
15649    GCC shouldn't do this; it should just output pointer to member DIEs.
15650    This is GCC PR debug/28767.  */
15651
15652 static void
15653 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15654 {
15655   struct type *pfn_type, *self_type, *new_type;
15656
15657   /* Check for a structure with no name and two children.  */
15658   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15659     return;
15660
15661   /* Check for __pfn and __delta members.  */
15662   if (TYPE_FIELD_NAME (type, 0) == NULL
15663       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15664       || TYPE_FIELD_NAME (type, 1) == NULL
15665       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15666     return;
15667
15668   /* Find the type of the method.  */
15669   pfn_type = TYPE_FIELD_TYPE (type, 0);
15670   if (pfn_type == NULL
15671       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15672       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15673     return;
15674
15675   /* Look for the "this" argument.  */
15676   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15677   if (TYPE_NFIELDS (pfn_type) == 0
15678       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15679       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15680     return;
15681
15682   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15683   new_type = alloc_type (objfile);
15684   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15685                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15686                         TYPE_VARARGS (pfn_type));
15687   smash_to_methodptr_type (type, new_type);
15688 }
15689
15690 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15691    appropriate error checking and issuing complaints if there is a
15692    problem.  */
15693
15694 static ULONGEST
15695 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15696 {
15697   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15698
15699   if (attr == nullptr)
15700     return 0;
15701
15702   if (!attr_form_is_constant (attr))
15703     {
15704       complaint (_("DW_AT_alignment must have constant form"
15705                    " - DIE at %s [in module %s]"),
15706                  sect_offset_str (die->sect_off),
15707                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15708       return 0;
15709     }
15710
15711   ULONGEST align;
15712   if (attr->form == DW_FORM_sdata)
15713     {
15714       LONGEST val = DW_SND (attr);
15715       if (val < 0)
15716         {
15717           complaint (_("DW_AT_alignment value must not be negative"
15718                        " - DIE at %s [in module %s]"),
15719                      sect_offset_str (die->sect_off),
15720                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15721           return 0;
15722         }
15723       align = val;
15724     }
15725   else
15726     align = DW_UNSND (attr);
15727
15728   if (align == 0)
15729     {
15730       complaint (_("DW_AT_alignment value must not be zero"
15731                    " - DIE at %s [in module %s]"),
15732                  sect_offset_str (die->sect_off),
15733                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15734       return 0;
15735     }
15736   if ((align & (align - 1)) != 0)
15737     {
15738       complaint (_("DW_AT_alignment value must be a power of 2"
15739                    " - DIE at %s [in module %s]"),
15740                  sect_offset_str (die->sect_off),
15741                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15742       return 0;
15743     }
15744
15745   return align;
15746 }
15747
15748 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15749    the alignment for TYPE.  */
15750
15751 static void
15752 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15753                      struct type *type)
15754 {
15755   if (!set_type_align (type, get_alignment (cu, die)))
15756     complaint (_("DW_AT_alignment value too large"
15757                  " - DIE at %s [in module %s]"),
15758                sect_offset_str (die->sect_off),
15759                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15760 }
15761
15762 /* Called when we find the DIE that starts a structure or union scope
15763    (definition) to create a type for the structure or union.  Fill in
15764    the type's name and general properties; the members will not be
15765    processed until process_structure_scope.  A symbol table entry for
15766    the type will also not be done until process_structure_scope (assuming
15767    the type has a name).
15768
15769    NOTE: we need to call these functions regardless of whether or not the
15770    DIE has a DW_AT_name attribute, since it might be an anonymous
15771    structure or union.  This gets the type entered into our set of
15772    user defined types.  */
15773
15774 static struct type *
15775 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15776 {
15777   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15778   struct type *type;
15779   struct attribute *attr;
15780   const char *name;
15781
15782   /* If the definition of this type lives in .debug_types, read that type.
15783      Don't follow DW_AT_specification though, that will take us back up
15784      the chain and we want to go down.  */
15785   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15786   if (attr)
15787     {
15788       type = get_DW_AT_signature_type (die, attr, cu);
15789
15790       /* The type's CU may not be the same as CU.
15791          Ensure TYPE is recorded with CU in die_type_hash.  */
15792       return set_die_type (die, type, cu);
15793     }
15794
15795   type = alloc_type (objfile);
15796   INIT_CPLUS_SPECIFIC (type);
15797
15798   name = dwarf2_name (die, cu);
15799   if (name != NULL)
15800     {
15801       if (cu->language == language_cplus
15802           || cu->language == language_d
15803           || cu->language == language_rust)
15804         {
15805           const char *full_name = dwarf2_full_name (name, die, cu);
15806
15807           /* dwarf2_full_name might have already finished building the DIE's
15808              type.  If so, there is no need to continue.  */
15809           if (get_die_type (die, cu) != NULL)
15810             return get_die_type (die, cu);
15811
15812           TYPE_NAME (type) = full_name;
15813         }
15814       else
15815         {
15816           /* The name is already allocated along with this objfile, so
15817              we don't need to duplicate it for the type.  */
15818           TYPE_NAME (type) = name;
15819         }
15820     }
15821
15822   if (die->tag == DW_TAG_structure_type)
15823     {
15824       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15825     }
15826   else if (die->tag == DW_TAG_union_type)
15827     {
15828       TYPE_CODE (type) = TYPE_CODE_UNION;
15829     }
15830   else if (die->tag == DW_TAG_variant_part)
15831     {
15832       TYPE_CODE (type) = TYPE_CODE_UNION;
15833       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15834     }
15835   else
15836     {
15837       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15838     }
15839
15840   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15841     TYPE_DECLARED_CLASS (type) = 1;
15842
15843   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15844   if (attr)
15845     {
15846       if (attr_form_is_constant (attr))
15847         TYPE_LENGTH (type) = DW_UNSND (attr);
15848       else
15849         {
15850           /* For the moment, dynamic type sizes are not supported
15851              by GDB's struct type.  The actual size is determined
15852              on-demand when resolving the type of a given object,
15853              so set the type's length to zero for now.  Otherwise,
15854              we record an expression as the length, and that expression
15855              could lead to a very large value, which could eventually
15856              lead to us trying to allocate that much memory when creating
15857              a value of that type.  */
15858           TYPE_LENGTH (type) = 0;
15859         }
15860     }
15861   else
15862     {
15863       TYPE_LENGTH (type) = 0;
15864     }
15865
15866   maybe_set_alignment (cu, die, type);
15867
15868   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15869     {
15870       /* ICC<14 does not output the required DW_AT_declaration on
15871          incomplete types, but gives them a size of zero.  */
15872       TYPE_STUB (type) = 1;
15873     }
15874   else
15875     TYPE_STUB_SUPPORTED (type) = 1;
15876
15877   if (die_is_declaration (die, cu))
15878     TYPE_STUB (type) = 1;
15879   else if (attr == NULL && die->child == NULL
15880            && producer_is_realview (cu->producer))
15881     /* RealView does not output the required DW_AT_declaration
15882        on incomplete types.  */
15883     TYPE_STUB (type) = 1;
15884
15885   /* We need to add the type field to the die immediately so we don't
15886      infinitely recurse when dealing with pointers to the structure
15887      type within the structure itself.  */
15888   set_die_type (die, type, cu);
15889
15890   /* set_die_type should be already done.  */
15891   set_descriptive_type (type, die, cu);
15892
15893   return type;
15894 }
15895
15896 /* A helper for process_structure_scope that handles a single member
15897    DIE.  */
15898
15899 static void
15900 handle_struct_member_die (struct die_info *child_die, struct type *type,
15901                           struct field_info *fi,
15902                           std::vector<struct symbol *> *template_args,
15903                           struct dwarf2_cu *cu)
15904 {
15905   if (child_die->tag == DW_TAG_member
15906       || child_die->tag == DW_TAG_variable
15907       || child_die->tag == DW_TAG_variant_part)
15908     {
15909       /* NOTE: carlton/2002-11-05: A C++ static data member
15910          should be a DW_TAG_member that is a declaration, but
15911          all versions of G++ as of this writing (so through at
15912          least 3.2.1) incorrectly generate DW_TAG_variable
15913          tags for them instead.  */
15914       dwarf2_add_field (fi, child_die, cu);
15915     }
15916   else if (child_die->tag == DW_TAG_subprogram)
15917     {
15918       /* Rust doesn't have member functions in the C++ sense.
15919          However, it does emit ordinary functions as children
15920          of a struct DIE.  */
15921       if (cu->language == language_rust)
15922         read_func_scope (child_die, cu);
15923       else
15924         {
15925           /* C++ member function.  */
15926           dwarf2_add_member_fn (fi, child_die, type, cu);
15927         }
15928     }
15929   else if (child_die->tag == DW_TAG_inheritance)
15930     {
15931       /* C++ base class field.  */
15932       dwarf2_add_field (fi, child_die, cu);
15933     }
15934   else if (type_can_define_types (child_die))
15935     dwarf2_add_type_defn (fi, child_die, cu);
15936   else if (child_die->tag == DW_TAG_template_type_param
15937            || child_die->tag == DW_TAG_template_value_param)
15938     {
15939       struct symbol *arg = new_symbol (child_die, NULL, cu);
15940
15941       if (arg != NULL)
15942         template_args->push_back (arg);
15943     }
15944   else if (child_die->tag == DW_TAG_variant)
15945     {
15946       /* In a variant we want to get the discriminant and also add a
15947          field for our sole member child.  */
15948       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15949
15950       for (die_info *variant_child = child_die->child;
15951            variant_child != NULL;
15952            variant_child = sibling_die (variant_child))
15953         {
15954           if (variant_child->tag == DW_TAG_member)
15955             {
15956               handle_struct_member_die (variant_child, type, fi,
15957                                         template_args, cu);
15958               /* Only handle the one.  */
15959               break;
15960             }
15961         }
15962
15963       /* We don't handle this but we might as well report it if we see
15964          it.  */
15965       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15966           complaint (_("DW_AT_discr_list is not supported yet"
15967                        " - DIE at %s [in module %s]"),
15968                      sect_offset_str (child_die->sect_off),
15969                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15970
15971       /* The first field was just added, so we can stash the
15972          discriminant there.  */
15973       gdb_assert (!fi->fields.empty ());
15974       if (discr == NULL)
15975         fi->fields.back ().variant.default_branch = true;
15976       else
15977         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15978     }
15979 }
15980
15981 /* Finish creating a structure or union type, including filling in
15982    its members and creating a symbol for it.  */
15983
15984 static void
15985 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15986 {
15987   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15988   struct die_info *child_die;
15989   struct type *type;
15990
15991   type = get_die_type (die, cu);
15992   if (type == NULL)
15993     type = read_structure_type (die, cu);
15994
15995   /* When reading a DW_TAG_variant_part, we need to notice when we
15996      read the discriminant member, so we can record it later in the
15997      discriminant_info.  */
15998   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15999   sect_offset discr_offset;
16000   bool has_template_parameters = false;
16001
16002   if (is_variant_part)
16003     {
16004       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
16005       if (discr == NULL)
16006         {
16007           /* Maybe it's a univariant form, an extension we support.
16008              In this case arrange not to check the offset.  */
16009           is_variant_part = false;
16010         }
16011       else if (attr_form_is_ref (discr))
16012         {
16013           struct dwarf2_cu *target_cu = cu;
16014           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
16015
16016           discr_offset = target_die->sect_off;
16017         }
16018       else
16019         {
16020           complaint (_("DW_AT_discr does not have DIE reference form"
16021                        " - DIE at %s [in module %s]"),
16022                      sect_offset_str (die->sect_off),
16023                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16024           is_variant_part = false;
16025         }
16026     }
16027
16028   if (die->child != NULL && ! die_is_declaration (die, cu))
16029     {
16030       struct field_info fi;
16031       std::vector<struct symbol *> template_args;
16032
16033       child_die = die->child;
16034
16035       while (child_die && child_die->tag)
16036         {
16037           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
16038
16039           if (is_variant_part && discr_offset == child_die->sect_off)
16040             fi.fields.back ().variant.is_discriminant = true;
16041
16042           child_die = sibling_die (child_die);
16043         }
16044
16045       /* Attach template arguments to type.  */
16046       if (!template_args.empty ())
16047         {
16048           has_template_parameters = true;
16049           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16050           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16051           TYPE_TEMPLATE_ARGUMENTS (type)
16052             = XOBNEWVEC (&objfile->objfile_obstack,
16053                          struct symbol *,
16054                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16055           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16056                   template_args.data (),
16057                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16058                    * sizeof (struct symbol *)));
16059         }
16060
16061       /* Attach fields and member functions to the type.  */
16062       if (fi.nfields)
16063         dwarf2_attach_fields_to_type (&fi, type, cu);
16064       if (!fi.fnfieldlists.empty ())
16065         {
16066           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16067
16068           /* Get the type which refers to the base class (possibly this
16069              class itself) which contains the vtable pointer for the current
16070              class from the DW_AT_containing_type attribute.  This use of
16071              DW_AT_containing_type is a GNU extension.  */
16072
16073           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16074             {
16075               struct type *t = die_containing_type (die, cu);
16076
16077               set_type_vptr_basetype (type, t);
16078               if (type == t)
16079                 {
16080                   int i;
16081
16082                   /* Our own class provides vtbl ptr.  */
16083                   for (i = TYPE_NFIELDS (t) - 1;
16084                        i >= TYPE_N_BASECLASSES (t);
16085                        --i)
16086                     {
16087                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16088
16089                       if (is_vtable_name (fieldname, cu))
16090                         {
16091                           set_type_vptr_fieldno (type, i);
16092                           break;
16093                         }
16094                     }
16095
16096                   /* Complain if virtual function table field not found.  */
16097                   if (i < TYPE_N_BASECLASSES (t))
16098                     complaint (_("virtual function table pointer "
16099                                  "not found when defining class '%s'"),
16100                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
16101                 }
16102               else
16103                 {
16104                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16105                 }
16106             }
16107           else if (cu->producer
16108                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16109             {
16110               /* The IBM XLC compiler does not provide direct indication
16111                  of the containing type, but the vtable pointer is
16112                  always named __vfp.  */
16113
16114               int i;
16115
16116               for (i = TYPE_NFIELDS (type) - 1;
16117                    i >= TYPE_N_BASECLASSES (type);
16118                    --i)
16119                 {
16120                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16121                     {
16122                       set_type_vptr_fieldno (type, i);
16123                       set_type_vptr_basetype (type, type);
16124                       break;
16125                     }
16126                 }
16127             }
16128         }
16129
16130       /* Copy fi.typedef_field_list linked list elements content into the
16131          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16132       if (!fi.typedef_field_list.empty ())
16133         {
16134           int count = fi.typedef_field_list.size ();
16135
16136           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16137           TYPE_TYPEDEF_FIELD_ARRAY (type)
16138             = ((struct decl_field *)
16139                TYPE_ALLOC (type,
16140                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16141           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16142
16143           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16144             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16145         }
16146
16147       /* Copy fi.nested_types_list linked list elements content into the
16148          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16149       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16150         {
16151           int count = fi.nested_types_list.size ();
16152
16153           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16154           TYPE_NESTED_TYPES_ARRAY (type)
16155             = ((struct decl_field *)
16156                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16157           TYPE_NESTED_TYPES_COUNT (type) = count;
16158
16159           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16160             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16161         }
16162     }
16163
16164   quirk_gcc_member_function_pointer (type, objfile);
16165   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16166     cu->rust_unions.push_back (type);
16167
16168   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16169      snapshots) has been known to create a die giving a declaration
16170      for a class that has, as a child, a die giving a definition for a
16171      nested class.  So we have to process our children even if the
16172      current die is a declaration.  Normally, of course, a declaration
16173      won't have any children at all.  */
16174
16175   child_die = die->child;
16176
16177   while (child_die != NULL && child_die->tag)
16178     {
16179       if (child_die->tag == DW_TAG_member
16180           || child_die->tag == DW_TAG_variable
16181           || child_die->tag == DW_TAG_inheritance
16182           || child_die->tag == DW_TAG_template_value_param
16183           || child_die->tag == DW_TAG_template_type_param)
16184         {
16185           /* Do nothing.  */
16186         }
16187       else
16188         process_die (child_die, cu);
16189
16190       child_die = sibling_die (child_die);
16191     }
16192
16193   /* Do not consider external references.  According to the DWARF standard,
16194      these DIEs are identified by the fact that they have no byte_size
16195      attribute, and a declaration attribute.  */
16196   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16197       || !die_is_declaration (die, cu))
16198     {
16199       struct symbol *sym = new_symbol (die, type, cu);
16200
16201       if (has_template_parameters)
16202         {
16203           struct symtab *symtab;
16204           if (sym != nullptr)
16205             symtab = symbol_symtab (sym);
16206           else if (cu->line_header != nullptr)
16207             {
16208               /* Any related symtab will do.  */
16209               symtab
16210                 = cu->line_header->file_name_at (file_name_index (1))->symtab;
16211             }
16212           else
16213             {
16214               symtab = nullptr;
16215               complaint (_("could not find suitable "
16216                            "symtab for template parameter"
16217                            " - DIE at %s [in module %s]"),
16218                          sect_offset_str (die->sect_off),
16219                          objfile_name (objfile));
16220             }
16221
16222           if (symtab != nullptr)
16223             {
16224               /* Make sure that the symtab is set on the new symbols.
16225                  Even though they don't appear in this symtab directly,
16226                  other parts of gdb assume that symbols do, and this is
16227                  reasonably true.  */
16228               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16229                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
16230             }
16231         }
16232     }
16233 }
16234
16235 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16236    update TYPE using some information only available in DIE's children.  */
16237
16238 static void
16239 update_enumeration_type_from_children (struct die_info *die,
16240                                        struct type *type,
16241                                        struct dwarf2_cu *cu)
16242 {
16243   struct die_info *child_die;
16244   int unsigned_enum = 1;
16245   int flag_enum = 1;
16246   ULONGEST mask = 0;
16247
16248   auto_obstack obstack;
16249
16250   for (child_die = die->child;
16251        child_die != NULL && child_die->tag;
16252        child_die = sibling_die (child_die))
16253     {
16254       struct attribute *attr;
16255       LONGEST value;
16256       const gdb_byte *bytes;
16257       struct dwarf2_locexpr_baton *baton;
16258       const char *name;
16259
16260       if (child_die->tag != DW_TAG_enumerator)
16261         continue;
16262
16263       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16264       if (attr == NULL)
16265         continue;
16266
16267       name = dwarf2_name (child_die, cu);
16268       if (name == NULL)
16269         name = "<anonymous enumerator>";
16270
16271       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16272                                &value, &bytes, &baton);
16273       if (value < 0)
16274         {
16275           unsigned_enum = 0;
16276           flag_enum = 0;
16277         }
16278       else if ((mask & value) != 0)
16279         flag_enum = 0;
16280       else
16281         mask |= value;
16282
16283       /* If we already know that the enum type is neither unsigned, nor
16284          a flag type, no need to look at the rest of the enumerates.  */
16285       if (!unsigned_enum && !flag_enum)
16286         break;
16287     }
16288
16289   if (unsigned_enum)
16290     TYPE_UNSIGNED (type) = 1;
16291   if (flag_enum)
16292     TYPE_FLAG_ENUM (type) = 1;
16293 }
16294
16295 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16296    complete the type's fields yet, or create any symbols.  */
16297
16298 static struct type *
16299 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16300 {
16301   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16302   struct type *type;
16303   struct attribute *attr;
16304   const char *name;
16305
16306   /* If the definition of this type lives in .debug_types, read that type.
16307      Don't follow DW_AT_specification though, that will take us back up
16308      the chain and we want to go down.  */
16309   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16310   if (attr)
16311     {
16312       type = get_DW_AT_signature_type (die, attr, cu);
16313
16314       /* The type's CU may not be the same as CU.
16315          Ensure TYPE is recorded with CU in die_type_hash.  */
16316       return set_die_type (die, type, cu);
16317     }
16318
16319   type = alloc_type (objfile);
16320
16321   TYPE_CODE (type) = TYPE_CODE_ENUM;
16322   name = dwarf2_full_name (NULL, die, cu);
16323   if (name != NULL)
16324     TYPE_NAME (type) = name;
16325
16326   attr = dwarf2_attr (die, DW_AT_type, cu);
16327   if (attr != NULL)
16328     {
16329       struct type *underlying_type = die_type (die, cu);
16330
16331       TYPE_TARGET_TYPE (type) = underlying_type;
16332     }
16333
16334   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16335   if (attr)
16336     {
16337       TYPE_LENGTH (type) = DW_UNSND (attr);
16338     }
16339   else
16340     {
16341       TYPE_LENGTH (type) = 0;
16342     }
16343
16344   maybe_set_alignment (cu, die, type);
16345
16346   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16347      declared as private in the package spec, and then defined only
16348      inside the package body.  Such types are known as Taft Amendment
16349      Types.  When another package uses such a type, an incomplete DIE
16350      may be generated by the compiler.  */
16351   if (die_is_declaration (die, cu))
16352     TYPE_STUB (type) = 1;
16353
16354   /* Finish the creation of this type by using the enum's children.
16355      We must call this even when the underlying type has been provided
16356      so that we can determine if we're looking at a "flag" enum.  */
16357   update_enumeration_type_from_children (die, type, cu);
16358
16359   /* If this type has an underlying type that is not a stub, then we
16360      may use its attributes.  We always use the "unsigned" attribute
16361      in this situation, because ordinarily we guess whether the type
16362      is unsigned -- but the guess can be wrong and the underlying type
16363      can tell us the reality.  However, we defer to a local size
16364      attribute if one exists, because this lets the compiler override
16365      the underlying type if needed.  */
16366   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16367     {
16368       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16369       if (TYPE_LENGTH (type) == 0)
16370         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16371       if (TYPE_RAW_ALIGN (type) == 0
16372           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16373         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16374     }
16375
16376   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16377
16378   return set_die_type (die, type, cu);
16379 }
16380
16381 /* Given a pointer to a die which begins an enumeration, process all
16382    the dies that define the members of the enumeration, and create the
16383    symbol for the enumeration type.
16384
16385    NOTE: We reverse the order of the element list.  */
16386
16387 static void
16388 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16389 {
16390   struct type *this_type;
16391
16392   this_type = get_die_type (die, cu);
16393   if (this_type == NULL)
16394     this_type = read_enumeration_type (die, cu);
16395
16396   if (die->child != NULL)
16397     {
16398       struct die_info *child_die;
16399       struct symbol *sym;
16400       struct field *fields = NULL;
16401       int num_fields = 0;
16402       const char *name;
16403
16404       child_die = die->child;
16405       while (child_die && child_die->tag)
16406         {
16407           if (child_die->tag != DW_TAG_enumerator)
16408             {
16409               process_die (child_die, cu);
16410             }
16411           else
16412             {
16413               name = dwarf2_name (child_die, cu);
16414               if (name)
16415                 {
16416                   sym = new_symbol (child_die, this_type, cu);
16417
16418                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16419                     {
16420                       fields = (struct field *)
16421                         xrealloc (fields,
16422                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16423                                   * sizeof (struct field));
16424                     }
16425
16426                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16427                   FIELD_TYPE (fields[num_fields]) = NULL;
16428                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16429                   FIELD_BITSIZE (fields[num_fields]) = 0;
16430
16431                   num_fields++;
16432                 }
16433             }
16434
16435           child_die = sibling_die (child_die);
16436         }
16437
16438       if (num_fields)
16439         {
16440           TYPE_NFIELDS (this_type) = num_fields;
16441           TYPE_FIELDS (this_type) = (struct field *)
16442             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16443           memcpy (TYPE_FIELDS (this_type), fields,
16444                   sizeof (struct field) * num_fields);
16445           xfree (fields);
16446         }
16447     }
16448
16449   /* If we are reading an enum from a .debug_types unit, and the enum
16450      is a declaration, and the enum is not the signatured type in the
16451      unit, then we do not want to add a symbol for it.  Adding a
16452      symbol would in some cases obscure the true definition of the
16453      enum, giving users an incomplete type when the definition is
16454      actually available.  Note that we do not want to do this for all
16455      enums which are just declarations, because C++0x allows forward
16456      enum declarations.  */
16457   if (cu->per_cu->is_debug_types
16458       && die_is_declaration (die, cu))
16459     {
16460       struct signatured_type *sig_type;
16461
16462       sig_type = (struct signatured_type *) cu->per_cu;
16463       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16464       if (sig_type->type_offset_in_section != die->sect_off)
16465         return;
16466     }
16467
16468   new_symbol (die, this_type, cu);
16469 }
16470
16471 /* Extract all information from a DW_TAG_array_type DIE and put it in
16472    the DIE's type field.  For now, this only handles one dimensional
16473    arrays.  */
16474
16475 static struct type *
16476 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16477 {
16478   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16479   struct die_info *child_die;
16480   struct type *type;
16481   struct type *element_type, *range_type, *index_type;
16482   struct attribute *attr;
16483   const char *name;
16484   struct dynamic_prop *byte_stride_prop = NULL;
16485   unsigned int bit_stride = 0;
16486
16487   element_type = die_type (die, cu);
16488
16489   /* The die_type call above may have already set the type for this DIE.  */
16490   type = get_die_type (die, cu);
16491   if (type)
16492     return type;
16493
16494   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16495   if (attr != NULL)
16496     {
16497       int stride_ok;
16498
16499       byte_stride_prop
16500         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16501       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16502       if (!stride_ok)
16503         {
16504           complaint (_("unable to read array DW_AT_byte_stride "
16505                        " - DIE at %s [in module %s]"),
16506                      sect_offset_str (die->sect_off),
16507                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16508           /* Ignore this attribute.  We will likely not be able to print
16509              arrays of this type correctly, but there is little we can do
16510              to help if we cannot read the attribute's value.  */
16511           byte_stride_prop = NULL;
16512         }
16513     }
16514
16515   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16516   if (attr != NULL)
16517     bit_stride = DW_UNSND (attr);
16518
16519   /* Irix 6.2 native cc creates array types without children for
16520      arrays with unspecified length.  */
16521   if (die->child == NULL)
16522     {
16523       index_type = objfile_type (objfile)->builtin_int;
16524       range_type = create_static_range_type (NULL, index_type, 0, -1);
16525       type = create_array_type_with_stride (NULL, element_type, range_type,
16526                                             byte_stride_prop, bit_stride);
16527       return set_die_type (die, type, cu);
16528     }
16529
16530   std::vector<struct type *> range_types;
16531   child_die = die->child;
16532   while (child_die && child_die->tag)
16533     {
16534       if (child_die->tag == DW_TAG_subrange_type)
16535         {
16536           struct type *child_type = read_type_die (child_die, cu);
16537
16538           if (child_type != NULL)
16539             {
16540               /* The range type was succesfully read.  Save it for the
16541                  array type creation.  */
16542               range_types.push_back (child_type);
16543             }
16544         }
16545       child_die = sibling_die (child_die);
16546     }
16547
16548   /* Dwarf2 dimensions are output from left to right, create the
16549      necessary array types in backwards order.  */
16550
16551   type = element_type;
16552
16553   if (read_array_order (die, cu) == DW_ORD_col_major)
16554     {
16555       int i = 0;
16556
16557       while (i < range_types.size ())
16558         type = create_array_type_with_stride (NULL, type, range_types[i++],
16559                                               byte_stride_prop, bit_stride);
16560     }
16561   else
16562     {
16563       size_t ndim = range_types.size ();
16564       while (ndim-- > 0)
16565         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16566                                               byte_stride_prop, bit_stride);
16567     }
16568
16569   /* Understand Dwarf2 support for vector types (like they occur on
16570      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16571      array type.  This is not part of the Dwarf2/3 standard yet, but a
16572      custom vendor extension.  The main difference between a regular
16573      array and the vector variant is that vectors are passed by value
16574      to functions.  */
16575   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16576   if (attr)
16577     make_vector_type (type);
16578
16579   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16580      implementation may choose to implement triple vectors using this
16581      attribute.  */
16582   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16583   if (attr)
16584     {
16585       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16586         TYPE_LENGTH (type) = DW_UNSND (attr);
16587       else
16588         complaint (_("DW_AT_byte_size for array type smaller "
16589                      "than the total size of elements"));
16590     }
16591
16592   name = dwarf2_name (die, cu);
16593   if (name)
16594     TYPE_NAME (type) = name;
16595
16596   maybe_set_alignment (cu, die, type);
16597
16598   /* Install the type in the die.  */
16599   set_die_type (die, type, cu);
16600
16601   /* set_die_type should be already done.  */
16602   set_descriptive_type (type, die, cu);
16603
16604   return type;
16605 }
16606
16607 static enum dwarf_array_dim_ordering
16608 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16609 {
16610   struct attribute *attr;
16611
16612   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16613
16614   if (attr)
16615     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16616
16617   /* GNU F77 is a special case, as at 08/2004 array type info is the
16618      opposite order to the dwarf2 specification, but data is still
16619      laid out as per normal fortran.
16620
16621      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16622      version checking.  */
16623
16624   if (cu->language == language_fortran
16625       && cu->producer && strstr (cu->producer, "GNU F77"))
16626     {
16627       return DW_ORD_row_major;
16628     }
16629
16630   switch (cu->language_defn->la_array_ordering)
16631     {
16632     case array_column_major:
16633       return DW_ORD_col_major;
16634     case array_row_major:
16635     default:
16636       return DW_ORD_row_major;
16637     };
16638 }
16639
16640 /* Extract all information from a DW_TAG_set_type DIE and put it in
16641    the DIE's type field.  */
16642
16643 static struct type *
16644 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16645 {
16646   struct type *domain_type, *set_type;
16647   struct attribute *attr;
16648
16649   domain_type = die_type (die, cu);
16650
16651   /* The die_type call above may have already set the type for this DIE.  */
16652   set_type = get_die_type (die, cu);
16653   if (set_type)
16654     return set_type;
16655
16656   set_type = create_set_type (NULL, domain_type);
16657
16658   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16659   if (attr)
16660     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16661
16662   maybe_set_alignment (cu, die, set_type);
16663
16664   return set_die_type (die, set_type, cu);
16665 }
16666
16667 /* A helper for read_common_block that creates a locexpr baton.
16668    SYM is the symbol which we are marking as computed.
16669    COMMON_DIE is the DIE for the common block.
16670    COMMON_LOC is the location expression attribute for the common
16671    block itself.
16672    MEMBER_LOC is the location expression attribute for the particular
16673    member of the common block that we are processing.
16674    CU is the CU from which the above come.  */
16675
16676 static void
16677 mark_common_block_symbol_computed (struct symbol *sym,
16678                                    struct die_info *common_die,
16679                                    struct attribute *common_loc,
16680                                    struct attribute *member_loc,
16681                                    struct dwarf2_cu *cu)
16682 {
16683   struct dwarf2_per_objfile *dwarf2_per_objfile
16684     = cu->per_cu->dwarf2_per_objfile;
16685   struct objfile *objfile = dwarf2_per_objfile->objfile;
16686   struct dwarf2_locexpr_baton *baton;
16687   gdb_byte *ptr;
16688   unsigned int cu_off;
16689   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16690   LONGEST offset = 0;
16691
16692   gdb_assert (common_loc && member_loc);
16693   gdb_assert (attr_form_is_block (common_loc));
16694   gdb_assert (attr_form_is_block (member_loc)
16695               || attr_form_is_constant (member_loc));
16696
16697   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16698   baton->per_cu = cu->per_cu;
16699   gdb_assert (baton->per_cu);
16700
16701   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16702
16703   if (attr_form_is_constant (member_loc))
16704     {
16705       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16706       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16707     }
16708   else
16709     baton->size += DW_BLOCK (member_loc)->size;
16710
16711   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16712   baton->data = ptr;
16713
16714   *ptr++ = DW_OP_call4;
16715   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16716   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16717   ptr += 4;
16718
16719   if (attr_form_is_constant (member_loc))
16720     {
16721       *ptr++ = DW_OP_addr;
16722       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16723       ptr += cu->header.addr_size;
16724     }
16725   else
16726     {
16727       /* We have to copy the data here, because DW_OP_call4 will only
16728          use a DW_AT_location attribute.  */
16729       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16730       ptr += DW_BLOCK (member_loc)->size;
16731     }
16732
16733   *ptr++ = DW_OP_plus;
16734   gdb_assert (ptr - baton->data == baton->size);
16735
16736   SYMBOL_LOCATION_BATON (sym) = baton;
16737   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16738 }
16739
16740 /* Create appropriate locally-scoped variables for all the
16741    DW_TAG_common_block entries.  Also create a struct common_block
16742    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16743    is used to sepate the common blocks name namespace from regular
16744    variable names.  */
16745
16746 static void
16747 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16748 {
16749   struct attribute *attr;
16750
16751   attr = dwarf2_attr (die, DW_AT_location, cu);
16752   if (attr)
16753     {
16754       /* Support the .debug_loc offsets.  */
16755       if (attr_form_is_block (attr))
16756         {
16757           /* Ok.  */
16758         }
16759       else if (attr_form_is_section_offset (attr))
16760         {
16761           dwarf2_complex_location_expr_complaint ();
16762           attr = NULL;
16763         }
16764       else
16765         {
16766           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16767                                                  "common block member");
16768           attr = NULL;
16769         }
16770     }
16771
16772   if (die->child != NULL)
16773     {
16774       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16775       struct die_info *child_die;
16776       size_t n_entries = 0, size;
16777       struct common_block *common_block;
16778       struct symbol *sym;
16779
16780       for (child_die = die->child;
16781            child_die && child_die->tag;
16782            child_die = sibling_die (child_die))
16783         ++n_entries;
16784
16785       size = (sizeof (struct common_block)
16786               + (n_entries - 1) * sizeof (struct symbol *));
16787       common_block
16788         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16789                                                  size);
16790       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16791       common_block->n_entries = 0;
16792
16793       for (child_die = die->child;
16794            child_die && child_die->tag;
16795            child_die = sibling_die (child_die))
16796         {
16797           /* Create the symbol in the DW_TAG_common_block block in the current
16798              symbol scope.  */
16799           sym = new_symbol (child_die, NULL, cu);
16800           if (sym != NULL)
16801             {
16802               struct attribute *member_loc;
16803
16804               common_block->contents[common_block->n_entries++] = sym;
16805
16806               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16807                                         cu);
16808               if (member_loc)
16809                 {
16810                   /* GDB has handled this for a long time, but it is
16811                      not specified by DWARF.  It seems to have been
16812                      emitted by gfortran at least as recently as:
16813                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16814                   complaint (_("Variable in common block has "
16815                                "DW_AT_data_member_location "
16816                                "- DIE at %s [in module %s]"),
16817                                sect_offset_str (child_die->sect_off),
16818                              objfile_name (objfile));
16819
16820                   if (attr_form_is_section_offset (member_loc))
16821                     dwarf2_complex_location_expr_complaint ();
16822                   else if (attr_form_is_constant (member_loc)
16823                            || attr_form_is_block (member_loc))
16824                     {
16825                       if (attr)
16826                         mark_common_block_symbol_computed (sym, die, attr,
16827                                                            member_loc, cu);
16828                     }
16829                   else
16830                     dwarf2_complex_location_expr_complaint ();
16831                 }
16832             }
16833         }
16834
16835       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16836       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16837     }
16838 }
16839
16840 /* Create a type for a C++ namespace.  */
16841
16842 static struct type *
16843 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16844 {
16845   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16846   const char *previous_prefix, *name;
16847   int is_anonymous;
16848   struct type *type;
16849
16850   /* For extensions, reuse the type of the original namespace.  */
16851   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16852     {
16853       struct die_info *ext_die;
16854       struct dwarf2_cu *ext_cu = cu;
16855
16856       ext_die = dwarf2_extension (die, &ext_cu);
16857       type = read_type_die (ext_die, ext_cu);
16858
16859       /* EXT_CU may not be the same as CU.
16860          Ensure TYPE is recorded with CU in die_type_hash.  */
16861       return set_die_type (die, type, cu);
16862     }
16863
16864   name = namespace_name (die, &is_anonymous, cu);
16865
16866   /* Now build the name of the current namespace.  */
16867
16868   previous_prefix = determine_prefix (die, cu);
16869   if (previous_prefix[0] != '\0')
16870     name = typename_concat (&objfile->objfile_obstack,
16871                             previous_prefix, name, 0, cu);
16872
16873   /* Create the type.  */
16874   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16875
16876   return set_die_type (die, type, cu);
16877 }
16878
16879 /* Read a namespace scope.  */
16880
16881 static void
16882 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16883 {
16884   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16885   int is_anonymous;
16886
16887   /* Add a symbol associated to this if we haven't seen the namespace
16888      before.  Also, add a using directive if it's an anonymous
16889      namespace.  */
16890
16891   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16892     {
16893       struct type *type;
16894
16895       type = read_type_die (die, cu);
16896       new_symbol (die, type, cu);
16897
16898       namespace_name (die, &is_anonymous, cu);
16899       if (is_anonymous)
16900         {
16901           const char *previous_prefix = determine_prefix (die, cu);
16902
16903           std::vector<const char *> excludes;
16904           add_using_directive (using_directives (cu),
16905                                previous_prefix, TYPE_NAME (type), NULL,
16906                                NULL, excludes, 0, &objfile->objfile_obstack);
16907         }
16908     }
16909
16910   if (die->child != NULL)
16911     {
16912       struct die_info *child_die = die->child;
16913
16914       while (child_die && child_die->tag)
16915         {
16916           process_die (child_die, cu);
16917           child_die = sibling_die (child_die);
16918         }
16919     }
16920 }
16921
16922 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16923    imported module.  Still we need that type as local Fortran "use ... only"
16924    declaration imports depend on the created type in determine_prefix.  */
16925
16926 static struct type *
16927 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16928 {
16929   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16930   const char *module_name;
16931   struct type *type;
16932
16933   module_name = dwarf2_name (die, cu);
16934   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16935
16936   return set_die_type (die, type, cu);
16937 }
16938
16939 /* Read a Fortran module.  */
16940
16941 static void
16942 read_module (struct die_info *die, struct dwarf2_cu *cu)
16943 {
16944   struct die_info *child_die = die->child;
16945   struct type *type;
16946
16947   type = read_type_die (die, cu);
16948   new_symbol (die, type, cu);
16949
16950   while (child_die && child_die->tag)
16951     {
16952       process_die (child_die, cu);
16953       child_die = sibling_die (child_die);
16954     }
16955 }
16956
16957 /* Return the name of the namespace represented by DIE.  Set
16958    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16959    namespace.  */
16960
16961 static const char *
16962 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16963 {
16964   struct die_info *current_die;
16965   const char *name = NULL;
16966
16967   /* Loop through the extensions until we find a name.  */
16968
16969   for (current_die = die;
16970        current_die != NULL;
16971        current_die = dwarf2_extension (die, &cu))
16972     {
16973       /* We don't use dwarf2_name here so that we can detect the absence
16974          of a name -> anonymous namespace.  */
16975       name = dwarf2_string_attr (die, DW_AT_name, cu);
16976
16977       if (name != NULL)
16978         break;
16979     }
16980
16981   /* Is it an anonymous namespace?  */
16982
16983   *is_anonymous = (name == NULL);
16984   if (*is_anonymous)
16985     name = CP_ANONYMOUS_NAMESPACE_STR;
16986
16987   return name;
16988 }
16989
16990 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16991    the user defined type vector.  */
16992
16993 static struct type *
16994 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16995 {
16996   struct gdbarch *gdbarch
16997     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16998   struct comp_unit_head *cu_header = &cu->header;
16999   struct type *type;
17000   struct attribute *attr_byte_size;
17001   struct attribute *attr_address_class;
17002   int byte_size, addr_class;
17003   struct type *target_type;
17004
17005   target_type = die_type (die, cu);
17006
17007   /* The die_type call above may have already set the type for this DIE.  */
17008   type = get_die_type (die, cu);
17009   if (type)
17010     return type;
17011
17012   type = lookup_pointer_type (target_type);
17013
17014   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17015   if (attr_byte_size)
17016     byte_size = DW_UNSND (attr_byte_size);
17017   else
17018     byte_size = cu_header->addr_size;
17019
17020   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17021   if (attr_address_class)
17022     addr_class = DW_UNSND (attr_address_class);
17023   else
17024     addr_class = DW_ADDR_none;
17025
17026   ULONGEST alignment = get_alignment (cu, die);
17027
17028   /* If the pointer size, alignment, or address class is different
17029      than the default, create a type variant marked as such and set
17030      the length accordingly.  */
17031   if (TYPE_LENGTH (type) != byte_size
17032       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
17033           && alignment != TYPE_RAW_ALIGN (type))
17034       || addr_class != DW_ADDR_none)
17035     {
17036       if (gdbarch_address_class_type_flags_p (gdbarch))
17037         {
17038           int type_flags;
17039
17040           type_flags = gdbarch_address_class_type_flags
17041                          (gdbarch, byte_size, addr_class);
17042           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17043                       == 0);
17044           type = make_type_with_address_space (type, type_flags);
17045         }
17046       else if (TYPE_LENGTH (type) != byte_size)
17047         {
17048           complaint (_("invalid pointer size %d"), byte_size);
17049         }
17050       else if (TYPE_RAW_ALIGN (type) != alignment)
17051         {
17052           complaint (_("Invalid DW_AT_alignment"
17053                        " - DIE at %s [in module %s]"),
17054                      sect_offset_str (die->sect_off),
17055                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17056         }
17057       else
17058         {
17059           /* Should we also complain about unhandled address classes?  */
17060         }
17061     }
17062
17063   TYPE_LENGTH (type) = byte_size;
17064   set_type_align (type, alignment);
17065   return set_die_type (die, type, cu);
17066 }
17067
17068 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17069    the user defined type vector.  */
17070
17071 static struct type *
17072 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17073 {
17074   struct type *type;
17075   struct type *to_type;
17076   struct type *domain;
17077
17078   to_type = die_type (die, cu);
17079   domain = die_containing_type (die, cu);
17080
17081   /* The calls above may have already set the type for this DIE.  */
17082   type = get_die_type (die, cu);
17083   if (type)
17084     return type;
17085
17086   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17087     type = lookup_methodptr_type (to_type);
17088   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17089     {
17090       struct type *new_type
17091         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17092
17093       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17094                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17095                             TYPE_VARARGS (to_type));
17096       type = lookup_methodptr_type (new_type);
17097     }
17098   else
17099     type = lookup_memberptr_type (to_type, domain);
17100
17101   return set_die_type (die, type, cu);
17102 }
17103
17104 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17105    the user defined type vector.  */
17106
17107 static struct type *
17108 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17109                           enum type_code refcode)
17110 {
17111   struct comp_unit_head *cu_header = &cu->header;
17112   struct type *type, *target_type;
17113   struct attribute *attr;
17114
17115   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17116
17117   target_type = die_type (die, cu);
17118
17119   /* The die_type call above may have already set the type for this DIE.  */
17120   type = get_die_type (die, cu);
17121   if (type)
17122     return type;
17123
17124   type = lookup_reference_type (target_type, refcode);
17125   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17126   if (attr)
17127     {
17128       TYPE_LENGTH (type) = DW_UNSND (attr);
17129     }
17130   else
17131     {
17132       TYPE_LENGTH (type) = cu_header->addr_size;
17133     }
17134   maybe_set_alignment (cu, die, type);
17135   return set_die_type (die, type, cu);
17136 }
17137
17138 /* Add the given cv-qualifiers to the element type of the array.  GCC
17139    outputs DWARF type qualifiers that apply to an array, not the
17140    element type.  But GDB relies on the array element type to carry
17141    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17142    specification.  */
17143
17144 static struct type *
17145 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17146                    struct type *base_type, int cnst, int voltl)
17147 {
17148   struct type *el_type, *inner_array;
17149
17150   base_type = copy_type (base_type);
17151   inner_array = base_type;
17152
17153   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17154     {
17155       TYPE_TARGET_TYPE (inner_array) =
17156         copy_type (TYPE_TARGET_TYPE (inner_array));
17157       inner_array = TYPE_TARGET_TYPE (inner_array);
17158     }
17159
17160   el_type = TYPE_TARGET_TYPE (inner_array);
17161   cnst |= TYPE_CONST (el_type);
17162   voltl |= TYPE_VOLATILE (el_type);
17163   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17164
17165   return set_die_type (die, base_type, cu);
17166 }
17167
17168 static struct type *
17169 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17170 {
17171   struct type *base_type, *cv_type;
17172
17173   base_type = die_type (die, cu);
17174
17175   /* The die_type call above may have already set the type for this DIE.  */
17176   cv_type = get_die_type (die, cu);
17177   if (cv_type)
17178     return cv_type;
17179
17180   /* In case the const qualifier is applied to an array type, the element type
17181      is so qualified, not the array type (section 6.7.3 of C99).  */
17182   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17183     return add_array_cv_type (die, cu, base_type, 1, 0);
17184
17185   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17186   return set_die_type (die, cv_type, cu);
17187 }
17188
17189 static struct type *
17190 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17191 {
17192   struct type *base_type, *cv_type;
17193
17194   base_type = die_type (die, cu);
17195
17196   /* The die_type call above may have already set the type for this DIE.  */
17197   cv_type = get_die_type (die, cu);
17198   if (cv_type)
17199     return cv_type;
17200
17201   /* In case the volatile qualifier is applied to an array type, the
17202      element type is so qualified, not the array type (section 6.7.3
17203      of C99).  */
17204   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17205     return add_array_cv_type (die, cu, base_type, 0, 1);
17206
17207   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17208   return set_die_type (die, cv_type, cu);
17209 }
17210
17211 /* Handle DW_TAG_restrict_type.  */
17212
17213 static struct type *
17214 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17215 {
17216   struct type *base_type, *cv_type;
17217
17218   base_type = die_type (die, cu);
17219
17220   /* The die_type call above may have already set the type for this DIE.  */
17221   cv_type = get_die_type (die, cu);
17222   if (cv_type)
17223     return cv_type;
17224
17225   cv_type = make_restrict_type (base_type);
17226   return set_die_type (die, cv_type, cu);
17227 }
17228
17229 /* Handle DW_TAG_atomic_type.  */
17230
17231 static struct type *
17232 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17233 {
17234   struct type *base_type, *cv_type;
17235
17236   base_type = die_type (die, cu);
17237
17238   /* The die_type call above may have already set the type for this DIE.  */
17239   cv_type = get_die_type (die, cu);
17240   if (cv_type)
17241     return cv_type;
17242
17243   cv_type = make_atomic_type (base_type);
17244   return set_die_type (die, cv_type, cu);
17245 }
17246
17247 /* Extract all information from a DW_TAG_string_type DIE and add to
17248    the user defined type vector.  It isn't really a user defined type,
17249    but it behaves like one, with other DIE's using an AT_user_def_type
17250    attribute to reference it.  */
17251
17252 static struct type *
17253 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17254 {
17255   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17256   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17257   struct type *type, *range_type, *index_type, *char_type;
17258   struct attribute *attr;
17259   unsigned int length;
17260
17261   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17262   if (attr)
17263     {
17264       length = DW_UNSND (attr);
17265     }
17266   else
17267     {
17268       /* Check for the DW_AT_byte_size attribute.  */
17269       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17270       if (attr)
17271         {
17272           length = DW_UNSND (attr);
17273         }
17274       else
17275         {
17276           length = 1;
17277         }
17278     }
17279
17280   index_type = objfile_type (objfile)->builtin_int;
17281   range_type = create_static_range_type (NULL, index_type, 1, length);
17282   char_type = language_string_char_type (cu->language_defn, gdbarch);
17283   type = create_string_type (NULL, char_type, range_type);
17284
17285   return set_die_type (die, type, cu);
17286 }
17287
17288 /* Assuming that DIE corresponds to a function, returns nonzero
17289    if the function is prototyped.  */
17290
17291 static int
17292 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17293 {
17294   struct attribute *attr;
17295
17296   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17297   if (attr && (DW_UNSND (attr) != 0))
17298     return 1;
17299
17300   /* The DWARF standard implies that the DW_AT_prototyped attribute
17301      is only meaninful for C, but the concept also extends to other
17302      languages that allow unprototyped functions (Eg: Objective C).
17303      For all other languages, assume that functions are always
17304      prototyped.  */
17305   if (cu->language != language_c
17306       && cu->language != language_objc
17307       && cu->language != language_opencl)
17308     return 1;
17309
17310   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17311      prototyped and unprototyped functions; default to prototyped,
17312      since that is more common in modern code (and RealView warns
17313      about unprototyped functions).  */
17314   if (producer_is_realview (cu->producer))
17315     return 1;
17316
17317   return 0;
17318 }
17319
17320 /* Handle DIES due to C code like:
17321
17322    struct foo
17323    {
17324    int (*funcp)(int a, long l);
17325    int b;
17326    };
17327
17328    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17329
17330 static struct type *
17331 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17332 {
17333   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17334   struct type *type;            /* Type that this function returns.  */
17335   struct type *ftype;           /* Function that returns above type.  */
17336   struct attribute *attr;
17337
17338   type = die_type (die, cu);
17339
17340   /* The die_type call above may have already set the type for this DIE.  */
17341   ftype = get_die_type (die, cu);
17342   if (ftype)
17343     return ftype;
17344
17345   ftype = lookup_function_type (type);
17346
17347   if (prototyped_function_p (die, cu))
17348     TYPE_PROTOTYPED (ftype) = 1;
17349
17350   /* Store the calling convention in the type if it's available in
17351      the subroutine die.  Otherwise set the calling convention to
17352      the default value DW_CC_normal.  */
17353   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17354   if (attr)
17355     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17356   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17357     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17358   else
17359     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17360
17361   /* Record whether the function returns normally to its caller or not
17362      if the DWARF producer set that information.  */
17363   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17364   if (attr && (DW_UNSND (attr) != 0))
17365     TYPE_NO_RETURN (ftype) = 1;
17366
17367   /* We need to add the subroutine type to the die immediately so
17368      we don't infinitely recurse when dealing with parameters
17369      declared as the same subroutine type.  */
17370   set_die_type (die, ftype, cu);
17371
17372   if (die->child != NULL)
17373     {
17374       struct type *void_type = objfile_type (objfile)->builtin_void;
17375       struct die_info *child_die;
17376       int nparams, iparams;
17377
17378       /* Count the number of parameters.
17379          FIXME: GDB currently ignores vararg functions, but knows about
17380          vararg member functions.  */
17381       nparams = 0;
17382       child_die = die->child;
17383       while (child_die && child_die->tag)
17384         {
17385           if (child_die->tag == DW_TAG_formal_parameter)
17386             nparams++;
17387           else if (child_die->tag == DW_TAG_unspecified_parameters)
17388             TYPE_VARARGS (ftype) = 1;
17389           child_die = sibling_die (child_die);
17390         }
17391
17392       /* Allocate storage for parameters and fill them in.  */
17393       TYPE_NFIELDS (ftype) = nparams;
17394       TYPE_FIELDS (ftype) = (struct field *)
17395         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17396
17397       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17398          even if we error out during the parameters reading below.  */
17399       for (iparams = 0; iparams < nparams; iparams++)
17400         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17401
17402       iparams = 0;
17403       child_die = die->child;
17404       while (child_die && child_die->tag)
17405         {
17406           if (child_die->tag == DW_TAG_formal_parameter)
17407             {
17408               struct type *arg_type;
17409
17410               /* DWARF version 2 has no clean way to discern C++
17411                  static and non-static member functions.  G++ helps
17412                  GDB by marking the first parameter for non-static
17413                  member functions (which is the this pointer) as
17414                  artificial.  We pass this information to
17415                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17416
17417                  DWARF version 3 added DW_AT_object_pointer, which GCC
17418                  4.5 does not yet generate.  */
17419               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17420               if (attr)
17421                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17422               else
17423                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17424               arg_type = die_type (child_die, cu);
17425
17426               /* RealView does not mark THIS as const, which the testsuite
17427                  expects.  GCC marks THIS as const in method definitions,
17428                  but not in the class specifications (GCC PR 43053).  */
17429               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17430                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17431                 {
17432                   int is_this = 0;
17433                   struct dwarf2_cu *arg_cu = cu;
17434                   const char *name = dwarf2_name (child_die, cu);
17435
17436                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17437                   if (attr)
17438                     {
17439                       /* If the compiler emits this, use it.  */
17440                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17441                         is_this = 1;
17442                     }
17443                   else if (name && strcmp (name, "this") == 0)
17444                     /* Function definitions will have the argument names.  */
17445                     is_this = 1;
17446                   else if (name == NULL && iparams == 0)
17447                     /* Declarations may not have the names, so like
17448                        elsewhere in GDB, assume an artificial first
17449                        argument is "this".  */
17450                     is_this = 1;
17451
17452                   if (is_this)
17453                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17454                                              arg_type, 0);
17455                 }
17456
17457               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17458               iparams++;
17459             }
17460           child_die = sibling_die (child_die);
17461         }
17462     }
17463
17464   return ftype;
17465 }
17466
17467 static struct type *
17468 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17469 {
17470   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17471   const char *name = NULL;
17472   struct type *this_type, *target_type;
17473
17474   name = dwarf2_full_name (NULL, die, cu);
17475   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17476   TYPE_TARGET_STUB (this_type) = 1;
17477   set_die_type (die, this_type, cu);
17478   target_type = die_type (die, cu);
17479   if (target_type != this_type)
17480     TYPE_TARGET_TYPE (this_type) = target_type;
17481   else
17482     {
17483       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17484          spec and cause infinite loops in GDB.  */
17485       complaint (_("Self-referential DW_TAG_typedef "
17486                    "- DIE at %s [in module %s]"),
17487                  sect_offset_str (die->sect_off), objfile_name (objfile));
17488       TYPE_TARGET_TYPE (this_type) = NULL;
17489     }
17490   return this_type;
17491 }
17492
17493 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17494    (which may be different from NAME) to the architecture back-end to allow
17495    it to guess the correct format if necessary.  */
17496
17497 static struct type *
17498 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17499                         const char *name_hint)
17500 {
17501   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17502   const struct floatformat **format;
17503   struct type *type;
17504
17505   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17506   if (format)
17507     type = init_float_type (objfile, bits, name, format);
17508   else
17509     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17510
17511   return type;
17512 }
17513
17514 /* Allocate an integer type of size BITS and name NAME.  */
17515
17516 static struct type *
17517 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17518                           int bits, int unsigned_p, const char *name)
17519 {
17520   struct type *type;
17521
17522   /* Versions of Intel's C Compiler generate an integer type called "void"
17523      instead of using DW_TAG_unspecified_type.  This has been seen on
17524      at least versions 14, 17, and 18.  */
17525   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17526       && strcmp (name, "void") == 0)
17527     type = objfile_type (objfile)->builtin_void;
17528   else
17529     type = init_integer_type (objfile, bits, unsigned_p, name);
17530
17531   return type;
17532 }
17533
17534 /* Initialise and return a floating point type of size BITS suitable for
17535    use as a component of a complex number.  The NAME_HINT is passed through
17536    when initialising the floating point type and is the name of the complex
17537    type.
17538
17539    As DWARF doesn't currently provide an explicit name for the components
17540    of a complex number, but it can be helpful to have these components
17541    named, we try to select a suitable name based on the size of the
17542    component.  */
17543 static struct type *
17544 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
17545                                  struct objfile *objfile,
17546                                  int bits, const char *name_hint)
17547 {
17548   gdbarch *gdbarch = get_objfile_arch (objfile);
17549   struct type *tt = nullptr;
17550
17551   /* Try to find a suitable floating point builtin type of size BITS.
17552      We're going to use the name of this type as the name for the complex
17553      target type that we are about to create.  */
17554   switch (cu->language)
17555     {
17556     case language_fortran:
17557       switch (bits)
17558         {
17559         case 32:
17560           tt = builtin_f_type (gdbarch)->builtin_real;
17561           break;
17562         case 64:
17563           tt = builtin_f_type (gdbarch)->builtin_real_s8;
17564           break;
17565         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17566         case 128:
17567           tt = builtin_f_type (gdbarch)->builtin_real_s16;
17568           break;
17569         }
17570       break;
17571     default:
17572       switch (bits)
17573         {
17574         case 32:
17575           tt = builtin_type (gdbarch)->builtin_float;
17576           break;
17577         case 64:
17578           tt = builtin_type (gdbarch)->builtin_double;
17579           break;
17580         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17581         case 128:
17582           tt = builtin_type (gdbarch)->builtin_long_double;
17583           break;
17584         }
17585       break;
17586     }
17587
17588   /* If the type we found doesn't match the size we were looking for, then
17589      pretend we didn't find a type at all, the complex target type we
17590      create will then be nameless.  */
17591   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
17592     tt = nullptr;
17593
17594   const char *name = (tt == nullptr) ? nullptr : TYPE_NAME (tt);
17595   return dwarf2_init_float_type (objfile, bits, name, name_hint);
17596 }
17597
17598 /* Find a representation of a given base type and install
17599    it in the TYPE field of the die.  */
17600
17601 static struct type *
17602 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17603 {
17604   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17605   struct type *type;
17606   struct attribute *attr;
17607   int encoding = 0, bits = 0;
17608   const char *name;
17609
17610   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17611   if (attr)
17612     {
17613       encoding = DW_UNSND (attr);
17614     }
17615   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17616   if (attr)
17617     {
17618       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17619     }
17620   name = dwarf2_name (die, cu);
17621   if (!name)
17622     {
17623       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17624     }
17625
17626   switch (encoding)
17627     {
17628       case DW_ATE_address:
17629         /* Turn DW_ATE_address into a void * pointer.  */
17630         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17631         type = init_pointer_type (objfile, bits, name, type);
17632         break;
17633       case DW_ATE_boolean:
17634         type = init_boolean_type (objfile, bits, 1, name);
17635         break;
17636       case DW_ATE_complex_float:
17637         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name);
17638         type = init_complex_type (objfile, name, type);
17639         break;
17640       case DW_ATE_decimal_float:
17641         type = init_decfloat_type (objfile, bits, name);
17642         break;
17643       case DW_ATE_float:
17644         type = dwarf2_init_float_type (objfile, bits, name, name);
17645         break;
17646       case DW_ATE_signed:
17647         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17648         break;
17649       case DW_ATE_unsigned:
17650         if (cu->language == language_fortran
17651             && name
17652             && startswith (name, "character("))
17653           type = init_character_type (objfile, bits, 1, name);
17654         else
17655           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17656         break;
17657       case DW_ATE_signed_char:
17658         if (cu->language == language_ada || cu->language == language_m2
17659             || cu->language == language_pascal
17660             || cu->language == language_fortran)
17661           type = init_character_type (objfile, bits, 0, name);
17662         else
17663           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17664         break;
17665       case DW_ATE_unsigned_char:
17666         if (cu->language == language_ada || cu->language == language_m2
17667             || cu->language == language_pascal
17668             || cu->language == language_fortran
17669             || cu->language == language_rust)
17670           type = init_character_type (objfile, bits, 1, name);
17671         else
17672           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17673         break;
17674       case DW_ATE_UTF:
17675         {
17676           gdbarch *arch = get_objfile_arch (objfile);
17677
17678           if (bits == 16)
17679             type = builtin_type (arch)->builtin_char16;
17680           else if (bits == 32)
17681             type = builtin_type (arch)->builtin_char32;
17682           else
17683             {
17684               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17685                          bits);
17686               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17687             }
17688           return set_die_type (die, type, cu);
17689         }
17690         break;
17691
17692       default:
17693         complaint (_("unsupported DW_AT_encoding: '%s'"),
17694                    dwarf_type_encoding_name (encoding));
17695         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17696         break;
17697     }
17698
17699   if (name && strcmp (name, "char") == 0)
17700     TYPE_NOSIGN (type) = 1;
17701
17702   maybe_set_alignment (cu, die, type);
17703
17704   return set_die_type (die, type, cu);
17705 }
17706
17707 /* Parse dwarf attribute if it's a block, reference or constant and put the
17708    resulting value of the attribute into struct bound_prop.
17709    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17710
17711 static int
17712 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17713                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17714 {
17715   struct dwarf2_property_baton *baton;
17716   struct obstack *obstack
17717     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17718
17719   if (attr == NULL || prop == NULL)
17720     return 0;
17721
17722   if (attr_form_is_block (attr))
17723     {
17724       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17725       baton->referenced_type = NULL;
17726       baton->locexpr.per_cu = cu->per_cu;
17727       baton->locexpr.size = DW_BLOCK (attr)->size;
17728       baton->locexpr.data = DW_BLOCK (attr)->data;
17729       prop->data.baton = baton;
17730       prop->kind = PROP_LOCEXPR;
17731       gdb_assert (prop->data.baton != NULL);
17732     }
17733   else if (attr_form_is_ref (attr))
17734     {
17735       struct dwarf2_cu *target_cu = cu;
17736       struct die_info *target_die;
17737       struct attribute *target_attr;
17738
17739       target_die = follow_die_ref (die, attr, &target_cu);
17740       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17741       if (target_attr == NULL)
17742         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17743                                    target_cu);
17744       if (target_attr == NULL)
17745         return 0;
17746
17747       switch (target_attr->name)
17748         {
17749           case DW_AT_location:
17750             if (attr_form_is_section_offset (target_attr))
17751               {
17752                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17753                 baton->referenced_type = die_type (target_die, target_cu);
17754                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17755                 prop->data.baton = baton;
17756                 prop->kind = PROP_LOCLIST;
17757                 gdb_assert (prop->data.baton != NULL);
17758               }
17759             else if (attr_form_is_block (target_attr))
17760               {
17761                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17762                 baton->referenced_type = die_type (target_die, target_cu);
17763                 baton->locexpr.per_cu = cu->per_cu;
17764                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17765                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17766                 prop->data.baton = baton;
17767                 prop->kind = PROP_LOCEXPR;
17768                 gdb_assert (prop->data.baton != NULL);
17769               }
17770             else
17771               {
17772                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17773                                                        "dynamic property");
17774                 return 0;
17775               }
17776             break;
17777           case DW_AT_data_member_location:
17778             {
17779               LONGEST offset;
17780
17781               if (!handle_data_member_location (target_die, target_cu,
17782                                                 &offset))
17783                 return 0;
17784
17785               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17786               baton->referenced_type = read_type_die (target_die->parent,
17787                                                       target_cu);
17788               baton->offset_info.offset = offset;
17789               baton->offset_info.type = die_type (target_die, target_cu);
17790               prop->data.baton = baton;
17791               prop->kind = PROP_ADDR_OFFSET;
17792               break;
17793             }
17794         }
17795     }
17796   else if (attr_form_is_constant (attr))
17797     {
17798       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17799       prop->kind = PROP_CONST;
17800     }
17801   else
17802     {
17803       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17804                                              dwarf2_name (die, cu));
17805       return 0;
17806     }
17807
17808   return 1;
17809 }
17810
17811 /* Read the given DW_AT_subrange DIE.  */
17812
17813 static struct type *
17814 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17815 {
17816   struct type *base_type, *orig_base_type;
17817   struct type *range_type;
17818   struct attribute *attr;
17819   struct dynamic_prop low, high;
17820   int low_default_is_valid;
17821   int high_bound_is_count = 0;
17822   const char *name;
17823   ULONGEST negative_mask;
17824
17825   orig_base_type = die_type (die, cu);
17826   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17827      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17828      creating the range type, but we use the result of check_typedef
17829      when examining properties of the type.  */
17830   base_type = check_typedef (orig_base_type);
17831
17832   /* The die_type call above may have already set the type for this DIE.  */
17833   range_type = get_die_type (die, cu);
17834   if (range_type)
17835     return range_type;
17836
17837   low.kind = PROP_CONST;
17838   high.kind = PROP_CONST;
17839   high.data.const_val = 0;
17840
17841   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17842      omitting DW_AT_lower_bound.  */
17843   switch (cu->language)
17844     {
17845     case language_c:
17846     case language_cplus:
17847       low.data.const_val = 0;
17848       low_default_is_valid = 1;
17849       break;
17850     case language_fortran:
17851       low.data.const_val = 1;
17852       low_default_is_valid = 1;
17853       break;
17854     case language_d:
17855     case language_objc:
17856     case language_rust:
17857       low.data.const_val = 0;
17858       low_default_is_valid = (cu->header.version >= 4);
17859       break;
17860     case language_ada:
17861     case language_m2:
17862     case language_pascal:
17863       low.data.const_val = 1;
17864       low_default_is_valid = (cu->header.version >= 4);
17865       break;
17866     default:
17867       low.data.const_val = 0;
17868       low_default_is_valid = 0;
17869       break;
17870     }
17871
17872   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17873   if (attr)
17874     attr_to_dynamic_prop (attr, die, cu, &low);
17875   else if (!low_default_is_valid)
17876     complaint (_("Missing DW_AT_lower_bound "
17877                                       "- DIE at %s [in module %s]"),
17878                sect_offset_str (die->sect_off),
17879                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17880
17881   struct attribute *attr_ub, *attr_count;
17882   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17883   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17884     {
17885       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17886       if (attr_to_dynamic_prop (attr, die, cu, &high))
17887         {
17888           /* If bounds are constant do the final calculation here.  */
17889           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17890             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17891           else
17892             high_bound_is_count = 1;
17893         }
17894       else
17895         {
17896           if (attr_ub != NULL)
17897             complaint (_("Unresolved DW_AT_upper_bound "
17898                          "- DIE at %s [in module %s]"),
17899                        sect_offset_str (die->sect_off),
17900                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17901           if (attr_count != NULL)
17902             complaint (_("Unresolved DW_AT_count "
17903                          "- DIE at %s [in module %s]"),
17904                        sect_offset_str (die->sect_off),
17905                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17906         }
17907         
17908     }
17909
17910   /* Dwarf-2 specifications explicitly allows to create subrange types
17911      without specifying a base type.
17912      In that case, the base type must be set to the type of
17913      the lower bound, upper bound or count, in that order, if any of these
17914      three attributes references an object that has a type.
17915      If no base type is found, the Dwarf-2 specifications say that
17916      a signed integer type of size equal to the size of an address should
17917      be used.
17918      For the following C code: `extern char gdb_int [];'
17919      GCC produces an empty range DIE.
17920      FIXME: muller/2010-05-28: Possible references to object for low bound,
17921      high bound or count are not yet handled by this code.  */
17922   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17923     {
17924       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17925       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17926       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17927       struct type *int_type = objfile_type (objfile)->builtin_int;
17928
17929       /* Test "int", "long int", and "long long int" objfile types,
17930          and select the first one having a size above or equal to the
17931          architecture address size.  */
17932       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17933         base_type = int_type;
17934       else
17935         {
17936           int_type = objfile_type (objfile)->builtin_long;
17937           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17938             base_type = int_type;
17939           else
17940             {
17941               int_type = objfile_type (objfile)->builtin_long_long;
17942               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17943                 base_type = int_type;
17944             }
17945         }
17946     }
17947
17948   /* Normally, the DWARF producers are expected to use a signed
17949      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17950      But this is unfortunately not always the case, as witnessed
17951      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17952      is used instead.  To work around that ambiguity, we treat
17953      the bounds as signed, and thus sign-extend their values, when
17954      the base type is signed.  */
17955   negative_mask =
17956     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17957   if (low.kind == PROP_CONST
17958       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17959     low.data.const_val |= negative_mask;
17960   if (high.kind == PROP_CONST
17961       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17962     high.data.const_val |= negative_mask;
17963
17964   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17965
17966   if (high_bound_is_count)
17967     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17968
17969   /* Ada expects an empty array on no boundary attributes.  */
17970   if (attr == NULL && cu->language != language_ada)
17971     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17972
17973   name = dwarf2_name (die, cu);
17974   if (name)
17975     TYPE_NAME (range_type) = name;
17976
17977   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17978   if (attr)
17979     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17980
17981   maybe_set_alignment (cu, die, range_type);
17982
17983   set_die_type (die, range_type, cu);
17984
17985   /* set_die_type should be already done.  */
17986   set_descriptive_type (range_type, die, cu);
17987
17988   return range_type;
17989 }
17990
17991 static struct type *
17992 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17993 {
17994   struct type *type;
17995
17996   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17997                     NULL);
17998   TYPE_NAME (type) = dwarf2_name (die, cu);
17999
18000   /* In Ada, an unspecified type is typically used when the description
18001      of the type is defered to a different unit.  When encountering
18002      such a type, we treat it as a stub, and try to resolve it later on,
18003      when needed.  */
18004   if (cu->language == language_ada)
18005     TYPE_STUB (type) = 1;
18006
18007   return set_die_type (die, type, cu);
18008 }
18009
18010 /* Read a single die and all its descendents.  Set the die's sibling
18011    field to NULL; set other fields in the die correctly, and set all
18012    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
18013    location of the info_ptr after reading all of those dies.  PARENT
18014    is the parent of the die in question.  */
18015
18016 static struct die_info *
18017 read_die_and_children (const struct die_reader_specs *reader,
18018                        const gdb_byte *info_ptr,
18019                        const gdb_byte **new_info_ptr,
18020                        struct die_info *parent)
18021 {
18022   struct die_info *die;
18023   const gdb_byte *cur_ptr;
18024   int has_children;
18025
18026   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
18027   if (die == NULL)
18028     {
18029       *new_info_ptr = cur_ptr;
18030       return NULL;
18031     }
18032   store_in_ref_table (die, reader->cu);
18033
18034   if (has_children)
18035     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
18036   else
18037     {
18038       die->child = NULL;
18039       *new_info_ptr = cur_ptr;
18040     }
18041
18042   die->sibling = NULL;
18043   die->parent = parent;
18044   return die;
18045 }
18046
18047 /* Read a die, all of its descendents, and all of its siblings; set
18048    all of the fields of all of the dies correctly.  Arguments are as
18049    in read_die_and_children.  */
18050
18051 static struct die_info *
18052 read_die_and_siblings_1 (const struct die_reader_specs *reader,
18053                          const gdb_byte *info_ptr,
18054                          const gdb_byte **new_info_ptr,
18055                          struct die_info *parent)
18056 {
18057   struct die_info *first_die, *last_sibling;
18058   const gdb_byte *cur_ptr;
18059
18060   cur_ptr = info_ptr;
18061   first_die = last_sibling = NULL;
18062
18063   while (1)
18064     {
18065       struct die_info *die
18066         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
18067
18068       if (die == NULL)
18069         {
18070           *new_info_ptr = cur_ptr;
18071           return first_die;
18072         }
18073
18074       if (!first_die)
18075         first_die = die;
18076       else
18077         last_sibling->sibling = die;
18078
18079       last_sibling = die;
18080     }
18081 }
18082
18083 /* Read a die, all of its descendents, and all of its siblings; set
18084    all of the fields of all of the dies correctly.  Arguments are as
18085    in read_die_and_children.
18086    This the main entry point for reading a DIE and all its children.  */
18087
18088 static struct die_info *
18089 read_die_and_siblings (const struct die_reader_specs *reader,
18090                        const gdb_byte *info_ptr,
18091                        const gdb_byte **new_info_ptr,
18092                        struct die_info *parent)
18093 {
18094   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18095                                                   new_info_ptr, parent);
18096
18097   if (dwarf_die_debug)
18098     {
18099       fprintf_unfiltered (gdb_stdlog,
18100                           "Read die from %s@0x%x of %s:\n",
18101                           get_section_name (reader->die_section),
18102                           (unsigned) (info_ptr - reader->die_section->buffer),
18103                           bfd_get_filename (reader->abfd));
18104       dump_die (die, dwarf_die_debug);
18105     }
18106
18107   return die;
18108 }
18109
18110 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18111    attributes.
18112    The caller is responsible for filling in the extra attributes
18113    and updating (*DIEP)->num_attrs.
18114    Set DIEP to point to a newly allocated die with its information,
18115    except for its child, sibling, and parent fields.
18116    Set HAS_CHILDREN to tell whether the die has children or not.  */
18117
18118 static const gdb_byte *
18119 read_full_die_1 (const struct die_reader_specs *reader,
18120                  struct die_info **diep, const gdb_byte *info_ptr,
18121                  int *has_children, int num_extra_attrs)
18122 {
18123   unsigned int abbrev_number, bytes_read, i;
18124   struct abbrev_info *abbrev;
18125   struct die_info *die;
18126   struct dwarf2_cu *cu = reader->cu;
18127   bfd *abfd = reader->abfd;
18128
18129   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18130   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18131   info_ptr += bytes_read;
18132   if (!abbrev_number)
18133     {
18134       *diep = NULL;
18135       *has_children = 0;
18136       return info_ptr;
18137     }
18138
18139   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18140   if (!abbrev)
18141     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18142            abbrev_number,
18143            bfd_get_filename (abfd));
18144
18145   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18146   die->sect_off = sect_off;
18147   die->tag = abbrev->tag;
18148   die->abbrev = abbrev_number;
18149
18150   /* Make the result usable.
18151      The caller needs to update num_attrs after adding the extra
18152      attributes.  */
18153   die->num_attrs = abbrev->num_attrs;
18154
18155   for (i = 0; i < abbrev->num_attrs; ++i)
18156     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18157                                info_ptr);
18158
18159   *diep = die;
18160   *has_children = abbrev->has_children;
18161   return info_ptr;
18162 }
18163
18164 /* Read a die and all its attributes.
18165    Set DIEP to point to a newly allocated die with its information,
18166    except for its child, sibling, and parent fields.
18167    Set HAS_CHILDREN to tell whether the die has children or not.  */
18168
18169 static const gdb_byte *
18170 read_full_die (const struct die_reader_specs *reader,
18171                struct die_info **diep, const gdb_byte *info_ptr,
18172                int *has_children)
18173 {
18174   const gdb_byte *result;
18175
18176   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18177
18178   if (dwarf_die_debug)
18179     {
18180       fprintf_unfiltered (gdb_stdlog,
18181                           "Read die from %s@0x%x of %s:\n",
18182                           get_section_name (reader->die_section),
18183                           (unsigned) (info_ptr - reader->die_section->buffer),
18184                           bfd_get_filename (reader->abfd));
18185       dump_die (*diep, dwarf_die_debug);
18186     }
18187
18188   return result;
18189 }
18190 \f
18191 /* Abbreviation tables.
18192
18193    In DWARF version 2, the description of the debugging information is
18194    stored in a separate .debug_abbrev section.  Before we read any
18195    dies from a section we read in all abbreviations and install them
18196    in a hash table.  */
18197
18198 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18199
18200 struct abbrev_info *
18201 abbrev_table::alloc_abbrev ()
18202 {
18203   struct abbrev_info *abbrev;
18204
18205   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18206   memset (abbrev, 0, sizeof (struct abbrev_info));
18207
18208   return abbrev;
18209 }
18210
18211 /* Add an abbreviation to the table.  */
18212
18213 void
18214 abbrev_table::add_abbrev (unsigned int abbrev_number,
18215                           struct abbrev_info *abbrev)
18216 {
18217   unsigned int hash_number;
18218
18219   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18220   abbrev->next = m_abbrevs[hash_number];
18221   m_abbrevs[hash_number] = abbrev;
18222 }
18223
18224 /* Look up an abbrev in the table.
18225    Returns NULL if the abbrev is not found.  */
18226
18227 struct abbrev_info *
18228 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18229 {
18230   unsigned int hash_number;
18231   struct abbrev_info *abbrev;
18232
18233   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18234   abbrev = m_abbrevs[hash_number];
18235
18236   while (abbrev)
18237     {
18238       if (abbrev->number == abbrev_number)
18239         return abbrev;
18240       abbrev = abbrev->next;
18241     }
18242   return NULL;
18243 }
18244
18245 /* Read in an abbrev table.  */
18246
18247 static abbrev_table_up
18248 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18249                          struct dwarf2_section_info *section,
18250                          sect_offset sect_off)
18251 {
18252   struct objfile *objfile = dwarf2_per_objfile->objfile;
18253   bfd *abfd = get_section_bfd_owner (section);
18254   const gdb_byte *abbrev_ptr;
18255   struct abbrev_info *cur_abbrev;
18256   unsigned int abbrev_number, bytes_read, abbrev_name;
18257   unsigned int abbrev_form;
18258   struct attr_abbrev *cur_attrs;
18259   unsigned int allocated_attrs;
18260
18261   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18262
18263   dwarf2_read_section (objfile, section);
18264   abbrev_ptr = section->buffer + to_underlying (sect_off);
18265   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18266   abbrev_ptr += bytes_read;
18267
18268   allocated_attrs = ATTR_ALLOC_CHUNK;
18269   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18270
18271   /* Loop until we reach an abbrev number of 0.  */
18272   while (abbrev_number)
18273     {
18274       cur_abbrev = abbrev_table->alloc_abbrev ();
18275
18276       /* read in abbrev header */
18277       cur_abbrev->number = abbrev_number;
18278       cur_abbrev->tag
18279         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18280       abbrev_ptr += bytes_read;
18281       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18282       abbrev_ptr += 1;
18283
18284       /* now read in declarations */
18285       for (;;)
18286         {
18287           LONGEST implicit_const;
18288
18289           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18290           abbrev_ptr += bytes_read;
18291           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18292           abbrev_ptr += bytes_read;
18293           if (abbrev_form == DW_FORM_implicit_const)
18294             {
18295               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18296                                                    &bytes_read);
18297               abbrev_ptr += bytes_read;
18298             }
18299           else
18300             {
18301               /* Initialize it due to a false compiler warning.  */
18302               implicit_const = -1;
18303             }
18304
18305           if (abbrev_name == 0)
18306             break;
18307
18308           if (cur_abbrev->num_attrs == allocated_attrs)
18309             {
18310               allocated_attrs += ATTR_ALLOC_CHUNK;
18311               cur_attrs
18312                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18313             }
18314
18315           cur_attrs[cur_abbrev->num_attrs].name
18316             = (enum dwarf_attribute) abbrev_name;
18317           cur_attrs[cur_abbrev->num_attrs].form
18318             = (enum dwarf_form) abbrev_form;
18319           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18320           ++cur_abbrev->num_attrs;
18321         }
18322
18323       cur_abbrev->attrs =
18324         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18325                    cur_abbrev->num_attrs);
18326       memcpy (cur_abbrev->attrs, cur_attrs,
18327               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18328
18329       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18330
18331       /* Get next abbreviation.
18332          Under Irix6 the abbreviations for a compilation unit are not
18333          always properly terminated with an abbrev number of 0.
18334          Exit loop if we encounter an abbreviation which we have
18335          already read (which means we are about to read the abbreviations
18336          for the next compile unit) or if the end of the abbreviation
18337          table is reached.  */
18338       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18339         break;
18340       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18341       abbrev_ptr += bytes_read;
18342       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18343         break;
18344     }
18345
18346   xfree (cur_attrs);
18347   return abbrev_table;
18348 }
18349
18350 /* Returns nonzero if TAG represents a type that we might generate a partial
18351    symbol for.  */
18352
18353 static int
18354 is_type_tag_for_partial (int tag)
18355 {
18356   switch (tag)
18357     {
18358 #if 0
18359     /* Some types that would be reasonable to generate partial symbols for,
18360        that we don't at present.  */
18361     case DW_TAG_array_type:
18362     case DW_TAG_file_type:
18363     case DW_TAG_ptr_to_member_type:
18364     case DW_TAG_set_type:
18365     case DW_TAG_string_type:
18366     case DW_TAG_subroutine_type:
18367 #endif
18368     case DW_TAG_base_type:
18369     case DW_TAG_class_type:
18370     case DW_TAG_interface_type:
18371     case DW_TAG_enumeration_type:
18372     case DW_TAG_structure_type:
18373     case DW_TAG_subrange_type:
18374     case DW_TAG_typedef:
18375     case DW_TAG_union_type:
18376       return 1;
18377     default:
18378       return 0;
18379     }
18380 }
18381
18382 /* Load all DIEs that are interesting for partial symbols into memory.  */
18383
18384 static struct partial_die_info *
18385 load_partial_dies (const struct die_reader_specs *reader,
18386                    const gdb_byte *info_ptr, int building_psymtab)
18387 {
18388   struct dwarf2_cu *cu = reader->cu;
18389   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18390   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18391   unsigned int bytes_read;
18392   unsigned int load_all = 0;
18393   int nesting_level = 1;
18394
18395   parent_die = NULL;
18396   last_die = NULL;
18397
18398   gdb_assert (cu->per_cu != NULL);
18399   if (cu->per_cu->load_all_dies)
18400     load_all = 1;
18401
18402   cu->partial_dies
18403     = htab_create_alloc_ex (cu->header.length / 12,
18404                             partial_die_hash,
18405                             partial_die_eq,
18406                             NULL,
18407                             &cu->comp_unit_obstack,
18408                             hashtab_obstack_allocate,
18409                             dummy_obstack_deallocate);
18410
18411   while (1)
18412     {
18413       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18414
18415       /* A NULL abbrev means the end of a series of children.  */
18416       if (abbrev == NULL)
18417         {
18418           if (--nesting_level == 0)
18419             return first_die;
18420
18421           info_ptr += bytes_read;
18422           last_die = parent_die;
18423           parent_die = parent_die->die_parent;
18424           continue;
18425         }
18426
18427       /* Check for template arguments.  We never save these; if
18428          they're seen, we just mark the parent, and go on our way.  */
18429       if (parent_die != NULL
18430           && cu->language == language_cplus
18431           && (abbrev->tag == DW_TAG_template_type_param
18432               || abbrev->tag == DW_TAG_template_value_param))
18433         {
18434           parent_die->has_template_arguments = 1;
18435
18436           if (!load_all)
18437             {
18438               /* We don't need a partial DIE for the template argument.  */
18439               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18440               continue;
18441             }
18442         }
18443
18444       /* We only recurse into c++ subprograms looking for template arguments.
18445          Skip their other children.  */
18446       if (!load_all
18447           && cu->language == language_cplus
18448           && parent_die != NULL
18449           && parent_die->tag == DW_TAG_subprogram)
18450         {
18451           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18452           continue;
18453         }
18454
18455       /* Check whether this DIE is interesting enough to save.  Normally
18456          we would not be interested in members here, but there may be
18457          later variables referencing them via DW_AT_specification (for
18458          static members).  */
18459       if (!load_all
18460           && !is_type_tag_for_partial (abbrev->tag)
18461           && abbrev->tag != DW_TAG_constant
18462           && abbrev->tag != DW_TAG_enumerator
18463           && abbrev->tag != DW_TAG_subprogram
18464           && abbrev->tag != DW_TAG_inlined_subroutine
18465           && abbrev->tag != DW_TAG_lexical_block
18466           && abbrev->tag != DW_TAG_variable
18467           && abbrev->tag != DW_TAG_namespace
18468           && abbrev->tag != DW_TAG_module
18469           && abbrev->tag != DW_TAG_member
18470           && abbrev->tag != DW_TAG_imported_unit
18471           && abbrev->tag != DW_TAG_imported_declaration)
18472         {
18473           /* Otherwise we skip to the next sibling, if any.  */
18474           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18475           continue;
18476         }
18477
18478       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18479                                    abbrev);
18480
18481       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18482
18483       /* This two-pass algorithm for processing partial symbols has a
18484          high cost in cache pressure.  Thus, handle some simple cases
18485          here which cover the majority of C partial symbols.  DIEs
18486          which neither have specification tags in them, nor could have
18487          specification tags elsewhere pointing at them, can simply be
18488          processed and discarded.
18489
18490          This segment is also optional; scan_partial_symbols and
18491          add_partial_symbol will handle these DIEs if we chain
18492          them in normally.  When compilers which do not emit large
18493          quantities of duplicate debug information are more common,
18494          this code can probably be removed.  */
18495
18496       /* Any complete simple types at the top level (pretty much all
18497          of them, for a language without namespaces), can be processed
18498          directly.  */
18499       if (parent_die == NULL
18500           && pdi.has_specification == 0
18501           && pdi.is_declaration == 0
18502           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18503               || pdi.tag == DW_TAG_base_type
18504               || pdi.tag == DW_TAG_subrange_type))
18505         {
18506           if (building_psymtab && pdi.name != NULL)
18507             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18508                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18509                                  psymbol_placement::STATIC,
18510                                  0, cu->language, objfile);
18511           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18512           continue;
18513         }
18514
18515       /* The exception for DW_TAG_typedef with has_children above is
18516          a workaround of GCC PR debug/47510.  In the case of this complaint
18517          type_name_or_error will error on such types later.
18518
18519          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18520          it could not find the child DIEs referenced later, this is checked
18521          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18522
18523       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18524         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18525                      "- DIE at %s [in module %s]"),
18526                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18527
18528       /* If we're at the second level, and we're an enumerator, and
18529          our parent has no specification (meaning possibly lives in a
18530          namespace elsewhere), then we can add the partial symbol now
18531          instead of queueing it.  */
18532       if (pdi.tag == DW_TAG_enumerator
18533           && parent_die != NULL
18534           && parent_die->die_parent == NULL
18535           && parent_die->tag == DW_TAG_enumeration_type
18536           && parent_die->has_specification == 0)
18537         {
18538           if (pdi.name == NULL)
18539             complaint (_("malformed enumerator DIE ignored"));
18540           else if (building_psymtab)
18541             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18542                                  VAR_DOMAIN, LOC_CONST, -1,
18543                                  cu->language == language_cplus
18544                                  ? psymbol_placement::GLOBAL
18545                                  : psymbol_placement::STATIC,
18546                                  0, cu->language, objfile);
18547
18548           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18549           continue;
18550         }
18551
18552       struct partial_die_info *part_die
18553         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18554
18555       /* We'll save this DIE so link it in.  */
18556       part_die->die_parent = parent_die;
18557       part_die->die_sibling = NULL;
18558       part_die->die_child = NULL;
18559
18560       if (last_die && last_die == parent_die)
18561         last_die->die_child = part_die;
18562       else if (last_die)
18563         last_die->die_sibling = part_die;
18564
18565       last_die = part_die;
18566
18567       if (first_die == NULL)
18568         first_die = part_die;
18569
18570       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18571          find interesting need to be in the hash table, because we
18572          also have the parent/sibling/child chains; only those that we
18573          might refer to by offset later during partial symbol reading.
18574
18575          For now this means things that might have be the target of a
18576          DW_AT_specification, DW_AT_abstract_origin, or
18577          DW_AT_extension.  DW_AT_extension will refer only to
18578          namespaces; DW_AT_abstract_origin refers to functions (and
18579          many things under the function DIE, but we do not recurse
18580          into function DIEs during partial symbol reading) and
18581          possibly variables as well; DW_AT_specification refers to
18582          declarations.  Declarations ought to have the DW_AT_declaration
18583          flag.  It happens that GCC forgets to put it in sometimes, but
18584          only for functions, not for types.
18585
18586          Adding more things than necessary to the hash table is harmless
18587          except for the performance cost.  Adding too few will result in
18588          wasted time in find_partial_die, when we reread the compilation
18589          unit with load_all_dies set.  */
18590
18591       if (load_all
18592           || abbrev->tag == DW_TAG_constant
18593           || abbrev->tag == DW_TAG_subprogram
18594           || abbrev->tag == DW_TAG_variable
18595           || abbrev->tag == DW_TAG_namespace
18596           || part_die->is_declaration)
18597         {
18598           void **slot;
18599
18600           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18601                                            to_underlying (part_die->sect_off),
18602                                            INSERT);
18603           *slot = part_die;
18604         }
18605
18606       /* For some DIEs we want to follow their children (if any).  For C
18607          we have no reason to follow the children of structures; for other
18608          languages we have to, so that we can get at method physnames
18609          to infer fully qualified class names, for DW_AT_specification,
18610          and for C++ template arguments.  For C++, we also look one level
18611          inside functions to find template arguments (if the name of the
18612          function does not already contain the template arguments).
18613
18614          For Ada, we need to scan the children of subprograms and lexical
18615          blocks as well because Ada allows the definition of nested
18616          entities that could be interesting for the debugger, such as
18617          nested subprograms for instance.  */
18618       if (last_die->has_children
18619           && (load_all
18620               || last_die->tag == DW_TAG_namespace
18621               || last_die->tag == DW_TAG_module
18622               || last_die->tag == DW_TAG_enumeration_type
18623               || (cu->language == language_cplus
18624                   && last_die->tag == DW_TAG_subprogram
18625                   && (last_die->name == NULL
18626                       || strchr (last_die->name, '<') == NULL))
18627               || (cu->language != language_c
18628                   && (last_die->tag == DW_TAG_class_type
18629                       || last_die->tag == DW_TAG_interface_type
18630                       || last_die->tag == DW_TAG_structure_type
18631                       || last_die->tag == DW_TAG_union_type))
18632               || (cu->language == language_ada
18633                   && (last_die->tag == DW_TAG_subprogram
18634                       || last_die->tag == DW_TAG_lexical_block))))
18635         {
18636           nesting_level++;
18637           parent_die = last_die;
18638           continue;
18639         }
18640
18641       /* Otherwise we skip to the next sibling, if any.  */
18642       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18643
18644       /* Back to the top, do it again.  */
18645     }
18646 }
18647
18648 partial_die_info::partial_die_info (sect_offset sect_off_,
18649                                     struct abbrev_info *abbrev)
18650   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18651 {
18652 }
18653
18654 /* Read a minimal amount of information into the minimal die structure.
18655    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18656
18657 const gdb_byte *
18658 partial_die_info::read (const struct die_reader_specs *reader,
18659                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18660 {
18661   struct dwarf2_cu *cu = reader->cu;
18662   struct dwarf2_per_objfile *dwarf2_per_objfile
18663     = cu->per_cu->dwarf2_per_objfile;
18664   unsigned int i;
18665   int has_low_pc_attr = 0;
18666   int has_high_pc_attr = 0;
18667   int high_pc_relative = 0;
18668
18669   for (i = 0; i < abbrev.num_attrs; ++i)
18670     {
18671       struct attribute attr;
18672
18673       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18674
18675       /* Store the data if it is of an attribute we want to keep in a
18676          partial symbol table.  */
18677       switch (attr.name)
18678         {
18679         case DW_AT_name:
18680           switch (tag)
18681             {
18682             case DW_TAG_compile_unit:
18683             case DW_TAG_partial_unit:
18684             case DW_TAG_type_unit:
18685               /* Compilation units have a DW_AT_name that is a filename, not
18686                  a source language identifier.  */
18687             case DW_TAG_enumeration_type:
18688             case DW_TAG_enumerator:
18689               /* These tags always have simple identifiers already; no need
18690                  to canonicalize them.  */
18691               name = DW_STRING (&attr);
18692               break;
18693             default:
18694               {
18695                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18696
18697                 name
18698                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18699                                               &objfile->per_bfd->storage_obstack);
18700               }
18701               break;
18702             }
18703           break;
18704         case DW_AT_linkage_name:
18705         case DW_AT_MIPS_linkage_name:
18706           /* Note that both forms of linkage name might appear.  We
18707              assume they will be the same, and we only store the last
18708              one we see.  */
18709           if (cu->language == language_ada)
18710             name = DW_STRING (&attr);
18711           linkage_name = DW_STRING (&attr);
18712           break;
18713         case DW_AT_low_pc:
18714           has_low_pc_attr = 1;
18715           lowpc = attr_value_as_address (&attr);
18716           break;
18717         case DW_AT_high_pc:
18718           has_high_pc_attr = 1;
18719           highpc = attr_value_as_address (&attr);
18720           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18721                 high_pc_relative = 1;
18722           break;
18723         case DW_AT_location:
18724           /* Support the .debug_loc offsets.  */
18725           if (attr_form_is_block (&attr))
18726             {
18727                d.locdesc = DW_BLOCK (&attr);
18728             }
18729           else if (attr_form_is_section_offset (&attr))
18730             {
18731               dwarf2_complex_location_expr_complaint ();
18732             }
18733           else
18734             {
18735               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18736                                                      "partial symbol information");
18737             }
18738           break;
18739         case DW_AT_external:
18740           is_external = DW_UNSND (&attr);
18741           break;
18742         case DW_AT_declaration:
18743           is_declaration = DW_UNSND (&attr);
18744           break;
18745         case DW_AT_type:
18746           has_type = 1;
18747           break;
18748         case DW_AT_abstract_origin:
18749         case DW_AT_specification:
18750         case DW_AT_extension:
18751           has_specification = 1;
18752           spec_offset = dwarf2_get_ref_die_offset (&attr);
18753           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18754                                    || cu->per_cu->is_dwz);
18755           break;
18756         case DW_AT_sibling:
18757           /* Ignore absolute siblings, they might point outside of
18758              the current compile unit.  */
18759           if (attr.form == DW_FORM_ref_addr)
18760             complaint (_("ignoring absolute DW_AT_sibling"));
18761           else
18762             {
18763               const gdb_byte *buffer = reader->buffer;
18764               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18765               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18766
18767               if (sibling_ptr < info_ptr)
18768                 complaint (_("DW_AT_sibling points backwards"));
18769               else if (sibling_ptr > reader->buffer_end)
18770                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18771               else
18772                 sibling = sibling_ptr;
18773             }
18774           break;
18775         case DW_AT_byte_size:
18776           has_byte_size = 1;
18777           break;
18778         case DW_AT_const_value:
18779           has_const_value = 1;
18780           break;
18781         case DW_AT_calling_convention:
18782           /* DWARF doesn't provide a way to identify a program's source-level
18783              entry point.  DW_AT_calling_convention attributes are only meant
18784              to describe functions' calling conventions.
18785
18786              However, because it's a necessary piece of information in
18787              Fortran, and before DWARF 4 DW_CC_program was the only
18788              piece of debugging information whose definition refers to
18789              a 'main program' at all, several compilers marked Fortran
18790              main programs with DW_CC_program --- even when those
18791              functions use the standard calling conventions.
18792
18793              Although DWARF now specifies a way to provide this
18794              information, we support this practice for backward
18795              compatibility.  */
18796           if (DW_UNSND (&attr) == DW_CC_program
18797               && cu->language == language_fortran)
18798             main_subprogram = 1;
18799           break;
18800         case DW_AT_inline:
18801           if (DW_UNSND (&attr) == DW_INL_inlined
18802               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18803             may_be_inlined = 1;
18804           break;
18805
18806         case DW_AT_import:
18807           if (tag == DW_TAG_imported_unit)
18808             {
18809               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18810               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18811                                   || cu->per_cu->is_dwz);
18812             }
18813           break;
18814
18815         case DW_AT_main_subprogram:
18816           main_subprogram = DW_UNSND (&attr);
18817           break;
18818
18819         case DW_AT_ranges:
18820           {
18821             /* It would be nice to reuse dwarf2_get_pc_bounds here,
18822                but that requires a full DIE, so instead we just
18823                reimplement it.  */
18824             int need_ranges_base = tag != DW_TAG_compile_unit;
18825             unsigned int ranges_offset = (DW_UNSND (&attr)
18826                                           + (need_ranges_base
18827                                              ? cu->ranges_base
18828                                              : 0));
18829
18830             /* Value of the DW_AT_ranges attribute is the offset in the
18831                .debug_ranges section.  */
18832             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
18833                                     nullptr))
18834               has_pc_info = 1;
18835           }
18836           break;
18837
18838         default:
18839           break;
18840         }
18841     }
18842
18843   if (high_pc_relative)
18844     highpc += lowpc;
18845
18846   if (has_low_pc_attr && has_high_pc_attr)
18847     {
18848       /* When using the GNU linker, .gnu.linkonce. sections are used to
18849          eliminate duplicate copies of functions and vtables and such.
18850          The linker will arbitrarily choose one and discard the others.
18851          The AT_*_pc values for such functions refer to local labels in
18852          these sections.  If the section from that file was discarded, the
18853          labels are not in the output, so the relocs get a value of 0.
18854          If this is a discarded function, mark the pc bounds as invalid,
18855          so that GDB will ignore it.  */
18856       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18857         {
18858           struct objfile *objfile = dwarf2_per_objfile->objfile;
18859           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18860
18861           complaint (_("DW_AT_low_pc %s is zero "
18862                        "for DIE at %s [in module %s]"),
18863                      paddress (gdbarch, lowpc),
18864                      sect_offset_str (sect_off),
18865                      objfile_name (objfile));
18866         }
18867       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18868       else if (lowpc >= highpc)
18869         {
18870           struct objfile *objfile = dwarf2_per_objfile->objfile;
18871           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18872
18873           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18874                        "for DIE at %s [in module %s]"),
18875                      paddress (gdbarch, lowpc),
18876                      paddress (gdbarch, highpc),
18877                      sect_offset_str (sect_off),
18878                      objfile_name (objfile));
18879         }
18880       else
18881         has_pc_info = 1;
18882     }
18883
18884   return info_ptr;
18885 }
18886
18887 /* Find a cached partial DIE at OFFSET in CU.  */
18888
18889 struct partial_die_info *
18890 dwarf2_cu::find_partial_die (sect_offset sect_off)
18891 {
18892   struct partial_die_info *lookup_die = NULL;
18893   struct partial_die_info part_die (sect_off);
18894
18895   lookup_die = ((struct partial_die_info *)
18896                 htab_find_with_hash (partial_dies, &part_die,
18897                                      to_underlying (sect_off)));
18898
18899   return lookup_die;
18900 }
18901
18902 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18903    except in the case of .debug_types DIEs which do not reference
18904    outside their CU (they do however referencing other types via
18905    DW_FORM_ref_sig8).  */
18906
18907 static const struct cu_partial_die_info
18908 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18909 {
18910   struct dwarf2_per_objfile *dwarf2_per_objfile
18911     = cu->per_cu->dwarf2_per_objfile;
18912   struct objfile *objfile = dwarf2_per_objfile->objfile;
18913   struct dwarf2_per_cu_data *per_cu = NULL;
18914   struct partial_die_info *pd = NULL;
18915
18916   if (offset_in_dwz == cu->per_cu->is_dwz
18917       && offset_in_cu_p (&cu->header, sect_off))
18918     {
18919       pd = cu->find_partial_die (sect_off);
18920       if (pd != NULL)
18921         return { cu, pd };
18922       /* We missed recording what we needed.
18923          Load all dies and try again.  */
18924       per_cu = cu->per_cu;
18925     }
18926   else
18927     {
18928       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18929       if (cu->per_cu->is_debug_types)
18930         {
18931           error (_("Dwarf Error: Type Unit at offset %s contains"
18932                    " external reference to offset %s [in module %s].\n"),
18933                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18934                  bfd_get_filename (objfile->obfd));
18935         }
18936       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18937                                                  dwarf2_per_objfile);
18938
18939       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18940         load_partial_comp_unit (per_cu);
18941
18942       per_cu->cu->last_used = 0;
18943       pd = per_cu->cu->find_partial_die (sect_off);
18944     }
18945
18946   /* If we didn't find it, and not all dies have been loaded,
18947      load them all and try again.  */
18948
18949   if (pd == NULL && per_cu->load_all_dies == 0)
18950     {
18951       per_cu->load_all_dies = 1;
18952
18953       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18954          THIS_CU->cu may already be in use.  So we can't just free it and
18955          replace its DIEs with the ones we read in.  Instead, we leave those
18956          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18957          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18958          set.  */
18959       load_partial_comp_unit (per_cu);
18960
18961       pd = per_cu->cu->find_partial_die (sect_off);
18962     }
18963
18964   if (pd == NULL)
18965     internal_error (__FILE__, __LINE__,
18966                     _("could not find partial DIE %s "
18967                       "in cache [from module %s]\n"),
18968                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18969   return { per_cu->cu, pd };
18970 }
18971
18972 /* See if we can figure out if the class lives in a namespace.  We do
18973    this by looking for a member function; its demangled name will
18974    contain namespace info, if there is any.  */
18975
18976 static void
18977 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18978                                   struct dwarf2_cu *cu)
18979 {
18980   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18981      what template types look like, because the demangler
18982      frequently doesn't give the same name as the debug info.  We
18983      could fix this by only using the demangled name to get the
18984      prefix (but see comment in read_structure_type).  */
18985
18986   struct partial_die_info *real_pdi;
18987   struct partial_die_info *child_pdi;
18988
18989   /* If this DIE (this DIE's specification, if any) has a parent, then
18990      we should not do this.  We'll prepend the parent's fully qualified
18991      name when we create the partial symbol.  */
18992
18993   real_pdi = struct_pdi;
18994   while (real_pdi->has_specification)
18995     {
18996       auto res = find_partial_die (real_pdi->spec_offset,
18997                                    real_pdi->spec_is_dwz, cu);
18998       real_pdi = res.pdi;
18999       cu = res.cu;
19000     }
19001
19002   if (real_pdi->die_parent != NULL)
19003     return;
19004
19005   for (child_pdi = struct_pdi->die_child;
19006        child_pdi != NULL;
19007        child_pdi = child_pdi->die_sibling)
19008     {
19009       if (child_pdi->tag == DW_TAG_subprogram
19010           && child_pdi->linkage_name != NULL)
19011         {
19012           char *actual_class_name
19013             = language_class_name_from_physname (cu->language_defn,
19014                                                  child_pdi->linkage_name);
19015           if (actual_class_name != NULL)
19016             {
19017               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19018               struct_pdi->name
19019                 = ((const char *)
19020                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
19021                                   actual_class_name,
19022                                   strlen (actual_class_name)));
19023               xfree (actual_class_name);
19024             }
19025           break;
19026         }
19027     }
19028 }
19029
19030 void
19031 partial_die_info::fixup (struct dwarf2_cu *cu)
19032 {
19033   /* Once we've fixed up a die, there's no point in doing so again.
19034      This also avoids a memory leak if we were to call
19035      guess_partial_die_structure_name multiple times.  */
19036   if (fixup_called)
19037     return;
19038
19039   /* If we found a reference attribute and the DIE has no name, try
19040      to find a name in the referred to DIE.  */
19041
19042   if (name == NULL && has_specification)
19043     {
19044       struct partial_die_info *spec_die;
19045
19046       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
19047       spec_die = res.pdi;
19048       cu = res.cu;
19049
19050       spec_die->fixup (cu);
19051
19052       if (spec_die->name)
19053         {
19054           name = spec_die->name;
19055
19056           /* Copy DW_AT_external attribute if it is set.  */
19057           if (spec_die->is_external)
19058             is_external = spec_die->is_external;
19059         }
19060     }
19061
19062   /* Set default names for some unnamed DIEs.  */
19063
19064   if (name == NULL && tag == DW_TAG_namespace)
19065     name = CP_ANONYMOUS_NAMESPACE_STR;
19066
19067   /* If there is no parent die to provide a namespace, and there are
19068      children, see if we can determine the namespace from their linkage
19069      name.  */
19070   if (cu->language == language_cplus
19071       && !VEC_empty (dwarf2_section_info_def,
19072                      cu->per_cu->dwarf2_per_objfile->types)
19073       && die_parent == NULL
19074       && has_children
19075       && (tag == DW_TAG_class_type
19076           || tag == DW_TAG_structure_type
19077           || tag == DW_TAG_union_type))
19078     guess_partial_die_structure_name (this, cu);
19079
19080   /* GCC might emit a nameless struct or union that has a linkage
19081      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19082   if (name == NULL
19083       && (tag == DW_TAG_class_type
19084           || tag == DW_TAG_interface_type
19085           || tag == DW_TAG_structure_type
19086           || tag == DW_TAG_union_type)
19087       && linkage_name != NULL)
19088     {
19089       char *demangled;
19090
19091       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
19092       if (demangled)
19093         {
19094           const char *base;
19095
19096           /* Strip any leading namespaces/classes, keep only the base name.
19097              DW_AT_name for named DIEs does not contain the prefixes.  */
19098           base = strrchr (demangled, ':');
19099           if (base && base > demangled && base[-1] == ':')
19100             base++;
19101           else
19102             base = demangled;
19103
19104           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19105           name
19106             = ((const char *)
19107                obstack_copy0 (&objfile->per_bfd->storage_obstack,
19108                               base, strlen (base)));
19109           xfree (demangled);
19110         }
19111     }
19112
19113   fixup_called = 1;
19114 }
19115
19116 /* Read an attribute value described by an attribute form.  */
19117
19118 static const gdb_byte *
19119 read_attribute_value (const struct die_reader_specs *reader,
19120                       struct attribute *attr, unsigned form,
19121                       LONGEST implicit_const, const gdb_byte *info_ptr)
19122 {
19123   struct dwarf2_cu *cu = reader->cu;
19124   struct dwarf2_per_objfile *dwarf2_per_objfile
19125     = cu->per_cu->dwarf2_per_objfile;
19126   struct objfile *objfile = dwarf2_per_objfile->objfile;
19127   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19128   bfd *abfd = reader->abfd;
19129   struct comp_unit_head *cu_header = &cu->header;
19130   unsigned int bytes_read;
19131   struct dwarf_block *blk;
19132
19133   attr->form = (enum dwarf_form) form;
19134   switch (form)
19135     {
19136     case DW_FORM_ref_addr:
19137       if (cu->header.version == 2)
19138         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19139       else
19140         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19141                                        &cu->header, &bytes_read);
19142       info_ptr += bytes_read;
19143       break;
19144     case DW_FORM_GNU_ref_alt:
19145       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19146       info_ptr += bytes_read;
19147       break;
19148     case DW_FORM_addr:
19149       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19150       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19151       info_ptr += bytes_read;
19152       break;
19153     case DW_FORM_block2:
19154       blk = dwarf_alloc_block (cu);
19155       blk->size = read_2_bytes (abfd, info_ptr);
19156       info_ptr += 2;
19157       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19158       info_ptr += blk->size;
19159       DW_BLOCK (attr) = blk;
19160       break;
19161     case DW_FORM_block4:
19162       blk = dwarf_alloc_block (cu);
19163       blk->size = read_4_bytes (abfd, info_ptr);
19164       info_ptr += 4;
19165       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19166       info_ptr += blk->size;
19167       DW_BLOCK (attr) = blk;
19168       break;
19169     case DW_FORM_data2:
19170       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19171       info_ptr += 2;
19172       break;
19173     case DW_FORM_data4:
19174       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19175       info_ptr += 4;
19176       break;
19177     case DW_FORM_data8:
19178       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19179       info_ptr += 8;
19180       break;
19181     case DW_FORM_data16:
19182       blk = dwarf_alloc_block (cu);
19183       blk->size = 16;
19184       blk->data = read_n_bytes (abfd, info_ptr, 16);
19185       info_ptr += 16;
19186       DW_BLOCK (attr) = blk;
19187       break;
19188     case DW_FORM_sec_offset:
19189       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19190       info_ptr += bytes_read;
19191       break;
19192     case DW_FORM_string:
19193       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19194       DW_STRING_IS_CANONICAL (attr) = 0;
19195       info_ptr += bytes_read;
19196       break;
19197     case DW_FORM_strp:
19198       if (!cu->per_cu->is_dwz)
19199         {
19200           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19201                                                    abfd, info_ptr, cu_header,
19202                                                    &bytes_read);
19203           DW_STRING_IS_CANONICAL (attr) = 0;
19204           info_ptr += bytes_read;
19205           break;
19206         }
19207       /* FALLTHROUGH */
19208     case DW_FORM_line_strp:
19209       if (!cu->per_cu->is_dwz)
19210         {
19211           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19212                                                         abfd, info_ptr,
19213                                                         cu_header, &bytes_read);
19214           DW_STRING_IS_CANONICAL (attr) = 0;
19215           info_ptr += bytes_read;
19216           break;
19217         }
19218       /* FALLTHROUGH */
19219     case DW_FORM_GNU_strp_alt:
19220       {
19221         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19222         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19223                                           &bytes_read);
19224
19225         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19226                                                           dwz, str_offset);
19227         DW_STRING_IS_CANONICAL (attr) = 0;
19228         info_ptr += bytes_read;
19229       }
19230       break;
19231     case DW_FORM_exprloc:
19232     case DW_FORM_block:
19233       blk = dwarf_alloc_block (cu);
19234       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19235       info_ptr += bytes_read;
19236       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19237       info_ptr += blk->size;
19238       DW_BLOCK (attr) = blk;
19239       break;
19240     case DW_FORM_block1:
19241       blk = dwarf_alloc_block (cu);
19242       blk->size = read_1_byte (abfd, info_ptr);
19243       info_ptr += 1;
19244       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19245       info_ptr += blk->size;
19246       DW_BLOCK (attr) = blk;
19247       break;
19248     case DW_FORM_data1:
19249       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19250       info_ptr += 1;
19251       break;
19252     case DW_FORM_flag:
19253       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19254       info_ptr += 1;
19255       break;
19256     case DW_FORM_flag_present:
19257       DW_UNSND (attr) = 1;
19258       break;
19259     case DW_FORM_sdata:
19260       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19261       info_ptr += bytes_read;
19262       break;
19263     case DW_FORM_udata:
19264       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19265       info_ptr += bytes_read;
19266       break;
19267     case DW_FORM_ref1:
19268       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19269                          + read_1_byte (abfd, info_ptr));
19270       info_ptr += 1;
19271       break;
19272     case DW_FORM_ref2:
19273       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19274                          + read_2_bytes (abfd, info_ptr));
19275       info_ptr += 2;
19276       break;
19277     case DW_FORM_ref4:
19278       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19279                          + read_4_bytes (abfd, info_ptr));
19280       info_ptr += 4;
19281       break;
19282     case DW_FORM_ref8:
19283       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19284                          + read_8_bytes (abfd, info_ptr));
19285       info_ptr += 8;
19286       break;
19287     case DW_FORM_ref_sig8:
19288       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19289       info_ptr += 8;
19290       break;
19291     case DW_FORM_ref_udata:
19292       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19293                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19294       info_ptr += bytes_read;
19295       break;
19296     case DW_FORM_indirect:
19297       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19298       info_ptr += bytes_read;
19299       if (form == DW_FORM_implicit_const)
19300         {
19301           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19302           info_ptr += bytes_read;
19303         }
19304       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19305                                        info_ptr);
19306       break;
19307     case DW_FORM_implicit_const:
19308       DW_SND (attr) = implicit_const;
19309       break;
19310     case DW_FORM_addrx:
19311     case DW_FORM_GNU_addr_index:
19312       if (reader->dwo_file == NULL)
19313         {
19314           /* For now flag a hard error.
19315              Later we can turn this into a complaint.  */
19316           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19317                  dwarf_form_name (form),
19318                  bfd_get_filename (abfd));
19319         }
19320       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19321       info_ptr += bytes_read;
19322       break;
19323     case DW_FORM_strx:
19324     case DW_FORM_strx1:
19325     case DW_FORM_strx2:
19326     case DW_FORM_strx3:
19327     case DW_FORM_strx4:
19328     case DW_FORM_GNU_str_index:
19329       if (reader->dwo_file == NULL)
19330         {
19331           /* For now flag a hard error.
19332              Later we can turn this into a complaint if warranted.  */
19333           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19334                  dwarf_form_name (form),
19335                  bfd_get_filename (abfd));
19336         }
19337       {
19338         ULONGEST str_index;
19339         if (form == DW_FORM_strx1)
19340           {
19341             str_index = read_1_byte (abfd, info_ptr);
19342             info_ptr += 1;
19343           }
19344         else if (form == DW_FORM_strx2)
19345           {
19346             str_index = read_2_bytes (abfd, info_ptr);
19347             info_ptr += 2;
19348           }
19349         else if (form == DW_FORM_strx3)
19350           {
19351             str_index = read_3_bytes (abfd, info_ptr);
19352             info_ptr += 3;
19353           }
19354         else if (form == DW_FORM_strx4)
19355           {
19356             str_index = read_4_bytes (abfd, info_ptr);
19357             info_ptr += 4;
19358           }
19359         else
19360           {
19361             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19362             info_ptr += bytes_read;
19363           }
19364         DW_STRING (attr) = read_str_index (reader, str_index);
19365         DW_STRING_IS_CANONICAL (attr) = 0;
19366       }
19367       break;
19368     default:
19369       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19370              dwarf_form_name (form),
19371              bfd_get_filename (abfd));
19372     }
19373
19374   /* Super hack.  */
19375   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19376     attr->form = DW_FORM_GNU_ref_alt;
19377
19378   /* We have seen instances where the compiler tried to emit a byte
19379      size attribute of -1 which ended up being encoded as an unsigned
19380      0xffffffff.  Although 0xffffffff is technically a valid size value,
19381      an object of this size seems pretty unlikely so we can relatively
19382      safely treat these cases as if the size attribute was invalid and
19383      treat them as zero by default.  */
19384   if (attr->name == DW_AT_byte_size
19385       && form == DW_FORM_data4
19386       && DW_UNSND (attr) >= 0xffffffff)
19387     {
19388       complaint
19389         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19390          hex_string (DW_UNSND (attr)));
19391       DW_UNSND (attr) = 0;
19392     }
19393
19394   return info_ptr;
19395 }
19396
19397 /* Read an attribute described by an abbreviated attribute.  */
19398
19399 static const gdb_byte *
19400 read_attribute (const struct die_reader_specs *reader,
19401                 struct attribute *attr, struct attr_abbrev *abbrev,
19402                 const gdb_byte *info_ptr)
19403 {
19404   attr->name = abbrev->name;
19405   return read_attribute_value (reader, attr, abbrev->form,
19406                                abbrev->implicit_const, info_ptr);
19407 }
19408
19409 /* Read dwarf information from a buffer.  */
19410
19411 static unsigned int
19412 read_1_byte (bfd *abfd, const gdb_byte *buf)
19413 {
19414   return bfd_get_8 (abfd, buf);
19415 }
19416
19417 static int
19418 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19419 {
19420   return bfd_get_signed_8 (abfd, buf);
19421 }
19422
19423 static unsigned int
19424 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19425 {
19426   return bfd_get_16 (abfd, buf);
19427 }
19428
19429 static int
19430 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19431 {
19432   return bfd_get_signed_16 (abfd, buf);
19433 }
19434
19435 static unsigned int
19436 read_3_bytes (bfd *abfd, const gdb_byte *buf)
19437 {
19438   unsigned int result = 0;
19439   for (int i = 0; i < 3; ++i)
19440     {
19441       unsigned char byte = bfd_get_8 (abfd, buf);
19442       buf++;
19443       result |= ((unsigned int) byte << (i * 8));
19444     }
19445   return result;
19446 }
19447
19448 static unsigned int
19449 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19450 {
19451   return bfd_get_32 (abfd, buf);
19452 }
19453
19454 static int
19455 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19456 {
19457   return bfd_get_signed_32 (abfd, buf);
19458 }
19459
19460 static ULONGEST
19461 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19462 {
19463   return bfd_get_64 (abfd, buf);
19464 }
19465
19466 static CORE_ADDR
19467 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19468               unsigned int *bytes_read)
19469 {
19470   struct comp_unit_head *cu_header = &cu->header;
19471   CORE_ADDR retval = 0;
19472
19473   if (cu_header->signed_addr_p)
19474     {
19475       switch (cu_header->addr_size)
19476         {
19477         case 2:
19478           retval = bfd_get_signed_16 (abfd, buf);
19479           break;
19480         case 4:
19481           retval = bfd_get_signed_32 (abfd, buf);
19482           break;
19483         case 8:
19484           retval = bfd_get_signed_64 (abfd, buf);
19485           break;
19486         default:
19487           internal_error (__FILE__, __LINE__,
19488                           _("read_address: bad switch, signed [in module %s]"),
19489                           bfd_get_filename (abfd));
19490         }
19491     }
19492   else
19493     {
19494       switch (cu_header->addr_size)
19495         {
19496         case 2:
19497           retval = bfd_get_16 (abfd, buf);
19498           break;
19499         case 4:
19500           retval = bfd_get_32 (abfd, buf);
19501           break;
19502         case 8:
19503           retval = bfd_get_64 (abfd, buf);
19504           break;
19505         default:
19506           internal_error (__FILE__, __LINE__,
19507                           _("read_address: bad switch, "
19508                             "unsigned [in module %s]"),
19509                           bfd_get_filename (abfd));
19510         }
19511     }
19512
19513   *bytes_read = cu_header->addr_size;
19514   return retval;
19515 }
19516
19517 /* Read the initial length from a section.  The (draft) DWARF 3
19518    specification allows the initial length to take up either 4 bytes
19519    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19520    bytes describe the length and all offsets will be 8 bytes in length
19521    instead of 4.
19522
19523    An older, non-standard 64-bit format is also handled by this
19524    function.  The older format in question stores the initial length
19525    as an 8-byte quantity without an escape value.  Lengths greater
19526    than 2^32 aren't very common which means that the initial 4 bytes
19527    is almost always zero.  Since a length value of zero doesn't make
19528    sense for the 32-bit format, this initial zero can be considered to
19529    be an escape value which indicates the presence of the older 64-bit
19530    format.  As written, the code can't detect (old format) lengths
19531    greater than 4GB.  If it becomes necessary to handle lengths
19532    somewhat larger than 4GB, we could allow other small values (such
19533    as the non-sensical values of 1, 2, and 3) to also be used as
19534    escape values indicating the presence of the old format.
19535
19536    The value returned via bytes_read should be used to increment the
19537    relevant pointer after calling read_initial_length().
19538
19539    [ Note:  read_initial_length() and read_offset() are based on the
19540      document entitled "DWARF Debugging Information Format", revision
19541      3, draft 8, dated November 19, 2001.  This document was obtained
19542      from:
19543
19544         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19545
19546      This document is only a draft and is subject to change.  (So beware.)
19547
19548      Details regarding the older, non-standard 64-bit format were
19549      determined empirically by examining 64-bit ELF files produced by
19550      the SGI toolchain on an IRIX 6.5 machine.
19551
19552      - Kevin, July 16, 2002
19553    ] */
19554
19555 static LONGEST
19556 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19557 {
19558   LONGEST length = bfd_get_32 (abfd, buf);
19559
19560   if (length == 0xffffffff)
19561     {
19562       length = bfd_get_64 (abfd, buf + 4);
19563       *bytes_read = 12;
19564     }
19565   else if (length == 0)
19566     {
19567       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19568       length = bfd_get_64 (abfd, buf);
19569       *bytes_read = 8;
19570     }
19571   else
19572     {
19573       *bytes_read = 4;
19574     }
19575
19576   return length;
19577 }
19578
19579 /* Cover function for read_initial_length.
19580    Returns the length of the object at BUF, and stores the size of the
19581    initial length in *BYTES_READ and stores the size that offsets will be in
19582    *OFFSET_SIZE.
19583    If the initial length size is not equivalent to that specified in
19584    CU_HEADER then issue a complaint.
19585    This is useful when reading non-comp-unit headers.  */
19586
19587 static LONGEST
19588 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19589                                         const struct comp_unit_head *cu_header,
19590                                         unsigned int *bytes_read,
19591                                         unsigned int *offset_size)
19592 {
19593   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19594
19595   gdb_assert (cu_header->initial_length_size == 4
19596               || cu_header->initial_length_size == 8
19597               || cu_header->initial_length_size == 12);
19598
19599   if (cu_header->initial_length_size != *bytes_read)
19600     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19601
19602   *offset_size = (*bytes_read == 4) ? 4 : 8;
19603   return length;
19604 }
19605
19606 /* Read an offset from the data stream.  The size of the offset is
19607    given by cu_header->offset_size.  */
19608
19609 static LONGEST
19610 read_offset (bfd *abfd, const gdb_byte *buf,
19611              const struct comp_unit_head *cu_header,
19612              unsigned int *bytes_read)
19613 {
19614   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19615
19616   *bytes_read = cu_header->offset_size;
19617   return offset;
19618 }
19619
19620 /* Read an offset from the data stream.  */
19621
19622 static LONGEST
19623 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19624 {
19625   LONGEST retval = 0;
19626
19627   switch (offset_size)
19628     {
19629     case 4:
19630       retval = bfd_get_32 (abfd, buf);
19631       break;
19632     case 8:
19633       retval = bfd_get_64 (abfd, buf);
19634       break;
19635     default:
19636       internal_error (__FILE__, __LINE__,
19637                       _("read_offset_1: bad switch [in module %s]"),
19638                       bfd_get_filename (abfd));
19639     }
19640
19641   return retval;
19642 }
19643
19644 static const gdb_byte *
19645 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19646 {
19647   /* If the size of a host char is 8 bits, we can return a pointer
19648      to the buffer, otherwise we have to copy the data to a buffer
19649      allocated on the temporary obstack.  */
19650   gdb_assert (HOST_CHAR_BIT == 8);
19651   return buf;
19652 }
19653
19654 static const char *
19655 read_direct_string (bfd *abfd, const gdb_byte *buf,
19656                     unsigned int *bytes_read_ptr)
19657 {
19658   /* If the size of a host char is 8 bits, we can return a pointer
19659      to the string, otherwise we have to copy the string to a buffer
19660      allocated on the temporary obstack.  */
19661   gdb_assert (HOST_CHAR_BIT == 8);
19662   if (*buf == '\0')
19663     {
19664       *bytes_read_ptr = 1;
19665       return NULL;
19666     }
19667   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19668   return (const char *) buf;
19669 }
19670
19671 /* Return pointer to string at section SECT offset STR_OFFSET with error
19672    reporting strings FORM_NAME and SECT_NAME.  */
19673
19674 static const char *
19675 read_indirect_string_at_offset_from (struct objfile *objfile,
19676                                      bfd *abfd, LONGEST str_offset,
19677                                      struct dwarf2_section_info *sect,
19678                                      const char *form_name,
19679                                      const char *sect_name)
19680 {
19681   dwarf2_read_section (objfile, sect);
19682   if (sect->buffer == NULL)
19683     error (_("%s used without %s section [in module %s]"),
19684            form_name, sect_name, bfd_get_filename (abfd));
19685   if (str_offset >= sect->size)
19686     error (_("%s pointing outside of %s section [in module %s]"),
19687            form_name, sect_name, bfd_get_filename (abfd));
19688   gdb_assert (HOST_CHAR_BIT == 8);
19689   if (sect->buffer[str_offset] == '\0')
19690     return NULL;
19691   return (const char *) (sect->buffer + str_offset);
19692 }
19693
19694 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19695
19696 static const char *
19697 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19698                                 bfd *abfd, LONGEST str_offset)
19699 {
19700   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19701                                               abfd, str_offset,
19702                                               &dwarf2_per_objfile->str,
19703                                               "DW_FORM_strp", ".debug_str");
19704 }
19705
19706 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19707
19708 static const char *
19709 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19710                                      bfd *abfd, LONGEST str_offset)
19711 {
19712   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19713                                               abfd, str_offset,
19714                                               &dwarf2_per_objfile->line_str,
19715                                               "DW_FORM_line_strp",
19716                                               ".debug_line_str");
19717 }
19718
19719 /* Read a string at offset STR_OFFSET in the .debug_str section from
19720    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19721    the string consists of a single NUL byte, return NULL; otherwise
19722    return a pointer to the string.  */
19723
19724 static const char *
19725 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19726                                LONGEST str_offset)
19727 {
19728   dwarf2_read_section (objfile, &dwz->str);
19729
19730   if (dwz->str.buffer == NULL)
19731     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19732              "section [in module %s]"),
19733            bfd_get_filename (dwz->dwz_bfd));
19734   if (str_offset >= dwz->str.size)
19735     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19736              ".debug_str section [in module %s]"),
19737            bfd_get_filename (dwz->dwz_bfd));
19738   gdb_assert (HOST_CHAR_BIT == 8);
19739   if (dwz->str.buffer[str_offset] == '\0')
19740     return NULL;
19741   return (const char *) (dwz->str.buffer + str_offset);
19742 }
19743
19744 /* Return pointer to string at .debug_str offset as read from BUF.
19745    BUF is assumed to be in a compilation unit described by CU_HEADER.
19746    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19747
19748 static const char *
19749 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19750                       const gdb_byte *buf,
19751                       const struct comp_unit_head *cu_header,
19752                       unsigned int *bytes_read_ptr)
19753 {
19754   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19755
19756   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19757 }
19758
19759 /* Return pointer to string at .debug_line_str offset as read from BUF.
19760    BUF is assumed to be in a compilation unit described by CU_HEADER.
19761    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19762
19763 static const char *
19764 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19765                            bfd *abfd, const gdb_byte *buf,
19766                            const struct comp_unit_head *cu_header,
19767                            unsigned int *bytes_read_ptr)
19768 {
19769   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19770
19771   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19772                                               str_offset);
19773 }
19774
19775 ULONGEST
19776 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19777                           unsigned int *bytes_read_ptr)
19778 {
19779   ULONGEST result;
19780   unsigned int num_read;
19781   int shift;
19782   unsigned char byte;
19783
19784   result = 0;
19785   shift = 0;
19786   num_read = 0;
19787   while (1)
19788     {
19789       byte = bfd_get_8 (abfd, buf);
19790       buf++;
19791       num_read++;
19792       result |= ((ULONGEST) (byte & 127) << shift);
19793       if ((byte & 128) == 0)
19794         {
19795           break;
19796         }
19797       shift += 7;
19798     }
19799   *bytes_read_ptr = num_read;
19800   return result;
19801 }
19802
19803 static LONGEST
19804 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19805                     unsigned int *bytes_read_ptr)
19806 {
19807   ULONGEST result;
19808   int shift, num_read;
19809   unsigned char byte;
19810
19811   result = 0;
19812   shift = 0;
19813   num_read = 0;
19814   while (1)
19815     {
19816       byte = bfd_get_8 (abfd, buf);
19817       buf++;
19818       num_read++;
19819       result |= ((ULONGEST) (byte & 127) << shift);
19820       shift += 7;
19821       if ((byte & 128) == 0)
19822         {
19823           break;
19824         }
19825     }
19826   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19827     result |= -(((ULONGEST) 1) << shift);
19828   *bytes_read_ptr = num_read;
19829   return result;
19830 }
19831
19832 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19833    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19834    ADDR_SIZE is the size of addresses from the CU header.  */
19835
19836 static CORE_ADDR
19837 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19838                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19839 {
19840   struct objfile *objfile = dwarf2_per_objfile->objfile;
19841   bfd *abfd = objfile->obfd;
19842   const gdb_byte *info_ptr;
19843
19844   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19845   if (dwarf2_per_objfile->addr.buffer == NULL)
19846     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19847            objfile_name (objfile));
19848   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19849     error (_("DW_FORM_addr_index pointing outside of "
19850              ".debug_addr section [in module %s]"),
19851            objfile_name (objfile));
19852   info_ptr = (dwarf2_per_objfile->addr.buffer
19853               + addr_base + addr_index * addr_size);
19854   if (addr_size == 4)
19855     return bfd_get_32 (abfd, info_ptr);
19856   else
19857     return bfd_get_64 (abfd, info_ptr);
19858 }
19859
19860 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19861
19862 static CORE_ADDR
19863 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19864 {
19865   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19866                             cu->addr_base, cu->header.addr_size);
19867 }
19868
19869 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19870
19871 static CORE_ADDR
19872 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19873                              unsigned int *bytes_read)
19874 {
19875   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19876   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19877
19878   return read_addr_index (cu, addr_index);
19879 }
19880
19881 /* Data structure to pass results from dwarf2_read_addr_index_reader
19882    back to dwarf2_read_addr_index.  */
19883
19884 struct dwarf2_read_addr_index_data
19885 {
19886   ULONGEST addr_base;
19887   int addr_size;
19888 };
19889
19890 /* die_reader_func for dwarf2_read_addr_index.  */
19891
19892 static void
19893 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19894                                const gdb_byte *info_ptr,
19895                                struct die_info *comp_unit_die,
19896                                int has_children,
19897                                void *data)
19898 {
19899   struct dwarf2_cu *cu = reader->cu;
19900   struct dwarf2_read_addr_index_data *aidata =
19901     (struct dwarf2_read_addr_index_data *) data;
19902
19903   aidata->addr_base = cu->addr_base;
19904   aidata->addr_size = cu->header.addr_size;
19905 }
19906
19907 /* Given an index in .debug_addr, fetch the value.
19908    NOTE: This can be called during dwarf expression evaluation,
19909    long after the debug information has been read, and thus per_cu->cu
19910    may no longer exist.  */
19911
19912 CORE_ADDR
19913 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19914                         unsigned int addr_index)
19915 {
19916   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19917   struct dwarf2_cu *cu = per_cu->cu;
19918   ULONGEST addr_base;
19919   int addr_size;
19920
19921   /* We need addr_base and addr_size.
19922      If we don't have PER_CU->cu, we have to get it.
19923      Nasty, but the alternative is storing the needed info in PER_CU,
19924      which at this point doesn't seem justified: it's not clear how frequently
19925      it would get used and it would increase the size of every PER_CU.
19926      Entry points like dwarf2_per_cu_addr_size do a similar thing
19927      so we're not in uncharted territory here.
19928      Alas we need to be a bit more complicated as addr_base is contained
19929      in the DIE.
19930
19931      We don't need to read the entire CU(/TU).
19932      We just need the header and top level die.
19933
19934      IWBN to use the aging mechanism to let us lazily later discard the CU.
19935      For now we skip this optimization.  */
19936
19937   if (cu != NULL)
19938     {
19939       addr_base = cu->addr_base;
19940       addr_size = cu->header.addr_size;
19941     }
19942   else
19943     {
19944       struct dwarf2_read_addr_index_data aidata;
19945
19946       /* Note: We can't use init_cutu_and_read_dies_simple here,
19947          we need addr_base.  */
19948       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19949                                dwarf2_read_addr_index_reader, &aidata);
19950       addr_base = aidata.addr_base;
19951       addr_size = aidata.addr_size;
19952     }
19953
19954   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19955                             addr_size);
19956 }
19957
19958 /* Given a DW_FORM_GNU_str_index or DW_FORM_strx, fetch the string.
19959    This is only used by the Fission support.  */
19960
19961 static const char *
19962 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19963 {
19964   struct dwarf2_cu *cu = reader->cu;
19965   struct dwarf2_per_objfile *dwarf2_per_objfile
19966     = cu->per_cu->dwarf2_per_objfile;
19967   struct objfile *objfile = dwarf2_per_objfile->objfile;
19968   const char *objf_name = objfile_name (objfile);
19969   bfd *abfd = objfile->obfd;
19970   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19971   struct dwarf2_section_info *str_offsets_section =
19972     &reader->dwo_file->sections.str_offsets;
19973   const gdb_byte *info_ptr;
19974   ULONGEST str_offset;
19975   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
19976
19977   dwarf2_read_section (objfile, str_section);
19978   dwarf2_read_section (objfile, str_offsets_section);
19979   if (str_section->buffer == NULL)
19980     error (_("%s used without .debug_str.dwo section"
19981              " in CU at offset %s [in module %s]"),
19982            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19983   if (str_offsets_section->buffer == NULL)
19984     error (_("%s used without .debug_str_offsets.dwo section"
19985              " in CU at offset %s [in module %s]"),
19986            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19987   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19988     error (_("%s pointing outside of .debug_str_offsets.dwo"
19989              " section in CU at offset %s [in module %s]"),
19990            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19991   info_ptr = (str_offsets_section->buffer
19992               + str_index * cu->header.offset_size);
19993   if (cu->header.offset_size == 4)
19994     str_offset = bfd_get_32 (abfd, info_ptr);
19995   else
19996     str_offset = bfd_get_64 (abfd, info_ptr);
19997   if (str_offset >= str_section->size)
19998     error (_("Offset from %s pointing outside of"
19999              " .debug_str.dwo section in CU at offset %s [in module %s]"),
20000            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20001   return (const char *) (str_section->buffer + str_offset);
20002 }
20003
20004 /* Return the length of an LEB128 number in BUF.  */
20005
20006 static int
20007 leb128_size (const gdb_byte *buf)
20008 {
20009   const gdb_byte *begin = buf;
20010   gdb_byte byte;
20011
20012   while (1)
20013     {
20014       byte = *buf++;
20015       if ((byte & 128) == 0)
20016         return buf - begin;
20017     }
20018 }
20019
20020 static void
20021 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
20022 {
20023   switch (lang)
20024     {
20025     case DW_LANG_C89:
20026     case DW_LANG_C99:
20027     case DW_LANG_C11:
20028     case DW_LANG_C:
20029     case DW_LANG_UPC:
20030       cu->language = language_c;
20031       break;
20032     case DW_LANG_Java:
20033     case DW_LANG_C_plus_plus:
20034     case DW_LANG_C_plus_plus_11:
20035     case DW_LANG_C_plus_plus_14:
20036       cu->language = language_cplus;
20037       break;
20038     case DW_LANG_D:
20039       cu->language = language_d;
20040       break;
20041     case DW_LANG_Fortran77:
20042     case DW_LANG_Fortran90:
20043     case DW_LANG_Fortran95:
20044     case DW_LANG_Fortran03:
20045     case DW_LANG_Fortran08:
20046       cu->language = language_fortran;
20047       break;
20048     case DW_LANG_Go:
20049       cu->language = language_go;
20050       break;
20051     case DW_LANG_Mips_Assembler:
20052       cu->language = language_asm;
20053       break;
20054     case DW_LANG_Ada83:
20055     case DW_LANG_Ada95:
20056       cu->language = language_ada;
20057       break;
20058     case DW_LANG_Modula2:
20059       cu->language = language_m2;
20060       break;
20061     case DW_LANG_Pascal83:
20062       cu->language = language_pascal;
20063       break;
20064     case DW_LANG_ObjC:
20065       cu->language = language_objc;
20066       break;
20067     case DW_LANG_Rust:
20068     case DW_LANG_Rust_old:
20069       cu->language = language_rust;
20070       break;
20071     case DW_LANG_Cobol74:
20072     case DW_LANG_Cobol85:
20073     default:
20074       cu->language = language_minimal;
20075       break;
20076     }
20077   cu->language_defn = language_def (cu->language);
20078 }
20079
20080 /* Return the named attribute or NULL if not there.  */
20081
20082 static struct attribute *
20083 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20084 {
20085   for (;;)
20086     {
20087       unsigned int i;
20088       struct attribute *spec = NULL;
20089
20090       for (i = 0; i < die->num_attrs; ++i)
20091         {
20092           if (die->attrs[i].name == name)
20093             return &die->attrs[i];
20094           if (die->attrs[i].name == DW_AT_specification
20095               || die->attrs[i].name == DW_AT_abstract_origin)
20096             spec = &die->attrs[i];
20097         }
20098
20099       if (!spec)
20100         break;
20101
20102       die = follow_die_ref (die, spec, &cu);
20103     }
20104
20105   return NULL;
20106 }
20107
20108 /* Return the named attribute or NULL if not there,
20109    but do not follow DW_AT_specification, etc.
20110    This is for use in contexts where we're reading .debug_types dies.
20111    Following DW_AT_specification, DW_AT_abstract_origin will take us
20112    back up the chain, and we want to go down.  */
20113
20114 static struct attribute *
20115 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
20116 {
20117   unsigned int i;
20118
20119   for (i = 0; i < die->num_attrs; ++i)
20120     if (die->attrs[i].name == name)
20121       return &die->attrs[i];
20122
20123   return NULL;
20124 }
20125
20126 /* Return the string associated with a string-typed attribute, or NULL if it
20127    is either not found or is of an incorrect type.  */
20128
20129 static const char *
20130 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20131 {
20132   struct attribute *attr;
20133   const char *str = NULL;
20134
20135   attr = dwarf2_attr (die, name, cu);
20136
20137   if (attr != NULL)
20138     {
20139       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20140           || attr->form == DW_FORM_string
20141           || attr->form == DW_FORM_strx
20142           || attr->form == DW_FORM_GNU_str_index
20143           || attr->form == DW_FORM_GNU_strp_alt)
20144         str = DW_STRING (attr);
20145       else
20146         complaint (_("string type expected for attribute %s for "
20147                      "DIE at %s in module %s"),
20148                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
20149                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
20150     }
20151
20152   return str;
20153 }
20154
20155 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20156    and holds a non-zero value.  This function should only be used for
20157    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20158
20159 static int
20160 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20161 {
20162   struct attribute *attr = dwarf2_attr (die, name, cu);
20163
20164   return (attr && DW_UNSND (attr));
20165 }
20166
20167 static int
20168 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20169 {
20170   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20171      which value is non-zero.  However, we have to be careful with
20172      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20173      (via dwarf2_flag_true_p) follows this attribute.  So we may
20174      end up accidently finding a declaration attribute that belongs
20175      to a different DIE referenced by the specification attribute,
20176      even though the given DIE does not have a declaration attribute.  */
20177   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20178           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20179 }
20180
20181 /* Return the die giving the specification for DIE, if there is
20182    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20183    containing the return value on output.  If there is no
20184    specification, but there is an abstract origin, that is
20185    returned.  */
20186
20187 static struct die_info *
20188 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20189 {
20190   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20191                                              *spec_cu);
20192
20193   if (spec_attr == NULL)
20194     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20195
20196   if (spec_attr == NULL)
20197     return NULL;
20198   else
20199     return follow_die_ref (die, spec_attr, spec_cu);
20200 }
20201
20202 /* Stub for free_line_header to match void * callback types.  */
20203
20204 static void
20205 free_line_header_voidp (void *arg)
20206 {
20207   struct line_header *lh = (struct line_header *) arg;
20208
20209   delete lh;
20210 }
20211
20212 void
20213 line_header::add_include_dir (const char *include_dir)
20214 {
20215   if (dwarf_line_debug >= 2)
20216     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20217                         include_dirs.size () + 1, include_dir);
20218
20219   include_dirs.push_back (include_dir);
20220 }
20221
20222 void
20223 line_header::add_file_name (const char *name,
20224                             dir_index d_index,
20225                             unsigned int mod_time,
20226                             unsigned int length)
20227 {
20228   if (dwarf_line_debug >= 2)
20229     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20230                         (unsigned) file_names.size () + 1, name);
20231
20232   file_names.emplace_back (name, d_index, mod_time, length);
20233 }
20234
20235 /* A convenience function to find the proper .debug_line section for a CU.  */
20236
20237 static struct dwarf2_section_info *
20238 get_debug_line_section (struct dwarf2_cu *cu)
20239 {
20240   struct dwarf2_section_info *section;
20241   struct dwarf2_per_objfile *dwarf2_per_objfile
20242     = cu->per_cu->dwarf2_per_objfile;
20243
20244   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20245      DWO file.  */
20246   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20247     section = &cu->dwo_unit->dwo_file->sections.line;
20248   else if (cu->per_cu->is_dwz)
20249     {
20250       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20251
20252       section = &dwz->line;
20253     }
20254   else
20255     section = &dwarf2_per_objfile->line;
20256
20257   return section;
20258 }
20259
20260 /* Read directory or file name entry format, starting with byte of
20261    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20262    entries count and the entries themselves in the described entry
20263    format.  */
20264
20265 static void
20266 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20267                         bfd *abfd, const gdb_byte **bufp,
20268                         struct line_header *lh,
20269                         const struct comp_unit_head *cu_header,
20270                         void (*callback) (struct line_header *lh,
20271                                           const char *name,
20272                                           dir_index d_index,
20273                                           unsigned int mod_time,
20274                                           unsigned int length))
20275 {
20276   gdb_byte format_count, formati;
20277   ULONGEST data_count, datai;
20278   const gdb_byte *buf = *bufp;
20279   const gdb_byte *format_header_data;
20280   unsigned int bytes_read;
20281
20282   format_count = read_1_byte (abfd, buf);
20283   buf += 1;
20284   format_header_data = buf;
20285   for (formati = 0; formati < format_count; formati++)
20286     {
20287       read_unsigned_leb128 (abfd, buf, &bytes_read);
20288       buf += bytes_read;
20289       read_unsigned_leb128 (abfd, buf, &bytes_read);
20290       buf += bytes_read;
20291     }
20292
20293   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20294   buf += bytes_read;
20295   for (datai = 0; datai < data_count; datai++)
20296     {
20297       const gdb_byte *format = format_header_data;
20298       struct file_entry fe;
20299
20300       for (formati = 0; formati < format_count; formati++)
20301         {
20302           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20303           format += bytes_read;
20304
20305           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20306           format += bytes_read;
20307
20308           gdb::optional<const char *> string;
20309           gdb::optional<unsigned int> uint;
20310
20311           switch (form)
20312             {
20313             case DW_FORM_string:
20314               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20315               buf += bytes_read;
20316               break;
20317
20318             case DW_FORM_line_strp:
20319               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20320                                                          abfd, buf,
20321                                                          cu_header,
20322                                                          &bytes_read));
20323               buf += bytes_read;
20324               break;
20325
20326             case DW_FORM_data1:
20327               uint.emplace (read_1_byte (abfd, buf));
20328               buf += 1;
20329               break;
20330
20331             case DW_FORM_data2:
20332               uint.emplace (read_2_bytes (abfd, buf));
20333               buf += 2;
20334               break;
20335
20336             case DW_FORM_data4:
20337               uint.emplace (read_4_bytes (abfd, buf));
20338               buf += 4;
20339               break;
20340
20341             case DW_FORM_data8:
20342               uint.emplace (read_8_bytes (abfd, buf));
20343               buf += 8;
20344               break;
20345
20346             case DW_FORM_udata:
20347               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20348               buf += bytes_read;
20349               break;
20350
20351             case DW_FORM_block:
20352               /* It is valid only for DW_LNCT_timestamp which is ignored by
20353                  current GDB.  */
20354               break;
20355             }
20356
20357           switch (content_type)
20358             {
20359             case DW_LNCT_path:
20360               if (string.has_value ())
20361                 fe.name = *string;
20362               break;
20363             case DW_LNCT_directory_index:
20364               if (uint.has_value ())
20365                 fe.d_index = (dir_index) *uint;
20366               break;
20367             case DW_LNCT_timestamp:
20368               if (uint.has_value ())
20369                 fe.mod_time = *uint;
20370               break;
20371             case DW_LNCT_size:
20372               if (uint.has_value ())
20373                 fe.length = *uint;
20374               break;
20375             case DW_LNCT_MD5:
20376               break;
20377             default:
20378               complaint (_("Unknown format content type %s"),
20379                          pulongest (content_type));
20380             }
20381         }
20382
20383       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20384     }
20385
20386   *bufp = buf;
20387 }
20388
20389 /* Read the statement program header starting at OFFSET in
20390    .debug_line, or .debug_line.dwo.  Return a pointer
20391    to a struct line_header, allocated using xmalloc.
20392    Returns NULL if there is a problem reading the header, e.g., if it
20393    has a version we don't understand.
20394
20395    NOTE: the strings in the include directory and file name tables of
20396    the returned object point into the dwarf line section buffer,
20397    and must not be freed.  */
20398
20399 static line_header_up
20400 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20401 {
20402   const gdb_byte *line_ptr;
20403   unsigned int bytes_read, offset_size;
20404   int i;
20405   const char *cur_dir, *cur_file;
20406   struct dwarf2_section_info *section;
20407   bfd *abfd;
20408   struct dwarf2_per_objfile *dwarf2_per_objfile
20409     = cu->per_cu->dwarf2_per_objfile;
20410
20411   section = get_debug_line_section (cu);
20412   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20413   if (section->buffer == NULL)
20414     {
20415       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20416         complaint (_("missing .debug_line.dwo section"));
20417       else
20418         complaint (_("missing .debug_line section"));
20419       return 0;
20420     }
20421
20422   /* We can't do this until we know the section is non-empty.
20423      Only then do we know we have such a section.  */
20424   abfd = get_section_bfd_owner (section);
20425
20426   /* Make sure that at least there's room for the total_length field.
20427      That could be 12 bytes long, but we're just going to fudge that.  */
20428   if (to_underlying (sect_off) + 4 >= section->size)
20429     {
20430       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20431       return 0;
20432     }
20433
20434   line_header_up lh (new line_header ());
20435
20436   lh->sect_off = sect_off;
20437   lh->offset_in_dwz = cu->per_cu->is_dwz;
20438
20439   line_ptr = section->buffer + to_underlying (sect_off);
20440
20441   /* Read in the header.  */
20442   lh->total_length =
20443     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20444                                             &bytes_read, &offset_size);
20445   line_ptr += bytes_read;
20446   if (line_ptr + lh->total_length > (section->buffer + section->size))
20447     {
20448       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20449       return 0;
20450     }
20451   lh->statement_program_end = line_ptr + lh->total_length;
20452   lh->version = read_2_bytes (abfd, line_ptr);
20453   line_ptr += 2;
20454   if (lh->version > 5)
20455     {
20456       /* This is a version we don't understand.  The format could have
20457          changed in ways we don't handle properly so just punt.  */
20458       complaint (_("unsupported version in .debug_line section"));
20459       return NULL;
20460     }
20461   if (lh->version >= 5)
20462     {
20463       gdb_byte segment_selector_size;
20464
20465       /* Skip address size.  */
20466       read_1_byte (abfd, line_ptr);
20467       line_ptr += 1;
20468
20469       segment_selector_size = read_1_byte (abfd, line_ptr);
20470       line_ptr += 1;
20471       if (segment_selector_size != 0)
20472         {
20473           complaint (_("unsupported segment selector size %u "
20474                        "in .debug_line section"),
20475                      segment_selector_size);
20476           return NULL;
20477         }
20478     }
20479   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20480   line_ptr += offset_size;
20481   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20482   line_ptr += 1;
20483   if (lh->version >= 4)
20484     {
20485       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20486       line_ptr += 1;
20487     }
20488   else
20489     lh->maximum_ops_per_instruction = 1;
20490
20491   if (lh->maximum_ops_per_instruction == 0)
20492     {
20493       lh->maximum_ops_per_instruction = 1;
20494       complaint (_("invalid maximum_ops_per_instruction "
20495                    "in `.debug_line' section"));
20496     }
20497
20498   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20499   line_ptr += 1;
20500   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20501   line_ptr += 1;
20502   lh->line_range = read_1_byte (abfd, line_ptr);
20503   line_ptr += 1;
20504   lh->opcode_base = read_1_byte (abfd, line_ptr);
20505   line_ptr += 1;
20506   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20507
20508   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20509   for (i = 1; i < lh->opcode_base; ++i)
20510     {
20511       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20512       line_ptr += 1;
20513     }
20514
20515   if (lh->version >= 5)
20516     {
20517       /* Read directory table.  */
20518       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20519                               &cu->header,
20520                               [] (struct line_header *header, const char *name,
20521                                   dir_index d_index, unsigned int mod_time,
20522                                   unsigned int length)
20523         {
20524           header->add_include_dir (name);
20525         });
20526
20527       /* Read file name table.  */
20528       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20529                               &cu->header,
20530                               [] (struct line_header *header, const char *name,
20531                                   dir_index d_index, unsigned int mod_time,
20532                                   unsigned int length)
20533         {
20534           header->add_file_name (name, d_index, mod_time, length);
20535         });
20536     }
20537   else
20538     {
20539       /* Read directory table.  */
20540       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20541         {
20542           line_ptr += bytes_read;
20543           lh->add_include_dir (cur_dir);
20544         }
20545       line_ptr += bytes_read;
20546
20547       /* Read file name table.  */
20548       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20549         {
20550           unsigned int mod_time, length;
20551           dir_index d_index;
20552
20553           line_ptr += bytes_read;
20554           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20555           line_ptr += bytes_read;
20556           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20557           line_ptr += bytes_read;
20558           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20559           line_ptr += bytes_read;
20560
20561           lh->add_file_name (cur_file, d_index, mod_time, length);
20562         }
20563       line_ptr += bytes_read;
20564     }
20565   lh->statement_program_start = line_ptr;
20566
20567   if (line_ptr > (section->buffer + section->size))
20568     complaint (_("line number info header doesn't "
20569                  "fit in `.debug_line' section"));
20570
20571   return lh;
20572 }
20573
20574 /* Subroutine of dwarf_decode_lines to simplify it.
20575    Return the file name of the psymtab for included file FILE_INDEX
20576    in line header LH of PST.
20577    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20578    If space for the result is malloc'd, *NAME_HOLDER will be set.
20579    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20580
20581 static const char *
20582 psymtab_include_file_name (const struct line_header *lh, int file_index,
20583                            const struct partial_symtab *pst,
20584                            const char *comp_dir,
20585                            gdb::unique_xmalloc_ptr<char> *name_holder)
20586 {
20587   const file_entry &fe = lh->file_names[file_index];
20588   const char *include_name = fe.name;
20589   const char *include_name_to_compare = include_name;
20590   const char *pst_filename;
20591   int file_is_pst;
20592
20593   const char *dir_name = fe.include_dir (lh);
20594
20595   gdb::unique_xmalloc_ptr<char> hold_compare;
20596   if (!IS_ABSOLUTE_PATH (include_name)
20597       && (dir_name != NULL || comp_dir != NULL))
20598     {
20599       /* Avoid creating a duplicate psymtab for PST.
20600          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20601          Before we do the comparison, however, we need to account
20602          for DIR_NAME and COMP_DIR.
20603          First prepend dir_name (if non-NULL).  If we still don't
20604          have an absolute path prepend comp_dir (if non-NULL).
20605          However, the directory we record in the include-file's
20606          psymtab does not contain COMP_DIR (to match the
20607          corresponding symtab(s)).
20608
20609          Example:
20610
20611          bash$ cd /tmp
20612          bash$ gcc -g ./hello.c
20613          include_name = "hello.c"
20614          dir_name = "."
20615          DW_AT_comp_dir = comp_dir = "/tmp"
20616          DW_AT_name = "./hello.c"
20617
20618       */
20619
20620       if (dir_name != NULL)
20621         {
20622           name_holder->reset (concat (dir_name, SLASH_STRING,
20623                                       include_name, (char *) NULL));
20624           include_name = name_holder->get ();
20625           include_name_to_compare = include_name;
20626         }
20627       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20628         {
20629           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20630                                       include_name, (char *) NULL));
20631           include_name_to_compare = hold_compare.get ();
20632         }
20633     }
20634
20635   pst_filename = pst->filename;
20636   gdb::unique_xmalloc_ptr<char> copied_name;
20637   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20638     {
20639       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20640                                  pst_filename, (char *) NULL));
20641       pst_filename = copied_name.get ();
20642     }
20643
20644   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20645
20646   if (file_is_pst)
20647     return NULL;
20648   return include_name;
20649 }
20650
20651 /* State machine to track the state of the line number program.  */
20652
20653 class lnp_state_machine
20654 {
20655 public:
20656   /* Initialize a machine state for the start of a line number
20657      program.  */
20658   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20659                      bool record_lines_p);
20660
20661   file_entry *current_file ()
20662   {
20663     /* lh->file_names is 0-based, but the file name numbers in the
20664        statement program are 1-based.  */
20665     return m_line_header->file_name_at (m_file);
20666   }
20667
20668   /* Record the line in the state machine.  END_SEQUENCE is true if
20669      we're processing the end of a sequence.  */
20670   void record_line (bool end_sequence);
20671
20672   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20673      nop-out rest of the lines in this sequence.  */
20674   void check_line_address (struct dwarf2_cu *cu,
20675                            const gdb_byte *line_ptr,
20676                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20677
20678   void handle_set_discriminator (unsigned int discriminator)
20679   {
20680     m_discriminator = discriminator;
20681     m_line_has_non_zero_discriminator |= discriminator != 0;
20682   }
20683
20684   /* Handle DW_LNE_set_address.  */
20685   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20686   {
20687     m_op_index = 0;
20688     address += baseaddr;
20689     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20690   }
20691
20692   /* Handle DW_LNS_advance_pc.  */
20693   void handle_advance_pc (CORE_ADDR adjust);
20694
20695   /* Handle a special opcode.  */
20696   void handle_special_opcode (unsigned char op_code);
20697
20698   /* Handle DW_LNS_advance_line.  */
20699   void handle_advance_line (int line_delta)
20700   {
20701     advance_line (line_delta);
20702   }
20703
20704   /* Handle DW_LNS_set_file.  */
20705   void handle_set_file (file_name_index file);
20706
20707   /* Handle DW_LNS_negate_stmt.  */
20708   void handle_negate_stmt ()
20709   {
20710     m_is_stmt = !m_is_stmt;
20711   }
20712
20713   /* Handle DW_LNS_const_add_pc.  */
20714   void handle_const_add_pc ();
20715
20716   /* Handle DW_LNS_fixed_advance_pc.  */
20717   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20718   {
20719     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20720     m_op_index = 0;
20721   }
20722
20723   /* Handle DW_LNS_copy.  */
20724   void handle_copy ()
20725   {
20726     record_line (false);
20727     m_discriminator = 0;
20728   }
20729
20730   /* Handle DW_LNE_end_sequence.  */
20731   void handle_end_sequence ()
20732   {
20733     m_currently_recording_lines = true;
20734   }
20735
20736 private:
20737   /* Advance the line by LINE_DELTA.  */
20738   void advance_line (int line_delta)
20739   {
20740     m_line += line_delta;
20741
20742     if (line_delta != 0)
20743       m_line_has_non_zero_discriminator = m_discriminator != 0;
20744   }
20745
20746   struct dwarf2_cu *m_cu;
20747
20748   gdbarch *m_gdbarch;
20749
20750   /* True if we're recording lines.
20751      Otherwise we're building partial symtabs and are just interested in
20752      finding include files mentioned by the line number program.  */
20753   bool m_record_lines_p;
20754
20755   /* The line number header.  */
20756   line_header *m_line_header;
20757
20758   /* These are part of the standard DWARF line number state machine,
20759      and initialized according to the DWARF spec.  */
20760
20761   unsigned char m_op_index = 0;
20762   /* The line table index (1-based) of the current file.  */
20763   file_name_index m_file = (file_name_index) 1;
20764   unsigned int m_line = 1;
20765
20766   /* These are initialized in the constructor.  */
20767
20768   CORE_ADDR m_address;
20769   bool m_is_stmt;
20770   unsigned int m_discriminator;
20771
20772   /* Additional bits of state we need to track.  */
20773
20774   /* The last file that we called dwarf2_start_subfile for.
20775      This is only used for TLLs.  */
20776   unsigned int m_last_file = 0;
20777   /* The last file a line number was recorded for.  */
20778   struct subfile *m_last_subfile = NULL;
20779
20780   /* When true, record the lines we decode.  */
20781   bool m_currently_recording_lines = false;
20782
20783   /* The last line number that was recorded, used to coalesce
20784      consecutive entries for the same line.  This can happen, for
20785      example, when discriminators are present.  PR 17276.  */
20786   unsigned int m_last_line = 0;
20787   bool m_line_has_non_zero_discriminator = false;
20788 };
20789
20790 void
20791 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20792 {
20793   CORE_ADDR addr_adj = (((m_op_index + adjust)
20794                          / m_line_header->maximum_ops_per_instruction)
20795                         * m_line_header->minimum_instruction_length);
20796   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20797   m_op_index = ((m_op_index + adjust)
20798                 % m_line_header->maximum_ops_per_instruction);
20799 }
20800
20801 void
20802 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20803 {
20804   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20805   CORE_ADDR addr_adj = (((m_op_index
20806                           + (adj_opcode / m_line_header->line_range))
20807                          / m_line_header->maximum_ops_per_instruction)
20808                         * m_line_header->minimum_instruction_length);
20809   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20810   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20811                 % m_line_header->maximum_ops_per_instruction);
20812
20813   int line_delta = (m_line_header->line_base
20814                     + (adj_opcode % m_line_header->line_range));
20815   advance_line (line_delta);
20816   record_line (false);
20817   m_discriminator = 0;
20818 }
20819
20820 void
20821 lnp_state_machine::handle_set_file (file_name_index file)
20822 {
20823   m_file = file;
20824
20825   const file_entry *fe = current_file ();
20826   if (fe == NULL)
20827     dwarf2_debug_line_missing_file_complaint ();
20828   else if (m_record_lines_p)
20829     {
20830       const char *dir = fe->include_dir (m_line_header);
20831
20832       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20833       m_line_has_non_zero_discriminator = m_discriminator != 0;
20834       dwarf2_start_subfile (m_cu, fe->name, dir);
20835     }
20836 }
20837
20838 void
20839 lnp_state_machine::handle_const_add_pc ()
20840 {
20841   CORE_ADDR adjust
20842     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20843
20844   CORE_ADDR addr_adj
20845     = (((m_op_index + adjust)
20846         / m_line_header->maximum_ops_per_instruction)
20847        * m_line_header->minimum_instruction_length);
20848
20849   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20850   m_op_index = ((m_op_index + adjust)
20851                 % m_line_header->maximum_ops_per_instruction);
20852 }
20853
20854 /* Return non-zero if we should add LINE to the line number table.
20855    LINE is the line to add, LAST_LINE is the last line that was added,
20856    LAST_SUBFILE is the subfile for LAST_LINE.
20857    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20858    had a non-zero discriminator.
20859
20860    We have to be careful in the presence of discriminators.
20861    E.g., for this line:
20862
20863      for (i = 0; i < 100000; i++);
20864
20865    clang can emit four line number entries for that one line,
20866    each with a different discriminator.
20867    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20868
20869    However, we want gdb to coalesce all four entries into one.
20870    Otherwise the user could stepi into the middle of the line and
20871    gdb would get confused about whether the pc really was in the
20872    middle of the line.
20873
20874    Things are further complicated by the fact that two consecutive
20875    line number entries for the same line is a heuristic used by gcc
20876    to denote the end of the prologue.  So we can't just discard duplicate
20877    entries, we have to be selective about it.  The heuristic we use is
20878    that we only collapse consecutive entries for the same line if at least
20879    one of those entries has a non-zero discriminator.  PR 17276.
20880
20881    Note: Addresses in the line number state machine can never go backwards
20882    within one sequence, thus this coalescing is ok.  */
20883
20884 static int
20885 dwarf_record_line_p (struct dwarf2_cu *cu,
20886                      unsigned int line, unsigned int last_line,
20887                      int line_has_non_zero_discriminator,
20888                      struct subfile *last_subfile)
20889 {
20890   if (cu->get_builder ()->get_current_subfile () != last_subfile)
20891     return 1;
20892   if (line != last_line)
20893     return 1;
20894   /* Same line for the same file that we've seen already.
20895      As a last check, for pr 17276, only record the line if the line
20896      has never had a non-zero discriminator.  */
20897   if (!line_has_non_zero_discriminator)
20898     return 1;
20899   return 0;
20900 }
20901
20902 /* Use the CU's builder to record line number LINE beginning at
20903    address ADDRESS in the line table of subfile SUBFILE.  */
20904
20905 static void
20906 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20907                      unsigned int line, CORE_ADDR address,
20908                      struct dwarf2_cu *cu)
20909 {
20910   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20911
20912   if (dwarf_line_debug)
20913     {
20914       fprintf_unfiltered (gdb_stdlog,
20915                           "Recording line %u, file %s, address %s\n",
20916                           line, lbasename (subfile->name),
20917                           paddress (gdbarch, address));
20918     }
20919
20920   if (cu != nullptr)
20921     cu->get_builder ()->record_line (subfile, line, addr);
20922 }
20923
20924 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20925    Mark the end of a set of line number records.
20926    The arguments are the same as for dwarf_record_line_1.
20927    If SUBFILE is NULL the request is ignored.  */
20928
20929 static void
20930 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20931                    CORE_ADDR address, struct dwarf2_cu *cu)
20932 {
20933   if (subfile == NULL)
20934     return;
20935
20936   if (dwarf_line_debug)
20937     {
20938       fprintf_unfiltered (gdb_stdlog,
20939                           "Finishing current line, file %s, address %s\n",
20940                           lbasename (subfile->name),
20941                           paddress (gdbarch, address));
20942     }
20943
20944   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20945 }
20946
20947 void
20948 lnp_state_machine::record_line (bool end_sequence)
20949 {
20950   if (dwarf_line_debug)
20951     {
20952       fprintf_unfiltered (gdb_stdlog,
20953                           "Processing actual line %u: file %u,"
20954                           " address %s, is_stmt %u, discrim %u\n",
20955                           m_line, to_underlying (m_file),
20956                           paddress (m_gdbarch, m_address),
20957                           m_is_stmt, m_discriminator);
20958     }
20959
20960   file_entry *fe = current_file ();
20961
20962   if (fe == NULL)
20963     dwarf2_debug_line_missing_file_complaint ();
20964   /* For now we ignore lines not starting on an instruction boundary.
20965      But not when processing end_sequence for compatibility with the
20966      previous version of the code.  */
20967   else if (m_op_index == 0 || end_sequence)
20968     {
20969       fe->included_p = 1;
20970       if (m_record_lines_p && (producer_is_codewarrior (m_cu) || m_is_stmt))
20971         {
20972           if (m_last_subfile != m_cu->get_builder ()->get_current_subfile ()
20973               || end_sequence)
20974             {
20975               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20976                                  m_currently_recording_lines ? m_cu : nullptr);
20977             }
20978
20979           if (!end_sequence)
20980             {
20981               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20982                                        m_line_has_non_zero_discriminator,
20983                                        m_last_subfile))
20984                 {
20985                   buildsym_compunit *builder = m_cu->get_builder ();
20986                   dwarf_record_line_1 (m_gdbarch,
20987                                        builder->get_current_subfile (),
20988                                        m_line, m_address,
20989                                        m_currently_recording_lines ? m_cu : nullptr);
20990                 }
20991               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20992               m_last_line = m_line;
20993             }
20994         }
20995     }
20996 }
20997
20998 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20999                                       line_header *lh, bool record_lines_p)
21000 {
21001   m_cu = cu;
21002   m_gdbarch = arch;
21003   m_record_lines_p = record_lines_p;
21004   m_line_header = lh;
21005
21006   m_currently_recording_lines = true;
21007
21008   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
21009      was a line entry for it so that the backend has a chance to adjust it
21010      and also record it in case it needs it.  This is currently used by MIPS
21011      code, cf. `mips_adjust_dwarf2_line'.  */
21012   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
21013   m_is_stmt = lh->default_is_stmt;
21014   m_discriminator = 0;
21015 }
21016
21017 void
21018 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
21019                                        const gdb_byte *line_ptr,
21020                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
21021 {
21022   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
21023      the pc range of the CU.  However, we restrict the test to only ADDRESS
21024      values of zero to preserve GDB's previous behaviour which is to handle
21025      the specific case of a function being GC'd by the linker.  */
21026
21027   if (address == 0 && address < unrelocated_lowpc)
21028     {
21029       /* This line table is for a function which has been
21030          GCd by the linker.  Ignore it.  PR gdb/12528 */
21031
21032       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21033       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
21034
21035       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
21036                  line_offset, objfile_name (objfile));
21037       m_currently_recording_lines = false;
21038       /* Note: m_currently_recording_lines is left as false until we see
21039          DW_LNE_end_sequence.  */
21040     }
21041 }
21042
21043 /* Subroutine of dwarf_decode_lines to simplify it.
21044    Process the line number information in LH.
21045    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21046    program in order to set included_p for every referenced header.  */
21047
21048 static void
21049 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21050                       const int decode_for_pst_p, CORE_ADDR lowpc)
21051 {
21052   const gdb_byte *line_ptr, *extended_end;
21053   const gdb_byte *line_end;
21054   unsigned int bytes_read, extended_len;
21055   unsigned char op_code, extended_op;
21056   CORE_ADDR baseaddr;
21057   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21058   bfd *abfd = objfile->obfd;
21059   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21060   /* True if we're recording line info (as opposed to building partial
21061      symtabs and just interested in finding include files mentioned by
21062      the line number program).  */
21063   bool record_lines_p = !decode_for_pst_p;
21064
21065   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21066
21067   line_ptr = lh->statement_program_start;
21068   line_end = lh->statement_program_end;
21069
21070   /* Read the statement sequences until there's nothing left.  */
21071   while (line_ptr < line_end)
21072     {
21073       /* The DWARF line number program state machine.  Reset the state
21074          machine at the start of each sequence.  */
21075       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
21076       bool end_sequence = false;
21077
21078       if (record_lines_p)
21079         {
21080           /* Start a subfile for the current file of the state
21081              machine.  */
21082           const file_entry *fe = state_machine.current_file ();
21083
21084           if (fe != NULL)
21085             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
21086         }
21087
21088       /* Decode the table.  */
21089       while (line_ptr < line_end && !end_sequence)
21090         {
21091           op_code = read_1_byte (abfd, line_ptr);
21092           line_ptr += 1;
21093
21094           if (op_code >= lh->opcode_base)
21095             {
21096               /* Special opcode.  */
21097               state_machine.handle_special_opcode (op_code);
21098             }
21099           else switch (op_code)
21100             {
21101             case DW_LNS_extended_op:
21102               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21103                                                    &bytes_read);
21104               line_ptr += bytes_read;
21105               extended_end = line_ptr + extended_len;
21106               extended_op = read_1_byte (abfd, line_ptr);
21107               line_ptr += 1;
21108               switch (extended_op)
21109                 {
21110                 case DW_LNE_end_sequence:
21111                   state_machine.handle_end_sequence ();
21112                   end_sequence = true;
21113                   break;
21114                 case DW_LNE_set_address:
21115                   {
21116                     CORE_ADDR address
21117                       = read_address (abfd, line_ptr, cu, &bytes_read);
21118                     line_ptr += bytes_read;
21119
21120                     state_machine.check_line_address (cu, line_ptr,
21121                                                       lowpc - baseaddr, address);
21122                     state_machine.handle_set_address (baseaddr, address);
21123                   }
21124                   break;
21125                 case DW_LNE_define_file:
21126                   {
21127                     const char *cur_file;
21128                     unsigned int mod_time, length;
21129                     dir_index dindex;
21130
21131                     cur_file = read_direct_string (abfd, line_ptr,
21132                                                    &bytes_read);
21133                     line_ptr += bytes_read;
21134                     dindex = (dir_index)
21135                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21136                     line_ptr += bytes_read;
21137                     mod_time =
21138                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21139                     line_ptr += bytes_read;
21140                     length =
21141                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21142                     line_ptr += bytes_read;
21143                     lh->add_file_name (cur_file, dindex, mod_time, length);
21144                   }
21145                   break;
21146                 case DW_LNE_set_discriminator:
21147                   {
21148                     /* The discriminator is not interesting to the
21149                        debugger; just ignore it.  We still need to
21150                        check its value though:
21151                        if there are consecutive entries for the same
21152                        (non-prologue) line we want to coalesce them.
21153                        PR 17276.  */
21154                     unsigned int discr
21155                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21156                     line_ptr += bytes_read;
21157
21158                     state_machine.handle_set_discriminator (discr);
21159                   }
21160                   break;
21161                 default:
21162                   complaint (_("mangled .debug_line section"));
21163                   return;
21164                 }
21165               /* Make sure that we parsed the extended op correctly.  If e.g.
21166                  we expected a different address size than the producer used,
21167                  we may have read the wrong number of bytes.  */
21168               if (line_ptr != extended_end)
21169                 {
21170                   complaint (_("mangled .debug_line section"));
21171                   return;
21172                 }
21173               break;
21174             case DW_LNS_copy:
21175               state_machine.handle_copy ();
21176               break;
21177             case DW_LNS_advance_pc:
21178               {
21179                 CORE_ADDR adjust
21180                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21181                 line_ptr += bytes_read;
21182
21183                 state_machine.handle_advance_pc (adjust);
21184               }
21185               break;
21186             case DW_LNS_advance_line:
21187               {
21188                 int line_delta
21189                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21190                 line_ptr += bytes_read;
21191
21192                 state_machine.handle_advance_line (line_delta);
21193               }
21194               break;
21195             case DW_LNS_set_file:
21196               {
21197                 file_name_index file
21198                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21199                                                             &bytes_read);
21200                 line_ptr += bytes_read;
21201
21202                 state_machine.handle_set_file (file);
21203               }
21204               break;
21205             case DW_LNS_set_column:
21206               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21207               line_ptr += bytes_read;
21208               break;
21209             case DW_LNS_negate_stmt:
21210               state_machine.handle_negate_stmt ();
21211               break;
21212             case DW_LNS_set_basic_block:
21213               break;
21214             /* Add to the address register of the state machine the
21215                address increment value corresponding to special opcode
21216                255.  I.e., this value is scaled by the minimum
21217                instruction length since special opcode 255 would have
21218                scaled the increment.  */
21219             case DW_LNS_const_add_pc:
21220               state_machine.handle_const_add_pc ();
21221               break;
21222             case DW_LNS_fixed_advance_pc:
21223               {
21224                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21225                 line_ptr += 2;
21226
21227                 state_machine.handle_fixed_advance_pc (addr_adj);
21228               }
21229               break;
21230             default:
21231               {
21232                 /* Unknown standard opcode, ignore it.  */
21233                 int i;
21234
21235                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21236                   {
21237                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21238                     line_ptr += bytes_read;
21239                   }
21240               }
21241             }
21242         }
21243
21244       if (!end_sequence)
21245         dwarf2_debug_line_missing_end_sequence_complaint ();
21246
21247       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21248          in which case we still finish recording the last line).  */
21249       state_machine.record_line (true);
21250     }
21251 }
21252
21253 /* Decode the Line Number Program (LNP) for the given line_header
21254    structure and CU.  The actual information extracted and the type
21255    of structures created from the LNP depends on the value of PST.
21256
21257    1. If PST is NULL, then this procedure uses the data from the program
21258       to create all necessary symbol tables, and their linetables.
21259
21260    2. If PST is not NULL, this procedure reads the program to determine
21261       the list of files included by the unit represented by PST, and
21262       builds all the associated partial symbol tables.
21263
21264    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21265    It is used for relative paths in the line table.
21266    NOTE: When processing partial symtabs (pst != NULL),
21267    comp_dir == pst->dirname.
21268
21269    NOTE: It is important that psymtabs have the same file name (via strcmp)
21270    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21271    symtab we don't use it in the name of the psymtabs we create.
21272    E.g. expand_line_sal requires this when finding psymtabs to expand.
21273    A good testcase for this is mb-inline.exp.
21274
21275    LOWPC is the lowest address in CU (or 0 if not known).
21276
21277    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21278    for its PC<->lines mapping information.  Otherwise only the filename
21279    table is read in.  */
21280
21281 static void
21282 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21283                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21284                     CORE_ADDR lowpc, int decode_mapping)
21285 {
21286   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21287   const int decode_for_pst_p = (pst != NULL);
21288
21289   if (decode_mapping)
21290     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21291
21292   if (decode_for_pst_p)
21293     {
21294       int file_index;
21295
21296       /* Now that we're done scanning the Line Header Program, we can
21297          create the psymtab of each included file.  */
21298       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21299         if (lh->file_names[file_index].included_p == 1)
21300           {
21301             gdb::unique_xmalloc_ptr<char> name_holder;
21302             const char *include_name =
21303               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21304                                          &name_holder);
21305             if (include_name != NULL)
21306               dwarf2_create_include_psymtab (include_name, pst, objfile);
21307           }
21308     }
21309   else
21310     {
21311       /* Make sure a symtab is created for every file, even files
21312          which contain only variables (i.e. no code with associated
21313          line numbers).  */
21314       buildsym_compunit *builder = cu->get_builder ();
21315       struct compunit_symtab *cust = builder->get_compunit_symtab ();
21316       int i;
21317
21318       for (i = 0; i < lh->file_names.size (); i++)
21319         {
21320           file_entry &fe = lh->file_names[i];
21321
21322           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21323
21324           if (builder->get_current_subfile ()->symtab == NULL)
21325             {
21326               builder->get_current_subfile ()->symtab
21327                 = allocate_symtab (cust,
21328                                    builder->get_current_subfile ()->name);
21329             }
21330           fe.symtab = builder->get_current_subfile ()->symtab;
21331         }
21332     }
21333 }
21334
21335 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21336    DIRNAME the name of the source directory which contains FILENAME
21337    or NULL if not known.
21338    This routine tries to keep line numbers from identical absolute and
21339    relative file names in a common subfile.
21340
21341    Using the `list' example from the GDB testsuite, which resides in
21342    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21343    of /srcdir/list0.c yields the following debugging information for list0.c:
21344
21345    DW_AT_name:          /srcdir/list0.c
21346    DW_AT_comp_dir:      /compdir
21347    files.files[0].name: list0.h
21348    files.files[0].dir:  /srcdir
21349    files.files[1].name: list0.c
21350    files.files[1].dir:  /srcdir
21351
21352    The line number information for list0.c has to end up in a single
21353    subfile, so that `break /srcdir/list0.c:1' works as expected.
21354    start_subfile will ensure that this happens provided that we pass the
21355    concatenation of files.files[1].dir and files.files[1].name as the
21356    subfile's name.  */
21357
21358 static void
21359 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21360                       const char *dirname)
21361 {
21362   char *copy = NULL;
21363
21364   /* In order not to lose the line information directory,
21365      we concatenate it to the filename when it makes sense.
21366      Note that the Dwarf3 standard says (speaking of filenames in line
21367      information): ``The directory index is ignored for file names
21368      that represent full path names''.  Thus ignoring dirname in the
21369      `else' branch below isn't an issue.  */
21370
21371   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21372     {
21373       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21374       filename = copy;
21375     }
21376
21377   cu->get_builder ()->start_subfile (filename);
21378
21379   if (copy != NULL)
21380     xfree (copy);
21381 }
21382
21383 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21384    buildsym_compunit constructor.  */
21385
21386 struct compunit_symtab *
21387 dwarf2_cu::start_symtab (const char *name, const char *comp_dir,
21388                          CORE_ADDR low_pc)
21389 {
21390   gdb_assert (m_builder == nullptr);
21391
21392   m_builder.reset (new struct buildsym_compunit
21393                    (per_cu->dwarf2_per_objfile->objfile,
21394                     name, comp_dir, language, low_pc));
21395
21396   list_in_scope = get_builder ()->get_file_symbols ();
21397
21398   get_builder ()->record_debugformat ("DWARF 2");
21399   get_builder ()->record_producer (producer);
21400
21401   processing_has_namespace_info = false;
21402
21403   return get_builder ()->get_compunit_symtab ();
21404 }
21405
21406 static void
21407 var_decode_location (struct attribute *attr, struct symbol *sym,
21408                      struct dwarf2_cu *cu)
21409 {
21410   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21411   struct comp_unit_head *cu_header = &cu->header;
21412
21413   /* NOTE drow/2003-01-30: There used to be a comment and some special
21414      code here to turn a symbol with DW_AT_external and a
21415      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21416      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21417      with some versions of binutils) where shared libraries could have
21418      relocations against symbols in their debug information - the
21419      minimal symbol would have the right address, but the debug info
21420      would not.  It's no longer necessary, because we will explicitly
21421      apply relocations when we read in the debug information now.  */
21422
21423   /* A DW_AT_location attribute with no contents indicates that a
21424      variable has been optimized away.  */
21425   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21426     {
21427       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21428       return;
21429     }
21430
21431   /* Handle one degenerate form of location expression specially, to
21432      preserve GDB's previous behavior when section offsets are
21433      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
21434      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
21435
21436   if (attr_form_is_block (attr)
21437       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21438            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21439           || ((DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21440                || DW_BLOCK (attr)->data[0] == DW_OP_addrx)
21441               && (DW_BLOCK (attr)->size
21442                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21443     {
21444       unsigned int dummy;
21445
21446       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21447         SYMBOL_VALUE_ADDRESS (sym) =
21448           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21449       else
21450         SYMBOL_VALUE_ADDRESS (sym) =
21451           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21452       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21453       fixup_symbol_section (sym, objfile);
21454       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21455                                               SYMBOL_SECTION (sym));
21456       return;
21457     }
21458
21459   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21460      expression evaluator, and use LOC_COMPUTED only when necessary
21461      (i.e. when the value of a register or memory location is
21462      referenced, or a thread-local block, etc.).  Then again, it might
21463      not be worthwhile.  I'm assuming that it isn't unless performance
21464      or memory numbers show me otherwise.  */
21465
21466   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21467
21468   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21469     cu->has_loclist = true;
21470 }
21471
21472 /* Given a pointer to a DWARF information entry, figure out if we need
21473    to make a symbol table entry for it, and if so, create a new entry
21474    and return a pointer to it.
21475    If TYPE is NULL, determine symbol type from the die, otherwise
21476    used the passed type.
21477    If SPACE is not NULL, use it to hold the new symbol.  If it is
21478    NULL, allocate a new symbol on the objfile's obstack.  */
21479
21480 static struct symbol *
21481 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21482             struct symbol *space)
21483 {
21484   struct dwarf2_per_objfile *dwarf2_per_objfile
21485     = cu->per_cu->dwarf2_per_objfile;
21486   struct objfile *objfile = dwarf2_per_objfile->objfile;
21487   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21488   struct symbol *sym = NULL;
21489   const char *name;
21490   struct attribute *attr = NULL;
21491   struct attribute *attr2 = NULL;
21492   CORE_ADDR baseaddr;
21493   struct pending **list_to_add = NULL;
21494
21495   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21496
21497   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21498
21499   name = dwarf2_name (die, cu);
21500   if (name)
21501     {
21502       const char *linkagename;
21503       int suppress_add = 0;
21504
21505       if (space)
21506         sym = space;
21507       else
21508         sym = allocate_symbol (objfile);
21509       OBJSTAT (objfile, n_syms++);
21510
21511       /* Cache this symbol's name and the name's demangled form (if any).  */
21512       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21513       linkagename = dwarf2_physname (name, die, cu);
21514       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21515
21516       /* Fortran does not have mangling standard and the mangling does differ
21517          between gfortran, iFort etc.  */
21518       if (cu->language == language_fortran
21519           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21520         symbol_set_demangled_name (&(sym->ginfo),
21521                                    dwarf2_full_name (name, die, cu),
21522                                    NULL);
21523
21524       /* Default assumptions.
21525          Use the passed type or decode it from the die.  */
21526       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21527       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21528       if (type != NULL)
21529         SYMBOL_TYPE (sym) = type;
21530       else
21531         SYMBOL_TYPE (sym) = die_type (die, cu);
21532       attr = dwarf2_attr (die,
21533                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21534                           cu);
21535       if (attr)
21536         {
21537           SYMBOL_LINE (sym) = DW_UNSND (attr);
21538         }
21539
21540       attr = dwarf2_attr (die,
21541                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21542                           cu);
21543       if (attr)
21544         {
21545           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21546           struct file_entry *fe;
21547
21548           if (cu->line_header != NULL)
21549             fe = cu->line_header->file_name_at (file_index);
21550           else
21551             fe = NULL;
21552
21553           if (fe == NULL)
21554             complaint (_("file index out of range"));
21555           else
21556             symbol_set_symtab (sym, fe->symtab);
21557         }
21558
21559       switch (die->tag)
21560         {
21561         case DW_TAG_label:
21562           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21563           if (attr)
21564             {
21565               CORE_ADDR addr;
21566
21567               addr = attr_value_as_address (attr);
21568               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21569               SYMBOL_VALUE_ADDRESS (sym) = addr;
21570             }
21571           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21572           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21573           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21574           add_symbol_to_list (sym, cu->list_in_scope);
21575           break;
21576         case DW_TAG_subprogram:
21577           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21578              finish_block.  */
21579           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21580           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21581           if ((attr2 && (DW_UNSND (attr2) != 0))
21582               || cu->language == language_ada)
21583             {
21584               /* Subprograms marked external are stored as a global symbol.
21585                  Ada subprograms, whether marked external or not, are always
21586                  stored as a global symbol, because we want to be able to
21587                  access them globally.  For instance, we want to be able
21588                  to break on a nested subprogram without having to
21589                  specify the context.  */
21590               list_to_add = cu->get_builder ()->get_global_symbols ();
21591             }
21592           else
21593             {
21594               list_to_add = cu->list_in_scope;
21595             }
21596           break;
21597         case DW_TAG_inlined_subroutine:
21598           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21599              finish_block.  */
21600           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21601           SYMBOL_INLINED (sym) = 1;
21602           list_to_add = cu->list_in_scope;
21603           break;
21604         case DW_TAG_template_value_param:
21605           suppress_add = 1;
21606           /* Fall through.  */
21607         case DW_TAG_constant:
21608         case DW_TAG_variable:
21609         case DW_TAG_member:
21610           /* Compilation with minimal debug info may result in
21611              variables with missing type entries.  Change the
21612              misleading `void' type to something sensible.  */
21613           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21614             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21615
21616           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21617           /* In the case of DW_TAG_member, we should only be called for
21618              static const members.  */
21619           if (die->tag == DW_TAG_member)
21620             {
21621               /* dwarf2_add_field uses die_is_declaration,
21622                  so we do the same.  */
21623               gdb_assert (die_is_declaration (die, cu));
21624               gdb_assert (attr);
21625             }
21626           if (attr)
21627             {
21628               dwarf2_const_value (attr, sym, cu);
21629               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21630               if (!suppress_add)
21631                 {
21632                   if (attr2 && (DW_UNSND (attr2) != 0))
21633                     list_to_add = cu->get_builder ()->get_global_symbols ();
21634                   else
21635                     list_to_add = cu->list_in_scope;
21636                 }
21637               break;
21638             }
21639           attr = dwarf2_attr (die, DW_AT_location, cu);
21640           if (attr)
21641             {
21642               var_decode_location (attr, sym, cu);
21643               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21644
21645               /* Fortran explicitly imports any global symbols to the local
21646                  scope by DW_TAG_common_block.  */
21647               if (cu->language == language_fortran && die->parent
21648                   && die->parent->tag == DW_TAG_common_block)
21649                 attr2 = NULL;
21650
21651               if (SYMBOL_CLASS (sym) == LOC_STATIC
21652                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21653                   && !dwarf2_per_objfile->has_section_at_zero)
21654                 {
21655                   /* When a static variable is eliminated by the linker,
21656                      the corresponding debug information is not stripped
21657                      out, but the variable address is set to null;
21658                      do not add such variables into symbol table.  */
21659                 }
21660               else if (attr2 && (DW_UNSND (attr2) != 0))
21661                 {
21662                   /* Workaround gfortran PR debug/40040 - it uses
21663                      DW_AT_location for variables in -fPIC libraries which may
21664                      get overriden by other libraries/executable and get
21665                      a different address.  Resolve it by the minimal symbol
21666                      which may come from inferior's executable using copy
21667                      relocation.  Make this workaround only for gfortran as for
21668                      other compilers GDB cannot guess the minimal symbol
21669                      Fortran mangling kind.  */
21670                   if (cu->language == language_fortran && die->parent
21671                       && die->parent->tag == DW_TAG_module
21672                       && cu->producer
21673                       && startswith (cu->producer, "GNU Fortran"))
21674                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21675
21676                   /* A variable with DW_AT_external is never static,
21677                      but it may be block-scoped.  */
21678                   list_to_add
21679                     = ((cu->list_in_scope
21680                         == cu->get_builder ()->get_file_symbols ())
21681                        ? cu->get_builder ()->get_global_symbols ()
21682                        : cu->list_in_scope);
21683                 }
21684               else
21685                 list_to_add = cu->list_in_scope;
21686             }
21687           else
21688             {
21689               /* We do not know the address of this symbol.
21690                  If it is an external symbol and we have type information
21691                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21692                  The address of the variable will then be determined from
21693                  the minimal symbol table whenever the variable is
21694                  referenced.  */
21695               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21696
21697               /* Fortran explicitly imports any global symbols to the local
21698                  scope by DW_TAG_common_block.  */
21699               if (cu->language == language_fortran && die->parent
21700                   && die->parent->tag == DW_TAG_common_block)
21701                 {
21702                   /* SYMBOL_CLASS doesn't matter here because
21703                      read_common_block is going to reset it.  */
21704                   if (!suppress_add)
21705                     list_to_add = cu->list_in_scope;
21706                 }
21707               else if (attr2 && (DW_UNSND (attr2) != 0)
21708                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21709                 {
21710                   /* A variable with DW_AT_external is never static, but it
21711                      may be block-scoped.  */
21712                   list_to_add
21713                     = ((cu->list_in_scope
21714                         == cu->get_builder ()->get_file_symbols ())
21715                        ? cu->get_builder ()->get_global_symbols ()
21716                        : cu->list_in_scope);
21717
21718                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21719                 }
21720               else if (!die_is_declaration (die, cu))
21721                 {
21722                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21723                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21724                   if (!suppress_add)
21725                     list_to_add = cu->list_in_scope;
21726                 }
21727             }
21728           break;
21729         case DW_TAG_formal_parameter:
21730           {
21731             /* If we are inside a function, mark this as an argument.  If
21732                not, we might be looking at an argument to an inlined function
21733                when we do not have enough information to show inlined frames;
21734                pretend it's a local variable in that case so that the user can
21735                still see it.  */
21736             struct context_stack *curr
21737               = cu->get_builder ()->get_current_context_stack ();
21738             if (curr != nullptr && curr->name != nullptr)
21739               SYMBOL_IS_ARGUMENT (sym) = 1;
21740             attr = dwarf2_attr (die, DW_AT_location, cu);
21741             if (attr)
21742               {
21743                 var_decode_location (attr, sym, cu);
21744               }
21745             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21746             if (attr)
21747               {
21748                 dwarf2_const_value (attr, sym, cu);
21749               }
21750
21751             list_to_add = cu->list_in_scope;
21752           }
21753           break;
21754         case DW_TAG_unspecified_parameters:
21755           /* From varargs functions; gdb doesn't seem to have any
21756              interest in this information, so just ignore it for now.
21757              (FIXME?) */
21758           break;
21759         case DW_TAG_template_type_param:
21760           suppress_add = 1;
21761           /* Fall through.  */
21762         case DW_TAG_class_type:
21763         case DW_TAG_interface_type:
21764         case DW_TAG_structure_type:
21765         case DW_TAG_union_type:
21766         case DW_TAG_set_type:
21767         case DW_TAG_enumeration_type:
21768           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21769           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21770
21771           {
21772             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21773                really ever be static objects: otherwise, if you try
21774                to, say, break of a class's method and you're in a file
21775                which doesn't mention that class, it won't work unless
21776                the check for all static symbols in lookup_symbol_aux
21777                saves you.  See the OtherFileClass tests in
21778                gdb.c++/namespace.exp.  */
21779
21780             if (!suppress_add)
21781               {
21782                 buildsym_compunit *builder = cu->get_builder ();
21783                 list_to_add
21784                   = (cu->list_in_scope == builder->get_file_symbols ()
21785                      && cu->language == language_cplus
21786                      ? builder->get_global_symbols ()
21787                      : cu->list_in_scope);
21788
21789                 /* The semantics of C++ state that "struct foo {
21790                    ... }" also defines a typedef for "foo".  */
21791                 if (cu->language == language_cplus
21792                     || cu->language == language_ada
21793                     || cu->language == language_d
21794                     || cu->language == language_rust)
21795                   {
21796                     /* The symbol's name is already allocated along
21797                        with this objfile, so we don't need to
21798                        duplicate it for the type.  */
21799                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21800                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21801                   }
21802               }
21803           }
21804           break;
21805         case DW_TAG_typedef:
21806           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21807           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21808           list_to_add = cu->list_in_scope;
21809           break;
21810         case DW_TAG_base_type:
21811         case DW_TAG_subrange_type:
21812           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21813           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21814           list_to_add = cu->list_in_scope;
21815           break;
21816         case DW_TAG_enumerator:
21817           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21818           if (attr)
21819             {
21820               dwarf2_const_value (attr, sym, cu);
21821             }
21822           {
21823             /* NOTE: carlton/2003-11-10: See comment above in the
21824                DW_TAG_class_type, etc. block.  */
21825
21826             list_to_add
21827               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
21828                  && cu->language == language_cplus
21829                  ? cu->get_builder ()->get_global_symbols ()
21830                  : cu->list_in_scope);
21831           }
21832           break;
21833         case DW_TAG_imported_declaration:
21834         case DW_TAG_namespace:
21835           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21836           list_to_add = cu->get_builder ()->get_global_symbols ();
21837           break;
21838         case DW_TAG_module:
21839           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21840           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21841           list_to_add = cu->get_builder ()->get_global_symbols ();
21842           break;
21843         case DW_TAG_common_block:
21844           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21845           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21846           add_symbol_to_list (sym, cu->list_in_scope);
21847           break;
21848         default:
21849           /* Not a tag we recognize.  Hopefully we aren't processing
21850              trash data, but since we must specifically ignore things
21851              we don't recognize, there is nothing else we should do at
21852              this point.  */
21853           complaint (_("unsupported tag: '%s'"),
21854                      dwarf_tag_name (die->tag));
21855           break;
21856         }
21857
21858       if (suppress_add)
21859         {
21860           sym->hash_next = objfile->template_symbols;
21861           objfile->template_symbols = sym;
21862           list_to_add = NULL;
21863         }
21864
21865       if (list_to_add != NULL)
21866         add_symbol_to_list (sym, list_to_add);
21867
21868       /* For the benefit of old versions of GCC, check for anonymous
21869          namespaces based on the demangled name.  */
21870       if (!cu->processing_has_namespace_info
21871           && cu->language == language_cplus)
21872         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
21873     }
21874   return (sym);
21875 }
21876
21877 /* Given an attr with a DW_FORM_dataN value in host byte order,
21878    zero-extend it as appropriate for the symbol's type.  The DWARF
21879    standard (v4) is not entirely clear about the meaning of using
21880    DW_FORM_dataN for a constant with a signed type, where the type is
21881    wider than the data.  The conclusion of a discussion on the DWARF
21882    list was that this is unspecified.  We choose to always zero-extend
21883    because that is the interpretation long in use by GCC.  */
21884
21885 static gdb_byte *
21886 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21887                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21888 {
21889   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21890   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21891                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21892   LONGEST l = DW_UNSND (attr);
21893
21894   if (bits < sizeof (*value) * 8)
21895     {
21896       l &= ((LONGEST) 1 << bits) - 1;
21897       *value = l;
21898     }
21899   else if (bits == sizeof (*value) * 8)
21900     *value = l;
21901   else
21902     {
21903       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21904       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21905       return bytes;
21906     }
21907
21908   return NULL;
21909 }
21910
21911 /* Read a constant value from an attribute.  Either set *VALUE, or if
21912    the value does not fit in *VALUE, set *BYTES - either already
21913    allocated on the objfile obstack, or newly allocated on OBSTACK,
21914    or, set *BATON, if we translated the constant to a location
21915    expression.  */
21916
21917 static void
21918 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21919                          const char *name, struct obstack *obstack,
21920                          struct dwarf2_cu *cu,
21921                          LONGEST *value, const gdb_byte **bytes,
21922                          struct dwarf2_locexpr_baton **baton)
21923 {
21924   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21925   struct comp_unit_head *cu_header = &cu->header;
21926   struct dwarf_block *blk;
21927   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21928                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21929
21930   *value = 0;
21931   *bytes = NULL;
21932   *baton = NULL;
21933
21934   switch (attr->form)
21935     {
21936     case DW_FORM_addr:
21937     case DW_FORM_addrx:
21938     case DW_FORM_GNU_addr_index:
21939       {
21940         gdb_byte *data;
21941
21942         if (TYPE_LENGTH (type) != cu_header->addr_size)
21943           dwarf2_const_value_length_mismatch_complaint (name,
21944                                                         cu_header->addr_size,
21945                                                         TYPE_LENGTH (type));
21946         /* Symbols of this form are reasonably rare, so we just
21947            piggyback on the existing location code rather than writing
21948            a new implementation of symbol_computed_ops.  */
21949         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21950         (*baton)->per_cu = cu->per_cu;
21951         gdb_assert ((*baton)->per_cu);
21952
21953         (*baton)->size = 2 + cu_header->addr_size;
21954         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21955         (*baton)->data = data;
21956
21957         data[0] = DW_OP_addr;
21958         store_unsigned_integer (&data[1], cu_header->addr_size,
21959                                 byte_order, DW_ADDR (attr));
21960         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21961       }
21962       break;
21963     case DW_FORM_string:
21964     case DW_FORM_strp:
21965     case DW_FORM_strx:
21966     case DW_FORM_GNU_str_index:
21967     case DW_FORM_GNU_strp_alt:
21968       /* DW_STRING is already allocated on the objfile obstack, point
21969          directly to it.  */
21970       *bytes = (const gdb_byte *) DW_STRING (attr);
21971       break;
21972     case DW_FORM_block1:
21973     case DW_FORM_block2:
21974     case DW_FORM_block4:
21975     case DW_FORM_block:
21976     case DW_FORM_exprloc:
21977     case DW_FORM_data16:
21978       blk = DW_BLOCK (attr);
21979       if (TYPE_LENGTH (type) != blk->size)
21980         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21981                                                       TYPE_LENGTH (type));
21982       *bytes = blk->data;
21983       break;
21984
21985       /* The DW_AT_const_value attributes are supposed to carry the
21986          symbol's value "represented as it would be on the target
21987          architecture."  By the time we get here, it's already been
21988          converted to host endianness, so we just need to sign- or
21989          zero-extend it as appropriate.  */
21990     case DW_FORM_data1:
21991       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21992       break;
21993     case DW_FORM_data2:
21994       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21995       break;
21996     case DW_FORM_data4:
21997       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21998       break;
21999     case DW_FORM_data8:
22000       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
22001       break;
22002
22003     case DW_FORM_sdata:
22004     case DW_FORM_implicit_const:
22005       *value = DW_SND (attr);
22006       break;
22007
22008     case DW_FORM_udata:
22009       *value = DW_UNSND (attr);
22010       break;
22011
22012     default:
22013       complaint (_("unsupported const value attribute form: '%s'"),
22014                  dwarf_form_name (attr->form));
22015       *value = 0;
22016       break;
22017     }
22018 }
22019
22020
22021 /* Copy constant value from an attribute to a symbol.  */
22022
22023 static void
22024 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
22025                     struct dwarf2_cu *cu)
22026 {
22027   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22028   LONGEST value;
22029   const gdb_byte *bytes;
22030   struct dwarf2_locexpr_baton *baton;
22031
22032   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
22033                            SYMBOL_PRINT_NAME (sym),
22034                            &objfile->objfile_obstack, cu,
22035                            &value, &bytes, &baton);
22036
22037   if (baton != NULL)
22038     {
22039       SYMBOL_LOCATION_BATON (sym) = baton;
22040       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22041     }
22042   else if (bytes != NULL)
22043      {
22044       SYMBOL_VALUE_BYTES (sym) = bytes;
22045       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22046     }
22047   else
22048     {
22049       SYMBOL_VALUE (sym) = value;
22050       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22051     }
22052 }
22053
22054 /* Return the type of the die in question using its DW_AT_type attribute.  */
22055
22056 static struct type *
22057 die_type (struct die_info *die, struct dwarf2_cu *cu)
22058 {
22059   struct attribute *type_attr;
22060
22061   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22062   if (!type_attr)
22063     {
22064       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22065       /* A missing DW_AT_type represents a void type.  */
22066       return objfile_type (objfile)->builtin_void;
22067     }
22068
22069   return lookup_die_type (die, type_attr, cu);
22070 }
22071
22072 /* True iff CU's producer generates GNAT Ada auxiliary information
22073    that allows to find parallel types through that information instead
22074    of having to do expensive parallel lookups by type name.  */
22075
22076 static int
22077 need_gnat_info (struct dwarf2_cu *cu)
22078 {
22079   /* Assume that the Ada compiler was GNAT, which always produces
22080      the auxiliary information.  */
22081   return (cu->language == language_ada);
22082 }
22083
22084 /* Return the auxiliary type of the die in question using its
22085    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22086    attribute is not present.  */
22087
22088 static struct type *
22089 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22090 {
22091   struct attribute *type_attr;
22092
22093   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22094   if (!type_attr)
22095     return NULL;
22096
22097   return lookup_die_type (die, type_attr, cu);
22098 }
22099
22100 /* If DIE has a descriptive_type attribute, then set the TYPE's
22101    descriptive type accordingly.  */
22102
22103 static void
22104 set_descriptive_type (struct type *type, struct die_info *die,
22105                       struct dwarf2_cu *cu)
22106 {
22107   struct type *descriptive_type = die_descriptive_type (die, cu);
22108
22109   if (descriptive_type)
22110     {
22111       ALLOCATE_GNAT_AUX_TYPE (type);
22112       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22113     }
22114 }
22115
22116 /* Return the containing type of the die in question using its
22117    DW_AT_containing_type attribute.  */
22118
22119 static struct type *
22120 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22121 {
22122   struct attribute *type_attr;
22123   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22124
22125   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22126   if (!type_attr)
22127     error (_("Dwarf Error: Problem turning containing type into gdb type "
22128              "[in module %s]"), objfile_name (objfile));
22129
22130   return lookup_die_type (die, type_attr, cu);
22131 }
22132
22133 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22134
22135 static struct type *
22136 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22137 {
22138   struct dwarf2_per_objfile *dwarf2_per_objfile
22139     = cu->per_cu->dwarf2_per_objfile;
22140   struct objfile *objfile = dwarf2_per_objfile->objfile;
22141   char *saved;
22142
22143   std::string message
22144     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
22145                      objfile_name (objfile),
22146                      sect_offset_str (cu->header.sect_off),
22147                      sect_offset_str (die->sect_off));
22148   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
22149                                   message.c_str (), message.length ());
22150
22151   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22152 }
22153
22154 /* Look up the type of DIE in CU using its type attribute ATTR.
22155    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22156    DW_AT_containing_type.
22157    If there is no type substitute an error marker.  */
22158
22159 static struct type *
22160 lookup_die_type (struct die_info *die, const struct attribute *attr,
22161                  struct dwarf2_cu *cu)
22162 {
22163   struct dwarf2_per_objfile *dwarf2_per_objfile
22164     = cu->per_cu->dwarf2_per_objfile;
22165   struct objfile *objfile = dwarf2_per_objfile->objfile;
22166   struct type *this_type;
22167
22168   gdb_assert (attr->name == DW_AT_type
22169               || attr->name == DW_AT_GNAT_descriptive_type
22170               || attr->name == DW_AT_containing_type);
22171
22172   /* First see if we have it cached.  */
22173
22174   if (attr->form == DW_FORM_GNU_ref_alt)
22175     {
22176       struct dwarf2_per_cu_data *per_cu;
22177       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22178
22179       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22180                                                  dwarf2_per_objfile);
22181       this_type = get_die_type_at_offset (sect_off, per_cu);
22182     }
22183   else if (attr_form_is_ref (attr))
22184     {
22185       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22186
22187       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22188     }
22189   else if (attr->form == DW_FORM_ref_sig8)
22190     {
22191       ULONGEST signature = DW_SIGNATURE (attr);
22192
22193       return get_signatured_type (die, signature, cu);
22194     }
22195   else
22196     {
22197       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
22198                    " at %s [in module %s]"),
22199                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22200                  objfile_name (objfile));
22201       return build_error_marker_type (cu, die);
22202     }
22203
22204   /* If not cached we need to read it in.  */
22205
22206   if (this_type == NULL)
22207     {
22208       struct die_info *type_die = NULL;
22209       struct dwarf2_cu *type_cu = cu;
22210
22211       if (attr_form_is_ref (attr))
22212         type_die = follow_die_ref (die, attr, &type_cu);
22213       if (type_die == NULL)
22214         return build_error_marker_type (cu, die);
22215       /* If we find the type now, it's probably because the type came
22216          from an inter-CU reference and the type's CU got expanded before
22217          ours.  */
22218       this_type = read_type_die (type_die, type_cu);
22219     }
22220
22221   /* If we still don't have a type use an error marker.  */
22222
22223   if (this_type == NULL)
22224     return build_error_marker_type (cu, die);
22225
22226   return this_type;
22227 }
22228
22229 /* Return the type in DIE, CU.
22230    Returns NULL for invalid types.
22231
22232    This first does a lookup in die_type_hash,
22233    and only reads the die in if necessary.
22234
22235    NOTE: This can be called when reading in partial or full symbols.  */
22236
22237 static struct type *
22238 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22239 {
22240   struct type *this_type;
22241
22242   this_type = get_die_type (die, cu);
22243   if (this_type)
22244     return this_type;
22245
22246   return read_type_die_1 (die, cu);
22247 }
22248
22249 /* Read the type in DIE, CU.
22250    Returns NULL for invalid types.  */
22251
22252 static struct type *
22253 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22254 {
22255   struct type *this_type = NULL;
22256
22257   switch (die->tag)
22258     {
22259     case DW_TAG_class_type:
22260     case DW_TAG_interface_type:
22261     case DW_TAG_structure_type:
22262     case DW_TAG_union_type:
22263       this_type = read_structure_type (die, cu);
22264       break;
22265     case DW_TAG_enumeration_type:
22266       this_type = read_enumeration_type (die, cu);
22267       break;
22268     case DW_TAG_subprogram:
22269     case DW_TAG_subroutine_type:
22270     case DW_TAG_inlined_subroutine:
22271       this_type = read_subroutine_type (die, cu);
22272       break;
22273     case DW_TAG_array_type:
22274       this_type = read_array_type (die, cu);
22275       break;
22276     case DW_TAG_set_type:
22277       this_type = read_set_type (die, cu);
22278       break;
22279     case DW_TAG_pointer_type:
22280       this_type = read_tag_pointer_type (die, cu);
22281       break;
22282     case DW_TAG_ptr_to_member_type:
22283       this_type = read_tag_ptr_to_member_type (die, cu);
22284       break;
22285     case DW_TAG_reference_type:
22286       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22287       break;
22288     case DW_TAG_rvalue_reference_type:
22289       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22290       break;
22291     case DW_TAG_const_type:
22292       this_type = read_tag_const_type (die, cu);
22293       break;
22294     case DW_TAG_volatile_type:
22295       this_type = read_tag_volatile_type (die, cu);
22296       break;
22297     case DW_TAG_restrict_type:
22298       this_type = read_tag_restrict_type (die, cu);
22299       break;
22300     case DW_TAG_string_type:
22301       this_type = read_tag_string_type (die, cu);
22302       break;
22303     case DW_TAG_typedef:
22304       this_type = read_typedef (die, cu);
22305       break;
22306     case DW_TAG_subrange_type:
22307       this_type = read_subrange_type (die, cu);
22308       break;
22309     case DW_TAG_base_type:
22310       this_type = read_base_type (die, cu);
22311       break;
22312     case DW_TAG_unspecified_type:
22313       this_type = read_unspecified_type (die, cu);
22314       break;
22315     case DW_TAG_namespace:
22316       this_type = read_namespace_type (die, cu);
22317       break;
22318     case DW_TAG_module:
22319       this_type = read_module_type (die, cu);
22320       break;
22321     case DW_TAG_atomic_type:
22322       this_type = read_tag_atomic_type (die, cu);
22323       break;
22324     default:
22325       complaint (_("unexpected tag in read_type_die: '%s'"),
22326                  dwarf_tag_name (die->tag));
22327       break;
22328     }
22329
22330   return this_type;
22331 }
22332
22333 /* See if we can figure out if the class lives in a namespace.  We do
22334    this by looking for a member function; its demangled name will
22335    contain namespace info, if there is any.
22336    Return the computed name or NULL.
22337    Space for the result is allocated on the objfile's obstack.
22338    This is the full-die version of guess_partial_die_structure_name.
22339    In this case we know DIE has no useful parent.  */
22340
22341 static char *
22342 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22343 {
22344   struct die_info *spec_die;
22345   struct dwarf2_cu *spec_cu;
22346   struct die_info *child;
22347   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22348
22349   spec_cu = cu;
22350   spec_die = die_specification (die, &spec_cu);
22351   if (spec_die != NULL)
22352     {
22353       die = spec_die;
22354       cu = spec_cu;
22355     }
22356
22357   for (child = die->child;
22358        child != NULL;
22359        child = child->sibling)
22360     {
22361       if (child->tag == DW_TAG_subprogram)
22362         {
22363           const char *linkage_name = dw2_linkage_name (child, cu);
22364
22365           if (linkage_name != NULL)
22366             {
22367               char *actual_name
22368                 = language_class_name_from_physname (cu->language_defn,
22369                                                      linkage_name);
22370               char *name = NULL;
22371
22372               if (actual_name != NULL)
22373                 {
22374                   const char *die_name = dwarf2_name (die, cu);
22375
22376                   if (die_name != NULL
22377                       && strcmp (die_name, actual_name) != 0)
22378                     {
22379                       /* Strip off the class name from the full name.
22380                          We want the prefix.  */
22381                       int die_name_len = strlen (die_name);
22382                       int actual_name_len = strlen (actual_name);
22383
22384                       /* Test for '::' as a sanity check.  */
22385                       if (actual_name_len > die_name_len + 2
22386                           && actual_name[actual_name_len
22387                                          - die_name_len - 1] == ':')
22388                         name = (char *) obstack_copy0 (
22389                           &objfile->per_bfd->storage_obstack,
22390                           actual_name, actual_name_len - die_name_len - 2);
22391                     }
22392                 }
22393               xfree (actual_name);
22394               return name;
22395             }
22396         }
22397     }
22398
22399   return NULL;
22400 }
22401
22402 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22403    prefix part in such case.  See
22404    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22405
22406 static const char *
22407 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22408 {
22409   struct attribute *attr;
22410   const char *base;
22411
22412   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22413       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22414     return NULL;
22415
22416   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22417     return NULL;
22418
22419   attr = dw2_linkage_name_attr (die, cu);
22420   if (attr == NULL || DW_STRING (attr) == NULL)
22421     return NULL;
22422
22423   /* dwarf2_name had to be already called.  */
22424   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22425
22426   /* Strip the base name, keep any leading namespaces/classes.  */
22427   base = strrchr (DW_STRING (attr), ':');
22428   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22429     return "";
22430
22431   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22432   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22433                                  DW_STRING (attr),
22434                                  &base[-1] - DW_STRING (attr));
22435 }
22436
22437 /* Return the name of the namespace/class that DIE is defined within,
22438    or "" if we can't tell.  The caller should not xfree the result.
22439
22440    For example, if we're within the method foo() in the following
22441    code:
22442
22443    namespace N {
22444      class C {
22445        void foo () {
22446        }
22447      };
22448    }
22449
22450    then determine_prefix on foo's die will return "N::C".  */
22451
22452 static const char *
22453 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22454 {
22455   struct dwarf2_per_objfile *dwarf2_per_objfile
22456     = cu->per_cu->dwarf2_per_objfile;
22457   struct die_info *parent, *spec_die;
22458   struct dwarf2_cu *spec_cu;
22459   struct type *parent_type;
22460   const char *retval;
22461
22462   if (cu->language != language_cplus
22463       && cu->language != language_fortran && cu->language != language_d
22464       && cu->language != language_rust)
22465     return "";
22466
22467   retval = anonymous_struct_prefix (die, cu);
22468   if (retval)
22469     return retval;
22470
22471   /* We have to be careful in the presence of DW_AT_specification.
22472      For example, with GCC 3.4, given the code
22473
22474      namespace N {
22475        void foo() {
22476          // Definition of N::foo.
22477        }
22478      }
22479
22480      then we'll have a tree of DIEs like this:
22481
22482      1: DW_TAG_compile_unit
22483        2: DW_TAG_namespace        // N
22484          3: DW_TAG_subprogram     // declaration of N::foo
22485        4: DW_TAG_subprogram       // definition of N::foo
22486             DW_AT_specification   // refers to die #3
22487
22488      Thus, when processing die #4, we have to pretend that we're in
22489      the context of its DW_AT_specification, namely the contex of die
22490      #3.  */
22491   spec_cu = cu;
22492   spec_die = die_specification (die, &spec_cu);
22493   if (spec_die == NULL)
22494     parent = die->parent;
22495   else
22496     {
22497       parent = spec_die->parent;
22498       cu = spec_cu;
22499     }
22500
22501   if (parent == NULL)
22502     return "";
22503   else if (parent->building_fullname)
22504     {
22505       const char *name;
22506       const char *parent_name;
22507
22508       /* It has been seen on RealView 2.2 built binaries,
22509          DW_TAG_template_type_param types actually _defined_ as
22510          children of the parent class:
22511
22512          enum E {};
22513          template class <class Enum> Class{};
22514          Class<enum E> class_e;
22515
22516          1: DW_TAG_class_type (Class)
22517            2: DW_TAG_enumeration_type (E)
22518              3: DW_TAG_enumerator (enum1:0)
22519              3: DW_TAG_enumerator (enum2:1)
22520              ...
22521            2: DW_TAG_template_type_param
22522               DW_AT_type  DW_FORM_ref_udata (E)
22523
22524          Besides being broken debug info, it can put GDB into an
22525          infinite loop.  Consider:
22526
22527          When we're building the full name for Class<E>, we'll start
22528          at Class, and go look over its template type parameters,
22529          finding E.  We'll then try to build the full name of E, and
22530          reach here.  We're now trying to build the full name of E,
22531          and look over the parent DIE for containing scope.  In the
22532          broken case, if we followed the parent DIE of E, we'd again
22533          find Class, and once again go look at its template type
22534          arguments, etc., etc.  Simply don't consider such parent die
22535          as source-level parent of this die (it can't be, the language
22536          doesn't allow it), and break the loop here.  */
22537       name = dwarf2_name (die, cu);
22538       parent_name = dwarf2_name (parent, cu);
22539       complaint (_("template param type '%s' defined within parent '%s'"),
22540                  name ? name : "<unknown>",
22541                  parent_name ? parent_name : "<unknown>");
22542       return "";
22543     }
22544   else
22545     switch (parent->tag)
22546       {
22547       case DW_TAG_namespace:
22548         parent_type = read_type_die (parent, cu);
22549         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22550            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22551            Work around this problem here.  */
22552         if (cu->language == language_cplus
22553             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22554           return "";
22555         /* We give a name to even anonymous namespaces.  */
22556         return TYPE_NAME (parent_type);
22557       case DW_TAG_class_type:
22558       case DW_TAG_interface_type:
22559       case DW_TAG_structure_type:
22560       case DW_TAG_union_type:
22561       case DW_TAG_module:
22562         parent_type = read_type_die (parent, cu);
22563         if (TYPE_NAME (parent_type) != NULL)
22564           return TYPE_NAME (parent_type);
22565         else
22566           /* An anonymous structure is only allowed non-static data
22567              members; no typedefs, no member functions, et cetera.
22568              So it does not need a prefix.  */
22569           return "";
22570       case DW_TAG_compile_unit:
22571       case DW_TAG_partial_unit:
22572         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22573         if (cu->language == language_cplus
22574             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22575             && die->child != NULL
22576             && (die->tag == DW_TAG_class_type
22577                 || die->tag == DW_TAG_structure_type
22578                 || die->tag == DW_TAG_union_type))
22579           {
22580             char *name = guess_full_die_structure_name (die, cu);
22581             if (name != NULL)
22582               return name;
22583           }
22584         return "";
22585       case DW_TAG_enumeration_type:
22586         parent_type = read_type_die (parent, cu);
22587         if (TYPE_DECLARED_CLASS (parent_type))
22588           {
22589             if (TYPE_NAME (parent_type) != NULL)
22590               return TYPE_NAME (parent_type);
22591             return "";
22592           }
22593         /* Fall through.  */
22594       default:
22595         return determine_prefix (parent, cu);
22596       }
22597 }
22598
22599 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22600    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22601    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22602    an obconcat, otherwise allocate storage for the result.  The CU argument is
22603    used to determine the language and hence, the appropriate separator.  */
22604
22605 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22606
22607 static char *
22608 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22609                  int physname, struct dwarf2_cu *cu)
22610 {
22611   const char *lead = "";
22612   const char *sep;
22613
22614   if (suffix == NULL || suffix[0] == '\0'
22615       || prefix == NULL || prefix[0] == '\0')
22616     sep = "";
22617   else if (cu->language == language_d)
22618     {
22619       /* For D, the 'main' function could be defined in any module, but it
22620          should never be prefixed.  */
22621       if (strcmp (suffix, "D main") == 0)
22622         {
22623           prefix = "";
22624           sep = "";
22625         }
22626       else
22627         sep = ".";
22628     }
22629   else if (cu->language == language_fortran && physname)
22630     {
22631       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22632          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22633
22634       lead = "__";
22635       sep = "_MOD_";
22636     }
22637   else
22638     sep = "::";
22639
22640   if (prefix == NULL)
22641     prefix = "";
22642   if (suffix == NULL)
22643     suffix = "";
22644
22645   if (obs == NULL)
22646     {
22647       char *retval
22648         = ((char *)
22649            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22650
22651       strcpy (retval, lead);
22652       strcat (retval, prefix);
22653       strcat (retval, sep);
22654       strcat (retval, suffix);
22655       return retval;
22656     }
22657   else
22658     {
22659       /* We have an obstack.  */
22660       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22661     }
22662 }
22663
22664 /* Return sibling of die, NULL if no sibling.  */
22665
22666 static struct die_info *
22667 sibling_die (struct die_info *die)
22668 {
22669   return die->sibling;
22670 }
22671
22672 /* Get name of a die, return NULL if not found.  */
22673
22674 static const char *
22675 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22676                           struct obstack *obstack)
22677 {
22678   if (name && cu->language == language_cplus)
22679     {
22680       std::string canon_name = cp_canonicalize_string (name);
22681
22682       if (!canon_name.empty ())
22683         {
22684           if (canon_name != name)
22685             name = (const char *) obstack_copy0 (obstack,
22686                                                  canon_name.c_str (),
22687                                                  canon_name.length ());
22688         }
22689     }
22690
22691   return name;
22692 }
22693
22694 /* Get name of a die, return NULL if not found.
22695    Anonymous namespaces are converted to their magic string.  */
22696
22697 static const char *
22698 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22699 {
22700   struct attribute *attr;
22701   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22702
22703   attr = dwarf2_attr (die, DW_AT_name, cu);
22704   if ((!attr || !DW_STRING (attr))
22705       && die->tag != DW_TAG_namespace
22706       && die->tag != DW_TAG_class_type
22707       && die->tag != DW_TAG_interface_type
22708       && die->tag != DW_TAG_structure_type
22709       && die->tag != DW_TAG_union_type)
22710     return NULL;
22711
22712   switch (die->tag)
22713     {
22714     case DW_TAG_compile_unit:
22715     case DW_TAG_partial_unit:
22716       /* Compilation units have a DW_AT_name that is a filename, not
22717          a source language identifier.  */
22718     case DW_TAG_enumeration_type:
22719     case DW_TAG_enumerator:
22720       /* These tags always have simple identifiers already; no need
22721          to canonicalize them.  */
22722       return DW_STRING (attr);
22723
22724     case DW_TAG_namespace:
22725       if (attr != NULL && DW_STRING (attr) != NULL)
22726         return DW_STRING (attr);
22727       return CP_ANONYMOUS_NAMESPACE_STR;
22728
22729     case DW_TAG_class_type:
22730     case DW_TAG_interface_type:
22731     case DW_TAG_structure_type:
22732     case DW_TAG_union_type:
22733       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22734          structures or unions.  These were of the form "._%d" in GCC 4.1,
22735          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22736          and GCC 4.4.  We work around this problem by ignoring these.  */
22737       if (attr && DW_STRING (attr)
22738           && (startswith (DW_STRING (attr), "._")
22739               || startswith (DW_STRING (attr), "<anonymous")))
22740         return NULL;
22741
22742       /* GCC might emit a nameless typedef that has a linkage name.  See
22743          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22744       if (!attr || DW_STRING (attr) == NULL)
22745         {
22746           char *demangled = NULL;
22747
22748           attr = dw2_linkage_name_attr (die, cu);
22749           if (attr == NULL || DW_STRING (attr) == NULL)
22750             return NULL;
22751
22752           /* Avoid demangling DW_STRING (attr) the second time on a second
22753              call for the same DIE.  */
22754           if (!DW_STRING_IS_CANONICAL (attr))
22755             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22756
22757           if (demangled)
22758             {
22759               const char *base;
22760
22761               /* FIXME: we already did this for the partial symbol... */
22762               DW_STRING (attr)
22763                 = ((const char *)
22764                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22765                                   demangled, strlen (demangled)));
22766               DW_STRING_IS_CANONICAL (attr) = 1;
22767               xfree (demangled);
22768
22769               /* Strip any leading namespaces/classes, keep only the base name.
22770                  DW_AT_name for named DIEs does not contain the prefixes.  */
22771               base = strrchr (DW_STRING (attr), ':');
22772               if (base && base > DW_STRING (attr) && base[-1] == ':')
22773                 return &base[1];
22774               else
22775                 return DW_STRING (attr);
22776             }
22777         }
22778       break;
22779
22780     default:
22781       break;
22782     }
22783
22784   if (!DW_STRING_IS_CANONICAL (attr))
22785     {
22786       DW_STRING (attr)
22787         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22788                                     &objfile->per_bfd->storage_obstack);
22789       DW_STRING_IS_CANONICAL (attr) = 1;
22790     }
22791   return DW_STRING (attr);
22792 }
22793
22794 /* Return the die that this die in an extension of, or NULL if there
22795    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22796    containing the return value on output.  */
22797
22798 static struct die_info *
22799 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22800 {
22801   struct attribute *attr;
22802
22803   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22804   if (attr == NULL)
22805     return NULL;
22806
22807   return follow_die_ref (die, attr, ext_cu);
22808 }
22809
22810 /* A convenience function that returns an "unknown" DWARF name,
22811    including the value of V.  STR is the name of the entity being
22812    printed, e.g., "TAG".  */
22813
22814 static const char *
22815 dwarf_unknown (const char *str, unsigned v)
22816 {
22817   char *cell = get_print_cell ();
22818   xsnprintf (cell, PRINT_CELL_SIZE, "DW_%s_<unknown: %u>", str, v);
22819   return cell;
22820 }
22821
22822 /* Convert a DIE tag into its string name.  */
22823
22824 static const char *
22825 dwarf_tag_name (unsigned tag)
22826 {
22827   const char *name = get_DW_TAG_name (tag);
22828
22829   if (name == NULL)
22830     return dwarf_unknown ("TAG", tag);
22831
22832   return name;
22833 }
22834
22835 /* Convert a DWARF attribute code into its string name.  */
22836
22837 static const char *
22838 dwarf_attr_name (unsigned attr)
22839 {
22840   const char *name;
22841
22842 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22843   if (attr == DW_AT_MIPS_fde)
22844     return "DW_AT_MIPS_fde";
22845 #else
22846   if (attr == DW_AT_HP_block_index)
22847     return "DW_AT_HP_block_index";
22848 #endif
22849
22850   name = get_DW_AT_name (attr);
22851
22852   if (name == NULL)
22853     return dwarf_unknown ("AT", attr);
22854
22855   return name;
22856 }
22857
22858 /* Convert a DWARF value form code into its string name.  */
22859
22860 static const char *
22861 dwarf_form_name (unsigned form)
22862 {
22863   const char *name = get_DW_FORM_name (form);
22864
22865   if (name == NULL)
22866     return dwarf_unknown ("FORM", form);
22867
22868   return name;
22869 }
22870
22871 static const char *
22872 dwarf_bool_name (unsigned mybool)
22873 {
22874   if (mybool)
22875     return "TRUE";
22876   else
22877     return "FALSE";
22878 }
22879
22880 /* Convert a DWARF type code into its string name.  */
22881
22882 static const char *
22883 dwarf_type_encoding_name (unsigned enc)
22884 {
22885   const char *name = get_DW_ATE_name (enc);
22886
22887   if (name == NULL)
22888     return dwarf_unknown ("ATE", enc);
22889
22890   return name;
22891 }
22892
22893 static void
22894 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22895 {
22896   unsigned int i;
22897
22898   print_spaces (indent, f);
22899   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22900                       dwarf_tag_name (die->tag), die->abbrev,
22901                       sect_offset_str (die->sect_off));
22902
22903   if (die->parent != NULL)
22904     {
22905       print_spaces (indent, f);
22906       fprintf_unfiltered (f, "  parent at offset: %s\n",
22907                           sect_offset_str (die->parent->sect_off));
22908     }
22909
22910   print_spaces (indent, f);
22911   fprintf_unfiltered (f, "  has children: %s\n",
22912            dwarf_bool_name (die->child != NULL));
22913
22914   print_spaces (indent, f);
22915   fprintf_unfiltered (f, "  attributes:\n");
22916
22917   for (i = 0; i < die->num_attrs; ++i)
22918     {
22919       print_spaces (indent, f);
22920       fprintf_unfiltered (f, "    %s (%s) ",
22921                dwarf_attr_name (die->attrs[i].name),
22922                dwarf_form_name (die->attrs[i].form));
22923
22924       switch (die->attrs[i].form)
22925         {
22926         case DW_FORM_addr:
22927         case DW_FORM_addrx:
22928         case DW_FORM_GNU_addr_index:
22929           fprintf_unfiltered (f, "address: ");
22930           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22931           break;
22932         case DW_FORM_block2:
22933         case DW_FORM_block4:
22934         case DW_FORM_block:
22935         case DW_FORM_block1:
22936           fprintf_unfiltered (f, "block: size %s",
22937                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22938           break;
22939         case DW_FORM_exprloc:
22940           fprintf_unfiltered (f, "expression: size %s",
22941                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22942           break;
22943         case DW_FORM_data16:
22944           fprintf_unfiltered (f, "constant of 16 bytes");
22945           break;
22946         case DW_FORM_ref_addr:
22947           fprintf_unfiltered (f, "ref address: ");
22948           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22949           break;
22950         case DW_FORM_GNU_ref_alt:
22951           fprintf_unfiltered (f, "alt ref address: ");
22952           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22953           break;
22954         case DW_FORM_ref1:
22955         case DW_FORM_ref2:
22956         case DW_FORM_ref4:
22957         case DW_FORM_ref8:
22958         case DW_FORM_ref_udata:
22959           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22960                               (long) (DW_UNSND (&die->attrs[i])));
22961           break;
22962         case DW_FORM_data1:
22963         case DW_FORM_data2:
22964         case DW_FORM_data4:
22965         case DW_FORM_data8:
22966         case DW_FORM_udata:
22967         case DW_FORM_sdata:
22968           fprintf_unfiltered (f, "constant: %s",
22969                               pulongest (DW_UNSND (&die->attrs[i])));
22970           break;
22971         case DW_FORM_sec_offset:
22972           fprintf_unfiltered (f, "section offset: %s",
22973                               pulongest (DW_UNSND (&die->attrs[i])));
22974           break;
22975         case DW_FORM_ref_sig8:
22976           fprintf_unfiltered (f, "signature: %s",
22977                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22978           break;
22979         case DW_FORM_string:
22980         case DW_FORM_strp:
22981         case DW_FORM_line_strp:
22982         case DW_FORM_strx:
22983         case DW_FORM_GNU_str_index:
22984         case DW_FORM_GNU_strp_alt:
22985           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22986                    DW_STRING (&die->attrs[i])
22987                    ? DW_STRING (&die->attrs[i]) : "",
22988                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22989           break;
22990         case DW_FORM_flag:
22991           if (DW_UNSND (&die->attrs[i]))
22992             fprintf_unfiltered (f, "flag: TRUE");
22993           else
22994             fprintf_unfiltered (f, "flag: FALSE");
22995           break;
22996         case DW_FORM_flag_present:
22997           fprintf_unfiltered (f, "flag: TRUE");
22998           break;
22999         case DW_FORM_indirect:
23000           /* The reader will have reduced the indirect form to
23001              the "base form" so this form should not occur.  */
23002           fprintf_unfiltered (f, 
23003                               "unexpected attribute form: DW_FORM_indirect");
23004           break;
23005         case DW_FORM_implicit_const:
23006           fprintf_unfiltered (f, "constant: %s",
23007                               plongest (DW_SND (&die->attrs[i])));
23008           break;
23009         default:
23010           fprintf_unfiltered (f, "unsupported attribute form: %d.",
23011                    die->attrs[i].form);
23012           break;
23013         }
23014       fprintf_unfiltered (f, "\n");
23015     }
23016 }
23017
23018 static void
23019 dump_die_for_error (struct die_info *die)
23020 {
23021   dump_die_shallow (gdb_stderr, 0, die);
23022 }
23023
23024 static void
23025 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
23026 {
23027   int indent = level * 4;
23028
23029   gdb_assert (die != NULL);
23030
23031   if (level >= max_level)
23032     return;
23033
23034   dump_die_shallow (f, indent, die);
23035
23036   if (die->child != NULL)
23037     {
23038       print_spaces (indent, f);
23039       fprintf_unfiltered (f, "  Children:");
23040       if (level + 1 < max_level)
23041         {
23042           fprintf_unfiltered (f, "\n");
23043           dump_die_1 (f, level + 1, max_level, die->child);
23044         }
23045       else
23046         {
23047           fprintf_unfiltered (f,
23048                               " [not printed, max nesting level reached]\n");
23049         }
23050     }
23051
23052   if (die->sibling != NULL && level > 0)
23053     {
23054       dump_die_1 (f, level, max_level, die->sibling);
23055     }
23056 }
23057
23058 /* This is called from the pdie macro in gdbinit.in.
23059    It's not static so gcc will keep a copy callable from gdb.  */
23060
23061 void
23062 dump_die (struct die_info *die, int max_level)
23063 {
23064   dump_die_1 (gdb_stdlog, 0, max_level, die);
23065 }
23066
23067 static void
23068 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23069 {
23070   void **slot;
23071
23072   slot = htab_find_slot_with_hash (cu->die_hash, die,
23073                                    to_underlying (die->sect_off),
23074                                    INSERT);
23075
23076   *slot = die;
23077 }
23078
23079 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
23080    required kind.  */
23081
23082 static sect_offset
23083 dwarf2_get_ref_die_offset (const struct attribute *attr)
23084 {
23085   if (attr_form_is_ref (attr))
23086     return (sect_offset) DW_UNSND (attr);
23087
23088   complaint (_("unsupported die ref attribute form: '%s'"),
23089              dwarf_form_name (attr->form));
23090   return {};
23091 }
23092
23093 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
23094  * the value held by the attribute is not constant.  */
23095
23096 static LONGEST
23097 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
23098 {
23099   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
23100     return DW_SND (attr);
23101   else if (attr->form == DW_FORM_udata
23102            || attr->form == DW_FORM_data1
23103            || attr->form == DW_FORM_data2
23104            || attr->form == DW_FORM_data4
23105            || attr->form == DW_FORM_data8)
23106     return DW_UNSND (attr);
23107   else
23108     {
23109       /* For DW_FORM_data16 see attr_form_is_constant.  */
23110       complaint (_("Attribute value is not a constant (%s)"),
23111                  dwarf_form_name (attr->form));
23112       return default_value;
23113     }
23114 }
23115
23116 /* Follow reference or signature attribute ATTR of SRC_DIE.
23117    On entry *REF_CU is the CU of SRC_DIE.
23118    On exit *REF_CU is the CU of the result.  */
23119
23120 static struct die_info *
23121 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23122                        struct dwarf2_cu **ref_cu)
23123 {
23124   struct die_info *die;
23125
23126   if (attr_form_is_ref (attr))
23127     die = follow_die_ref (src_die, attr, ref_cu);
23128   else if (attr->form == DW_FORM_ref_sig8)
23129     die = follow_die_sig (src_die, attr, ref_cu);
23130   else
23131     {
23132       dump_die_for_error (src_die);
23133       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23134              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23135     }
23136
23137   return die;
23138 }
23139
23140 /* Follow reference OFFSET.
23141    On entry *REF_CU is the CU of the source die referencing OFFSET.
23142    On exit *REF_CU is the CU of the result.
23143    Returns NULL if OFFSET is invalid.  */
23144
23145 static struct die_info *
23146 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23147                    struct dwarf2_cu **ref_cu)
23148 {
23149   struct die_info temp_die;
23150   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23151   struct dwarf2_per_objfile *dwarf2_per_objfile
23152     = cu->per_cu->dwarf2_per_objfile;
23153
23154   gdb_assert (cu->per_cu != NULL);
23155
23156   target_cu = cu;
23157
23158   if (cu->per_cu->is_debug_types)
23159     {
23160       /* .debug_types CUs cannot reference anything outside their CU.
23161          If they need to, they have to reference a signatured type via
23162          DW_FORM_ref_sig8.  */
23163       if (!offset_in_cu_p (&cu->header, sect_off))
23164         return NULL;
23165     }
23166   else if (offset_in_dwz != cu->per_cu->is_dwz
23167            || !offset_in_cu_p (&cu->header, sect_off))
23168     {
23169       struct dwarf2_per_cu_data *per_cu;
23170
23171       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23172                                                  dwarf2_per_objfile);
23173
23174       /* If necessary, add it to the queue and load its DIEs.  */
23175       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23176         load_full_comp_unit (per_cu, false, cu->language);
23177
23178       target_cu = per_cu->cu;
23179     }
23180   else if (cu->dies == NULL)
23181     {
23182       /* We're loading full DIEs during partial symbol reading.  */
23183       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23184       load_full_comp_unit (cu->per_cu, false, language_minimal);
23185     }
23186
23187   *ref_cu = target_cu;
23188   temp_die.sect_off = sect_off;
23189
23190   if (target_cu != cu)
23191     target_cu->ancestor = cu;
23192
23193   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23194                                                   &temp_die,
23195                                                   to_underlying (sect_off));
23196 }
23197
23198 /* Follow reference attribute ATTR of SRC_DIE.
23199    On entry *REF_CU is the CU of SRC_DIE.
23200    On exit *REF_CU is the CU of the result.  */
23201
23202 static struct die_info *
23203 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23204                 struct dwarf2_cu **ref_cu)
23205 {
23206   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23207   struct dwarf2_cu *cu = *ref_cu;
23208   struct die_info *die;
23209
23210   die = follow_die_offset (sect_off,
23211                            (attr->form == DW_FORM_GNU_ref_alt
23212                             || cu->per_cu->is_dwz),
23213                            ref_cu);
23214   if (!die)
23215     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23216            "at %s [in module %s]"),
23217            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23218            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23219
23220   return die;
23221 }
23222
23223 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23224    Returned value is intended for DW_OP_call*.  Returned
23225    dwarf2_locexpr_baton->data has lifetime of
23226    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23227
23228 struct dwarf2_locexpr_baton
23229 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23230                                struct dwarf2_per_cu_data *per_cu,
23231                                CORE_ADDR (*get_frame_pc) (void *baton),
23232                                void *baton, bool resolve_abstract_p)
23233 {
23234   struct dwarf2_cu *cu;
23235   struct die_info *die;
23236   struct attribute *attr;
23237   struct dwarf2_locexpr_baton retval;
23238   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
23239   struct objfile *objfile = dwarf2_per_objfile->objfile;
23240
23241   if (per_cu->cu == NULL)
23242     load_cu (per_cu, false);
23243   cu = per_cu->cu;
23244   if (cu == NULL)
23245     {
23246       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23247          Instead just throw an error, not much else we can do.  */
23248       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23249              sect_offset_str (sect_off), objfile_name (objfile));
23250     }
23251
23252   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23253   if (!die)
23254     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23255            sect_offset_str (sect_off), objfile_name (objfile));
23256
23257   attr = dwarf2_attr (die, DW_AT_location, cu);
23258   if (!attr && resolve_abstract_p
23259       && (dwarf2_per_objfile->abstract_to_concrete.find (die->sect_off)
23260           != dwarf2_per_objfile->abstract_to_concrete.end ()))
23261     {
23262       CORE_ADDR pc = (*get_frame_pc) (baton);
23263
23264       for (const auto &cand_off
23265              : dwarf2_per_objfile->abstract_to_concrete[die->sect_off])
23266         {
23267           struct dwarf2_cu *cand_cu = cu;
23268           struct die_info *cand
23269             = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
23270           if (!cand
23271               || !cand->parent
23272               || cand->parent->tag != DW_TAG_subprogram)
23273             continue;
23274
23275           CORE_ADDR pc_low, pc_high;
23276           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
23277           if (pc_low == ((CORE_ADDR) -1)
23278               || !(pc_low <= pc && pc < pc_high))
23279             continue;
23280
23281           die = cand;
23282           attr = dwarf2_attr (die, DW_AT_location, cu);
23283           break;
23284         }
23285     }
23286
23287   if (!attr)
23288     {
23289       /* DWARF: "If there is no such attribute, then there is no effect.".
23290          DATA is ignored if SIZE is 0.  */
23291
23292       retval.data = NULL;
23293       retval.size = 0;
23294     }
23295   else if (attr_form_is_section_offset (attr))
23296     {
23297       struct dwarf2_loclist_baton loclist_baton;
23298       CORE_ADDR pc = (*get_frame_pc) (baton);
23299       size_t size;
23300
23301       fill_in_loclist_baton (cu, &loclist_baton, attr);
23302
23303       retval.data = dwarf2_find_location_expression (&loclist_baton,
23304                                                      &size, pc);
23305       retval.size = size;
23306     }
23307   else
23308     {
23309       if (!attr_form_is_block (attr))
23310         error (_("Dwarf Error: DIE at %s referenced in module %s "
23311                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23312                sect_offset_str (sect_off), objfile_name (objfile));
23313
23314       retval.data = DW_BLOCK (attr)->data;
23315       retval.size = DW_BLOCK (attr)->size;
23316     }
23317   retval.per_cu = cu->per_cu;
23318
23319   age_cached_comp_units (dwarf2_per_objfile);
23320
23321   return retval;
23322 }
23323
23324 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23325    offset.  */
23326
23327 struct dwarf2_locexpr_baton
23328 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23329                              struct dwarf2_per_cu_data *per_cu,
23330                              CORE_ADDR (*get_frame_pc) (void *baton),
23331                              void *baton)
23332 {
23333   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23334
23335   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23336 }
23337
23338 /* Write a constant of a given type as target-ordered bytes into
23339    OBSTACK.  */
23340
23341 static const gdb_byte *
23342 write_constant_as_bytes (struct obstack *obstack,
23343                          enum bfd_endian byte_order,
23344                          struct type *type,
23345                          ULONGEST value,
23346                          LONGEST *len)
23347 {
23348   gdb_byte *result;
23349
23350   *len = TYPE_LENGTH (type);
23351   result = (gdb_byte *) obstack_alloc (obstack, *len);
23352   store_unsigned_integer (result, *len, byte_order, value);
23353
23354   return result;
23355 }
23356
23357 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23358    pointer to the constant bytes and set LEN to the length of the
23359    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23360    does not have a DW_AT_const_value, return NULL.  */
23361
23362 const gdb_byte *
23363 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23364                              struct dwarf2_per_cu_data *per_cu,
23365                              struct obstack *obstack,
23366                              LONGEST *len)
23367 {
23368   struct dwarf2_cu *cu;
23369   struct die_info *die;
23370   struct attribute *attr;
23371   const gdb_byte *result = NULL;
23372   struct type *type;
23373   LONGEST value;
23374   enum bfd_endian byte_order;
23375   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23376
23377   if (per_cu->cu == NULL)
23378     load_cu (per_cu, false);
23379   cu = per_cu->cu;
23380   if (cu == NULL)
23381     {
23382       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23383          Instead just throw an error, not much else we can do.  */
23384       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23385              sect_offset_str (sect_off), objfile_name (objfile));
23386     }
23387
23388   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23389   if (!die)
23390     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23391            sect_offset_str (sect_off), objfile_name (objfile));
23392
23393   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23394   if (attr == NULL)
23395     return NULL;
23396
23397   byte_order = (bfd_big_endian (objfile->obfd)
23398                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23399
23400   switch (attr->form)
23401     {
23402     case DW_FORM_addr:
23403     case DW_FORM_addrx:
23404     case DW_FORM_GNU_addr_index:
23405       {
23406         gdb_byte *tem;
23407
23408         *len = cu->header.addr_size;
23409         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23410         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23411         result = tem;
23412       }
23413       break;
23414     case DW_FORM_string:
23415     case DW_FORM_strp:
23416     case DW_FORM_strx:
23417     case DW_FORM_GNU_str_index:
23418     case DW_FORM_GNU_strp_alt:
23419       /* DW_STRING is already allocated on the objfile obstack, point
23420          directly to it.  */
23421       result = (const gdb_byte *) DW_STRING (attr);
23422       *len = strlen (DW_STRING (attr));
23423       break;
23424     case DW_FORM_block1:
23425     case DW_FORM_block2:
23426     case DW_FORM_block4:
23427     case DW_FORM_block:
23428     case DW_FORM_exprloc:
23429     case DW_FORM_data16:
23430       result = DW_BLOCK (attr)->data;
23431       *len = DW_BLOCK (attr)->size;
23432       break;
23433
23434       /* The DW_AT_const_value attributes are supposed to carry the
23435          symbol's value "represented as it would be on the target
23436          architecture."  By the time we get here, it's already been
23437          converted to host endianness, so we just need to sign- or
23438          zero-extend it as appropriate.  */
23439     case DW_FORM_data1:
23440       type = die_type (die, cu);
23441       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23442       if (result == NULL)
23443         result = write_constant_as_bytes (obstack, byte_order,
23444                                           type, value, len);
23445       break;
23446     case DW_FORM_data2:
23447       type = die_type (die, cu);
23448       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23449       if (result == NULL)
23450         result = write_constant_as_bytes (obstack, byte_order,
23451                                           type, value, len);
23452       break;
23453     case DW_FORM_data4:
23454       type = die_type (die, cu);
23455       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23456       if (result == NULL)
23457         result = write_constant_as_bytes (obstack, byte_order,
23458                                           type, value, len);
23459       break;
23460     case DW_FORM_data8:
23461       type = die_type (die, cu);
23462       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23463       if (result == NULL)
23464         result = write_constant_as_bytes (obstack, byte_order,
23465                                           type, value, len);
23466       break;
23467
23468     case DW_FORM_sdata:
23469     case DW_FORM_implicit_const:
23470       type = die_type (die, cu);
23471       result = write_constant_as_bytes (obstack, byte_order,
23472                                         type, DW_SND (attr), len);
23473       break;
23474
23475     case DW_FORM_udata:
23476       type = die_type (die, cu);
23477       result = write_constant_as_bytes (obstack, byte_order,
23478                                         type, DW_UNSND (attr), len);
23479       break;
23480
23481     default:
23482       complaint (_("unsupported const value attribute form: '%s'"),
23483                  dwarf_form_name (attr->form));
23484       break;
23485     }
23486
23487   return result;
23488 }
23489
23490 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23491    valid type for this die is found.  */
23492
23493 struct type *
23494 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23495                                 struct dwarf2_per_cu_data *per_cu)
23496 {
23497   struct dwarf2_cu *cu;
23498   struct die_info *die;
23499
23500   if (per_cu->cu == NULL)
23501     load_cu (per_cu, false);
23502   cu = per_cu->cu;
23503   if (!cu)
23504     return NULL;
23505
23506   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23507   if (!die)
23508     return NULL;
23509
23510   return die_type (die, cu);
23511 }
23512
23513 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23514    PER_CU.  */
23515
23516 struct type *
23517 dwarf2_get_die_type (cu_offset die_offset,
23518                      struct dwarf2_per_cu_data *per_cu)
23519 {
23520   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23521   return get_die_type_at_offset (die_offset_sect, per_cu);
23522 }
23523
23524 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23525    On entry *REF_CU is the CU of SRC_DIE.
23526    On exit *REF_CU is the CU of the result.
23527    Returns NULL if the referenced DIE isn't found.  */
23528
23529 static struct die_info *
23530 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23531                   struct dwarf2_cu **ref_cu)
23532 {
23533   struct die_info temp_die;
23534   struct dwarf2_cu *sig_cu, *cu = *ref_cu;
23535   struct die_info *die;
23536
23537   /* While it might be nice to assert sig_type->type == NULL here,
23538      we can get here for DW_AT_imported_declaration where we need
23539      the DIE not the type.  */
23540
23541   /* If necessary, add it to the queue and load its DIEs.  */
23542
23543   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23544     read_signatured_type (sig_type);
23545
23546   sig_cu = sig_type->per_cu.cu;
23547   gdb_assert (sig_cu != NULL);
23548   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23549   temp_die.sect_off = sig_type->type_offset_in_section;
23550   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23551                                                  to_underlying (temp_die.sect_off));
23552   if (die)
23553     {
23554       struct dwarf2_per_objfile *dwarf2_per_objfile
23555         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23556
23557       /* For .gdb_index version 7 keep track of included TUs.
23558          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23559       if (dwarf2_per_objfile->index_table != NULL
23560           && dwarf2_per_objfile->index_table->version <= 7)
23561         {
23562           VEC_safe_push (dwarf2_per_cu_ptr,
23563                          (*ref_cu)->per_cu->imported_symtabs,
23564                          sig_cu->per_cu);
23565         }
23566
23567       *ref_cu = sig_cu;
23568       if (sig_cu != cu)
23569         sig_cu->ancestor = cu;
23570
23571       return die;
23572     }
23573
23574   return NULL;
23575 }
23576
23577 /* Follow signatured type referenced by ATTR in SRC_DIE.
23578    On entry *REF_CU is the CU of SRC_DIE.
23579    On exit *REF_CU is the CU of the result.
23580    The result is the DIE of the type.
23581    If the referenced type cannot be found an error is thrown.  */
23582
23583 static struct die_info *
23584 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23585                 struct dwarf2_cu **ref_cu)
23586 {
23587   ULONGEST signature = DW_SIGNATURE (attr);
23588   struct signatured_type *sig_type;
23589   struct die_info *die;
23590
23591   gdb_assert (attr->form == DW_FORM_ref_sig8);
23592
23593   sig_type = lookup_signatured_type (*ref_cu, signature);
23594   /* sig_type will be NULL if the signatured type is missing from
23595      the debug info.  */
23596   if (sig_type == NULL)
23597     {
23598       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23599                " from DIE at %s [in module %s]"),
23600              hex_string (signature), sect_offset_str (src_die->sect_off),
23601              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23602     }
23603
23604   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23605   if (die == NULL)
23606     {
23607       dump_die_for_error (src_die);
23608       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23609                " from DIE at %s [in module %s]"),
23610              hex_string (signature), sect_offset_str (src_die->sect_off),
23611              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23612     }
23613
23614   return die;
23615 }
23616
23617 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23618    reading in and processing the type unit if necessary.  */
23619
23620 static struct type *
23621 get_signatured_type (struct die_info *die, ULONGEST signature,
23622                      struct dwarf2_cu *cu)
23623 {
23624   struct dwarf2_per_objfile *dwarf2_per_objfile
23625     = cu->per_cu->dwarf2_per_objfile;
23626   struct signatured_type *sig_type;
23627   struct dwarf2_cu *type_cu;
23628   struct die_info *type_die;
23629   struct type *type;
23630
23631   sig_type = lookup_signatured_type (cu, signature);
23632   /* sig_type will be NULL if the signatured type is missing from
23633      the debug info.  */
23634   if (sig_type == NULL)
23635     {
23636       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23637                    " from DIE at %s [in module %s]"),
23638                  hex_string (signature), sect_offset_str (die->sect_off),
23639                  objfile_name (dwarf2_per_objfile->objfile));
23640       return build_error_marker_type (cu, die);
23641     }
23642
23643   /* If we already know the type we're done.  */
23644   if (sig_type->type != NULL)
23645     return sig_type->type;
23646
23647   type_cu = cu;
23648   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23649   if (type_die != NULL)
23650     {
23651       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23652          is created.  This is important, for example, because for c++ classes
23653          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23654       type = read_type_die (type_die, type_cu);
23655       if (type == NULL)
23656         {
23657           complaint (_("Dwarf Error: Cannot build signatured type %s"
23658                        " referenced from DIE at %s [in module %s]"),
23659                      hex_string (signature), sect_offset_str (die->sect_off),
23660                      objfile_name (dwarf2_per_objfile->objfile));
23661           type = build_error_marker_type (cu, die);
23662         }
23663     }
23664   else
23665     {
23666       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23667                    " from DIE at %s [in module %s]"),
23668                  hex_string (signature), sect_offset_str (die->sect_off),
23669                  objfile_name (dwarf2_per_objfile->objfile));
23670       type = build_error_marker_type (cu, die);
23671     }
23672   sig_type->type = type;
23673
23674   return type;
23675 }
23676
23677 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23678    reading in and processing the type unit if necessary.  */
23679
23680 static struct type *
23681 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23682                           struct dwarf2_cu *cu) /* ARI: editCase function */
23683 {
23684   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23685   if (attr_form_is_ref (attr))
23686     {
23687       struct dwarf2_cu *type_cu = cu;
23688       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23689
23690       return read_type_die (type_die, type_cu);
23691     }
23692   else if (attr->form == DW_FORM_ref_sig8)
23693     {
23694       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23695     }
23696   else
23697     {
23698       struct dwarf2_per_objfile *dwarf2_per_objfile
23699         = cu->per_cu->dwarf2_per_objfile;
23700
23701       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23702                    " at %s [in module %s]"),
23703                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23704                  objfile_name (dwarf2_per_objfile->objfile));
23705       return build_error_marker_type (cu, die);
23706     }
23707 }
23708
23709 /* Load the DIEs associated with type unit PER_CU into memory.  */
23710
23711 static void
23712 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23713 {
23714   struct signatured_type *sig_type;
23715
23716   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23717   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23718
23719   /* We have the per_cu, but we need the signatured_type.
23720      Fortunately this is an easy translation.  */
23721   gdb_assert (per_cu->is_debug_types);
23722   sig_type = (struct signatured_type *) per_cu;
23723
23724   gdb_assert (per_cu->cu == NULL);
23725
23726   read_signatured_type (sig_type);
23727
23728   gdb_assert (per_cu->cu != NULL);
23729 }
23730
23731 /* die_reader_func for read_signatured_type.
23732    This is identical to load_full_comp_unit_reader,
23733    but is kept separate for now.  */
23734
23735 static void
23736 read_signatured_type_reader (const struct die_reader_specs *reader,
23737                              const gdb_byte *info_ptr,
23738                              struct die_info *comp_unit_die,
23739                              int has_children,
23740                              void *data)
23741 {
23742   struct dwarf2_cu *cu = reader->cu;
23743
23744   gdb_assert (cu->die_hash == NULL);
23745   cu->die_hash =
23746     htab_create_alloc_ex (cu->header.length / 12,
23747                           die_hash,
23748                           die_eq,
23749                           NULL,
23750                           &cu->comp_unit_obstack,
23751                           hashtab_obstack_allocate,
23752                           dummy_obstack_deallocate);
23753
23754   if (has_children)
23755     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23756                                                   &info_ptr, comp_unit_die);
23757   cu->dies = comp_unit_die;
23758   /* comp_unit_die is not stored in die_hash, no need.  */
23759
23760   /* We try not to read any attributes in this function, because not
23761      all CUs needed for references have been loaded yet, and symbol
23762      table processing isn't initialized.  But we have to set the CU language,
23763      or we won't be able to build types correctly.
23764      Similarly, if we do not read the producer, we can not apply
23765      producer-specific interpretation.  */
23766   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23767 }
23768
23769 /* Read in a signatured type and build its CU and DIEs.
23770    If the type is a stub for the real type in a DWO file,
23771    read in the real type from the DWO file as well.  */
23772
23773 static void
23774 read_signatured_type (struct signatured_type *sig_type)
23775 {
23776   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23777
23778   gdb_assert (per_cu->is_debug_types);
23779   gdb_assert (per_cu->cu == NULL);
23780
23781   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23782                            read_signatured_type_reader, NULL);
23783   sig_type->per_cu.tu_read = 1;
23784 }
23785
23786 /* Decode simple location descriptions.
23787    Given a pointer to a dwarf block that defines a location, compute
23788    the location and return the value.
23789
23790    NOTE drow/2003-11-18: This function is called in two situations
23791    now: for the address of static or global variables (partial symbols
23792    only) and for offsets into structures which are expected to be
23793    (more or less) constant.  The partial symbol case should go away,
23794    and only the constant case should remain.  That will let this
23795    function complain more accurately.  A few special modes are allowed
23796    without complaint for global variables (for instance, global
23797    register values and thread-local values).
23798
23799    A location description containing no operations indicates that the
23800    object is optimized out.  The return value is 0 for that case.
23801    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23802    callers will only want a very basic result and this can become a
23803    complaint.
23804
23805    Note that stack[0] is unused except as a default error return.  */
23806
23807 static CORE_ADDR
23808 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23809 {
23810   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23811   size_t i;
23812   size_t size = blk->size;
23813   const gdb_byte *data = blk->data;
23814   CORE_ADDR stack[64];
23815   int stacki;
23816   unsigned int bytes_read, unsnd;
23817   gdb_byte op;
23818
23819   i = 0;
23820   stacki = 0;
23821   stack[stacki] = 0;
23822   stack[++stacki] = 0;
23823
23824   while (i < size)
23825     {
23826       op = data[i++];
23827       switch (op)
23828         {
23829         case DW_OP_lit0:
23830         case DW_OP_lit1:
23831         case DW_OP_lit2:
23832         case DW_OP_lit3:
23833         case DW_OP_lit4:
23834         case DW_OP_lit5:
23835         case DW_OP_lit6:
23836         case DW_OP_lit7:
23837         case DW_OP_lit8:
23838         case DW_OP_lit9:
23839         case DW_OP_lit10:
23840         case DW_OP_lit11:
23841         case DW_OP_lit12:
23842         case DW_OP_lit13:
23843         case DW_OP_lit14:
23844         case DW_OP_lit15:
23845         case DW_OP_lit16:
23846         case DW_OP_lit17:
23847         case DW_OP_lit18:
23848         case DW_OP_lit19:
23849         case DW_OP_lit20:
23850         case DW_OP_lit21:
23851         case DW_OP_lit22:
23852         case DW_OP_lit23:
23853         case DW_OP_lit24:
23854         case DW_OP_lit25:
23855         case DW_OP_lit26:
23856         case DW_OP_lit27:
23857         case DW_OP_lit28:
23858         case DW_OP_lit29:
23859         case DW_OP_lit30:
23860         case DW_OP_lit31:
23861           stack[++stacki] = op - DW_OP_lit0;
23862           break;
23863
23864         case DW_OP_reg0:
23865         case DW_OP_reg1:
23866         case DW_OP_reg2:
23867         case DW_OP_reg3:
23868         case DW_OP_reg4:
23869         case DW_OP_reg5:
23870         case DW_OP_reg6:
23871         case DW_OP_reg7:
23872         case DW_OP_reg8:
23873         case DW_OP_reg9:
23874         case DW_OP_reg10:
23875         case DW_OP_reg11:
23876         case DW_OP_reg12:
23877         case DW_OP_reg13:
23878         case DW_OP_reg14:
23879         case DW_OP_reg15:
23880         case DW_OP_reg16:
23881         case DW_OP_reg17:
23882         case DW_OP_reg18:
23883         case DW_OP_reg19:
23884         case DW_OP_reg20:
23885         case DW_OP_reg21:
23886         case DW_OP_reg22:
23887         case DW_OP_reg23:
23888         case DW_OP_reg24:
23889         case DW_OP_reg25:
23890         case DW_OP_reg26:
23891         case DW_OP_reg27:
23892         case DW_OP_reg28:
23893         case DW_OP_reg29:
23894         case DW_OP_reg30:
23895         case DW_OP_reg31:
23896           stack[++stacki] = op - DW_OP_reg0;
23897           if (i < size)
23898             dwarf2_complex_location_expr_complaint ();
23899           break;
23900
23901         case DW_OP_regx:
23902           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23903           i += bytes_read;
23904           stack[++stacki] = unsnd;
23905           if (i < size)
23906             dwarf2_complex_location_expr_complaint ();
23907           break;
23908
23909         case DW_OP_addr:
23910           stack[++stacki] = read_address (objfile->obfd, &data[i],
23911                                           cu, &bytes_read);
23912           i += bytes_read;
23913           break;
23914
23915         case DW_OP_const1u:
23916           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23917           i += 1;
23918           break;
23919
23920         case DW_OP_const1s:
23921           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23922           i += 1;
23923           break;
23924
23925         case DW_OP_const2u:
23926           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23927           i += 2;
23928           break;
23929
23930         case DW_OP_const2s:
23931           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23932           i += 2;
23933           break;
23934
23935         case DW_OP_const4u:
23936           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23937           i += 4;
23938           break;
23939
23940         case DW_OP_const4s:
23941           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23942           i += 4;
23943           break;
23944
23945         case DW_OP_const8u:
23946           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23947           i += 8;
23948           break;
23949
23950         case DW_OP_constu:
23951           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23952                                                   &bytes_read);
23953           i += bytes_read;
23954           break;
23955
23956         case DW_OP_consts:
23957           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23958           i += bytes_read;
23959           break;
23960
23961         case DW_OP_dup:
23962           stack[stacki + 1] = stack[stacki];
23963           stacki++;
23964           break;
23965
23966         case DW_OP_plus:
23967           stack[stacki - 1] += stack[stacki];
23968           stacki--;
23969           break;
23970
23971         case DW_OP_plus_uconst:
23972           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23973                                                  &bytes_read);
23974           i += bytes_read;
23975           break;
23976
23977         case DW_OP_minus:
23978           stack[stacki - 1] -= stack[stacki];
23979           stacki--;
23980           break;
23981
23982         case DW_OP_deref:
23983           /* If we're not the last op, then we definitely can't encode
23984              this using GDB's address_class enum.  This is valid for partial
23985              global symbols, although the variable's address will be bogus
23986              in the psymtab.  */
23987           if (i < size)
23988             dwarf2_complex_location_expr_complaint ();
23989           break;
23990
23991         case DW_OP_GNU_push_tls_address:
23992         case DW_OP_form_tls_address:
23993           /* The top of the stack has the offset from the beginning
23994              of the thread control block at which the variable is located.  */
23995           /* Nothing should follow this operator, so the top of stack would
23996              be returned.  */
23997           /* This is valid for partial global symbols, but the variable's
23998              address will be bogus in the psymtab.  Make it always at least
23999              non-zero to not look as a variable garbage collected by linker
24000              which have DW_OP_addr 0.  */
24001           if (i < size)
24002             dwarf2_complex_location_expr_complaint ();
24003           stack[stacki]++;
24004           break;
24005
24006         case DW_OP_GNU_uninit:
24007           break;
24008
24009         case DW_OP_addrx:
24010         case DW_OP_GNU_addr_index:
24011         case DW_OP_GNU_const_index:
24012           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
24013                                                          &bytes_read);
24014           i += bytes_read;
24015           break;
24016
24017         default:
24018           {
24019             const char *name = get_DW_OP_name (op);
24020
24021             if (name)
24022               complaint (_("unsupported stack op: '%s'"),
24023                          name);
24024             else
24025               complaint (_("unsupported stack op: '%02x'"),
24026                          op);
24027           }
24028
24029           return (stack[stacki]);
24030         }
24031
24032       /* Enforce maximum stack depth of SIZE-1 to avoid writing
24033          outside of the allocated space.  Also enforce minimum>0.  */
24034       if (stacki >= ARRAY_SIZE (stack) - 1)
24035         {
24036           complaint (_("location description stack overflow"));
24037           return 0;
24038         }
24039
24040       if (stacki <= 0)
24041         {
24042           complaint (_("location description stack underflow"));
24043           return 0;
24044         }
24045     }
24046   return (stack[stacki]);
24047 }
24048
24049 /* memory allocation interface */
24050
24051 static struct dwarf_block *
24052 dwarf_alloc_block (struct dwarf2_cu *cu)
24053 {
24054   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24055 }
24056
24057 static struct die_info *
24058 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24059 {
24060   struct die_info *die;
24061   size_t size = sizeof (struct die_info);
24062
24063   if (num_attrs > 1)
24064     size += (num_attrs - 1) * sizeof (struct attribute);
24065
24066   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24067   memset (die, 0, sizeof (struct die_info));
24068   return (die);
24069 }
24070
24071 \f
24072 /* Macro support.  */
24073
24074 /* Return file name relative to the compilation directory of file number I in
24075    *LH's file name table.  The result is allocated using xmalloc; the caller is
24076    responsible for freeing it.  */
24077
24078 static char *
24079 file_file_name (int file, struct line_header *lh)
24080 {
24081   /* Is the file number a valid index into the line header's file name
24082      table?  Remember that file numbers start with one, not zero.  */
24083   if (1 <= file && file <= lh->file_names.size ())
24084     {
24085       const file_entry &fe = lh->file_names[file - 1];
24086
24087       if (!IS_ABSOLUTE_PATH (fe.name))
24088         {
24089           const char *dir = fe.include_dir (lh);
24090           if (dir != NULL)
24091             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
24092         }
24093       return xstrdup (fe.name);
24094     }
24095   else
24096     {
24097       /* The compiler produced a bogus file number.  We can at least
24098          record the macro definitions made in the file, even if we
24099          won't be able to find the file by name.  */
24100       char fake_name[80];
24101
24102       xsnprintf (fake_name, sizeof (fake_name),
24103                  "<bad macro file number %d>", file);
24104
24105       complaint (_("bad file number in macro information (%d)"),
24106                  file);
24107
24108       return xstrdup (fake_name);
24109     }
24110 }
24111
24112 /* Return the full name of file number I in *LH's file name table.
24113    Use COMP_DIR as the name of the current directory of the
24114    compilation.  The result is allocated using xmalloc; the caller is
24115    responsible for freeing it.  */
24116 static char *
24117 file_full_name (int file, struct line_header *lh, const char *comp_dir)
24118 {
24119   /* Is the file number a valid index into the line header's file name
24120      table?  Remember that file numbers start with one, not zero.  */
24121   if (1 <= file && file <= lh->file_names.size ())
24122     {
24123       char *relative = file_file_name (file, lh);
24124
24125       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
24126         return relative;
24127       return reconcat (relative, comp_dir, SLASH_STRING,
24128                        relative, (char *) NULL);
24129     }
24130   else
24131     return file_file_name (file, lh);
24132 }
24133
24134
24135 static struct macro_source_file *
24136 macro_start_file (struct dwarf2_cu *cu,
24137                   int file, int line,
24138                   struct macro_source_file *current_file,
24139                   struct line_header *lh)
24140 {
24141   /* File name relative to the compilation directory of this source file.  */
24142   char *file_name = file_file_name (file, lh);
24143
24144   if (! current_file)
24145     {
24146       /* Note: We don't create a macro table for this compilation unit
24147          at all until we actually get a filename.  */
24148       struct macro_table *macro_table = cu->get_builder ()->get_macro_table ();
24149
24150       /* If we have no current file, then this must be the start_file
24151          directive for the compilation unit's main source file.  */
24152       current_file = macro_set_main (macro_table, file_name);
24153       macro_define_special (macro_table);
24154     }
24155   else
24156     current_file = macro_include (current_file, line, file_name);
24157
24158   xfree (file_name);
24159
24160   return current_file;
24161 }
24162
24163 static const char *
24164 consume_improper_spaces (const char *p, const char *body)
24165 {
24166   if (*p == ' ')
24167     {
24168       complaint (_("macro definition contains spaces "
24169                    "in formal argument list:\n`%s'"),
24170                  body);
24171
24172       while (*p == ' ')
24173         p++;
24174     }
24175
24176   return p;
24177 }
24178
24179
24180 static void
24181 parse_macro_definition (struct macro_source_file *file, int line,
24182                         const char *body)
24183 {
24184   const char *p;
24185
24186   /* The body string takes one of two forms.  For object-like macro
24187      definitions, it should be:
24188
24189         <macro name> " " <definition>
24190
24191      For function-like macro definitions, it should be:
24192
24193         <macro name> "() " <definition>
24194      or
24195         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24196
24197      Spaces may appear only where explicitly indicated, and in the
24198      <definition>.
24199
24200      The Dwarf 2 spec says that an object-like macro's name is always
24201      followed by a space, but versions of GCC around March 2002 omit
24202      the space when the macro's definition is the empty string.
24203
24204      The Dwarf 2 spec says that there should be no spaces between the
24205      formal arguments in a function-like macro's formal argument list,
24206      but versions of GCC around March 2002 include spaces after the
24207      commas.  */
24208
24209
24210   /* Find the extent of the macro name.  The macro name is terminated
24211      by either a space or null character (for an object-like macro) or
24212      an opening paren (for a function-like macro).  */
24213   for (p = body; *p; p++)
24214     if (*p == ' ' || *p == '(')
24215       break;
24216
24217   if (*p == ' ' || *p == '\0')
24218     {
24219       /* It's an object-like macro.  */
24220       int name_len = p - body;
24221       char *name = savestring (body, name_len);
24222       const char *replacement;
24223
24224       if (*p == ' ')
24225         replacement = body + name_len + 1;
24226       else
24227         {
24228           dwarf2_macro_malformed_definition_complaint (body);
24229           replacement = body + name_len;
24230         }
24231
24232       macro_define_object (file, line, name, replacement);
24233
24234       xfree (name);
24235     }
24236   else if (*p == '(')
24237     {
24238       /* It's a function-like macro.  */
24239       char *name = savestring (body, p - body);
24240       int argc = 0;
24241       int argv_size = 1;
24242       char **argv = XNEWVEC (char *, argv_size);
24243
24244       p++;
24245
24246       p = consume_improper_spaces (p, body);
24247
24248       /* Parse the formal argument list.  */
24249       while (*p && *p != ')')
24250         {
24251           /* Find the extent of the current argument name.  */
24252           const char *arg_start = p;
24253
24254           while (*p && *p != ',' && *p != ')' && *p != ' ')
24255             p++;
24256
24257           if (! *p || p == arg_start)
24258             dwarf2_macro_malformed_definition_complaint (body);
24259           else
24260             {
24261               /* Make sure argv has room for the new argument.  */
24262               if (argc >= argv_size)
24263                 {
24264                   argv_size *= 2;
24265                   argv = XRESIZEVEC (char *, argv, argv_size);
24266                 }
24267
24268               argv[argc++] = savestring (arg_start, p - arg_start);
24269             }
24270
24271           p = consume_improper_spaces (p, body);
24272
24273           /* Consume the comma, if present.  */
24274           if (*p == ',')
24275             {
24276               p++;
24277
24278               p = consume_improper_spaces (p, body);
24279             }
24280         }
24281
24282       if (*p == ')')
24283         {
24284           p++;
24285
24286           if (*p == ' ')
24287             /* Perfectly formed definition, no complaints.  */
24288             macro_define_function (file, line, name,
24289                                    argc, (const char **) argv,
24290                                    p + 1);
24291           else if (*p == '\0')
24292             {
24293               /* Complain, but do define it.  */
24294               dwarf2_macro_malformed_definition_complaint (body);
24295               macro_define_function (file, line, name,
24296                                      argc, (const char **) argv,
24297                                      p);
24298             }
24299           else
24300             /* Just complain.  */
24301             dwarf2_macro_malformed_definition_complaint (body);
24302         }
24303       else
24304         /* Just complain.  */
24305         dwarf2_macro_malformed_definition_complaint (body);
24306
24307       xfree (name);
24308       {
24309         int i;
24310
24311         for (i = 0; i < argc; i++)
24312           xfree (argv[i]);
24313       }
24314       xfree (argv);
24315     }
24316   else
24317     dwarf2_macro_malformed_definition_complaint (body);
24318 }
24319
24320 /* Skip some bytes from BYTES according to the form given in FORM.
24321    Returns the new pointer.  */
24322
24323 static const gdb_byte *
24324 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24325                  enum dwarf_form form,
24326                  unsigned int offset_size,
24327                  struct dwarf2_section_info *section)
24328 {
24329   unsigned int bytes_read;
24330
24331   switch (form)
24332     {
24333     case DW_FORM_data1:
24334     case DW_FORM_flag:
24335       ++bytes;
24336       break;
24337
24338     case DW_FORM_data2:
24339       bytes += 2;
24340       break;
24341
24342     case DW_FORM_data4:
24343       bytes += 4;
24344       break;
24345
24346     case DW_FORM_data8:
24347       bytes += 8;
24348       break;
24349
24350     case DW_FORM_data16:
24351       bytes += 16;
24352       break;
24353
24354     case DW_FORM_string:
24355       read_direct_string (abfd, bytes, &bytes_read);
24356       bytes += bytes_read;
24357       break;
24358
24359     case DW_FORM_sec_offset:
24360     case DW_FORM_strp:
24361     case DW_FORM_GNU_strp_alt:
24362       bytes += offset_size;
24363       break;
24364
24365     case DW_FORM_block:
24366       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24367       bytes += bytes_read;
24368       break;
24369
24370     case DW_FORM_block1:
24371       bytes += 1 + read_1_byte (abfd, bytes);
24372       break;
24373     case DW_FORM_block2:
24374       bytes += 2 + read_2_bytes (abfd, bytes);
24375       break;
24376     case DW_FORM_block4:
24377       bytes += 4 + read_4_bytes (abfd, bytes);
24378       break;
24379
24380     case DW_FORM_addrx:
24381     case DW_FORM_sdata:
24382     case DW_FORM_strx:
24383     case DW_FORM_udata:
24384     case DW_FORM_GNU_addr_index:
24385     case DW_FORM_GNU_str_index:
24386       bytes = gdb_skip_leb128 (bytes, buffer_end);
24387       if (bytes == NULL)
24388         {
24389           dwarf2_section_buffer_overflow_complaint (section);
24390           return NULL;
24391         }
24392       break;
24393
24394     case DW_FORM_implicit_const:
24395       break;
24396
24397     default:
24398       {
24399         complaint (_("invalid form 0x%x in `%s'"),
24400                    form, get_section_name (section));
24401         return NULL;
24402       }
24403     }
24404
24405   return bytes;
24406 }
24407
24408 /* A helper for dwarf_decode_macros that handles skipping an unknown
24409    opcode.  Returns an updated pointer to the macro data buffer; or,
24410    on error, issues a complaint and returns NULL.  */
24411
24412 static const gdb_byte *
24413 skip_unknown_opcode (unsigned int opcode,
24414                      const gdb_byte **opcode_definitions,
24415                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24416                      bfd *abfd,
24417                      unsigned int offset_size,
24418                      struct dwarf2_section_info *section)
24419 {
24420   unsigned int bytes_read, i;
24421   unsigned long arg;
24422   const gdb_byte *defn;
24423
24424   if (opcode_definitions[opcode] == NULL)
24425     {
24426       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24427                  opcode);
24428       return NULL;
24429     }
24430
24431   defn = opcode_definitions[opcode];
24432   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24433   defn += bytes_read;
24434
24435   for (i = 0; i < arg; ++i)
24436     {
24437       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24438                                  (enum dwarf_form) defn[i], offset_size,
24439                                  section);
24440       if (mac_ptr == NULL)
24441         {
24442           /* skip_form_bytes already issued the complaint.  */
24443           return NULL;
24444         }
24445     }
24446
24447   return mac_ptr;
24448 }
24449
24450 /* A helper function which parses the header of a macro section.
24451    If the macro section is the extended (for now called "GNU") type,
24452    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24453    the header, or issues a complaint and returns NULL on error.  */
24454
24455 static const gdb_byte *
24456 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24457                           bfd *abfd,
24458                           const gdb_byte *mac_ptr,
24459                           unsigned int *offset_size,
24460                           int section_is_gnu)
24461 {
24462   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24463
24464   if (section_is_gnu)
24465     {
24466       unsigned int version, flags;
24467
24468       version = read_2_bytes (abfd, mac_ptr);
24469       if (version != 4 && version != 5)
24470         {
24471           complaint (_("unrecognized version `%d' in .debug_macro section"),
24472                      version);
24473           return NULL;
24474         }
24475       mac_ptr += 2;
24476
24477       flags = read_1_byte (abfd, mac_ptr);
24478       ++mac_ptr;
24479       *offset_size = (flags & 1) ? 8 : 4;
24480
24481       if ((flags & 2) != 0)
24482         /* We don't need the line table offset.  */
24483         mac_ptr += *offset_size;
24484
24485       /* Vendor opcode descriptions.  */
24486       if ((flags & 4) != 0)
24487         {
24488           unsigned int i, count;
24489
24490           count = read_1_byte (abfd, mac_ptr);
24491           ++mac_ptr;
24492           for (i = 0; i < count; ++i)
24493             {
24494               unsigned int opcode, bytes_read;
24495               unsigned long arg;
24496
24497               opcode = read_1_byte (abfd, mac_ptr);
24498               ++mac_ptr;
24499               opcode_definitions[opcode] = mac_ptr;
24500               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24501               mac_ptr += bytes_read;
24502               mac_ptr += arg;
24503             }
24504         }
24505     }
24506
24507   return mac_ptr;
24508 }
24509
24510 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24511    including DW_MACRO_import.  */
24512
24513 static void
24514 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24515                           bfd *abfd,
24516                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24517                           struct macro_source_file *current_file,
24518                           struct line_header *lh,
24519                           struct dwarf2_section_info *section,
24520                           int section_is_gnu, int section_is_dwz,
24521                           unsigned int offset_size,
24522                           htab_t include_hash)
24523 {
24524   struct dwarf2_per_objfile *dwarf2_per_objfile
24525     = cu->per_cu->dwarf2_per_objfile;
24526   struct objfile *objfile = dwarf2_per_objfile->objfile;
24527   enum dwarf_macro_record_type macinfo_type;
24528   int at_commandline;
24529   const gdb_byte *opcode_definitions[256];
24530
24531   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24532                                       &offset_size, section_is_gnu);
24533   if (mac_ptr == NULL)
24534     {
24535       /* We already issued a complaint.  */
24536       return;
24537     }
24538
24539   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24540      GDB is still reading the definitions from command line.  First
24541      DW_MACINFO_start_file will need to be ignored as it was already executed
24542      to create CURRENT_FILE for the main source holding also the command line
24543      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24544      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24545
24546   at_commandline = 1;
24547
24548   do
24549     {
24550       /* Do we at least have room for a macinfo type byte?  */
24551       if (mac_ptr >= mac_end)
24552         {
24553           dwarf2_section_buffer_overflow_complaint (section);
24554           break;
24555         }
24556
24557       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24558       mac_ptr++;
24559
24560       /* Note that we rely on the fact that the corresponding GNU and
24561          DWARF constants are the same.  */
24562       DIAGNOSTIC_PUSH
24563       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24564       switch (macinfo_type)
24565         {
24566           /* A zero macinfo type indicates the end of the macro
24567              information.  */
24568         case 0:
24569           break;
24570
24571         case DW_MACRO_define:
24572         case DW_MACRO_undef:
24573         case DW_MACRO_define_strp:
24574         case DW_MACRO_undef_strp:
24575         case DW_MACRO_define_sup:
24576         case DW_MACRO_undef_sup:
24577           {
24578             unsigned int bytes_read;
24579             int line;
24580             const char *body;
24581             int is_define;
24582
24583             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24584             mac_ptr += bytes_read;
24585
24586             if (macinfo_type == DW_MACRO_define
24587                 || macinfo_type == DW_MACRO_undef)
24588               {
24589                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24590                 mac_ptr += bytes_read;
24591               }
24592             else
24593               {
24594                 LONGEST str_offset;
24595
24596                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24597                 mac_ptr += offset_size;
24598
24599                 if (macinfo_type == DW_MACRO_define_sup
24600                     || macinfo_type == DW_MACRO_undef_sup
24601                     || section_is_dwz)
24602                   {
24603                     struct dwz_file *dwz
24604                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24605
24606                     body = read_indirect_string_from_dwz (objfile,
24607                                                           dwz, str_offset);
24608                   }
24609                 else
24610                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24611                                                          abfd, str_offset);
24612               }
24613
24614             is_define = (macinfo_type == DW_MACRO_define
24615                          || macinfo_type == DW_MACRO_define_strp
24616                          || macinfo_type == DW_MACRO_define_sup);
24617             if (! current_file)
24618               {
24619                 /* DWARF violation as no main source is present.  */
24620                 complaint (_("debug info with no main source gives macro %s "
24621                              "on line %d: %s"),
24622                            is_define ? _("definition") : _("undefinition"),
24623                            line, body);
24624                 break;
24625               }
24626             if ((line == 0 && !at_commandline)
24627                 || (line != 0 && at_commandline))
24628               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24629                          at_commandline ? _("command-line") : _("in-file"),
24630                          is_define ? _("definition") : _("undefinition"),
24631                          line == 0 ? _("zero") : _("non-zero"), line, body);
24632
24633             if (body == NULL)
24634               {
24635                 /* Fedora's rpm-build's "debugedit" binary
24636                    corrupted .debug_macro sections.
24637
24638                    For more info, see
24639                    https://bugzilla.redhat.com/show_bug.cgi?id=1708786 */
24640                 complaint (_("debug info gives %s invalid macro %s "
24641                              "without body (corrupted?) at line %d "
24642                              "on file %s"),
24643                            at_commandline ? _("command-line") : _("in-file"),
24644                            is_define ? _("definition") : _("undefinition"),
24645                            line, current_file->filename);
24646               }
24647             else if (is_define)
24648               parse_macro_definition (current_file, line, body);
24649             else
24650               {
24651                 gdb_assert (macinfo_type == DW_MACRO_undef
24652                             || macinfo_type == DW_MACRO_undef_strp
24653                             || macinfo_type == DW_MACRO_undef_sup);
24654                 macro_undef (current_file, line, body);
24655               }
24656           }
24657           break;
24658
24659         case DW_MACRO_start_file:
24660           {
24661             unsigned int bytes_read;
24662             int line, file;
24663
24664             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24665             mac_ptr += bytes_read;
24666             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24667             mac_ptr += bytes_read;
24668
24669             if ((line == 0 && !at_commandline)
24670                 || (line != 0 && at_commandline))
24671               complaint (_("debug info gives source %d included "
24672                            "from %s at %s line %d"),
24673                          file, at_commandline ? _("command-line") : _("file"),
24674                          line == 0 ? _("zero") : _("non-zero"), line);
24675
24676             if (at_commandline)
24677               {
24678                 /* This DW_MACRO_start_file was executed in the
24679                    pass one.  */
24680                 at_commandline = 0;
24681               }
24682             else
24683               current_file = macro_start_file (cu, file, line, current_file,
24684                                                lh);
24685           }
24686           break;
24687
24688         case DW_MACRO_end_file:
24689           if (! current_file)
24690             complaint (_("macro debug info has an unmatched "
24691                          "`close_file' directive"));
24692           else
24693             {
24694               current_file = current_file->included_by;
24695               if (! current_file)
24696                 {
24697                   enum dwarf_macro_record_type next_type;
24698
24699                   /* GCC circa March 2002 doesn't produce the zero
24700                      type byte marking the end of the compilation
24701                      unit.  Complain if it's not there, but exit no
24702                      matter what.  */
24703
24704                   /* Do we at least have room for a macinfo type byte?  */
24705                   if (mac_ptr >= mac_end)
24706                     {
24707                       dwarf2_section_buffer_overflow_complaint (section);
24708                       return;
24709                     }
24710
24711                   /* We don't increment mac_ptr here, so this is just
24712                      a look-ahead.  */
24713                   next_type
24714                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24715                                                                   mac_ptr);
24716                   if (next_type != 0)
24717                     complaint (_("no terminating 0-type entry for "
24718                                  "macros in `.debug_macinfo' section"));
24719
24720                   return;
24721                 }
24722             }
24723           break;
24724
24725         case DW_MACRO_import:
24726         case DW_MACRO_import_sup:
24727           {
24728             LONGEST offset;
24729             void **slot;
24730             bfd *include_bfd = abfd;
24731             struct dwarf2_section_info *include_section = section;
24732             const gdb_byte *include_mac_end = mac_end;
24733             int is_dwz = section_is_dwz;
24734             const gdb_byte *new_mac_ptr;
24735
24736             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24737             mac_ptr += offset_size;
24738
24739             if (macinfo_type == DW_MACRO_import_sup)
24740               {
24741                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24742
24743                 dwarf2_read_section (objfile, &dwz->macro);
24744
24745                 include_section = &dwz->macro;
24746                 include_bfd = get_section_bfd_owner (include_section);
24747                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24748                 is_dwz = 1;
24749               }
24750
24751             new_mac_ptr = include_section->buffer + offset;
24752             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24753
24754             if (*slot != NULL)
24755               {
24756                 /* This has actually happened; see
24757                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24758                 complaint (_("recursive DW_MACRO_import in "
24759                              ".debug_macro section"));
24760               }
24761             else
24762               {
24763                 *slot = (void *) new_mac_ptr;
24764
24765                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24766                                           include_mac_end, current_file, lh,
24767                                           section, section_is_gnu, is_dwz,
24768                                           offset_size, include_hash);
24769
24770                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24771               }
24772           }
24773           break;
24774
24775         case DW_MACINFO_vendor_ext:
24776           if (!section_is_gnu)
24777             {
24778               unsigned int bytes_read;
24779
24780               /* This reads the constant, but since we don't recognize
24781                  any vendor extensions, we ignore it.  */
24782               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24783               mac_ptr += bytes_read;
24784               read_direct_string (abfd, mac_ptr, &bytes_read);
24785               mac_ptr += bytes_read;
24786
24787               /* We don't recognize any vendor extensions.  */
24788               break;
24789             }
24790           /* FALLTHROUGH */
24791
24792         default:
24793           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24794                                          mac_ptr, mac_end, abfd, offset_size,
24795                                          section);
24796           if (mac_ptr == NULL)
24797             return;
24798           break;
24799         }
24800       DIAGNOSTIC_POP
24801     } while (macinfo_type != 0);
24802 }
24803
24804 static void
24805 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24806                      int section_is_gnu)
24807 {
24808   struct dwarf2_per_objfile *dwarf2_per_objfile
24809     = cu->per_cu->dwarf2_per_objfile;
24810   struct objfile *objfile = dwarf2_per_objfile->objfile;
24811   struct line_header *lh = cu->line_header;
24812   bfd *abfd;
24813   const gdb_byte *mac_ptr, *mac_end;
24814   struct macro_source_file *current_file = 0;
24815   enum dwarf_macro_record_type macinfo_type;
24816   unsigned int offset_size = cu->header.offset_size;
24817   const gdb_byte *opcode_definitions[256];
24818   void **slot;
24819   struct dwarf2_section_info *section;
24820   const char *section_name;
24821
24822   if (cu->dwo_unit != NULL)
24823     {
24824       if (section_is_gnu)
24825         {
24826           section = &cu->dwo_unit->dwo_file->sections.macro;
24827           section_name = ".debug_macro.dwo";
24828         }
24829       else
24830         {
24831           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24832           section_name = ".debug_macinfo.dwo";
24833         }
24834     }
24835   else
24836     {
24837       if (section_is_gnu)
24838         {
24839           section = &dwarf2_per_objfile->macro;
24840           section_name = ".debug_macro";
24841         }
24842       else
24843         {
24844           section = &dwarf2_per_objfile->macinfo;
24845           section_name = ".debug_macinfo";
24846         }
24847     }
24848
24849   dwarf2_read_section (objfile, section);
24850   if (section->buffer == NULL)
24851     {
24852       complaint (_("missing %s section"), section_name);
24853       return;
24854     }
24855   abfd = get_section_bfd_owner (section);
24856
24857   /* First pass: Find the name of the base filename.
24858      This filename is needed in order to process all macros whose definition
24859      (or undefinition) comes from the command line.  These macros are defined
24860      before the first DW_MACINFO_start_file entry, and yet still need to be
24861      associated to the base file.
24862
24863      To determine the base file name, we scan the macro definitions until we
24864      reach the first DW_MACINFO_start_file entry.  We then initialize
24865      CURRENT_FILE accordingly so that any macro definition found before the
24866      first DW_MACINFO_start_file can still be associated to the base file.  */
24867
24868   mac_ptr = section->buffer + offset;
24869   mac_end = section->buffer + section->size;
24870
24871   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24872                                       &offset_size, section_is_gnu);
24873   if (mac_ptr == NULL)
24874     {
24875       /* We already issued a complaint.  */
24876       return;
24877     }
24878
24879   do
24880     {
24881       /* Do we at least have room for a macinfo type byte?  */
24882       if (mac_ptr >= mac_end)
24883         {
24884           /* Complaint is printed during the second pass as GDB will probably
24885              stop the first pass earlier upon finding
24886              DW_MACINFO_start_file.  */
24887           break;
24888         }
24889
24890       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24891       mac_ptr++;
24892
24893       /* Note that we rely on the fact that the corresponding GNU and
24894          DWARF constants are the same.  */
24895       DIAGNOSTIC_PUSH
24896       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24897       switch (macinfo_type)
24898         {
24899           /* A zero macinfo type indicates the end of the macro
24900              information.  */
24901         case 0:
24902           break;
24903
24904         case DW_MACRO_define:
24905         case DW_MACRO_undef:
24906           /* Only skip the data by MAC_PTR.  */
24907           {
24908             unsigned int bytes_read;
24909
24910             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24911             mac_ptr += bytes_read;
24912             read_direct_string (abfd, mac_ptr, &bytes_read);
24913             mac_ptr += bytes_read;
24914           }
24915           break;
24916
24917         case DW_MACRO_start_file:
24918           {
24919             unsigned int bytes_read;
24920             int line, file;
24921
24922             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24923             mac_ptr += bytes_read;
24924             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24925             mac_ptr += bytes_read;
24926
24927             current_file = macro_start_file (cu, file, line, current_file, lh);
24928           }
24929           break;
24930
24931         case DW_MACRO_end_file:
24932           /* No data to skip by MAC_PTR.  */
24933           break;
24934
24935         case DW_MACRO_define_strp:
24936         case DW_MACRO_undef_strp:
24937         case DW_MACRO_define_sup:
24938         case DW_MACRO_undef_sup:
24939           {
24940             unsigned int bytes_read;
24941
24942             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24943             mac_ptr += bytes_read;
24944             mac_ptr += offset_size;
24945           }
24946           break;
24947
24948         case DW_MACRO_import:
24949         case DW_MACRO_import_sup:
24950           /* Note that, according to the spec, a transparent include
24951              chain cannot call DW_MACRO_start_file.  So, we can just
24952              skip this opcode.  */
24953           mac_ptr += offset_size;
24954           break;
24955
24956         case DW_MACINFO_vendor_ext:
24957           /* Only skip the data by MAC_PTR.  */
24958           if (!section_is_gnu)
24959             {
24960               unsigned int bytes_read;
24961
24962               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24963               mac_ptr += bytes_read;
24964               read_direct_string (abfd, mac_ptr, &bytes_read);
24965               mac_ptr += bytes_read;
24966             }
24967           /* FALLTHROUGH */
24968
24969         default:
24970           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24971                                          mac_ptr, mac_end, abfd, offset_size,
24972                                          section);
24973           if (mac_ptr == NULL)
24974             return;
24975           break;
24976         }
24977       DIAGNOSTIC_POP
24978     } while (macinfo_type != 0 && current_file == NULL);
24979
24980   /* Second pass: Process all entries.
24981
24982      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24983      command-line macro definitions/undefinitions.  This flag is unset when we
24984      reach the first DW_MACINFO_start_file entry.  */
24985
24986   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24987                                            htab_eq_pointer,
24988                                            NULL, xcalloc, xfree));
24989   mac_ptr = section->buffer + offset;
24990   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24991   *slot = (void *) mac_ptr;
24992   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24993                             current_file, lh, section,
24994                             section_is_gnu, 0, offset_size,
24995                             include_hash.get ());
24996 }
24997
24998 /* Check if the attribute's form is a DW_FORM_block*
24999    if so return true else false.  */
25000
25001 static int
25002 attr_form_is_block (const struct attribute *attr)
25003 {
25004   return (attr == NULL ? 0 :
25005       attr->form == DW_FORM_block1
25006       || attr->form == DW_FORM_block2
25007       || attr->form == DW_FORM_block4
25008       || attr->form == DW_FORM_block
25009       || attr->form == DW_FORM_exprloc);
25010 }
25011
25012 /* Return non-zero if ATTR's value is a section offset --- classes
25013    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
25014    You may use DW_UNSND (attr) to retrieve such offsets.
25015
25016    Section 7.5.4, "Attribute Encodings", explains that no attribute
25017    may have a value that belongs to more than one of these classes; it
25018    would be ambiguous if we did, because we use the same forms for all
25019    of them.  */
25020
25021 static int
25022 attr_form_is_section_offset (const struct attribute *attr)
25023 {
25024   return (attr->form == DW_FORM_data4
25025           || attr->form == DW_FORM_data8
25026           || attr->form == DW_FORM_sec_offset);
25027 }
25028
25029 /* Return non-zero if ATTR's value falls in the 'constant' class, or
25030    zero otherwise.  When this function returns true, you can apply
25031    dwarf2_get_attr_constant_value to it.
25032
25033    However, note that for some attributes you must check
25034    attr_form_is_section_offset before using this test.  DW_FORM_data4
25035    and DW_FORM_data8 are members of both the constant class, and of
25036    the classes that contain offsets into other debug sections
25037    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
25038    that, if an attribute's can be either a constant or one of the
25039    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
25040    taken as section offsets, not constants.
25041
25042    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
25043    cannot handle that.  */
25044
25045 static int
25046 attr_form_is_constant (const struct attribute *attr)
25047 {
25048   switch (attr->form)
25049     {
25050     case DW_FORM_sdata:
25051     case DW_FORM_udata:
25052     case DW_FORM_data1:
25053     case DW_FORM_data2:
25054     case DW_FORM_data4:
25055     case DW_FORM_data8:
25056     case DW_FORM_implicit_const:
25057       return 1;
25058     default:
25059       return 0;
25060     }
25061 }
25062
25063
25064 /* DW_ADDR is always stored already as sect_offset; despite for the forms
25065    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
25066
25067 static int
25068 attr_form_is_ref (const struct attribute *attr)
25069 {
25070   switch (attr->form)
25071     {
25072     case DW_FORM_ref_addr:
25073     case DW_FORM_ref1:
25074     case DW_FORM_ref2:
25075     case DW_FORM_ref4:
25076     case DW_FORM_ref8:
25077     case DW_FORM_ref_udata:
25078     case DW_FORM_GNU_ref_alt:
25079       return 1;
25080     default:
25081       return 0;
25082     }
25083 }
25084
25085 /* Return the .debug_loc section to use for CU.
25086    For DWO files use .debug_loc.dwo.  */
25087
25088 static struct dwarf2_section_info *
25089 cu_debug_loc_section (struct dwarf2_cu *cu)
25090 {
25091   struct dwarf2_per_objfile *dwarf2_per_objfile
25092     = cu->per_cu->dwarf2_per_objfile;
25093
25094   if (cu->dwo_unit)
25095     {
25096       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
25097       
25098       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
25099     }
25100   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
25101                                   : &dwarf2_per_objfile->loc);
25102 }
25103
25104 /* A helper function that fills in a dwarf2_loclist_baton.  */
25105
25106 static void
25107 fill_in_loclist_baton (struct dwarf2_cu *cu,
25108                        struct dwarf2_loclist_baton *baton,
25109                        const struct attribute *attr)
25110 {
25111   struct dwarf2_per_objfile *dwarf2_per_objfile
25112     = cu->per_cu->dwarf2_per_objfile;
25113   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25114
25115   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
25116
25117   baton->per_cu = cu->per_cu;
25118   gdb_assert (baton->per_cu);
25119   /* We don't know how long the location list is, but make sure we
25120      don't run off the edge of the section.  */
25121   baton->size = section->size - DW_UNSND (attr);
25122   baton->data = section->buffer + DW_UNSND (attr);
25123   baton->base_address = cu->base_address;
25124   baton->from_dwo = cu->dwo_unit != NULL;
25125 }
25126
25127 static void
25128 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
25129                              struct dwarf2_cu *cu, int is_block)
25130 {
25131   struct dwarf2_per_objfile *dwarf2_per_objfile
25132     = cu->per_cu->dwarf2_per_objfile;
25133   struct objfile *objfile = dwarf2_per_objfile->objfile;
25134   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25135
25136   if (attr_form_is_section_offset (attr)
25137       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
25138          the section.  If so, fall through to the complaint in the
25139          other branch.  */
25140       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
25141     {
25142       struct dwarf2_loclist_baton *baton;
25143
25144       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
25145
25146       fill_in_loclist_baton (cu, baton, attr);
25147
25148       if (cu->base_known == 0)
25149         complaint (_("Location list used without "
25150                      "specifying the CU base address."));
25151
25152       SYMBOL_ACLASS_INDEX (sym) = (is_block
25153                                    ? dwarf2_loclist_block_index
25154                                    : dwarf2_loclist_index);
25155       SYMBOL_LOCATION_BATON (sym) = baton;
25156     }
25157   else
25158     {
25159       struct dwarf2_locexpr_baton *baton;
25160
25161       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
25162       baton->per_cu = cu->per_cu;
25163       gdb_assert (baton->per_cu);
25164
25165       if (attr_form_is_block (attr))
25166         {
25167           /* Note that we're just copying the block's data pointer
25168              here, not the actual data.  We're still pointing into the
25169              info_buffer for SYM's objfile; right now we never release
25170              that buffer, but when we do clean up properly this may
25171              need to change.  */
25172           baton->size = DW_BLOCK (attr)->size;
25173           baton->data = DW_BLOCK (attr)->data;
25174         }
25175       else
25176         {
25177           dwarf2_invalid_attrib_class_complaint ("location description",
25178                                                  SYMBOL_NATURAL_NAME (sym));
25179           baton->size = 0;
25180         }
25181
25182       SYMBOL_ACLASS_INDEX (sym) = (is_block
25183                                    ? dwarf2_locexpr_block_index
25184                                    : dwarf2_locexpr_index);
25185       SYMBOL_LOCATION_BATON (sym) = baton;
25186     }
25187 }
25188
25189 /* Return the OBJFILE associated with the compilation unit CU.  If CU
25190    came from a separate debuginfo file, then the master objfile is
25191    returned.  */
25192
25193 struct objfile *
25194 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25195 {
25196   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25197
25198   /* Return the master objfile, so that we can report and look up the
25199      correct file containing this variable.  */
25200   if (objfile->separate_debug_objfile_backlink)
25201     objfile = objfile->separate_debug_objfile_backlink;
25202
25203   return objfile;
25204 }
25205
25206 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25207    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25208    CU_HEADERP first.  */
25209
25210 static const struct comp_unit_head *
25211 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25212                        struct dwarf2_per_cu_data *per_cu)
25213 {
25214   const gdb_byte *info_ptr;
25215
25216   if (per_cu->cu)
25217     return &per_cu->cu->header;
25218
25219   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25220
25221   memset (cu_headerp, 0, sizeof (*cu_headerp));
25222   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25223                        rcuh_kind::COMPILE);
25224
25225   return cu_headerp;
25226 }
25227
25228 /* Return the address size given in the compilation unit header for CU.  */
25229
25230 int
25231 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25232 {
25233   struct comp_unit_head cu_header_local;
25234   const struct comp_unit_head *cu_headerp;
25235
25236   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25237
25238   return cu_headerp->addr_size;
25239 }
25240
25241 /* Return the offset size given in the compilation unit header for CU.  */
25242
25243 int
25244 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25245 {
25246   struct comp_unit_head cu_header_local;
25247   const struct comp_unit_head *cu_headerp;
25248
25249   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25250
25251   return cu_headerp->offset_size;
25252 }
25253
25254 /* See its dwarf2loc.h declaration.  */
25255
25256 int
25257 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25258 {
25259   struct comp_unit_head cu_header_local;
25260   const struct comp_unit_head *cu_headerp;
25261
25262   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25263
25264   if (cu_headerp->version == 2)
25265     return cu_headerp->addr_size;
25266   else
25267     return cu_headerp->offset_size;
25268 }
25269
25270 /* Return the text offset of the CU.  The returned offset comes from
25271    this CU's objfile.  If this objfile came from a separate debuginfo
25272    file, then the offset may be different from the corresponding
25273    offset in the parent objfile.  */
25274
25275 CORE_ADDR
25276 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25277 {
25278   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25279
25280   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25281 }
25282
25283 /* Return DWARF version number of PER_CU.  */
25284
25285 short
25286 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25287 {
25288   return per_cu->dwarf_version;
25289 }
25290
25291 /* Locate the .debug_info compilation unit from CU's objfile which contains
25292    the DIE at OFFSET.  Raises an error on failure.  */
25293
25294 static struct dwarf2_per_cu_data *
25295 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25296                                   unsigned int offset_in_dwz,
25297                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25298 {
25299   struct dwarf2_per_cu_data *this_cu;
25300   int low, high;
25301
25302   low = 0;
25303   high = dwarf2_per_objfile->all_comp_units.size () - 1;
25304   while (high > low)
25305     {
25306       struct dwarf2_per_cu_data *mid_cu;
25307       int mid = low + (high - low) / 2;
25308
25309       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25310       if (mid_cu->is_dwz > offset_in_dwz
25311           || (mid_cu->is_dwz == offset_in_dwz
25312               && mid_cu->sect_off + mid_cu->length >= sect_off))
25313         high = mid;
25314       else
25315         low = mid + 1;
25316     }
25317   gdb_assert (low == high);
25318   this_cu = dwarf2_per_objfile->all_comp_units[low];
25319   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
25320     {
25321       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25322         error (_("Dwarf Error: could not find partial DIE containing "
25323                "offset %s [in module %s]"),
25324                sect_offset_str (sect_off),
25325                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25326
25327       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25328                   <= sect_off);
25329       return dwarf2_per_objfile->all_comp_units[low-1];
25330     }
25331   else
25332     {
25333       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
25334           && sect_off >= this_cu->sect_off + this_cu->length)
25335         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25336       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25337       return this_cu;
25338     }
25339 }
25340
25341 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25342
25343 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25344   : per_cu (per_cu_),
25345     mark (false),
25346     has_loclist (false),
25347     checked_producer (false),
25348     producer_is_gxx_lt_4_6 (false),
25349     producer_is_gcc_lt_4_3 (false),
25350     producer_is_icc (false),
25351     producer_is_icc_lt_14 (false),
25352     producer_is_codewarrior (false),
25353     processing_has_namespace_info (false)
25354 {
25355   per_cu->cu = this;
25356 }
25357
25358 /* Destroy a dwarf2_cu.  */
25359
25360 dwarf2_cu::~dwarf2_cu ()
25361 {
25362   per_cu->cu = NULL;
25363 }
25364
25365 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25366
25367 static void
25368 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25369                        enum language pretend_language)
25370 {
25371   struct attribute *attr;
25372
25373   /* Set the language we're debugging.  */
25374   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25375   if (attr)
25376     set_cu_language (DW_UNSND (attr), cu);
25377   else
25378     {
25379       cu->language = pretend_language;
25380       cu->language_defn = language_def (cu->language);
25381     }
25382
25383   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25384 }
25385
25386 /* Increase the age counter on each cached compilation unit, and free
25387    any that are too old.  */
25388
25389 static void
25390 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25391 {
25392   struct dwarf2_per_cu_data *per_cu, **last_chain;
25393
25394   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25395   per_cu = dwarf2_per_objfile->read_in_chain;
25396   while (per_cu != NULL)
25397     {
25398       per_cu->cu->last_used ++;
25399       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25400         dwarf2_mark (per_cu->cu);
25401       per_cu = per_cu->cu->read_in_chain;
25402     }
25403
25404   per_cu = dwarf2_per_objfile->read_in_chain;
25405   last_chain = &dwarf2_per_objfile->read_in_chain;
25406   while (per_cu != NULL)
25407     {
25408       struct dwarf2_per_cu_data *next_cu;
25409
25410       next_cu = per_cu->cu->read_in_chain;
25411
25412       if (!per_cu->cu->mark)
25413         {
25414           delete per_cu->cu;
25415           *last_chain = next_cu;
25416         }
25417       else
25418         last_chain = &per_cu->cu->read_in_chain;
25419
25420       per_cu = next_cu;
25421     }
25422 }
25423
25424 /* Remove a single compilation unit from the cache.  */
25425
25426 static void
25427 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25428 {
25429   struct dwarf2_per_cu_data *per_cu, **last_chain;
25430   struct dwarf2_per_objfile *dwarf2_per_objfile
25431     = target_per_cu->dwarf2_per_objfile;
25432
25433   per_cu = dwarf2_per_objfile->read_in_chain;
25434   last_chain = &dwarf2_per_objfile->read_in_chain;
25435   while (per_cu != NULL)
25436     {
25437       struct dwarf2_per_cu_data *next_cu;
25438
25439       next_cu = per_cu->cu->read_in_chain;
25440
25441       if (per_cu == target_per_cu)
25442         {
25443           delete per_cu->cu;
25444           per_cu->cu = NULL;
25445           *last_chain = next_cu;
25446           break;
25447         }
25448       else
25449         last_chain = &per_cu->cu->read_in_chain;
25450
25451       per_cu = next_cu;
25452     }
25453 }
25454
25455 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25456    We store these in a hash table separate from the DIEs, and preserve them
25457    when the DIEs are flushed out of cache.
25458
25459    The CU "per_cu" pointer is needed because offset alone is not enough to
25460    uniquely identify the type.  A file may have multiple .debug_types sections,
25461    or the type may come from a DWO file.  Furthermore, while it's more logical
25462    to use per_cu->section+offset, with Fission the section with the data is in
25463    the DWO file but we don't know that section at the point we need it.
25464    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25465    because we can enter the lookup routine, get_die_type_at_offset, from
25466    outside this file, and thus won't necessarily have PER_CU->cu.
25467    Fortunately, PER_CU is stable for the life of the objfile.  */
25468
25469 struct dwarf2_per_cu_offset_and_type
25470 {
25471   const struct dwarf2_per_cu_data *per_cu;
25472   sect_offset sect_off;
25473   struct type *type;
25474 };
25475
25476 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25477
25478 static hashval_t
25479 per_cu_offset_and_type_hash (const void *item)
25480 {
25481   const struct dwarf2_per_cu_offset_and_type *ofs
25482     = (const struct dwarf2_per_cu_offset_and_type *) item;
25483
25484   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25485 }
25486
25487 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25488
25489 static int
25490 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25491 {
25492   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25493     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25494   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25495     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25496
25497   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25498           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25499 }
25500
25501 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25502    table if necessary.  For convenience, return TYPE.
25503
25504    The DIEs reading must have careful ordering to:
25505     * Not cause infite loops trying to read in DIEs as a prerequisite for
25506       reading current DIE.
25507     * Not trying to dereference contents of still incompletely read in types
25508       while reading in other DIEs.
25509     * Enable referencing still incompletely read in types just by a pointer to
25510       the type without accessing its fields.
25511
25512    Therefore caller should follow these rules:
25513      * Try to fetch any prerequisite types we may need to build this DIE type
25514        before building the type and calling set_die_type.
25515      * After building type call set_die_type for current DIE as soon as
25516        possible before fetching more types to complete the current type.
25517      * Make the type as complete as possible before fetching more types.  */
25518
25519 static struct type *
25520 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25521 {
25522   struct dwarf2_per_objfile *dwarf2_per_objfile
25523     = cu->per_cu->dwarf2_per_objfile;
25524   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25525   struct objfile *objfile = dwarf2_per_objfile->objfile;
25526   struct attribute *attr;
25527   struct dynamic_prop prop;
25528
25529   /* For Ada types, make sure that the gnat-specific data is always
25530      initialized (if not already set).  There are a few types where
25531      we should not be doing so, because the type-specific area is
25532      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25533      where the type-specific area is used to store the floatformat).
25534      But this is not a problem, because the gnat-specific information
25535      is actually not needed for these types.  */
25536   if (need_gnat_info (cu)
25537       && TYPE_CODE (type) != TYPE_CODE_FUNC
25538       && TYPE_CODE (type) != TYPE_CODE_FLT
25539       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25540       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25541       && TYPE_CODE (type) != TYPE_CODE_METHOD
25542       && !HAVE_GNAT_AUX_INFO (type))
25543     INIT_GNAT_SPECIFIC (type);
25544
25545   /* Read DW_AT_allocated and set in type.  */
25546   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25547   if (attr_form_is_block (attr))
25548     {
25549       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25550         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25551     }
25552   else if (attr != NULL)
25553     {
25554       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25555                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25556                  sect_offset_str (die->sect_off));
25557     }
25558
25559   /* Read DW_AT_associated and set in type.  */
25560   attr = dwarf2_attr (die, DW_AT_associated, cu);
25561   if (attr_form_is_block (attr))
25562     {
25563       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25564         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25565     }
25566   else if (attr != NULL)
25567     {
25568       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25569                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25570                  sect_offset_str (die->sect_off));
25571     }
25572
25573   /* Read DW_AT_data_location and set in type.  */
25574   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25575   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25576     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25577
25578   if (dwarf2_per_objfile->die_type_hash == NULL)
25579     {
25580       dwarf2_per_objfile->die_type_hash =
25581         htab_create_alloc_ex (127,
25582                               per_cu_offset_and_type_hash,
25583                               per_cu_offset_and_type_eq,
25584                               NULL,
25585                               &objfile->objfile_obstack,
25586                               hashtab_obstack_allocate,
25587                               dummy_obstack_deallocate);
25588     }
25589
25590   ofs.per_cu = cu->per_cu;
25591   ofs.sect_off = die->sect_off;
25592   ofs.type = type;
25593   slot = (struct dwarf2_per_cu_offset_and_type **)
25594     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25595   if (*slot)
25596     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25597                sect_offset_str (die->sect_off));
25598   *slot = XOBNEW (&objfile->objfile_obstack,
25599                   struct dwarf2_per_cu_offset_and_type);
25600   **slot = ofs;
25601   return type;
25602 }
25603
25604 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25605    or return NULL if the die does not have a saved type.  */
25606
25607 static struct type *
25608 get_die_type_at_offset (sect_offset sect_off,
25609                         struct dwarf2_per_cu_data *per_cu)
25610 {
25611   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25612   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25613
25614   if (dwarf2_per_objfile->die_type_hash == NULL)
25615     return NULL;
25616
25617   ofs.per_cu = per_cu;
25618   ofs.sect_off = sect_off;
25619   slot = ((struct dwarf2_per_cu_offset_and_type *)
25620           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25621   if (slot)
25622     return slot->type;
25623   else
25624     return NULL;
25625 }
25626
25627 /* Look up the type for DIE in CU in die_type_hash,
25628    or return NULL if DIE does not have a saved type.  */
25629
25630 static struct type *
25631 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25632 {
25633   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25634 }
25635
25636 /* Add a dependence relationship from CU to REF_PER_CU.  */
25637
25638 static void
25639 dwarf2_add_dependence (struct dwarf2_cu *cu,
25640                        struct dwarf2_per_cu_data *ref_per_cu)
25641 {
25642   void **slot;
25643
25644   if (cu->dependencies == NULL)
25645     cu->dependencies
25646       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25647                               NULL, &cu->comp_unit_obstack,
25648                               hashtab_obstack_allocate,
25649                               dummy_obstack_deallocate);
25650
25651   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25652   if (*slot == NULL)
25653     *slot = ref_per_cu;
25654 }
25655
25656 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25657    Set the mark field in every compilation unit in the
25658    cache that we must keep because we are keeping CU.  */
25659
25660 static int
25661 dwarf2_mark_helper (void **slot, void *data)
25662 {
25663   struct dwarf2_per_cu_data *per_cu;
25664
25665   per_cu = (struct dwarf2_per_cu_data *) *slot;
25666
25667   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25668      reading of the chain.  As such dependencies remain valid it is not much
25669      useful to track and undo them during QUIT cleanups.  */
25670   if (per_cu->cu == NULL)
25671     return 1;
25672
25673   if (per_cu->cu->mark)
25674     return 1;
25675   per_cu->cu->mark = true;
25676
25677   if (per_cu->cu->dependencies != NULL)
25678     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25679
25680   return 1;
25681 }
25682
25683 /* Set the mark field in CU and in every other compilation unit in the
25684    cache that we must keep because we are keeping CU.  */
25685
25686 static void
25687 dwarf2_mark (struct dwarf2_cu *cu)
25688 {
25689   if (cu->mark)
25690     return;
25691   cu->mark = true;
25692   if (cu->dependencies != NULL)
25693     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25694 }
25695
25696 static void
25697 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25698 {
25699   while (per_cu)
25700     {
25701       per_cu->cu->mark = false;
25702       per_cu = per_cu->cu->read_in_chain;
25703     }
25704 }
25705
25706 /* Trivial hash function for partial_die_info: the hash value of a DIE
25707    is its offset in .debug_info for this objfile.  */
25708
25709 static hashval_t
25710 partial_die_hash (const void *item)
25711 {
25712   const struct partial_die_info *part_die
25713     = (const struct partial_die_info *) item;
25714
25715   return to_underlying (part_die->sect_off);
25716 }
25717
25718 /* Trivial comparison function for partial_die_info structures: two DIEs
25719    are equal if they have the same offset.  */
25720
25721 static int
25722 partial_die_eq (const void *item_lhs, const void *item_rhs)
25723 {
25724   const struct partial_die_info *part_die_lhs
25725     = (const struct partial_die_info *) item_lhs;
25726   const struct partial_die_info *part_die_rhs
25727     = (const struct partial_die_info *) item_rhs;
25728
25729   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25730 }
25731
25732 struct cmd_list_element *set_dwarf_cmdlist;
25733 struct cmd_list_element *show_dwarf_cmdlist;
25734
25735 static void
25736 set_dwarf_cmd (const char *args, int from_tty)
25737 {
25738   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25739              gdb_stdout);
25740 }
25741
25742 static void
25743 show_dwarf_cmd (const char *args, int from_tty)
25744 {
25745   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25746 }
25747
25748 int dwarf_always_disassemble;
25749
25750 static void
25751 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25752                                struct cmd_list_element *c, const char *value)
25753 {
25754   fprintf_filtered (file,
25755                     _("Whether to always disassemble "
25756                       "DWARF expressions is %s.\n"),
25757                     value);
25758 }
25759
25760 static void
25761 show_check_physname (struct ui_file *file, int from_tty,
25762                      struct cmd_list_element *c, const char *value)
25763 {
25764   fprintf_filtered (file,
25765                     _("Whether to check \"physname\" is %s.\n"),
25766                     value);
25767 }
25768
25769 void
25770 _initialize_dwarf2_read (void)
25771 {
25772   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25773 Set DWARF specific variables.\n\
25774 Configure DWARF variables such as the cache size"),
25775                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25776                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25777
25778   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25779 Show DWARF specific variables\n\
25780 Show DWARF variables such as the cache size"),
25781                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25782                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25783
25784   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25785                             &dwarf_max_cache_age, _("\
25786 Set the upper bound on the age of cached DWARF compilation units."), _("\
25787 Show the upper bound on the age of cached DWARF compilation units."), _("\
25788 A higher limit means that cached compilation units will be stored\n\
25789 in memory longer, and more total memory will be used.  Zero disables\n\
25790 caching, which can slow down startup."),
25791                             NULL,
25792                             show_dwarf_max_cache_age,
25793                             &set_dwarf_cmdlist,
25794                             &show_dwarf_cmdlist);
25795
25796   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25797                            &dwarf_always_disassemble, _("\
25798 Set whether `info address' always disassembles DWARF expressions."), _("\
25799 Show whether `info address' always disassembles DWARF expressions."), _("\
25800 When enabled, DWARF expressions are always printed in an assembly-like\n\
25801 syntax.  When disabled, expressions will be printed in a more\n\
25802 conversational style, when possible."),
25803                            NULL,
25804                            show_dwarf_always_disassemble,
25805                            &set_dwarf_cmdlist,
25806                            &show_dwarf_cmdlist);
25807
25808   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25809 Set debugging of the DWARF reader."), _("\
25810 Show debugging of the DWARF reader."), _("\
25811 When enabled (non-zero), debugging messages are printed during DWARF\n\
25812 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25813 information.  A value greater than 1 provides more verbose information."),
25814                             NULL,
25815                             NULL,
25816                             &setdebuglist, &showdebuglist);
25817
25818   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25819 Set debugging of the DWARF DIE reader."), _("\
25820 Show debugging of the DWARF DIE reader."), _("\
25821 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25822 The value is the maximum depth to print."),
25823                              NULL,
25824                              NULL,
25825                              &setdebuglist, &showdebuglist);
25826
25827   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25828 Set debugging of the dwarf line reader."), _("\
25829 Show debugging of the dwarf line reader."), _("\
25830 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25831 A value of 1 (one) provides basic information.\n\
25832 A value greater than 1 provides more verbose information."),
25833                              NULL,
25834                              NULL,
25835                              &setdebuglist, &showdebuglist);
25836
25837   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25838 Set cross-checking of \"physname\" code against demangler."), _("\
25839 Show cross-checking of \"physname\" code against demangler."), _("\
25840 When enabled, GDB's internal \"physname\" code is checked against\n\
25841 the demangler."),
25842                            NULL, show_check_physname,
25843                            &setdebuglist, &showdebuglist);
25844
25845   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25846                            no_class, &use_deprecated_index_sections, _("\
25847 Set whether to use deprecated gdb_index sections."), _("\
25848 Show whether to use deprecated gdb_index sections."), _("\
25849 When enabled, deprecated .gdb_index sections are used anyway.\n\
25850 Normally they are ignored either because of a missing feature or\n\
25851 performance issue.\n\
25852 Warning: This option must be enabled before gdb reads the file."),
25853                            NULL,
25854                            NULL,
25855                            &setlist, &showlist);
25856
25857   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25858                                                         &dwarf2_locexpr_funcs);
25859   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25860                                                         &dwarf2_loclist_funcs);
25861
25862   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25863                                         &dwarf2_block_frame_base_locexpr_funcs);
25864   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25865                                         &dwarf2_block_frame_base_loclist_funcs);
25866
25867 #if GDB_SELF_TEST
25868   selftests::register_test ("dw2_expand_symtabs_matching",
25869                             selftests::dw2_expand_symtabs_matching::run_test);
25870 #endif
25871 }