]> Git Repo - binutils.git/blob - gdb/dwarf2/read.c
Avoid some pointer chasing in DWARF reader
[binutils.git] / gdb / dwarf2 / read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2021 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck ([email protected]), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "dwarf2/read.h"
33 #include "dwarf2/abbrev.h"
34 #include "dwarf2/attribute.h"
35 #include "dwarf2/comp-unit.h"
36 #include "dwarf2/index-cache.h"
37 #include "dwarf2/index-common.h"
38 #include "dwarf2/leb.h"
39 #include "dwarf2/line-header.h"
40 #include "dwarf2/dwz.h"
41 #include "dwarf2/macro.h"
42 #include "dwarf2/die.h"
43 #include "dwarf2/sect-names.h"
44 #include "dwarf2/stringify.h"
45 #include "dwarf2/public.h"
46 #include "bfd.h"
47 #include "elf-bfd.h"
48 #include "symtab.h"
49 #include "gdbtypes.h"
50 #include "objfiles.h"
51 #include "dwarf2.h"
52 #include "buildsym.h"
53 #include "demangle.h"
54 #include "gdb-demangle.h"
55 #include "filenames.h"  /* for DOSish file names */
56 #include "language.h"
57 #include "complaints.h"
58 #include "dwarf2/expr.h"
59 #include "dwarf2/loc.h"
60 #include "cp-support.h"
61 #include "hashtab.h"
62 #include "command.h"
63 #include "gdbcmd.h"
64 #include "block.h"
65 #include "addrmap.h"
66 #include "typeprint.h"
67 #include "psympriv.h"
68 #include "c-lang.h"
69 #include "go-lang.h"
70 #include "valprint.h"
71 #include "gdbcore.h" /* for gnutarget */
72 #include "gdb/gdb-index.h"
73 #include "gdb_bfd.h"
74 #include "f-lang.h"
75 #include "source.h"
76 #include "build-id.h"
77 #include "namespace.h"
78 #include "gdbsupport/function-view.h"
79 #include "gdbsupport/gdb_optional.h"
80 #include "gdbsupport/underlying.h"
81 #include "gdbsupport/hash_enum.h"
82 #include "filename-seen-cache.h"
83 #include "producer.h"
84 #include <fcntl.h>
85 #include <algorithm>
86 #include <unordered_map>
87 #include "gdbsupport/selftest.h"
88 #include "rust-lang.h"
89 #include "gdbsupport/pathstuff.h"
90 #include "count-one-bits.h"
91
92 /* When == 1, print basic high level tracing messages.
93    When > 1, be more verbose.
94    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
95 static unsigned int dwarf_read_debug = 0;
96
97 /* Print a "dwarf-read" debug statement if dwarf_read_debug is >= 1.  */
98
99 #define dwarf_read_debug_printf(fmt, ...) \
100   debug_prefixed_printf_cond (dwarf_read_debug >= 1, "dwarf-read", fmt, \
101                               ##__VA_ARGS__)
102
103 /* Print a "dwarf-read" debug statement if dwarf_read_debug is >= 2.  */
104
105 #define dwarf_read_debug_printf_v(fmt, ...) \
106   debug_prefixed_printf_cond (dwarf_read_debug >= 2, "dwarf-read", fmt, \
107                               ##__VA_ARGS__)
108
109 /* When non-zero, dump DIEs after they are read in.  */
110 static unsigned int dwarf_die_debug = 0;
111
112 /* When non-zero, dump line number entries as they are read in.  */
113 unsigned int dwarf_line_debug = 0;
114
115 /* When true, cross-check physname against demangler.  */
116 static bool check_physname = false;
117
118 /* When true, do not reject deprecated .gdb_index sections.  */
119 static bool use_deprecated_index_sections = false;
120
121 /* This is used to store the data that is always per objfile.  */
122 static const objfile_key<dwarf2_per_objfile> dwarf2_objfile_data_key;
123
124 /* These are used to store the dwarf2_per_bfd objects.
125
126    objfiles having the same BFD, which doesn't require relocations, are going to
127    share a dwarf2_per_bfd object, which is held in the _bfd_data_key version.
128
129    Other objfiles are not going to share a dwarf2_per_bfd with any other
130    objfiles, so they'll have their own version kept in the _objfile_data_key
131    version.  */
132 static const struct bfd_key<dwarf2_per_bfd> dwarf2_per_bfd_bfd_data_key;
133 static const struct objfile_key<dwarf2_per_bfd> dwarf2_per_bfd_objfile_data_key;
134
135 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
136
137 static int dwarf2_locexpr_index;
138 static int dwarf2_loclist_index;
139 static int dwarf2_locexpr_block_index;
140 static int dwarf2_loclist_block_index;
141
142 /* Size of .debug_loclists section header for 32-bit DWARF format.  */
143 #define LOCLIST_HEADER_SIZE32 12
144
145 /* Size of .debug_loclists section header for 64-bit DWARF format.  */
146 #define LOCLIST_HEADER_SIZE64 20
147
148 /* Size of .debug_rnglists section header for 32-bit DWARF format.  */
149 #define RNGLIST_HEADER_SIZE32 12
150
151 /* Size of .debug_rnglists section header for 64-bit DWARF format.  */
152 #define RNGLIST_HEADER_SIZE64 20
153
154 /* An index into a (C++) symbol name component in a symbol name as
155    recorded in the mapped_index's symbol table.  For each C++ symbol
156    in the symbol table, we record one entry for the start of each
157    component in the symbol in a table of name components, and then
158    sort the table, in order to be able to binary search symbol names,
159    ignoring leading namespaces, both completion and regular look up.
160    For example, for symbol "A::B::C", we'll have an entry that points
161    to "A::B::C", another that points to "B::C", and another for "C".
162    Note that function symbols in GDB index have no parameter
163    information, just the function/method names.  You can convert a
164    name_component to a "const char *" using the
165    'mapped_index::symbol_name_at(offset_type)' method.  */
166
167 struct name_component
168 {
169   /* Offset in the symbol name where the component starts.  Stored as
170      a (32-bit) offset instead of a pointer to save memory and improve
171      locality on 64-bit architectures.  */
172   offset_type name_offset;
173
174   /* The symbol's index in the symbol and constant pool tables of a
175      mapped_index.  */
176   offset_type idx;
177 };
178
179 /* Base class containing bits shared by both .gdb_index and
180    .debug_name indexes.  */
181
182 struct mapped_index_base
183 {
184   mapped_index_base () = default;
185   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
186
187   /* The name_component table (a sorted vector).  See name_component's
188      description above.  */
189   std::vector<name_component> name_components;
190
191   /* How NAME_COMPONENTS is sorted.  */
192   enum case_sensitivity name_components_casing;
193
194   /* Return the number of names in the symbol table.  */
195   virtual size_t symbol_name_count () const = 0;
196
197   /* Get the name of the symbol at IDX in the symbol table.  */
198   virtual const char *symbol_name_at
199     (offset_type idx, dwarf2_per_objfile *per_objfile) const = 0;
200
201   /* Return whether the name at IDX in the symbol table should be
202      ignored.  */
203   virtual bool symbol_name_slot_invalid (offset_type idx) const
204   {
205     return false;
206   }
207
208   /* Build the symbol name component sorted vector, if we haven't
209      yet.  */
210   void build_name_components (dwarf2_per_objfile *per_objfile);
211
212   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
213      possible matches for LN_NO_PARAMS in the name component
214      vector.  */
215   std::pair<std::vector<name_component>::const_iterator,
216             std::vector<name_component>::const_iterator>
217     find_name_components_bounds (const lookup_name_info &ln_no_params,
218                                  enum language lang,
219                                  dwarf2_per_objfile *per_objfile) const;
220
221   /* Prevent deleting/destroying via a base class pointer.  */
222 protected:
223   ~mapped_index_base() = default;
224 };
225
226 /* A description of the mapped index.  The file format is described in
227    a comment by the code that writes the index.  */
228 struct mapped_index final : public mapped_index_base
229 {
230   /* A slot/bucket in the symbol table hash.  */
231   struct symbol_table_slot
232   {
233     const offset_type name;
234     const offset_type vec;
235   };
236
237   /* Index data format version.  */
238   int version = 0;
239
240   /* The address table data.  */
241   gdb::array_view<const gdb_byte> address_table;
242
243   /* The symbol table, implemented as a hash table.  */
244   gdb::array_view<symbol_table_slot> symbol_table;
245
246   /* A pointer to the constant pool.  */
247   const char *constant_pool = nullptr;
248
249   bool symbol_name_slot_invalid (offset_type idx) const override
250   {
251     const auto &bucket = this->symbol_table[idx];
252     return bucket.name == 0 && bucket.vec == 0;
253   }
254
255   /* Convenience method to get at the name of the symbol at IDX in the
256      symbol table.  */
257   const char *symbol_name_at
258     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
259   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
260
261   size_t symbol_name_count () const override
262   { return this->symbol_table.size (); }
263 };
264
265 /* A description of the mapped .debug_names.
266    Uninitialized map has CU_COUNT 0.  */
267 struct mapped_debug_names final : public mapped_index_base
268 {
269   bfd_endian dwarf5_byte_order;
270   bool dwarf5_is_dwarf64;
271   bool augmentation_is_gdb;
272   uint8_t offset_size;
273   uint32_t cu_count = 0;
274   uint32_t tu_count, bucket_count, name_count;
275   const gdb_byte *cu_table_reordered, *tu_table_reordered;
276   const uint32_t *bucket_table_reordered, *hash_table_reordered;
277   const gdb_byte *name_table_string_offs_reordered;
278   const gdb_byte *name_table_entry_offs_reordered;
279   const gdb_byte *entry_pool;
280
281   struct index_val
282   {
283     ULONGEST dwarf_tag;
284     struct attr
285     {
286       /* Attribute name DW_IDX_*.  */
287       ULONGEST dw_idx;
288
289       /* Attribute form DW_FORM_*.  */
290       ULONGEST form;
291
292       /* Value if FORM is DW_FORM_implicit_const.  */
293       LONGEST implicit_const;
294     };
295     std::vector<attr> attr_vec;
296   };
297
298   std::unordered_map<ULONGEST, index_val> abbrev_map;
299
300   const char *namei_to_name
301     (uint32_t namei, dwarf2_per_objfile *per_objfile) const;
302
303   /* Implementation of the mapped_index_base virtual interface, for
304      the name_components cache.  */
305
306   const char *symbol_name_at
307     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
308   { return namei_to_name (idx, per_objfile); }
309
310   size_t symbol_name_count () const override
311   { return this->name_count; }
312 };
313
314 /* See dwarf2read.h.  */
315
316 dwarf2_per_objfile *
317 get_dwarf2_per_objfile (struct objfile *objfile)
318 {
319   return dwarf2_objfile_data_key.get (objfile);
320 }
321
322 /* Default names of the debugging sections.  */
323
324 /* Note that if the debugging section has been compressed, it might
325    have a name like .zdebug_info.  */
326
327 const struct dwarf2_debug_sections dwarf2_elf_names =
328 {
329   { ".debug_info", ".zdebug_info" },
330   { ".debug_abbrev", ".zdebug_abbrev" },
331   { ".debug_line", ".zdebug_line" },
332   { ".debug_loc", ".zdebug_loc" },
333   { ".debug_loclists", ".zdebug_loclists" },
334   { ".debug_macinfo", ".zdebug_macinfo" },
335   { ".debug_macro", ".zdebug_macro" },
336   { ".debug_str", ".zdebug_str" },
337   { ".debug_str_offsets", ".zdebug_str_offsets" },
338   { ".debug_line_str", ".zdebug_line_str" },
339   { ".debug_ranges", ".zdebug_ranges" },
340   { ".debug_rnglists", ".zdebug_rnglists" },
341   { ".debug_types", ".zdebug_types" },
342   { ".debug_addr", ".zdebug_addr" },
343   { ".debug_frame", ".zdebug_frame" },
344   { ".eh_frame", NULL },
345   { ".gdb_index", ".zgdb_index" },
346   { ".debug_names", ".zdebug_names" },
347   { ".debug_aranges", ".zdebug_aranges" },
348   23
349 };
350
351 /* List of DWO/DWP sections.  */
352
353 static const struct dwop_section_names
354 {
355   struct dwarf2_section_names abbrev_dwo;
356   struct dwarf2_section_names info_dwo;
357   struct dwarf2_section_names line_dwo;
358   struct dwarf2_section_names loc_dwo;
359   struct dwarf2_section_names loclists_dwo;
360   struct dwarf2_section_names macinfo_dwo;
361   struct dwarf2_section_names macro_dwo;
362   struct dwarf2_section_names rnglists_dwo;
363   struct dwarf2_section_names str_dwo;
364   struct dwarf2_section_names str_offsets_dwo;
365   struct dwarf2_section_names types_dwo;
366   struct dwarf2_section_names cu_index;
367   struct dwarf2_section_names tu_index;
368 }
369 dwop_section_names =
370 {
371   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
372   { ".debug_info.dwo", ".zdebug_info.dwo" },
373   { ".debug_line.dwo", ".zdebug_line.dwo" },
374   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
375   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
376   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
377   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
378   { ".debug_rnglists.dwo", ".zdebug_rnglists.dwo" },
379   { ".debug_str.dwo", ".zdebug_str.dwo" },
380   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
381   { ".debug_types.dwo", ".zdebug_types.dwo" },
382   { ".debug_cu_index", ".zdebug_cu_index" },
383   { ".debug_tu_index", ".zdebug_tu_index" },
384 };
385
386 /* local data types */
387
388 /* The location list and range list sections (.debug_loclists & .debug_rnglists)
389    begin with a header,  which contains the following information.  */
390 struct loclists_rnglists_header
391 {
392   /* A 4-byte or 12-byte length containing the length of the
393      set of entries for this compilation unit, not including the
394      length field itself.  */
395   unsigned int length;
396
397   /* A 2-byte version identifier.  */
398   short version;
399
400   /* A 1-byte unsigned integer containing the size in bytes of an address on
401      the target system.  */
402   unsigned char addr_size;
403
404   /* A 1-byte unsigned integer containing the size in bytes of a segment selector
405      on the target system.  */
406   unsigned char segment_collector_size;
407
408   /* A 4-byte count of the number of offsets that follow the header.  */
409   unsigned int offset_entry_count;
410 };
411
412 /* Type used for delaying computation of method physnames.
413    See comments for compute_delayed_physnames.  */
414 struct delayed_method_info
415 {
416   /* The type to which the method is attached, i.e., its parent class.  */
417   struct type *type;
418
419   /* The index of the method in the type's function fieldlists.  */
420   int fnfield_index;
421
422   /* The index of the method in the fieldlist.  */
423   int index;
424
425   /* The name of the DIE.  */
426   const char *name;
427
428   /*  The DIE associated with this method.  */
429   struct die_info *die;
430 };
431
432 /* Internal state when decoding a particular compilation unit.  */
433 struct dwarf2_cu
434 {
435   explicit dwarf2_cu (dwarf2_per_cu_data *per_cu,
436                       dwarf2_per_objfile *per_objfile);
437
438   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
439
440   /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
441      Create the set of symtabs used by this TU, or if this TU is sharing
442      symtabs with another TU and the symtabs have already been created
443      then restore those symtabs in the line header.
444      We don't need the pc/line-number mapping for type units.  */
445   void setup_type_unit_groups (struct die_info *die);
446
447   /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
448      buildsym_compunit constructor.  */
449   struct compunit_symtab *start_symtab (const char *name,
450                                         const char *comp_dir,
451                                         CORE_ADDR low_pc);
452
453   /* Reset the builder.  */
454   void reset_builder () { m_builder.reset (); }
455
456   /* Return a type that is a generic pointer type, the size of which
457      matches the address size given in the compilation unit header for
458      this CU.  */
459   struct type *addr_type () const;
460
461   /* Find an integer type the same size as the address size given in
462      the compilation unit header for this CU.  UNSIGNED_P controls if
463      the integer is unsigned or not.  */
464   struct type *addr_sized_int_type (bool unsigned_p) const;
465
466   /* The header of the compilation unit.  */
467   struct comp_unit_head header {};
468
469   /* Base address of this compilation unit.  */
470   gdb::optional<CORE_ADDR> base_address;
471
472   /* The language we are debugging.  */
473   enum language language = language_unknown;
474   const struct language_defn *language_defn = nullptr;
475
476   const char *producer = nullptr;
477
478 private:
479   /* The symtab builder for this CU.  This is only non-NULL when full
480      symbols are being read.  */
481   std::unique_ptr<buildsym_compunit> m_builder;
482
483 public:
484   /* The generic symbol table building routines have separate lists for
485      file scope symbols and all all other scopes (local scopes).  So
486      we need to select the right one to pass to add_symbol_to_list().
487      We do it by keeping a pointer to the correct list in list_in_scope.
488
489      FIXME: The original dwarf code just treated the file scope as the
490      first local scope, and all other local scopes as nested local
491      scopes, and worked fine.  Check to see if we really need to
492      distinguish these in buildsym.c.  */
493   struct pending **list_in_scope = nullptr;
494
495   /* Hash table holding all the loaded partial DIEs
496      with partial_die->offset.SECT_OFF as hash.  */
497   htab_t partial_dies = nullptr;
498
499   /* Storage for things with the same lifetime as this read-in compilation
500      unit, including partial DIEs.  */
501   auto_obstack comp_unit_obstack;
502
503   /* Backlink to our per_cu entry.  */
504   struct dwarf2_per_cu_data *per_cu;
505
506   /* The dwarf2_per_objfile that owns this.  */
507   dwarf2_per_objfile *per_objfile;
508
509   /* How many compilation units ago was this CU last referenced?  */
510   int last_used = 0;
511
512   /* A hash table of DIE cu_offset for following references with
513      die_info->offset.sect_off as hash.  */
514   htab_t die_hash = nullptr;
515
516   /* Full DIEs if read in.  */
517   struct die_info *dies = nullptr;
518
519   /* A set of pointers to dwarf2_per_cu_data objects for compilation
520      units referenced by this one.  Only set during full symbol processing;
521      partial symbol tables do not have dependencies.  */
522   htab_t dependencies = nullptr;
523
524   /* Header data from the line table, during full symbol processing.  */
525   struct line_header *line_header = nullptr;
526   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
527      it's owned by dwarf2_per_bfd::line_header_hash.  If non-NULL,
528      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
529      to the line header as long as this DIE is being processed.  See
530      process_die_scope.  */
531   die_info *line_header_die_owner = nullptr;
532
533   /* A list of methods which need to have physnames computed
534      after all type information has been read.  */
535   std::vector<delayed_method_info> method_list;
536
537   /* To be copied to symtab->call_site_htab.  */
538   htab_t call_site_htab = nullptr;
539
540   /* Non-NULL if this CU came from a DWO file.
541      There is an invariant here that is important to remember:
542      Except for attributes copied from the top level DIE in the "main"
543      (or "stub") file in preparation for reading the DWO file
544      (e.g., DW_AT_addr_base), we KISS: there is only *one* CU.
545      Either there isn't a DWO file (in which case this is NULL and the point
546      is moot), or there is and either we're not going to read it (in which
547      case this is NULL) or there is and we are reading it (in which case this
548      is non-NULL).  */
549   struct dwo_unit *dwo_unit = nullptr;
550
551   /* The DW_AT_addr_base (DW_AT_GNU_addr_base) attribute if present.
552      Note this value comes from the Fission stub CU/TU's DIE.  */
553   gdb::optional<ULONGEST> addr_base;
554
555   /* The DW_AT_GNU_ranges_base attribute, if present.
556
557      This is only relevant in the context of pre-DWARF 5 split units.  In this
558      context, there is a .debug_ranges section in the linked executable,
559      containing all the ranges data for all the compilation units.  Each
560      skeleton/stub unit has (if needed) a DW_AT_GNU_ranges_base attribute that
561      indicates the base of its contribution to that section.  The DW_AT_ranges
562      attributes in the split-unit are of the form DW_FORM_sec_offset and point
563      into the .debug_ranges section of the linked file.  However, they are not
564      "true" DW_FORM_sec_offset, because they are relative to the base of their
565      compilation unit's contribution, rather than relative to the beginning of
566      the section.  The DW_AT_GNU_ranges_base value must be added to it to make
567      it relative to the beginning of the section.
568
569      Note that the value is zero when we are not in a pre-DWARF 5 split-unit
570      case, so this value can be added without needing to know whether we are in
571      this case or not.
572
573      N.B. If a DW_AT_ranges attribute is found on the DW_TAG_compile_unit in the
574      skeleton/stub, it must not have the base added, as it already points to the
575      right place.  And since the DW_TAG_compile_unit DIE in the split-unit can't
576      have a DW_AT_ranges attribute, we can use the
577
578        die->tag != DW_AT_compile_unit
579
580      to determine whether the base should be added or not.  */
581   ULONGEST gnu_ranges_base = 0;
582
583   /* The DW_AT_rnglists_base attribute, if present.
584
585      This is used when processing attributes of form DW_FORM_rnglistx in
586      non-split units.  Attributes of this form found in a split unit don't
587      use it, as split-unit files have their own non-shared .debug_rnglists.dwo
588      section.  */
589   ULONGEST rnglists_base = 0;
590
591   /* The DW_AT_loclists_base attribute if present.  */
592   ULONGEST loclist_base = 0;
593
594   /* When reading debug info generated by older versions of rustc, we
595      have to rewrite some union types to be struct types with a
596      variant part.  This rewriting must be done after the CU is fully
597      read in, because otherwise at the point of rewriting some struct
598      type might not have been fully processed.  So, we keep a list of
599      all such types here and process them after expansion.  */
600   std::vector<struct type *> rust_unions;
601
602   /* The DW_AT_str_offsets_base attribute if present.  For DWARF 4 version DWO
603      files, the value is implicitly zero.  For DWARF 5 version DWO files, the
604      value is often implicit and is the size of the header of
605      .debug_str_offsets section (8 or 4, depending on the address size).  */
606   gdb::optional<ULONGEST> str_offsets_base;
607
608   /* Mark used when releasing cached dies.  */
609   bool mark : 1;
610
611   /* This CU references .debug_loc.  See the symtab->locations_valid field.
612      This test is imperfect as there may exist optimized debug code not using
613      any location list and still facing inlining issues if handled as
614      unoptimized code.  For a future better test see GCC PR other/32998.  */
615   bool has_loclist : 1;
616
617   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is true
618      if all the producer_is_* fields are valid.  This information is cached
619      because profiling CU expansion showed excessive time spent in
620      producer_is_gxx_lt_4_6.  */
621   bool checked_producer : 1;
622   bool producer_is_gxx_lt_4_6 : 1;
623   bool producer_is_gcc_lt_4_3 : 1;
624   bool producer_is_icc : 1;
625   bool producer_is_icc_lt_14 : 1;
626   bool producer_is_codewarrior : 1;
627
628   /* When true, the file that we're processing is known to have
629      debugging info for C++ namespaces.  GCC 3.3.x did not produce
630      this information, but later versions do.  */
631
632   bool processing_has_namespace_info : 1;
633
634   struct partial_die_info *find_partial_die (sect_offset sect_off);
635
636   /* If this CU was inherited by another CU (via specification,
637      abstract_origin, etc), this is the ancestor CU.  */
638   dwarf2_cu *ancestor;
639
640   /* Get the buildsym_compunit for this CU.  */
641   buildsym_compunit *get_builder ()
642   {
643     /* If this CU has a builder associated with it, use that.  */
644     if (m_builder != nullptr)
645       return m_builder.get ();
646
647     /* Otherwise, search ancestors for a valid builder.  */
648     if (ancestor != nullptr)
649       return ancestor->get_builder ();
650
651     return nullptr;
652   }
653 };
654
655 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
656    This includes type_unit_group and quick_file_names.  */
657
658 struct stmt_list_hash
659 {
660   /* The DWO unit this table is from or NULL if there is none.  */
661   struct dwo_unit *dwo_unit;
662
663   /* Offset in .debug_line or .debug_line.dwo.  */
664   sect_offset line_sect_off;
665 };
666
667 /* Each element of dwarf2_per_bfd->type_unit_groups is a pointer to
668    an object of this type.  This contains elements of type unit groups
669    that can be shared across objfiles.  The non-shareable parts are in
670    type_unit_group_unshareable.  */
671
672 struct type_unit_group
673 {
674   /* dwarf2read.c's main "handle" on a TU symtab.
675      To simplify things we create an artificial CU that "includes" all the
676      type units using this stmt_list so that the rest of the code still has
677      a "per_cu" handle on the symtab.  */
678   struct dwarf2_per_cu_data per_cu;
679
680   /* The TUs that share this DW_AT_stmt_list entry.
681      This is added to while parsing type units to build partial symtabs,
682      and is deleted afterwards and not used again.  */
683   std::vector<signatured_type *> *tus;
684
685   /* The data used to construct the hash key.  */
686   struct stmt_list_hash hash;
687 };
688
689 /* These sections are what may appear in a (real or virtual) DWO file.  */
690
691 struct dwo_sections
692 {
693   struct dwarf2_section_info abbrev;
694   struct dwarf2_section_info line;
695   struct dwarf2_section_info loc;
696   struct dwarf2_section_info loclists;
697   struct dwarf2_section_info macinfo;
698   struct dwarf2_section_info macro;
699   struct dwarf2_section_info rnglists;
700   struct dwarf2_section_info str;
701   struct dwarf2_section_info str_offsets;
702   /* In the case of a virtual DWO file, these two are unused.  */
703   struct dwarf2_section_info info;
704   std::vector<dwarf2_section_info> types;
705 };
706
707 /* CUs/TUs in DWP/DWO files.  */
708
709 struct dwo_unit
710 {
711   /* Backlink to the containing struct dwo_file.  */
712   struct dwo_file *dwo_file;
713
714   /* The "id" that distinguishes this CU/TU.
715      .debug_info calls this "dwo_id", .debug_types calls this "signature".
716      Since signatures came first, we stick with it for consistency.  */
717   ULONGEST signature;
718
719   /* The section this CU/TU lives in, in the DWO file.  */
720   struct dwarf2_section_info *section;
721
722   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
723   sect_offset sect_off;
724   unsigned int length;
725
726   /* For types, offset in the type's DIE of the type defined by this TU.  */
727   cu_offset type_offset_in_tu;
728 };
729
730 /* include/dwarf2.h defines the DWP section codes.
731    It defines a max value but it doesn't define a min value, which we
732    use for error checking, so provide one.  */
733
734 enum dwp_v2_section_ids
735 {
736   DW_SECT_MIN = 1
737 };
738
739 /* Data for one DWO file.
740
741    This includes virtual DWO files (a virtual DWO file is a DWO file as it
742    appears in a DWP file).  DWP files don't really have DWO files per se -
743    comdat folding of types "loses" the DWO file they came from, and from
744    a high level view DWP files appear to contain a mass of random types.
745    However, to maintain consistency with the non-DWP case we pretend DWP
746    files contain virtual DWO files, and we assign each TU with one virtual
747    DWO file (generally based on the line and abbrev section offsets -
748    a heuristic that seems to work in practice).  */
749
750 struct dwo_file
751 {
752   dwo_file () = default;
753   DISABLE_COPY_AND_ASSIGN (dwo_file);
754
755   /* The DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.
756      For virtual DWO files the name is constructed from the section offsets
757      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
758      from related CU+TUs.  */
759   const char *dwo_name = nullptr;
760
761   /* The DW_AT_comp_dir attribute.  */
762   const char *comp_dir = nullptr;
763
764   /* The bfd, when the file is open.  Otherwise this is NULL.
765      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
766   gdb_bfd_ref_ptr dbfd;
767
768   /* The sections that make up this DWO file.
769      Remember that for virtual DWO files in DWP V2 or DWP V5, these are virtual
770      sections (for lack of a better name).  */
771   struct dwo_sections sections {};
772
773   /* The CUs in the file.
774      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
775      an extension to handle LLVM's Link Time Optimization output (where
776      multiple source files may be compiled into a single object/dwo pair). */
777   htab_up cus;
778
779   /* Table of TUs in the file.
780      Each element is a struct dwo_unit.  */
781   htab_up tus;
782 };
783
784 /* These sections are what may appear in a DWP file.  */
785
786 struct dwp_sections
787 {
788   /* These are used by all DWP versions (1, 2 and 5).  */
789   struct dwarf2_section_info str;
790   struct dwarf2_section_info cu_index;
791   struct dwarf2_section_info tu_index;
792
793   /* These are only used by DWP version 2 and version 5 files.
794      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
795      sections are referenced by section number, and are not recorded here.
796      In DWP version 2 or 5 there is at most one copy of all these sections,
797      each section being (effectively) comprised of the concatenation of all of
798      the individual sections that exist in the version 1 format.
799      To keep the code simple we treat each of these concatenated pieces as a
800      section itself (a virtual section?).  */
801   struct dwarf2_section_info abbrev;
802   struct dwarf2_section_info info;
803   struct dwarf2_section_info line;
804   struct dwarf2_section_info loc;
805   struct dwarf2_section_info loclists;
806   struct dwarf2_section_info macinfo;
807   struct dwarf2_section_info macro;
808   struct dwarf2_section_info rnglists;
809   struct dwarf2_section_info str_offsets;
810   struct dwarf2_section_info types;
811 };
812
813 /* These sections are what may appear in a virtual DWO file in DWP version 1.
814    A virtual DWO file is a DWO file as it appears in a DWP file.  */
815
816 struct virtual_v1_dwo_sections
817 {
818   struct dwarf2_section_info abbrev;
819   struct dwarf2_section_info line;
820   struct dwarf2_section_info loc;
821   struct dwarf2_section_info macinfo;
822   struct dwarf2_section_info macro;
823   struct dwarf2_section_info str_offsets;
824   /* Each DWP hash table entry records one CU or one TU.
825      That is recorded here, and copied to dwo_unit.section.  */
826   struct dwarf2_section_info info_or_types;
827 };
828
829 /* Similar to virtual_v1_dwo_sections, but for DWP version 2 or 5.
830    In version 2, the sections of the DWO files are concatenated together
831    and stored in one section of that name.  Thus each ELF section contains
832    several "virtual" sections.  */
833
834 struct virtual_v2_or_v5_dwo_sections
835 {
836   bfd_size_type abbrev_offset;
837   bfd_size_type abbrev_size;
838
839   bfd_size_type line_offset;
840   bfd_size_type line_size;
841
842   bfd_size_type loc_offset;
843   bfd_size_type loc_size;
844
845   bfd_size_type loclists_offset;
846   bfd_size_type loclists_size;
847
848   bfd_size_type macinfo_offset;
849   bfd_size_type macinfo_size;
850
851   bfd_size_type macro_offset;
852   bfd_size_type macro_size;
853
854   bfd_size_type rnglists_offset;
855   bfd_size_type rnglists_size;
856
857   bfd_size_type str_offsets_offset;
858   bfd_size_type str_offsets_size;
859
860   /* Each DWP hash table entry records one CU or one TU.
861      That is recorded here, and copied to dwo_unit.section.  */
862   bfd_size_type info_or_types_offset;
863   bfd_size_type info_or_types_size;
864 };
865
866 /* Contents of DWP hash tables.  */
867
868 struct dwp_hash_table
869 {
870   uint32_t version, nr_columns;
871   uint32_t nr_units, nr_slots;
872   const gdb_byte *hash_table, *unit_table;
873   union
874   {
875     struct
876     {
877       const gdb_byte *indices;
878     } v1;
879     struct
880     {
881       /* This is indexed by column number and gives the id of the section
882          in that column.  */
883 #define MAX_NR_V2_DWO_SECTIONS \
884   (1 /* .debug_info or .debug_types */ \
885    + 1 /* .debug_abbrev */ \
886    + 1 /* .debug_line */ \
887    + 1 /* .debug_loc */ \
888    + 1 /* .debug_str_offsets */ \
889    + 1 /* .debug_macro or .debug_macinfo */)
890       int section_ids[MAX_NR_V2_DWO_SECTIONS];
891       const gdb_byte *offsets;
892       const gdb_byte *sizes;
893     } v2;
894     struct
895     {
896       /* This is indexed by column number and gives the id of the section
897          in that column.  */
898 #define MAX_NR_V5_DWO_SECTIONS \
899   (1 /* .debug_info */ \
900    + 1 /* .debug_abbrev */ \
901    + 1 /* .debug_line */ \
902    + 1 /* .debug_loclists */ \
903    + 1 /* .debug_str_offsets */ \
904    + 1 /* .debug_macro */ \
905    + 1 /* .debug_rnglists */)
906       int section_ids[MAX_NR_V5_DWO_SECTIONS];
907       const gdb_byte *offsets;
908       const gdb_byte *sizes;
909     } v5;
910   } section_pool;
911 };
912
913 /* Data for one DWP file.  */
914
915 struct dwp_file
916 {
917   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
918     : name (name_),
919       dbfd (std::move (abfd))
920   {
921   }
922
923   /* Name of the file.  */
924   const char *name;
925
926   /* File format version.  */
927   int version = 0;
928
929   /* The bfd.  */
930   gdb_bfd_ref_ptr dbfd;
931
932   /* Section info for this file.  */
933   struct dwp_sections sections {};
934
935   /* Table of CUs in the file.  */
936   const struct dwp_hash_table *cus = nullptr;
937
938   /* Table of TUs in the file.  */
939   const struct dwp_hash_table *tus = nullptr;
940
941   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
942   htab_up loaded_cus;
943   htab_up loaded_tus;
944
945   /* Table to map ELF section numbers to their sections.
946      This is only needed for the DWP V1 file format.  */
947   unsigned int num_sections = 0;
948   asection **elf_sections = nullptr;
949 };
950
951 /* Struct used to pass misc. parameters to read_die_and_children, et
952    al.  which are used for both .debug_info and .debug_types dies.
953    All parameters here are unchanging for the life of the call.  This
954    struct exists to abstract away the constant parameters of die reading.  */
955
956 struct die_reader_specs
957 {
958   /* The bfd of die_section.  */
959   bfd *abfd;
960
961   /* The CU of the DIE we are parsing.  */
962   struct dwarf2_cu *cu;
963
964   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
965   struct dwo_file *dwo_file;
966
967   /* The section the die comes from.
968      This is either .debug_info or .debug_types, or the .dwo variants.  */
969   struct dwarf2_section_info *die_section;
970
971   /* die_section->buffer.  */
972   const gdb_byte *buffer;
973
974   /* The end of the buffer.  */
975   const gdb_byte *buffer_end;
976
977   /* The abbreviation table to use when reading the DIEs.  */
978   struct abbrev_table *abbrev_table;
979 };
980
981 /* A subclass of die_reader_specs that holds storage and has complex
982    constructor and destructor behavior.  */
983
984 class cutu_reader : public die_reader_specs
985 {
986 public:
987
988   cutu_reader (dwarf2_per_cu_data *this_cu,
989                dwarf2_per_objfile *per_objfile,
990                struct abbrev_table *abbrev_table,
991                dwarf2_cu *existing_cu,
992                bool skip_partial);
993
994   explicit cutu_reader (struct dwarf2_per_cu_data *this_cu,
995                         dwarf2_per_objfile *per_objfile,
996                         struct dwarf2_cu *parent_cu = nullptr,
997                         struct dwo_file *dwo_file = nullptr);
998
999   DISABLE_COPY_AND_ASSIGN (cutu_reader);
1000
1001   const gdb_byte *info_ptr = nullptr;
1002   struct die_info *comp_unit_die = nullptr;
1003   bool dummy_p = false;
1004
1005   /* Release the new CU, putting it on the chain.  This cannot be done
1006      for dummy CUs.  */
1007   void keep ();
1008
1009 private:
1010   void init_tu_and_read_dwo_dies (dwarf2_per_cu_data *this_cu,
1011                                   dwarf2_per_objfile *per_objfile,
1012                                   dwarf2_cu *existing_cu);
1013
1014   struct dwarf2_per_cu_data *m_this_cu;
1015   std::unique_ptr<dwarf2_cu> m_new_cu;
1016
1017   /* The ordinary abbreviation table.  */
1018   abbrev_table_up m_abbrev_table_holder;
1019
1020   /* The DWO abbreviation table.  */
1021   abbrev_table_up m_dwo_abbrev_table;
1022 };
1023
1024 /* When we construct a partial symbol table entry we only
1025    need this much information.  */
1026 struct partial_die_info : public allocate_on_obstack
1027   {
1028     partial_die_info (sect_offset sect_off, const struct abbrev_info *abbrev);
1029
1030     /* Disable assign but still keep copy ctor, which is needed
1031        load_partial_dies.   */
1032     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1033
1034     /* Adjust the partial die before generating a symbol for it.  This
1035        function may set the is_external flag or change the DIE's
1036        name.  */
1037     void fixup (struct dwarf2_cu *cu);
1038
1039     /* Read a minimal amount of information into the minimal die
1040        structure.  */
1041     const gdb_byte *read (const struct die_reader_specs *reader,
1042                           const struct abbrev_info &abbrev,
1043                           const gdb_byte *info_ptr);
1044
1045     /* Compute the name of this partial DIE.  This memoizes the
1046        result, so it is safe to call multiple times.  */
1047     const char *name (dwarf2_cu *cu);
1048
1049     /* Offset of this DIE.  */
1050     const sect_offset sect_off;
1051
1052     /* DWARF-2 tag for this DIE.  */
1053     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1054
1055     /* Assorted flags describing the data found in this DIE.  */
1056     const unsigned int has_children : 1;
1057
1058     unsigned int is_external : 1;
1059     unsigned int is_declaration : 1;
1060     unsigned int has_type : 1;
1061     unsigned int has_specification : 1;
1062     unsigned int has_pc_info : 1;
1063     unsigned int may_be_inlined : 1;
1064
1065     /* This DIE has been marked DW_AT_main_subprogram.  */
1066     unsigned int main_subprogram : 1;
1067
1068     /* Flag set if the SCOPE field of this structure has been
1069        computed.  */
1070     unsigned int scope_set : 1;
1071
1072     /* Flag set if the DIE has a byte_size attribute.  */
1073     unsigned int has_byte_size : 1;
1074
1075     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1076     unsigned int has_const_value : 1;
1077
1078     /* Flag set if any of the DIE's children are template arguments.  */
1079     unsigned int has_template_arguments : 1;
1080
1081     /* Flag set if fixup has been called on this die.  */
1082     unsigned int fixup_called : 1;
1083
1084     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1085     unsigned int is_dwz : 1;
1086
1087     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1088     unsigned int spec_is_dwz : 1;
1089
1090     unsigned int canonical_name : 1;
1091
1092     /* The name of this DIE.  Normally the value of DW_AT_name, but
1093        sometimes a default name for unnamed DIEs.  */
1094     const char *raw_name = nullptr;
1095
1096     /* The linkage name, if present.  */
1097     const char *linkage_name = nullptr;
1098
1099     /* The scope to prepend to our children.  This is generally
1100        allocated on the comp_unit_obstack, so will disappear
1101        when this compilation unit leaves the cache.  */
1102     const char *scope = nullptr;
1103
1104     /* Some data associated with the partial DIE.  The tag determines
1105        which field is live.  */
1106     union
1107     {
1108       /* The location description associated with this DIE, if any.  */
1109       struct dwarf_block *locdesc;
1110       /* The offset of an import, for DW_TAG_imported_unit.  */
1111       sect_offset sect_off;
1112     } d {};
1113
1114     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1115     CORE_ADDR lowpc = 0;
1116     CORE_ADDR highpc = 0;
1117
1118     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1119        DW_AT_sibling, if any.  */
1120     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1121        could return DW_AT_sibling values to its caller load_partial_dies.  */
1122     const gdb_byte *sibling = nullptr;
1123
1124     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1125        DW_AT_specification (or DW_AT_abstract_origin or
1126        DW_AT_extension).  */
1127     sect_offset spec_offset {};
1128
1129     /* Pointers to this DIE's parent, first child, and next sibling,
1130        if any.  */
1131     struct partial_die_info *die_parent = nullptr;
1132     struct partial_die_info *die_child = nullptr;
1133     struct partial_die_info *die_sibling = nullptr;
1134
1135     friend struct partial_die_info *
1136     dwarf2_cu::find_partial_die (sect_offset sect_off);
1137
1138   private:
1139     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1140     partial_die_info (sect_offset sect_off)
1141       : partial_die_info (sect_off, DW_TAG_padding, 0)
1142     {
1143     }
1144
1145     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1146                       int has_children_)
1147       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1148     {
1149       is_external = 0;
1150       is_declaration = 0;
1151       has_type = 0;
1152       has_specification = 0;
1153       has_pc_info = 0;
1154       may_be_inlined = 0;
1155       main_subprogram = 0;
1156       scope_set = 0;
1157       has_byte_size = 0;
1158       has_const_value = 0;
1159       has_template_arguments = 0;
1160       fixup_called = 0;
1161       is_dwz = 0;
1162       spec_is_dwz = 0;
1163       canonical_name = 0;
1164     }
1165   };
1166
1167 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1168    but this would require a corresponding change in unpack_field_as_long
1169    and friends.  */
1170 static int bits_per_byte = 8;
1171
1172 struct variant_part_builder;
1173
1174 /* When reading a variant, we track a bit more information about the
1175    field, and store it in an object of this type.  */
1176
1177 struct variant_field
1178 {
1179   int first_field = -1;
1180   int last_field = -1;
1181
1182   /* A variant can contain other variant parts.  */
1183   std::vector<variant_part_builder> variant_parts;
1184
1185   /* If we see a DW_TAG_variant, then this will be set if this is the
1186      default branch.  */
1187   bool default_branch = false;
1188   /* If we see a DW_AT_discr_value, then this will be the discriminant
1189      value.  */
1190   ULONGEST discriminant_value = 0;
1191   /* If we see a DW_AT_discr_list, then this is a pointer to the list
1192      data.  */
1193   struct dwarf_block *discr_list_data = nullptr;
1194 };
1195
1196 /* This represents a DW_TAG_variant_part.  */
1197
1198 struct variant_part_builder
1199 {
1200   /* The offset of the discriminant field.  */
1201   sect_offset discriminant_offset {};
1202
1203   /* Variants that are direct children of this variant part.  */
1204   std::vector<variant_field> variants;
1205
1206   /* True if we're currently reading a variant.  */
1207   bool processing_variant = false;
1208 };
1209
1210 struct nextfield
1211 {
1212   int accessibility = 0;
1213   int virtuality = 0;
1214   /* Variant parts need to find the discriminant, which is a DIE
1215      reference.  We track the section offset of each field to make
1216      this link.  */
1217   sect_offset offset;
1218   struct field field {};
1219 };
1220
1221 struct fnfieldlist
1222 {
1223   const char *name = nullptr;
1224   std::vector<struct fn_field> fnfields;
1225 };
1226
1227 /* The routines that read and process dies for a C struct or C++ class
1228    pass lists of data member fields and lists of member function fields
1229    in an instance of a field_info structure, as defined below.  */
1230 struct field_info
1231 {
1232   /* List of data member and baseclasses fields.  */
1233   std::vector<struct nextfield> fields;
1234   std::vector<struct nextfield> baseclasses;
1235
1236   /* Set if the accessibility of one of the fields is not public.  */
1237   bool non_public_fields = false;
1238
1239   /* Member function fieldlist array, contains name of possibly overloaded
1240      member function, number of overloaded member functions and a pointer
1241      to the head of the member function field chain.  */
1242   std::vector<struct fnfieldlist> fnfieldlists;
1243
1244   /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1245      a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1246   std::vector<struct decl_field> typedef_field_list;
1247
1248   /* Nested types defined by this class and the number of elements in this
1249      list.  */
1250   std::vector<struct decl_field> nested_types_list;
1251
1252   /* If non-null, this is the variant part we are currently
1253      reading.  */
1254   variant_part_builder *current_variant_part = nullptr;
1255   /* This holds all the top-level variant parts attached to the type
1256      we're reading.  */
1257   std::vector<variant_part_builder> variant_parts;
1258
1259   /* Return the total number of fields (including baseclasses).  */
1260   int nfields () const
1261   {
1262     return fields.size () + baseclasses.size ();
1263   }
1264 };
1265
1266 /* Loaded secondary compilation units are kept in memory until they
1267    have not been referenced for the processing of this many
1268    compilation units.  Set this to zero to disable caching.  Cache
1269    sizes of up to at least twenty will improve startup time for
1270    typical inter-CU-reference binaries, at an obvious memory cost.  */
1271 static int dwarf_max_cache_age = 5;
1272 static void
1273 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1274                           struct cmd_list_element *c, const char *value)
1275 {
1276   fprintf_filtered (file, _("The upper bound on the age of cached "
1277                             "DWARF compilation units is %s.\n"),
1278                     value);
1279 }
1280 \f
1281 /* local function prototypes */
1282
1283 static void dwarf2_find_base_address (struct die_info *die,
1284                                       struct dwarf2_cu *cu);
1285
1286 static dwarf2_psymtab *create_partial_symtab
1287   (dwarf2_per_cu_data *per_cu, dwarf2_per_objfile *per_objfile,
1288    const char *name);
1289
1290 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1291                                         const gdb_byte *info_ptr,
1292                                         struct die_info *type_unit_die);
1293
1294 static void dwarf2_build_psymtabs_hard (dwarf2_per_objfile *per_objfile);
1295
1296 static void scan_partial_symbols (struct partial_die_info *,
1297                                   CORE_ADDR *, CORE_ADDR *,
1298                                   int, struct dwarf2_cu *);
1299
1300 static void add_partial_symbol (struct partial_die_info *,
1301                                 struct dwarf2_cu *);
1302
1303 static void add_partial_namespace (struct partial_die_info *pdi,
1304                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1305                                    int set_addrmap, struct dwarf2_cu *cu);
1306
1307 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1308                                 CORE_ADDR *highpc, int set_addrmap,
1309                                 struct dwarf2_cu *cu);
1310
1311 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1312                                      struct dwarf2_cu *cu);
1313
1314 static void add_partial_subprogram (struct partial_die_info *pdi,
1315                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1316                                     int need_pc, struct dwarf2_cu *cu);
1317
1318 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1319
1320 static struct partial_die_info *load_partial_dies
1321   (const struct die_reader_specs *, const gdb_byte *, int);
1322
1323 /* A pair of partial_die_info and compilation unit.  */
1324 struct cu_partial_die_info
1325 {
1326   /* The compilation unit of the partial_die_info.  */
1327   struct dwarf2_cu *cu;
1328   /* A partial_die_info.  */
1329   struct partial_die_info *pdi;
1330
1331   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1332     : cu (cu),
1333       pdi (pdi)
1334   { /* Nothing.  */ }
1335
1336 private:
1337   cu_partial_die_info () = delete;
1338 };
1339
1340 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1341                                                           struct dwarf2_cu *);
1342
1343 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1344                                        struct attribute *,
1345                                        const struct attr_abbrev *,
1346                                        const gdb_byte *);
1347
1348 static void read_attribute_reprocess (const struct die_reader_specs *reader,
1349                                       struct attribute *attr, dwarf_tag tag);
1350
1351 static CORE_ADDR read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index);
1352
1353 static sect_offset read_abbrev_offset (dwarf2_per_objfile *per_objfile,
1354                                        dwarf2_section_info *, sect_offset);
1355
1356 static const char *read_indirect_string
1357   (dwarf2_per_objfile *per_objfile, bfd *, const gdb_byte *,
1358    const struct comp_unit_head *, unsigned int *);
1359
1360 static const char *read_indirect_string_at_offset
1361   (dwarf2_per_objfile *per_objfile, LONGEST str_offset);
1362
1363 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1364                                               const gdb_byte *,
1365                                               unsigned int *);
1366
1367 static const char *read_dwo_str_index (const struct die_reader_specs *reader,
1368                                        ULONGEST str_index);
1369
1370 static const char *read_stub_str_index (struct dwarf2_cu *cu,
1371                                         ULONGEST str_index);
1372
1373 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1374
1375 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1376                                       struct dwarf2_cu *);
1377
1378 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1379                                        struct dwarf2_cu *cu);
1380
1381 static const char *dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu);
1382
1383 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1384                                struct dwarf2_cu *cu);
1385
1386 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1387
1388 static struct die_info *die_specification (struct die_info *die,
1389                                            struct dwarf2_cu **);
1390
1391 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1392                                                 struct dwarf2_cu *cu);
1393
1394 static void dwarf_decode_lines (struct line_header *, const char *,
1395                                 struct dwarf2_cu *, dwarf2_psymtab *,
1396                                 CORE_ADDR, int decode_mapping);
1397
1398 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1399                                   const char *);
1400
1401 static struct symbol *new_symbol (struct die_info *, struct type *,
1402                                   struct dwarf2_cu *, struct symbol * = NULL);
1403
1404 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1405                                 struct dwarf2_cu *);
1406
1407 static void dwarf2_const_value_attr (const struct attribute *attr,
1408                                      struct type *type,
1409                                      const char *name,
1410                                      struct obstack *obstack,
1411                                      struct dwarf2_cu *cu, LONGEST *value,
1412                                      const gdb_byte **bytes,
1413                                      struct dwarf2_locexpr_baton **baton);
1414
1415 static struct type *read_subrange_index_type (struct die_info *die,
1416                                               struct dwarf2_cu *cu);
1417
1418 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1419
1420 static int need_gnat_info (struct dwarf2_cu *);
1421
1422 static struct type *die_descriptive_type (struct die_info *,
1423                                           struct dwarf2_cu *);
1424
1425 static void set_descriptive_type (struct type *, struct die_info *,
1426                                   struct dwarf2_cu *);
1427
1428 static struct type *die_containing_type (struct die_info *,
1429                                          struct dwarf2_cu *);
1430
1431 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1432                                      struct dwarf2_cu *);
1433
1434 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1435
1436 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1437
1438 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1439
1440 static char *typename_concat (struct obstack *obs, const char *prefix,
1441                               const char *suffix, int physname,
1442                               struct dwarf2_cu *cu);
1443
1444 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1445
1446 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1447
1448 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1449
1450 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1451
1452 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1453
1454 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1455
1456 /* Return the .debug_loclists section to use for cu.  */
1457 static struct dwarf2_section_info *cu_debug_loc_section (struct dwarf2_cu *cu);
1458
1459 /* Return the .debug_rnglists section to use for cu.  */
1460 static struct dwarf2_section_info *cu_debug_rnglists_section
1461   (struct dwarf2_cu *cu, dwarf_tag tag);
1462
1463 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1464    values.  Keep the items ordered with increasing constraints compliance.  */
1465 enum pc_bounds_kind
1466 {
1467   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1468   PC_BOUNDS_NOT_PRESENT,
1469
1470   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1471      were present but they do not form a valid range of PC addresses.  */
1472   PC_BOUNDS_INVALID,
1473
1474   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1475   PC_BOUNDS_RANGES,
1476
1477   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1478   PC_BOUNDS_HIGH_LOW,
1479 };
1480
1481 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1482                                                  CORE_ADDR *, CORE_ADDR *,
1483                                                  struct dwarf2_cu *,
1484                                                  dwarf2_psymtab *);
1485
1486 static void get_scope_pc_bounds (struct die_info *,
1487                                  CORE_ADDR *, CORE_ADDR *,
1488                                  struct dwarf2_cu *);
1489
1490 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1491                                         CORE_ADDR, struct dwarf2_cu *);
1492
1493 static void dwarf2_add_field (struct field_info *, struct die_info *,
1494                               struct dwarf2_cu *);
1495
1496 static void dwarf2_attach_fields_to_type (struct field_info *,
1497                                           struct type *, struct dwarf2_cu *);
1498
1499 static void dwarf2_add_member_fn (struct field_info *,
1500                                   struct die_info *, struct type *,
1501                                   struct dwarf2_cu *);
1502
1503 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1504                                              struct type *,
1505                                              struct dwarf2_cu *);
1506
1507 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1508
1509 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1510
1511 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1512
1513 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1514
1515 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1516
1517 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1518
1519 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1520
1521 static struct type *read_module_type (struct die_info *die,
1522                                       struct dwarf2_cu *cu);
1523
1524 static const char *namespace_name (struct die_info *die,
1525                                    int *is_anonymous, struct dwarf2_cu *);
1526
1527 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1528
1529 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *,
1530                                  bool * = nullptr);
1531
1532 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1533                                                        struct dwarf2_cu *);
1534
1535 static struct die_info *read_die_and_siblings_1
1536   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1537    struct die_info *);
1538
1539 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1540                                                const gdb_byte *info_ptr,
1541                                                const gdb_byte **new_info_ptr,
1542                                                struct die_info *parent);
1543
1544 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1545                                         struct die_info **, const gdb_byte *,
1546                                         int);
1547
1548 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1549                                       struct die_info **, const gdb_byte *);
1550
1551 static void process_die (struct die_info *, struct dwarf2_cu *);
1552
1553 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1554                                              struct objfile *);
1555
1556 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1557
1558 static const char *dwarf2_full_name (const char *name,
1559                                      struct die_info *die,
1560                                      struct dwarf2_cu *cu);
1561
1562 static const char *dwarf2_physname (const char *name, struct die_info *die,
1563                                     struct dwarf2_cu *cu);
1564
1565 static struct die_info *dwarf2_extension (struct die_info *die,
1566                                           struct dwarf2_cu **);
1567
1568 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1569
1570 static void dump_die_for_error (struct die_info *);
1571
1572 static void dump_die_1 (struct ui_file *, int level, int max_level,
1573                         struct die_info *);
1574
1575 /*static*/ void dump_die (struct die_info *, int max_level);
1576
1577 static void store_in_ref_table (struct die_info *,
1578                                 struct dwarf2_cu *);
1579
1580 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1581                                                const struct attribute *,
1582                                                struct dwarf2_cu **);
1583
1584 static struct die_info *follow_die_ref (struct die_info *,
1585                                         const struct attribute *,
1586                                         struct dwarf2_cu **);
1587
1588 static struct die_info *follow_die_sig (struct die_info *,
1589                                         const struct attribute *,
1590                                         struct dwarf2_cu **);
1591
1592 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1593                                          struct dwarf2_cu *);
1594
1595 static struct type *get_DW_AT_signature_type (struct die_info *,
1596                                               const struct attribute *,
1597                                               struct dwarf2_cu *);
1598
1599 static void load_full_type_unit (dwarf2_per_cu_data *per_cu,
1600                                  dwarf2_per_objfile *per_objfile);
1601
1602 static void read_signatured_type (signatured_type *sig_type,
1603                                   dwarf2_per_objfile *per_objfile);
1604
1605 static int attr_to_dynamic_prop (const struct attribute *attr,
1606                                  struct die_info *die, struct dwarf2_cu *cu,
1607                                  struct dynamic_prop *prop, struct type *type);
1608
1609 /* memory allocation interface */
1610
1611 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1612
1613 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1614
1615 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1616
1617 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1618                                    struct dwarf2_loclist_baton *baton,
1619                                    const struct attribute *attr);
1620
1621 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1622                                          struct symbol *sym,
1623                                          struct dwarf2_cu *cu,
1624                                          int is_block);
1625
1626 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1627                                      const gdb_byte *info_ptr,
1628                                      const struct abbrev_info *abbrev);
1629
1630 static hashval_t partial_die_hash (const void *item);
1631
1632 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1633
1634 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1635   (sect_offset sect_off, unsigned int offset_in_dwz,
1636    dwarf2_per_objfile *per_objfile);
1637
1638 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1639                                    struct die_info *comp_unit_die,
1640                                    enum language pretend_language);
1641
1642 static struct type *set_die_type (struct die_info *, struct type *,
1643                                   struct dwarf2_cu *, bool = false);
1644
1645 static void create_all_comp_units (dwarf2_per_objfile *per_objfile);
1646
1647 static int create_all_type_units (dwarf2_per_objfile *per_objfile);
1648
1649 static void load_full_comp_unit (dwarf2_per_cu_data *per_cu,
1650                                  dwarf2_per_objfile *per_objfile,
1651                                  dwarf2_cu *existing_cu,
1652                                  bool skip_partial,
1653                                  enum language pretend_language);
1654
1655 static void process_full_comp_unit (dwarf2_cu *cu,
1656                                     enum language pretend_language);
1657
1658 static void process_full_type_unit (dwarf2_cu *cu,
1659                                     enum language pretend_language);
1660
1661 static void dwarf2_add_dependence (struct dwarf2_cu *,
1662                                    struct dwarf2_per_cu_data *);
1663
1664 static void dwarf2_mark (struct dwarf2_cu *);
1665
1666 static struct type *get_die_type_at_offset (sect_offset,
1667                                             dwarf2_per_cu_data *per_cu,
1668                                             dwarf2_per_objfile *per_objfile);
1669
1670 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1671
1672 static void queue_comp_unit (dwarf2_per_cu_data *per_cu,
1673                              dwarf2_per_objfile *per_objfile,
1674                              enum language pretend_language);
1675
1676 static void process_queue (dwarf2_per_objfile *per_objfile);
1677
1678 /* Class, the destructor of which frees all allocated queue entries.  This
1679    will only have work to do if an error was thrown while processing the
1680    dwarf.  If no error was thrown then the queue entries should have all
1681    been processed, and freed, as we went along.  */
1682
1683 class dwarf2_queue_guard
1684 {
1685 public:
1686   explicit dwarf2_queue_guard (dwarf2_per_objfile *per_objfile)
1687     : m_per_objfile (per_objfile)
1688   {
1689     gdb_assert (!m_per_objfile->per_bfd->queue.has_value ());
1690
1691     m_per_objfile->per_bfd->queue.emplace ();
1692   }
1693
1694   /* Free any entries remaining on the queue.  There should only be
1695      entries left if we hit an error while processing the dwarf.  */
1696   ~dwarf2_queue_guard ()
1697   {
1698     gdb_assert (m_per_objfile->per_bfd->queue.has_value ());
1699
1700     m_per_objfile->per_bfd->queue.reset ();
1701   }
1702
1703   DISABLE_COPY_AND_ASSIGN (dwarf2_queue_guard);
1704
1705 private:
1706   dwarf2_per_objfile *m_per_objfile;
1707 };
1708
1709 dwarf2_queue_item::~dwarf2_queue_item ()
1710 {
1711   /* Anything still marked queued is likely to be in an
1712      inconsistent state, so discard it.  */
1713   if (per_cu->queued)
1714     {
1715       per_objfile->remove_cu (per_cu);
1716       per_cu->queued = 0;
1717     }
1718 }
1719
1720 /* The return type of find_file_and_directory.  Note, the enclosed
1721    string pointers are only valid while this object is valid.  */
1722
1723 struct file_and_directory
1724 {
1725   /* The filename.  This is never NULL.  */
1726   const char *name;
1727
1728   /* The compilation directory.  NULL if not known.  If we needed to
1729      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1730      points directly to the DW_AT_comp_dir string attribute owned by
1731      the obstack that owns the DIE.  */
1732   const char *comp_dir;
1733
1734   /* If we needed to build a new string for comp_dir, this is what
1735      owns the storage.  */
1736   std::string comp_dir_storage;
1737 };
1738
1739 static file_and_directory find_file_and_directory (struct die_info *die,
1740                                                    struct dwarf2_cu *cu);
1741
1742 static htab_up allocate_signatured_type_table ();
1743
1744 static htab_up allocate_dwo_unit_table ();
1745
1746 static struct dwo_unit *lookup_dwo_unit_in_dwp
1747   (dwarf2_per_objfile *per_objfile, struct dwp_file *dwp_file,
1748    const char *comp_dir, ULONGEST signature, int is_debug_types);
1749
1750 static struct dwp_file *get_dwp_file (dwarf2_per_objfile *per_objfile);
1751
1752 static struct dwo_unit *lookup_dwo_comp_unit
1753   (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
1754    ULONGEST signature);
1755
1756 static struct dwo_unit *lookup_dwo_type_unit
1757   (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir);
1758
1759 static void queue_and_load_all_dwo_tus (dwarf2_cu *cu);
1760
1761 /* A unique pointer to a dwo_file.  */
1762
1763 typedef std::unique_ptr<struct dwo_file> dwo_file_up;
1764
1765 static void process_cu_includes (dwarf2_per_objfile *per_objfile);
1766
1767 static void check_producer (struct dwarf2_cu *cu);
1768
1769 static void free_line_header_voidp (void *arg);
1770 \f
1771 /* Various complaints about symbol reading that don't abort the process.  */
1772
1773 static void
1774 dwarf2_debug_line_missing_file_complaint (void)
1775 {
1776   complaint (_(".debug_line section has line data without a file"));
1777 }
1778
1779 static void
1780 dwarf2_debug_line_missing_end_sequence_complaint (void)
1781 {
1782   complaint (_(".debug_line section has line "
1783                "program sequence without an end"));
1784 }
1785
1786 static void
1787 dwarf2_complex_location_expr_complaint (void)
1788 {
1789   complaint (_("location expression too complex"));
1790 }
1791
1792 static void
1793 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1794                                               int arg3)
1795 {
1796   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
1797              arg1, arg2, arg3);
1798 }
1799
1800 static void
1801 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1802 {
1803   complaint (_("invalid attribute class or form for '%s' in '%s'"),
1804              arg1, arg2);
1805 }
1806
1807 /* Hash function for line_header_hash.  */
1808
1809 static hashval_t
1810 line_header_hash (const struct line_header *ofs)
1811 {
1812   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
1813 }
1814
1815 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
1816
1817 static hashval_t
1818 line_header_hash_voidp (const void *item)
1819 {
1820   const struct line_header *ofs = (const struct line_header *) item;
1821
1822   return line_header_hash (ofs);
1823 }
1824
1825 /* Equality function for line_header_hash.  */
1826
1827 static int
1828 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
1829 {
1830   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
1831   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
1832
1833   return (ofs_lhs->sect_off == ofs_rhs->sect_off
1834           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
1835 }
1836
1837 \f
1838
1839 /* See declaration.  */
1840
1841 dwarf2_per_bfd::dwarf2_per_bfd (bfd *obfd, const dwarf2_debug_sections *names,
1842                                 bool can_copy_)
1843   : obfd (obfd),
1844     can_copy (can_copy_)
1845 {
1846   if (names == NULL)
1847     names = &dwarf2_elf_names;
1848
1849   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
1850     locate_sections (obfd, sec, *names);
1851 }
1852
1853 dwarf2_per_bfd::~dwarf2_per_bfd ()
1854 {
1855   for (dwarf2_per_cu_data *per_cu : all_comp_units)
1856     per_cu->imported_symtabs_free ();
1857
1858   for (signatured_type *sig_type : all_type_units)
1859     sig_type->per_cu.imported_symtabs_free ();
1860
1861   /* Everything else should be on this->obstack.  */
1862 }
1863
1864 /* See read.h.  */
1865
1866 void
1867 dwarf2_per_objfile::remove_all_cus ()
1868 {
1869   gdb_assert (!this->per_bfd->queue.has_value ());
1870
1871   for (auto pair : m_dwarf2_cus)
1872     delete pair.second;
1873
1874   m_dwarf2_cus.clear ();
1875 }
1876
1877 /* A helper class that calls free_cached_comp_units on
1878    destruction.  */
1879
1880 class free_cached_comp_units
1881 {
1882 public:
1883
1884   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
1885     : m_per_objfile (per_objfile)
1886   {
1887   }
1888
1889   ~free_cached_comp_units ()
1890   {
1891     m_per_objfile->remove_all_cus ();
1892   }
1893
1894   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
1895
1896 private:
1897
1898   dwarf2_per_objfile *m_per_objfile;
1899 };
1900
1901 /* See read.h.  */
1902
1903 bool
1904 dwarf2_per_objfile::symtab_set_p (const dwarf2_per_cu_data *per_cu) const
1905 {
1906   gdb_assert (per_cu->index < this->m_symtabs.size ());
1907
1908   return this->m_symtabs[per_cu->index] != nullptr;
1909 }
1910
1911 /* See read.h.  */
1912
1913 compunit_symtab *
1914 dwarf2_per_objfile::get_symtab (const dwarf2_per_cu_data *per_cu) const
1915 {
1916   gdb_assert (per_cu->index < this->m_symtabs.size ());
1917
1918   return this->m_symtabs[per_cu->index];
1919 }
1920
1921 /* See read.h.  */
1922
1923 void
1924 dwarf2_per_objfile::set_symtab (const dwarf2_per_cu_data *per_cu,
1925                                 compunit_symtab *symtab)
1926 {
1927   gdb_assert (per_cu->index < this->m_symtabs.size ());
1928   gdb_assert (this->m_symtabs[per_cu->index] == nullptr);
1929
1930   this->m_symtabs[per_cu->index] = symtab;
1931 }
1932
1933 /* Try to locate the sections we need for DWARF 2 debugging
1934    information and return true if we have enough to do something.
1935    NAMES points to the dwarf2 section names, or is NULL if the standard
1936    ELF names are used.  CAN_COPY is true for formats where symbol
1937    interposition is possible and so symbol values must follow copy
1938    relocation rules.  */
1939
1940 int
1941 dwarf2_has_info (struct objfile *objfile,
1942                  const struct dwarf2_debug_sections *names,
1943                  bool can_copy)
1944 {
1945   if (objfile->flags & OBJF_READNEVER)
1946     return 0;
1947
1948   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
1949
1950   if (per_objfile == NULL)
1951     {
1952       dwarf2_per_bfd *per_bfd;
1953
1954       /* We can share a "dwarf2_per_bfd" with other objfiles if the BFD
1955          doesn't require relocations.  */
1956       if (!gdb_bfd_requires_relocations (objfile->obfd))
1957         {
1958           /* See if one has been created for this BFD yet.  */
1959           per_bfd = dwarf2_per_bfd_bfd_data_key.get (objfile->obfd);
1960
1961           if (per_bfd == nullptr)
1962             {
1963               /* No, create it now.  */
1964               per_bfd = new dwarf2_per_bfd (objfile->obfd, names, can_copy);
1965               dwarf2_per_bfd_bfd_data_key.set (objfile->obfd, per_bfd);
1966             }
1967         }
1968       else
1969         {
1970           /* No sharing possible, create one specifically for this objfile.  */
1971           per_bfd = new dwarf2_per_bfd (objfile->obfd, names, can_copy);
1972           dwarf2_per_bfd_objfile_data_key.set (objfile, per_bfd);
1973         }
1974
1975       per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile, per_bfd);
1976     }
1977
1978   return (!per_objfile->per_bfd->info.is_virtual
1979           && per_objfile->per_bfd->info.s.section != NULL
1980           && !per_objfile->per_bfd->abbrev.is_virtual
1981           && per_objfile->per_bfd->abbrev.s.section != NULL);
1982 }
1983
1984 /* See declaration.  */
1985
1986 void
1987 dwarf2_per_bfd::locate_sections (bfd *abfd, asection *sectp,
1988                                  const dwarf2_debug_sections &names)
1989 {
1990   flagword aflag = bfd_section_flags (sectp);
1991
1992   if ((aflag & SEC_HAS_CONTENTS) == 0)
1993     {
1994     }
1995   else if (elf_section_data (sectp)->this_hdr.sh_size
1996            > bfd_get_file_size (abfd))
1997     {
1998       bfd_size_type size = elf_section_data (sectp)->this_hdr.sh_size;
1999       warning (_("Discarding section %s which has a section size (%s"
2000                  ") larger than the file size [in module %s]"),
2001                bfd_section_name (sectp), phex_nz (size, sizeof (size)),
2002                bfd_get_filename (abfd));
2003     }
2004   else if (names.info.matches (sectp->name))
2005     {
2006       this->info.s.section = sectp;
2007       this->info.size = bfd_section_size (sectp);
2008     }
2009   else if (names.abbrev.matches (sectp->name))
2010     {
2011       this->abbrev.s.section = sectp;
2012       this->abbrev.size = bfd_section_size (sectp);
2013     }
2014   else if (names.line.matches (sectp->name))
2015     {
2016       this->line.s.section = sectp;
2017       this->line.size = bfd_section_size (sectp);
2018     }
2019   else if (names.loc.matches (sectp->name))
2020     {
2021       this->loc.s.section = sectp;
2022       this->loc.size = bfd_section_size (sectp);
2023     }
2024   else if (names.loclists.matches (sectp->name))
2025     {
2026       this->loclists.s.section = sectp;
2027       this->loclists.size = bfd_section_size (sectp);
2028     }
2029   else if (names.macinfo.matches (sectp->name))
2030     {
2031       this->macinfo.s.section = sectp;
2032       this->macinfo.size = bfd_section_size (sectp);
2033     }
2034   else if (names.macro.matches (sectp->name))
2035     {
2036       this->macro.s.section = sectp;
2037       this->macro.size = bfd_section_size (sectp);
2038     }
2039   else if (names.str.matches (sectp->name))
2040     {
2041       this->str.s.section = sectp;
2042       this->str.size = bfd_section_size (sectp);
2043     }
2044   else if (names.str_offsets.matches (sectp->name))
2045     {
2046       this->str_offsets.s.section = sectp;
2047       this->str_offsets.size = bfd_section_size (sectp);
2048     }
2049   else if (names.line_str.matches (sectp->name))
2050     {
2051       this->line_str.s.section = sectp;
2052       this->line_str.size = bfd_section_size (sectp);
2053     }
2054   else if (names.addr.matches (sectp->name))
2055     {
2056       this->addr.s.section = sectp;
2057       this->addr.size = bfd_section_size (sectp);
2058     }
2059   else if (names.frame.matches (sectp->name))
2060     {
2061       this->frame.s.section = sectp;
2062       this->frame.size = bfd_section_size (sectp);
2063     }
2064   else if (names.eh_frame.matches (sectp->name))
2065     {
2066       this->eh_frame.s.section = sectp;
2067       this->eh_frame.size = bfd_section_size (sectp);
2068     }
2069   else if (names.ranges.matches (sectp->name))
2070     {
2071       this->ranges.s.section = sectp;
2072       this->ranges.size = bfd_section_size (sectp);
2073     }
2074   else if (names.rnglists.matches (sectp->name))
2075     {
2076       this->rnglists.s.section = sectp;
2077       this->rnglists.size = bfd_section_size (sectp);
2078     }
2079   else if (names.types.matches (sectp->name))
2080     {
2081       struct dwarf2_section_info type_section;
2082
2083       memset (&type_section, 0, sizeof (type_section));
2084       type_section.s.section = sectp;
2085       type_section.size = bfd_section_size (sectp);
2086
2087       this->types.push_back (type_section);
2088     }
2089   else if (names.gdb_index.matches (sectp->name))
2090     {
2091       this->gdb_index.s.section = sectp;
2092       this->gdb_index.size = bfd_section_size (sectp);
2093     }
2094   else if (names.debug_names.matches (sectp->name))
2095     {
2096       this->debug_names.s.section = sectp;
2097       this->debug_names.size = bfd_section_size (sectp);
2098     }
2099   else if (names.debug_aranges.matches (sectp->name))
2100     {
2101       this->debug_aranges.s.section = sectp;
2102       this->debug_aranges.size = bfd_section_size (sectp);
2103     }
2104
2105   if ((bfd_section_flags (sectp) & (SEC_LOAD | SEC_ALLOC))
2106       && bfd_section_vma (sectp) == 0)
2107     this->has_section_at_zero = true;
2108 }
2109
2110 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2111    SECTION_NAME.  */
2112
2113 void
2114 dwarf2_get_section_info (struct objfile *objfile,
2115                          enum dwarf2_section_enum sect,
2116                          asection **sectp, const gdb_byte **bufp,
2117                          bfd_size_type *sizep)
2118 {
2119   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
2120   struct dwarf2_section_info *info;
2121
2122   /* We may see an objfile without any DWARF, in which case we just
2123      return nothing.  */
2124   if (per_objfile == NULL)
2125     {
2126       *sectp = NULL;
2127       *bufp = NULL;
2128       *sizep = 0;
2129       return;
2130     }
2131   switch (sect)
2132     {
2133     case DWARF2_DEBUG_FRAME:
2134       info = &per_objfile->per_bfd->frame;
2135       break;
2136     case DWARF2_EH_FRAME:
2137       info = &per_objfile->per_bfd->eh_frame;
2138       break;
2139     default:
2140       gdb_assert_not_reached ("unexpected section");
2141     }
2142
2143   info->read (objfile);
2144
2145   *sectp = info->get_bfd_section ();
2146   *bufp = info->buffer;
2147   *sizep = info->size;
2148 }
2149
2150 \f
2151 /* DWARF quick_symbol_functions support.  */
2152
2153 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2154    unique line tables, so we maintain a separate table of all .debug_line
2155    derived entries to support the sharing.
2156    All the quick functions need is the list of file names.  We discard the
2157    line_header when we're done and don't need to record it here.  */
2158 struct quick_file_names
2159 {
2160   /* The data used to construct the hash key.  */
2161   struct stmt_list_hash hash;
2162
2163   /* The number of entries in file_names, real_names.  */
2164   unsigned int num_file_names;
2165
2166   /* The file names from the line table, after being run through
2167      file_full_name.  */
2168   const char **file_names;
2169
2170   /* The file names from the line table after being run through
2171      gdb_realpath.  These are computed lazily.  */
2172   const char **real_names;
2173 };
2174
2175 /* When using the index (and thus not using psymtabs), each CU has an
2176    object of this type.  This is used to hold information needed by
2177    the various "quick" methods.  */
2178 struct dwarf2_per_cu_quick_data
2179 {
2180   /* The file table.  This can be NULL if there was no file table
2181      or it's currently not read in.
2182      NOTE: This points into dwarf2_per_objfile->per_bfd->quick_file_names_table.  */
2183   struct quick_file_names *file_names;
2184
2185   /* A temporary mark bit used when iterating over all CUs in
2186      expand_symtabs_matching.  */
2187   unsigned int mark : 1;
2188
2189   /* True if we've tried to read the file table and found there isn't one.
2190      There will be no point in trying to read it again next time.  */
2191   unsigned int no_file_data : 1;
2192 };
2193
2194 struct dwarf2_base_index_functions : public quick_symbol_functions
2195 {
2196   bool has_symbols (struct objfile *objfile) override;
2197
2198   struct symtab *find_last_source_symtab (struct objfile *objfile) override;
2199
2200   void forget_cached_source_info (struct objfile *objfile) override;
2201
2202   bool map_symtabs_matching_filename
2203     (struct objfile *objfile, const char *name, const char *real_path,
2204      gdb::function_view<bool (symtab *)> callback) override;
2205
2206   enum language lookup_global_symbol_language (struct objfile *objfile,
2207                                                const char *name,
2208                                                domain_enum domain,
2209                                                bool *symbol_found_p) override
2210   {
2211     *symbol_found_p = false;
2212     return language_unknown;
2213   }
2214
2215   void print_stats (struct objfile *objfile, bool print_bcache) override;
2216
2217   void expand_all_symtabs (struct objfile *objfile) override;
2218
2219   void expand_symtabs_with_fullname (struct objfile *objfile,
2220                                      const char *fullname) override;
2221
2222   struct compunit_symtab *find_pc_sect_compunit_symtab
2223     (struct objfile *objfile, struct bound_minimal_symbol msymbol,
2224      CORE_ADDR pc, struct obj_section *section, int warn_if_readin) override;
2225
2226   struct compunit_symtab *find_compunit_symtab_by_address
2227     (struct objfile *objfile, CORE_ADDR address) override
2228   {
2229     return nullptr;
2230   }
2231
2232   void map_symbol_filenames (struct objfile *objfile,
2233                              symbol_filename_ftype *fun, void *data,
2234                              int need_fullname) override;
2235 };
2236
2237 struct dwarf2_gdb_index : public dwarf2_base_index_functions
2238 {
2239   struct compunit_symtab *lookup_symbol (struct objfile *objfile,
2240                                          block_enum block_index,
2241                                          const char *name,
2242                                          domain_enum domain) override;
2243
2244   void dump (struct objfile *objfile) override;
2245
2246   void expand_symtabs_for_function (struct objfile *objfile,
2247                                     const char *func_name) override;
2248
2249   void map_matching_symbols
2250     (struct objfile *,
2251      const lookup_name_info &lookup_name,
2252      domain_enum domain,
2253      int global,
2254      gdb::function_view<symbol_found_callback_ftype> callback,
2255      symbol_compare_ftype *ordered_compare) override;
2256
2257   void expand_symtabs_matching
2258     (struct objfile *objfile,
2259      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
2260      const lookup_name_info *lookup_name,
2261      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
2262      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
2263      enum search_domain kind) override;
2264 };
2265
2266 struct dwarf2_debug_names_index : public dwarf2_base_index_functions
2267 {
2268   struct compunit_symtab *lookup_symbol (struct objfile *objfile,
2269                                          block_enum block_index,
2270                                          const char *name,
2271                                          domain_enum domain) override;
2272
2273   void dump (struct objfile *objfile) override;
2274
2275   void expand_symtabs_for_function (struct objfile *objfile,
2276                                     const char *func_name) override;
2277
2278   void map_matching_symbols
2279     (struct objfile *,
2280      const lookup_name_info &lookup_name,
2281      domain_enum domain,
2282      int global,
2283      gdb::function_view<symbol_found_callback_ftype> callback,
2284      symbol_compare_ftype *ordered_compare) override;
2285
2286   void expand_symtabs_matching
2287     (struct objfile *objfile,
2288      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
2289      const lookup_name_info *lookup_name,
2290      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
2291      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
2292      enum search_domain kind) override;
2293 };
2294
2295 quick_symbol_functions_up
2296 make_dwarf_gdb_index ()
2297 {
2298   return quick_symbol_functions_up (new dwarf2_gdb_index);
2299 }
2300
2301 quick_symbol_functions_up
2302 make_dwarf_debug_names ()
2303 {
2304   return quick_symbol_functions_up (new dwarf2_debug_names_index);
2305 }
2306
2307 /* Utility hash function for a stmt_list_hash.  */
2308
2309 static hashval_t
2310 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2311 {
2312   hashval_t v = 0;
2313
2314   if (stmt_list_hash->dwo_unit != NULL)
2315     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2316   v += to_underlying (stmt_list_hash->line_sect_off);
2317   return v;
2318 }
2319
2320 /* Utility equality function for a stmt_list_hash.  */
2321
2322 static int
2323 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2324                     const struct stmt_list_hash *rhs)
2325 {
2326   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2327     return 0;
2328   if (lhs->dwo_unit != NULL
2329       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2330     return 0;
2331
2332   return lhs->line_sect_off == rhs->line_sect_off;
2333 }
2334
2335 /* Hash function for a quick_file_names.  */
2336
2337 static hashval_t
2338 hash_file_name_entry (const void *e)
2339 {
2340   const struct quick_file_names *file_data
2341     = (const struct quick_file_names *) e;
2342
2343   return hash_stmt_list_entry (&file_data->hash);
2344 }
2345
2346 /* Equality function for a quick_file_names.  */
2347
2348 static int
2349 eq_file_name_entry (const void *a, const void *b)
2350 {
2351   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2352   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2353
2354   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2355 }
2356
2357 /* Delete function for a quick_file_names.  */
2358
2359 static void
2360 delete_file_name_entry (void *e)
2361 {
2362   struct quick_file_names *file_data = (struct quick_file_names *) e;
2363   int i;
2364
2365   for (i = 0; i < file_data->num_file_names; ++i)
2366     {
2367       xfree ((void*) file_data->file_names[i]);
2368       if (file_data->real_names)
2369         xfree ((void*) file_data->real_names[i]);
2370     }
2371
2372   /* The space for the struct itself lives on the obstack, so we don't
2373      free it here.  */
2374 }
2375
2376 /* Create a quick_file_names hash table.  */
2377
2378 static htab_up
2379 create_quick_file_names_table (unsigned int nr_initial_entries)
2380 {
2381   return htab_up (htab_create_alloc (nr_initial_entries,
2382                                      hash_file_name_entry, eq_file_name_entry,
2383                                      delete_file_name_entry, xcalloc, xfree));
2384 }
2385
2386 /* Read in CU (dwarf2_cu object) for PER_CU in the context of PER_OBJFILE.  This
2387    function is unrelated to symtabs, symtab would have to be created afterwards.
2388    You should call age_cached_comp_units after processing the CU.  */
2389
2390 static dwarf2_cu *
2391 load_cu (dwarf2_per_cu_data *per_cu, dwarf2_per_objfile *per_objfile,
2392          bool skip_partial)
2393 {
2394   if (per_cu->is_debug_types)
2395     load_full_type_unit (per_cu, per_objfile);
2396   else
2397     load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
2398                          skip_partial, language_minimal);
2399
2400   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
2401   if (cu == nullptr)
2402     return nullptr;  /* Dummy CU.  */
2403
2404   dwarf2_find_base_address (cu->dies, cu);
2405
2406   return cu;
2407 }
2408
2409 /* Read in the symbols for PER_CU in the context of PER_OBJFILE.  */
2410
2411 static void
2412 dw2_do_instantiate_symtab (dwarf2_per_cu_data *per_cu,
2413                            dwarf2_per_objfile *per_objfile, bool skip_partial)
2414 {
2415   /* Skip type_unit_groups, reading the type units they contain
2416      is handled elsewhere.  */
2417   if (per_cu->type_unit_group_p ())
2418     return;
2419
2420   {
2421     /* The destructor of dwarf2_queue_guard frees any entries left on
2422        the queue.  After this point we're guaranteed to leave this function
2423        with the dwarf queue empty.  */
2424     dwarf2_queue_guard q_guard (per_objfile);
2425
2426     if (!per_objfile->symtab_set_p (per_cu))
2427       {
2428         queue_comp_unit (per_cu, per_objfile, language_minimal);
2429         dwarf2_cu *cu = load_cu (per_cu, per_objfile, skip_partial);
2430
2431         /* If we just loaded a CU from a DWO, and we're working with an index
2432            that may badly handle TUs, load all the TUs in that DWO as well.
2433            http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2434         if (!per_cu->is_debug_types
2435             && cu != NULL
2436             && cu->dwo_unit != NULL
2437             && per_objfile->per_bfd->index_table != NULL
2438             && per_objfile->per_bfd->index_table->version <= 7
2439             /* DWP files aren't supported yet.  */
2440             && get_dwp_file (per_objfile) == NULL)
2441           queue_and_load_all_dwo_tus (cu);
2442       }
2443
2444     process_queue (per_objfile);
2445   }
2446
2447   /* Age the cache, releasing compilation units that have not
2448      been used recently.  */
2449   per_objfile->age_comp_units ();
2450 }
2451
2452 /* Ensure that the symbols for PER_CU have been read in.  DWARF2_PER_OBJFILE is
2453    the per-objfile for which this symtab is instantiated.
2454
2455    Returns the resulting symbol table.  */
2456
2457 static struct compunit_symtab *
2458 dw2_instantiate_symtab (dwarf2_per_cu_data *per_cu,
2459                         dwarf2_per_objfile *per_objfile,
2460                         bool skip_partial)
2461 {
2462   gdb_assert (per_objfile->per_bfd->using_index);
2463
2464   if (!per_objfile->symtab_set_p (per_cu))
2465     {
2466       free_cached_comp_units freer (per_objfile);
2467       scoped_restore decrementer = increment_reading_symtab ();
2468       dw2_do_instantiate_symtab (per_cu, per_objfile, skip_partial);
2469       process_cu_includes (per_objfile);
2470     }
2471
2472   return per_objfile->get_symtab (per_cu);
2473 }
2474
2475 /* See declaration.  */
2476
2477 dwarf2_per_cu_data *
2478 dwarf2_per_bfd::get_cutu (int index)
2479 {
2480   if (index >= this->all_comp_units.size ())
2481     {
2482       index -= this->all_comp_units.size ();
2483       gdb_assert (index < this->all_type_units.size ());
2484       return &this->all_type_units[index]->per_cu;
2485     }
2486
2487   return this->all_comp_units[index];
2488 }
2489
2490 /* See declaration.  */
2491
2492 dwarf2_per_cu_data *
2493 dwarf2_per_bfd::get_cu (int index)
2494 {
2495   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2496
2497   return this->all_comp_units[index];
2498 }
2499
2500 /* See declaration.  */
2501
2502 signatured_type *
2503 dwarf2_per_bfd::get_tu (int index)
2504 {
2505   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2506
2507   return this->all_type_units[index];
2508 }
2509
2510 /* See read.h.  */
2511
2512 dwarf2_per_cu_data *
2513 dwarf2_per_bfd::allocate_per_cu ()
2514 {
2515   dwarf2_per_cu_data *result = OBSTACK_ZALLOC (&obstack, dwarf2_per_cu_data);
2516   result->per_bfd = this;
2517   result->index = m_num_psymtabs++;
2518   return result;
2519 }
2520
2521 /* See read.h.  */
2522
2523 signatured_type *
2524 dwarf2_per_bfd::allocate_signatured_type ()
2525 {
2526   signatured_type *result = OBSTACK_ZALLOC (&obstack, signatured_type);
2527   result->per_cu.per_bfd = this;
2528   result->per_cu.index = m_num_psymtabs++;
2529   return result;
2530 }
2531
2532 /* Return a new dwarf2_per_cu_data allocated on the per-bfd
2533    obstack, and constructed with the specified field values.  */
2534
2535 static dwarf2_per_cu_data *
2536 create_cu_from_index_list (dwarf2_per_bfd *per_bfd,
2537                            struct dwarf2_section_info *section,
2538                            int is_dwz,
2539                            sect_offset sect_off, ULONGEST length)
2540 {
2541   dwarf2_per_cu_data *the_cu = per_bfd->allocate_per_cu ();
2542   the_cu->sect_off = sect_off;
2543   the_cu->length = length;
2544   the_cu->section = section;
2545   the_cu->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
2546                                     struct dwarf2_per_cu_quick_data);
2547   the_cu->is_dwz = is_dwz;
2548   return the_cu;
2549 }
2550
2551 /* A helper for create_cus_from_index that handles a given list of
2552    CUs.  */
2553
2554 static void
2555 create_cus_from_index_list (dwarf2_per_bfd *per_bfd,
2556                             const gdb_byte *cu_list, offset_type n_elements,
2557                             struct dwarf2_section_info *section,
2558                             int is_dwz)
2559 {
2560   for (offset_type i = 0; i < n_elements; i += 2)
2561     {
2562       gdb_static_assert (sizeof (ULONGEST) >= 8);
2563
2564       sect_offset sect_off
2565         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2566       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2567       cu_list += 2 * 8;
2568
2569       dwarf2_per_cu_data *per_cu
2570         = create_cu_from_index_list (per_bfd, section, is_dwz, sect_off,
2571                                      length);
2572       per_bfd->all_comp_units.push_back (per_cu);
2573     }
2574 }
2575
2576 /* Read the CU list from the mapped index, and use it to create all
2577    the CU objects for PER_BFD.  */
2578
2579 static void
2580 create_cus_from_index (dwarf2_per_bfd *per_bfd,
2581                        const gdb_byte *cu_list, offset_type cu_list_elements,
2582                        const gdb_byte *dwz_list, offset_type dwz_elements)
2583 {
2584   gdb_assert (per_bfd->all_comp_units.empty ());
2585   per_bfd->all_comp_units.reserve ((cu_list_elements + dwz_elements) / 2);
2586
2587   create_cus_from_index_list (per_bfd, cu_list, cu_list_elements,
2588                               &per_bfd->info, 0);
2589
2590   if (dwz_elements == 0)
2591     return;
2592
2593   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
2594   create_cus_from_index_list (per_bfd, dwz_list, dwz_elements,
2595                               &dwz->info, 1);
2596 }
2597
2598 /* Create the signatured type hash table from the index.  */
2599
2600 static void
2601 create_signatured_type_table_from_index
2602   (dwarf2_per_bfd *per_bfd, struct dwarf2_section_info *section,
2603    const gdb_byte *bytes, offset_type elements)
2604 {
2605   gdb_assert (per_bfd->all_type_units.empty ());
2606   per_bfd->all_type_units.reserve (elements / 3);
2607
2608   htab_up sig_types_hash = allocate_signatured_type_table ();
2609
2610   for (offset_type i = 0; i < elements; i += 3)
2611     {
2612       struct signatured_type *sig_type;
2613       ULONGEST signature;
2614       void **slot;
2615       cu_offset type_offset_in_tu;
2616
2617       gdb_static_assert (sizeof (ULONGEST) >= 8);
2618       sect_offset sect_off
2619         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2620       type_offset_in_tu
2621         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
2622                                                 BFD_ENDIAN_LITTLE);
2623       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2624       bytes += 3 * 8;
2625
2626       sig_type = per_bfd->allocate_signatured_type ();
2627       sig_type->signature = signature;
2628       sig_type->type_offset_in_tu = type_offset_in_tu;
2629       sig_type->per_cu.is_debug_types = 1;
2630       sig_type->per_cu.section = section;
2631       sig_type->per_cu.sect_off = sect_off;
2632       sig_type->per_cu.v.quick
2633         = OBSTACK_ZALLOC (&per_bfd->obstack,
2634                           struct dwarf2_per_cu_quick_data);
2635
2636       slot = htab_find_slot (sig_types_hash.get (), sig_type, INSERT);
2637       *slot = sig_type;
2638
2639       per_bfd->all_type_units.push_back (sig_type);
2640     }
2641
2642   per_bfd->signatured_types = std::move (sig_types_hash);
2643 }
2644
2645 /* Create the signatured type hash table from .debug_names.  */
2646
2647 static void
2648 create_signatured_type_table_from_debug_names
2649   (dwarf2_per_objfile *per_objfile,
2650    const mapped_debug_names &map,
2651    struct dwarf2_section_info *section,
2652    struct dwarf2_section_info *abbrev_section)
2653 {
2654   struct objfile *objfile = per_objfile->objfile;
2655
2656   section->read (objfile);
2657   abbrev_section->read (objfile);
2658
2659   gdb_assert (per_objfile->per_bfd->all_type_units.empty ());
2660   per_objfile->per_bfd->all_type_units.reserve (map.tu_count);
2661
2662   htab_up sig_types_hash = allocate_signatured_type_table ();
2663
2664   for (uint32_t i = 0; i < map.tu_count; ++i)
2665     {
2666       struct signatured_type *sig_type;
2667       void **slot;
2668
2669       sect_offset sect_off
2670         = (sect_offset) (extract_unsigned_integer
2671                          (map.tu_table_reordered + i * map.offset_size,
2672                           map.offset_size,
2673                           map.dwarf5_byte_order));
2674
2675       comp_unit_head cu_header;
2676       read_and_check_comp_unit_head (per_objfile, &cu_header, section,
2677                                      abbrev_section,
2678                                      section->buffer + to_underlying (sect_off),
2679                                      rcuh_kind::TYPE);
2680
2681       sig_type = per_objfile->per_bfd->allocate_signatured_type ();
2682       sig_type->signature = cu_header.signature;
2683       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
2684       sig_type->per_cu.is_debug_types = 1;
2685       sig_type->per_cu.section = section;
2686       sig_type->per_cu.sect_off = sect_off;
2687       sig_type->per_cu.v.quick
2688         = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack,
2689                           struct dwarf2_per_cu_quick_data);
2690
2691       slot = htab_find_slot (sig_types_hash.get (), sig_type, INSERT);
2692       *slot = sig_type;
2693
2694       per_objfile->per_bfd->all_type_units.push_back (sig_type);
2695     }
2696
2697   per_objfile->per_bfd->signatured_types = std::move (sig_types_hash);
2698 }
2699
2700 /* Read the address map data from the mapped index, and use it to
2701    populate the psymtabs_addrmap.  */
2702
2703 static void
2704 create_addrmap_from_index (dwarf2_per_objfile *per_objfile,
2705                            struct mapped_index *index)
2706 {
2707   struct objfile *objfile = per_objfile->objfile;
2708   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
2709   struct gdbarch *gdbarch = objfile->arch ();
2710   const gdb_byte *iter, *end;
2711   struct addrmap *mutable_map;
2712   CORE_ADDR baseaddr;
2713
2714   auto_obstack temp_obstack;
2715
2716   mutable_map = addrmap_create_mutable (&temp_obstack);
2717
2718   iter = index->address_table.data ();
2719   end = iter + index->address_table.size ();
2720
2721   baseaddr = objfile->text_section_offset ();
2722
2723   while (iter < end)
2724     {
2725       ULONGEST hi, lo, cu_index;
2726       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2727       iter += 8;
2728       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2729       iter += 8;
2730       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2731       iter += 4;
2732
2733       if (lo > hi)
2734         {
2735           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
2736                      hex_string (lo), hex_string (hi));
2737           continue;
2738         }
2739
2740       if (cu_index >= per_bfd->all_comp_units.size ())
2741         {
2742           complaint (_(".gdb_index address table has invalid CU number %u"),
2743                      (unsigned) cu_index);
2744           continue;
2745         }
2746
2747       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
2748       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
2749       addrmap_set_empty (mutable_map, lo, hi - 1,
2750                          per_bfd->get_cu (cu_index));
2751     }
2752
2753   per_bfd->index_addrmap = addrmap_create_fixed (mutable_map,
2754                                                  &per_bfd->obstack);
2755 }
2756
2757 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
2758    populate the psymtabs_addrmap.  */
2759
2760 static void
2761 create_addrmap_from_aranges (dwarf2_per_objfile *per_objfile,
2762                              struct dwarf2_section_info *section)
2763 {
2764   struct objfile *objfile = per_objfile->objfile;
2765   bfd *abfd = objfile->obfd;
2766   struct gdbarch *gdbarch = objfile->arch ();
2767   const CORE_ADDR baseaddr = objfile->text_section_offset ();
2768   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
2769
2770   auto_obstack temp_obstack;
2771   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
2772
2773   std::unordered_map<sect_offset,
2774                      dwarf2_per_cu_data *,
2775                      gdb::hash_enum<sect_offset>>
2776     debug_info_offset_to_per_cu;
2777   for (dwarf2_per_cu_data *per_cu : per_bfd->all_comp_units)
2778     {
2779       const auto insertpair
2780         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
2781       if (!insertpair.second)
2782         {
2783           warning (_("Section .debug_aranges in %s has duplicate "
2784                      "debug_info_offset %s, ignoring .debug_aranges."),
2785                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
2786           return;
2787         }
2788     }
2789
2790   section->read (objfile);
2791
2792   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
2793
2794   const gdb_byte *addr = section->buffer;
2795
2796   while (addr < section->buffer + section->size)
2797     {
2798       const gdb_byte *const entry_addr = addr;
2799       unsigned int bytes_read;
2800
2801       const LONGEST entry_length = read_initial_length (abfd, addr,
2802                                                         &bytes_read);
2803       addr += bytes_read;
2804
2805       const gdb_byte *const entry_end = addr + entry_length;
2806       const bool dwarf5_is_dwarf64 = bytes_read != 4;
2807       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
2808       if (addr + entry_length > section->buffer + section->size)
2809         {
2810           warning (_("Section .debug_aranges in %s entry at offset %s "
2811                      "length %s exceeds section length %s, "
2812                      "ignoring .debug_aranges."),
2813                    objfile_name (objfile),
2814                    plongest (entry_addr - section->buffer),
2815                    plongest (bytes_read + entry_length),
2816                    pulongest (section->size));
2817           return;
2818         }
2819
2820       /* The version number.  */
2821       const uint16_t version = read_2_bytes (abfd, addr);
2822       addr += 2;
2823       if (version != 2)
2824         {
2825           warning (_("Section .debug_aranges in %s entry at offset %s "
2826                      "has unsupported version %d, ignoring .debug_aranges."),
2827                    objfile_name (objfile),
2828                    plongest (entry_addr - section->buffer), version);
2829           return;
2830         }
2831
2832       const uint64_t debug_info_offset
2833         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
2834       addr += offset_size;
2835       const auto per_cu_it
2836         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
2837       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
2838         {
2839           warning (_("Section .debug_aranges in %s entry at offset %s "
2840                      "debug_info_offset %s does not exists, "
2841                      "ignoring .debug_aranges."),
2842                    objfile_name (objfile),
2843                    plongest (entry_addr - section->buffer),
2844                    pulongest (debug_info_offset));
2845           return;
2846         }
2847       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
2848
2849       const uint8_t address_size = *addr++;
2850       if (address_size < 1 || address_size > 8)
2851         {
2852           warning (_("Section .debug_aranges in %s entry at offset %s "
2853                      "address_size %u is invalid, ignoring .debug_aranges."),
2854                    objfile_name (objfile),
2855                    plongest (entry_addr - section->buffer), address_size);
2856           return;
2857         }
2858
2859       const uint8_t segment_selector_size = *addr++;
2860       if (segment_selector_size != 0)
2861         {
2862           warning (_("Section .debug_aranges in %s entry at offset %s "
2863                      "segment_selector_size %u is not supported, "
2864                      "ignoring .debug_aranges."),
2865                    objfile_name (objfile),
2866                    plongest (entry_addr - section->buffer),
2867                    segment_selector_size);
2868           return;
2869         }
2870
2871       /* Must pad to an alignment boundary that is twice the address
2872          size.  It is undocumented by the DWARF standard but GCC does
2873          use it.  */
2874       for (size_t padding = ((-(addr - section->buffer))
2875                              & (2 * address_size - 1));
2876            padding > 0; padding--)
2877         if (*addr++ != 0)
2878           {
2879             warning (_("Section .debug_aranges in %s entry at offset %s "
2880                        "padding is not zero, ignoring .debug_aranges."),
2881                      objfile_name (objfile),
2882                      plongest (entry_addr - section->buffer));
2883             return;
2884           }
2885
2886       for (;;)
2887         {
2888           if (addr + 2 * address_size > entry_end)
2889             {
2890               warning (_("Section .debug_aranges in %s entry at offset %s "
2891                          "address list is not properly terminated, "
2892                          "ignoring .debug_aranges."),
2893                        objfile_name (objfile),
2894                        plongest (entry_addr - section->buffer));
2895               return;
2896             }
2897           ULONGEST start = extract_unsigned_integer (addr, address_size,
2898                                                      dwarf5_byte_order);
2899           addr += address_size;
2900           ULONGEST length = extract_unsigned_integer (addr, address_size,
2901                                                       dwarf5_byte_order);
2902           addr += address_size;
2903           if (start == 0 && length == 0)
2904             break;
2905           if (start == 0 && !per_bfd->has_section_at_zero)
2906             {
2907               /* Symbol was eliminated due to a COMDAT group.  */
2908               continue;
2909             }
2910           ULONGEST end = start + length;
2911           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
2912                    - baseaddr);
2913           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
2914                  - baseaddr);
2915           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
2916         }
2917     }
2918
2919   per_bfd->index_addrmap = addrmap_create_fixed (mutable_map,
2920                                                  &per_bfd->obstack);
2921 }
2922
2923 /* Find a slot in the mapped index INDEX for the object named NAME.
2924    If NAME is found, set *VEC_OUT to point to the CU vector in the
2925    constant pool and return true.  If NAME cannot be found, return
2926    false.  */
2927
2928 static bool
2929 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2930                           offset_type **vec_out)
2931 {
2932   offset_type hash;
2933   offset_type slot, step;
2934   int (*cmp) (const char *, const char *);
2935
2936   gdb::unique_xmalloc_ptr<char> without_params;
2937   if (current_language->la_language == language_cplus
2938       || current_language->la_language == language_fortran
2939       || current_language->la_language == language_d)
2940     {
2941       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2942          not contain any.  */
2943
2944       if (strchr (name, '(') != NULL)
2945         {
2946           without_params = cp_remove_params (name);
2947
2948           if (without_params != NULL)
2949             name = without_params.get ();
2950         }
2951     }
2952
2953   /* Index version 4 did not support case insensitive searches.  But the
2954      indices for case insensitive languages are built in lowercase, therefore
2955      simulate our NAME being searched is also lowercased.  */
2956   hash = mapped_index_string_hash ((index->version == 4
2957                                     && case_sensitivity == case_sensitive_off
2958                                     ? 5 : index->version),
2959                                    name);
2960
2961   slot = hash & (index->symbol_table.size () - 1);
2962   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
2963   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2964
2965   for (;;)
2966     {
2967       const char *str;
2968
2969       const auto &bucket = index->symbol_table[slot];
2970       if (bucket.name == 0 && bucket.vec == 0)
2971         return false;
2972
2973       str = index->constant_pool + MAYBE_SWAP (bucket.name);
2974       if (!cmp (name, str))
2975         {
2976           *vec_out = (offset_type *) (index->constant_pool
2977                                       + MAYBE_SWAP (bucket.vec));
2978           return true;
2979         }
2980
2981       slot = (slot + step) & (index->symbol_table.size () - 1);
2982     }
2983 }
2984
2985 /* A helper function that reads the .gdb_index from BUFFER and fills
2986    in MAP.  FILENAME is the name of the file containing the data;
2987    it is used for error reporting.  DEPRECATED_OK is true if it is
2988    ok to use deprecated sections.
2989
2990    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2991    out parameters that are filled in with information about the CU and
2992    TU lists in the section.
2993
2994    Returns true if all went well, false otherwise.  */
2995
2996 static bool
2997 read_gdb_index_from_buffer (const char *filename,
2998                             bool deprecated_ok,
2999                             gdb::array_view<const gdb_byte> buffer,
3000                             struct mapped_index *map,
3001                             const gdb_byte **cu_list,
3002                             offset_type *cu_list_elements,
3003                             const gdb_byte **types_list,
3004                             offset_type *types_list_elements)
3005 {
3006   const gdb_byte *addr = &buffer[0];
3007
3008   /* Version check.  */
3009   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3010   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3011      causes the index to behave very poorly for certain requests.  Version 3
3012      contained incomplete addrmap.  So, it seems better to just ignore such
3013      indices.  */
3014   if (version < 4)
3015     {
3016       static int warning_printed = 0;
3017       if (!warning_printed)
3018         {
3019           warning (_("Skipping obsolete .gdb_index section in %s."),
3020                    filename);
3021           warning_printed = 1;
3022         }
3023       return 0;
3024     }
3025   /* Index version 4 uses a different hash function than index version
3026      5 and later.
3027
3028      Versions earlier than 6 did not emit psymbols for inlined
3029      functions.  Using these files will cause GDB not to be able to
3030      set breakpoints on inlined functions by name, so we ignore these
3031      indices unless the user has done
3032      "set use-deprecated-index-sections on".  */
3033   if (version < 6 && !deprecated_ok)
3034     {
3035       static int warning_printed = 0;
3036       if (!warning_printed)
3037         {
3038           warning (_("\
3039 Skipping deprecated .gdb_index section in %s.\n\
3040 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3041 to use the section anyway."),
3042                    filename);
3043           warning_printed = 1;
3044         }
3045       return 0;
3046     }
3047   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3048      of the TU (for symbols coming from TUs),
3049      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3050      Plus gold-generated indices can have duplicate entries for global symbols,
3051      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3052      These are just performance bugs, and we can't distinguish gdb-generated
3053      indices from gold-generated ones, so issue no warning here.  */
3054
3055   /* Indexes with higher version than the one supported by GDB may be no
3056      longer backward compatible.  */
3057   if (version > 8)
3058     return 0;
3059
3060   map->version = version;
3061
3062   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3063
3064   int i = 0;
3065   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3066   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3067                        / 8);
3068   ++i;
3069
3070   *types_list = addr + MAYBE_SWAP (metadata[i]);
3071   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3072                            - MAYBE_SWAP (metadata[i]))
3073                           / 8);
3074   ++i;
3075
3076   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3077   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3078   map->address_table
3079     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3080   ++i;
3081
3082   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3083   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3084   map->symbol_table
3085     = gdb::array_view<mapped_index::symbol_table_slot>
3086        ((mapped_index::symbol_table_slot *) symbol_table,
3087         (mapped_index::symbol_table_slot *) symbol_table_end);
3088
3089   ++i;
3090   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3091
3092   return 1;
3093 }
3094
3095 /* Callback types for dwarf2_read_gdb_index.  */
3096
3097 typedef gdb::function_view
3098     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_bfd *)>
3099     get_gdb_index_contents_ftype;
3100 typedef gdb::function_view
3101     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3102     get_gdb_index_contents_dwz_ftype;
3103
3104 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3105    elements of all the CUs and return 1.  Otherwise, return 0.  */
3106
3107 static int
3108 dwarf2_read_gdb_index
3109   (dwarf2_per_objfile *per_objfile,
3110    get_gdb_index_contents_ftype get_gdb_index_contents,
3111    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3112 {
3113   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3114   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3115   struct dwz_file *dwz;
3116   struct objfile *objfile = per_objfile->objfile;
3117   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
3118
3119   gdb::array_view<const gdb_byte> main_index_contents
3120     = get_gdb_index_contents (objfile, per_bfd);
3121
3122   if (main_index_contents.empty ())
3123     return 0;
3124
3125   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3126   if (!read_gdb_index_from_buffer (objfile_name (objfile),
3127                                    use_deprecated_index_sections,
3128                                    main_index_contents, map.get (), &cu_list,
3129                                    &cu_list_elements, &types_list,
3130                                    &types_list_elements))
3131     return 0;
3132
3133   /* Don't use the index if it's empty.  */
3134   if (map->symbol_table.empty ())
3135     return 0;
3136
3137   /* If there is a .dwz file, read it so we can get its CU list as
3138      well.  */
3139   dwz = dwarf2_get_dwz_file (per_bfd);
3140   if (dwz != NULL)
3141     {
3142       struct mapped_index dwz_map;
3143       const gdb_byte *dwz_types_ignore;
3144       offset_type dwz_types_elements_ignore;
3145
3146       gdb::array_view<const gdb_byte> dwz_index_content
3147         = get_gdb_index_contents_dwz (objfile, dwz);
3148
3149       if (dwz_index_content.empty ())
3150         return 0;
3151
3152       if (!read_gdb_index_from_buffer (bfd_get_filename (dwz->dwz_bfd.get ()),
3153                                        1, dwz_index_content, &dwz_map,
3154                                        &dwz_list, &dwz_list_elements,
3155                                        &dwz_types_ignore,
3156                                        &dwz_types_elements_ignore))
3157         {
3158           warning (_("could not read '.gdb_index' section from %s; skipping"),
3159                    bfd_get_filename (dwz->dwz_bfd.get ()));
3160           return 0;
3161         }
3162     }
3163
3164   create_cus_from_index (per_bfd, cu_list, cu_list_elements, dwz_list,
3165                          dwz_list_elements);
3166
3167   if (types_list_elements)
3168     {
3169       /* We can only handle a single .debug_types when we have an
3170          index.  */
3171       if (per_bfd->types.size () != 1)
3172         return 0;
3173
3174       dwarf2_section_info *section = &per_bfd->types[0];
3175
3176       create_signatured_type_table_from_index (per_bfd, section, types_list,
3177                                                types_list_elements);
3178     }
3179
3180   create_addrmap_from_index (per_objfile, map.get ());
3181
3182   per_bfd->index_table = std::move (map);
3183   per_bfd->using_index = 1;
3184   per_bfd->quick_file_names_table =
3185     create_quick_file_names_table (per_bfd->all_comp_units.size ());
3186
3187   return 1;
3188 }
3189
3190 /* die_reader_func for dw2_get_file_names.  */
3191
3192 static void
3193 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3194                            struct die_info *comp_unit_die)
3195 {
3196   struct dwarf2_cu *cu = reader->cu;
3197   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3198   dwarf2_per_objfile *per_objfile = cu->per_objfile;
3199   struct dwarf2_per_cu_data *lh_cu;
3200   struct attribute *attr;
3201   void **slot;
3202   struct quick_file_names *qfn;
3203
3204   gdb_assert (! this_cu->is_debug_types);
3205
3206   /* Our callers never want to match partial units -- instead they
3207      will match the enclosing full CU.  */
3208   if (comp_unit_die->tag == DW_TAG_partial_unit)
3209     {
3210       this_cu->v.quick->no_file_data = 1;
3211       return;
3212     }
3213
3214   lh_cu = this_cu;
3215   slot = NULL;
3216
3217   line_header_up lh;
3218   sect_offset line_offset {};
3219
3220   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3221   if (attr != nullptr && attr->form_is_unsigned ())
3222     {
3223       struct quick_file_names find_entry;
3224
3225       line_offset = (sect_offset) attr->as_unsigned ();
3226
3227       /* We may have already read in this line header (TU line header sharing).
3228          If we have we're done.  */
3229       find_entry.hash.dwo_unit = cu->dwo_unit;
3230       find_entry.hash.line_sect_off = line_offset;
3231       slot = htab_find_slot (per_objfile->per_bfd->quick_file_names_table.get (),
3232                              &find_entry, INSERT);
3233       if (*slot != NULL)
3234         {
3235           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3236           return;
3237         }
3238
3239       lh = dwarf_decode_line_header (line_offset, cu);
3240     }
3241   if (lh == NULL)
3242     {
3243       lh_cu->v.quick->no_file_data = 1;
3244       return;
3245     }
3246
3247   qfn = XOBNEW (&per_objfile->per_bfd->obstack, struct quick_file_names);
3248   qfn->hash.dwo_unit = cu->dwo_unit;
3249   qfn->hash.line_sect_off = line_offset;
3250   gdb_assert (slot != NULL);
3251   *slot = qfn;
3252
3253   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3254
3255   int offset = 0;
3256   if (strcmp (fnd.name, "<unknown>") != 0)
3257     ++offset;
3258
3259   qfn->num_file_names = offset + lh->file_names_size ();
3260   qfn->file_names =
3261     XOBNEWVEC (&per_objfile->per_bfd->obstack, const char *,
3262                qfn->num_file_names);
3263   if (offset != 0)
3264     qfn->file_names[0] = xstrdup (fnd.name);
3265   for (int i = 0; i < lh->file_names_size (); ++i)
3266     qfn->file_names[i + offset] = lh->file_full_name (i + 1,
3267                                                       fnd.comp_dir).release ();
3268   qfn->real_names = NULL;
3269
3270   lh_cu->v.quick->file_names = qfn;
3271 }
3272
3273 /* A helper for the "quick" functions which attempts to read the line
3274    table for THIS_CU.  */
3275
3276 static struct quick_file_names *
3277 dw2_get_file_names (dwarf2_per_cu_data *this_cu,
3278                     dwarf2_per_objfile *per_objfile)
3279 {
3280   /* This should never be called for TUs.  */
3281   gdb_assert (! this_cu->is_debug_types);
3282   /* Nor type unit groups.  */
3283   gdb_assert (! this_cu->type_unit_group_p ());
3284
3285   if (this_cu->v.quick->file_names != NULL)
3286     return this_cu->v.quick->file_names;
3287   /* If we know there is no line data, no point in looking again.  */
3288   if (this_cu->v.quick->no_file_data)
3289     return NULL;
3290
3291   cutu_reader reader (this_cu, per_objfile);
3292   if (!reader.dummy_p)
3293     dw2_get_file_names_reader (&reader, reader.comp_unit_die);
3294
3295   if (this_cu->v.quick->no_file_data)
3296     return NULL;
3297   return this_cu->v.quick->file_names;
3298 }
3299
3300 /* A helper for the "quick" functions which computes and caches the
3301    real path for a given file name from the line table.  */
3302
3303 static const char *
3304 dw2_get_real_path (dwarf2_per_objfile *per_objfile,
3305                    struct quick_file_names *qfn, int index)
3306 {
3307   if (qfn->real_names == NULL)
3308     qfn->real_names = OBSTACK_CALLOC (&per_objfile->per_bfd->obstack,
3309                                       qfn->num_file_names, const char *);
3310
3311   if (qfn->real_names[index] == NULL)
3312     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3313
3314   return qfn->real_names[index];
3315 }
3316
3317 struct symtab *
3318 dwarf2_base_index_functions::find_last_source_symtab (struct objfile *objfile)
3319 {
3320   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3321   dwarf2_per_cu_data *dwarf_cu = per_objfile->per_bfd->all_comp_units.back ();
3322   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, per_objfile, false);
3323
3324   if (cust == NULL)
3325     return NULL;
3326
3327   return compunit_primary_filetab (cust);
3328 }
3329
3330 /* Traversal function for dw2_forget_cached_source_info.  */
3331
3332 static int
3333 dw2_free_cached_file_names (void **slot, void *info)
3334 {
3335   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3336
3337   if (file_data->real_names)
3338     {
3339       int i;
3340
3341       for (i = 0; i < file_data->num_file_names; ++i)
3342         {
3343           xfree ((void*) file_data->real_names[i]);
3344           file_data->real_names[i] = NULL;
3345         }
3346     }
3347
3348   return 1;
3349 }
3350
3351 void
3352 dwarf2_base_index_functions::forget_cached_source_info
3353      (struct objfile *objfile)
3354 {
3355   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3356
3357   htab_traverse_noresize (per_objfile->per_bfd->quick_file_names_table.get (),
3358                           dw2_free_cached_file_names, NULL);
3359 }
3360
3361 /* Helper function for dw2_map_symtabs_matching_filename that expands
3362    the symtabs and calls the iterator.  */
3363
3364 static int
3365 dw2_map_expand_apply (struct objfile *objfile,
3366                       struct dwarf2_per_cu_data *per_cu,
3367                       const char *name, const char *real_path,
3368                       gdb::function_view<bool (symtab *)> callback)
3369 {
3370   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3371
3372   /* Don't visit already-expanded CUs.  */
3373   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3374   if (per_objfile->symtab_set_p (per_cu))
3375     return 0;
3376
3377   /* This may expand more than one symtab, and we want to iterate over
3378      all of them.  */
3379   dw2_instantiate_symtab (per_cu, per_objfile, false);
3380
3381   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3382                                     last_made, callback);
3383 }
3384
3385 /* Implementation of the map_symtabs_matching_filename method.  */
3386
3387 bool
3388 dwarf2_base_index_functions::map_symtabs_matching_filename
3389   (struct objfile *objfile, const char *name, const char *real_path,
3390    gdb::function_view<bool (symtab *)> callback)
3391 {
3392   const char *name_basename = lbasename (name);
3393   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3394
3395   /* The rule is CUs specify all the files, including those used by
3396      any TU, so there's no need to scan TUs here.  */
3397
3398   for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
3399     {
3400       /* We only need to look at symtabs not already expanded.  */
3401       if (per_objfile->symtab_set_p (per_cu))
3402         continue;
3403
3404       quick_file_names *file_data = dw2_get_file_names (per_cu, per_objfile);
3405       if (file_data == NULL)
3406         continue;
3407
3408       for (int j = 0; j < file_data->num_file_names; ++j)
3409         {
3410           const char *this_name = file_data->file_names[j];
3411           const char *this_real_name;
3412
3413           if (compare_filenames_for_search (this_name, name))
3414             {
3415               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3416                                         callback))
3417                 return true;
3418               continue;
3419             }
3420
3421           /* Before we invoke realpath, which can get expensive when many
3422              files are involved, do a quick comparison of the basenames.  */
3423           if (! basenames_may_differ
3424               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3425             continue;
3426
3427           this_real_name = dw2_get_real_path (per_objfile, file_data, j);
3428           if (compare_filenames_for_search (this_real_name, name))
3429             {
3430               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3431                                         callback))
3432                 return true;
3433               continue;
3434             }
3435
3436           if (real_path != NULL)
3437             {
3438               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3439               gdb_assert (IS_ABSOLUTE_PATH (name));
3440               if (this_real_name != NULL
3441                   && FILENAME_CMP (real_path, this_real_name) == 0)
3442                 {
3443                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3444                                             callback))
3445                     return true;
3446                   continue;
3447                 }
3448             }
3449         }
3450     }
3451
3452   return false;
3453 }
3454
3455 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3456
3457 struct dw2_symtab_iterator
3458 {
3459   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3460   dwarf2_per_objfile *per_objfile;
3461   /* If set, only look for symbols that match that block.  Valid values are
3462      GLOBAL_BLOCK and STATIC_BLOCK.  */
3463   gdb::optional<block_enum> block_index;
3464   /* The kind of symbol we're looking for.  */
3465   domain_enum domain;
3466   /* The list of CUs from the index entry of the symbol,
3467      or NULL if not found.  */
3468   offset_type *vec;
3469   /* The next element in VEC to look at.  */
3470   int next;
3471   /* The number of elements in VEC, or zero if there is no match.  */
3472   int length;
3473   /* Have we seen a global version of the symbol?
3474      If so we can ignore all further global instances.
3475      This is to work around gold/15646, inefficient gold-generated
3476      indices.  */
3477   int global_seen;
3478 };
3479
3480 /* Initialize the index symtab iterator ITER, common part.  */
3481
3482 static void
3483 dw2_symtab_iter_init_common (struct dw2_symtab_iterator *iter,
3484                              dwarf2_per_objfile *per_objfile,
3485                              gdb::optional<block_enum> block_index,
3486                              domain_enum domain)
3487 {
3488   iter->per_objfile = per_objfile;
3489   iter->block_index = block_index;
3490   iter->domain = domain;
3491   iter->next = 0;
3492   iter->global_seen = 0;
3493   iter->vec = NULL;
3494   iter->length = 0;
3495 }
3496
3497 /* Initialize the index symtab iterator ITER, const char *NAME variant.  */
3498
3499 static void
3500 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3501                       dwarf2_per_objfile *per_objfile,
3502                       gdb::optional<block_enum> block_index,
3503                       domain_enum domain,
3504                       const char *name)
3505 {
3506   dw2_symtab_iter_init_common (iter, per_objfile, block_index, domain);
3507
3508   mapped_index *index = per_objfile->per_bfd->index_table.get ();
3509   /* index is NULL if OBJF_READNOW.  */
3510   if (index == NULL)
3511     return;
3512
3513   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3514     iter->length = MAYBE_SWAP (*iter->vec);
3515 }
3516
3517 /* Initialize the index symtab iterator ITER, offset_type NAMEI variant.  */
3518
3519 static void
3520 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3521                       dwarf2_per_objfile *per_objfile,
3522                       gdb::optional<block_enum> block_index,
3523                       domain_enum domain, offset_type namei)
3524 {
3525   dw2_symtab_iter_init_common (iter, per_objfile, block_index, domain);
3526
3527   mapped_index *index = per_objfile->per_bfd->index_table.get ();
3528   /* index is NULL if OBJF_READNOW.  */
3529   if (index == NULL)
3530     return;
3531
3532   gdb_assert (!index->symbol_name_slot_invalid (namei));
3533   const auto &bucket = index->symbol_table[namei];
3534
3535   iter->vec = (offset_type *) (index->constant_pool
3536                                + MAYBE_SWAP (bucket.vec));
3537   iter->length = MAYBE_SWAP (*iter->vec);
3538 }
3539
3540 /* Return the next matching CU or NULL if there are no more.  */
3541
3542 static struct dwarf2_per_cu_data *
3543 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3544 {
3545   dwarf2_per_objfile *per_objfile = iter->per_objfile;
3546
3547   for ( ; iter->next < iter->length; ++iter->next)
3548     {
3549       offset_type cu_index_and_attrs =
3550         MAYBE_SWAP (iter->vec[iter->next + 1]);
3551       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3552       gdb_index_symbol_kind symbol_kind =
3553         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3554       /* Only check the symbol attributes if they're present.
3555          Indices prior to version 7 don't record them,
3556          and indices >= 7 may elide them for certain symbols
3557          (gold does this).  */
3558       int attrs_valid =
3559         (per_objfile->per_bfd->index_table->version >= 7
3560          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3561
3562       /* Don't crash on bad data.  */
3563       if (cu_index >= (per_objfile->per_bfd->all_comp_units.size ()
3564                        + per_objfile->per_bfd->all_type_units.size ()))
3565         {
3566           complaint (_(".gdb_index entry has bad CU index"
3567                        " [in module %s]"), objfile_name (per_objfile->objfile));
3568           continue;
3569         }
3570
3571       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cutu (cu_index);
3572
3573       /* Skip if already read in.  */
3574       if (per_objfile->symtab_set_p (per_cu))
3575         continue;
3576
3577       /* Check static vs global.  */
3578       if (attrs_valid)
3579         {
3580           bool is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3581
3582           if (iter->block_index.has_value ())
3583             {
3584               bool want_static = *iter->block_index == STATIC_BLOCK;
3585
3586               if (is_static != want_static)
3587                 continue;
3588             }
3589
3590           /* Work around gold/15646.  */
3591           if (!is_static
3592               && symbol_kind == GDB_INDEX_SYMBOL_KIND_TYPE)
3593             {
3594               if (iter->global_seen)
3595                 continue;
3596
3597               iter->global_seen = 1;
3598             }
3599         }
3600
3601       /* Only check the symbol's kind if it has one.  */
3602       if (attrs_valid)
3603         {
3604           switch (iter->domain)
3605             {
3606             case VAR_DOMAIN:
3607               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3608                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3609                   /* Some types are also in VAR_DOMAIN.  */
3610                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3611                 continue;
3612               break;
3613             case STRUCT_DOMAIN:
3614               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3615                 continue;
3616               break;
3617             case LABEL_DOMAIN:
3618               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3619                 continue;
3620               break;
3621             case MODULE_DOMAIN:
3622               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3623                 continue;
3624               break;
3625             default:
3626               break;
3627             }
3628         }
3629
3630       ++iter->next;
3631       return per_cu;
3632     }
3633
3634   return NULL;
3635 }
3636
3637 struct compunit_symtab *
3638 dwarf2_gdb_index::lookup_symbol (struct objfile *objfile,
3639                                  block_enum block_index,
3640                                  const char *name, domain_enum domain)
3641 {
3642   struct compunit_symtab *stab_best = NULL;
3643   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3644
3645   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3646
3647   struct dw2_symtab_iterator iter;
3648   struct dwarf2_per_cu_data *per_cu;
3649
3650   dw2_symtab_iter_init (&iter, per_objfile, block_index, domain, name);
3651
3652   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3653     {
3654       struct symbol *sym, *with_opaque = NULL;
3655       struct compunit_symtab *stab
3656         = dw2_instantiate_symtab (per_cu, per_objfile, false);
3657       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3658       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3659
3660       sym = block_find_symbol (block, name, domain,
3661                                block_find_non_opaque_type_preferred,
3662                                &with_opaque);
3663
3664       /* Some caution must be observed with overloaded functions
3665          and methods, since the index will not contain any overload
3666          information (but NAME might contain it).  */
3667
3668       if (sym != NULL
3669           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3670         return stab;
3671       if (with_opaque != NULL
3672           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3673         stab_best = stab;
3674
3675       /* Keep looking through other CUs.  */
3676     }
3677
3678   return stab_best;
3679 }
3680
3681 void
3682 dwarf2_base_index_functions::print_stats (struct objfile *objfile,
3683                                           bool print_bcache)
3684 {
3685   if (print_bcache)
3686     return;
3687
3688   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3689   int total = (per_objfile->per_bfd->all_comp_units.size ()
3690                + per_objfile->per_bfd->all_type_units.size ());
3691   int count = 0;
3692
3693   for (int i = 0; i < total; ++i)
3694     {
3695       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cutu (i);
3696
3697       if (!per_objfile->symtab_set_p (per_cu))
3698         ++count;
3699     }
3700   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3701   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3702 }
3703
3704 /* This dumps minimal information about the index.
3705    It is called via "mt print objfiles".
3706    One use is to verify .gdb_index has been loaded by the
3707    gdb.dwarf2/gdb-index.exp testcase.  */
3708
3709 void
3710 dwarf2_gdb_index::dump (struct objfile *objfile)
3711 {
3712   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3713
3714   gdb_assert (per_objfile->per_bfd->using_index);
3715   printf_filtered (".gdb_index:");
3716   if (per_objfile->per_bfd->index_table != NULL)
3717     {
3718       printf_filtered (" version %d\n",
3719                        per_objfile->per_bfd->index_table->version);
3720     }
3721   else
3722     printf_filtered (" faked for \"readnow\"\n");
3723   printf_filtered ("\n");
3724 }
3725
3726 void
3727 dwarf2_gdb_index::expand_symtabs_for_function (struct objfile *objfile,
3728                                                const char *func_name)
3729 {
3730   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3731
3732   struct dw2_symtab_iterator iter;
3733   struct dwarf2_per_cu_data *per_cu;
3734
3735   dw2_symtab_iter_init (&iter, per_objfile, {}, VAR_DOMAIN, func_name);
3736
3737   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3738     dw2_instantiate_symtab (per_cu, per_objfile, false);
3739
3740 }
3741
3742 void
3743 dwarf2_base_index_functions::expand_all_symtabs (struct objfile *objfile)
3744 {
3745   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3746   int total_units = (per_objfile->per_bfd->all_comp_units.size ()
3747                      + per_objfile->per_bfd->all_type_units.size ());
3748
3749   for (int i = 0; i < total_units; ++i)
3750     {
3751       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cutu (i);
3752
3753       /* We don't want to directly expand a partial CU, because if we
3754          read it with the wrong language, then assertion failures can
3755          be triggered later on.  See PR symtab/23010.  So, tell
3756          dw2_instantiate_symtab to skip partial CUs -- any important
3757          partial CU will be read via DW_TAG_imported_unit anyway.  */
3758       dw2_instantiate_symtab (per_cu, per_objfile, true);
3759     }
3760 }
3761
3762 void
3763 dwarf2_base_index_functions::expand_symtabs_with_fullname
3764      (struct objfile *objfile, const char *fullname)
3765 {
3766   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3767
3768   /* We don't need to consider type units here.
3769      This is only called for examining code, e.g. expand_line_sal.
3770      There can be an order of magnitude (or more) more type units
3771      than comp units, and we avoid them if we can.  */
3772
3773   for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
3774     {
3775       /* We only need to look at symtabs not already expanded.  */
3776       if (per_objfile->symtab_set_p (per_cu))
3777         continue;
3778
3779       quick_file_names *file_data = dw2_get_file_names (per_cu, per_objfile);
3780       if (file_data == NULL)
3781         continue;
3782
3783       for (int j = 0; j < file_data->num_file_names; ++j)
3784         {
3785           const char *this_fullname = file_data->file_names[j];
3786
3787           if (filename_cmp (this_fullname, fullname) == 0)
3788             {
3789               dw2_instantiate_symtab (per_cu, per_objfile, false);
3790               break;
3791             }
3792         }
3793     }
3794 }
3795
3796 static void
3797 dw2_expand_symtabs_matching_symbol
3798   (mapped_index_base &index,
3799    const lookup_name_info &lookup_name_in,
3800    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
3801    gdb::function_view<bool (offset_type)> match_callback,
3802    dwarf2_per_objfile *per_objfile);
3803
3804 static void
3805 dw2_expand_symtabs_matching_one
3806   (dwarf2_per_cu_data *per_cu,
3807    dwarf2_per_objfile *per_objfile,
3808    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
3809    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify);
3810
3811 static void
3812 dw2_map_matching_symbols
3813   (struct objfile *objfile,
3814    const lookup_name_info &name, domain_enum domain,
3815    int global,
3816    gdb::function_view<symbol_found_callback_ftype> callback,
3817    symbol_compare_ftype *ordered_compare)
3818 {
3819   /* Used for Ada.  */
3820   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3821
3822   const block_enum block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
3823
3824   if (per_objfile->per_bfd->index_table != nullptr)
3825     {
3826       mapped_index &index = *per_objfile->per_bfd->index_table;
3827
3828       const char *match_name = name.ada ().lookup_name ().c_str ();
3829       auto matcher = [&] (const char *symname)
3830         {
3831           if (ordered_compare == nullptr)
3832             return true;
3833           return ordered_compare (symname, match_name) == 0;
3834         };
3835
3836       dw2_expand_symtabs_matching_symbol (index, name, matcher,
3837                                           [&] (offset_type namei)
3838       {
3839         struct dw2_symtab_iterator iter;
3840         struct dwarf2_per_cu_data *per_cu;
3841
3842         dw2_symtab_iter_init (&iter, per_objfile, block_kind, domain,
3843                               namei);
3844         while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3845           dw2_expand_symtabs_matching_one (per_cu, per_objfile, nullptr,
3846                                            nullptr);
3847         return true;
3848       }, per_objfile);
3849     }
3850   else
3851     {
3852       /* We have -readnow: no .gdb_index, but no partial symtabs either.  So,
3853          proceed assuming all symtabs have been read in.  */
3854     }
3855
3856   for (compunit_symtab *cust : objfile->compunits ())
3857     {
3858       const struct block *block;
3859
3860       if (cust == NULL)
3861         continue;
3862       block = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cust), block_kind);
3863       if (!iterate_over_symbols_terminated (block, name,
3864                                             domain, callback))
3865         return;
3866     }
3867 }
3868
3869 void
3870 dwarf2_gdb_index::map_matching_symbols
3871   (struct objfile *objfile,
3872    const lookup_name_info &name, domain_enum domain,
3873    int global,
3874    gdb::function_view<symbol_found_callback_ftype> callback,
3875    symbol_compare_ftype *ordered_compare)
3876 {
3877   dw2_map_matching_symbols (objfile, name, domain, global, callback,
3878                             ordered_compare);
3879 }
3880
3881 /* Starting from a search name, return the string that finds the upper
3882    bound of all strings that start with SEARCH_NAME in a sorted name
3883    list.  Returns the empty string to indicate that the upper bound is
3884    the end of the list.  */
3885
3886 static std::string
3887 make_sort_after_prefix_name (const char *search_name)
3888 {
3889   /* When looking to complete "func", we find the upper bound of all
3890      symbols that start with "func" by looking for where we'd insert
3891      the closest string that would follow "func" in lexicographical
3892      order.  Usually, that's "func"-with-last-character-incremented,
3893      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
3894      will be UTF-8 multi-byte sequences, but we can't be certain.
3895      Especially mind the 0xff character, which is a valid character in
3896      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
3897      rule out compilers allowing it in identifiers.  Note that
3898      conveniently, strcmp/strcasecmp are specified to compare
3899      characters interpreted as unsigned char.  So what we do is treat
3900      the whole string as a base 256 number composed of a sequence of
3901      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
3902      to 0, and carries 1 to the following more-significant position.
3903      If the very first character in SEARCH_NAME ends up incremented
3904      and carries/overflows, then the upper bound is the end of the
3905      list.  The string after the empty string is also the empty
3906      string.
3907
3908      Some examples of this operation:
3909
3910        SEARCH_NAME  => "+1" RESULT
3911
3912        "abc"              => "abd"
3913        "ab\xff"           => "ac"
3914        "\xff" "a" "\xff"  => "\xff" "b"
3915        "\xff"             => ""
3916        "\xff\xff"         => ""
3917        ""                 => ""
3918
3919      Then, with these symbols for example:
3920
3921       func
3922       func1
3923       fund
3924
3925      completing "func" looks for symbols between "func" and
3926      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
3927      which finds "func" and "func1", but not "fund".
3928
3929      And with:
3930
3931       funcÿ     (Latin1 'ÿ' [0xff])
3932       funcÿ1
3933       fund
3934
3935      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
3936      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
3937
3938      And with:
3939
3940       ÿÿ        (Latin1 'ÿ' [0xff])
3941       ÿÿ1
3942
3943      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
3944      the end of the list.
3945   */
3946   std::string after = search_name;
3947   while (!after.empty () && (unsigned char) after.back () == 0xff)
3948     after.pop_back ();
3949   if (!after.empty ())
3950     after.back () = (unsigned char) after.back () + 1;
3951   return after;
3952 }
3953
3954 /* See declaration.  */
3955
3956 std::pair<std::vector<name_component>::const_iterator,
3957           std::vector<name_component>::const_iterator>
3958 mapped_index_base::find_name_components_bounds
3959   (const lookup_name_info &lookup_name_without_params, language lang,
3960    dwarf2_per_objfile *per_objfile) const
3961 {
3962   auto *name_cmp
3963     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3964
3965   const char *lang_name
3966     = lookup_name_without_params.language_lookup_name (lang);
3967
3968   /* Comparison function object for lower_bound that matches against a
3969      given symbol name.  */
3970   auto lookup_compare_lower = [&] (const name_component &elem,
3971                                    const char *name)
3972     {
3973       const char *elem_qualified = this->symbol_name_at (elem.idx, per_objfile);
3974       const char *elem_name = elem_qualified + elem.name_offset;
3975       return name_cmp (elem_name, name) < 0;
3976     };
3977
3978   /* Comparison function object for upper_bound that matches against a
3979      given symbol name.  */
3980   auto lookup_compare_upper = [&] (const char *name,
3981                                    const name_component &elem)
3982     {
3983       const char *elem_qualified = this->symbol_name_at (elem.idx, per_objfile);
3984       const char *elem_name = elem_qualified + elem.name_offset;
3985       return name_cmp (name, elem_name) < 0;
3986     };
3987
3988   auto begin = this->name_components.begin ();
3989   auto end = this->name_components.end ();
3990
3991   /* Find the lower bound.  */
3992   auto lower = [&] ()
3993     {
3994       if (lookup_name_without_params.completion_mode () && lang_name[0] == '\0')
3995         return begin;
3996       else
3997         return std::lower_bound (begin, end, lang_name, lookup_compare_lower);
3998     } ();
3999
4000   /* Find the upper bound.  */
4001   auto upper = [&] ()
4002     {
4003       if (lookup_name_without_params.completion_mode ())
4004         {
4005           /* In completion mode, we want UPPER to point past all
4006              symbols names that have the same prefix.  I.e., with
4007              these symbols, and completing "func":
4008
4009               function        << lower bound
4010               function1
4011               other_function  << upper bound
4012
4013              We find the upper bound by looking for the insertion
4014              point of "func"-with-last-character-incremented,
4015              i.e. "fund".  */
4016           std::string after = make_sort_after_prefix_name (lang_name);
4017           if (after.empty ())
4018             return end;
4019           return std::lower_bound (lower, end, after.c_str (),
4020                                    lookup_compare_lower);
4021         }
4022       else
4023         return std::upper_bound (lower, end, lang_name, lookup_compare_upper);
4024     } ();
4025
4026   return {lower, upper};
4027 }
4028
4029 /* See declaration.  */
4030
4031 void
4032 mapped_index_base::build_name_components (dwarf2_per_objfile *per_objfile)
4033 {
4034   if (!this->name_components.empty ())
4035     return;
4036
4037   this->name_components_casing = case_sensitivity;
4038   auto *name_cmp
4039     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4040
4041   /* The code below only knows how to break apart components of C++
4042      symbol names (and other languages that use '::' as
4043      namespace/module separator) and Ada symbol names.  */
4044   auto count = this->symbol_name_count ();
4045   for (offset_type idx = 0; idx < count; idx++)
4046     {
4047       if (this->symbol_name_slot_invalid (idx))
4048         continue;
4049
4050       const char *name = this->symbol_name_at (idx, per_objfile);
4051
4052       /* Add each name component to the name component table.  */
4053       unsigned int previous_len = 0;
4054
4055       if (strstr (name, "::") != nullptr)
4056         {
4057           for (unsigned int current_len = cp_find_first_component (name);
4058                name[current_len] != '\0';
4059                current_len += cp_find_first_component (name + current_len))
4060             {
4061               gdb_assert (name[current_len] == ':');
4062               this->name_components.push_back ({previous_len, idx});
4063               /* Skip the '::'.  */
4064               current_len += 2;
4065               previous_len = current_len;
4066             }
4067         }
4068       else
4069         {
4070           /* Handle the Ada encoded (aka mangled) form here.  */
4071           for (const char *iter = strstr (name, "__");
4072                iter != nullptr;
4073                iter = strstr (iter, "__"))
4074             {
4075               this->name_components.push_back ({previous_len, idx});
4076               iter += 2;
4077               previous_len = iter - name;
4078             }
4079         }
4080
4081       this->name_components.push_back ({previous_len, idx});
4082     }
4083
4084   /* Sort name_components elements by name.  */
4085   auto name_comp_compare = [&] (const name_component &left,
4086                                 const name_component &right)
4087     {
4088       const char *left_qualified
4089         = this->symbol_name_at (left.idx, per_objfile);
4090       const char *right_qualified
4091         = this->symbol_name_at (right.idx, per_objfile);
4092
4093       const char *left_name = left_qualified + left.name_offset;
4094       const char *right_name = right_qualified + right.name_offset;
4095
4096       return name_cmp (left_name, right_name) < 0;
4097     };
4098
4099   std::sort (this->name_components.begin (),
4100              this->name_components.end (),
4101              name_comp_compare);
4102 }
4103
4104 /* Helper for dw2_expand_symtabs_matching that works with a
4105    mapped_index_base instead of the containing objfile.  This is split
4106    to a separate function in order to be able to unit test the
4107    name_components matching using a mock mapped_index_base.  For each
4108    symbol name that matches, calls MATCH_CALLBACK, passing it the
4109    symbol's index in the mapped_index_base symbol table.  */
4110
4111 static void
4112 dw2_expand_symtabs_matching_symbol
4113   (mapped_index_base &index,
4114    const lookup_name_info &lookup_name_in,
4115    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4116    gdb::function_view<bool (offset_type)> match_callback,
4117    dwarf2_per_objfile *per_objfile)
4118 {
4119   lookup_name_info lookup_name_without_params
4120     = lookup_name_in.make_ignore_params ();
4121
4122   /* Build the symbol name component sorted vector, if we haven't
4123      yet.  */
4124   index.build_name_components (per_objfile);
4125
4126   /* The same symbol may appear more than once in the range though.
4127      E.g., if we're looking for symbols that complete "w", and we have
4128      a symbol named "w1::w2", we'll find the two name components for
4129      that same symbol in the range.  To be sure we only call the
4130      callback once per symbol, we first collect the symbol name
4131      indexes that matched in a temporary vector and ignore
4132      duplicates.  */
4133   std::vector<offset_type> matches;
4134
4135   struct name_and_matcher
4136   {
4137     symbol_name_matcher_ftype *matcher;
4138     const char *name;
4139
4140     bool operator== (const name_and_matcher &other) const
4141     {
4142       return matcher == other.matcher && strcmp (name, other.name) == 0;
4143     }
4144   };
4145
4146   /* A vector holding all the different symbol name matchers, for all
4147      languages.  */
4148   std::vector<name_and_matcher> matchers;
4149
4150   for (int i = 0; i < nr_languages; i++)
4151     {
4152       enum language lang_e = (enum language) i;
4153
4154       const language_defn *lang = language_def (lang_e);
4155       symbol_name_matcher_ftype *name_matcher
4156         = lang->get_symbol_name_matcher (lookup_name_without_params);
4157
4158       name_and_matcher key {
4159          name_matcher,
4160          lookup_name_without_params.language_lookup_name (lang_e)
4161       };
4162
4163       /* Don't insert the same comparison routine more than once.
4164          Note that we do this linear walk.  This is not a problem in
4165          practice because the number of supported languages is
4166          low.  */
4167       if (std::find (matchers.begin (), matchers.end (), key)
4168           != matchers.end ())
4169         continue;
4170       matchers.push_back (std::move (key));
4171
4172       auto bounds
4173         = index.find_name_components_bounds (lookup_name_without_params,
4174                                              lang_e, per_objfile);
4175
4176       /* Now for each symbol name in range, check to see if we have a name
4177          match, and if so, call the MATCH_CALLBACK callback.  */
4178
4179       for (; bounds.first != bounds.second; ++bounds.first)
4180         {
4181           const char *qualified
4182             = index.symbol_name_at (bounds.first->idx, per_objfile);
4183
4184           if (!name_matcher (qualified, lookup_name_without_params, NULL)
4185               || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4186             continue;
4187
4188           matches.push_back (bounds.first->idx);
4189         }
4190     }
4191
4192   std::sort (matches.begin (), matches.end ());
4193
4194   /* Finally call the callback, once per match.  */
4195   ULONGEST prev = -1;
4196   for (offset_type idx : matches)
4197     {
4198       if (prev != idx)
4199         {
4200           if (!match_callback (idx))
4201             break;
4202           prev = idx;
4203         }
4204     }
4205
4206   /* Above we use a type wider than idx's for 'prev', since 0 and
4207      (offset_type)-1 are both possible values.  */
4208   static_assert (sizeof (prev) > sizeof (offset_type), "");
4209 }
4210
4211 #if GDB_SELF_TEST
4212
4213 namespace selftests { namespace dw2_expand_symtabs_matching {
4214
4215 /* A mock .gdb_index/.debug_names-like name index table, enough to
4216    exercise dw2_expand_symtabs_matching_symbol, which works with the
4217    mapped_index_base interface.  Builds an index from the symbol list
4218    passed as parameter to the constructor.  */
4219 class mock_mapped_index : public mapped_index_base
4220 {
4221 public:
4222   mock_mapped_index (gdb::array_view<const char *> symbols)
4223     : m_symbol_table (symbols)
4224   {}
4225
4226   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4227
4228   /* Return the number of names in the symbol table.  */
4229   size_t symbol_name_count () const override
4230   {
4231     return m_symbol_table.size ();
4232   }
4233
4234   /* Get the name of the symbol at IDX in the symbol table.  */
4235   const char *symbol_name_at
4236     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
4237   {
4238     return m_symbol_table[idx];
4239   }
4240
4241 private:
4242   gdb::array_view<const char *> m_symbol_table;
4243 };
4244
4245 /* Convenience function that converts a NULL pointer to a "<null>"
4246    string, to pass to print routines.  */
4247
4248 static const char *
4249 string_or_null (const char *str)
4250 {
4251   return str != NULL ? str : "<null>";
4252 }
4253
4254 /* Check if a lookup_name_info built from
4255    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4256    index.  EXPECTED_LIST is the list of expected matches, in expected
4257    matching order.  If no match expected, then an empty list is
4258    specified.  Returns true on success.  On failure prints a warning
4259    indicating the file:line that failed, and returns false.  */
4260
4261 static bool
4262 check_match (const char *file, int line,
4263              mock_mapped_index &mock_index,
4264              const char *name, symbol_name_match_type match_type,
4265              bool completion_mode,
4266              std::initializer_list<const char *> expected_list,
4267              dwarf2_per_objfile *per_objfile)
4268 {
4269   lookup_name_info lookup_name (name, match_type, completion_mode);
4270
4271   bool matched = true;
4272
4273   auto mismatch = [&] (const char *expected_str,
4274                        const char *got)
4275   {
4276     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4277                "expected=\"%s\", got=\"%s\"\n"),
4278              file, line,
4279              (match_type == symbol_name_match_type::FULL
4280               ? "FULL" : "WILD"),
4281              name, string_or_null (expected_str), string_or_null (got));
4282     matched = false;
4283   };
4284
4285   auto expected_it = expected_list.begin ();
4286   auto expected_end = expected_list.end ();
4287
4288   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4289                                       nullptr,
4290                                       [&] (offset_type idx)
4291   {
4292     const char *matched_name = mock_index.symbol_name_at (idx, per_objfile);
4293     const char *expected_str
4294       = expected_it == expected_end ? NULL : *expected_it++;
4295
4296     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4297       mismatch (expected_str, matched_name);
4298     return true;
4299   }, per_objfile);
4300
4301   const char *expected_str
4302   = expected_it == expected_end ? NULL : *expected_it++;
4303   if (expected_str != NULL)
4304     mismatch (expected_str, NULL);
4305
4306   return matched;
4307 }
4308
4309 /* The symbols added to the mock mapped_index for testing (in
4310    canonical form).  */
4311 static const char *test_symbols[] = {
4312   "function",
4313   "std::bar",
4314   "std::zfunction",
4315   "std::zfunction2",
4316   "w1::w2",
4317   "ns::foo<char*>",
4318   "ns::foo<int>",
4319   "ns::foo<long>",
4320   "ns2::tmpl<int>::foo2",
4321   "(anonymous namespace)::A::B::C",
4322
4323   /* These are used to check that the increment-last-char in the
4324      matching algorithm for completion doesn't match "t1_fund" when
4325      completing "t1_func".  */
4326   "t1_func",
4327   "t1_func1",
4328   "t1_fund",
4329   "t1_fund1",
4330
4331   /* A UTF-8 name with multi-byte sequences to make sure that
4332      cp-name-parser understands this as a single identifier ("função"
4333      is "function" in PT).  */
4334   u8"u8função",
4335
4336   /* \377 (0xff) is Latin1 'ÿ'.  */
4337   "yfunc\377",
4338
4339   /* \377 (0xff) is Latin1 'ÿ'.  */
4340   "\377",
4341   "\377\377123",
4342
4343   /* A name with all sorts of complications.  Starts with "z" to make
4344      it easier for the completion tests below.  */
4345 #define Z_SYM_NAME \
4346   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4347     "::tuple<(anonymous namespace)::ui*, " \
4348     "std::default_delete<(anonymous namespace)::ui>, void>"
4349
4350   Z_SYM_NAME
4351 };
4352
4353 /* Returns true if the mapped_index_base::find_name_component_bounds
4354    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4355    in completion mode.  */
4356
4357 static bool
4358 check_find_bounds_finds (mapped_index_base &index,
4359                          const char *search_name,
4360                          gdb::array_view<const char *> expected_syms,
4361                          dwarf2_per_objfile *per_objfile)
4362 {
4363   lookup_name_info lookup_name (search_name,
4364                                 symbol_name_match_type::FULL, true);
4365
4366   auto bounds = index.find_name_components_bounds (lookup_name,
4367                                                    language_cplus,
4368                                                    per_objfile);
4369
4370   size_t distance = std::distance (bounds.first, bounds.second);
4371   if (distance != expected_syms.size ())
4372     return false;
4373
4374   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4375     {
4376       auto nc_elem = bounds.first + exp_elem;
4377       const char *qualified = index.symbol_name_at (nc_elem->idx, per_objfile);
4378       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4379         return false;
4380     }
4381
4382   return true;
4383 }
4384
4385 /* Test the lower-level mapped_index::find_name_component_bounds
4386    method.  */
4387
4388 static void
4389 test_mapped_index_find_name_component_bounds ()
4390 {
4391   mock_mapped_index mock_index (test_symbols);
4392
4393   mock_index.build_name_components (NULL /* per_objfile */);
4394
4395   /* Test the lower-level mapped_index::find_name_component_bounds
4396      method in completion mode.  */
4397   {
4398     static const char *expected_syms[] = {
4399       "t1_func",
4400       "t1_func1",
4401     };
4402
4403     SELF_CHECK (check_find_bounds_finds
4404                   (mock_index, "t1_func", expected_syms,
4405                    NULL /* per_objfile */));
4406   }
4407
4408   /* Check that the increment-last-char in the name matching algorithm
4409      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4410   {
4411     static const char *expected_syms1[] = {
4412       "\377",
4413       "\377\377123",
4414     };
4415     SELF_CHECK (check_find_bounds_finds
4416                   (mock_index, "\377", expected_syms1, NULL /* per_objfile */));
4417
4418     static const char *expected_syms2[] = {
4419       "\377\377123",
4420     };
4421     SELF_CHECK (check_find_bounds_finds
4422                   (mock_index, "\377\377", expected_syms2,
4423                    NULL /* per_objfile */));
4424   }
4425 }
4426
4427 /* Test dw2_expand_symtabs_matching_symbol.  */
4428
4429 static void
4430 test_dw2_expand_symtabs_matching_symbol ()
4431 {
4432   mock_mapped_index mock_index (test_symbols);
4433
4434   /* We let all tests run until the end even if some fails, for debug
4435      convenience.  */
4436   bool any_mismatch = false;
4437
4438   /* Create the expected symbols list (an initializer_list).  Needed
4439      because lists have commas, and we need to pass them to CHECK,
4440      which is a macro.  */
4441 #define EXPECT(...) { __VA_ARGS__ }
4442
4443   /* Wrapper for check_match that passes down the current
4444      __FILE__/__LINE__.  */
4445 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4446   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4447                                 mock_index,                             \
4448                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4449                                 EXPECTED_LIST, NULL)
4450
4451   /* Identity checks.  */
4452   for (const char *sym : test_symbols)
4453     {
4454       /* Should be able to match all existing symbols.  */
4455       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4456                    EXPECT (sym));
4457
4458       /* Should be able to match all existing symbols with
4459          parameters.  */
4460       std::string with_params = std::string (sym) + "(int)";
4461       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4462                    EXPECT (sym));
4463
4464       /* Should be able to match all existing symbols with
4465          parameters and qualifiers.  */
4466       with_params = std::string (sym) + " ( int ) const";
4467       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4468                    EXPECT (sym));
4469
4470       /* This should really find sym, but cp-name-parser.y doesn't
4471          know about lvalue/rvalue qualifiers yet.  */
4472       with_params = std::string (sym) + " ( int ) &&";
4473       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4474                    {});
4475     }
4476
4477   /* Check that the name matching algorithm for completion doesn't get
4478      confused with Latin1 'ÿ' / 0xff.  */
4479   {
4480     static const char str[] = "\377";
4481     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4482                  EXPECT ("\377", "\377\377123"));
4483   }
4484
4485   /* Check that the increment-last-char in the matching algorithm for
4486      completion doesn't match "t1_fund" when completing "t1_func".  */
4487   {
4488     static const char str[] = "t1_func";
4489     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4490                  EXPECT ("t1_func", "t1_func1"));
4491   }
4492
4493   /* Check that completion mode works at each prefix of the expected
4494      symbol name.  */
4495   {
4496     static const char str[] = "function(int)";
4497     size_t len = strlen (str);
4498     std::string lookup;
4499
4500     for (size_t i = 1; i < len; i++)
4501       {
4502         lookup.assign (str, i);
4503         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4504                      EXPECT ("function"));
4505       }
4506   }
4507
4508   /* While "w" is a prefix of both components, the match function
4509      should still only be called once.  */
4510   {
4511     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4512                  EXPECT ("w1::w2"));
4513     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4514                  EXPECT ("w1::w2"));
4515   }
4516
4517   /* Same, with a "complicated" symbol.  */
4518   {
4519     static const char str[] = Z_SYM_NAME;
4520     size_t len = strlen (str);
4521     std::string lookup;
4522
4523     for (size_t i = 1; i < len; i++)
4524       {
4525         lookup.assign (str, i);
4526         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4527                      EXPECT (Z_SYM_NAME));
4528       }
4529   }
4530
4531   /* In FULL mode, an incomplete symbol doesn't match.  */
4532   {
4533     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4534                  {});
4535   }
4536
4537   /* A complete symbol with parameters matches any overload, since the
4538      index has no overload info.  */
4539   {
4540     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4541                  EXPECT ("std::zfunction", "std::zfunction2"));
4542     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4543                  EXPECT ("std::zfunction", "std::zfunction2"));
4544     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4545                  EXPECT ("std::zfunction", "std::zfunction2"));
4546   }
4547
4548   /* Check that whitespace is ignored appropriately.  A symbol with a
4549      template argument list. */
4550   {
4551     static const char expected[] = "ns::foo<int>";
4552     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4553                  EXPECT (expected));
4554     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4555                  EXPECT (expected));
4556   }
4557
4558   /* Check that whitespace is ignored appropriately.  A symbol with a
4559      template argument list that includes a pointer.  */
4560   {
4561     static const char expected[] = "ns::foo<char*>";
4562     /* Try both completion and non-completion modes.  */
4563     static const bool completion_mode[2] = {false, true};
4564     for (size_t i = 0; i < 2; i++)
4565       {
4566         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4567                      completion_mode[i], EXPECT (expected));
4568         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4569                      completion_mode[i], EXPECT (expected));
4570
4571         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4572                      completion_mode[i], EXPECT (expected));
4573         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4574                      completion_mode[i], EXPECT (expected));
4575       }
4576   }
4577
4578   {
4579     /* Check method qualifiers are ignored.  */
4580     static const char expected[] = "ns::foo<char*>";
4581     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4582                  symbol_name_match_type::FULL, true, EXPECT (expected));
4583     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4584                  symbol_name_match_type::FULL, true, EXPECT (expected));
4585     CHECK_MATCH ("foo < char * >  ( int ) const",
4586                  symbol_name_match_type::WILD, true, EXPECT (expected));
4587     CHECK_MATCH ("foo < char * >  ( int ) &&",
4588                  symbol_name_match_type::WILD, true, EXPECT (expected));
4589   }
4590
4591   /* Test lookup names that don't match anything.  */
4592   {
4593     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4594                  {});
4595
4596     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4597                  {});
4598   }
4599
4600   /* Some wild matching tests, exercising "(anonymous namespace)",
4601      which should not be confused with a parameter list.  */
4602   {
4603     static const char *syms[] = {
4604       "A::B::C",
4605       "B::C",
4606       "C",
4607       "A :: B :: C ( int )",
4608       "B :: C ( int )",
4609       "C ( int )",
4610     };
4611
4612     for (const char *s : syms)
4613       {
4614         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4615                      EXPECT ("(anonymous namespace)::A::B::C"));
4616       }
4617   }
4618
4619   {
4620     static const char expected[] = "ns2::tmpl<int>::foo2";
4621     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4622                  EXPECT (expected));
4623     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4624                  EXPECT (expected));
4625   }
4626
4627   SELF_CHECK (!any_mismatch);
4628
4629 #undef EXPECT
4630 #undef CHECK_MATCH
4631 }
4632
4633 static void
4634 run_test ()
4635 {
4636   test_mapped_index_find_name_component_bounds ();
4637   test_dw2_expand_symtabs_matching_symbol ();
4638 }
4639
4640 }} // namespace selftests::dw2_expand_symtabs_matching
4641
4642 #endif /* GDB_SELF_TEST */
4643
4644 /* If FILE_MATCHER is NULL or if PER_CU has
4645    dwarf2_per_cu_quick_data::MARK set (see
4646    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4647    EXPANSION_NOTIFY on it.  */
4648
4649 static void
4650 dw2_expand_symtabs_matching_one
4651   (dwarf2_per_cu_data *per_cu,
4652    dwarf2_per_objfile *per_objfile,
4653    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4654    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4655 {
4656   if (file_matcher == NULL || per_cu->v.quick->mark)
4657     {
4658       bool symtab_was_null = !per_objfile->symtab_set_p (per_cu);
4659
4660       compunit_symtab *symtab
4661         = dw2_instantiate_symtab (per_cu, per_objfile, false);
4662       gdb_assert (symtab != nullptr);
4663
4664       if (expansion_notify != NULL && symtab_was_null)
4665         expansion_notify (symtab);
4666     }
4667 }
4668
4669 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4670    matched, to expand corresponding CUs that were marked.  IDX is the
4671    index of the symbol name that matched.  */
4672
4673 static void
4674 dw2_expand_marked_cus
4675   (dwarf2_per_objfile *per_objfile, offset_type idx,
4676    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4677    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4678    search_domain kind)
4679 {
4680   offset_type *vec, vec_len, vec_idx;
4681   bool global_seen = false;
4682   mapped_index &index = *per_objfile->per_bfd->index_table;
4683
4684   vec = (offset_type *) (index.constant_pool
4685                          + MAYBE_SWAP (index.symbol_table[idx].vec));
4686   vec_len = MAYBE_SWAP (vec[0]);
4687   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4688     {
4689       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4690       /* This value is only valid for index versions >= 7.  */
4691       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4692       gdb_index_symbol_kind symbol_kind =
4693         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4694       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4695       /* Only check the symbol attributes if they're present.
4696          Indices prior to version 7 don't record them,
4697          and indices >= 7 may elide them for certain symbols
4698          (gold does this).  */
4699       int attrs_valid =
4700         (index.version >= 7
4701          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4702
4703       /* Work around gold/15646.  */
4704       if (attrs_valid
4705           && !is_static
4706           && symbol_kind == GDB_INDEX_SYMBOL_KIND_TYPE)
4707         {
4708           if (global_seen)
4709             continue;
4710
4711           global_seen = true;
4712         }
4713
4714       /* Only check the symbol's kind if it has one.  */
4715       if (attrs_valid)
4716         {
4717           switch (kind)
4718             {
4719             case VARIABLES_DOMAIN:
4720               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4721                 continue;
4722               break;
4723             case FUNCTIONS_DOMAIN:
4724               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4725                 continue;
4726               break;
4727             case TYPES_DOMAIN:
4728               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4729                 continue;
4730               break;
4731             case MODULES_DOMAIN:
4732               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4733                 continue;
4734               break;
4735             default:
4736               break;
4737             }
4738         }
4739
4740       /* Don't crash on bad data.  */
4741       if (cu_index >= (per_objfile->per_bfd->all_comp_units.size ()
4742                        + per_objfile->per_bfd->all_type_units.size ()))
4743         {
4744           complaint (_(".gdb_index entry has bad CU index"
4745                        " [in module %s]"), objfile_name (per_objfile->objfile));
4746           continue;
4747         }
4748
4749       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cutu (cu_index);
4750       dw2_expand_symtabs_matching_one (per_cu, per_objfile, file_matcher,
4751                                        expansion_notify);
4752     }
4753 }
4754
4755 /* If FILE_MATCHER is non-NULL, set all the
4756    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
4757    that match FILE_MATCHER.  */
4758
4759 static void
4760 dw_expand_symtabs_matching_file_matcher
4761   (dwarf2_per_objfile *per_objfile,
4762    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
4763 {
4764   if (file_matcher == NULL)
4765     return;
4766
4767   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4768                                             htab_eq_pointer,
4769                                             NULL, xcalloc, xfree));
4770   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4771                                                 htab_eq_pointer,
4772                                                 NULL, xcalloc, xfree));
4773
4774   /* The rule is CUs specify all the files, including those used by
4775      any TU, so there's no need to scan TUs here.  */
4776
4777   for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
4778     {
4779       QUIT;
4780
4781       per_cu->v.quick->mark = 0;
4782
4783       /* We only need to look at symtabs not already expanded.  */
4784       if (per_objfile->symtab_set_p (per_cu))
4785         continue;
4786
4787       quick_file_names *file_data = dw2_get_file_names (per_cu, per_objfile);
4788       if (file_data == NULL)
4789         continue;
4790
4791       if (htab_find (visited_not_found.get (), file_data) != NULL)
4792         continue;
4793       else if (htab_find (visited_found.get (), file_data) != NULL)
4794         {
4795           per_cu->v.quick->mark = 1;
4796           continue;
4797         }
4798
4799       for (int j = 0; j < file_data->num_file_names; ++j)
4800         {
4801           const char *this_real_name;
4802
4803           if (file_matcher (file_data->file_names[j], false))
4804             {
4805               per_cu->v.quick->mark = 1;
4806               break;
4807             }
4808
4809           /* Before we invoke realpath, which can get expensive when many
4810              files are involved, do a quick comparison of the basenames.  */
4811           if (!basenames_may_differ
4812               && !file_matcher (lbasename (file_data->file_names[j]),
4813                                 true))
4814             continue;
4815
4816           this_real_name = dw2_get_real_path (per_objfile, file_data, j);
4817           if (file_matcher (this_real_name, false))
4818             {
4819               per_cu->v.quick->mark = 1;
4820               break;
4821             }
4822         }
4823
4824       void **slot = htab_find_slot (per_cu->v.quick->mark
4825                                     ? visited_found.get ()
4826                                     : visited_not_found.get (),
4827                                     file_data, INSERT);
4828       *slot = file_data;
4829     }
4830 }
4831
4832 static void
4833 dw2_expand_symtabs_matching
4834   (struct objfile *objfile,
4835    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4836    const lookup_name_info *lookup_name,
4837    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4838    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4839    enum search_domain kind)
4840 {
4841   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4842
4843   /* index_table is NULL if OBJF_READNOW.  */
4844   if (!per_objfile->per_bfd->index_table)
4845     return;
4846
4847   dw_expand_symtabs_matching_file_matcher (per_objfile, file_matcher);
4848
4849   if (symbol_matcher == NULL && lookup_name == NULL)
4850     {
4851       for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
4852         {
4853           QUIT;
4854
4855           dw2_expand_symtabs_matching_one (per_cu, per_objfile,
4856                                            file_matcher, expansion_notify);
4857         }
4858       return;
4859     }
4860
4861   mapped_index &index = *per_objfile->per_bfd->index_table;
4862
4863   dw2_expand_symtabs_matching_symbol (index, *lookup_name,
4864                                       symbol_matcher,
4865                                       [&] (offset_type idx)
4866     {
4867       dw2_expand_marked_cus (per_objfile, idx, file_matcher, expansion_notify,
4868                              kind);
4869       return true;
4870     }, per_objfile);
4871 }
4872
4873 void
4874 dwarf2_gdb_index::expand_symtabs_matching
4875     (struct objfile *objfile,
4876      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4877      const lookup_name_info *lookup_name,
4878      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4879      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4880      enum search_domain kind)
4881 {
4882   dw2_expand_symtabs_matching (objfile, file_matcher, lookup_name,
4883                                symbol_matcher, expansion_notify, kind);
4884 }
4885
4886 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4887    symtab.  */
4888
4889 static struct compunit_symtab *
4890 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4891                                           CORE_ADDR pc)
4892 {
4893   int i;
4894
4895   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4896       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4897     return cust;
4898
4899   if (cust->includes == NULL)
4900     return NULL;
4901
4902   for (i = 0; cust->includes[i]; ++i)
4903     {
4904       struct compunit_symtab *s = cust->includes[i];
4905
4906       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4907       if (s != NULL)
4908         return s;
4909     }
4910
4911   return NULL;
4912 }
4913
4914 struct compunit_symtab *
4915 dwarf2_base_index_functions::find_pc_sect_compunit_symtab
4916      (struct objfile *objfile,
4917       struct bound_minimal_symbol msymbol,
4918       CORE_ADDR pc,
4919       struct obj_section *section,
4920       int warn_if_readin)
4921 {
4922   struct dwarf2_per_cu_data *data;
4923   struct compunit_symtab *result;
4924
4925   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4926   if (per_objfile->per_bfd->index_addrmap == nullptr)
4927     return NULL;
4928
4929   CORE_ADDR baseaddr = objfile->text_section_offset ();
4930   data = ((struct dwarf2_per_cu_data *)
4931           addrmap_find (per_objfile->per_bfd->index_addrmap,
4932                         pc - baseaddr));
4933   if (!data)
4934     return NULL;
4935
4936   if (warn_if_readin && per_objfile->symtab_set_p (data))
4937     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4938              paddress (objfile->arch (), pc));
4939
4940   result = recursively_find_pc_sect_compunit_symtab
4941     (dw2_instantiate_symtab (data, per_objfile, false), pc);
4942
4943   gdb_assert (result != NULL);
4944   return result;
4945 }
4946
4947 void
4948 dwarf2_base_index_functions::map_symbol_filenames (struct objfile *objfile,
4949                                                    symbol_filename_ftype *fun,
4950                                                    void *data,
4951                                                    int need_fullname)
4952 {
4953   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4954
4955   if (!per_objfile->per_bfd->filenames_cache)
4956     {
4957       per_objfile->per_bfd->filenames_cache.emplace ();
4958
4959       htab_up visited (htab_create_alloc (10,
4960                                           htab_hash_pointer, htab_eq_pointer,
4961                                           NULL, xcalloc, xfree));
4962
4963       /* The rule is CUs specify all the files, including those used
4964          by any TU, so there's no need to scan TUs here.  We can
4965          ignore file names coming from already-expanded CUs.  */
4966
4967       for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
4968         {
4969           if (per_objfile->symtab_set_p (per_cu))
4970             {
4971               void **slot = htab_find_slot (visited.get (),
4972                                             per_cu->v.quick->file_names,
4973                                             INSERT);
4974
4975               *slot = per_cu->v.quick->file_names;
4976             }
4977         }
4978
4979       for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
4980         {
4981           /* We only need to look at symtabs not already expanded.  */
4982           if (per_objfile->symtab_set_p (per_cu))
4983             continue;
4984
4985           quick_file_names *file_data
4986             = dw2_get_file_names (per_cu, per_objfile);
4987           if (file_data == NULL)
4988             continue;
4989
4990           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
4991           if (*slot)
4992             {
4993               /* Already visited.  */
4994               continue;
4995             }
4996           *slot = file_data;
4997
4998           for (int j = 0; j < file_data->num_file_names; ++j)
4999             {
5000               const char *filename = file_data->file_names[j];
5001               per_objfile->per_bfd->filenames_cache->seen (filename);
5002             }
5003         }
5004     }
5005
5006   per_objfile->per_bfd->filenames_cache->traverse ([&] (const char *filename)
5007     {
5008       gdb::unique_xmalloc_ptr<char> this_real_name;
5009
5010       if (need_fullname)
5011         this_real_name = gdb_realpath (filename);
5012       (*fun) (filename, this_real_name.get (), data);
5013     });
5014 }
5015
5016 bool
5017 dwarf2_base_index_functions::has_symbols (struct objfile *objfile)
5018 {
5019   return true;
5020 }
5021
5022 /* DWARF-5 debug_names reader.  */
5023
5024 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5025 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5026
5027 /* A helper function that reads the .debug_names section in SECTION
5028    and fills in MAP.  FILENAME is the name of the file containing the
5029    section; it is used for error reporting.
5030
5031    Returns true if all went well, false otherwise.  */
5032
5033 static bool
5034 read_debug_names_from_section (struct objfile *objfile,
5035                                const char *filename,
5036                                struct dwarf2_section_info *section,
5037                                mapped_debug_names &map)
5038 {
5039   if (section->empty ())
5040     return false;
5041
5042   /* Older elfutils strip versions could keep the section in the main
5043      executable while splitting it for the separate debug info file.  */
5044   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5045     return false;
5046
5047   section->read (objfile);
5048
5049   map.dwarf5_byte_order = gdbarch_byte_order (objfile->arch ());
5050
5051   const gdb_byte *addr = section->buffer;
5052
5053   bfd *const abfd = section->get_bfd_owner ();
5054
5055   unsigned int bytes_read;
5056   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5057   addr += bytes_read;
5058
5059   map.dwarf5_is_dwarf64 = bytes_read != 4;
5060   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5061   if (bytes_read + length != section->size)
5062     {
5063       /* There may be multiple per-CU indices.  */
5064       warning (_("Section .debug_names in %s length %s does not match "
5065                  "section length %s, ignoring .debug_names."),
5066                filename, plongest (bytes_read + length),
5067                pulongest (section->size));
5068       return false;
5069     }
5070
5071   /* The version number.  */
5072   uint16_t version = read_2_bytes (abfd, addr);
5073   addr += 2;
5074   if (version != 5)
5075     {
5076       warning (_("Section .debug_names in %s has unsupported version %d, "
5077                  "ignoring .debug_names."),
5078                filename, version);
5079       return false;
5080     }
5081
5082   /* Padding.  */
5083   uint16_t padding = read_2_bytes (abfd, addr);
5084   addr += 2;
5085   if (padding != 0)
5086     {
5087       warning (_("Section .debug_names in %s has unsupported padding %d, "
5088                  "ignoring .debug_names."),
5089                filename, padding);
5090       return false;
5091     }
5092
5093   /* comp_unit_count - The number of CUs in the CU list.  */
5094   map.cu_count = read_4_bytes (abfd, addr);
5095   addr += 4;
5096
5097   /* local_type_unit_count - The number of TUs in the local TU
5098      list.  */
5099   map.tu_count = read_4_bytes (abfd, addr);
5100   addr += 4;
5101
5102   /* foreign_type_unit_count - The number of TUs in the foreign TU
5103      list.  */
5104   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5105   addr += 4;
5106   if (foreign_tu_count != 0)
5107     {
5108       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5109                  "ignoring .debug_names."),
5110                filename, static_cast<unsigned long> (foreign_tu_count));
5111       return false;
5112     }
5113
5114   /* bucket_count - The number of hash buckets in the hash lookup
5115      table.  */
5116   map.bucket_count = read_4_bytes (abfd, addr);
5117   addr += 4;
5118
5119   /* name_count - The number of unique names in the index.  */
5120   map.name_count = read_4_bytes (abfd, addr);
5121   addr += 4;
5122
5123   /* abbrev_table_size - The size in bytes of the abbreviations
5124      table.  */
5125   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5126   addr += 4;
5127
5128   /* augmentation_string_size - The size in bytes of the augmentation
5129      string.  This value is rounded up to a multiple of 4.  */
5130   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5131   addr += 4;
5132   map.augmentation_is_gdb = ((augmentation_string_size
5133                               == sizeof (dwarf5_augmentation))
5134                              && memcmp (addr, dwarf5_augmentation,
5135                                         sizeof (dwarf5_augmentation)) == 0);
5136   augmentation_string_size += (-augmentation_string_size) & 3;
5137   addr += augmentation_string_size;
5138
5139   /* List of CUs */
5140   map.cu_table_reordered = addr;
5141   addr += map.cu_count * map.offset_size;
5142
5143   /* List of Local TUs */
5144   map.tu_table_reordered = addr;
5145   addr += map.tu_count * map.offset_size;
5146
5147   /* Hash Lookup Table */
5148   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5149   addr += map.bucket_count * 4;
5150   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5151   addr += map.name_count * 4;
5152
5153   /* Name Table */
5154   map.name_table_string_offs_reordered = addr;
5155   addr += map.name_count * map.offset_size;
5156   map.name_table_entry_offs_reordered = addr;
5157   addr += map.name_count * map.offset_size;
5158
5159   const gdb_byte *abbrev_table_start = addr;
5160   for (;;)
5161     {
5162       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5163       addr += bytes_read;
5164       if (index_num == 0)
5165         break;
5166
5167       const auto insertpair
5168         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5169       if (!insertpair.second)
5170         {
5171           warning (_("Section .debug_names in %s has duplicate index %s, "
5172                      "ignoring .debug_names."),
5173                    filename, pulongest (index_num));
5174           return false;
5175         }
5176       mapped_debug_names::index_val &indexval = insertpair.first->second;
5177       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5178       addr += bytes_read;
5179
5180       for (;;)
5181         {
5182           mapped_debug_names::index_val::attr attr;
5183           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5184           addr += bytes_read;
5185           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5186           addr += bytes_read;
5187           if (attr.form == DW_FORM_implicit_const)
5188             {
5189               attr.implicit_const = read_signed_leb128 (abfd, addr,
5190                                                         &bytes_read);
5191               addr += bytes_read;
5192             }
5193           if (attr.dw_idx == 0 && attr.form == 0)
5194             break;
5195           indexval.attr_vec.push_back (std::move (attr));
5196         }
5197     }
5198   if (addr != abbrev_table_start + abbrev_table_size)
5199     {
5200       warning (_("Section .debug_names in %s has abbreviation_table "
5201                  "of size %s vs. written as %u, ignoring .debug_names."),
5202                filename, plongest (addr - abbrev_table_start),
5203                abbrev_table_size);
5204       return false;
5205     }
5206   map.entry_pool = addr;
5207
5208   return true;
5209 }
5210
5211 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5212    list.  */
5213
5214 static void
5215 create_cus_from_debug_names_list (dwarf2_per_bfd *per_bfd,
5216                                   const mapped_debug_names &map,
5217                                   dwarf2_section_info &section,
5218                                   bool is_dwz)
5219 {
5220   if (!map.augmentation_is_gdb)
5221     {
5222       for (uint32_t i = 0; i < map.cu_count; ++i)
5223         {
5224           sect_offset sect_off
5225             = (sect_offset) (extract_unsigned_integer
5226                              (map.cu_table_reordered + i * map.offset_size,
5227                               map.offset_size,
5228                               map.dwarf5_byte_order));
5229           /* We don't know the length of the CU, because the CU list in a
5230              .debug_names index can be incomplete, so we can't use the start
5231              of the next CU as end of this CU.  We create the CUs here with
5232              length 0, and in cutu_reader::cutu_reader we'll fill in the
5233              actual length.  */
5234           dwarf2_per_cu_data *per_cu
5235             = create_cu_from_index_list (per_bfd, &section, is_dwz,
5236                                          sect_off, 0);
5237           per_bfd->all_comp_units.push_back (per_cu);
5238         }
5239       return;
5240     }
5241
5242   sect_offset sect_off_prev;
5243   for (uint32_t i = 0; i <= map.cu_count; ++i)
5244     {
5245       sect_offset sect_off_next;
5246       if (i < map.cu_count)
5247         {
5248           sect_off_next
5249             = (sect_offset) (extract_unsigned_integer
5250                              (map.cu_table_reordered + i * map.offset_size,
5251                               map.offset_size,
5252                               map.dwarf5_byte_order));
5253         }
5254       else
5255         sect_off_next = (sect_offset) section.size;
5256       if (i >= 1)
5257         {
5258           const ULONGEST length = sect_off_next - sect_off_prev;
5259           dwarf2_per_cu_data *per_cu
5260             = create_cu_from_index_list (per_bfd, &section, is_dwz,
5261                                          sect_off_prev, length);
5262           per_bfd->all_comp_units.push_back (per_cu);
5263         }
5264       sect_off_prev = sect_off_next;
5265     }
5266 }
5267
5268 /* Read the CU list from the mapped index, and use it to create all
5269    the CU objects for this dwarf2_per_objfile.  */
5270
5271 static void
5272 create_cus_from_debug_names (dwarf2_per_bfd *per_bfd,
5273                              const mapped_debug_names &map,
5274                              const mapped_debug_names &dwz_map)
5275 {
5276   gdb_assert (per_bfd->all_comp_units.empty ());
5277   per_bfd->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5278
5279   create_cus_from_debug_names_list (per_bfd, map, per_bfd->info,
5280                                     false /* is_dwz */);
5281
5282   if (dwz_map.cu_count == 0)
5283     return;
5284
5285   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
5286   create_cus_from_debug_names_list (per_bfd, dwz_map, dwz->info,
5287                                     true /* is_dwz */);
5288 }
5289
5290 /* Read .debug_names.  If everything went ok, initialize the "quick"
5291    elements of all the CUs and return true.  Otherwise, return false.  */
5292
5293 static bool
5294 dwarf2_read_debug_names (dwarf2_per_objfile *per_objfile)
5295 {
5296   std::unique_ptr<mapped_debug_names> map (new mapped_debug_names);
5297   mapped_debug_names dwz_map;
5298   struct objfile *objfile = per_objfile->objfile;
5299   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
5300
5301   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5302                                       &per_bfd->debug_names, *map))
5303     return false;
5304
5305   /* Don't use the index if it's empty.  */
5306   if (map->name_count == 0)
5307     return false;
5308
5309   /* If there is a .dwz file, read it so we can get its CU list as
5310      well.  */
5311   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
5312   if (dwz != NULL)
5313     {
5314       if (!read_debug_names_from_section (objfile,
5315                                           bfd_get_filename (dwz->dwz_bfd.get ()),
5316                                           &dwz->debug_names, dwz_map))
5317         {
5318           warning (_("could not read '.debug_names' section from %s; skipping"),
5319                    bfd_get_filename (dwz->dwz_bfd.get ()));
5320           return false;
5321         }
5322     }
5323
5324   create_cus_from_debug_names (per_bfd, *map, dwz_map);
5325
5326   if (map->tu_count != 0)
5327     {
5328       /* We can only handle a single .debug_types when we have an
5329          index.  */
5330       if (per_bfd->types.size () != 1)
5331         return false;
5332
5333       dwarf2_section_info *section = &per_bfd->types[0];
5334
5335       create_signatured_type_table_from_debug_names
5336         (per_objfile, *map, section, &per_bfd->abbrev);
5337     }
5338
5339   create_addrmap_from_aranges (per_objfile, &per_bfd->debug_aranges);
5340
5341   per_bfd->debug_names_table = std::move (map);
5342   per_bfd->using_index = 1;
5343   per_bfd->quick_file_names_table =
5344     create_quick_file_names_table (per_bfd->all_comp_units.size ());
5345
5346   return true;
5347 }
5348
5349 /* Type used to manage iterating over all CUs looking for a symbol for
5350    .debug_names.  */
5351
5352 class dw2_debug_names_iterator
5353 {
5354 public:
5355   dw2_debug_names_iterator (const mapped_debug_names &map,
5356                             gdb::optional<block_enum> block_index,
5357                             domain_enum domain,
5358                             const char *name, dwarf2_per_objfile *per_objfile)
5359     : m_map (map), m_block_index (block_index), m_domain (domain),
5360       m_addr (find_vec_in_debug_names (map, name, per_objfile)),
5361       m_per_objfile (per_objfile)
5362   {}
5363
5364   dw2_debug_names_iterator (const mapped_debug_names &map,
5365                             search_domain search, uint32_t namei, dwarf2_per_objfile *per_objfile)
5366     : m_map (map),
5367       m_search (search),
5368       m_addr (find_vec_in_debug_names (map, namei, per_objfile)),
5369       m_per_objfile (per_objfile)
5370   {}
5371
5372   dw2_debug_names_iterator (const mapped_debug_names &map,
5373                             block_enum block_index, domain_enum domain,
5374                             uint32_t namei, dwarf2_per_objfile *per_objfile)
5375     : m_map (map), m_block_index (block_index), m_domain (domain),
5376       m_addr (find_vec_in_debug_names (map, namei, per_objfile)),
5377       m_per_objfile (per_objfile)
5378   {}
5379
5380   /* Return the next matching CU or NULL if there are no more.  */
5381   dwarf2_per_cu_data *next ();
5382
5383 private:
5384   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5385                                                   const char *name,
5386                                                   dwarf2_per_objfile *per_objfile);
5387   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5388                                                   uint32_t namei,
5389                                                   dwarf2_per_objfile *per_objfile);
5390
5391   /* The internalized form of .debug_names.  */
5392   const mapped_debug_names &m_map;
5393
5394   /* If set, only look for symbols that match that block.  Valid values are
5395      GLOBAL_BLOCK and STATIC_BLOCK.  */
5396   const gdb::optional<block_enum> m_block_index;
5397
5398   /* The kind of symbol we're looking for.  */
5399   const domain_enum m_domain = UNDEF_DOMAIN;
5400   const search_domain m_search = ALL_DOMAIN;
5401
5402   /* The list of CUs from the index entry of the symbol, or NULL if
5403      not found.  */
5404   const gdb_byte *m_addr;
5405
5406   dwarf2_per_objfile *m_per_objfile;
5407 };
5408
5409 const char *
5410 mapped_debug_names::namei_to_name
5411   (uint32_t namei, dwarf2_per_objfile *per_objfile) const
5412 {
5413   const ULONGEST namei_string_offs
5414     = extract_unsigned_integer ((name_table_string_offs_reordered
5415                                  + namei * offset_size),
5416                                 offset_size,
5417                                 dwarf5_byte_order);
5418   return read_indirect_string_at_offset (per_objfile, namei_string_offs);
5419 }
5420
5421 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5422    found, return pointer to its pool data.  If NAME cannot be found,
5423    return NULL.  */
5424
5425 const gdb_byte *
5426 dw2_debug_names_iterator::find_vec_in_debug_names
5427   (const mapped_debug_names &map, const char *name,
5428    dwarf2_per_objfile *per_objfile)
5429 {
5430   int (*cmp) (const char *, const char *);
5431
5432   gdb::unique_xmalloc_ptr<char> without_params;
5433   if (current_language->la_language == language_cplus
5434       || current_language->la_language == language_fortran
5435       || current_language->la_language == language_d)
5436     {
5437       /* NAME is already canonical.  Drop any qualifiers as
5438          .debug_names does not contain any.  */
5439
5440       if (strchr (name, '(') != NULL)
5441         {
5442           without_params = cp_remove_params (name);
5443           if (without_params != NULL)
5444             name = without_params.get ();
5445         }
5446     }
5447
5448   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5449
5450   const uint32_t full_hash = dwarf5_djb_hash (name);
5451   uint32_t namei
5452     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5453                                 (map.bucket_table_reordered
5454                                  + (full_hash % map.bucket_count)), 4,
5455                                 map.dwarf5_byte_order);
5456   if (namei == 0)
5457     return NULL;
5458   --namei;
5459   if (namei >= map.name_count)
5460     {
5461       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5462                    "[in module %s]"),
5463                  namei, map.name_count,
5464                  objfile_name (per_objfile->objfile));
5465       return NULL;
5466     }
5467
5468   for (;;)
5469     {
5470       const uint32_t namei_full_hash
5471         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5472                                     (map.hash_table_reordered + namei), 4,
5473                                     map.dwarf5_byte_order);
5474       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5475         return NULL;
5476
5477       if (full_hash == namei_full_hash)
5478         {
5479           const char *const namei_string = map.namei_to_name (namei, per_objfile);
5480
5481 #if 0 /* An expensive sanity check.  */
5482           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5483             {
5484               complaint (_("Wrong .debug_names hash for string at index %u "
5485                            "[in module %s]"),
5486                          namei, objfile_name (dwarf2_per_objfile->objfile));
5487               return NULL;
5488             }
5489 #endif
5490
5491           if (cmp (namei_string, name) == 0)
5492             {
5493               const ULONGEST namei_entry_offs
5494                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5495                                              + namei * map.offset_size),
5496                                             map.offset_size, map.dwarf5_byte_order);
5497               return map.entry_pool + namei_entry_offs;
5498             }
5499         }
5500
5501       ++namei;
5502       if (namei >= map.name_count)
5503         return NULL;
5504     }
5505 }
5506
5507 const gdb_byte *
5508 dw2_debug_names_iterator::find_vec_in_debug_names
5509   (const mapped_debug_names &map, uint32_t namei, dwarf2_per_objfile *per_objfile)
5510 {
5511   if (namei >= map.name_count)
5512     {
5513       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5514                    "[in module %s]"),
5515                  namei, map.name_count,
5516                  objfile_name (per_objfile->objfile));
5517       return NULL;
5518     }
5519
5520   const ULONGEST namei_entry_offs
5521     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5522                                  + namei * map.offset_size),
5523                                 map.offset_size, map.dwarf5_byte_order);
5524   return map.entry_pool + namei_entry_offs;
5525 }
5526
5527 /* See dw2_debug_names_iterator.  */
5528
5529 dwarf2_per_cu_data *
5530 dw2_debug_names_iterator::next ()
5531 {
5532   if (m_addr == NULL)
5533     return NULL;
5534
5535   dwarf2_per_bfd *per_bfd = m_per_objfile->per_bfd;
5536   struct objfile *objfile = m_per_objfile->objfile;
5537   bfd *const abfd = objfile->obfd;
5538
5539  again:
5540
5541   unsigned int bytes_read;
5542   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5543   m_addr += bytes_read;
5544   if (abbrev == 0)
5545     return NULL;
5546
5547   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5548   if (indexval_it == m_map.abbrev_map.cend ())
5549     {
5550       complaint (_("Wrong .debug_names undefined abbrev code %s "
5551                    "[in module %s]"),
5552                  pulongest (abbrev), objfile_name (objfile));
5553       return NULL;
5554     }
5555   const mapped_debug_names::index_val &indexval = indexval_it->second;
5556   enum class symbol_linkage {
5557     unknown,
5558     static_,
5559     extern_,
5560   } symbol_linkage_ = symbol_linkage::unknown;
5561   dwarf2_per_cu_data *per_cu = NULL;
5562   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5563     {
5564       ULONGEST ull;
5565       switch (attr.form)
5566         {
5567         case DW_FORM_implicit_const:
5568           ull = attr.implicit_const;
5569           break;
5570         case DW_FORM_flag_present:
5571           ull = 1;
5572           break;
5573         case DW_FORM_udata:
5574           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5575           m_addr += bytes_read;
5576           break;
5577         case DW_FORM_ref4:
5578           ull = read_4_bytes (abfd, m_addr);
5579           m_addr += 4;
5580           break;
5581         case DW_FORM_ref8:
5582           ull = read_8_bytes (abfd, m_addr);
5583           m_addr += 8;
5584           break;
5585         case DW_FORM_ref_sig8:
5586           ull = read_8_bytes (abfd, m_addr);
5587           m_addr += 8;
5588           break;
5589         default:
5590           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5591                      dwarf_form_name (attr.form),
5592                      objfile_name (objfile));
5593           return NULL;
5594         }
5595       switch (attr.dw_idx)
5596         {
5597         case DW_IDX_compile_unit:
5598           /* Don't crash on bad data.  */
5599           if (ull >= per_bfd->all_comp_units.size ())
5600             {
5601               complaint (_(".debug_names entry has bad CU index %s"
5602                            " [in module %s]"),
5603                          pulongest (ull),
5604                          objfile_name (objfile));
5605               continue;
5606             }
5607           per_cu = per_bfd->get_cutu (ull);
5608           break;
5609         case DW_IDX_type_unit:
5610           /* Don't crash on bad data.  */
5611           if (ull >= per_bfd->all_type_units.size ())
5612             {
5613               complaint (_(".debug_names entry has bad TU index %s"
5614                            " [in module %s]"),
5615                          pulongest (ull),
5616                          objfile_name (objfile));
5617               continue;
5618             }
5619           per_cu = &per_bfd->get_tu (ull)->per_cu;
5620           break;
5621         case DW_IDX_die_offset:
5622           /* In a per-CU index (as opposed to a per-module index), index
5623              entries without CU attribute implicitly refer to the single CU.  */
5624           if (per_cu == NULL)
5625             per_cu = per_bfd->get_cu (0);
5626           break;
5627         case DW_IDX_GNU_internal:
5628           if (!m_map.augmentation_is_gdb)
5629             break;
5630           symbol_linkage_ = symbol_linkage::static_;
5631           break;
5632         case DW_IDX_GNU_external:
5633           if (!m_map.augmentation_is_gdb)
5634             break;
5635           symbol_linkage_ = symbol_linkage::extern_;
5636           break;
5637         }
5638     }
5639
5640   /* Skip if already read in.  */
5641   if (m_per_objfile->symtab_set_p (per_cu))
5642     goto again;
5643
5644   /* Check static vs global.  */
5645   if (symbol_linkage_ != symbol_linkage::unknown && m_block_index.has_value ())
5646     {
5647         const bool want_static = *m_block_index == STATIC_BLOCK;
5648         const bool symbol_is_static =
5649           symbol_linkage_ == symbol_linkage::static_;
5650         if (want_static != symbol_is_static)
5651           goto again;
5652     }
5653
5654   /* Match dw2_symtab_iter_next, symbol_kind
5655      and debug_names::psymbol_tag.  */
5656   switch (m_domain)
5657     {
5658     case VAR_DOMAIN:
5659       switch (indexval.dwarf_tag)
5660         {
5661         case DW_TAG_variable:
5662         case DW_TAG_subprogram:
5663         /* Some types are also in VAR_DOMAIN.  */
5664         case DW_TAG_typedef:
5665         case DW_TAG_structure_type:
5666           break;
5667         default:
5668           goto again;
5669         }
5670       break;
5671     case STRUCT_DOMAIN:
5672       switch (indexval.dwarf_tag)
5673         {
5674         case DW_TAG_typedef:
5675         case DW_TAG_structure_type:
5676           break;
5677         default:
5678           goto again;
5679         }
5680       break;
5681     case LABEL_DOMAIN:
5682       switch (indexval.dwarf_tag)
5683         {
5684         case 0:
5685         case DW_TAG_variable:
5686           break;
5687         default:
5688           goto again;
5689         }
5690       break;
5691     case MODULE_DOMAIN:
5692       switch (indexval.dwarf_tag)
5693         {
5694         case DW_TAG_module:
5695           break;
5696         default:
5697           goto again;
5698         }
5699       break;
5700     default:
5701       break;
5702     }
5703
5704   /* Match dw2_expand_symtabs_matching, symbol_kind and
5705      debug_names::psymbol_tag.  */
5706   switch (m_search)
5707     {
5708     case VARIABLES_DOMAIN:
5709       switch (indexval.dwarf_tag)
5710         {
5711         case DW_TAG_variable:
5712           break;
5713         default:
5714           goto again;
5715         }
5716       break;
5717     case FUNCTIONS_DOMAIN:
5718       switch (indexval.dwarf_tag)
5719         {
5720         case DW_TAG_subprogram:
5721           break;
5722         default:
5723           goto again;
5724         }
5725       break;
5726     case TYPES_DOMAIN:
5727       switch (indexval.dwarf_tag)
5728         {
5729         case DW_TAG_typedef:
5730         case DW_TAG_structure_type:
5731           break;
5732         default:
5733           goto again;
5734         }
5735       break;
5736     case MODULES_DOMAIN:
5737       switch (indexval.dwarf_tag)
5738         {
5739         case DW_TAG_module:
5740           break;
5741         default:
5742           goto again;
5743         }
5744     default:
5745       break;
5746     }
5747
5748   return per_cu;
5749 }
5750
5751 struct compunit_symtab *
5752 dwarf2_debug_names_index::lookup_symbol
5753      (struct objfile *objfile, block_enum block_index,
5754       const char *name, domain_enum domain)
5755 {
5756   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5757
5758   const auto &mapp = per_objfile->per_bfd->debug_names_table;
5759   if (!mapp)
5760     {
5761       /* index is NULL if OBJF_READNOW.  */
5762       return NULL;
5763     }
5764   const auto &map = *mapp;
5765
5766   dw2_debug_names_iterator iter (map, block_index, domain, name, per_objfile);
5767
5768   struct compunit_symtab *stab_best = NULL;
5769   struct dwarf2_per_cu_data *per_cu;
5770   while ((per_cu = iter.next ()) != NULL)
5771     {
5772       struct symbol *sym, *with_opaque = NULL;
5773       compunit_symtab *stab
5774         = dw2_instantiate_symtab (per_cu, per_objfile, false);
5775       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
5776       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
5777
5778       sym = block_find_symbol (block, name, domain,
5779                                block_find_non_opaque_type_preferred,
5780                                &with_opaque);
5781
5782       /* Some caution must be observed with overloaded functions and
5783          methods, since the index will not contain any overload
5784          information (but NAME might contain it).  */
5785
5786       if (sym != NULL
5787           && strcmp_iw (sym->search_name (), name) == 0)
5788         return stab;
5789       if (with_opaque != NULL
5790           && strcmp_iw (with_opaque->search_name (), name) == 0)
5791         stab_best = stab;
5792
5793       /* Keep looking through other CUs.  */
5794     }
5795
5796   return stab_best;
5797 }
5798
5799 /* This dumps minimal information about .debug_names.  It is called
5800    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
5801    uses this to verify that .debug_names has been loaded.  */
5802
5803 void
5804 dwarf2_debug_names_index::dump (struct objfile *objfile)
5805 {
5806   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5807
5808   gdb_assert (per_objfile->per_bfd->using_index);
5809   printf_filtered (".debug_names:");
5810   if (per_objfile->per_bfd->debug_names_table)
5811     printf_filtered (" exists\n");
5812   else
5813     printf_filtered (" faked for \"readnow\"\n");
5814   printf_filtered ("\n");
5815 }
5816
5817 void
5818 dwarf2_debug_names_index::expand_symtabs_for_function
5819      (struct objfile *objfile, const char *func_name)
5820 {
5821   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5822
5823   /* per_objfile->per_bfd->debug_names_table is NULL if OBJF_READNOW.  */
5824   if (per_objfile->per_bfd->debug_names_table)
5825     {
5826       const mapped_debug_names &map = *per_objfile->per_bfd->debug_names_table;
5827
5828       dw2_debug_names_iterator iter (map, {}, VAR_DOMAIN, func_name,
5829                                      per_objfile);
5830
5831       struct dwarf2_per_cu_data *per_cu;
5832       while ((per_cu = iter.next ()) != NULL)
5833         dw2_instantiate_symtab (per_cu, per_objfile, false);
5834     }
5835 }
5836
5837 void
5838 dwarf2_debug_names_index::map_matching_symbols
5839   (struct objfile *objfile,
5840    const lookup_name_info &name, domain_enum domain,
5841    int global,
5842    gdb::function_view<symbol_found_callback_ftype> callback,
5843    symbol_compare_ftype *ordered_compare)
5844 {
5845   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5846
5847   /* debug_names_table is NULL if OBJF_READNOW.  */
5848   if (!per_objfile->per_bfd->debug_names_table)
5849     return;
5850
5851   mapped_debug_names &map = *per_objfile->per_bfd->debug_names_table;
5852   const block_enum block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5853
5854   const char *match_name = name.ada ().lookup_name ().c_str ();
5855   auto matcher = [&] (const char *symname)
5856     {
5857       if (ordered_compare == nullptr)
5858         return true;
5859       return ordered_compare (symname, match_name) == 0;
5860     };
5861
5862   dw2_expand_symtabs_matching_symbol (map, name, matcher,
5863                                       [&] (offset_type namei)
5864     {
5865       /* The name was matched, now expand corresponding CUs that were
5866          marked.  */
5867       dw2_debug_names_iterator iter (map, block_kind, domain, namei,
5868                                      per_objfile);
5869
5870       struct dwarf2_per_cu_data *per_cu;
5871       while ((per_cu = iter.next ()) != NULL)
5872         dw2_expand_symtabs_matching_one (per_cu, per_objfile, nullptr,
5873                                          nullptr);
5874       return true;
5875     }, per_objfile);
5876
5877   /* It's a shame we couldn't do this inside the
5878      dw2_expand_symtabs_matching_symbol callback, but that skips CUs
5879      that have already been expanded.  Instead, this loop matches what
5880      the psymtab code does.  */
5881   for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
5882     {
5883       compunit_symtab *symtab = per_objfile->get_symtab (per_cu);
5884       if (symtab != nullptr)
5885         {
5886           const struct block *block
5887             = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (symtab), block_kind);
5888           if (!iterate_over_symbols_terminated (block, name,
5889                                                 domain, callback))
5890             break;
5891         }
5892     }
5893 }
5894
5895 void
5896 dwarf2_debug_names_index::expand_symtabs_matching
5897   (struct objfile *objfile,
5898    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5899    const lookup_name_info *lookup_name,
5900    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5901    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5902    enum search_domain kind)
5903 {
5904   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5905
5906   /* debug_names_table is NULL if OBJF_READNOW.  */
5907   if (!per_objfile->per_bfd->debug_names_table)
5908     return;
5909
5910   dw_expand_symtabs_matching_file_matcher (per_objfile, file_matcher);
5911
5912   if (symbol_matcher == NULL && lookup_name == NULL)
5913     {
5914       for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
5915         {
5916           QUIT;
5917
5918           dw2_expand_symtabs_matching_one (per_cu, per_objfile, file_matcher,
5919                                            expansion_notify);
5920         }
5921       return;
5922     }
5923
5924   mapped_debug_names &map = *per_objfile->per_bfd->debug_names_table;
5925
5926   dw2_expand_symtabs_matching_symbol (map, *lookup_name,
5927                                       symbol_matcher,
5928                                       [&] (offset_type namei)
5929     {
5930       /* The name was matched, now expand corresponding CUs that were
5931          marked.  */
5932       dw2_debug_names_iterator iter (map, kind, namei, per_objfile);
5933
5934       struct dwarf2_per_cu_data *per_cu;
5935       while ((per_cu = iter.next ()) != NULL)
5936         dw2_expand_symtabs_matching_one (per_cu, per_objfile, file_matcher,
5937                                          expansion_notify);
5938       return true;
5939     }, per_objfile);
5940 }
5941
5942 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
5943    to either a dwarf2_per_bfd or dwz_file object.  */
5944
5945 template <typename T>
5946 static gdb::array_view<const gdb_byte>
5947 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
5948 {
5949   dwarf2_section_info *section = &section_owner->gdb_index;
5950
5951   if (section->empty ())
5952     return {};
5953
5954   /* Older elfutils strip versions could keep the section in the main
5955      executable while splitting it for the separate debug info file.  */
5956   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5957     return {};
5958
5959   section->read (obj);
5960
5961   /* dwarf2_section_info::size is a bfd_size_type, while
5962      gdb::array_view works with size_t.  On 32-bit hosts, with
5963      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
5964      is 32-bit.  So we need an explicit narrowing conversion here.
5965      This is fine, because it's impossible to allocate or mmap an
5966      array/buffer larger than what size_t can represent.  */
5967   return gdb::make_array_view (section->buffer, section->size);
5968 }
5969
5970 /* Lookup the index cache for the contents of the index associated to
5971    DWARF2_OBJ.  */
5972
5973 static gdb::array_view<const gdb_byte>
5974 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_bfd *dwarf2_per_bfd)
5975 {
5976   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
5977   if (build_id == nullptr)
5978     return {};
5979
5980   return global_index_cache.lookup_gdb_index (build_id,
5981                                               &dwarf2_per_bfd->index_cache_res);
5982 }
5983
5984 /* Same as the above, but for DWZ.  */
5985
5986 static gdb::array_view<const gdb_byte>
5987 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
5988 {
5989   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
5990   if (build_id == nullptr)
5991     return {};
5992
5993   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
5994 }
5995
5996 /* See symfile.h.  */
5997
5998 bool
5999 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6000 {
6001   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
6002   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
6003
6004   dwarf_read_debug_printf ("called");
6005
6006   /* If we're about to read full symbols, don't bother with the
6007      indices.  In this case we also don't care if some other debug
6008      format is making psymtabs, because they are all about to be
6009      expanded anyway.  */
6010   if ((objfile->flags & OBJF_READNOW))
6011     {
6012       dwarf_read_debug_printf ("readnow requested");
6013
6014       /* When using READNOW, the using_index flag (set below) indicates that
6015          PER_BFD was already initialized, when we loaded some other objfile.  */
6016       if (per_bfd->using_index)
6017         {
6018           dwarf_read_debug_printf ("using_index already set");
6019           *index_kind = dw_index_kind::GDB_INDEX;
6020           per_objfile->resize_symtabs ();
6021           return true;
6022         }
6023
6024       per_bfd->using_index = 1;
6025       create_all_comp_units (per_objfile);
6026       create_all_type_units (per_objfile);
6027       per_bfd->quick_file_names_table
6028         = create_quick_file_names_table (per_bfd->all_comp_units.size ());
6029       per_objfile->resize_symtabs ();
6030
6031       for (int i = 0; i < (per_bfd->all_comp_units.size ()
6032                            + per_bfd->all_type_units.size ()); ++i)
6033         {
6034           dwarf2_per_cu_data *per_cu = per_bfd->get_cutu (i);
6035
6036           per_cu->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
6037                                             struct dwarf2_per_cu_quick_data);
6038         }
6039
6040       /* Return 1 so that gdb sees the "quick" functions.  However,
6041          these functions will be no-ops because we will have expanded
6042          all symtabs.  */
6043       *index_kind = dw_index_kind::GDB_INDEX;
6044       return true;
6045     }
6046
6047   /* Was a debug names index already read when we processed an objfile sharing
6048      PER_BFD?  */
6049   if (per_bfd->debug_names_table != nullptr)
6050     {
6051       dwarf_read_debug_printf ("re-using shared debug names table");
6052       *index_kind = dw_index_kind::DEBUG_NAMES;
6053       per_objfile->resize_symtabs ();
6054       return true;
6055     }
6056
6057   /* Was a GDB index already read when we processed an objfile sharing
6058      PER_BFD?  */
6059   if (per_bfd->index_table != nullptr)
6060     {
6061       dwarf_read_debug_printf ("re-using shared index table");
6062       *index_kind = dw_index_kind::GDB_INDEX;
6063       per_objfile->resize_symtabs ();
6064       return true;
6065     }
6066
6067   /* There might already be partial symtabs built for this BFD.  This happens
6068      when loading the same binary twice with the index-cache enabled.  If so,
6069      don't try to read an index.  The objfile / per_objfile initialization will
6070      be completed in dwarf2_build_psymtabs, in the standard partial symtabs
6071      code path.  */
6072   if (per_bfd->partial_symtabs != nullptr)
6073     {
6074       dwarf_read_debug_printf ("re-using shared partial symtabs");
6075       return false;
6076     }
6077
6078   if (dwarf2_read_debug_names (per_objfile))
6079     {
6080       dwarf_read_debug_printf ("found debug names");
6081       *index_kind = dw_index_kind::DEBUG_NAMES;
6082       per_objfile->resize_symtabs ();
6083       return true;
6084     }
6085
6086   if (dwarf2_read_gdb_index (per_objfile,
6087                              get_gdb_index_contents_from_section<struct dwarf2_per_bfd>,
6088                              get_gdb_index_contents_from_section<dwz_file>))
6089     {
6090       dwarf_read_debug_printf ("found gdb index from file");
6091       *index_kind = dw_index_kind::GDB_INDEX;
6092       per_objfile->resize_symtabs ();
6093       return true;
6094     }
6095
6096   /* ... otherwise, try to find the index in the index cache.  */
6097   if (dwarf2_read_gdb_index (per_objfile,
6098                              get_gdb_index_contents_from_cache,
6099                              get_gdb_index_contents_from_cache_dwz))
6100     {
6101       dwarf_read_debug_printf ("found gdb index from cache");
6102       global_index_cache.hit ();
6103       *index_kind = dw_index_kind::GDB_INDEX;
6104       per_objfile->resize_symtabs ();
6105       return true;
6106     }
6107
6108   global_index_cache.miss ();
6109   return false;
6110 }
6111
6112 \f
6113
6114 /* Build a partial symbol table.  */
6115
6116 void
6117 dwarf2_build_psymtabs (struct objfile *objfile, psymbol_functions *psf)
6118 {
6119   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
6120   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
6121
6122   if (per_bfd->partial_symtabs != nullptr)
6123     {
6124       /* Partial symbols were already read, so now we can simply
6125          attach them.  */
6126       if (psf == nullptr)
6127         {
6128           psf = new psymbol_functions (per_bfd->partial_symtabs);
6129           objfile->qf.emplace_front (psf);
6130         }
6131       else
6132         psf->set_partial_symtabs (per_bfd->partial_symtabs);
6133       per_objfile->resize_symtabs ();
6134       return;
6135     }
6136
6137   if (psf == nullptr)
6138     {
6139       psf = new psymbol_functions;
6140       objfile->qf.emplace_front (psf);
6141     }
6142   const std::shared_ptr<psymtab_storage> &partial_symtabs
6143     = psf->get_partial_symtabs ();
6144
6145   /* Set the local reference to partial symtabs, so that we don't try
6146      to read them again if reading another objfile with the same BFD.
6147      If we can't in fact share, this won't make a difference anyway as
6148      the dwarf2_per_bfd object won't be shared.  */
6149   per_bfd->partial_symtabs = partial_symtabs;
6150
6151   try
6152     {
6153       /* This isn't really ideal: all the data we allocate on the
6154          objfile's obstack is still uselessly kept around.  However,
6155          freeing it seems unsafe.  */
6156       psymtab_discarder psymtabs (partial_symtabs.get ());
6157       dwarf2_build_psymtabs_hard (per_objfile);
6158       psymtabs.keep ();
6159
6160       per_objfile->resize_symtabs ();
6161
6162       /* (maybe) store an index in the cache.  */
6163       global_index_cache.store (per_objfile);
6164     }
6165   catch (const gdb_exception_error &except)
6166     {
6167       exception_print (gdb_stderr, except);
6168     }
6169 }
6170
6171 /* Find the base address of the compilation unit for range lists and
6172    location lists.  It will normally be specified by DW_AT_low_pc.
6173    In DWARF-3 draft 4, the base address could be overridden by
6174    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6175    compilation units with discontinuous ranges.  */
6176
6177 static void
6178 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6179 {
6180   struct attribute *attr;
6181
6182   cu->base_address.reset ();
6183
6184   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6185   if (attr != nullptr)
6186     cu->base_address = attr->as_address ();
6187   else
6188     {
6189       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6190       if (attr != nullptr)
6191         cu->base_address = attr->as_address ();
6192     }
6193 }
6194
6195 /* Helper function that returns the proper abbrev section for
6196    THIS_CU.  */
6197
6198 static struct dwarf2_section_info *
6199 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6200 {
6201   struct dwarf2_section_info *abbrev;
6202   dwarf2_per_bfd *per_bfd = this_cu->per_bfd;
6203
6204   if (this_cu->is_dwz)
6205     abbrev = &dwarf2_get_dwz_file (per_bfd, true)->abbrev;
6206   else
6207     abbrev = &per_bfd->abbrev;
6208
6209   return abbrev;
6210 }
6211
6212 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6213
6214 static sect_offset
6215 read_abbrev_offset (dwarf2_per_objfile *per_objfile,
6216                     struct dwarf2_section_info *section,
6217                     sect_offset sect_off)
6218 {
6219   bfd *abfd = section->get_bfd_owner ();
6220   const gdb_byte *info_ptr;
6221   unsigned int initial_length_size, offset_size;
6222   uint16_t version;
6223
6224   section->read (per_objfile->objfile);
6225   info_ptr = section->buffer + to_underlying (sect_off);
6226   read_initial_length (abfd, info_ptr, &initial_length_size);
6227   offset_size = initial_length_size == 4 ? 4 : 8;
6228   info_ptr += initial_length_size;
6229
6230   version = read_2_bytes (abfd, info_ptr);
6231   info_ptr += 2;
6232   if (version >= 5)
6233     {
6234       /* Skip unit type and address size.  */
6235       info_ptr += 2;
6236     }
6237
6238   return (sect_offset) read_offset (abfd, info_ptr, offset_size);
6239 }
6240
6241 /* A partial symtab that is used only for include files.  */
6242 struct dwarf2_include_psymtab : public partial_symtab
6243 {
6244   dwarf2_include_psymtab (const char *filename,
6245                           psymtab_storage *partial_symtabs,
6246                           struct objfile *objfile)
6247     : partial_symtab (filename, partial_symtabs, objfile)
6248   {
6249   }
6250
6251   void read_symtab (struct objfile *objfile) override
6252   {
6253     /* It's an include file, no symbols to read for it.
6254        Everything is in the includer symtab.  */
6255
6256     /* The expansion of a dwarf2_include_psymtab is just a trigger for
6257        expansion of the includer psymtab.  We use the dependencies[0] field to
6258        model the includer.  But if we go the regular route of calling
6259        expand_psymtab here, and having expand_psymtab call expand_dependencies
6260        to expand the includer, we'll only use expand_psymtab on the includer
6261        (making it a non-toplevel psymtab), while if we expand the includer via
6262        another path, we'll use read_symtab (making it a toplevel psymtab).
6263        So, don't pretend a dwarf2_include_psymtab is an actual toplevel
6264        psymtab, and trigger read_symtab on the includer here directly.  */
6265     includer ()->read_symtab (objfile);
6266   }
6267
6268   void expand_psymtab (struct objfile *objfile) override
6269   {
6270     /* This is not called by read_symtab, and should not be called by any
6271        expand_dependencies.  */
6272     gdb_assert (false);
6273   }
6274
6275   bool readin_p (struct objfile *objfile) const override
6276   {
6277     return includer ()->readin_p (objfile);
6278   }
6279
6280   compunit_symtab *get_compunit_symtab (struct objfile *objfile) const override
6281   {
6282     return nullptr;
6283   }
6284
6285 private:
6286   partial_symtab *includer () const
6287   {
6288     /* An include psymtab has exactly one dependency: the psymtab that
6289        includes it.  */
6290     gdb_assert (this->number_of_dependencies == 1);
6291     return this->dependencies[0];
6292   }
6293 };
6294
6295 /* Allocate a new partial symtab for file named NAME and mark this new
6296    partial symtab as being an include of PST.  */
6297
6298 static void
6299 dwarf2_create_include_psymtab (dwarf2_per_bfd *per_bfd,
6300                                const char *name,
6301                                dwarf2_psymtab *pst,
6302                                psymtab_storage *partial_symtabs,
6303                                struct objfile *objfile)
6304 {
6305   dwarf2_include_psymtab *subpst
6306     = new dwarf2_include_psymtab (name, partial_symtabs, objfile);
6307
6308   if (!IS_ABSOLUTE_PATH (subpst->filename))
6309     subpst->dirname = pst->dirname;
6310
6311   subpst->dependencies = per_bfd->partial_symtabs->allocate_dependencies (1);
6312   subpst->dependencies[0] = pst;
6313   subpst->number_of_dependencies = 1;
6314 }
6315
6316 /* Read the Line Number Program data and extract the list of files
6317    included by the source file represented by PST.  Build an include
6318    partial symtab for each of these included files.  */
6319
6320 static void
6321 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6322                                struct die_info *die,
6323                                dwarf2_psymtab *pst)
6324 {
6325   line_header_up lh;
6326   struct attribute *attr;
6327
6328   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6329   if (attr != nullptr && attr->form_is_unsigned ())
6330     lh = dwarf_decode_line_header ((sect_offset) attr->as_unsigned (), cu);
6331   if (lh == NULL)
6332     return;  /* No linetable, so no includes.  */
6333
6334   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6335      that we pass in the raw text_low here; that is ok because we're
6336      only decoding the line table to make include partial symtabs, and
6337      so the addresses aren't really used.  */
6338   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6339                       pst->raw_text_low (), 1);
6340 }
6341
6342 static hashval_t
6343 hash_signatured_type (const void *item)
6344 {
6345   const struct signatured_type *sig_type
6346     = (const struct signatured_type *) item;
6347
6348   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6349   return sig_type->signature;
6350 }
6351
6352 static int
6353 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6354 {
6355   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6356   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6357
6358   return lhs->signature == rhs->signature;
6359 }
6360
6361 /* Allocate a hash table for signatured types.  */
6362
6363 static htab_up
6364 allocate_signatured_type_table ()
6365 {
6366   return htab_up (htab_create_alloc (41,
6367                                      hash_signatured_type,
6368                                      eq_signatured_type,
6369                                      NULL, xcalloc, xfree));
6370 }
6371
6372 /* A helper function to add a signatured type CU to a table.  */
6373
6374 static int
6375 add_signatured_type_cu_to_table (void **slot, void *datum)
6376 {
6377   struct signatured_type *sigt = (struct signatured_type *) *slot;
6378   std::vector<signatured_type *> *all_type_units
6379     = (std::vector<signatured_type *> *) datum;
6380
6381   all_type_units->push_back (sigt);
6382
6383   return 1;
6384 }
6385
6386 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6387    and fill them into TYPES_HTAB.  It will process only type units,
6388    therefore DW_UT_type.  */
6389
6390 static void
6391 create_debug_type_hash_table (dwarf2_per_objfile *per_objfile,
6392                               struct dwo_file *dwo_file,
6393                               dwarf2_section_info *section, htab_up &types_htab,
6394                               rcuh_kind section_kind)
6395 {
6396   struct objfile *objfile = per_objfile->objfile;
6397   struct dwarf2_section_info *abbrev_section;
6398   bfd *abfd;
6399   const gdb_byte *info_ptr, *end_ptr;
6400
6401   abbrev_section = (dwo_file != NULL
6402                     ? &dwo_file->sections.abbrev
6403                     : &per_objfile->per_bfd->abbrev);
6404
6405   dwarf_read_debug_printf ("Reading %s for %s",
6406                            section->get_name (),
6407                            abbrev_section->get_file_name ());
6408
6409   section->read (objfile);
6410   info_ptr = section->buffer;
6411
6412   if (info_ptr == NULL)
6413     return;
6414
6415   /* We can't set abfd until now because the section may be empty or
6416      not present, in which case the bfd is unknown.  */
6417   abfd = section->get_bfd_owner ();
6418
6419   /* We don't use cutu_reader here because we don't need to read
6420      any dies: the signature is in the header.  */
6421
6422   end_ptr = info_ptr + section->size;
6423   while (info_ptr < end_ptr)
6424     {
6425       struct signatured_type *sig_type;
6426       struct dwo_unit *dwo_tu;
6427       void **slot;
6428       const gdb_byte *ptr = info_ptr;
6429       struct comp_unit_head header;
6430       unsigned int length;
6431
6432       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6433
6434       /* Initialize it due to a false compiler warning.  */
6435       header.signature = -1;
6436       header.type_cu_offset_in_tu = (cu_offset) -1;
6437
6438       /* We need to read the type's signature in order to build the hash
6439          table, but we don't need anything else just yet.  */
6440
6441       ptr = read_and_check_comp_unit_head (per_objfile, &header, section,
6442                                            abbrev_section, ptr, section_kind);
6443
6444       length = header.get_length ();
6445
6446       /* Skip dummy type units.  */
6447       if (ptr >= info_ptr + length
6448           || peek_abbrev_code (abfd, ptr) == 0
6449           || (header.unit_type != DW_UT_type
6450               && header.unit_type != DW_UT_split_type))
6451         {
6452           info_ptr += length;
6453           continue;
6454         }
6455
6456       if (types_htab == NULL)
6457         {
6458           if (dwo_file)
6459             types_htab = allocate_dwo_unit_table ();
6460           else
6461             types_htab = allocate_signatured_type_table ();
6462         }
6463
6464       if (dwo_file)
6465         {
6466           sig_type = NULL;
6467           dwo_tu = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, dwo_unit);
6468           dwo_tu->dwo_file = dwo_file;
6469           dwo_tu->signature = header.signature;
6470           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6471           dwo_tu->section = section;
6472           dwo_tu->sect_off = sect_off;
6473           dwo_tu->length = length;
6474         }
6475       else
6476         {
6477           /* N.B.: type_offset is not usable if this type uses a DWO file.
6478              The real type_offset is in the DWO file.  */
6479           dwo_tu = NULL;
6480           sig_type = per_objfile->per_bfd->allocate_signatured_type ();
6481           sig_type->signature = header.signature;
6482           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6483           sig_type->per_cu.is_debug_types = 1;
6484           sig_type->per_cu.section = section;
6485           sig_type->per_cu.sect_off = sect_off;
6486           sig_type->per_cu.length = length;
6487         }
6488
6489       slot = htab_find_slot (types_htab.get (),
6490                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6491                              INSERT);
6492       gdb_assert (slot != NULL);
6493       if (*slot != NULL)
6494         {
6495           sect_offset dup_sect_off;
6496
6497           if (dwo_file)
6498             {
6499               const struct dwo_unit *dup_tu
6500                 = (const struct dwo_unit *) *slot;
6501
6502               dup_sect_off = dup_tu->sect_off;
6503             }
6504           else
6505             {
6506               const struct signatured_type *dup_tu
6507                 = (const struct signatured_type *) *slot;
6508
6509               dup_sect_off = dup_tu->per_cu.sect_off;
6510             }
6511
6512           complaint (_("debug type entry at offset %s is duplicate to"
6513                        " the entry at offset %s, signature %s"),
6514                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6515                      hex_string (header.signature));
6516         }
6517       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6518
6519       dwarf_read_debug_printf_v ("  offset %s, signature %s",
6520                                  sect_offset_str (sect_off),
6521                                  hex_string (header.signature));
6522
6523       info_ptr += length;
6524     }
6525 }
6526
6527 /* Create the hash table of all entries in the .debug_types
6528    (or .debug_types.dwo) section(s).
6529    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6530    otherwise it is NULL.
6531
6532    The result is a pointer to the hash table or NULL if there are no types.
6533
6534    Note: This function processes DWO files only, not DWP files.  */
6535
6536 static void
6537 create_debug_types_hash_table (dwarf2_per_objfile *per_objfile,
6538                                struct dwo_file *dwo_file,
6539                                gdb::array_view<dwarf2_section_info> type_sections,
6540                                htab_up &types_htab)
6541 {
6542   for (dwarf2_section_info &section : type_sections)
6543     create_debug_type_hash_table (per_objfile, dwo_file, &section, types_htab,
6544                                   rcuh_kind::TYPE);
6545 }
6546
6547 /* Create the hash table of all entries in the .debug_types section,
6548    and initialize all_type_units.
6549    The result is zero if there is an error (e.g. missing .debug_types section),
6550    otherwise non-zero.  */
6551
6552 static int
6553 create_all_type_units (dwarf2_per_objfile *per_objfile)
6554 {
6555   htab_up types_htab;
6556
6557   create_debug_type_hash_table (per_objfile, NULL, &per_objfile->per_bfd->info,
6558                                 types_htab, rcuh_kind::COMPILE);
6559   create_debug_types_hash_table (per_objfile, NULL, per_objfile->per_bfd->types,
6560                                  types_htab);
6561   if (types_htab == NULL)
6562     {
6563       per_objfile->per_bfd->signatured_types = NULL;
6564       return 0;
6565     }
6566
6567   per_objfile->per_bfd->signatured_types = std::move (types_htab);
6568
6569   gdb_assert (per_objfile->per_bfd->all_type_units.empty ());
6570   per_objfile->per_bfd->all_type_units.reserve
6571     (htab_elements (per_objfile->per_bfd->signatured_types.get ()));
6572
6573   htab_traverse_noresize (per_objfile->per_bfd->signatured_types.get (),
6574                           add_signatured_type_cu_to_table,
6575                           &per_objfile->per_bfd->all_type_units);
6576
6577   return 1;
6578 }
6579
6580 /* Add an entry for signature SIG to dwarf2_per_objfile->per_bfd->signatured_types.
6581    If SLOT is non-NULL, it is the entry to use in the hash table.
6582    Otherwise we find one.  */
6583
6584 static struct signatured_type *
6585 add_type_unit (dwarf2_per_objfile *per_objfile, ULONGEST sig, void **slot)
6586 {
6587   if (per_objfile->per_bfd->all_type_units.size ()
6588       == per_objfile->per_bfd->all_type_units.capacity ())
6589     ++per_objfile->per_bfd->tu_stats.nr_all_type_units_reallocs;
6590
6591   signatured_type *sig_type = per_objfile->per_bfd->allocate_signatured_type ();
6592
6593   per_objfile->resize_symtabs ();
6594
6595   per_objfile->per_bfd->all_type_units.push_back (sig_type);
6596   sig_type->signature = sig;
6597   sig_type->per_cu.is_debug_types = 1;
6598   if (per_objfile->per_bfd->using_index)
6599     {
6600       sig_type->per_cu.v.quick =
6601         OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack,
6602                         struct dwarf2_per_cu_quick_data);
6603     }
6604
6605   if (slot == NULL)
6606     {
6607       slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
6608                              sig_type, INSERT);
6609     }
6610   gdb_assert (*slot == NULL);
6611   *slot = sig_type;
6612   /* The rest of sig_type must be filled in by the caller.  */
6613   return sig_type;
6614 }
6615
6616 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6617    Fill in SIG_ENTRY with DWO_ENTRY.  */
6618
6619 static void
6620 fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile *per_objfile,
6621                                   struct signatured_type *sig_entry,
6622                                   struct dwo_unit *dwo_entry)
6623 {
6624   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
6625
6626   /* Make sure we're not clobbering something we don't expect to.  */
6627   gdb_assert (! sig_entry->per_cu.queued);
6628   gdb_assert (per_objfile->get_cu (&sig_entry->per_cu) == NULL);
6629   if (per_bfd->using_index)
6630     {
6631       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6632       gdb_assert (!per_objfile->symtab_set_p (&sig_entry->per_cu));
6633     }
6634   else
6635       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6636   gdb_assert (sig_entry->signature == dwo_entry->signature);
6637   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6638   gdb_assert (sig_entry->type_unit_group == NULL);
6639   gdb_assert (sig_entry->dwo_unit == NULL);
6640
6641   sig_entry->per_cu.section = dwo_entry->section;
6642   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6643   sig_entry->per_cu.length = dwo_entry->length;
6644   sig_entry->per_cu.reading_dwo_directly = 1;
6645   sig_entry->per_cu.per_bfd = per_bfd;
6646   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6647   sig_entry->dwo_unit = dwo_entry;
6648 }
6649
6650 /* Subroutine of lookup_signatured_type.
6651    If we haven't read the TU yet, create the signatured_type data structure
6652    for a TU to be read in directly from a DWO file, bypassing the stub.
6653    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6654    using .gdb_index, then when reading a CU we want to stay in the DWO file
6655    containing that CU.  Otherwise we could end up reading several other DWO
6656    files (due to comdat folding) to process the transitive closure of all the
6657    mentioned TUs, and that can be slow.  The current DWO file will have every
6658    type signature that it needs.
6659    We only do this for .gdb_index because in the psymtab case we already have
6660    to read all the DWOs to build the type unit groups.  */
6661
6662 static struct signatured_type *
6663 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6664 {
6665   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6666   struct dwo_file *dwo_file;
6667   struct dwo_unit find_dwo_entry, *dwo_entry;
6668   struct signatured_type find_sig_entry, *sig_entry;
6669   void **slot;
6670
6671   gdb_assert (cu->dwo_unit && per_objfile->per_bfd->using_index);
6672
6673   /* If TU skeletons have been removed then we may not have read in any
6674      TUs yet.  */
6675   if (per_objfile->per_bfd->signatured_types == NULL)
6676     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
6677
6678   /* We only ever need to read in one copy of a signatured type.
6679      Use the global signatured_types array to do our own comdat-folding
6680      of types.  If this is the first time we're reading this TU, and
6681      the TU has an entry in .gdb_index, replace the recorded data from
6682      .gdb_index with this TU.  */
6683
6684   find_sig_entry.signature = sig;
6685   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
6686                          &find_sig_entry, INSERT);
6687   sig_entry = (struct signatured_type *) *slot;
6688
6689   /* We can get here with the TU already read, *or* in the process of being
6690      read.  Don't reassign the global entry to point to this DWO if that's
6691      the case.  Also note that if the TU is already being read, it may not
6692      have come from a DWO, the program may be a mix of Fission-compiled
6693      code and non-Fission-compiled code.  */
6694
6695   /* Have we already tried to read this TU?
6696      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6697      needn't exist in the global table yet).  */
6698   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6699     return sig_entry;
6700
6701   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6702      dwo_unit of the TU itself.  */
6703   dwo_file = cu->dwo_unit->dwo_file;
6704
6705   /* Ok, this is the first time we're reading this TU.  */
6706   if (dwo_file->tus == NULL)
6707     return NULL;
6708   find_dwo_entry.signature = sig;
6709   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
6710                                              &find_dwo_entry);
6711   if (dwo_entry == NULL)
6712     return NULL;
6713
6714   /* If the global table doesn't have an entry for this TU, add one.  */
6715   if (sig_entry == NULL)
6716     sig_entry = add_type_unit (per_objfile, sig, slot);
6717
6718   fill_in_sig_entry_from_dwo_entry (per_objfile, sig_entry, dwo_entry);
6719   sig_entry->per_cu.tu_read = 1;
6720   return sig_entry;
6721 }
6722
6723 /* Subroutine of lookup_signatured_type.
6724    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6725    then try the DWP file.  If the TU stub (skeleton) has been removed then
6726    it won't be in .gdb_index.  */
6727
6728 static struct signatured_type *
6729 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6730 {
6731   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6732   struct dwp_file *dwp_file = get_dwp_file (per_objfile);
6733   struct dwo_unit *dwo_entry;
6734   struct signatured_type find_sig_entry, *sig_entry;
6735   void **slot;
6736
6737   gdb_assert (cu->dwo_unit && per_objfile->per_bfd->using_index);
6738   gdb_assert (dwp_file != NULL);
6739
6740   /* If TU skeletons have been removed then we may not have read in any
6741      TUs yet.  */
6742   if (per_objfile->per_bfd->signatured_types == NULL)
6743     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
6744
6745   find_sig_entry.signature = sig;
6746   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
6747                          &find_sig_entry, INSERT);
6748   sig_entry = (struct signatured_type *) *slot;
6749
6750   /* Have we already tried to read this TU?
6751      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6752      needn't exist in the global table yet).  */
6753   if (sig_entry != NULL)
6754     return sig_entry;
6755
6756   if (dwp_file->tus == NULL)
6757     return NULL;
6758   dwo_entry = lookup_dwo_unit_in_dwp (per_objfile, dwp_file, NULL, sig,
6759                                       1 /* is_debug_types */);
6760   if (dwo_entry == NULL)
6761     return NULL;
6762
6763   sig_entry = add_type_unit (per_objfile, sig, slot);
6764   fill_in_sig_entry_from_dwo_entry (per_objfile, sig_entry, dwo_entry);
6765
6766   return sig_entry;
6767 }
6768
6769 /* Lookup a signature based type for DW_FORM_ref_sig8.
6770    Returns NULL if signature SIG is not present in the table.
6771    It is up to the caller to complain about this.  */
6772
6773 static struct signatured_type *
6774 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6775 {
6776   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6777
6778   if (cu->dwo_unit && per_objfile->per_bfd->using_index)
6779     {
6780       /* We're in a DWO/DWP file, and we're using .gdb_index.
6781          These cases require special processing.  */
6782       if (get_dwp_file (per_objfile) == NULL)
6783         return lookup_dwo_signatured_type (cu, sig);
6784       else
6785         return lookup_dwp_signatured_type (cu, sig);
6786     }
6787   else
6788     {
6789       struct signatured_type find_entry, *entry;
6790
6791       if (per_objfile->per_bfd->signatured_types == NULL)
6792         return NULL;
6793       find_entry.signature = sig;
6794       entry = ((struct signatured_type *)
6795                htab_find (per_objfile->per_bfd->signatured_types.get (),
6796                           &find_entry));
6797       return entry;
6798     }
6799 }
6800
6801 /* Low level DIE reading support.  */
6802
6803 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6804
6805 static void
6806 init_cu_die_reader (struct die_reader_specs *reader,
6807                     struct dwarf2_cu *cu,
6808                     struct dwarf2_section_info *section,
6809                     struct dwo_file *dwo_file,
6810                     struct abbrev_table *abbrev_table)
6811 {
6812   gdb_assert (section->readin && section->buffer != NULL);
6813   reader->abfd = section->get_bfd_owner ();
6814   reader->cu = cu;
6815   reader->dwo_file = dwo_file;
6816   reader->die_section = section;
6817   reader->buffer = section->buffer;
6818   reader->buffer_end = section->buffer + section->size;
6819   reader->abbrev_table = abbrev_table;
6820 }
6821
6822 /* Subroutine of cutu_reader to simplify it.
6823    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6824    There's just a lot of work to do, and cutu_reader is big enough
6825    already.
6826
6827    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6828    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6829    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6830    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6831    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6832    STUB_COMP_DIR may be non-NULL.
6833    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE
6834    are filled in with the info of the DIE from the DWO file.
6835    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
6836    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
6837    kept around for at least as long as *RESULT_READER.
6838
6839    The result is non-zero if a valid (non-dummy) DIE was found.  */
6840
6841 static int
6842 read_cutu_die_from_dwo (dwarf2_cu *cu,
6843                         struct dwo_unit *dwo_unit,
6844                         struct die_info *stub_comp_unit_die,
6845                         const char *stub_comp_dir,
6846                         struct die_reader_specs *result_reader,
6847                         const gdb_byte **result_info_ptr,
6848                         struct die_info **result_comp_unit_die,
6849                         abbrev_table_up *result_dwo_abbrev_table)
6850 {
6851   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6852   dwarf2_per_cu_data *per_cu = cu->per_cu;
6853   struct objfile *objfile = per_objfile->objfile;
6854   bfd *abfd;
6855   const gdb_byte *begin_info_ptr, *info_ptr;
6856   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6857   int i,num_extra_attrs;
6858   struct dwarf2_section_info *dwo_abbrev_section;
6859   struct die_info *comp_unit_die;
6860
6861   /* At most one of these may be provided.  */
6862   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6863
6864   /* These attributes aren't processed until later:
6865      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6866      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6867      referenced later.  However, these attributes are found in the stub
6868      which we won't have later.  In order to not impose this complication
6869      on the rest of the code, we read them here and copy them to the
6870      DWO CU/TU die.  */
6871
6872   stmt_list = NULL;
6873   low_pc = NULL;
6874   high_pc = NULL;
6875   ranges = NULL;
6876   comp_dir = NULL;
6877
6878   if (stub_comp_unit_die != NULL)
6879     {
6880       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6881          DWO file.  */
6882       if (!per_cu->is_debug_types)
6883         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6884       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6885       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6886       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6887       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6888
6889       cu->addr_base = stub_comp_unit_die->addr_base ();
6890
6891       /* There should be a DW_AT_GNU_ranges_base attribute here (if needed).
6892          We need the value before we can process DW_AT_ranges values from the
6893          DWO.  */
6894       cu->gnu_ranges_base = stub_comp_unit_die->gnu_ranges_base ();
6895
6896       /* For DWARF5: record the DW_AT_rnglists_base value from the skeleton.  If
6897          there are attributes of form DW_FORM_rnglistx in the skeleton, they'll
6898          need the rnglists base.  Attributes of form DW_FORM_rnglistx in the
6899          split unit don't use it, as the DWO has its own .debug_rnglists.dwo
6900          section.  */
6901       cu->rnglists_base = stub_comp_unit_die->rnglists_base ();
6902     }
6903   else if (stub_comp_dir != NULL)
6904     {
6905       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6906       comp_dir = OBSTACK_ZALLOC (&cu->comp_unit_obstack, struct attribute);
6907       comp_dir->name = DW_AT_comp_dir;
6908       comp_dir->form = DW_FORM_string;
6909       comp_dir->set_string_noncanonical (stub_comp_dir);
6910     }
6911
6912   /* Set up for reading the DWO CU/TU.  */
6913   cu->dwo_unit = dwo_unit;
6914   dwarf2_section_info *section = dwo_unit->section;
6915   section->read (objfile);
6916   abfd = section->get_bfd_owner ();
6917   begin_info_ptr = info_ptr = (section->buffer
6918                                + to_underlying (dwo_unit->sect_off));
6919   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
6920
6921   if (per_cu->is_debug_types)
6922     {
6923       signatured_type *sig_type = (struct signatured_type *) per_cu;
6924
6925       info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6926                                                 section, dwo_abbrev_section,
6927                                                 info_ptr, rcuh_kind::TYPE);
6928       /* This is not an assert because it can be caused by bad debug info.  */
6929       if (sig_type->signature != cu->header.signature)
6930         {
6931           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
6932                    " TU at offset %s [in module %s]"),
6933                  hex_string (sig_type->signature),
6934                  hex_string (cu->header.signature),
6935                  sect_offset_str (dwo_unit->sect_off),
6936                  bfd_get_filename (abfd));
6937         }
6938       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6939       /* For DWOs coming from DWP files, we don't know the CU length
6940          nor the type's offset in the TU until now.  */
6941       dwo_unit->length = cu->header.get_length ();
6942       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
6943
6944       /* Establish the type offset that can be used to lookup the type.
6945          For DWO files, we don't know it until now.  */
6946       sig_type->type_offset_in_section
6947         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
6948     }
6949   else
6950     {
6951       info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6952                                                 section, dwo_abbrev_section,
6953                                                 info_ptr, rcuh_kind::COMPILE);
6954       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6955       /* For DWOs coming from DWP files, we don't know the CU length
6956          until now.  */
6957       dwo_unit->length = cu->header.get_length ();
6958     }
6959
6960   dwo_abbrev_section->read (objfile);
6961   *result_dwo_abbrev_table
6962     = abbrev_table::read (dwo_abbrev_section, cu->header.abbrev_sect_off);
6963   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
6964                       result_dwo_abbrev_table->get ());
6965
6966   /* Read in the die, but leave space to copy over the attributes
6967      from the stub.  This has the benefit of simplifying the rest of
6968      the code - all the work to maintain the illusion of a single
6969      DW_TAG_{compile,type}_unit DIE is done here.  */
6970   num_extra_attrs = ((stmt_list != NULL)
6971                      + (low_pc != NULL)
6972                      + (high_pc != NULL)
6973                      + (ranges != NULL)
6974                      + (comp_dir != NULL));
6975   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
6976                               num_extra_attrs);
6977
6978   /* Copy over the attributes from the stub to the DIE we just read in.  */
6979   comp_unit_die = *result_comp_unit_die;
6980   i = comp_unit_die->num_attrs;
6981   if (stmt_list != NULL)
6982     comp_unit_die->attrs[i++] = *stmt_list;
6983   if (low_pc != NULL)
6984     comp_unit_die->attrs[i++] = *low_pc;
6985   if (high_pc != NULL)
6986     comp_unit_die->attrs[i++] = *high_pc;
6987   if (ranges != NULL)
6988     comp_unit_die->attrs[i++] = *ranges;
6989   if (comp_dir != NULL)
6990     comp_unit_die->attrs[i++] = *comp_dir;
6991   comp_unit_die->num_attrs += num_extra_attrs;
6992
6993   if (dwarf_die_debug)
6994     {
6995       fprintf_unfiltered (gdb_stdlog,
6996                           "Read die from %s@0x%x of %s:\n",
6997                           section->get_name (),
6998                           (unsigned) (begin_info_ptr - section->buffer),
6999                           bfd_get_filename (abfd));
7000       dump_die (comp_unit_die, dwarf_die_debug);
7001     }
7002
7003   /* Skip dummy compilation units.  */
7004   if (info_ptr >= begin_info_ptr + dwo_unit->length
7005       || peek_abbrev_code (abfd, info_ptr) == 0)
7006     return 0;
7007
7008   *result_info_ptr = info_ptr;
7009   return 1;
7010 }
7011
7012 /* Return the signature of the compile unit, if found. In DWARF 4 and before,
7013    the signature is in the DW_AT_GNU_dwo_id attribute. In DWARF 5 and later, the
7014    signature is part of the header.  */
7015 static gdb::optional<ULONGEST>
7016 lookup_dwo_id (struct dwarf2_cu *cu, struct die_info* comp_unit_die)
7017 {
7018   if (cu->header.version >= 5)
7019     return cu->header.signature;
7020   struct attribute *attr;
7021   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7022   if (attr == nullptr || !attr->form_is_unsigned ())
7023     return gdb::optional<ULONGEST> ();
7024   return attr->as_unsigned ();
7025 }
7026
7027 /* Subroutine of cutu_reader to simplify it.
7028    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7029    Returns NULL if the specified DWO unit cannot be found.  */
7030
7031 static struct dwo_unit *
7032 lookup_dwo_unit (dwarf2_cu *cu, die_info *comp_unit_die, const char *dwo_name)
7033 {
7034   dwarf2_per_cu_data *per_cu = cu->per_cu;
7035   struct dwo_unit *dwo_unit;
7036   const char *comp_dir;
7037
7038   gdb_assert (cu != NULL);
7039
7040   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7041   dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
7042   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7043
7044   if (per_cu->is_debug_types)
7045     dwo_unit = lookup_dwo_type_unit (cu, dwo_name, comp_dir);
7046   else
7047     {
7048       gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
7049
7050       if (!signature.has_value ())
7051         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7052                  " [in module %s]"),
7053                dwo_name, bfd_get_filename (per_cu->per_bfd->obfd));
7054
7055       dwo_unit = lookup_dwo_comp_unit (cu, dwo_name, comp_dir, *signature);
7056     }
7057
7058   return dwo_unit;
7059 }
7060
7061 /* Subroutine of cutu_reader to simplify it.
7062    See it for a description of the parameters.
7063    Read a TU directly from a DWO file, bypassing the stub.  */
7064
7065 void
7066 cutu_reader::init_tu_and_read_dwo_dies (dwarf2_per_cu_data *this_cu,
7067                                         dwarf2_per_objfile *per_objfile,
7068                                         dwarf2_cu *existing_cu)
7069 {
7070   struct signatured_type *sig_type;
7071
7072   /* Verify we can do the following downcast, and that we have the
7073      data we need.  */
7074   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7075   sig_type = (struct signatured_type *) this_cu;
7076   gdb_assert (sig_type->dwo_unit != NULL);
7077
7078   dwarf2_cu *cu;
7079
7080   if (existing_cu != nullptr)
7081     {
7082       cu = existing_cu;
7083       gdb_assert (cu->dwo_unit == sig_type->dwo_unit);
7084       /* There's no need to do the rereading_dwo_cu handling that
7085          cutu_reader does since we don't read the stub.  */
7086     }
7087   else
7088     {
7089       /* If an existing_cu is provided, a dwarf2_cu must not exist for this_cu
7090          in per_objfile yet.  */
7091       gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
7092       m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
7093       cu = m_new_cu.get ();
7094     }
7095
7096   /* A future optimization, if needed, would be to use an existing
7097      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7098      could share abbrev tables.  */
7099
7100   if (read_cutu_die_from_dwo (cu, sig_type->dwo_unit,
7101                               NULL /* stub_comp_unit_die */,
7102                               sig_type->dwo_unit->dwo_file->comp_dir,
7103                               this, &info_ptr,
7104                               &comp_unit_die,
7105                               &m_dwo_abbrev_table) == 0)
7106     {
7107       /* Dummy die.  */
7108       dummy_p = true;
7109     }
7110 }
7111
7112 /* Initialize a CU (or TU) and read its DIEs.
7113    If the CU defers to a DWO file, read the DWO file as well.
7114
7115    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7116    Otherwise the table specified in the comp unit header is read in and used.
7117    This is an optimization for when we already have the abbrev table.
7118
7119    If EXISTING_CU is non-NULL, then use it.  Otherwise, a new CU is
7120    allocated.  */
7121
7122 cutu_reader::cutu_reader (dwarf2_per_cu_data *this_cu,
7123                           dwarf2_per_objfile *per_objfile,
7124                           struct abbrev_table *abbrev_table,
7125                           dwarf2_cu *existing_cu,
7126                           bool skip_partial)
7127   : die_reader_specs {},
7128     m_this_cu (this_cu)
7129 {
7130   struct objfile *objfile = per_objfile->objfile;
7131   struct dwarf2_section_info *section = this_cu->section;
7132   bfd *abfd = section->get_bfd_owner ();
7133   const gdb_byte *begin_info_ptr;
7134   struct signatured_type *sig_type = NULL;
7135   struct dwarf2_section_info *abbrev_section;
7136   /* Non-zero if CU currently points to a DWO file and we need to
7137      reread it.  When this happens we need to reread the skeleton die
7138      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7139   int rereading_dwo_cu = 0;
7140
7141   if (dwarf_die_debug)
7142     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7143                         this_cu->is_debug_types ? "type" : "comp",
7144                         sect_offset_str (this_cu->sect_off));
7145
7146   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7147      file (instead of going through the stub), short-circuit all of this.  */
7148   if (this_cu->reading_dwo_directly)
7149     {
7150       /* Narrow down the scope of possibilities to have to understand.  */
7151       gdb_assert (this_cu->is_debug_types);
7152       gdb_assert (abbrev_table == NULL);
7153       init_tu_and_read_dwo_dies (this_cu, per_objfile, existing_cu);
7154       return;
7155     }
7156
7157   /* This is cheap if the section is already read in.  */
7158   section->read (objfile);
7159
7160   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7161
7162   abbrev_section = get_abbrev_section_for_cu (this_cu);
7163
7164   dwarf2_cu *cu;
7165
7166   if (existing_cu != nullptr)
7167     {
7168       cu = existing_cu;
7169       /* If this CU is from a DWO file we need to start over, we need to
7170          refetch the attributes from the skeleton CU.
7171          This could be optimized by retrieving those attributes from when we
7172          were here the first time: the previous comp_unit_die was stored in
7173          comp_unit_obstack.  But there's no data yet that we need this
7174          optimization.  */
7175       if (cu->dwo_unit != NULL)
7176         rereading_dwo_cu = 1;
7177     }
7178   else
7179     {
7180       /* If an existing_cu is provided, a dwarf2_cu must not exist for this_cu
7181          in per_objfile yet.  */
7182       gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
7183       m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
7184       cu = m_new_cu.get ();
7185     }
7186
7187   /* Get the header.  */
7188   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7189     {
7190       /* We already have the header, there's no need to read it in again.  */
7191       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7192     }
7193   else
7194     {
7195       if (this_cu->is_debug_types)
7196         {
7197           info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
7198                                                     section, abbrev_section,
7199                                                     info_ptr, rcuh_kind::TYPE);
7200
7201           /* Since per_cu is the first member of struct signatured_type,
7202              we can go from a pointer to one to a pointer to the other.  */
7203           sig_type = (struct signatured_type *) this_cu;
7204           gdb_assert (sig_type->signature == cu->header.signature);
7205           gdb_assert (sig_type->type_offset_in_tu
7206                       == cu->header.type_cu_offset_in_tu);
7207           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7208
7209           /* LENGTH has not been set yet for type units if we're
7210              using .gdb_index.  */
7211           this_cu->length = cu->header.get_length ();
7212
7213           /* Establish the type offset that can be used to lookup the type.  */
7214           sig_type->type_offset_in_section =
7215             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7216
7217           this_cu->dwarf_version = cu->header.version;
7218         }
7219       else
7220         {
7221           info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
7222                                                     section, abbrev_section,
7223                                                     info_ptr,
7224                                                     rcuh_kind::COMPILE);
7225
7226           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7227           if (this_cu->length == 0)
7228             this_cu->length = cu->header.get_length ();
7229           else
7230             gdb_assert (this_cu->length == cu->header.get_length ());
7231           this_cu->dwarf_version = cu->header.version;
7232         }
7233     }
7234
7235   /* Skip dummy compilation units.  */
7236   if (info_ptr >= begin_info_ptr + this_cu->length
7237       || peek_abbrev_code (abfd, info_ptr) == 0)
7238     {
7239       dummy_p = true;
7240       return;
7241     }
7242
7243   /* If we don't have them yet, read the abbrevs for this compilation unit.
7244      And if we need to read them now, make sure they're freed when we're
7245      done.  */
7246   if (abbrev_table != NULL)
7247     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7248   else
7249     {
7250       abbrev_section->read (objfile);
7251       m_abbrev_table_holder
7252         = abbrev_table::read (abbrev_section, cu->header.abbrev_sect_off);
7253       abbrev_table = m_abbrev_table_holder.get ();
7254     }
7255
7256   /* Read the top level CU/TU die.  */
7257   init_cu_die_reader (this, cu, section, NULL, abbrev_table);
7258   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
7259
7260   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7261     {
7262       dummy_p = true;
7263       return;
7264     }
7265
7266   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7267      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7268      table from the DWO file and pass the ownership over to us.  It will be
7269      referenced from READER, so we must make sure to free it after we're done
7270      with READER.
7271
7272      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7273      DWO CU, that this test will fail (the attribute will not be present).  */
7274   const char *dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
7275   if (dwo_name != nullptr)
7276     {
7277       struct dwo_unit *dwo_unit;
7278       struct die_info *dwo_comp_unit_die;
7279
7280       if (comp_unit_die->has_children)
7281         {
7282           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7283                        " has children (offset %s) [in module %s]"),
7284                      sect_offset_str (this_cu->sect_off),
7285                      bfd_get_filename (abfd));
7286         }
7287       dwo_unit = lookup_dwo_unit (cu, comp_unit_die, dwo_name);
7288       if (dwo_unit != NULL)
7289         {
7290           if (read_cutu_die_from_dwo (cu, dwo_unit,
7291                                       comp_unit_die, NULL,
7292                                       this, &info_ptr,
7293                                       &dwo_comp_unit_die,
7294                                       &m_dwo_abbrev_table) == 0)
7295             {
7296               /* Dummy die.  */
7297               dummy_p = true;
7298               return;
7299             }
7300           comp_unit_die = dwo_comp_unit_die;
7301         }
7302       else
7303         {
7304           /* Yikes, we couldn't find the rest of the DIE, we only have
7305              the stub.  A complaint has already been logged.  There's
7306              not much more we can do except pass on the stub DIE to
7307              die_reader_func.  We don't want to throw an error on bad
7308              debug info.  */
7309         }
7310     }
7311 }
7312
7313 void
7314 cutu_reader::keep ()
7315 {
7316   /* Done, clean up.  */
7317   gdb_assert (!dummy_p);
7318   if (m_new_cu != NULL)
7319     {
7320       /* Save this dwarf2_cu in the per_objfile.  The per_objfile owns it
7321          now.  */
7322       dwarf2_per_objfile *per_objfile = m_new_cu->per_objfile;
7323       per_objfile->set_cu (m_this_cu, m_new_cu.release ());
7324     }
7325 }
7326
7327 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name (DW_AT_dwo_name)
7328    if present. DWO_FILE, if non-NULL, is the DWO file to read (the caller is
7329    assumed to have already done the lookup to find the DWO file).
7330
7331    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7332    THIS_CU->is_debug_types, but nothing else.
7333
7334    We fill in THIS_CU->length.
7335
7336    THIS_CU->cu is always freed when done.
7337    This is done in order to not leave THIS_CU->cu in a state where we have
7338    to care whether it refers to the "main" CU or the DWO CU.
7339
7340    When parent_cu is passed, it is used to provide a default value for
7341    str_offsets_base and addr_base from the parent.  */
7342
7343 cutu_reader::cutu_reader (dwarf2_per_cu_data *this_cu,
7344                           dwarf2_per_objfile *per_objfile,
7345                           struct dwarf2_cu *parent_cu,
7346                           struct dwo_file *dwo_file)
7347   : die_reader_specs {},
7348     m_this_cu (this_cu)
7349 {
7350   struct objfile *objfile = per_objfile->objfile;
7351   struct dwarf2_section_info *section = this_cu->section;
7352   bfd *abfd = section->get_bfd_owner ();
7353   struct dwarf2_section_info *abbrev_section;
7354   const gdb_byte *begin_info_ptr, *info_ptr;
7355
7356   if (dwarf_die_debug)
7357     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7358                         this_cu->is_debug_types ? "type" : "comp",
7359                         sect_offset_str (this_cu->sect_off));
7360
7361   gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
7362
7363   abbrev_section = (dwo_file != NULL
7364                     ? &dwo_file->sections.abbrev
7365                     : get_abbrev_section_for_cu (this_cu));
7366
7367   /* This is cheap if the section is already read in.  */
7368   section->read (objfile);
7369
7370   m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
7371
7372   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7373   info_ptr = read_and_check_comp_unit_head (per_objfile, &m_new_cu->header,
7374                                             section, abbrev_section, info_ptr,
7375                                             (this_cu->is_debug_types
7376                                              ? rcuh_kind::TYPE
7377                                              : rcuh_kind::COMPILE));
7378
7379   if (parent_cu != nullptr)
7380     {
7381       m_new_cu->str_offsets_base = parent_cu->str_offsets_base;
7382       m_new_cu->addr_base = parent_cu->addr_base;
7383     }
7384   this_cu->length = m_new_cu->header.get_length ();
7385
7386   /* Skip dummy compilation units.  */
7387   if (info_ptr >= begin_info_ptr + this_cu->length
7388       || peek_abbrev_code (abfd, info_ptr) == 0)
7389     {
7390       dummy_p = true;
7391       return;
7392     }
7393
7394   abbrev_section->read (objfile);
7395   m_abbrev_table_holder
7396     = abbrev_table::read (abbrev_section, m_new_cu->header.abbrev_sect_off);
7397
7398   init_cu_die_reader (this, m_new_cu.get (), section, dwo_file,
7399                       m_abbrev_table_holder.get ());
7400   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
7401 }
7402
7403 \f
7404 /* Type Unit Groups.
7405
7406    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7407    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7408    so that all types coming from the same compilation (.o file) are grouped
7409    together.  A future step could be to put the types in the same symtab as
7410    the CU the types ultimately came from.  */
7411
7412 static hashval_t
7413 hash_type_unit_group (const void *item)
7414 {
7415   const struct type_unit_group *tu_group
7416     = (const struct type_unit_group *) item;
7417
7418   return hash_stmt_list_entry (&tu_group->hash);
7419 }
7420
7421 static int
7422 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7423 {
7424   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7425   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7426
7427   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7428 }
7429
7430 /* Allocate a hash table for type unit groups.  */
7431
7432 static htab_up
7433 allocate_type_unit_groups_table ()
7434 {
7435   return htab_up (htab_create_alloc (3,
7436                                      hash_type_unit_group,
7437                                      eq_type_unit_group,
7438                                      NULL, xcalloc, xfree));
7439 }
7440
7441 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7442    partial symtabs.  We combine several TUs per psymtab to not let the size
7443    of any one psymtab grow too big.  */
7444 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7445 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7446
7447 /* Helper routine for get_type_unit_group.
7448    Create the type_unit_group object used to hold one or more TUs.  */
7449
7450 static struct type_unit_group *
7451 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7452 {
7453   dwarf2_per_objfile *per_objfile = cu->per_objfile;
7454   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
7455   struct dwarf2_per_cu_data *per_cu;
7456   struct type_unit_group *tu_group;
7457
7458   tu_group = OBSTACK_ZALLOC (&per_bfd->obstack, type_unit_group);
7459   per_cu = &tu_group->per_cu;
7460   per_cu->per_bfd = per_bfd;
7461
7462   if (per_bfd->using_index)
7463     {
7464       per_cu->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
7465                                         struct dwarf2_per_cu_quick_data);
7466     }
7467   else
7468     {
7469       unsigned int line_offset = to_underlying (line_offset_struct);
7470       dwarf2_psymtab *pst;
7471       std::string name;
7472
7473       /* Give the symtab a useful name for debug purposes.  */
7474       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7475         name = string_printf ("<type_units_%d>",
7476                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7477       else
7478         name = string_printf ("<type_units_at_0x%x>", line_offset);
7479
7480       pst = create_partial_symtab (per_cu, per_objfile, name.c_str ());
7481       pst->anonymous = true;
7482     }
7483
7484   tu_group->hash.dwo_unit = cu->dwo_unit;
7485   tu_group->hash.line_sect_off = line_offset_struct;
7486
7487   return tu_group;
7488 }
7489
7490 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7491    STMT_LIST is a DW_AT_stmt_list attribute.  */
7492
7493 static struct type_unit_group *
7494 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7495 {
7496   dwarf2_per_objfile *per_objfile = cu->per_objfile;
7497   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
7498   struct type_unit_group *tu_group;
7499   void **slot;
7500   unsigned int line_offset;
7501   struct type_unit_group type_unit_group_for_lookup;
7502
7503   if (per_objfile->per_bfd->type_unit_groups == NULL)
7504     per_objfile->per_bfd->type_unit_groups = allocate_type_unit_groups_table ();
7505
7506   /* Do we need to create a new group, or can we use an existing one?  */
7507
7508   if (stmt_list != nullptr && stmt_list->form_is_unsigned ())
7509     {
7510       line_offset = stmt_list->as_unsigned ();
7511       ++tu_stats->nr_symtab_sharers;
7512     }
7513   else
7514     {
7515       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7516          We can do various things here like create one group per TU or
7517          spread them over multiple groups to split up the expansion work.
7518          To avoid worst case scenarios (too many groups or too large groups)
7519          we, umm, group them in bunches.  */
7520       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7521                      | (tu_stats->nr_stmt_less_type_units
7522                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7523       ++tu_stats->nr_stmt_less_type_units;
7524     }
7525
7526   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7527   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7528   slot = htab_find_slot (per_objfile->per_bfd->type_unit_groups.get (),
7529                          &type_unit_group_for_lookup, INSERT);
7530   if (*slot != NULL)
7531     {
7532       tu_group = (struct type_unit_group *) *slot;
7533       gdb_assert (tu_group != NULL);
7534     }
7535   else
7536     {
7537       sect_offset line_offset_struct = (sect_offset) line_offset;
7538       tu_group = create_type_unit_group (cu, line_offset_struct);
7539       *slot = tu_group;
7540       ++tu_stats->nr_symtabs;
7541     }
7542
7543   return tu_group;
7544 }
7545 \f
7546 /* Partial symbol tables.  */
7547
7548 /* Create a psymtab named NAME and assign it to PER_CU.
7549
7550    The caller must fill in the following details:
7551    dirname, textlow, texthigh.  */
7552
7553 static dwarf2_psymtab *
7554 create_partial_symtab (dwarf2_per_cu_data *per_cu,
7555                        dwarf2_per_objfile *per_objfile,
7556                        const char *name)
7557 {
7558   struct objfile *objfile = per_objfile->objfile;
7559   dwarf2_psymtab *pst;
7560
7561   pst = new dwarf2_psymtab (name, per_objfile->per_bfd->partial_symtabs.get (),
7562                             objfile, per_cu);
7563
7564   pst->psymtabs_addrmap_supported = true;
7565
7566   /* This is the glue that links PST into GDB's symbol API.  */
7567   per_cu->v.psymtab = pst;
7568
7569   return pst;
7570 }
7571
7572 /* DIE reader function for process_psymtab_comp_unit.  */
7573
7574 static void
7575 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7576                                   const gdb_byte *info_ptr,
7577                                   struct die_info *comp_unit_die,
7578                                   enum language pretend_language)
7579 {
7580   struct dwarf2_cu *cu = reader->cu;
7581   dwarf2_per_objfile *per_objfile = cu->per_objfile;
7582   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
7583   struct objfile *objfile = per_objfile->objfile;
7584   struct gdbarch *gdbarch = objfile->arch ();
7585   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7586   CORE_ADDR baseaddr;
7587   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7588   dwarf2_psymtab *pst;
7589   enum pc_bounds_kind cu_bounds_kind;
7590   const char *filename;
7591
7592   gdb_assert (! per_cu->is_debug_types);
7593
7594   prepare_one_comp_unit (cu, comp_unit_die, pretend_language);
7595
7596   /* Allocate a new partial symbol table structure.  */
7597   gdb::unique_xmalloc_ptr<char> debug_filename;
7598   static const char artificial[] = "<artificial>";
7599   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7600   if (filename == NULL)
7601     filename = "";
7602   else if (strcmp (filename, artificial) == 0)
7603     {
7604       debug_filename.reset (concat (artificial, "@",
7605                                     sect_offset_str (per_cu->sect_off),
7606                                     (char *) NULL));
7607       filename = debug_filename.get ();
7608     }
7609
7610   pst = create_partial_symtab (per_cu, per_objfile, filename);
7611
7612   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7613   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7614
7615   baseaddr = objfile->text_section_offset ();
7616
7617   dwarf2_find_base_address (comp_unit_die, cu);
7618
7619   /* Possibly set the default values of LOWPC and HIGHPC from
7620      `DW_AT_ranges'.  */
7621   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7622                                          &best_highpc, cu, pst);
7623   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7624     {
7625       CORE_ADDR low
7626         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
7627            - baseaddr);
7628       CORE_ADDR high
7629         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
7630            - baseaddr - 1);
7631       /* Store the contiguous range if it is not empty; it can be
7632          empty for CUs with no code.  */
7633       addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
7634                          low, high, pst);
7635     }
7636
7637   /* Check if comp unit has_children.
7638      If so, read the rest of the partial symbols from this comp unit.
7639      If not, there's no more debug_info for this comp unit.  */
7640   if (comp_unit_die->has_children)
7641     {
7642       struct partial_die_info *first_die;
7643       CORE_ADDR lowpc, highpc;
7644
7645       lowpc = ((CORE_ADDR) -1);
7646       highpc = ((CORE_ADDR) 0);
7647
7648       first_die = load_partial_dies (reader, info_ptr, 1);
7649
7650       scan_partial_symbols (first_die, &lowpc, &highpc,
7651                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7652
7653       /* If we didn't find a lowpc, set it to highpc to avoid
7654          complaints from `maint check'.  */
7655       if (lowpc == ((CORE_ADDR) -1))
7656         lowpc = highpc;
7657
7658       /* If the compilation unit didn't have an explicit address range,
7659          then use the information extracted from its child dies.  */
7660       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7661         {
7662           best_lowpc = lowpc;
7663           best_highpc = highpc;
7664         }
7665     }
7666   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
7667                                                  best_lowpc + baseaddr)
7668                      - baseaddr);
7669   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
7670                                                   best_highpc + baseaddr)
7671                       - baseaddr);
7672
7673   pst->end ();
7674
7675   if (!cu->per_cu->imported_symtabs_empty ())
7676     {
7677       int i;
7678       int len = cu->per_cu->imported_symtabs_size ();
7679
7680       /* Fill in 'dependencies' here; we fill in 'users' in a
7681          post-pass.  */
7682       pst->number_of_dependencies = len;
7683       pst->dependencies
7684         = per_bfd->partial_symtabs->allocate_dependencies (len);
7685       for (i = 0; i < len; ++i)
7686         {
7687           pst->dependencies[i]
7688             = cu->per_cu->imported_symtabs->at (i)->v.psymtab;
7689         }
7690
7691       cu->per_cu->imported_symtabs_free ();
7692     }
7693
7694   /* Get the list of files included in the current compilation unit,
7695      and build a psymtab for each of them.  */
7696   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7697
7698   dwarf_read_debug_printf ("Psymtab for %s unit @%s: %s - %s"
7699                            ", %d global, %d static syms",
7700                            per_cu->is_debug_types ? "type" : "comp",
7701                            sect_offset_str (per_cu->sect_off),
7702                            paddress (gdbarch, pst->text_low (objfile)),
7703                            paddress (gdbarch, pst->text_high (objfile)),
7704                            (int) pst->global_psymbols.size (),
7705                            (int) pst->static_psymbols.size ());
7706 }
7707
7708 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7709    Process compilation unit THIS_CU for a psymtab.  */
7710
7711 static void
7712 process_psymtab_comp_unit (dwarf2_per_cu_data *this_cu,
7713                            dwarf2_per_objfile *per_objfile,
7714                            bool want_partial_unit,
7715                            enum language pretend_language)
7716 {
7717   /* If this compilation unit was already read in, free the
7718      cached copy in order to read it in again.  This is
7719      necessary because we skipped some symbols when we first
7720      read in the compilation unit (see load_partial_dies).
7721      This problem could be avoided, but the benefit is unclear.  */
7722   per_objfile->remove_cu (this_cu);
7723
7724   cutu_reader reader (this_cu, per_objfile, nullptr, nullptr, false);
7725
7726   switch (reader.comp_unit_die->tag)
7727     {
7728     case DW_TAG_compile_unit:
7729       this_cu->unit_type = DW_UT_compile;
7730       break;
7731     case DW_TAG_partial_unit:
7732       this_cu->unit_type = DW_UT_partial;
7733       break;
7734     case DW_TAG_type_unit:
7735       this_cu->unit_type = DW_UT_type;
7736       break;
7737     default:
7738       error (_("Dwarf Error: unexpected tag '%s' at offset %s [in module %s]"),
7739              dwarf_tag_name (reader.comp_unit_die->tag),
7740              sect_offset_str (reader.cu->per_cu->sect_off),
7741              objfile_name (per_objfile->objfile));
7742     }
7743
7744   if (reader.dummy_p)
7745     {
7746       /* Nothing.  */
7747     }
7748   else if (this_cu->is_debug_types)
7749     build_type_psymtabs_reader (&reader, reader.info_ptr,
7750                                 reader.comp_unit_die);
7751   else if (want_partial_unit
7752            || reader.comp_unit_die->tag != DW_TAG_partial_unit)
7753     process_psymtab_comp_unit_reader (&reader, reader.info_ptr,
7754                                       reader.comp_unit_die,
7755                                       pretend_language);
7756
7757   this_cu->lang = reader.cu->language;
7758
7759   /* Age out any secondary CUs.  */
7760   per_objfile->age_comp_units ();
7761 }
7762
7763 /* Reader function for build_type_psymtabs.  */
7764
7765 static void
7766 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7767                             const gdb_byte *info_ptr,
7768                             struct die_info *type_unit_die)
7769 {
7770   dwarf2_per_objfile *per_objfile = reader->cu->per_objfile;
7771   struct dwarf2_cu *cu = reader->cu;
7772   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7773   struct signatured_type *sig_type;
7774   struct type_unit_group *tu_group;
7775   struct attribute *attr;
7776   struct partial_die_info *first_die;
7777   CORE_ADDR lowpc, highpc;
7778   dwarf2_psymtab *pst;
7779
7780   gdb_assert (per_cu->is_debug_types);
7781   sig_type = (struct signatured_type *) per_cu;
7782
7783   if (! type_unit_die->has_children)
7784     return;
7785
7786   attr = type_unit_die->attr (DW_AT_stmt_list);
7787   tu_group = get_type_unit_group (cu, attr);
7788
7789   if (tu_group->tus == nullptr)
7790     tu_group->tus = new std::vector<signatured_type *>;
7791   tu_group->tus->push_back (sig_type);
7792
7793   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7794   pst = create_partial_symtab (per_cu, per_objfile, "");
7795   pst->anonymous = true;
7796
7797   first_die = load_partial_dies (reader, info_ptr, 1);
7798
7799   lowpc = (CORE_ADDR) -1;
7800   highpc = (CORE_ADDR) 0;
7801   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7802
7803   pst->end ();
7804 }
7805
7806 /* Struct used to sort TUs by their abbreviation table offset.  */
7807
7808 struct tu_abbrev_offset
7809 {
7810   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
7811   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
7812   {}
7813
7814   signatured_type *sig_type;
7815   sect_offset abbrev_offset;
7816 };
7817
7818 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
7819
7820 static bool
7821 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
7822                           const struct tu_abbrev_offset &b)
7823 {
7824   return a.abbrev_offset < b.abbrev_offset;
7825 }
7826
7827 /* Efficiently read all the type units.
7828    This does the bulk of the work for build_type_psymtabs.
7829
7830    The efficiency is because we sort TUs by the abbrev table they use and
7831    only read each abbrev table once.  In one program there are 200K TUs
7832    sharing 8K abbrev tables.
7833
7834    The main purpose of this function is to support building the
7835    dwarf2_per_objfile->per_bfd->type_unit_groups table.
7836    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7837    can collapse the search space by grouping them by stmt_list.
7838    The savings can be significant, in the same program from above the 200K TUs
7839    share 8K stmt_list tables.
7840
7841    FUNC is expected to call get_type_unit_group, which will create the
7842    struct type_unit_group if necessary and add it to
7843    dwarf2_per_objfile->per_bfd->type_unit_groups.  */
7844
7845 static void
7846 build_type_psymtabs_1 (dwarf2_per_objfile *per_objfile)
7847 {
7848   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
7849   abbrev_table_up abbrev_table;
7850   sect_offset abbrev_offset;
7851
7852   /* It's up to the caller to not call us multiple times.  */
7853   gdb_assert (per_objfile->per_bfd->type_unit_groups == NULL);
7854
7855   if (per_objfile->per_bfd->all_type_units.empty ())
7856     return;
7857
7858   /* TUs typically share abbrev tables, and there can be way more TUs than
7859      abbrev tables.  Sort by abbrev table to reduce the number of times we
7860      read each abbrev table in.
7861      Alternatives are to punt or to maintain a cache of abbrev tables.
7862      This is simpler and efficient enough for now.
7863
7864      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7865      symtab to use).  Typically TUs with the same abbrev offset have the same
7866      stmt_list value too so in practice this should work well.
7867
7868      The basic algorithm here is:
7869
7870       sort TUs by abbrev table
7871       for each TU with same abbrev table:
7872         read abbrev table if first user
7873         read TU top level DIE
7874           [IWBN if DWO skeletons had DW_AT_stmt_list]
7875         call FUNC  */
7876
7877   dwarf_read_debug_printf ("Building type unit groups ...");
7878
7879   /* Sort in a separate table to maintain the order of all_type_units
7880      for .gdb_index: TU indices directly index all_type_units.  */
7881   std::vector<tu_abbrev_offset> sorted_by_abbrev;
7882   sorted_by_abbrev.reserve (per_objfile->per_bfd->all_type_units.size ());
7883
7884   for (signatured_type *sig_type : per_objfile->per_bfd->all_type_units)
7885     sorted_by_abbrev.emplace_back
7886       (sig_type, read_abbrev_offset (per_objfile, sig_type->per_cu.section,
7887                                      sig_type->per_cu.sect_off));
7888
7889   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
7890              sort_tu_by_abbrev_offset);
7891
7892   abbrev_offset = (sect_offset) ~(unsigned) 0;
7893
7894   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
7895     {
7896       /* Switch to the next abbrev table if necessary.  */
7897       if (abbrev_table == NULL
7898           || tu.abbrev_offset != abbrev_offset)
7899         {
7900           abbrev_offset = tu.abbrev_offset;
7901           per_objfile->per_bfd->abbrev.read (per_objfile->objfile);
7902           abbrev_table =
7903             abbrev_table::read (&per_objfile->per_bfd->abbrev, abbrev_offset);
7904           ++tu_stats->nr_uniq_abbrev_tables;
7905         }
7906
7907       cutu_reader reader (&tu.sig_type->per_cu, per_objfile,
7908                           abbrev_table.get (), nullptr, false);
7909       if (!reader.dummy_p)
7910         build_type_psymtabs_reader (&reader, reader.info_ptr,
7911                                     reader.comp_unit_die);
7912     }
7913 }
7914
7915 /* Print collected type unit statistics.  */
7916
7917 static void
7918 print_tu_stats (dwarf2_per_objfile *per_objfile)
7919 {
7920   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
7921
7922   dwarf_read_debug_printf ("Type unit statistics:");
7923   dwarf_read_debug_printf ("  %zu TUs",
7924                            per_objfile->per_bfd->all_type_units.size ());
7925   dwarf_read_debug_printf ("  %d uniq abbrev tables",
7926                            tu_stats->nr_uniq_abbrev_tables);
7927   dwarf_read_debug_printf ("  %d symtabs from stmt_list entries",
7928                            tu_stats->nr_symtabs);
7929   dwarf_read_debug_printf ("  %d symtab sharers",
7930                            tu_stats->nr_symtab_sharers);
7931   dwarf_read_debug_printf ("  %d type units without a stmt_list",
7932                            tu_stats->nr_stmt_less_type_units);
7933   dwarf_read_debug_printf ("  %d all_type_units reallocs",
7934                            tu_stats->nr_all_type_units_reallocs);
7935 }
7936
7937 /* Traversal function for build_type_psymtabs.  */
7938
7939 static int
7940 build_type_psymtab_dependencies (void **slot, void *info)
7941 {
7942   dwarf2_per_objfile *per_objfile = (dwarf2_per_objfile *) info;
7943   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
7944   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
7945   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
7946   dwarf2_psymtab *pst = per_cu->v.psymtab;
7947   int len = (tu_group->tus == nullptr) ? 0 : tu_group->tus->size ();
7948   int i;
7949
7950   gdb_assert (len > 0);
7951   gdb_assert (per_cu->type_unit_group_p ());
7952
7953   pst->number_of_dependencies = len;
7954   pst->dependencies = per_bfd->partial_symtabs->allocate_dependencies (len);
7955   for (i = 0; i < len; ++i)
7956     {
7957       struct signatured_type *iter = tu_group->tus->at (i);
7958       gdb_assert (iter->per_cu.is_debug_types);
7959       pst->dependencies[i] = iter->per_cu.v.psymtab;
7960       iter->type_unit_group = tu_group;
7961     }
7962
7963   delete tu_group->tus;
7964   tu_group->tus = nullptr;
7965
7966   return 1;
7967 }
7968
7969 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7970    Build partial symbol tables for the .debug_types comp-units.  */
7971
7972 static void
7973 build_type_psymtabs (dwarf2_per_objfile *per_objfile)
7974 {
7975   if (! create_all_type_units (per_objfile))
7976     return;
7977
7978   build_type_psymtabs_1 (per_objfile);
7979 }
7980
7981 /* Traversal function for process_skeletonless_type_unit.
7982    Read a TU in a DWO file and build partial symbols for it.  */
7983
7984 static int
7985 process_skeletonless_type_unit (void **slot, void *info)
7986 {
7987   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
7988   dwarf2_per_objfile *per_objfile = (dwarf2_per_objfile *) info;
7989   struct signatured_type find_entry, *entry;
7990
7991   /* If this TU doesn't exist in the global table, add it and read it in.  */
7992
7993   if (per_objfile->per_bfd->signatured_types == NULL)
7994     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
7995
7996   find_entry.signature = dwo_unit->signature;
7997   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
7998                          &find_entry, INSERT);
7999   /* If we've already seen this type there's nothing to do.  What's happening
8000      is we're doing our own version of comdat-folding here.  */
8001   if (*slot != NULL)
8002     return 1;
8003
8004   /* This does the job that create_all_type_units would have done for
8005      this TU.  */
8006   entry = add_type_unit (per_objfile, dwo_unit->signature, slot);
8007   fill_in_sig_entry_from_dwo_entry (per_objfile, entry, dwo_unit);
8008   *slot = entry;
8009
8010   /* This does the job that build_type_psymtabs_1 would have done.  */
8011   cutu_reader reader (&entry->per_cu, per_objfile, nullptr, nullptr, false);
8012   if (!reader.dummy_p)
8013     build_type_psymtabs_reader (&reader, reader.info_ptr,
8014                                 reader.comp_unit_die);
8015
8016   return 1;
8017 }
8018
8019 /* Traversal function for process_skeletonless_type_units.  */
8020
8021 static int
8022 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8023 {
8024   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8025
8026   if (dwo_file->tus != NULL)
8027     htab_traverse_noresize (dwo_file->tus.get (),
8028                             process_skeletonless_type_unit, info);
8029
8030   return 1;
8031 }
8032
8033 /* Scan all TUs of DWO files, verifying we've processed them.
8034    This is needed in case a TU was emitted without its skeleton.
8035    Note: This can't be done until we know what all the DWO files are.  */
8036
8037 static void
8038 process_skeletonless_type_units (dwarf2_per_objfile *per_objfile)
8039 {
8040   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8041   if (get_dwp_file (per_objfile) == NULL
8042       && per_objfile->per_bfd->dwo_files != NULL)
8043     {
8044       htab_traverse_noresize (per_objfile->per_bfd->dwo_files.get (),
8045                               process_dwo_file_for_skeletonless_type_units,
8046                               per_objfile);
8047     }
8048 }
8049
8050 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8051
8052 static void
8053 set_partial_user (dwarf2_per_objfile *per_objfile)
8054 {
8055   for (dwarf2_per_cu_data *per_cu : per_objfile->per_bfd->all_comp_units)
8056     {
8057       dwarf2_psymtab *pst = per_cu->v.psymtab;
8058
8059       if (pst == NULL)
8060         continue;
8061
8062       for (int j = 0; j < pst->number_of_dependencies; ++j)
8063         {
8064           /* Set the 'user' field only if it is not already set.  */
8065           if (pst->dependencies[j]->user == NULL)
8066             pst->dependencies[j]->user = pst;
8067         }
8068     }
8069 }
8070
8071 /* Build the partial symbol table by doing a quick pass through the
8072    .debug_info and .debug_abbrev sections.  */
8073
8074 static void
8075 dwarf2_build_psymtabs_hard (dwarf2_per_objfile *per_objfile)
8076 {
8077   struct objfile *objfile = per_objfile->objfile;
8078   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
8079
8080   dwarf_read_debug_printf ("Building psymtabs of objfile %s ...",
8081                            objfile_name (objfile));
8082
8083   scoped_restore restore_reading_psyms
8084     = make_scoped_restore (&per_bfd->reading_partial_symbols, true);
8085
8086   per_bfd->info.read (objfile);
8087
8088   /* Any cached compilation units will be linked by the per-objfile
8089      read_in_chain.  Make sure to free them when we're done.  */
8090   free_cached_comp_units freer (per_objfile);
8091
8092   build_type_psymtabs (per_objfile);
8093
8094   create_all_comp_units (per_objfile);
8095
8096   /* Create a temporary address map on a temporary obstack.  We later
8097      copy this to the final obstack.  */
8098   auto_obstack temp_obstack;
8099
8100   scoped_restore save_psymtabs_addrmap
8101     = make_scoped_restore (&per_bfd->partial_symtabs->psymtabs_addrmap,
8102                            addrmap_create_mutable (&temp_obstack));
8103
8104   for (dwarf2_per_cu_data *per_cu : per_bfd->all_comp_units)
8105     {
8106       if (per_cu->v.psymtab != NULL)
8107         /* In case a forward DW_TAG_imported_unit has read the CU already.  */
8108         continue;
8109       process_psymtab_comp_unit (per_cu, per_objfile, false,
8110                                  language_minimal);
8111     }
8112
8113   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8114   process_skeletonless_type_units (per_objfile);
8115
8116   /* Now that all TUs have been processed we can fill in the dependencies.  */
8117   if (per_bfd->type_unit_groups != NULL)
8118     {
8119       htab_traverse_noresize (per_bfd->type_unit_groups.get (),
8120                               build_type_psymtab_dependencies, per_objfile);
8121     }
8122
8123   if (dwarf_read_debug > 0)
8124     print_tu_stats (per_objfile);
8125
8126   set_partial_user (per_objfile);
8127
8128   per_bfd->partial_symtabs->psymtabs_addrmap
8129     = addrmap_create_fixed (per_bfd->partial_symtabs->psymtabs_addrmap,
8130                             per_bfd->partial_symtabs->obstack ());
8131   /* At this point we want to keep the address map.  */
8132   save_psymtabs_addrmap.release ();
8133
8134   dwarf_read_debug_printf ("Done building psymtabs of %s",
8135                            objfile_name (objfile));
8136 }
8137
8138 /* Load the partial DIEs for a secondary CU into memory.
8139    This is also used when rereading a primary CU with load_all_dies.  */
8140
8141 static void
8142 load_partial_comp_unit (dwarf2_per_cu_data *this_cu,
8143                         dwarf2_per_objfile *per_objfile,
8144                         dwarf2_cu *existing_cu)
8145 {
8146   cutu_reader reader (this_cu, per_objfile, nullptr, existing_cu, false);
8147
8148   if (!reader.dummy_p)
8149     {
8150       prepare_one_comp_unit (reader.cu, reader.comp_unit_die,
8151                              language_minimal);
8152
8153       /* Check if comp unit has_children.
8154          If so, read the rest of the partial symbols from this comp unit.
8155          If not, there's no more debug_info for this comp unit.  */
8156       if (reader.comp_unit_die->has_children)
8157         load_partial_dies (&reader, reader.info_ptr, 0);
8158
8159       reader.keep ();
8160     }
8161 }
8162
8163 static void
8164 read_comp_units_from_section (dwarf2_per_objfile *per_objfile,
8165                               struct dwarf2_section_info *section,
8166                               struct dwarf2_section_info *abbrev_section,
8167                               unsigned int is_dwz)
8168 {
8169   const gdb_byte *info_ptr;
8170   struct objfile *objfile = per_objfile->objfile;
8171
8172   dwarf_read_debug_printf ("Reading %s for %s",
8173                            section->get_name (),
8174                            section->get_file_name ());
8175
8176   section->read (objfile);
8177
8178   info_ptr = section->buffer;
8179
8180   while (info_ptr < section->buffer + section->size)
8181     {
8182       struct dwarf2_per_cu_data *this_cu;
8183
8184       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8185
8186       comp_unit_head cu_header;
8187       read_and_check_comp_unit_head (per_objfile, &cu_header, section,
8188                                      abbrev_section, info_ptr,
8189                                      rcuh_kind::COMPILE);
8190
8191       /* Save the compilation unit for later lookup.  */
8192       if (cu_header.unit_type != DW_UT_type)
8193         this_cu = per_objfile->per_bfd->allocate_per_cu ();
8194       else
8195         {
8196           auto sig_type = per_objfile->per_bfd->allocate_signatured_type ();
8197           sig_type->signature = cu_header.signature;
8198           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8199           this_cu = &sig_type->per_cu;
8200         }
8201       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8202       this_cu->sect_off = sect_off;
8203       this_cu->length = cu_header.length + cu_header.initial_length_size;
8204       this_cu->is_dwz = is_dwz;
8205       this_cu->section = section;
8206
8207       per_objfile->per_bfd->all_comp_units.push_back (this_cu);
8208
8209       info_ptr = info_ptr + this_cu->length;
8210     }
8211 }
8212
8213 /* Create a list of all compilation units in OBJFILE.
8214    This is only done for -readnow and building partial symtabs.  */
8215
8216 static void
8217 create_all_comp_units (dwarf2_per_objfile *per_objfile)
8218 {
8219   gdb_assert (per_objfile->per_bfd->all_comp_units.empty ());
8220   read_comp_units_from_section (per_objfile, &per_objfile->per_bfd->info,
8221                                 &per_objfile->per_bfd->abbrev, 0);
8222
8223   dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd);
8224   if (dwz != NULL)
8225     read_comp_units_from_section (per_objfile, &dwz->info, &dwz->abbrev, 1);
8226 }
8227
8228 /* Process all loaded DIEs for compilation unit CU, starting at
8229    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8230    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8231    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8232    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8233
8234 static void
8235 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8236                       CORE_ADDR *highpc, int set_addrmap,
8237                       struct dwarf2_cu *cu)
8238 {
8239   struct partial_die_info *pdi;
8240
8241   /* Now, march along the PDI's, descending into ones which have
8242      interesting children but skipping the children of the other ones,
8243      until we reach the end of the compilation unit.  */
8244
8245   pdi = first_die;
8246
8247   while (pdi != NULL)
8248     {
8249       pdi->fixup (cu);
8250
8251       /* Anonymous namespaces or modules have no name but have interesting
8252          children, so we need to look at them.  Ditto for anonymous
8253          enums.  */
8254
8255       if (pdi->raw_name != NULL || pdi->tag == DW_TAG_namespace
8256           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8257           || pdi->tag == DW_TAG_imported_unit
8258           || pdi->tag == DW_TAG_inlined_subroutine)
8259         {
8260           switch (pdi->tag)
8261             {
8262             case DW_TAG_subprogram:
8263             case DW_TAG_inlined_subroutine:
8264               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8265               if (cu->language == language_cplus)
8266                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8267                                       set_addrmap, cu);
8268               break;
8269             case DW_TAG_constant:
8270             case DW_TAG_variable:
8271             case DW_TAG_typedef:
8272             case DW_TAG_union_type:
8273               if (!pdi->is_declaration
8274                   || (pdi->tag == DW_TAG_variable && pdi->is_external))
8275                 {
8276                   add_partial_symbol (pdi, cu);
8277                 }
8278               break;
8279             case DW_TAG_class_type:
8280             case DW_TAG_interface_type:
8281             case DW_TAG_structure_type:
8282               if (!pdi->is_declaration)
8283                 {
8284                   add_partial_symbol (pdi, cu);
8285                 }
8286               if ((cu->language == language_rust
8287                    || cu->language == language_cplus) && pdi->has_children)
8288                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8289                                       set_addrmap, cu);
8290               break;
8291             case DW_TAG_enumeration_type:
8292               if (!pdi->is_declaration)
8293                 add_partial_enumeration (pdi, cu);
8294               break;
8295             case DW_TAG_base_type:
8296             case DW_TAG_subrange_type:
8297               /* File scope base type definitions are added to the partial
8298                  symbol table.  */
8299               add_partial_symbol (pdi, cu);
8300               break;
8301             case DW_TAG_namespace:
8302               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8303               break;
8304             case DW_TAG_module:
8305               if (!pdi->is_declaration)
8306                 add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8307               break;
8308             case DW_TAG_imported_unit:
8309               {
8310                 struct dwarf2_per_cu_data *per_cu;
8311
8312                 /* For now we don't handle imported units in type units.  */
8313                 if (cu->per_cu->is_debug_types)
8314                   {
8315                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8316                              " supported in type units [in module %s]"),
8317                            objfile_name (cu->per_objfile->objfile));
8318                   }
8319
8320                 per_cu = dwarf2_find_containing_comp_unit
8321                            (pdi->d.sect_off, pdi->is_dwz, cu->per_objfile);
8322
8323                 /* Go read the partial unit, if needed.  */
8324                 if (per_cu->v.psymtab == NULL)
8325                   process_psymtab_comp_unit (per_cu, cu->per_objfile, true,
8326                                              cu->language);
8327
8328                 cu->per_cu->imported_symtabs_push (per_cu);
8329               }
8330               break;
8331             case DW_TAG_imported_declaration:
8332               add_partial_symbol (pdi, cu);
8333               break;
8334             default:
8335               break;
8336             }
8337         }
8338
8339       /* If the die has a sibling, skip to the sibling.  */
8340
8341       pdi = pdi->die_sibling;
8342     }
8343 }
8344
8345 /* Functions used to compute the fully scoped name of a partial DIE.
8346
8347    Normally, this is simple.  For C++, the parent DIE's fully scoped
8348    name is concatenated with "::" and the partial DIE's name.
8349    Enumerators are an exception; they use the scope of their parent
8350    enumeration type, i.e. the name of the enumeration type is not
8351    prepended to the enumerator.
8352
8353    There are two complexities.  One is DW_AT_specification; in this
8354    case "parent" means the parent of the target of the specification,
8355    instead of the direct parent of the DIE.  The other is compilers
8356    which do not emit DW_TAG_namespace; in this case we try to guess
8357    the fully qualified name of structure types from their members'
8358    linkage names.  This must be done using the DIE's children rather
8359    than the children of any DW_AT_specification target.  We only need
8360    to do this for structures at the top level, i.e. if the target of
8361    any DW_AT_specification (if any; otherwise the DIE itself) does not
8362    have a parent.  */
8363
8364 /* Compute the scope prefix associated with PDI's parent, in
8365    compilation unit CU.  The result will be allocated on CU's
8366    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8367    field.  NULL is returned if no prefix is necessary.  */
8368 static const char *
8369 partial_die_parent_scope (struct partial_die_info *pdi,
8370                           struct dwarf2_cu *cu)
8371 {
8372   const char *grandparent_scope;
8373   struct partial_die_info *parent, *real_pdi;
8374
8375   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8376      then this means the parent of the specification DIE.  */
8377
8378   real_pdi = pdi;
8379   while (real_pdi->has_specification)
8380     {
8381       auto res = find_partial_die (real_pdi->spec_offset,
8382                                    real_pdi->spec_is_dwz, cu);
8383       real_pdi = res.pdi;
8384       cu = res.cu;
8385     }
8386
8387   parent = real_pdi->die_parent;
8388   if (parent == NULL)
8389     return NULL;
8390
8391   if (parent->scope_set)
8392     return parent->scope;
8393
8394   parent->fixup (cu);
8395
8396   grandparent_scope = partial_die_parent_scope (parent, cu);
8397
8398   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8399      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8400      Work around this problem here.  */
8401   if (cu->language == language_cplus
8402       && parent->tag == DW_TAG_namespace
8403       && strcmp (parent->name (cu), "::") == 0
8404       && grandparent_scope == NULL)
8405     {
8406       parent->scope = NULL;
8407       parent->scope_set = 1;
8408       return NULL;
8409     }
8410
8411   /* Nested subroutines in Fortran get a prefix.  */
8412   if (pdi->tag == DW_TAG_enumerator)
8413     /* Enumerators should not get the name of the enumeration as a prefix.  */
8414     parent->scope = grandparent_scope;
8415   else if (parent->tag == DW_TAG_namespace
8416       || parent->tag == DW_TAG_module
8417       || parent->tag == DW_TAG_structure_type
8418       || parent->tag == DW_TAG_class_type
8419       || parent->tag == DW_TAG_interface_type
8420       || parent->tag == DW_TAG_union_type
8421       || parent->tag == DW_TAG_enumeration_type
8422       || (cu->language == language_fortran
8423           && parent->tag == DW_TAG_subprogram
8424           && pdi->tag == DW_TAG_subprogram))
8425     {
8426       if (grandparent_scope == NULL)
8427         parent->scope = parent->name (cu);
8428       else
8429         parent->scope = typename_concat (&cu->comp_unit_obstack,
8430                                          grandparent_scope,
8431                                          parent->name (cu), 0, cu);
8432     }
8433   else
8434     {
8435       /* FIXME drow/2004-04-01: What should we be doing with
8436          function-local names?  For partial symbols, we should probably be
8437          ignoring them.  */
8438       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
8439                  dwarf_tag_name (parent->tag),
8440                  sect_offset_str (pdi->sect_off));
8441       parent->scope = grandparent_scope;
8442     }
8443
8444   parent->scope_set = 1;
8445   return parent->scope;
8446 }
8447
8448 /* Return the fully scoped name associated with PDI, from compilation unit
8449    CU.  The result will be allocated with malloc.  */
8450
8451 static gdb::unique_xmalloc_ptr<char>
8452 partial_die_full_name (struct partial_die_info *pdi,
8453                        struct dwarf2_cu *cu)
8454 {
8455   const char *parent_scope;
8456
8457   /* If this is a template instantiation, we can not work out the
8458      template arguments from partial DIEs.  So, unfortunately, we have
8459      to go through the full DIEs.  At least any work we do building
8460      types here will be reused if full symbols are loaded later.  */
8461   if (pdi->has_template_arguments)
8462     {
8463       pdi->fixup (cu);
8464
8465       if (pdi->name (cu) != NULL && strchr (pdi->name (cu), '<') == NULL)
8466         {
8467           struct die_info *die;
8468           struct attribute attr;
8469           struct dwarf2_cu *ref_cu = cu;
8470
8471           /* DW_FORM_ref_addr is using section offset.  */
8472           attr.name = (enum dwarf_attribute) 0;
8473           attr.form = DW_FORM_ref_addr;
8474           attr.u.unsnd = to_underlying (pdi->sect_off);
8475           die = follow_die_ref (NULL, &attr, &ref_cu);
8476
8477           return make_unique_xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8478         }
8479     }
8480
8481   parent_scope = partial_die_parent_scope (pdi, cu);
8482   if (parent_scope == NULL)
8483     return NULL;
8484   else
8485     return gdb::unique_xmalloc_ptr<char> (typename_concat (NULL, parent_scope,
8486                                                            pdi->name (cu),
8487                                                            0, cu));
8488 }
8489
8490 static void
8491 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8492 {
8493   dwarf2_per_objfile *per_objfile = cu->per_objfile;
8494   struct objfile *objfile = per_objfile->objfile;
8495   struct gdbarch *gdbarch = objfile->arch ();
8496   CORE_ADDR addr = 0;
8497   const char *actual_name = NULL;
8498   CORE_ADDR baseaddr;
8499
8500   baseaddr = objfile->text_section_offset ();
8501
8502   gdb::unique_xmalloc_ptr<char> built_actual_name
8503     = partial_die_full_name (pdi, cu);
8504   if (built_actual_name != NULL)
8505     actual_name = built_actual_name.get ();
8506
8507   if (actual_name == NULL)
8508     actual_name = pdi->name (cu);
8509
8510   partial_symbol psymbol;
8511   memset (&psymbol, 0, sizeof (psymbol));
8512   psymbol.ginfo.set_language (cu->language, &objfile->objfile_obstack);
8513   psymbol.ginfo.set_section_index (-1);
8514
8515   /* The code below indicates that the psymbol should be installed by
8516      setting this.  */
8517   gdb::optional<psymbol_placement> where;
8518
8519   switch (pdi->tag)
8520     {
8521     case DW_TAG_inlined_subroutine:
8522     case DW_TAG_subprogram:
8523       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8524               - baseaddr);
8525       if (pdi->is_external
8526           || cu->language == language_ada
8527           || (cu->language == language_fortran
8528               && pdi->die_parent != NULL
8529               && pdi->die_parent->tag == DW_TAG_subprogram))
8530         {
8531           /* Normally, only "external" DIEs are part of the global scope.
8532              But in Ada and Fortran, we want to be able to access nested
8533              procedures globally.  So all Ada and Fortran subprograms are
8534              stored in the global scope.  */
8535           where = psymbol_placement::GLOBAL;
8536         }
8537       else
8538         where = psymbol_placement::STATIC;
8539
8540       psymbol.domain = VAR_DOMAIN;
8541       psymbol.aclass = LOC_BLOCK;
8542       psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
8543       psymbol.ginfo.value.address = addr;
8544
8545       if (pdi->main_subprogram && actual_name != NULL)
8546         set_objfile_main_name (objfile, actual_name, cu->language);
8547       break;
8548     case DW_TAG_constant:
8549       psymbol.domain = VAR_DOMAIN;
8550       psymbol.aclass = LOC_STATIC;
8551       where = (pdi->is_external
8552                ? psymbol_placement::GLOBAL
8553                : psymbol_placement::STATIC);
8554       break;
8555     case DW_TAG_variable:
8556       if (pdi->d.locdesc)
8557         addr = decode_locdesc (pdi->d.locdesc, cu);
8558
8559       if (pdi->d.locdesc
8560           && addr == 0
8561           && !per_objfile->per_bfd->has_section_at_zero)
8562         {
8563           /* A global or static variable may also have been stripped
8564              out by the linker if unused, in which case its address
8565              will be nullified; do not add such variables into partial
8566              symbol table then.  */
8567         }
8568       else if (pdi->is_external)
8569         {
8570           /* Global Variable.
8571              Don't enter into the minimal symbol tables as there is
8572              a minimal symbol table entry from the ELF symbols already.
8573              Enter into partial symbol table if it has a location
8574              descriptor or a type.
8575              If the location descriptor is missing, new_symbol will create
8576              a LOC_UNRESOLVED symbol, the address of the variable will then
8577              be determined from the minimal symbol table whenever the variable
8578              is referenced.
8579              The address for the partial symbol table entry is not
8580              used by GDB, but it comes in handy for debugging partial symbol
8581              table building.  */
8582
8583           if (pdi->d.locdesc || pdi->has_type)
8584             {
8585               psymbol.domain = VAR_DOMAIN;
8586               psymbol.aclass = LOC_STATIC;
8587               psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
8588               psymbol.ginfo.value.address = addr;
8589               where = psymbol_placement::GLOBAL;
8590             }
8591         }
8592       else
8593         {
8594           int has_loc = pdi->d.locdesc != NULL;
8595
8596           /* Static Variable.  Skip symbols whose value we cannot know (those
8597              without location descriptors or constant values).  */
8598           if (!has_loc && !pdi->has_const_value)
8599             return;
8600
8601           psymbol.domain = VAR_DOMAIN;
8602           psymbol.aclass = LOC_STATIC;
8603           psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
8604           if (has_loc)
8605             psymbol.ginfo.value.address = addr;
8606           where = psymbol_placement::STATIC;
8607         }
8608       break;
8609     case DW_TAG_array_type:
8610     case DW_TAG_typedef:
8611     case DW_TAG_base_type:
8612     case DW_TAG_subrange_type:
8613       psymbol.domain = VAR_DOMAIN;
8614       psymbol.aclass = LOC_TYPEDEF;
8615       where = psymbol_placement::STATIC;
8616       break;
8617     case DW_TAG_imported_declaration:
8618     case DW_TAG_namespace:
8619       psymbol.domain = VAR_DOMAIN;
8620       psymbol.aclass = LOC_TYPEDEF;
8621       where = psymbol_placement::GLOBAL;
8622       break;
8623     case DW_TAG_module:
8624       /* With Fortran 77 there might be a "BLOCK DATA" module
8625          available without any name.  If so, we skip the module as it
8626          doesn't bring any value.  */
8627       if (actual_name != nullptr)
8628         {
8629           psymbol.domain = MODULE_DOMAIN;
8630           psymbol.aclass = LOC_TYPEDEF;
8631           where = psymbol_placement::GLOBAL;
8632         }
8633       break;
8634     case DW_TAG_class_type:
8635     case DW_TAG_interface_type:
8636     case DW_TAG_structure_type:
8637     case DW_TAG_union_type:
8638     case DW_TAG_enumeration_type:
8639       /* Skip external references.  The DWARF standard says in the section
8640          about "Structure, Union, and Class Type Entries": "An incomplete
8641          structure, union or class type is represented by a structure,
8642          union or class entry that does not have a byte size attribute
8643          and that has a DW_AT_declaration attribute."  */
8644       if (!pdi->has_byte_size && pdi->is_declaration)
8645         return;
8646
8647       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8648          static vs. global.  */
8649       psymbol.domain = STRUCT_DOMAIN;
8650       psymbol.aclass = LOC_TYPEDEF;
8651       where = (cu->language == language_cplus
8652                ? psymbol_placement::GLOBAL
8653                : psymbol_placement::STATIC);
8654       break;
8655     case DW_TAG_enumerator:
8656       psymbol.domain = VAR_DOMAIN;
8657       psymbol.aclass = LOC_CONST;
8658       where = (cu->language == language_cplus
8659                ? psymbol_placement::GLOBAL
8660                : psymbol_placement::STATIC);
8661       break;
8662     default:
8663       break;
8664     }
8665
8666   if (where.has_value ())
8667     {
8668       if (built_actual_name != nullptr)
8669         actual_name = objfile->intern (actual_name);
8670       if (pdi->linkage_name == nullptr || cu->language == language_ada)
8671         psymbol.ginfo.set_linkage_name (actual_name);
8672       else
8673         {
8674           psymbol.ginfo.set_demangled_name (actual_name,
8675                                             &objfile->objfile_obstack);
8676           psymbol.ginfo.set_linkage_name (pdi->linkage_name);
8677         }
8678       cu->per_cu->v.psymtab->add_psymbol
8679         (psymbol, *where, per_objfile->per_bfd->partial_symtabs.get (),
8680          objfile);
8681     }
8682 }
8683
8684 /* Read a partial die corresponding to a namespace; also, add a symbol
8685    corresponding to that namespace to the symbol table.  NAMESPACE is
8686    the name of the enclosing namespace.  */
8687
8688 static void
8689 add_partial_namespace (struct partial_die_info *pdi,
8690                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8691                        int set_addrmap, struct dwarf2_cu *cu)
8692 {
8693   /* Add a symbol for the namespace.  */
8694
8695   add_partial_symbol (pdi, cu);
8696
8697   /* Now scan partial symbols in that namespace.  */
8698
8699   if (pdi->has_children)
8700     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8701 }
8702
8703 /* Read a partial die corresponding to a Fortran module.  */
8704
8705 static void
8706 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8707                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8708 {
8709   /* Add a symbol for the namespace.  */
8710
8711   add_partial_symbol (pdi, cu);
8712
8713   /* Now scan partial symbols in that module.  */
8714
8715   if (pdi->has_children)
8716     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8717 }
8718
8719 /* Read a partial die corresponding to a subprogram or an inlined
8720    subprogram and create a partial symbol for that subprogram.
8721    When the CU language allows it, this routine also defines a partial
8722    symbol for each nested subprogram that this subprogram contains.
8723    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
8724    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
8725
8726    PDI may also be a lexical block, in which case we simply search
8727    recursively for subprograms defined inside that lexical block.
8728    Again, this is only performed when the CU language allows this
8729    type of definitions.  */
8730
8731 static void
8732 add_partial_subprogram (struct partial_die_info *pdi,
8733                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
8734                         int set_addrmap, struct dwarf2_cu *cu)
8735 {
8736   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
8737     {
8738       if (pdi->has_pc_info)
8739         {
8740           if (pdi->lowpc < *lowpc)
8741             *lowpc = pdi->lowpc;
8742           if (pdi->highpc > *highpc)
8743             *highpc = pdi->highpc;
8744           if (set_addrmap)
8745             {
8746               struct objfile *objfile = cu->per_objfile->objfile;
8747               dwarf2_per_bfd *per_bfd = cu->per_objfile->per_bfd;
8748               struct gdbarch *gdbarch = objfile->arch ();
8749               CORE_ADDR baseaddr;
8750               CORE_ADDR this_highpc;
8751               CORE_ADDR this_lowpc;
8752
8753               baseaddr = objfile->text_section_offset ();
8754               this_lowpc
8755                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8756                                                pdi->lowpc + baseaddr)
8757                    - baseaddr);
8758               this_highpc
8759                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8760                                                pdi->highpc + baseaddr)
8761                    - baseaddr);
8762               addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
8763                                  this_lowpc, this_highpc - 1,
8764                                  cu->per_cu->v.psymtab);
8765             }
8766         }
8767
8768       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8769         {
8770           if (!pdi->is_declaration)
8771             /* Ignore subprogram DIEs that do not have a name, they are
8772                illegal.  Do not emit a complaint at this point, we will
8773                do so when we convert this psymtab into a symtab.  */
8774             if (pdi->name (cu))
8775               add_partial_symbol (pdi, cu);
8776         }
8777     }
8778
8779   if (! pdi->has_children)
8780     return;
8781
8782   if (cu->language == language_ada || cu->language == language_fortran)
8783     {
8784       pdi = pdi->die_child;
8785       while (pdi != NULL)
8786         {
8787           pdi->fixup (cu);
8788           if (pdi->tag == DW_TAG_subprogram
8789               || pdi->tag == DW_TAG_inlined_subroutine
8790               || pdi->tag == DW_TAG_lexical_block)
8791             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8792           pdi = pdi->die_sibling;
8793         }
8794     }
8795 }
8796
8797 /* Read a partial die corresponding to an enumeration type.  */
8798
8799 static void
8800 add_partial_enumeration (struct partial_die_info *enum_pdi,
8801                          struct dwarf2_cu *cu)
8802 {
8803   struct partial_die_info *pdi;
8804
8805   if (enum_pdi->name (cu) != NULL)
8806     add_partial_symbol (enum_pdi, cu);
8807
8808   pdi = enum_pdi->die_child;
8809   while (pdi)
8810     {
8811       if (pdi->tag != DW_TAG_enumerator || pdi->raw_name == NULL)
8812         complaint (_("malformed enumerator DIE ignored"));
8813       else
8814         add_partial_symbol (pdi, cu);
8815       pdi = pdi->die_sibling;
8816     }
8817 }
8818
8819 /* Return the initial uleb128 in the die at INFO_PTR.  */
8820
8821 static unsigned int
8822 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8823 {
8824   unsigned int bytes_read;
8825
8826   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8827 }
8828
8829 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
8830    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
8831
8832    Return the corresponding abbrev, or NULL if the number is zero (indicating
8833    an empty DIE).  In either case *BYTES_READ will be set to the length of
8834    the initial number.  */
8835
8836 static const struct abbrev_info *
8837 peek_die_abbrev (const die_reader_specs &reader,
8838                  const gdb_byte *info_ptr, unsigned int *bytes_read)
8839 {
8840   dwarf2_cu *cu = reader.cu;
8841   bfd *abfd = reader.abfd;
8842   unsigned int abbrev_number
8843     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8844
8845   if (abbrev_number == 0)
8846     return NULL;
8847
8848   const abbrev_info *abbrev
8849     = reader.abbrev_table->lookup_abbrev (abbrev_number);
8850   if (!abbrev)
8851     {
8852       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8853                " at offset %s [in module %s]"),
8854              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8855              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
8856     }
8857
8858   return abbrev;
8859 }
8860
8861 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8862    Returns a pointer to the end of a series of DIEs, terminated by an empty
8863    DIE.  Any children of the skipped DIEs will also be skipped.  */
8864
8865 static const gdb_byte *
8866 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8867 {
8868   while (1)
8869     {
8870       unsigned int bytes_read;
8871       const abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr,
8872                                                    &bytes_read);
8873
8874       if (abbrev == NULL)
8875         return info_ptr + bytes_read;
8876       else
8877         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8878     }
8879 }
8880
8881 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8882    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8883    abbrev corresponding to that skipped uleb128 should be passed in
8884    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8885    children.  */
8886
8887 static const gdb_byte *
8888 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8889               const struct abbrev_info *abbrev)
8890 {
8891   unsigned int bytes_read;
8892   struct attribute attr;
8893   bfd *abfd = reader->abfd;
8894   struct dwarf2_cu *cu = reader->cu;
8895   const gdb_byte *buffer = reader->buffer;
8896   const gdb_byte *buffer_end = reader->buffer_end;
8897   unsigned int form, i;
8898
8899   for (i = 0; i < abbrev->num_attrs; i++)
8900     {
8901       /* The only abbrev we care about is DW_AT_sibling.  */
8902       if (abbrev->attrs[i].name == DW_AT_sibling)
8903         {
8904           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
8905           if (attr.form == DW_FORM_ref_addr)
8906             complaint (_("ignoring absolute DW_AT_sibling"));
8907           else
8908             {
8909               sect_offset off = attr.get_ref_die_offset ();
8910               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8911
8912               if (sibling_ptr < info_ptr)
8913                 complaint (_("DW_AT_sibling points backwards"));
8914               else if (sibling_ptr > reader->buffer_end)
8915                 reader->die_section->overflow_complaint ();
8916               else
8917                 return sibling_ptr;
8918             }
8919         }
8920
8921       /* If it isn't DW_AT_sibling, skip this attribute.  */
8922       form = abbrev->attrs[i].form;
8923     skip_attribute:
8924       switch (form)
8925         {
8926         case DW_FORM_ref_addr:
8927           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8928              and later it is offset sized.  */
8929           if (cu->header.version == 2)
8930             info_ptr += cu->header.addr_size;
8931           else
8932             info_ptr += cu->header.offset_size;
8933           break;
8934         case DW_FORM_GNU_ref_alt:
8935           info_ptr += cu->header.offset_size;
8936           break;
8937         case DW_FORM_addr:
8938           info_ptr += cu->header.addr_size;
8939           break;
8940         case DW_FORM_data1:
8941         case DW_FORM_ref1:
8942         case DW_FORM_flag:
8943         case DW_FORM_strx1:
8944           info_ptr += 1;
8945           break;
8946         case DW_FORM_flag_present:
8947         case DW_FORM_implicit_const:
8948           break;
8949         case DW_FORM_data2:
8950         case DW_FORM_ref2:
8951         case DW_FORM_strx2:
8952           info_ptr += 2;
8953           break;
8954         case DW_FORM_strx3:
8955           info_ptr += 3;
8956           break;
8957         case DW_FORM_data4:
8958         case DW_FORM_ref4:
8959         case DW_FORM_strx4:
8960           info_ptr += 4;
8961           break;
8962         case DW_FORM_data8:
8963         case DW_FORM_ref8:
8964         case DW_FORM_ref_sig8:
8965           info_ptr += 8;
8966           break;
8967         case DW_FORM_data16:
8968           info_ptr += 16;
8969           break;
8970         case DW_FORM_string:
8971           read_direct_string (abfd, info_ptr, &bytes_read);
8972           info_ptr += bytes_read;
8973           break;
8974         case DW_FORM_sec_offset:
8975         case DW_FORM_strp:
8976         case DW_FORM_GNU_strp_alt:
8977           info_ptr += cu->header.offset_size;
8978           break;
8979         case DW_FORM_exprloc:
8980         case DW_FORM_block:
8981           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8982           info_ptr += bytes_read;
8983           break;
8984         case DW_FORM_block1:
8985           info_ptr += 1 + read_1_byte (abfd, info_ptr);
8986           break;
8987         case DW_FORM_block2:
8988           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
8989           break;
8990         case DW_FORM_block4:
8991           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
8992           break;
8993         case DW_FORM_addrx:
8994         case DW_FORM_strx:
8995         case DW_FORM_sdata:
8996         case DW_FORM_udata:
8997         case DW_FORM_ref_udata:
8998         case DW_FORM_GNU_addr_index:
8999         case DW_FORM_GNU_str_index:
9000         case DW_FORM_rnglistx:
9001         case DW_FORM_loclistx:
9002           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9003           break;
9004         case DW_FORM_indirect:
9005           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9006           info_ptr += bytes_read;
9007           /* We need to continue parsing from here, so just go back to
9008              the top.  */
9009           goto skip_attribute;
9010
9011         default:
9012           error (_("Dwarf Error: Cannot handle %s "
9013                    "in DWARF reader [in module %s]"),
9014                  dwarf_form_name (form),
9015                  bfd_get_filename (abfd));
9016         }
9017     }
9018
9019   if (abbrev->has_children)
9020     return skip_children (reader, info_ptr);
9021   else
9022     return info_ptr;
9023 }
9024
9025 /* Locate ORIG_PDI's sibling.
9026    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9027
9028 static const gdb_byte *
9029 locate_pdi_sibling (const struct die_reader_specs *reader,
9030                     struct partial_die_info *orig_pdi,
9031                     const gdb_byte *info_ptr)
9032 {
9033   /* Do we know the sibling already?  */
9034
9035   if (orig_pdi->sibling)
9036     return orig_pdi->sibling;
9037
9038   /* Are there any children to deal with?  */
9039
9040   if (!orig_pdi->has_children)
9041     return info_ptr;
9042
9043   /* Skip the children the long way.  */
9044
9045   return skip_children (reader, info_ptr);
9046 }
9047
9048 /* Expand this partial symbol table into a full symbol table.  SELF is
9049    not NULL.  */
9050
9051 void
9052 dwarf2_psymtab::read_symtab (struct objfile *objfile)
9053 {
9054   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
9055
9056   gdb_assert (!per_objfile->symtab_set_p (per_cu_data));
9057
9058   /* If this psymtab is constructed from a debug-only objfile, the
9059      has_section_at_zero flag will not necessarily be correct.  We
9060      can get the correct value for this flag by looking at the data
9061      associated with the (presumably stripped) associated objfile.  */
9062   if (objfile->separate_debug_objfile_backlink)
9063     {
9064       dwarf2_per_objfile *per_objfile_backlink
9065         = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9066
9067       per_objfile->per_bfd->has_section_at_zero
9068         = per_objfile_backlink->per_bfd->has_section_at_zero;
9069     }
9070
9071   expand_psymtab (objfile);
9072
9073   process_cu_includes (per_objfile);
9074 }
9075 \f
9076 /* Reading in full CUs.  */
9077
9078 /* Add PER_CU to the queue.  */
9079
9080 static void
9081 queue_comp_unit (dwarf2_per_cu_data *per_cu,
9082                  dwarf2_per_objfile *per_objfile,
9083                  enum language pretend_language)
9084 {
9085   per_cu->queued = 1;
9086
9087   gdb_assert (per_objfile->per_bfd->queue.has_value ());
9088   per_cu->per_bfd->queue->emplace (per_cu, per_objfile, pretend_language);
9089 }
9090
9091 /* If PER_CU is not yet expanded of queued for expansion, add it to the queue.
9092
9093    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9094    dependency.
9095
9096    Return true if maybe_queue_comp_unit requires the caller to load the CU's
9097    DIEs, false otherwise.
9098
9099    Explanation: there is an invariant that if a CU is queued for expansion
9100    (present in `dwarf2_per_bfd::queue`), then its DIEs are loaded
9101    (a dwarf2_cu object exists for this CU, and `dwarf2_per_objfile::get_cu`
9102    returns non-nullptr).  If the CU gets enqueued by this function but its DIEs
9103    are not yet loaded, the the caller must load the CU's DIEs to ensure the
9104    invariant is respected.
9105
9106    The caller is therefore not required to load the CU's DIEs (we return false)
9107    if:
9108
9109      - the CU is already expanded, and therefore does not get enqueued
9110      - the CU gets enqueued for expansion, but its DIEs are already loaded
9111
9112    Note that the caller should not use this function's return value as an
9113    indicator of whether the CU's DIEs are loaded right now, it should check
9114    that by calling `dwarf2_per_objfile::get_cu` instead.  */
9115
9116 static int
9117 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9118                        dwarf2_per_cu_data *per_cu,
9119                        dwarf2_per_objfile *per_objfile,
9120                        enum language pretend_language)
9121 {
9122   /* We may arrive here during partial symbol reading, if we need full
9123      DIEs to process an unusual case (e.g. template arguments).  Do
9124      not queue PER_CU, just tell our caller to load its DIEs.  */
9125   if (per_cu->per_bfd->reading_partial_symbols)
9126     {
9127       dwarf2_cu *cu = per_objfile->get_cu (per_cu);
9128
9129       if (cu == NULL || cu->dies == NULL)
9130         return 1;
9131       return 0;
9132     }
9133
9134   /* Mark the dependence relation so that we don't flush PER_CU
9135      too early.  */
9136   if (dependent_cu != NULL)
9137     dwarf2_add_dependence (dependent_cu, per_cu);
9138
9139   /* If it's already on the queue, we have nothing to do.  */
9140   if (per_cu->queued)
9141     {
9142       /* Verify the invariant that if a CU is queued for expansion, its DIEs are
9143          loaded.  */
9144       gdb_assert (per_objfile->get_cu (per_cu) != nullptr);
9145
9146       /* If the CU is queued for expansion, it should not already be
9147          expanded.  */
9148       gdb_assert (!per_objfile->symtab_set_p (per_cu));
9149
9150       /* The DIEs are already loaded, the caller doesn't need to do it.  */
9151       return 0;
9152     }
9153
9154   bool queued = false;
9155   if (!per_objfile->symtab_set_p (per_cu))
9156     {
9157       /* Add it to the queue.  */
9158       queue_comp_unit (per_cu, per_objfile,  pretend_language);
9159       queued = true;
9160     }
9161
9162   /* If the compilation unit is already loaded, just mark it as
9163      used.  */
9164   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
9165   if (cu != nullptr)
9166     cu->last_used = 0;
9167
9168   /* Ask the caller to load the CU's DIEs if the CU got enqueued for expansion
9169      and the DIEs are not already loaded.  */
9170   return queued && cu == nullptr;
9171 }
9172
9173 /* Process the queue.  */
9174
9175 static void
9176 process_queue (dwarf2_per_objfile *per_objfile)
9177 {
9178   dwarf_read_debug_printf ("Expanding one or more symtabs of objfile %s ...",
9179                            objfile_name (per_objfile->objfile));
9180
9181   /* The queue starts out with one item, but following a DIE reference
9182      may load a new CU, adding it to the end of the queue.  */
9183   while (!per_objfile->per_bfd->queue->empty ())
9184     {
9185       dwarf2_queue_item &item = per_objfile->per_bfd->queue->front ();
9186       dwarf2_per_cu_data *per_cu = item.per_cu;
9187
9188       if (!per_objfile->symtab_set_p (per_cu))
9189         {
9190           dwarf2_cu *cu = per_objfile->get_cu (per_cu);
9191
9192           /* Skip dummy CUs.  */
9193           if (cu != nullptr)
9194             {
9195               unsigned int debug_print_threshold;
9196               char buf[100];
9197
9198               if (per_cu->is_debug_types)
9199                 {
9200                   struct signatured_type *sig_type =
9201                     (struct signatured_type *) per_cu;
9202
9203                   sprintf (buf, "TU %s at offset %s",
9204                            hex_string (sig_type->signature),
9205                            sect_offset_str (per_cu->sect_off));
9206                   /* There can be 100s of TUs.
9207                      Only print them in verbose mode.  */
9208                   debug_print_threshold = 2;
9209                 }
9210               else
9211                 {
9212                   sprintf (buf, "CU at offset %s",
9213                            sect_offset_str (per_cu->sect_off));
9214                   debug_print_threshold = 1;
9215                 }
9216
9217               if (dwarf_read_debug >= debug_print_threshold)
9218                 dwarf_read_debug_printf ("Expanding symtab of %s", buf);
9219
9220               if (per_cu->is_debug_types)
9221                 process_full_type_unit (cu, item.pretend_language);
9222               else
9223                 process_full_comp_unit (cu, item.pretend_language);
9224
9225               if (dwarf_read_debug >= debug_print_threshold)
9226                 dwarf_read_debug_printf ("Done expanding %s", buf);
9227             }
9228         }
9229
9230       per_cu->queued = 0;
9231       per_objfile->per_bfd->queue->pop ();
9232     }
9233
9234   dwarf_read_debug_printf ("Done expanding symtabs of %s.",
9235                            objfile_name (per_objfile->objfile));
9236 }
9237
9238 /* Read in full symbols for PST, and anything it depends on.  */
9239
9240 void
9241 dwarf2_psymtab::expand_psymtab (struct objfile *objfile)
9242 {
9243   gdb_assert (!readin_p (objfile));
9244
9245   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
9246   free_cached_comp_units freer (per_objfile);
9247   expand_dependencies (objfile);
9248
9249   dw2_do_instantiate_symtab (per_cu_data, per_objfile, false);
9250   gdb_assert (get_compunit_symtab (objfile) != nullptr);
9251 }
9252
9253 /* See psympriv.h.  */
9254
9255 bool
9256 dwarf2_psymtab::readin_p (struct objfile *objfile) const
9257 {
9258   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
9259   return per_objfile->symtab_set_p (per_cu_data);
9260 }
9261
9262 /* See psympriv.h.  */
9263
9264 compunit_symtab *
9265 dwarf2_psymtab::get_compunit_symtab (struct objfile *objfile) const
9266 {
9267   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
9268   return per_objfile->get_symtab (per_cu_data);
9269 }
9270
9271 /* Trivial hash function for die_info: the hash value of a DIE
9272    is its offset in .debug_info for this objfile.  */
9273
9274 static hashval_t
9275 die_hash (const void *item)
9276 {
9277   const struct die_info *die = (const struct die_info *) item;
9278
9279   return to_underlying (die->sect_off);
9280 }
9281
9282 /* Trivial comparison function for die_info structures: two DIEs
9283    are equal if they have the same offset.  */
9284
9285 static int
9286 die_eq (const void *item_lhs, const void *item_rhs)
9287 {
9288   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9289   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9290
9291   return die_lhs->sect_off == die_rhs->sect_off;
9292 }
9293
9294 /* Load the DIEs associated with PER_CU into memory.
9295
9296    In some cases, the caller, while reading partial symbols, will need to load
9297    the full symbols for the CU for some reason.  It will already have a
9298    dwarf2_cu object for THIS_CU and pass it as EXISTING_CU, so it can be re-used
9299    rather than creating a new one.  */
9300
9301 static void
9302 load_full_comp_unit (dwarf2_per_cu_data *this_cu,
9303                      dwarf2_per_objfile *per_objfile,
9304                      dwarf2_cu *existing_cu,
9305                      bool skip_partial,
9306                      enum language pretend_language)
9307 {
9308   gdb_assert (! this_cu->is_debug_types);
9309
9310   cutu_reader reader (this_cu, per_objfile, NULL, existing_cu, skip_partial);
9311   if (reader.dummy_p)
9312     return;
9313
9314   struct dwarf2_cu *cu = reader.cu;
9315   const gdb_byte *info_ptr = reader.info_ptr;
9316
9317   gdb_assert (cu->die_hash == NULL);
9318   cu->die_hash =
9319     htab_create_alloc_ex (cu->header.length / 12,
9320                           die_hash,
9321                           die_eq,
9322                           NULL,
9323                           &cu->comp_unit_obstack,
9324                           hashtab_obstack_allocate,
9325                           dummy_obstack_deallocate);
9326
9327   if (reader.comp_unit_die->has_children)
9328     reader.comp_unit_die->child
9329       = read_die_and_siblings (&reader, reader.info_ptr,
9330                                &info_ptr, reader.comp_unit_die);
9331   cu->dies = reader.comp_unit_die;
9332   /* comp_unit_die is not stored in die_hash, no need.  */
9333
9334   /* We try not to read any attributes in this function, because not
9335      all CUs needed for references have been loaded yet, and symbol
9336      table processing isn't initialized.  But we have to set the CU language,
9337      or we won't be able to build types correctly.
9338      Similarly, if we do not read the producer, we can not apply
9339      producer-specific interpretation.  */
9340   prepare_one_comp_unit (cu, cu->dies, pretend_language);
9341
9342   reader.keep ();
9343 }
9344
9345 /* Add a DIE to the delayed physname list.  */
9346
9347 static void
9348 add_to_method_list (struct type *type, int fnfield_index, int index,
9349                     const char *name, struct die_info *die,
9350                     struct dwarf2_cu *cu)
9351 {
9352   struct delayed_method_info mi;
9353   mi.type = type;
9354   mi.fnfield_index = fnfield_index;
9355   mi.index = index;
9356   mi.name = name;
9357   mi.die = die;
9358   cu->method_list.push_back (mi);
9359 }
9360
9361 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9362    "const" / "volatile".  If so, decrements LEN by the length of the
9363    modifier and return true.  Otherwise return false.  */
9364
9365 template<size_t N>
9366 static bool
9367 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9368 {
9369   size_t mod_len = sizeof (mod) - 1;
9370   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9371     {
9372       len -= mod_len;
9373       return true;
9374     }
9375   return false;
9376 }
9377
9378 /* Compute the physnames of any methods on the CU's method list.
9379
9380    The computation of method physnames is delayed in order to avoid the
9381    (bad) condition that one of the method's formal parameters is of an as yet
9382    incomplete type.  */
9383
9384 static void
9385 compute_delayed_physnames (struct dwarf2_cu *cu)
9386 {
9387   /* Only C++ delays computing physnames.  */
9388   if (cu->method_list.empty ())
9389     return;
9390   gdb_assert (cu->language == language_cplus);
9391
9392   for (const delayed_method_info &mi : cu->method_list)
9393     {
9394       const char *physname;
9395       struct fn_fieldlist *fn_flp
9396         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9397       physname = dwarf2_physname (mi.name, mi.die, cu);
9398       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9399         = physname ? physname : "";
9400
9401       /* Since there's no tag to indicate whether a method is a
9402          const/volatile overload, extract that information out of the
9403          demangled name.  */
9404       if (physname != NULL)
9405         {
9406           size_t len = strlen (physname);
9407
9408           while (1)
9409             {
9410               if (physname[len] == ')') /* shortcut */
9411                 break;
9412               else if (check_modifier (physname, len, " const"))
9413                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9414               else if (check_modifier (physname, len, " volatile"))
9415                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9416               else
9417                 break;
9418             }
9419         }
9420     }
9421
9422   /* The list is no longer needed.  */
9423   cu->method_list.clear ();
9424 }
9425
9426 /* Go objects should be embedded in a DW_TAG_module DIE,
9427    and it's not clear if/how imported objects will appear.
9428    To keep Go support simple until that's worked out,
9429    go back through what we've read and create something usable.
9430    We could do this while processing each DIE, and feels kinda cleaner,
9431    but that way is more invasive.
9432    This is to, for example, allow the user to type "p var" or "b main"
9433    without having to specify the package name, and allow lookups
9434    of module.object to work in contexts that use the expression
9435    parser.  */
9436
9437 static void
9438 fixup_go_packaging (struct dwarf2_cu *cu)
9439 {
9440   gdb::unique_xmalloc_ptr<char> package_name;
9441   struct pending *list;
9442   int i;
9443
9444   for (list = *cu->get_builder ()->get_global_symbols ();
9445        list != NULL;
9446        list = list->next)
9447     {
9448       for (i = 0; i < list->nsyms; ++i)
9449         {
9450           struct symbol *sym = list->symbol[i];
9451
9452           if (sym->language () == language_go
9453               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9454             {
9455               gdb::unique_xmalloc_ptr<char> this_package_name
9456                 (go_symbol_package_name (sym));
9457
9458               if (this_package_name == NULL)
9459                 continue;
9460               if (package_name == NULL)
9461                 package_name = std::move (this_package_name);
9462               else
9463                 {
9464                   struct objfile *objfile = cu->per_objfile->objfile;
9465                   if (strcmp (package_name.get (), this_package_name.get ()) != 0)
9466                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9467                                (symbol_symtab (sym) != NULL
9468                                 ? symtab_to_filename_for_display
9469                                     (symbol_symtab (sym))
9470                                 : objfile_name (objfile)),
9471                                this_package_name.get (), package_name.get ());
9472                 }
9473             }
9474         }
9475     }
9476
9477   if (package_name != NULL)
9478     {
9479       struct objfile *objfile = cu->per_objfile->objfile;
9480       const char *saved_package_name = objfile->intern (package_name.get ());
9481       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9482                                      saved_package_name);
9483       struct symbol *sym;
9484
9485       sym = new (&objfile->objfile_obstack) symbol;
9486       sym->set_language (language_go, &objfile->objfile_obstack);
9487       sym->compute_and_set_names (saved_package_name, false, objfile->per_bfd);
9488       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9489          e.g., "main" finds the "main" module and not C's main().  */
9490       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9491       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9492       SYMBOL_TYPE (sym) = type;
9493
9494       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
9495     }
9496 }
9497
9498 /* Allocate a fully-qualified name consisting of the two parts on the
9499    obstack.  */
9500
9501 static const char *
9502 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9503 {
9504   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9505 }
9506
9507 /* A helper that allocates a variant part to attach to a Rust enum
9508    type.  OBSTACK is where the results should be allocated.  TYPE is
9509    the type we're processing.  DISCRIMINANT_INDEX is the index of the
9510    discriminant.  It must be the index of one of the fields of TYPE,
9511    or -1 to mean there is no discriminant (univariant enum).
9512    DEFAULT_INDEX is the index of the default field; or -1 if there is
9513    no default.  RANGES is indexed by "effective" field number (the
9514    field index, but omitting the discriminant and default fields) and
9515    must hold the discriminant values used by the variants.  Note that
9516    RANGES must have a lifetime at least as long as OBSTACK -- either
9517    already allocated on it, or static.  */
9518
9519 static void
9520 alloc_rust_variant (struct obstack *obstack, struct type *type,
9521                     int discriminant_index, int default_index,
9522                     gdb::array_view<discriminant_range> ranges)
9523 {
9524   /* When DISCRIMINANT_INDEX == -1, we have a univariant enum.  */
9525   gdb_assert (discriminant_index == -1
9526               || (discriminant_index >= 0
9527                   && discriminant_index < type->num_fields ()));
9528   gdb_assert (default_index == -1
9529               || (default_index >= 0 && default_index < type->num_fields ()));
9530
9531   /* We have one variant for each non-discriminant field.  */
9532   int n_variants = type->num_fields ();
9533   if (discriminant_index != -1)
9534     --n_variants;
9535
9536   variant *variants = new (obstack) variant[n_variants];
9537   int var_idx = 0;
9538   int range_idx = 0;
9539   for (int i = 0; i < type->num_fields (); ++i)
9540     {
9541       if (i == discriminant_index)
9542         continue;
9543
9544       variants[var_idx].first_field = i;
9545       variants[var_idx].last_field = i + 1;
9546
9547       /* The default field does not need a range, but other fields do.
9548          We skipped the discriminant above.  */
9549       if (i != default_index)
9550         {
9551           variants[var_idx].discriminants = ranges.slice (range_idx, 1);
9552           ++range_idx;
9553         }
9554
9555       ++var_idx;
9556     }
9557
9558   gdb_assert (range_idx == ranges.size ());
9559   gdb_assert (var_idx == n_variants);
9560
9561   variant_part *part = new (obstack) variant_part;
9562   part->discriminant_index = discriminant_index;
9563   /* If there is no discriminant, then whether it is signed is of no
9564      consequence.  */
9565   part->is_unsigned
9566     = (discriminant_index == -1
9567        ? false
9568        : type->field (discriminant_index).type ()->is_unsigned ());
9569   part->variants = gdb::array_view<variant> (variants, n_variants);
9570
9571   void *storage = obstack_alloc (obstack, sizeof (gdb::array_view<variant_part>));
9572   gdb::array_view<variant_part> *prop_value
9573     = new (storage) gdb::array_view<variant_part> (part, 1);
9574
9575   struct dynamic_prop prop;
9576   prop.set_variant_parts (prop_value);
9577
9578   type->add_dyn_prop (DYN_PROP_VARIANT_PARTS, prop);
9579 }
9580
9581 /* Some versions of rustc emitted enums in an unusual way.
9582
9583    Ordinary enums were emitted as unions.  The first element of each
9584    structure in the union was named "RUST$ENUM$DISR".  This element
9585    held the discriminant.
9586
9587    These versions of Rust also implemented the "non-zero"
9588    optimization.  When the enum had two values, and one is empty and
9589    the other holds a pointer that cannot be zero, the pointer is used
9590    as the discriminant, with a zero value meaning the empty variant.
9591    Here, the union's first member is of the form
9592    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9593    where the fieldnos are the indices of the fields that should be
9594    traversed in order to find the field (which may be several fields deep)
9595    and the variantname is the name of the variant of the case when the
9596    field is zero.
9597
9598    This function recognizes whether TYPE is of one of these forms,
9599    and, if so, smashes it to be a variant type.  */
9600
9601 static void
9602 quirk_rust_enum (struct type *type, struct objfile *objfile)
9603 {
9604   gdb_assert (type->code () == TYPE_CODE_UNION);
9605
9606   /* We don't need to deal with empty enums.  */
9607   if (type->num_fields () == 0)
9608     return;
9609
9610 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9611   if (type->num_fields () == 1
9612       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9613     {
9614       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9615
9616       /* Decode the field name to find the offset of the
9617          discriminant.  */
9618       ULONGEST bit_offset = 0;
9619       struct type *field_type = type->field (0).type ();
9620       while (name[0] >= '0' && name[0] <= '9')
9621         {
9622           char *tail;
9623           unsigned long index = strtoul (name, &tail, 10);
9624           name = tail;
9625           if (*name != '$'
9626               || index >= field_type->num_fields ()
9627               || (TYPE_FIELD_LOC_KIND (field_type, index)
9628                   != FIELD_LOC_KIND_BITPOS))
9629             {
9630               complaint (_("Could not parse Rust enum encoding string \"%s\""
9631                            "[in module %s]"),
9632                          TYPE_FIELD_NAME (type, 0),
9633                          objfile_name (objfile));
9634               return;
9635             }
9636           ++name;
9637
9638           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9639           field_type = field_type->field (index).type ();
9640         }
9641
9642       /* Smash this type to be a structure type.  We have to do this
9643          because the type has already been recorded.  */
9644       type->set_code (TYPE_CODE_STRUCT);
9645       type->set_num_fields (3);
9646       /* Save the field we care about.  */
9647       struct field saved_field = type->field (0);
9648       type->set_fields
9649         ((struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field)));
9650
9651       /* Put the discriminant at index 0.  */
9652       type->field (0).set_type (field_type);
9653       TYPE_FIELD_ARTIFICIAL (type, 0) = 1;
9654       TYPE_FIELD_NAME (type, 0) = "<<discriminant>>";
9655       SET_FIELD_BITPOS (type->field (0), bit_offset);
9656
9657       /* The order of fields doesn't really matter, so put the real
9658          field at index 1 and the data-less field at index 2.  */
9659       type->field (1) = saved_field;
9660       TYPE_FIELD_NAME (type, 1)
9661         = rust_last_path_segment (type->field (1).type ()->name ());
9662       type->field (1).type ()->set_name
9663         (rust_fully_qualify (&objfile->objfile_obstack, type->name (),
9664                              TYPE_FIELD_NAME (type, 1)));
9665
9666       const char *dataless_name
9667         = rust_fully_qualify (&objfile->objfile_obstack, type->name (),
9668                               name);
9669       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9670                                               dataless_name);
9671       type->field (2).set_type (dataless_type);
9672       /* NAME points into the original discriminant name, which
9673          already has the correct lifetime.  */
9674       TYPE_FIELD_NAME (type, 2) = name;
9675       SET_FIELD_BITPOS (type->field (2), 0);
9676
9677       /* Indicate that this is a variant type.  */
9678       static discriminant_range ranges[1] = { { 0, 0 } };
9679       alloc_rust_variant (&objfile->objfile_obstack, type, 0, 1, ranges);
9680     }
9681   /* A union with a single anonymous field is probably an old-style
9682      univariant enum.  */
9683   else if (type->num_fields () == 1 && streq (TYPE_FIELD_NAME (type, 0), ""))
9684     {
9685       /* Smash this type to be a structure type.  We have to do this
9686          because the type has already been recorded.  */
9687       type->set_code (TYPE_CODE_STRUCT);
9688
9689       struct type *field_type = type->field (0).type ();
9690       const char *variant_name
9691         = rust_last_path_segment (field_type->name ());
9692       TYPE_FIELD_NAME (type, 0) = variant_name;
9693       field_type->set_name
9694         (rust_fully_qualify (&objfile->objfile_obstack,
9695                              type->name (), variant_name));
9696
9697       alloc_rust_variant (&objfile->objfile_obstack, type, -1, 0, {});
9698     }
9699   else
9700     {
9701       struct type *disr_type = nullptr;
9702       for (int i = 0; i < type->num_fields (); ++i)
9703         {
9704           disr_type = type->field (i).type ();
9705
9706           if (disr_type->code () != TYPE_CODE_STRUCT)
9707             {
9708               /* All fields of a true enum will be structs.  */
9709               return;
9710             }
9711           else if (disr_type->num_fields () == 0)
9712             {
9713               /* Could be data-less variant, so keep going.  */
9714               disr_type = nullptr;
9715             }
9716           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9717                            "RUST$ENUM$DISR") != 0)
9718             {
9719               /* Not a Rust enum.  */
9720               return;
9721             }
9722           else
9723             {
9724               /* Found one.  */
9725               break;
9726             }
9727         }
9728
9729       /* If we got here without a discriminant, then it's probably
9730          just a union.  */
9731       if (disr_type == nullptr)
9732         return;
9733
9734       /* Smash this type to be a structure type.  We have to do this
9735          because the type has already been recorded.  */
9736       type->set_code (TYPE_CODE_STRUCT);
9737
9738       /* Make space for the discriminant field.  */
9739       struct field *disr_field = &disr_type->field (0);
9740       field *new_fields
9741         = (struct field *) TYPE_ZALLOC (type, ((type->num_fields () + 1)
9742                                                * sizeof (struct field)));
9743       memcpy (new_fields + 1, type->fields (),
9744               type->num_fields () * sizeof (struct field));
9745       type->set_fields (new_fields);
9746       type->set_num_fields (type->num_fields () + 1);
9747
9748       /* Install the discriminant at index 0 in the union.  */
9749       type->field (0) = *disr_field;
9750       TYPE_FIELD_ARTIFICIAL (type, 0) = 1;
9751       TYPE_FIELD_NAME (type, 0) = "<<discriminant>>";
9752
9753       /* We need a way to find the correct discriminant given a
9754          variant name.  For convenience we build a map here.  */
9755       struct type *enum_type = disr_field->type ();
9756       std::unordered_map<std::string, ULONGEST> discriminant_map;
9757       for (int i = 0; i < enum_type->num_fields (); ++i)
9758         {
9759           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
9760             {
9761               const char *name
9762                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
9763               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
9764             }
9765         }
9766
9767       int n_fields = type->num_fields ();
9768       /* We don't need a range entry for the discriminant, but we do
9769          need one for every other field, as there is no default
9770          variant.  */
9771       discriminant_range *ranges = XOBNEWVEC (&objfile->objfile_obstack,
9772                                               discriminant_range,
9773                                               n_fields - 1);
9774       /* Skip the discriminant here.  */
9775       for (int i = 1; i < n_fields; ++i)
9776         {
9777           /* Find the final word in the name of this variant's type.
9778              That name can be used to look up the correct
9779              discriminant.  */
9780           const char *variant_name
9781             = rust_last_path_segment (type->field (i).type ()->name ());
9782
9783           auto iter = discriminant_map.find (variant_name);
9784           if (iter != discriminant_map.end ())
9785             {
9786               ranges[i - 1].low = iter->second;
9787               ranges[i - 1].high = iter->second;
9788             }
9789
9790           /* In Rust, each element should have the size of the
9791              enclosing enum.  */
9792           TYPE_LENGTH (type->field (i).type ()) = TYPE_LENGTH (type);
9793
9794           /* Remove the discriminant field, if it exists.  */
9795           struct type *sub_type = type->field (i).type ();
9796           if (sub_type->num_fields () > 0)
9797             {
9798               sub_type->set_num_fields (sub_type->num_fields () - 1);
9799               sub_type->set_fields (sub_type->fields () + 1);
9800             }
9801           TYPE_FIELD_NAME (type, i) = variant_name;
9802           sub_type->set_name
9803             (rust_fully_qualify (&objfile->objfile_obstack,
9804                                  type->name (), variant_name));
9805         }
9806
9807       /* Indicate that this is a variant type.  */
9808       alloc_rust_variant (&objfile->objfile_obstack, type, 0, -1,
9809                           gdb::array_view<discriminant_range> (ranges,
9810                                                                n_fields - 1));
9811     }
9812 }
9813
9814 /* Rewrite some Rust unions to be structures with variants parts.  */
9815
9816 static void
9817 rust_union_quirks (struct dwarf2_cu *cu)
9818 {
9819   gdb_assert (cu->language == language_rust);
9820   for (type *type_ : cu->rust_unions)
9821     quirk_rust_enum (type_, cu->per_objfile->objfile);
9822   /* We don't need this any more.  */
9823   cu->rust_unions.clear ();
9824 }
9825
9826 /* See read.h.  */
9827
9828 type_unit_group_unshareable *
9829 dwarf2_per_objfile::get_type_unit_group_unshareable (type_unit_group *tu_group)
9830 {
9831   auto iter = this->m_type_units.find (tu_group);
9832   if (iter != this->m_type_units.end ())
9833     return iter->second.get ();
9834
9835   type_unit_group_unshareable_up uniq (new type_unit_group_unshareable);
9836   type_unit_group_unshareable *result = uniq.get ();
9837   this->m_type_units[tu_group] = std::move (uniq);
9838   return result;
9839 }
9840
9841 struct type *
9842 dwarf2_per_objfile::get_type_for_signatured_type
9843   (signatured_type *sig_type) const
9844 {
9845   auto iter = this->m_type_map.find (sig_type);
9846   if (iter == this->m_type_map.end ())
9847     return nullptr;
9848
9849   return iter->second;
9850 }
9851
9852 void dwarf2_per_objfile::set_type_for_signatured_type
9853   (signatured_type *sig_type, struct type *type)
9854 {
9855   gdb_assert (this->m_type_map.find (sig_type) == this->m_type_map.end ());
9856
9857   this->m_type_map[sig_type] = type;
9858 }
9859
9860 /* A helper function for computing the list of all symbol tables
9861    included by PER_CU.  */
9862
9863 static void
9864 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
9865                                 htab_t all_children, htab_t all_type_symtabs,
9866                                 dwarf2_per_cu_data *per_cu,
9867                                 dwarf2_per_objfile *per_objfile,
9868                                 struct compunit_symtab *immediate_parent)
9869 {
9870   void **slot = htab_find_slot (all_children, per_cu, INSERT);
9871   if (*slot != NULL)
9872     {
9873       /* This inclusion and its children have been processed.  */
9874       return;
9875     }
9876
9877   *slot = per_cu;
9878
9879   /* Only add a CU if it has a symbol table.  */
9880   compunit_symtab *cust = per_objfile->get_symtab (per_cu);
9881   if (cust != NULL)
9882     {
9883       /* If this is a type unit only add its symbol table if we haven't
9884          seen it yet (type unit per_cu's can share symtabs).  */
9885       if (per_cu->is_debug_types)
9886         {
9887           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9888           if (*slot == NULL)
9889             {
9890               *slot = cust;
9891               result->push_back (cust);
9892               if (cust->user == NULL)
9893                 cust->user = immediate_parent;
9894             }
9895         }
9896       else
9897         {
9898           result->push_back (cust);
9899           if (cust->user == NULL)
9900             cust->user = immediate_parent;
9901         }
9902     }
9903
9904   if (!per_cu->imported_symtabs_empty ())
9905     for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9906       {
9907         recursively_compute_inclusions (result, all_children,
9908                                         all_type_symtabs, ptr, per_objfile,
9909                                         cust);
9910       }
9911 }
9912
9913 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9914    PER_CU.  */
9915
9916 static void
9917 compute_compunit_symtab_includes (dwarf2_per_cu_data *per_cu,
9918                                   dwarf2_per_objfile *per_objfile)
9919 {
9920   gdb_assert (! per_cu->is_debug_types);
9921
9922   if (!per_cu->imported_symtabs_empty ())
9923     {
9924       int len;
9925       std::vector<compunit_symtab *> result_symtabs;
9926       compunit_symtab *cust = per_objfile->get_symtab (per_cu);
9927
9928       /* If we don't have a symtab, we can just skip this case.  */
9929       if (cust == NULL)
9930         return;
9931
9932       htab_up all_children (htab_create_alloc (1, htab_hash_pointer,
9933                                                htab_eq_pointer,
9934                                                NULL, xcalloc, xfree));
9935       htab_up all_type_symtabs (htab_create_alloc (1, htab_hash_pointer,
9936                                                    htab_eq_pointer,
9937                                                    NULL, xcalloc, xfree));
9938
9939       for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9940         {
9941           recursively_compute_inclusions (&result_symtabs, all_children.get (),
9942                                           all_type_symtabs.get (), ptr,
9943                                           per_objfile, cust);
9944         }
9945
9946       /* Now we have a transitive closure of all the included symtabs.  */
9947       len = result_symtabs.size ();
9948       cust->includes
9949         = XOBNEWVEC (&per_objfile->objfile->objfile_obstack,
9950                      struct compunit_symtab *, len + 1);
9951       memcpy (cust->includes, result_symtabs.data (),
9952               len * sizeof (compunit_symtab *));
9953       cust->includes[len] = NULL;
9954     }
9955 }
9956
9957 /* Compute the 'includes' field for the symtabs of all the CUs we just
9958    read.  */
9959
9960 static void
9961 process_cu_includes (dwarf2_per_objfile *per_objfile)
9962 {
9963   for (dwarf2_per_cu_data *iter : per_objfile->per_bfd->just_read_cus)
9964     {
9965       if (! iter->is_debug_types)
9966         compute_compunit_symtab_includes (iter, per_objfile);
9967     }
9968
9969   per_objfile->per_bfd->just_read_cus.clear ();
9970 }
9971
9972 /* Generate full symbol information for CU, whose DIEs have
9973    already been loaded into memory.  */
9974
9975 static void
9976 process_full_comp_unit (dwarf2_cu *cu, enum language pretend_language)
9977 {
9978   dwarf2_per_objfile *per_objfile = cu->per_objfile;
9979   struct objfile *objfile = per_objfile->objfile;
9980   struct gdbarch *gdbarch = objfile->arch ();
9981   CORE_ADDR lowpc, highpc;
9982   struct compunit_symtab *cust;
9983   CORE_ADDR baseaddr;
9984   struct block *static_block;
9985   CORE_ADDR addr;
9986
9987   baseaddr = objfile->text_section_offset ();
9988
9989   /* Clear the list here in case something was left over.  */
9990   cu->method_list.clear ();
9991
9992   cu->language = pretend_language;
9993   cu->language_defn = language_def (cu->language);
9994
9995   dwarf2_find_base_address (cu->dies, cu);
9996
9997   /* Before we start reading the top-level DIE, ensure it has a valid tag
9998      type.  */
9999   switch (cu->dies->tag)
10000     {
10001     case DW_TAG_compile_unit:
10002     case DW_TAG_partial_unit:
10003     case DW_TAG_type_unit:
10004       break;
10005     default:
10006       error (_("Dwarf Error: unexpected tag '%s' at offset %s [in module %s]"),
10007              dwarf_tag_name (cu->dies->tag),
10008              sect_offset_str (cu->per_cu->sect_off),
10009              objfile_name (per_objfile->objfile));
10010     }
10011
10012   /* Do line number decoding in read_file_scope () */
10013   process_die (cu->dies, cu);
10014
10015   /* For now fudge the Go package.  */
10016   if (cu->language == language_go)
10017     fixup_go_packaging (cu);
10018
10019   /* Now that we have processed all the DIEs in the CU, all the types
10020      should be complete, and it should now be safe to compute all of the
10021      physnames.  */
10022   compute_delayed_physnames (cu);
10023
10024   if (cu->language == language_rust)
10025     rust_union_quirks (cu);
10026
10027   /* Some compilers don't define a DW_AT_high_pc attribute for the
10028      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10029      it, by scanning the DIE's below the compilation unit.  */
10030   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10031
10032   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10033   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
10034
10035   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10036      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10037      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10038      addrmap to help ensure it has an accurate map of pc values belonging to
10039      this comp unit.  */
10040   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10041
10042   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
10043                                                     SECT_OFF_TEXT (objfile),
10044                                                     0);
10045
10046   if (cust != NULL)
10047     {
10048       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10049
10050       /* Set symtab language to language from DW_AT_language.  If the
10051          compilation is from a C file generated by language preprocessors, do
10052          not set the language if it was already deduced by start_subfile.  */
10053       if (!(cu->language == language_c
10054             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10055         COMPUNIT_FILETABS (cust)->language = cu->language;
10056
10057       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10058          produce DW_AT_location with location lists but it can be possibly
10059          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10060          there were bugs in prologue debug info, fixed later in GCC-4.5
10061          by "unwind info for epilogues" patch (which is not directly related).
10062
10063          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10064          needed, it would be wrong due to missing DW_AT_producer there.
10065
10066          Still one can confuse GDB by using non-standard GCC compilation
10067          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10068          */
10069       if (cu->has_loclist && gcc_4_minor >= 5)
10070         cust->locations_valid = 1;
10071
10072       if (gcc_4_minor >= 5)
10073         cust->epilogue_unwind_valid = 1;
10074
10075       cust->call_site_htab = cu->call_site_htab;
10076     }
10077
10078   per_objfile->set_symtab (cu->per_cu, cust);
10079
10080   /* Push it for inclusion processing later.  */
10081   per_objfile->per_bfd->just_read_cus.push_back (cu->per_cu);
10082
10083   /* Not needed any more.  */
10084   cu->reset_builder ();
10085 }
10086
10087 /* Generate full symbol information for type unit CU, whose DIEs have
10088    already been loaded into memory.  */
10089
10090 static void
10091 process_full_type_unit (dwarf2_cu *cu,
10092                         enum language pretend_language)
10093 {
10094   dwarf2_per_objfile *per_objfile = cu->per_objfile;
10095   struct objfile *objfile = per_objfile->objfile;
10096   struct compunit_symtab *cust;
10097   struct signatured_type *sig_type;
10098
10099   gdb_assert (cu->per_cu->is_debug_types);
10100   sig_type = (struct signatured_type *) cu->per_cu;
10101
10102   /* Clear the list here in case something was left over.  */
10103   cu->method_list.clear ();
10104
10105   cu->language = pretend_language;
10106   cu->language_defn = language_def (cu->language);
10107
10108   /* The symbol tables are set up in read_type_unit_scope.  */
10109   process_die (cu->dies, cu);
10110
10111   /* For now fudge the Go package.  */
10112   if (cu->language == language_go)
10113     fixup_go_packaging (cu);
10114
10115   /* Now that we have processed all the DIEs in the CU, all the types
10116      should be complete, and it should now be safe to compute all of the
10117      physnames.  */
10118   compute_delayed_physnames (cu);
10119
10120   if (cu->language == language_rust)
10121     rust_union_quirks (cu);
10122
10123   /* TUs share symbol tables.
10124      If this is the first TU to use this symtab, complete the construction
10125      of it with end_expandable_symtab.  Otherwise, complete the addition of
10126      this TU's symbols to the existing symtab.  */
10127   type_unit_group_unshareable *tug_unshare =
10128     per_objfile->get_type_unit_group_unshareable (sig_type->type_unit_group);
10129   if (tug_unshare->compunit_symtab == NULL)
10130     {
10131       buildsym_compunit *builder = cu->get_builder ();
10132       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10133       tug_unshare->compunit_symtab = cust;
10134
10135       if (cust != NULL)
10136         {
10137           /* Set symtab language to language from DW_AT_language.  If the
10138              compilation is from a C file generated by language preprocessors,
10139              do not set the language if it was already deduced by
10140              start_subfile.  */
10141           if (!(cu->language == language_c
10142                 && COMPUNIT_FILETABS (cust)->language != language_c))
10143             COMPUNIT_FILETABS (cust)->language = cu->language;
10144         }
10145     }
10146   else
10147     {
10148       cu->get_builder ()->augment_type_symtab ();
10149       cust = tug_unshare->compunit_symtab;
10150     }
10151
10152   per_objfile->set_symtab (cu->per_cu, cust);
10153
10154   /* Not needed any more.  */
10155   cu->reset_builder ();
10156 }
10157
10158 /* Process an imported unit DIE.  */
10159
10160 static void
10161 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10162 {
10163   struct attribute *attr;
10164
10165   /* For now we don't handle imported units in type units.  */
10166   if (cu->per_cu->is_debug_types)
10167     {
10168       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10169                " supported in type units [in module %s]"),
10170              objfile_name (cu->per_objfile->objfile));
10171     }
10172
10173   attr = dwarf2_attr (die, DW_AT_import, cu);
10174   if (attr != NULL)
10175     {
10176       sect_offset sect_off = attr->get_ref_die_offset ();
10177       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10178       dwarf2_per_objfile *per_objfile = cu->per_objfile;
10179       dwarf2_per_cu_data *per_cu
10180         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, per_objfile);
10181
10182       /* We're importing a C++ compilation unit with tag DW_TAG_compile_unit
10183          into another compilation unit, at root level.  Regard this as a hint,
10184          and ignore it.  */
10185       if (die->parent && die->parent->parent == NULL
10186           && per_cu->unit_type == DW_UT_compile
10187           && per_cu->lang == language_cplus)
10188         return;
10189
10190       /* If necessary, add it to the queue and load its DIEs.  */
10191       if (maybe_queue_comp_unit (cu, per_cu, per_objfile, cu->language))
10192         load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
10193                              false, cu->language);
10194
10195       cu->per_cu->imported_symtabs_push (per_cu);
10196     }
10197 }
10198
10199 /* RAII object that represents a process_die scope: i.e.,
10200    starts/finishes processing a DIE.  */
10201 class process_die_scope
10202 {
10203 public:
10204   process_die_scope (die_info *die, dwarf2_cu *cu)
10205     : m_die (die), m_cu (cu)
10206   {
10207     /* We should only be processing DIEs not already in process.  */
10208     gdb_assert (!m_die->in_process);
10209     m_die->in_process = true;
10210   }
10211
10212   ~process_die_scope ()
10213   {
10214     m_die->in_process = false;
10215
10216     /* If we're done processing the DIE for the CU that owns the line
10217        header, we don't need the line header anymore.  */
10218     if (m_cu->line_header_die_owner == m_die)
10219       {
10220         delete m_cu->line_header;
10221         m_cu->line_header = NULL;
10222         m_cu->line_header_die_owner = NULL;
10223       }
10224   }
10225
10226 private:
10227   die_info *m_die;
10228   dwarf2_cu *m_cu;
10229 };
10230
10231 /* Process a die and its children.  */
10232
10233 static void
10234 process_die (struct die_info *die, struct dwarf2_cu *cu)
10235 {
10236   process_die_scope scope (die, cu);
10237
10238   switch (die->tag)
10239     {
10240     case DW_TAG_padding:
10241       break;
10242     case DW_TAG_compile_unit:
10243     case DW_TAG_partial_unit:
10244       read_file_scope (die, cu);
10245       break;
10246     case DW_TAG_type_unit:
10247       read_type_unit_scope (die, cu);
10248       break;
10249     case DW_TAG_subprogram:
10250       /* Nested subprograms in Fortran get a prefix.  */
10251       if (cu->language == language_fortran
10252           && die->parent != NULL
10253           && die->parent->tag == DW_TAG_subprogram)
10254         cu->processing_has_namespace_info = true;
10255       /* Fall through.  */
10256     case DW_TAG_inlined_subroutine:
10257       read_func_scope (die, cu);
10258       break;
10259     case DW_TAG_lexical_block:
10260     case DW_TAG_try_block:
10261     case DW_TAG_catch_block:
10262       read_lexical_block_scope (die, cu);
10263       break;
10264     case DW_TAG_call_site:
10265     case DW_TAG_GNU_call_site:
10266       read_call_site_scope (die, cu);
10267       break;
10268     case DW_TAG_class_type:
10269     case DW_TAG_interface_type:
10270     case DW_TAG_structure_type:
10271     case DW_TAG_union_type:
10272       process_structure_scope (die, cu);
10273       break;
10274     case DW_TAG_enumeration_type:
10275       process_enumeration_scope (die, cu);
10276       break;
10277
10278     /* These dies have a type, but processing them does not create
10279        a symbol or recurse to process the children.  Therefore we can
10280        read them on-demand through read_type_die.  */
10281     case DW_TAG_subroutine_type:
10282     case DW_TAG_set_type:
10283     case DW_TAG_pointer_type:
10284     case DW_TAG_ptr_to_member_type:
10285     case DW_TAG_reference_type:
10286     case DW_TAG_rvalue_reference_type:
10287     case DW_TAG_string_type:
10288       break;
10289
10290     case DW_TAG_array_type:
10291       /* We only need to handle this case for Ada -- in other
10292          languages, it's normal for the compiler to emit a typedef
10293          instead.  */
10294       if (cu->language != language_ada)
10295         break;
10296       /* FALLTHROUGH */
10297     case DW_TAG_base_type:
10298     case DW_TAG_subrange_type:
10299     case DW_TAG_typedef:
10300       /* Add a typedef symbol for the type definition, if it has a
10301          DW_AT_name.  */
10302       new_symbol (die, read_type_die (die, cu), cu);
10303       break;
10304     case DW_TAG_common_block:
10305       read_common_block (die, cu);
10306       break;
10307     case DW_TAG_common_inclusion:
10308       break;
10309     case DW_TAG_namespace:
10310       cu->processing_has_namespace_info = true;
10311       read_namespace (die, cu);
10312       break;
10313     case DW_TAG_module:
10314       cu->processing_has_namespace_info = true;
10315       read_module (die, cu);
10316       break;
10317     case DW_TAG_imported_declaration:
10318       cu->processing_has_namespace_info = true;
10319       if (read_namespace_alias (die, cu))
10320         break;
10321       /* The declaration is not a global namespace alias.  */
10322       /* Fall through.  */
10323     case DW_TAG_imported_module:
10324       cu->processing_has_namespace_info = true;
10325       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10326                                  || cu->language != language_fortran))
10327         complaint (_("Tag '%s' has unexpected children"),
10328                    dwarf_tag_name (die->tag));
10329       read_import_statement (die, cu);
10330       break;
10331
10332     case DW_TAG_imported_unit:
10333       process_imported_unit_die (die, cu);
10334       break;
10335
10336     case DW_TAG_variable:
10337       read_variable (die, cu);
10338       break;
10339
10340     default:
10341       new_symbol (die, NULL, cu);
10342       break;
10343     }
10344 }
10345 \f
10346 /* DWARF name computation.  */
10347
10348 /* A helper function for dwarf2_compute_name which determines whether DIE
10349    needs to have the name of the scope prepended to the name listed in the
10350    die.  */
10351
10352 static int
10353 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10354 {
10355   struct attribute *attr;
10356
10357   switch (die->tag)
10358     {
10359     case DW_TAG_namespace:
10360     case DW_TAG_typedef:
10361     case DW_TAG_class_type:
10362     case DW_TAG_interface_type:
10363     case DW_TAG_structure_type:
10364     case DW_TAG_union_type:
10365     case DW_TAG_enumeration_type:
10366     case DW_TAG_enumerator:
10367     case DW_TAG_subprogram:
10368     case DW_TAG_inlined_subroutine:
10369     case DW_TAG_member:
10370     case DW_TAG_imported_declaration:
10371       return 1;
10372
10373     case DW_TAG_variable:
10374     case DW_TAG_constant:
10375       /* We only need to prefix "globally" visible variables.  These include
10376          any variable marked with DW_AT_external or any variable that
10377          lives in a namespace.  [Variables in anonymous namespaces
10378          require prefixing, but they are not DW_AT_external.]  */
10379
10380       if (dwarf2_attr (die, DW_AT_specification, cu))
10381         {
10382           struct dwarf2_cu *spec_cu = cu;
10383
10384           return die_needs_namespace (die_specification (die, &spec_cu),
10385                                       spec_cu);
10386         }
10387
10388       attr = dwarf2_attr (die, DW_AT_external, cu);
10389       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10390           && die->parent->tag != DW_TAG_module)
10391         return 0;
10392       /* A variable in a lexical block of some kind does not need a
10393          namespace, even though in C++ such variables may be external
10394          and have a mangled name.  */
10395       if (die->parent->tag ==  DW_TAG_lexical_block
10396           || die->parent->tag ==  DW_TAG_try_block
10397           || die->parent->tag ==  DW_TAG_catch_block
10398           || die->parent->tag == DW_TAG_subprogram)
10399         return 0;
10400       return 1;
10401
10402     default:
10403       return 0;
10404     }
10405 }
10406
10407 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10408    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10409    defined for the given DIE.  */
10410
10411 static struct attribute *
10412 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10413 {
10414   struct attribute *attr;
10415
10416   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10417   if (attr == NULL)
10418     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10419
10420   return attr;
10421 }
10422
10423 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10424    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10425    defined for the given DIE.  */
10426
10427 static const char *
10428 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10429 {
10430   const char *linkage_name;
10431
10432   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10433   if (linkage_name == NULL)
10434     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10435
10436   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10437      See https://github.com/rust-lang/rust/issues/32925.  */
10438   if (cu->language == language_rust && linkage_name != NULL
10439       && strchr (linkage_name, '{') != NULL)
10440     linkage_name = NULL;
10441
10442   return linkage_name;
10443 }
10444
10445 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10446    compute the physname for the object, which include a method's:
10447    - formal parameters (C++),
10448    - receiver type (Go),
10449
10450    The term "physname" is a bit confusing.
10451    For C++, for example, it is the demangled name.
10452    For Go, for example, it's the mangled name.
10453
10454    For Ada, return the DIE's linkage name rather than the fully qualified
10455    name.  PHYSNAME is ignored..
10456
10457    The result is allocated on the objfile->per_bfd's obstack and
10458    canonicalized.  */
10459
10460 static const char *
10461 dwarf2_compute_name (const char *name,
10462                      struct die_info *die, struct dwarf2_cu *cu,
10463                      int physname)
10464 {
10465   struct objfile *objfile = cu->per_objfile->objfile;
10466
10467   if (name == NULL)
10468     name = dwarf2_name (die, cu);
10469
10470   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10471      but otherwise compute it by typename_concat inside GDB.
10472      FIXME: Actually this is not really true, or at least not always true.
10473      It's all very confusing.  compute_and_set_names doesn't try to demangle
10474      Fortran names because there is no mangling standard.  So new_symbol
10475      will set the demangled name to the result of dwarf2_full_name, and it is
10476      the demangled name that GDB uses if it exists.  */
10477   if (cu->language == language_ada
10478       || (cu->language == language_fortran && physname))
10479     {
10480       /* For Ada unit, we prefer the linkage name over the name, as
10481          the former contains the exported name, which the user expects
10482          to be able to reference.  Ideally, we want the user to be able
10483          to reference this entity using either natural or linkage name,
10484          but we haven't started looking at this enhancement yet.  */
10485       const char *linkage_name = dw2_linkage_name (die, cu);
10486
10487       if (linkage_name != NULL)
10488         return linkage_name;
10489     }
10490
10491   /* These are the only languages we know how to qualify names in.  */
10492   if (name != NULL
10493       && (cu->language == language_cplus
10494           || cu->language == language_fortran || cu->language == language_d
10495           || cu->language == language_rust))
10496     {
10497       if (die_needs_namespace (die, cu))
10498         {
10499           const char *prefix;
10500           const char *canonical_name = NULL;
10501
10502           string_file buf;
10503
10504           prefix = determine_prefix (die, cu);
10505           if (*prefix != '\0')
10506             {
10507               gdb::unique_xmalloc_ptr<char> prefixed_name
10508                 (typename_concat (NULL, prefix, name, physname, cu));
10509
10510               buf.puts (prefixed_name.get ());
10511             }
10512           else
10513             buf.puts (name);
10514
10515           /* Template parameters may be specified in the DIE's DW_AT_name, or
10516              as children with DW_TAG_template_type_param or
10517              DW_TAG_value_type_param.  If the latter, add them to the name
10518              here.  If the name already has template parameters, then
10519              skip this step; some versions of GCC emit both, and
10520              it is more efficient to use the pre-computed name.
10521
10522              Something to keep in mind about this process: it is very
10523              unlikely, or in some cases downright impossible, to produce
10524              something that will match the mangled name of a function.
10525              If the definition of the function has the same debug info,
10526              we should be able to match up with it anyway.  But fallbacks
10527              using the minimal symbol, for instance to find a method
10528              implemented in a stripped copy of libstdc++, will not work.
10529              If we do not have debug info for the definition, we will have to
10530              match them up some other way.
10531
10532              When we do name matching there is a related problem with function
10533              templates; two instantiated function templates are allowed to
10534              differ only by their return types, which we do not add here.  */
10535
10536           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10537             {
10538               struct attribute *attr;
10539               struct die_info *child;
10540               int first = 1;
10541               const language_defn *cplus_lang = language_def (cu->language);
10542
10543               die->building_fullname = 1;
10544
10545               for (child = die->child; child != NULL; child = child->sibling)
10546                 {
10547                   struct type *type;
10548                   LONGEST value;
10549                   const gdb_byte *bytes;
10550                   struct dwarf2_locexpr_baton *baton;
10551                   struct value *v;
10552
10553                   if (child->tag != DW_TAG_template_type_param
10554                       && child->tag != DW_TAG_template_value_param)
10555                     continue;
10556
10557                   if (first)
10558                     {
10559                       buf.puts ("<");
10560                       first = 0;
10561                     }
10562                   else
10563                     buf.puts (", ");
10564
10565                   attr = dwarf2_attr (child, DW_AT_type, cu);
10566                   if (attr == NULL)
10567                     {
10568                       complaint (_("template parameter missing DW_AT_type"));
10569                       buf.puts ("UNKNOWN_TYPE");
10570                       continue;
10571                     }
10572                   type = die_type (child, cu);
10573
10574                   if (child->tag == DW_TAG_template_type_param)
10575                     {
10576                       cplus_lang->print_type (type, "", &buf, -1, 0,
10577                                               &type_print_raw_options);
10578                       continue;
10579                     }
10580
10581                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10582                   if (attr == NULL)
10583                     {
10584                       complaint (_("template parameter missing "
10585                                    "DW_AT_const_value"));
10586                       buf.puts ("UNKNOWN_VALUE");
10587                       continue;
10588                     }
10589
10590                   dwarf2_const_value_attr (attr, type, name,
10591                                            &cu->comp_unit_obstack, cu,
10592                                            &value, &bytes, &baton);
10593
10594                   if (type->has_no_signedness ())
10595                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10596                        changed, this can use value_print instead.  */
10597                     cplus_lang->printchar (value, type, &buf);
10598                   else
10599                     {
10600                       struct value_print_options opts;
10601
10602                       if (baton != NULL)
10603                         v = dwarf2_evaluate_loc_desc (type, NULL,
10604                                                       baton->data,
10605                                                       baton->size,
10606                                                       baton->per_cu,
10607                                                       baton->per_objfile);
10608                       else if (bytes != NULL)
10609                         {
10610                           v = allocate_value (type);
10611                           memcpy (value_contents_writeable (v), bytes,
10612                                   TYPE_LENGTH (type));
10613                         }
10614                       else
10615                         v = value_from_longest (type, value);
10616
10617                       /* Specify decimal so that we do not depend on
10618                          the radix.  */
10619                       get_formatted_print_options (&opts, 'd');
10620                       opts.raw = 1;
10621                       value_print (v, &buf, &opts);
10622                       release_value (v);
10623                     }
10624                 }
10625
10626               die->building_fullname = 0;
10627
10628               if (!first)
10629                 {
10630                   /* Close the argument list, with a space if necessary
10631                      (nested templates).  */
10632                   if (!buf.empty () && buf.string ().back () == '>')
10633                     buf.puts (" >");
10634                   else
10635                     buf.puts (">");
10636                 }
10637             }
10638
10639           /* For C++ methods, append formal parameter type
10640              information, if PHYSNAME.  */
10641
10642           if (physname && die->tag == DW_TAG_subprogram
10643               && cu->language == language_cplus)
10644             {
10645               struct type *type = read_type_die (die, cu);
10646
10647               c_type_print_args (type, &buf, 1, cu->language,
10648                                  &type_print_raw_options);
10649
10650               if (cu->language == language_cplus)
10651                 {
10652                   /* Assume that an artificial first parameter is
10653                      "this", but do not crash if it is not.  RealView
10654                      marks unnamed (and thus unused) parameters as
10655                      artificial; there is no way to differentiate
10656                      the two cases.  */
10657                   if (type->num_fields () > 0
10658                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10659                       && type->field (0).type ()->code () == TYPE_CODE_PTR
10660                       && TYPE_CONST (TYPE_TARGET_TYPE (type->field (0).type ())))
10661                     buf.puts (" const");
10662                 }
10663             }
10664
10665           const std::string &intermediate_name = buf.string ();
10666
10667           if (cu->language == language_cplus)
10668             canonical_name
10669               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10670                                           objfile);
10671
10672           /* If we only computed INTERMEDIATE_NAME, or if
10673              INTERMEDIATE_NAME is already canonical, then we need to
10674              intern it.  */
10675           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10676             name = objfile->intern (intermediate_name);
10677           else
10678             name = canonical_name;
10679         }
10680     }
10681
10682   return name;
10683 }
10684
10685 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10686    If scope qualifiers are appropriate they will be added.  The result
10687    will be allocated on the storage_obstack, or NULL if the DIE does
10688    not have a name.  NAME may either be from a previous call to
10689    dwarf2_name or NULL.
10690
10691    The output string will be canonicalized (if C++).  */
10692
10693 static const char *
10694 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10695 {
10696   return dwarf2_compute_name (name, die, cu, 0);
10697 }
10698
10699 /* Construct a physname for the given DIE in CU.  NAME may either be
10700    from a previous call to dwarf2_name or NULL.  The result will be
10701    allocated on the objfile_objstack or NULL if the DIE does not have a
10702    name.
10703
10704    The output string will be canonicalized (if C++).  */
10705
10706 static const char *
10707 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10708 {
10709   struct objfile *objfile = cu->per_objfile->objfile;
10710   const char *retval, *mangled = NULL, *canon = NULL;
10711   int need_copy = 1;
10712
10713   /* In this case dwarf2_compute_name is just a shortcut not building anything
10714      on its own.  */
10715   if (!die_needs_namespace (die, cu))
10716     return dwarf2_compute_name (name, die, cu, 1);
10717
10718   if (cu->language != language_rust)
10719     mangled = dw2_linkage_name (die, cu);
10720
10721   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10722      has computed.  */
10723   gdb::unique_xmalloc_ptr<char> demangled;
10724   if (mangled != NULL)
10725     {
10726
10727       if (language_def (cu->language)->store_sym_names_in_linkage_form_p ())
10728         {
10729           /* Do nothing (do not demangle the symbol name).  */
10730         }
10731       else
10732         {
10733           /* Use DMGL_RET_DROP for C++ template functions to suppress
10734              their return type.  It is easier for GDB users to search
10735              for such functions as `name(params)' than `long name(params)'.
10736              In such case the minimal symbol names do not match the full
10737              symbol names but for template functions there is never a need
10738              to look up their definition from their declaration so
10739              the only disadvantage remains the minimal symbol variant
10740              `long name(params)' does not have the proper inferior type.  */
10741           demangled.reset (gdb_demangle (mangled,
10742                                          (DMGL_PARAMS | DMGL_ANSI
10743                                           | DMGL_RET_DROP)));
10744         }
10745       if (demangled)
10746         canon = demangled.get ();
10747       else
10748         {
10749           canon = mangled;
10750           need_copy = 0;
10751         }
10752     }
10753
10754   if (canon == NULL || check_physname)
10755     {
10756       const char *physname = dwarf2_compute_name (name, die, cu, 1);
10757
10758       if (canon != NULL && strcmp (physname, canon) != 0)
10759         {
10760           /* It may not mean a bug in GDB.  The compiler could also
10761              compute DW_AT_linkage_name incorrectly.  But in such case
10762              GDB would need to be bug-to-bug compatible.  */
10763
10764           complaint (_("Computed physname <%s> does not match demangled <%s> "
10765                        "(from linkage <%s>) - DIE at %s [in module %s]"),
10766                      physname, canon, mangled, sect_offset_str (die->sect_off),
10767                      objfile_name (objfile));
10768
10769           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
10770              is available here - over computed PHYSNAME.  It is safer
10771              against both buggy GDB and buggy compilers.  */
10772
10773           retval = canon;
10774         }
10775       else
10776         {
10777           retval = physname;
10778           need_copy = 0;
10779         }
10780     }
10781   else
10782     retval = canon;
10783
10784   if (need_copy)
10785     retval = objfile->intern (retval);
10786
10787   return retval;
10788 }
10789
10790 /* Inspect DIE in CU for a namespace alias.  If one exists, record
10791    a new symbol for it.
10792
10793    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
10794
10795 static int
10796 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
10797 {
10798   struct attribute *attr;
10799
10800   /* If the die does not have a name, this is not a namespace
10801      alias.  */
10802   attr = dwarf2_attr (die, DW_AT_name, cu);
10803   if (attr != NULL)
10804     {
10805       int num;
10806       struct die_info *d = die;
10807       struct dwarf2_cu *imported_cu = cu;
10808
10809       /* If the compiler has nested DW_AT_imported_declaration DIEs,
10810          keep inspecting DIEs until we hit the underlying import.  */
10811 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
10812       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
10813         {
10814           attr = dwarf2_attr (d, DW_AT_import, cu);
10815           if (attr == NULL)
10816             break;
10817
10818           d = follow_die_ref (d, attr, &imported_cu);
10819           if (d->tag != DW_TAG_imported_declaration)
10820             break;
10821         }
10822
10823       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10824         {
10825           complaint (_("DIE at %s has too many recursively imported "
10826                        "declarations"), sect_offset_str (d->sect_off));
10827           return 0;
10828         }
10829
10830       if (attr != NULL)
10831         {
10832           struct type *type;
10833           sect_offset sect_off = attr->get_ref_die_offset ();
10834
10835           type = get_die_type_at_offset (sect_off, cu->per_cu, cu->per_objfile);
10836           if (type != NULL && type->code () == TYPE_CODE_NAMESPACE)
10837             {
10838               /* This declaration is a global namespace alias.  Add
10839                  a symbol for it whose type is the aliased namespace.  */
10840               new_symbol (die, type, cu);
10841               return 1;
10842             }
10843         }
10844     }
10845
10846   return 0;
10847 }
10848
10849 /* Return the using directives repository (global or local?) to use in the
10850    current context for CU.
10851
10852    For Ada, imported declarations can materialize renamings, which *may* be
10853    global.  However it is impossible (for now?) in DWARF to distinguish
10854    "external" imported declarations and "static" ones.  As all imported
10855    declarations seem to be static in all other languages, make them all CU-wide
10856    global only in Ada.  */
10857
10858 static struct using_direct **
10859 using_directives (struct dwarf2_cu *cu)
10860 {
10861   if (cu->language == language_ada
10862       && cu->get_builder ()->outermost_context_p ())
10863     return cu->get_builder ()->get_global_using_directives ();
10864   else
10865     return cu->get_builder ()->get_local_using_directives ();
10866 }
10867
10868 /* Read the import statement specified by the given die and record it.  */
10869
10870 static void
10871 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10872 {
10873   struct objfile *objfile = cu->per_objfile->objfile;
10874   struct attribute *import_attr;
10875   struct die_info *imported_die, *child_die;
10876   struct dwarf2_cu *imported_cu;
10877   const char *imported_name;
10878   const char *imported_name_prefix;
10879   const char *canonical_name;
10880   const char *import_alias;
10881   const char *imported_declaration = NULL;
10882   const char *import_prefix;
10883   std::vector<const char *> excludes;
10884
10885   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10886   if (import_attr == NULL)
10887     {
10888       complaint (_("Tag '%s' has no DW_AT_import"),
10889                  dwarf_tag_name (die->tag));
10890       return;
10891     }
10892
10893   imported_cu = cu;
10894   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10895   imported_name = dwarf2_name (imported_die, imported_cu);
10896   if (imported_name == NULL)
10897     {
10898       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10899
10900         The import in the following code:
10901         namespace A
10902           {
10903             typedef int B;
10904           }
10905
10906         int main ()
10907           {
10908             using A::B;
10909             B b;
10910             return b;
10911           }
10912
10913         ...
10914          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10915             <52>   DW_AT_decl_file   : 1
10916             <53>   DW_AT_decl_line   : 6
10917             <54>   DW_AT_import      : <0x75>
10918          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10919             <59>   DW_AT_name        : B
10920             <5b>   DW_AT_decl_file   : 1
10921             <5c>   DW_AT_decl_line   : 2
10922             <5d>   DW_AT_type        : <0x6e>
10923         ...
10924          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10925             <76>   DW_AT_byte_size   : 4
10926             <77>   DW_AT_encoding    : 5        (signed)
10927
10928         imports the wrong die ( 0x75 instead of 0x58 ).
10929         This case will be ignored until the gcc bug is fixed.  */
10930       return;
10931     }
10932
10933   /* Figure out the local name after import.  */
10934   import_alias = dwarf2_name (die, cu);
10935
10936   /* Figure out where the statement is being imported to.  */
10937   import_prefix = determine_prefix (die, cu);
10938
10939   /* Figure out what the scope of the imported die is and prepend it
10940      to the name of the imported die.  */
10941   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10942
10943   if (imported_die->tag != DW_TAG_namespace
10944       && imported_die->tag != DW_TAG_module)
10945     {
10946       imported_declaration = imported_name;
10947       canonical_name = imported_name_prefix;
10948     }
10949   else if (strlen (imported_name_prefix) > 0)
10950     canonical_name = obconcat (&objfile->objfile_obstack,
10951                                imported_name_prefix,
10952                                (cu->language == language_d ? "." : "::"),
10953                                imported_name, (char *) NULL);
10954   else
10955     canonical_name = imported_name;
10956
10957   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
10958     for (child_die = die->child; child_die && child_die->tag;
10959          child_die = child_die->sibling)
10960       {
10961         /* DWARF-4: A Fortran use statement with a “rename list” may be
10962            represented by an imported module entry with an import attribute
10963            referring to the module and owned entries corresponding to those
10964            entities that are renamed as part of being imported.  */
10965
10966         if (child_die->tag != DW_TAG_imported_declaration)
10967           {
10968             complaint (_("child DW_TAG_imported_declaration expected "
10969                          "- DIE at %s [in module %s]"),
10970                        sect_offset_str (child_die->sect_off),
10971                        objfile_name (objfile));
10972             continue;
10973           }
10974
10975         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10976         if (import_attr == NULL)
10977           {
10978             complaint (_("Tag '%s' has no DW_AT_import"),
10979                        dwarf_tag_name (child_die->tag));
10980             continue;
10981           }
10982
10983         imported_cu = cu;
10984         imported_die = follow_die_ref_or_sig (child_die, import_attr,
10985                                               &imported_cu);
10986         imported_name = dwarf2_name (imported_die, imported_cu);
10987         if (imported_name == NULL)
10988           {
10989             complaint (_("child DW_TAG_imported_declaration has unknown "
10990                          "imported name - DIE at %s [in module %s]"),
10991                        sect_offset_str (child_die->sect_off),
10992                        objfile_name (objfile));
10993             continue;
10994           }
10995
10996         excludes.push_back (imported_name);
10997
10998         process_die (child_die, cu);
10999       }
11000
11001   add_using_directive (using_directives (cu),
11002                        import_prefix,
11003                        canonical_name,
11004                        import_alias,
11005                        imported_declaration,
11006                        excludes,
11007                        0,
11008                        &objfile->objfile_obstack);
11009 }
11010
11011 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11012    types, but gives them a size of zero.  Starting with version 14,
11013    ICC is compatible with GCC.  */
11014
11015 static bool
11016 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11017 {
11018   if (!cu->checked_producer)
11019     check_producer (cu);
11020
11021   return cu->producer_is_icc_lt_14;
11022 }
11023
11024 /* ICC generates a DW_AT_type for C void functions.  This was observed on
11025    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
11026    which says that void functions should not have a DW_AT_type.  */
11027
11028 static bool
11029 producer_is_icc (struct dwarf2_cu *cu)
11030 {
11031   if (!cu->checked_producer)
11032     check_producer (cu);
11033
11034   return cu->producer_is_icc;
11035 }
11036
11037 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11038    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11039    this, it was first present in GCC release 4.3.0.  */
11040
11041 static bool
11042 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11043 {
11044   if (!cu->checked_producer)
11045     check_producer (cu);
11046
11047   return cu->producer_is_gcc_lt_4_3;
11048 }
11049
11050 static file_and_directory
11051 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11052 {
11053   file_and_directory res;
11054
11055   /* Find the filename.  Do not use dwarf2_name here, since the filename
11056      is not a source language identifier.  */
11057   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11058   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11059
11060   if (res.comp_dir == NULL
11061       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11062       && IS_ABSOLUTE_PATH (res.name))
11063     {
11064       res.comp_dir_storage = ldirname (res.name);
11065       if (!res.comp_dir_storage.empty ())
11066         res.comp_dir = res.comp_dir_storage.c_str ();
11067     }
11068   if (res.comp_dir != NULL)
11069     {
11070       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11071          directory, get rid of it.  */
11072       const char *cp = strchr (res.comp_dir, ':');
11073
11074       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11075         res.comp_dir = cp + 1;
11076     }
11077
11078   if (res.name == NULL)
11079     res.name = "<unknown>";
11080
11081   return res;
11082 }
11083
11084 /* Handle DW_AT_stmt_list for a compilation unit.
11085    DIE is the DW_TAG_compile_unit die for CU.
11086    COMP_DIR is the compilation directory.  LOWPC is passed to
11087    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11088
11089 static void
11090 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11091                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11092 {
11093   dwarf2_per_objfile *per_objfile = cu->per_objfile;
11094   struct attribute *attr;
11095   struct line_header line_header_local;
11096   hashval_t line_header_local_hash;
11097   void **slot;
11098   int decode_mapping;
11099
11100   gdb_assert (! cu->per_cu->is_debug_types);
11101
11102   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11103   if (attr == NULL || !attr->form_is_unsigned ())
11104     return;
11105
11106   sect_offset line_offset = (sect_offset) attr->as_unsigned ();
11107
11108   /* The line header hash table is only created if needed (it exists to
11109      prevent redundant reading of the line table for partial_units).
11110      If we're given a partial_unit, we'll need it.  If we're given a
11111      compile_unit, then use the line header hash table if it's already
11112      created, but don't create one just yet.  */
11113
11114   if (per_objfile->line_header_hash == NULL
11115       && die->tag == DW_TAG_partial_unit)
11116     {
11117       per_objfile->line_header_hash
11118         .reset (htab_create_alloc (127, line_header_hash_voidp,
11119                                    line_header_eq_voidp,
11120                                    free_line_header_voidp,
11121                                    xcalloc, xfree));
11122     }
11123
11124   line_header_local.sect_off = line_offset;
11125   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11126   line_header_local_hash = line_header_hash (&line_header_local);
11127   if (per_objfile->line_header_hash != NULL)
11128     {
11129       slot = htab_find_slot_with_hash (per_objfile->line_header_hash.get (),
11130                                        &line_header_local,
11131                                        line_header_local_hash, NO_INSERT);
11132
11133       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11134          is not present in *SLOT (since if there is something in *SLOT then
11135          it will be for a partial_unit).  */
11136       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11137         {
11138           gdb_assert (*slot != NULL);
11139           cu->line_header = (struct line_header *) *slot;
11140           return;
11141         }
11142     }
11143
11144   /* dwarf_decode_line_header does not yet provide sufficient information.
11145      We always have to call also dwarf_decode_lines for it.  */
11146   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11147   if (lh == NULL)
11148     return;
11149
11150   cu->line_header = lh.release ();
11151   cu->line_header_die_owner = die;
11152
11153   if (per_objfile->line_header_hash == NULL)
11154     slot = NULL;
11155   else
11156     {
11157       slot = htab_find_slot_with_hash (per_objfile->line_header_hash.get (),
11158                                        &line_header_local,
11159                                        line_header_local_hash, INSERT);
11160       gdb_assert (slot != NULL);
11161     }
11162   if (slot != NULL && *slot == NULL)
11163     {
11164       /* This newly decoded line number information unit will be owned
11165          by line_header_hash hash table.  */
11166       *slot = cu->line_header;
11167       cu->line_header_die_owner = NULL;
11168     }
11169   else
11170     {
11171       /* We cannot free any current entry in (*slot) as that struct line_header
11172          may be already used by multiple CUs.  Create only temporary decoded
11173          line_header for this CU - it may happen at most once for each line
11174          number information unit.  And if we're not using line_header_hash
11175          then this is what we want as well.  */
11176       gdb_assert (die->tag != DW_TAG_partial_unit);
11177     }
11178   decode_mapping = (die->tag != DW_TAG_partial_unit);
11179   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11180                       decode_mapping);
11181
11182 }
11183
11184 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11185
11186 static void
11187 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11188 {
11189   dwarf2_per_objfile *per_objfile = cu->per_objfile;
11190   struct objfile *objfile = per_objfile->objfile;
11191   struct gdbarch *gdbarch = objfile->arch ();
11192   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11193   CORE_ADDR highpc = ((CORE_ADDR) 0);
11194   struct attribute *attr;
11195   struct die_info *child_die;
11196   CORE_ADDR baseaddr;
11197
11198   prepare_one_comp_unit (cu, die, cu->language);
11199   baseaddr = objfile->text_section_offset ();
11200
11201   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11202
11203   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11204      from finish_block.  */
11205   if (lowpc == ((CORE_ADDR) -1))
11206     lowpc = highpc;
11207   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11208
11209   file_and_directory fnd = find_file_and_directory (die, cu);
11210
11211   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11212      standardised yet.  As a workaround for the language detection we fall
11213      back to the DW_AT_producer string.  */
11214   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11215     cu->language = language_opencl;
11216
11217   /* Similar hack for Go.  */
11218   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11219     set_cu_language (DW_LANG_Go, cu);
11220
11221   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
11222
11223   /* Decode line number information if present.  We do this before
11224      processing child DIEs, so that the line header table is available
11225      for DW_AT_decl_file.  */
11226   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11227
11228   /* Process all dies in compilation unit.  */
11229   if (die->child != NULL)
11230     {
11231       child_die = die->child;
11232       while (child_die && child_die->tag)
11233         {
11234           process_die (child_die, cu);
11235           child_die = child_die->sibling;
11236         }
11237     }
11238
11239   /* Decode macro information, if present.  Dwarf 2 macro information
11240      refers to information in the line number info statement program
11241      header, so we can only read it if we've read the header
11242      successfully.  */
11243   attr = dwarf2_attr (die, DW_AT_macros, cu);
11244   if (attr == NULL)
11245     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11246   if (attr != nullptr && attr->form_is_unsigned () && cu->line_header)
11247     {
11248       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11249         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11250
11251       dwarf_decode_macros (cu, attr->as_unsigned (), 1);
11252     }
11253   else
11254     {
11255       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11256       if (attr != nullptr && attr->form_is_unsigned () && cu->line_header)
11257         {
11258           unsigned int macro_offset = attr->as_unsigned ();
11259
11260           dwarf_decode_macros (cu, macro_offset, 0);
11261         }
11262     }
11263 }
11264
11265 void
11266 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
11267 {
11268   struct type_unit_group *tu_group;
11269   int first_time;
11270   struct attribute *attr;
11271   unsigned int i;
11272   struct signatured_type *sig_type;
11273
11274   gdb_assert (per_cu->is_debug_types);
11275   sig_type = (struct signatured_type *) per_cu;
11276
11277   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
11278
11279   /* If we're using .gdb_index (includes -readnow) then
11280      per_cu->type_unit_group may not have been set up yet.  */
11281   if (sig_type->type_unit_group == NULL)
11282     sig_type->type_unit_group = get_type_unit_group (this, attr);
11283   tu_group = sig_type->type_unit_group;
11284
11285   /* If we've already processed this stmt_list there's no real need to
11286      do it again, we could fake it and just recreate the part we need
11287      (file name,index -> symtab mapping).  If data shows this optimization
11288      is useful we can do it then.  */
11289   type_unit_group_unshareable *tug_unshare
11290     = per_objfile->get_type_unit_group_unshareable (tu_group);
11291   first_time = tug_unshare->compunit_symtab == NULL;
11292
11293   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11294      debug info.  */
11295   line_header_up lh;
11296   if (attr != NULL && attr->form_is_unsigned ())
11297     {
11298       sect_offset line_offset = (sect_offset) attr->as_unsigned ();
11299       lh = dwarf_decode_line_header (line_offset, this);
11300     }
11301   if (lh == NULL)
11302     {
11303       if (first_time)
11304         start_symtab ("", NULL, 0);
11305       else
11306         {
11307           gdb_assert (tug_unshare->symtabs == NULL);
11308           gdb_assert (m_builder == nullptr);
11309           struct compunit_symtab *cust = tug_unshare->compunit_symtab;
11310           m_builder.reset (new struct buildsym_compunit
11311                            (COMPUNIT_OBJFILE (cust), "",
11312                             COMPUNIT_DIRNAME (cust),
11313                             compunit_language (cust),
11314                             0, cust));
11315           list_in_scope = get_builder ()->get_file_symbols ();
11316         }
11317       return;
11318     }
11319
11320   line_header = lh.release ();
11321   line_header_die_owner = die;
11322
11323   if (first_time)
11324     {
11325       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
11326
11327       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11328          still initializing it, and our caller (a few levels up)
11329          process_full_type_unit still needs to know if this is the first
11330          time.  */
11331
11332       tug_unshare->symtabs
11333         = XOBNEWVEC (&COMPUNIT_OBJFILE (cust)->objfile_obstack,
11334                      struct symtab *, line_header->file_names_size ());
11335
11336       auto &file_names = line_header->file_names ();
11337       for (i = 0; i < file_names.size (); ++i)
11338         {
11339           file_entry &fe = file_names[i];
11340           dwarf2_start_subfile (this, fe.name,
11341                                 fe.include_dir (line_header));
11342           buildsym_compunit *b = get_builder ();
11343           if (b->get_current_subfile ()->symtab == NULL)
11344             {
11345               /* NOTE: start_subfile will recognize when it's been
11346                  passed a file it has already seen.  So we can't
11347                  assume there's a simple mapping from
11348                  cu->line_header->file_names to subfiles, plus
11349                  cu->line_header->file_names may contain dups.  */
11350               b->get_current_subfile ()->symtab
11351                 = allocate_symtab (cust, b->get_current_subfile ()->name);
11352             }
11353
11354           fe.symtab = b->get_current_subfile ()->symtab;
11355           tug_unshare->symtabs[i] = fe.symtab;
11356         }
11357     }
11358   else
11359     {
11360       gdb_assert (m_builder == nullptr);
11361       struct compunit_symtab *cust = tug_unshare->compunit_symtab;
11362       m_builder.reset (new struct buildsym_compunit
11363                        (COMPUNIT_OBJFILE (cust), "",
11364                         COMPUNIT_DIRNAME (cust),
11365                         compunit_language (cust),
11366                         0, cust));
11367       list_in_scope = get_builder ()->get_file_symbols ();
11368
11369       auto &file_names = line_header->file_names ();
11370       for (i = 0; i < file_names.size (); ++i)
11371         {
11372           file_entry &fe = file_names[i];
11373           fe.symtab = tug_unshare->symtabs[i];
11374         }
11375     }
11376
11377   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11378      so they don't have a "real" (so to speak) symtab anyway.
11379      There is later code that will assign the main symtab to all symbols
11380      that don't have one.  We need to handle the case of a symbol with a
11381      missing symtab (DW_AT_decl_file) anyway.  */
11382 }
11383
11384 /* Process DW_TAG_type_unit.
11385    For TUs we want to skip the first top level sibling if it's not the
11386    actual type being defined by this TU.  In this case the first top
11387    level sibling is there to provide context only.  */
11388
11389 static void
11390 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11391 {
11392   struct die_info *child_die;
11393
11394   prepare_one_comp_unit (cu, die, language_minimal);
11395
11396   /* Initialize (or reinitialize) the machinery for building symtabs.
11397      We do this before processing child DIEs, so that the line header table
11398      is available for DW_AT_decl_file.  */
11399   cu->setup_type_unit_groups (die);
11400
11401   if (die->child != NULL)
11402     {
11403       child_die = die->child;
11404       while (child_die && child_die->tag)
11405         {
11406           process_die (child_die, cu);
11407           child_die = child_die->sibling;
11408         }
11409     }
11410 }
11411 \f
11412 /* DWO/DWP files.
11413
11414    http://gcc.gnu.org/wiki/DebugFission
11415    http://gcc.gnu.org/wiki/DebugFissionDWP
11416
11417    To simplify handling of both DWO files ("object" files with the DWARF info)
11418    and DWP files (a file with the DWOs packaged up into one file), we treat
11419    DWP files as having a collection of virtual DWO files.  */
11420
11421 static hashval_t
11422 hash_dwo_file (const void *item)
11423 {
11424   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11425   hashval_t hash;
11426
11427   hash = htab_hash_string (dwo_file->dwo_name);
11428   if (dwo_file->comp_dir != NULL)
11429     hash += htab_hash_string (dwo_file->comp_dir);
11430   return hash;
11431 }
11432
11433 static int
11434 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11435 {
11436   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11437   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11438
11439   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11440     return 0;
11441   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11442     return lhs->comp_dir == rhs->comp_dir;
11443   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11444 }
11445
11446 /* Allocate a hash table for DWO files.  */
11447
11448 static htab_up
11449 allocate_dwo_file_hash_table ()
11450 {
11451   auto delete_dwo_file = [] (void *item)
11452     {
11453       struct dwo_file *dwo_file = (struct dwo_file *) item;
11454
11455       delete dwo_file;
11456     };
11457
11458   return htab_up (htab_create_alloc (41,
11459                                      hash_dwo_file,
11460                                      eq_dwo_file,
11461                                      delete_dwo_file,
11462                                      xcalloc, xfree));
11463 }
11464
11465 /* Lookup DWO file DWO_NAME.  */
11466
11467 static void **
11468 lookup_dwo_file_slot (dwarf2_per_objfile *per_objfile,
11469                       const char *dwo_name,
11470                       const char *comp_dir)
11471 {
11472   struct dwo_file find_entry;
11473   void **slot;
11474
11475   if (per_objfile->per_bfd->dwo_files == NULL)
11476     per_objfile->per_bfd->dwo_files = allocate_dwo_file_hash_table ();
11477
11478   find_entry.dwo_name = dwo_name;
11479   find_entry.comp_dir = comp_dir;
11480   slot = htab_find_slot (per_objfile->per_bfd->dwo_files.get (), &find_entry,
11481                          INSERT);
11482
11483   return slot;
11484 }
11485
11486 static hashval_t
11487 hash_dwo_unit (const void *item)
11488 {
11489   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11490
11491   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11492   return dwo_unit->signature;
11493 }
11494
11495 static int
11496 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11497 {
11498   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11499   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11500
11501   /* The signature is assumed to be unique within the DWO file.
11502      So while object file CU dwo_id's always have the value zero,
11503      that's OK, assuming each object file DWO file has only one CU,
11504      and that's the rule for now.  */
11505   return lhs->signature == rhs->signature;
11506 }
11507
11508 /* Allocate a hash table for DWO CUs,TUs.
11509    There is one of these tables for each of CUs,TUs for each DWO file.  */
11510
11511 static htab_up
11512 allocate_dwo_unit_table ()
11513 {
11514   /* Start out with a pretty small number.
11515      Generally DWO files contain only one CU and maybe some TUs.  */
11516   return htab_up (htab_create_alloc (3,
11517                                      hash_dwo_unit,
11518                                      eq_dwo_unit,
11519                                      NULL, xcalloc, xfree));
11520 }
11521
11522 /* die_reader_func for create_dwo_cu.  */
11523
11524 static void
11525 create_dwo_cu_reader (const struct die_reader_specs *reader,
11526                       const gdb_byte *info_ptr,
11527                       struct die_info *comp_unit_die,
11528                       struct dwo_file *dwo_file,
11529                       struct dwo_unit *dwo_unit)
11530 {
11531   struct dwarf2_cu *cu = reader->cu;
11532   sect_offset sect_off = cu->per_cu->sect_off;
11533   struct dwarf2_section_info *section = cu->per_cu->section;
11534
11535   gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
11536   if (!signature.has_value ())
11537     {
11538       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11539                    " its dwo_id [in module %s]"),
11540                  sect_offset_str (sect_off), dwo_file->dwo_name);
11541       return;
11542     }
11543
11544   dwo_unit->dwo_file = dwo_file;
11545   dwo_unit->signature = *signature;
11546   dwo_unit->section = section;
11547   dwo_unit->sect_off = sect_off;
11548   dwo_unit->length = cu->per_cu->length;
11549
11550   dwarf_read_debug_printf ("  offset %s, dwo_id %s",
11551                            sect_offset_str (sect_off),
11552                            hex_string (dwo_unit->signature));
11553 }
11554
11555 /* Create the dwo_units for the CUs in a DWO_FILE.
11556    Note: This function processes DWO files only, not DWP files.  */
11557
11558 static void
11559 create_cus_hash_table (dwarf2_per_objfile *per_objfile,
11560                        dwarf2_cu *cu, struct dwo_file &dwo_file,
11561                        dwarf2_section_info &section, htab_up &cus_htab)
11562 {
11563   struct objfile *objfile = per_objfile->objfile;
11564   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
11565   const gdb_byte *info_ptr, *end_ptr;
11566
11567   section.read (objfile);
11568   info_ptr = section.buffer;
11569
11570   if (info_ptr == NULL)
11571     return;
11572
11573   dwarf_read_debug_printf ("Reading %s for %s:",
11574                            section.get_name (),
11575                            section.get_file_name ());
11576
11577   end_ptr = info_ptr + section.size;
11578   while (info_ptr < end_ptr)
11579     {
11580       struct dwarf2_per_cu_data per_cu;
11581       struct dwo_unit read_unit {};
11582       struct dwo_unit *dwo_unit;
11583       void **slot;
11584       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11585
11586       memset (&per_cu, 0, sizeof (per_cu));
11587       per_cu.per_bfd = per_bfd;
11588       per_cu.is_debug_types = 0;
11589       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11590       per_cu.section = &section;
11591
11592       cutu_reader reader (&per_cu, per_objfile, cu, &dwo_file);
11593       if (!reader.dummy_p)
11594         create_dwo_cu_reader (&reader, reader.info_ptr, reader.comp_unit_die,
11595                               &dwo_file, &read_unit);
11596       info_ptr += per_cu.length;
11597
11598       // If the unit could not be parsed, skip it.
11599       if (read_unit.dwo_file == NULL)
11600         continue;
11601
11602       if (cus_htab == NULL)
11603         cus_htab = allocate_dwo_unit_table ();
11604
11605       dwo_unit = OBSTACK_ZALLOC (&per_bfd->obstack,
11606                                  struct dwo_unit);
11607       *dwo_unit = read_unit;
11608       slot = htab_find_slot (cus_htab.get (), dwo_unit, INSERT);
11609       gdb_assert (slot != NULL);
11610       if (*slot != NULL)
11611         {
11612           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11613           sect_offset dup_sect_off = dup_cu->sect_off;
11614
11615           complaint (_("debug cu entry at offset %s is duplicate to"
11616                        " the entry at offset %s, signature %s"),
11617                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11618                      hex_string (dwo_unit->signature));
11619         }
11620       *slot = (void *)dwo_unit;
11621     }
11622 }
11623
11624 /* DWP file .debug_{cu,tu}_index section format:
11625    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11626    [ref: http://dwarfstd.org/doc/DWARF5.pdf, sect 7.3.5 "DWARF Package Files"]
11627
11628    DWP Versions 1 & 2 are older, pre-standard format versions.  The first
11629    officially standard DWP format was published with DWARF v5 and is called
11630    Version 5.  There are no versions 3 or 4.
11631
11632    DWP Version 1:
11633
11634    Both index sections have the same format, and serve to map a 64-bit
11635    signature to a set of section numbers.  Each section begins with a header,
11636    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11637    indexes, and a pool of 32-bit section numbers.  The index sections will be
11638    aligned at 8-byte boundaries in the file.
11639
11640    The index section header consists of:
11641
11642     V, 32 bit version number
11643     -, 32 bits unused
11644     N, 32 bit number of compilation units or type units in the index
11645     M, 32 bit number of slots in the hash table
11646
11647    Numbers are recorded using the byte order of the application binary.
11648
11649    The hash table begins at offset 16 in the section, and consists of an array
11650    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11651    order of the application binary).  Unused slots in the hash table are 0.
11652    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11653
11654    The parallel table begins immediately after the hash table
11655    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11656    array of 32-bit indexes (using the byte order of the application binary),
11657    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11658    table contains a 32-bit index into the pool of section numbers.  For unused
11659    hash table slots, the corresponding entry in the parallel table will be 0.
11660
11661    The pool of section numbers begins immediately following the hash table
11662    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11663    section numbers consists of an array of 32-bit words (using the byte order
11664    of the application binary).  Each item in the array is indexed starting
11665    from 0.  The hash table entry provides the index of the first section
11666    number in the set.  Additional section numbers in the set follow, and the
11667    set is terminated by a 0 entry (section number 0 is not used in ELF).
11668
11669    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11670    section must be the first entry in the set, and the .debug_abbrev.dwo must
11671    be the second entry. Other members of the set may follow in any order.
11672
11673    ---
11674
11675    DWP Versions 2 and 5:
11676
11677    DWP Versions 2 and 5 combine all the .debug_info, etc. sections into one,
11678    and the entries in the index tables are now offsets into these sections.
11679    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11680    section.
11681
11682    Index Section Contents:
11683     Header
11684     Hash Table of Signatures   dwp_hash_table.hash_table
11685     Parallel Table of Indices  dwp_hash_table.unit_table
11686     Table of Section Offsets   dwp_hash_table.{v2|v5}.{section_ids,offsets}
11687     Table of Section Sizes     dwp_hash_table.{v2|v5}.sizes
11688
11689    The index section header consists of:
11690
11691     V, 32 bit version number
11692     L, 32 bit number of columns in the table of section offsets
11693     N, 32 bit number of compilation units or type units in the index
11694     M, 32 bit number of slots in the hash table
11695
11696    Numbers are recorded using the byte order of the application binary.
11697
11698    The hash table has the same format as version 1.
11699    The parallel table of indices has the same format as version 1,
11700    except that the entries are origin-1 indices into the table of sections
11701    offsets and the table of section sizes.
11702
11703    The table of offsets begins immediately following the parallel table
11704    (at offset 16 + 12 * M from the beginning of the section).  The table is
11705    a two-dimensional array of 32-bit words (using the byte order of the
11706    application binary), with L columns and N+1 rows, in row-major order.
11707    Each row in the array is indexed starting from 0.  The first row provides
11708    a key to the remaining rows: each column in this row provides an identifier
11709    for a debug section, and the offsets in the same column of subsequent rows
11710    refer to that section.  The section identifiers for Version 2 are:
11711
11712     DW_SECT_INFO         1  .debug_info.dwo
11713     DW_SECT_TYPES        2  .debug_types.dwo
11714     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11715     DW_SECT_LINE         4  .debug_line.dwo
11716     DW_SECT_LOC          5  .debug_loc.dwo
11717     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11718     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11719     DW_SECT_MACRO        8  .debug_macro.dwo
11720
11721    The section identifiers for Version 5 are:
11722
11723     DW_SECT_INFO_V5         1  .debug_info.dwo
11724     DW_SECT_RESERVED_V5     2  --
11725     DW_SECT_ABBREV_V5       3  .debug_abbrev.dwo
11726     DW_SECT_LINE_V5         4  .debug_line.dwo
11727     DW_SECT_LOCLISTS_V5     5  .debug_loclists.dwo
11728     DW_SECT_STR_OFFSETS_V5  6  .debug_str_offsets.dwo
11729     DW_SECT_MACRO_V5        7  .debug_macro.dwo
11730     DW_SECT_RNGLISTS_V5     8  .debug_rnglists.dwo
11731
11732    The offsets provided by the CU and TU index sections are the base offsets
11733    for the contributions made by each CU or TU to the corresponding section
11734    in the package file.  Each CU and TU header contains an abbrev_offset
11735    field, used to find the abbreviations table for that CU or TU within the
11736    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11737    be interpreted as relative to the base offset given in the index section.
11738    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11739    should be interpreted as relative to the base offset for .debug_line.dwo,
11740    and offsets into other debug sections obtained from DWARF attributes should
11741    also be interpreted as relative to the corresponding base offset.
11742
11743    The table of sizes begins immediately following the table of offsets.
11744    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11745    with L columns and N rows, in row-major order.  Each row in the array is
11746    indexed starting from 1 (row 0 is shared by the two tables).
11747
11748    ---
11749
11750    Hash table lookup is handled the same in version 1 and 2:
11751
11752    We assume that N and M will not exceed 2^32 - 1.
11753    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11754
11755    Given a 64-bit compilation unit signature or a type signature S, an entry
11756    in the hash table is located as follows:
11757
11758    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11759       the low-order k bits all set to 1.
11760
11761    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11762
11763    3) If the hash table entry at index H matches the signature, use that
11764       entry.  If the hash table entry at index H is unused (all zeroes),
11765       terminate the search: the signature is not present in the table.
11766
11767    4) Let H = (H + H') modulo M. Repeat at Step 3.
11768
11769    Because M > N and H' and M are relatively prime, the search is guaranteed
11770    to stop at an unused slot or find the match.  */
11771
11772 /* Create a hash table to map DWO IDs to their CU/TU entry in
11773    .debug_{info,types}.dwo in DWP_FILE.
11774    Returns NULL if there isn't one.
11775    Note: This function processes DWP files only, not DWO files.  */
11776
11777 static struct dwp_hash_table *
11778 create_dwp_hash_table (dwarf2_per_objfile *per_objfile,
11779                        struct dwp_file *dwp_file, int is_debug_types)
11780 {
11781   struct objfile *objfile = per_objfile->objfile;
11782   bfd *dbfd = dwp_file->dbfd.get ();
11783   const gdb_byte *index_ptr, *index_end;
11784   struct dwarf2_section_info *index;
11785   uint32_t version, nr_columns, nr_units, nr_slots;
11786   struct dwp_hash_table *htab;
11787
11788   if (is_debug_types)
11789     index = &dwp_file->sections.tu_index;
11790   else
11791     index = &dwp_file->sections.cu_index;
11792
11793   if (index->empty ())
11794     return NULL;
11795   index->read (objfile);
11796
11797   index_ptr = index->buffer;
11798   index_end = index_ptr + index->size;
11799
11800   /* For Version 5, the version is really 2 bytes of data & 2 bytes of padding.
11801      For now it's safe to just read 4 bytes (particularly as it's difficult to
11802      tell if you're dealing with Version 5 before you've read the version).   */
11803   version = read_4_bytes (dbfd, index_ptr);
11804   index_ptr += 4;
11805   if (version == 2 || version == 5)
11806     nr_columns = read_4_bytes (dbfd, index_ptr);
11807   else
11808     nr_columns = 0;
11809   index_ptr += 4;
11810   nr_units = read_4_bytes (dbfd, index_ptr);
11811   index_ptr += 4;
11812   nr_slots = read_4_bytes (dbfd, index_ptr);
11813   index_ptr += 4;
11814
11815   if (version != 1 && version != 2 && version != 5)
11816     {
11817       error (_("Dwarf Error: unsupported DWP file version (%s)"
11818                " [in module %s]"),
11819              pulongest (version), dwp_file->name);
11820     }
11821   if (nr_slots != (nr_slots & -nr_slots))
11822     {
11823       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
11824                " is not power of 2 [in module %s]"),
11825              pulongest (nr_slots), dwp_file->name);
11826     }
11827
11828   htab = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwp_hash_table);
11829   htab->version = version;
11830   htab->nr_columns = nr_columns;
11831   htab->nr_units = nr_units;
11832   htab->nr_slots = nr_slots;
11833   htab->hash_table = index_ptr;
11834   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
11835
11836   /* Exit early if the table is empty.  */
11837   if (nr_slots == 0 || nr_units == 0
11838       || (version == 2 && nr_columns == 0)
11839       || (version == 5 && nr_columns == 0))
11840     {
11841       /* All must be zero.  */
11842       if (nr_slots != 0 || nr_units != 0
11843           || (version == 2 && nr_columns != 0)
11844           || (version == 5 && nr_columns != 0))
11845         {
11846           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
11847                        " all zero [in modules %s]"),
11848                      dwp_file->name);
11849         }
11850       return htab;
11851     }
11852
11853   if (version == 1)
11854     {
11855       htab->section_pool.v1.indices =
11856         htab->unit_table + sizeof (uint32_t) * nr_slots;
11857       /* It's harder to decide whether the section is too small in v1.
11858          V1 is deprecated anyway so we punt.  */
11859     }
11860   else if (version == 2)
11861     {
11862       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11863       int *ids = htab->section_pool.v2.section_ids;
11864       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
11865       /* Reverse map for error checking.  */
11866       int ids_seen[DW_SECT_MAX + 1];
11867       int i;
11868
11869       if (nr_columns < 2)
11870         {
11871           error (_("Dwarf Error: bad DWP hash table, too few columns"
11872                    " in section table [in module %s]"),
11873                  dwp_file->name);
11874         }
11875       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11876         {
11877           error (_("Dwarf Error: bad DWP hash table, too many columns"
11878                    " in section table [in module %s]"),
11879                  dwp_file->name);
11880         }
11881       memset (ids, 255, sizeof_ids);
11882       memset (ids_seen, 255, sizeof (ids_seen));
11883       for (i = 0; i < nr_columns; ++i)
11884         {
11885           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11886
11887           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11888             {
11889               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11890                        " in section table [in module %s]"),
11891                      id, dwp_file->name);
11892             }
11893           if (ids_seen[id] != -1)
11894             {
11895               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11896                        " id %d in section table [in module %s]"),
11897                      id, dwp_file->name);
11898             }
11899           ids_seen[id] = i;
11900           ids[i] = id;
11901         }
11902       /* Must have exactly one info or types section.  */
11903       if (((ids_seen[DW_SECT_INFO] != -1)
11904            + (ids_seen[DW_SECT_TYPES] != -1))
11905           != 1)
11906         {
11907           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11908                    " DWO info/types section [in module %s]"),
11909                  dwp_file->name);
11910         }
11911       /* Must have an abbrev section.  */
11912       if (ids_seen[DW_SECT_ABBREV] == -1)
11913         {
11914           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11915                    " section [in module %s]"),
11916                  dwp_file->name);
11917         }
11918       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11919       htab->section_pool.v2.sizes =
11920         htab->section_pool.v2.offsets + (sizeof (uint32_t)
11921                                          * nr_units * nr_columns);
11922       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11923                                           * nr_units * nr_columns))
11924           > index_end)
11925         {
11926           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11927                    " [in module %s]"),
11928                  dwp_file->name);
11929         }
11930     }
11931   else /* version == 5  */
11932     {
11933       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11934       int *ids = htab->section_pool.v5.section_ids;
11935       size_t sizeof_ids = sizeof (htab->section_pool.v5.section_ids);
11936       /* Reverse map for error checking.  */
11937       int ids_seen[DW_SECT_MAX_V5 + 1];
11938
11939       if (nr_columns < 2)
11940         {
11941           error (_("Dwarf Error: bad DWP hash table, too few columns"
11942                    " in section table [in module %s]"),
11943                  dwp_file->name);
11944         }
11945       if (nr_columns > MAX_NR_V5_DWO_SECTIONS)
11946         {
11947           error (_("Dwarf Error: bad DWP hash table, too many columns"
11948                    " in section table [in module %s]"),
11949                  dwp_file->name);
11950         }
11951       memset (ids, 255, sizeof_ids);
11952       memset (ids_seen, 255, sizeof (ids_seen));
11953       for (int i = 0; i < nr_columns; ++i)
11954         {
11955           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11956
11957           if (id < DW_SECT_MIN || id > DW_SECT_MAX_V5)
11958             {
11959               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11960                        " in section table [in module %s]"),
11961                      id, dwp_file->name);
11962             }
11963           if (ids_seen[id] != -1)
11964             {
11965               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11966                        " id %d in section table [in module %s]"),
11967                      id, dwp_file->name);
11968             }
11969           ids_seen[id] = i;
11970           ids[i] = id;
11971         }
11972       /* Must have seen an info section.  */
11973       if (ids_seen[DW_SECT_INFO_V5] == -1)
11974         {
11975           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11976                    " DWO info/types section [in module %s]"),
11977                  dwp_file->name);
11978         }
11979       /* Must have an abbrev section.  */
11980       if (ids_seen[DW_SECT_ABBREV_V5] == -1)
11981         {
11982           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11983                    " section [in module %s]"),
11984                  dwp_file->name);
11985         }
11986       htab->section_pool.v5.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11987       htab->section_pool.v5.sizes
11988         = htab->section_pool.v5.offsets + (sizeof (uint32_t)
11989                                          * nr_units * nr_columns);
11990       if ((htab->section_pool.v5.sizes + (sizeof (uint32_t)
11991                                           * nr_units * nr_columns))
11992           > index_end)
11993         {
11994           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11995                    " [in module %s]"),
11996                  dwp_file->name);
11997         }
11998     }
11999
12000   return htab;
12001 }
12002
12003 /* Update SECTIONS with the data from SECTP.
12004
12005    This function is like the other "locate" section routines, but in
12006    this context the sections to read comes from the DWP V1 hash table,
12007    not the full ELF section table.
12008
12009    The result is non-zero for success, or zero if an error was found.  */
12010
12011 static int
12012 locate_v1_virtual_dwo_sections (asection *sectp,
12013                                 struct virtual_v1_dwo_sections *sections)
12014 {
12015   const struct dwop_section_names *names = &dwop_section_names;
12016
12017   if (names->abbrev_dwo.matches (sectp->name))
12018     {
12019       /* There can be only one.  */
12020       if (sections->abbrev.s.section != NULL)
12021         return 0;
12022       sections->abbrev.s.section = sectp;
12023       sections->abbrev.size = bfd_section_size (sectp);
12024     }
12025   else if (names->info_dwo.matches (sectp->name)
12026            || names->types_dwo.matches (sectp->name))
12027     {
12028       /* There can be only one.  */
12029       if (sections->info_or_types.s.section != NULL)
12030         return 0;
12031       sections->info_or_types.s.section = sectp;
12032       sections->info_or_types.size = bfd_section_size (sectp);
12033     }
12034   else if (names->line_dwo.matches (sectp->name))
12035     {
12036       /* There can be only one.  */
12037       if (sections->line.s.section != NULL)
12038         return 0;
12039       sections->line.s.section = sectp;
12040       sections->line.size = bfd_section_size (sectp);
12041     }
12042   else if (names->loc_dwo.matches (sectp->name))
12043     {
12044       /* There can be only one.  */
12045       if (sections->loc.s.section != NULL)
12046         return 0;
12047       sections->loc.s.section = sectp;
12048       sections->loc.size = bfd_section_size (sectp);
12049     }
12050   else if (names->macinfo_dwo.matches (sectp->name))
12051     {
12052       /* There can be only one.  */
12053       if (sections->macinfo.s.section != NULL)
12054         return 0;
12055       sections->macinfo.s.section = sectp;
12056       sections->macinfo.size = bfd_section_size (sectp);
12057     }
12058   else if (names->macro_dwo.matches (sectp->name))
12059     {
12060       /* There can be only one.  */
12061       if (sections->macro.s.section != NULL)
12062         return 0;
12063       sections->macro.s.section = sectp;
12064       sections->macro.size = bfd_section_size (sectp);
12065     }
12066   else if (names->str_offsets_dwo.matches (sectp->name))
12067     {
12068       /* There can be only one.  */
12069       if (sections->str_offsets.s.section != NULL)
12070         return 0;
12071       sections->str_offsets.s.section = sectp;
12072       sections->str_offsets.size = bfd_section_size (sectp);
12073     }
12074   else
12075     {
12076       /* No other kind of section is valid.  */
12077       return 0;
12078     }
12079
12080   return 1;
12081 }
12082
12083 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12084    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12085    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12086    This is for DWP version 1 files.  */
12087
12088 static struct dwo_unit *
12089 create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile *per_objfile,
12090                            struct dwp_file *dwp_file,
12091                            uint32_t unit_index,
12092                            const char *comp_dir,
12093                            ULONGEST signature, int is_debug_types)
12094 {
12095   const struct dwp_hash_table *dwp_htab =
12096     is_debug_types ? dwp_file->tus : dwp_file->cus;
12097   bfd *dbfd = dwp_file->dbfd.get ();
12098   const char *kind = is_debug_types ? "TU" : "CU";
12099   struct dwo_file *dwo_file;
12100   struct dwo_unit *dwo_unit;
12101   struct virtual_v1_dwo_sections sections;
12102   void **dwo_file_slot;
12103   int i;
12104
12105   gdb_assert (dwp_file->version == 1);
12106
12107   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V1 file: %s",
12108                            kind, pulongest (unit_index), hex_string (signature),
12109                            dwp_file->name);
12110
12111   /* Fetch the sections of this DWO unit.
12112      Put a limit on the number of sections we look for so that bad data
12113      doesn't cause us to loop forever.  */
12114
12115 #define MAX_NR_V1_DWO_SECTIONS \
12116   (1 /* .debug_info or .debug_types */ \
12117    + 1 /* .debug_abbrev */ \
12118    + 1 /* .debug_line */ \
12119    + 1 /* .debug_loc */ \
12120    + 1 /* .debug_str_offsets */ \
12121    + 1 /* .debug_macro or .debug_macinfo */ \
12122    + 1 /* trailing zero */)
12123
12124   memset (&sections, 0, sizeof (sections));
12125
12126   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12127     {
12128       asection *sectp;
12129       uint32_t section_nr =
12130         read_4_bytes (dbfd,
12131                       dwp_htab->section_pool.v1.indices
12132                       + (unit_index + i) * sizeof (uint32_t));
12133
12134       if (section_nr == 0)
12135         break;
12136       if (section_nr >= dwp_file->num_sections)
12137         {
12138           error (_("Dwarf Error: bad DWP hash table, section number too large"
12139                    " [in module %s]"),
12140                  dwp_file->name);
12141         }
12142
12143       sectp = dwp_file->elf_sections[section_nr];
12144       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12145         {
12146           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12147                    " [in module %s]"),
12148                  dwp_file->name);
12149         }
12150     }
12151
12152   if (i < 2
12153       || sections.info_or_types.empty ()
12154       || sections.abbrev.empty ())
12155     {
12156       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12157                " [in module %s]"),
12158              dwp_file->name);
12159     }
12160   if (i == MAX_NR_V1_DWO_SECTIONS)
12161     {
12162       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12163                " [in module %s]"),
12164              dwp_file->name);
12165     }
12166
12167   /* It's easier for the rest of the code if we fake a struct dwo_file and
12168      have dwo_unit "live" in that.  At least for now.
12169
12170      The DWP file can be made up of a random collection of CUs and TUs.
12171      However, for each CU + set of TUs that came from the same original DWO
12172      file, we can combine them back into a virtual DWO file to save space
12173      (fewer struct dwo_file objects to allocate).  Remember that for really
12174      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12175
12176   std::string virtual_dwo_name =
12177     string_printf ("virtual-dwo/%d-%d-%d-%d",
12178                    sections.abbrev.get_id (),
12179                    sections.line.get_id (),
12180                    sections.loc.get_id (),
12181                    sections.str_offsets.get_id ());
12182   /* Can we use an existing virtual DWO file?  */
12183   dwo_file_slot = lookup_dwo_file_slot (per_objfile, virtual_dwo_name.c_str (),
12184                                         comp_dir);
12185   /* Create one if necessary.  */
12186   if (*dwo_file_slot == NULL)
12187     {
12188       dwarf_read_debug_printf ("Creating virtual DWO: %s",
12189                                virtual_dwo_name.c_str ());
12190
12191       dwo_file = new struct dwo_file;
12192       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
12193       dwo_file->comp_dir = comp_dir;
12194       dwo_file->sections.abbrev = sections.abbrev;
12195       dwo_file->sections.line = sections.line;
12196       dwo_file->sections.loc = sections.loc;
12197       dwo_file->sections.macinfo = sections.macinfo;
12198       dwo_file->sections.macro = sections.macro;
12199       dwo_file->sections.str_offsets = sections.str_offsets;
12200       /* The "str" section is global to the entire DWP file.  */
12201       dwo_file->sections.str = dwp_file->sections.str;
12202       /* The info or types section is assigned below to dwo_unit,
12203          there's no need to record it in dwo_file.
12204          Also, we can't simply record type sections in dwo_file because
12205          we record a pointer into the vector in dwo_unit.  As we collect more
12206          types we'll grow the vector and eventually have to reallocate space
12207          for it, invalidating all copies of pointers into the previous
12208          contents.  */
12209       *dwo_file_slot = dwo_file;
12210     }
12211   else
12212     {
12213       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
12214                                virtual_dwo_name.c_str ());
12215
12216       dwo_file = (struct dwo_file *) *dwo_file_slot;
12217     }
12218
12219   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
12220   dwo_unit->dwo_file = dwo_file;
12221   dwo_unit->signature = signature;
12222   dwo_unit->section =
12223     XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
12224   *dwo_unit->section = sections.info_or_types;
12225   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12226
12227   return dwo_unit;
12228 }
12229
12230 /* Subroutine of create_dwo_unit_in_dwp_v2 and create_dwo_unit_in_dwp_v5 to
12231    simplify them.  Given a pointer to the containing section SECTION, and
12232    OFFSET,SIZE of the piece within that section used by a TU/CU, return a
12233    virtual section of just that piece.  */
12234
12235 static struct dwarf2_section_info
12236 create_dwp_v2_or_v5_section (dwarf2_per_objfile *per_objfile,
12237                              struct dwarf2_section_info *section,
12238                              bfd_size_type offset, bfd_size_type size)
12239 {
12240   struct dwarf2_section_info result;
12241   asection *sectp;
12242
12243   gdb_assert (section != NULL);
12244   gdb_assert (!section->is_virtual);
12245
12246   memset (&result, 0, sizeof (result));
12247   result.s.containing_section = section;
12248   result.is_virtual = true;
12249
12250   if (size == 0)
12251     return result;
12252
12253   sectp = section->get_bfd_section ();
12254
12255   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12256      bounds of the real section.  This is a pretty-rare event, so just
12257      flag an error (easier) instead of a warning and trying to cope.  */
12258   if (sectp == NULL
12259       || offset + size > bfd_section_size (sectp))
12260     {
12261       error (_("Dwarf Error: Bad DWP V2 or V5 section info, doesn't fit"
12262                " in section %s [in module %s]"),
12263              sectp ? bfd_section_name (sectp) : "<unknown>",
12264              objfile_name (per_objfile->objfile));
12265     }
12266
12267   result.virtual_offset = offset;
12268   result.size = size;
12269   return result;
12270 }
12271
12272 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12273    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12274    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12275    This is for DWP version 2 files.  */
12276
12277 static struct dwo_unit *
12278 create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile *per_objfile,
12279                            struct dwp_file *dwp_file,
12280                            uint32_t unit_index,
12281                            const char *comp_dir,
12282                            ULONGEST signature, int is_debug_types)
12283 {
12284   const struct dwp_hash_table *dwp_htab =
12285     is_debug_types ? dwp_file->tus : dwp_file->cus;
12286   bfd *dbfd = dwp_file->dbfd.get ();
12287   const char *kind = is_debug_types ? "TU" : "CU";
12288   struct dwo_file *dwo_file;
12289   struct dwo_unit *dwo_unit;
12290   struct virtual_v2_or_v5_dwo_sections sections;
12291   void **dwo_file_slot;
12292   int i;
12293
12294   gdb_assert (dwp_file->version == 2);
12295
12296   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V2 file: %s",
12297                            kind, pulongest (unit_index), hex_string (signature),
12298                            dwp_file->name);
12299
12300   /* Fetch the section offsets of this DWO unit.  */
12301
12302   memset (&sections, 0, sizeof (sections));
12303
12304   for (i = 0; i < dwp_htab->nr_columns; ++i)
12305     {
12306       uint32_t offset = read_4_bytes (dbfd,
12307                                       dwp_htab->section_pool.v2.offsets
12308                                       + (((unit_index - 1) * dwp_htab->nr_columns
12309                                           + i)
12310                                          * sizeof (uint32_t)));
12311       uint32_t size = read_4_bytes (dbfd,
12312                                     dwp_htab->section_pool.v2.sizes
12313                                     + (((unit_index - 1) * dwp_htab->nr_columns
12314                                         + i)
12315                                        * sizeof (uint32_t)));
12316
12317       switch (dwp_htab->section_pool.v2.section_ids[i])
12318         {
12319         case DW_SECT_INFO:
12320         case DW_SECT_TYPES:
12321           sections.info_or_types_offset = offset;
12322           sections.info_or_types_size = size;
12323           break;
12324         case DW_SECT_ABBREV:
12325           sections.abbrev_offset = offset;
12326           sections.abbrev_size = size;
12327           break;
12328         case DW_SECT_LINE:
12329           sections.line_offset = offset;
12330           sections.line_size = size;
12331           break;
12332         case DW_SECT_LOC:
12333           sections.loc_offset = offset;
12334           sections.loc_size = size;
12335           break;
12336         case DW_SECT_STR_OFFSETS:
12337           sections.str_offsets_offset = offset;
12338           sections.str_offsets_size = size;
12339           break;
12340         case DW_SECT_MACINFO:
12341           sections.macinfo_offset = offset;
12342           sections.macinfo_size = size;
12343           break;
12344         case DW_SECT_MACRO:
12345           sections.macro_offset = offset;
12346           sections.macro_size = size;
12347           break;
12348         }
12349     }
12350
12351   /* It's easier for the rest of the code if we fake a struct dwo_file and
12352      have dwo_unit "live" in that.  At least for now.
12353
12354      The DWP file can be made up of a random collection of CUs and TUs.
12355      However, for each CU + set of TUs that came from the same original DWO
12356      file, we can combine them back into a virtual DWO file to save space
12357      (fewer struct dwo_file objects to allocate).  Remember that for really
12358      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12359
12360   std::string virtual_dwo_name =
12361     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12362                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12363                    (long) (sections.line_size ? sections.line_offset : 0),
12364                    (long) (sections.loc_size ? sections.loc_offset : 0),
12365                    (long) (sections.str_offsets_size
12366                            ? sections.str_offsets_offset : 0));
12367   /* Can we use an existing virtual DWO file?  */
12368   dwo_file_slot = lookup_dwo_file_slot (per_objfile, virtual_dwo_name.c_str (),
12369                                         comp_dir);
12370   /* Create one if necessary.  */
12371   if (*dwo_file_slot == NULL)
12372     {
12373       dwarf_read_debug_printf ("Creating virtual DWO: %s",
12374                                virtual_dwo_name.c_str ());
12375
12376       dwo_file = new struct dwo_file;
12377       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
12378       dwo_file->comp_dir = comp_dir;
12379       dwo_file->sections.abbrev =
12380         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.abbrev,
12381                                      sections.abbrev_offset,
12382                                      sections.abbrev_size);
12383       dwo_file->sections.line =
12384         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.line,
12385                                      sections.line_offset,
12386                                      sections.line_size);
12387       dwo_file->sections.loc =
12388         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.loc,
12389                                      sections.loc_offset, sections.loc_size);
12390       dwo_file->sections.macinfo =
12391         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.macinfo,
12392                                      sections.macinfo_offset,
12393                                      sections.macinfo_size);
12394       dwo_file->sections.macro =
12395         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.macro,
12396                                      sections.macro_offset,
12397                                      sections.macro_size);
12398       dwo_file->sections.str_offsets =
12399         create_dwp_v2_or_v5_section (per_objfile,
12400                                      &dwp_file->sections.str_offsets,
12401                                      sections.str_offsets_offset,
12402                                      sections.str_offsets_size);
12403       /* The "str" section is global to the entire DWP file.  */
12404       dwo_file->sections.str = dwp_file->sections.str;
12405       /* The info or types section is assigned below to dwo_unit,
12406          there's no need to record it in dwo_file.
12407          Also, we can't simply record type sections in dwo_file because
12408          we record a pointer into the vector in dwo_unit.  As we collect more
12409          types we'll grow the vector and eventually have to reallocate space
12410          for it, invalidating all copies of pointers into the previous
12411          contents.  */
12412       *dwo_file_slot = dwo_file;
12413     }
12414   else
12415     {
12416       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
12417                                virtual_dwo_name.c_str ());
12418
12419       dwo_file = (struct dwo_file *) *dwo_file_slot;
12420     }
12421
12422   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
12423   dwo_unit->dwo_file = dwo_file;
12424   dwo_unit->signature = signature;
12425   dwo_unit->section =
12426     XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
12427   *dwo_unit->section = create_dwp_v2_or_v5_section
12428                          (per_objfile,
12429                           is_debug_types
12430                           ? &dwp_file->sections.types
12431                           : &dwp_file->sections.info,
12432                           sections.info_or_types_offset,
12433                           sections.info_or_types_size);
12434   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12435
12436   return dwo_unit;
12437 }
12438
12439 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12440    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12441    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12442    This is for DWP version 5 files.  */
12443
12444 static struct dwo_unit *
12445 create_dwo_unit_in_dwp_v5 (dwarf2_per_objfile *per_objfile,
12446                            struct dwp_file *dwp_file,
12447                            uint32_t unit_index,
12448                            const char *comp_dir,
12449                            ULONGEST signature, int is_debug_types)
12450 {
12451   const struct dwp_hash_table *dwp_htab
12452     = is_debug_types ? dwp_file->tus : dwp_file->cus;
12453   bfd *dbfd = dwp_file->dbfd.get ();
12454   const char *kind = is_debug_types ? "TU" : "CU";
12455   struct dwo_file *dwo_file;
12456   struct dwo_unit *dwo_unit;
12457   struct virtual_v2_or_v5_dwo_sections sections {};
12458   void **dwo_file_slot;
12459
12460   gdb_assert (dwp_file->version == 5);
12461
12462   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V5 file: %s",
12463                            kind, pulongest (unit_index), hex_string (signature),
12464                            dwp_file->name);
12465
12466   /* Fetch the section offsets of this DWO unit.  */
12467
12468   /*  memset (&sections, 0, sizeof (sections)); */
12469
12470   for (int i = 0; i < dwp_htab->nr_columns; ++i)
12471     {
12472       uint32_t offset = read_4_bytes (dbfd,
12473                                       dwp_htab->section_pool.v5.offsets
12474                                       + (((unit_index - 1)
12475                                           * dwp_htab->nr_columns
12476                                           + i)
12477                                          * sizeof (uint32_t)));
12478       uint32_t size = read_4_bytes (dbfd,
12479                                     dwp_htab->section_pool.v5.sizes
12480                                     + (((unit_index - 1) * dwp_htab->nr_columns
12481                                         + i)
12482                                        * sizeof (uint32_t)));
12483
12484       switch (dwp_htab->section_pool.v5.section_ids[i])
12485         {
12486           case DW_SECT_ABBREV_V5:
12487             sections.abbrev_offset = offset;
12488             sections.abbrev_size = size;
12489             break;
12490           case DW_SECT_INFO_V5:
12491             sections.info_or_types_offset = offset;
12492             sections.info_or_types_size = size;
12493             break;
12494           case DW_SECT_LINE_V5:
12495             sections.line_offset = offset;
12496             sections.line_size = size;
12497             break;
12498           case DW_SECT_LOCLISTS_V5:
12499             sections.loclists_offset = offset;
12500             sections.loclists_size = size;
12501             break;
12502           case DW_SECT_MACRO_V5:
12503             sections.macro_offset = offset;
12504             sections.macro_size = size;
12505             break;
12506           case DW_SECT_RNGLISTS_V5:
12507             sections.rnglists_offset = offset;
12508             sections.rnglists_size = size;
12509             break;
12510           case DW_SECT_STR_OFFSETS_V5:
12511             sections.str_offsets_offset = offset;
12512             sections.str_offsets_size = size;
12513             break;
12514           case DW_SECT_RESERVED_V5:
12515           default:
12516             break;
12517         }
12518     }
12519
12520   /* It's easier for the rest of the code if we fake a struct dwo_file and
12521      have dwo_unit "live" in that.  At least for now.
12522
12523      The DWP file can be made up of a random collection of CUs and TUs.
12524      However, for each CU + set of TUs that came from the same original DWO
12525      file, we can combine them back into a virtual DWO file to save space
12526      (fewer struct dwo_file objects to allocate).  Remember that for really
12527      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12528
12529   std::string virtual_dwo_name =
12530     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld-%ld-%ld",
12531                  (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12532                  (long) (sections.line_size ? sections.line_offset : 0),
12533                  (long) (sections.loclists_size ? sections.loclists_offset : 0),
12534                  (long) (sections.str_offsets_size
12535                             ? sections.str_offsets_offset : 0),
12536                  (long) (sections.macro_size ? sections.macro_offset : 0),
12537                  (long) (sections.rnglists_size ? sections.rnglists_offset: 0));
12538   /* Can we use an existing virtual DWO file?  */
12539   dwo_file_slot = lookup_dwo_file_slot (per_objfile,
12540                                         virtual_dwo_name.c_str (),
12541                                         comp_dir);
12542   /* Create one if necessary.  */
12543   if (*dwo_file_slot == NULL)
12544     {
12545       dwarf_read_debug_printf ("Creating virtual DWO: %s",
12546                                virtual_dwo_name.c_str ());
12547
12548       dwo_file = new struct dwo_file;
12549       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
12550       dwo_file->comp_dir = comp_dir;
12551       dwo_file->sections.abbrev =
12552         create_dwp_v2_or_v5_section (per_objfile,
12553                                      &dwp_file->sections.abbrev,
12554                                      sections.abbrev_offset,
12555                                      sections.abbrev_size);
12556       dwo_file->sections.line =
12557         create_dwp_v2_or_v5_section (per_objfile,
12558                                      &dwp_file->sections.line,
12559                                      sections.line_offset, sections.line_size);
12560       dwo_file->sections.macro =
12561         create_dwp_v2_or_v5_section (per_objfile,
12562                                      &dwp_file->sections.macro,
12563                                      sections.macro_offset,
12564                                      sections.macro_size);
12565       dwo_file->sections.loclists =
12566         create_dwp_v2_or_v5_section (per_objfile,
12567                                      &dwp_file->sections.loclists,
12568                                      sections.loclists_offset,
12569                                      sections.loclists_size);
12570       dwo_file->sections.rnglists =
12571         create_dwp_v2_or_v5_section (per_objfile,
12572                                      &dwp_file->sections.rnglists,
12573                                      sections.rnglists_offset,
12574                                      sections.rnglists_size);
12575       dwo_file->sections.str_offsets =
12576         create_dwp_v2_or_v5_section (per_objfile,
12577                                      &dwp_file->sections.str_offsets,
12578                                      sections.str_offsets_offset,
12579                                      sections.str_offsets_size);
12580       /* The "str" section is global to the entire DWP file.  */
12581       dwo_file->sections.str = dwp_file->sections.str;
12582       /* The info or types section is assigned below to dwo_unit,
12583          there's no need to record it in dwo_file.
12584          Also, we can't simply record type sections in dwo_file because
12585          we record a pointer into the vector in dwo_unit.  As we collect more
12586          types we'll grow the vector and eventually have to reallocate space
12587          for it, invalidating all copies of pointers into the previous
12588          contents.  */
12589       *dwo_file_slot = dwo_file;
12590     }
12591   else
12592     {
12593       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
12594                                virtual_dwo_name.c_str ());
12595
12596       dwo_file = (struct dwo_file *) *dwo_file_slot;
12597     }
12598
12599   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
12600   dwo_unit->dwo_file = dwo_file;
12601   dwo_unit->signature = signature;
12602   dwo_unit->section
12603     = XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
12604   *dwo_unit->section = create_dwp_v2_or_v5_section (per_objfile,
12605                                               &dwp_file->sections.info,
12606                                               sections.info_or_types_offset,
12607                                               sections.info_or_types_size);
12608   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12609
12610   return dwo_unit;
12611 }
12612
12613 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12614    Returns NULL if the signature isn't found.  */
12615
12616 static struct dwo_unit *
12617 lookup_dwo_unit_in_dwp (dwarf2_per_objfile *per_objfile,
12618                         struct dwp_file *dwp_file, const char *comp_dir,
12619                         ULONGEST signature, int is_debug_types)
12620 {
12621   const struct dwp_hash_table *dwp_htab =
12622     is_debug_types ? dwp_file->tus : dwp_file->cus;
12623   bfd *dbfd = dwp_file->dbfd.get ();
12624   uint32_t mask = dwp_htab->nr_slots - 1;
12625   uint32_t hash = signature & mask;
12626   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12627   unsigned int i;
12628   void **slot;
12629   struct dwo_unit find_dwo_cu;
12630
12631   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12632   find_dwo_cu.signature = signature;
12633   slot = htab_find_slot (is_debug_types
12634                          ? dwp_file->loaded_tus.get ()
12635                          : dwp_file->loaded_cus.get (),
12636                          &find_dwo_cu, INSERT);
12637
12638   if (*slot != NULL)
12639     return (struct dwo_unit *) *slot;
12640
12641   /* Use a for loop so that we don't loop forever on bad debug info.  */
12642   for (i = 0; i < dwp_htab->nr_slots; ++i)
12643     {
12644       ULONGEST signature_in_table;
12645
12646       signature_in_table =
12647         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12648       if (signature_in_table == signature)
12649         {
12650           uint32_t unit_index =
12651             read_4_bytes (dbfd,
12652                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12653
12654           if (dwp_file->version == 1)
12655             {
12656               *slot = create_dwo_unit_in_dwp_v1 (per_objfile, dwp_file,
12657                                                  unit_index, comp_dir,
12658                                                  signature, is_debug_types);
12659             }
12660           else if (dwp_file->version == 2)
12661             {
12662               *slot = create_dwo_unit_in_dwp_v2 (per_objfile, dwp_file,
12663                                                  unit_index, comp_dir,
12664                                                  signature, is_debug_types);
12665             }
12666           else /* version == 5  */
12667             {
12668               *slot = create_dwo_unit_in_dwp_v5 (per_objfile, dwp_file,
12669                                                  unit_index, comp_dir,
12670                                                  signature, is_debug_types);
12671             }
12672           return (struct dwo_unit *) *slot;
12673         }
12674       if (signature_in_table == 0)
12675         return NULL;
12676       hash = (hash + hash2) & mask;
12677     }
12678
12679   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12680            " [in module %s]"),
12681          dwp_file->name);
12682 }
12683
12684 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12685    Open the file specified by FILE_NAME and hand it off to BFD for
12686    preliminary analysis.  Return a newly initialized bfd *, which
12687    includes a canonicalized copy of FILE_NAME.
12688    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12689    SEARCH_CWD is true if the current directory is to be searched.
12690    It will be searched before debug-file-directory.
12691    If successful, the file is added to the bfd include table of the
12692    objfile's bfd (see gdb_bfd_record_inclusion).
12693    If unable to find/open the file, return NULL.
12694    NOTE: This function is derived from symfile_bfd_open.  */
12695
12696 static gdb_bfd_ref_ptr
12697 try_open_dwop_file (dwarf2_per_objfile *per_objfile,
12698                     const char *file_name, int is_dwp, int search_cwd)
12699 {
12700   int desc;
12701   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12702      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12703      to debug_file_directory.  */
12704   const char *search_path;
12705   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12706
12707   gdb::unique_xmalloc_ptr<char> search_path_holder;
12708   if (search_cwd)
12709     {
12710       if (*debug_file_directory != '\0')
12711         {
12712           search_path_holder.reset (concat (".", dirname_separator_string,
12713                                             debug_file_directory,
12714                                             (char *) NULL));
12715           search_path = search_path_holder.get ();
12716         }
12717       else
12718         search_path = ".";
12719     }
12720   else
12721     search_path = debug_file_directory;
12722
12723   openp_flags flags = OPF_RETURN_REALPATH;
12724   if (is_dwp)
12725     flags |= OPF_SEARCH_IN_PATH;
12726
12727   gdb::unique_xmalloc_ptr<char> absolute_name;
12728   desc = openp (search_path, flags, file_name,
12729                 O_RDONLY | O_BINARY, &absolute_name);
12730   if (desc < 0)
12731     return NULL;
12732
12733   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12734                                          gnutarget, desc));
12735   if (sym_bfd == NULL)
12736     return NULL;
12737   bfd_set_cacheable (sym_bfd.get (), 1);
12738
12739   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12740     return NULL;
12741
12742   /* Success.  Record the bfd as having been included by the objfile's bfd.
12743      This is important because things like demangled_names_hash lives in the
12744      objfile's per_bfd space and may have references to things like symbol
12745      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12746   gdb_bfd_record_inclusion (per_objfile->objfile->obfd, sym_bfd.get ());
12747
12748   return sym_bfd;
12749 }
12750
12751 /* Try to open DWO file FILE_NAME.
12752    COMP_DIR is the DW_AT_comp_dir attribute.
12753    The result is the bfd handle of the file.
12754    If there is a problem finding or opening the file, return NULL.
12755    Upon success, the canonicalized path of the file is stored in the bfd,
12756    same as symfile_bfd_open.  */
12757
12758 static gdb_bfd_ref_ptr
12759 open_dwo_file (dwarf2_per_objfile *per_objfile,
12760                const char *file_name, const char *comp_dir)
12761 {
12762   if (IS_ABSOLUTE_PATH (file_name))
12763     return try_open_dwop_file (per_objfile, file_name,
12764                                0 /*is_dwp*/, 0 /*search_cwd*/);
12765
12766   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12767
12768   if (comp_dir != NULL)
12769     {
12770       gdb::unique_xmalloc_ptr<char> path_to_try
12771         (concat (comp_dir, SLASH_STRING, file_name, (char *) NULL));
12772
12773       /* NOTE: If comp_dir is a relative path, this will also try the
12774          search path, which seems useful.  */
12775       gdb_bfd_ref_ptr abfd (try_open_dwop_file (per_objfile, path_to_try.get (),
12776                                                 0 /*is_dwp*/,
12777                                                 1 /*search_cwd*/));
12778       if (abfd != NULL)
12779         return abfd;
12780     }
12781
12782   /* That didn't work, try debug-file-directory, which, despite its name,
12783      is a list of paths.  */
12784
12785   if (*debug_file_directory == '\0')
12786     return NULL;
12787
12788   return try_open_dwop_file (per_objfile, file_name,
12789                              0 /*is_dwp*/, 1 /*search_cwd*/);
12790 }
12791
12792 /* This function is mapped across the sections and remembers the offset and
12793    size of each of the DWO debugging sections we are interested in.  */
12794
12795 static void
12796 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp,
12797                             dwo_sections *dwo_sections)
12798 {
12799   const struct dwop_section_names *names = &dwop_section_names;
12800
12801   if (names->abbrev_dwo.matches (sectp->name))
12802     {
12803       dwo_sections->abbrev.s.section = sectp;
12804       dwo_sections->abbrev.size = bfd_section_size (sectp);
12805     }
12806   else if (names->info_dwo.matches (sectp->name))
12807     {
12808       dwo_sections->info.s.section = sectp;
12809       dwo_sections->info.size = bfd_section_size (sectp);
12810     }
12811   else if (names->line_dwo.matches (sectp->name))
12812     {
12813       dwo_sections->line.s.section = sectp;
12814       dwo_sections->line.size = bfd_section_size (sectp);
12815     }
12816   else if (names->loc_dwo.matches (sectp->name))
12817     {
12818       dwo_sections->loc.s.section = sectp;
12819       dwo_sections->loc.size = bfd_section_size (sectp);
12820     }
12821   else if (names->loclists_dwo.matches (sectp->name))
12822     {
12823       dwo_sections->loclists.s.section = sectp;
12824       dwo_sections->loclists.size = bfd_section_size (sectp);
12825     }
12826   else if (names->macinfo_dwo.matches (sectp->name))
12827     {
12828       dwo_sections->macinfo.s.section = sectp;
12829       dwo_sections->macinfo.size = bfd_section_size (sectp);
12830     }
12831   else if (names->macro_dwo.matches (sectp->name))
12832     {
12833       dwo_sections->macro.s.section = sectp;
12834       dwo_sections->macro.size = bfd_section_size (sectp);
12835     }
12836   else if (names->rnglists_dwo.matches (sectp->name))
12837     {
12838       dwo_sections->rnglists.s.section = sectp;
12839       dwo_sections->rnglists.size = bfd_section_size (sectp);
12840     }
12841   else if (names->str_dwo.matches (sectp->name))
12842     {
12843       dwo_sections->str.s.section = sectp;
12844       dwo_sections->str.size = bfd_section_size (sectp);
12845     }
12846   else if (names->str_offsets_dwo.matches (sectp->name))
12847     {
12848       dwo_sections->str_offsets.s.section = sectp;
12849       dwo_sections->str_offsets.size = bfd_section_size (sectp);
12850     }
12851   else if (names->types_dwo.matches (sectp->name))
12852     {
12853       struct dwarf2_section_info type_section;
12854
12855       memset (&type_section, 0, sizeof (type_section));
12856       type_section.s.section = sectp;
12857       type_section.size = bfd_section_size (sectp);
12858       dwo_sections->types.push_back (type_section);
12859     }
12860 }
12861
12862 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12863    by PER_CU.  This is for the non-DWP case.
12864    The result is NULL if DWO_NAME can't be found.  */
12865
12866 static struct dwo_file *
12867 open_and_init_dwo_file (dwarf2_cu *cu, const char *dwo_name,
12868                         const char *comp_dir)
12869 {
12870   dwarf2_per_objfile *per_objfile = cu->per_objfile;
12871
12872   gdb_bfd_ref_ptr dbfd = open_dwo_file (per_objfile, dwo_name, comp_dir);
12873   if (dbfd == NULL)
12874     {
12875       dwarf_read_debug_printf ("DWO file not found: %s", dwo_name);
12876
12877       return NULL;
12878     }
12879
12880   dwo_file_up dwo_file (new struct dwo_file);
12881   dwo_file->dwo_name = dwo_name;
12882   dwo_file->comp_dir = comp_dir;
12883   dwo_file->dbfd = std::move (dbfd);
12884
12885   for (asection *sec : gdb_bfd_sections (dwo_file->dbfd))
12886     dwarf2_locate_dwo_sections (dwo_file->dbfd.get (), sec,
12887                                 &dwo_file->sections);
12888
12889   create_cus_hash_table (per_objfile, cu, *dwo_file, dwo_file->sections.info,
12890                          dwo_file->cus);
12891
12892   if (cu->per_cu->dwarf_version < 5)
12893     {
12894       create_debug_types_hash_table (per_objfile, dwo_file.get (),
12895                                      dwo_file->sections.types, dwo_file->tus);
12896     }
12897   else
12898     {
12899       create_debug_type_hash_table (per_objfile, dwo_file.get (),
12900                                     &dwo_file->sections.info, dwo_file->tus,
12901                                     rcuh_kind::COMPILE);
12902     }
12903
12904   dwarf_read_debug_printf ("DWO file found: %s", dwo_name);
12905
12906   return dwo_file.release ();
12907 }
12908
12909 /* This function is mapped across the sections and remembers the offset and
12910    size of each of the DWP debugging sections common to version 1 and 2 that
12911    we are interested in.  */
12912
12913 static void
12914 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12915                                    dwp_file *dwp_file)
12916 {
12917   const struct dwop_section_names *names = &dwop_section_names;
12918   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12919
12920   /* Record the ELF section number for later lookup: this is what the
12921      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12922   gdb_assert (elf_section_nr < dwp_file->num_sections);
12923   dwp_file->elf_sections[elf_section_nr] = sectp;
12924
12925   /* Look for specific sections that we need.  */
12926   if (names->str_dwo.matches (sectp->name))
12927     {
12928       dwp_file->sections.str.s.section = sectp;
12929       dwp_file->sections.str.size = bfd_section_size (sectp);
12930     }
12931   else if (names->cu_index.matches (sectp->name))
12932     {
12933       dwp_file->sections.cu_index.s.section = sectp;
12934       dwp_file->sections.cu_index.size = bfd_section_size (sectp);
12935     }
12936   else if (names->tu_index.matches (sectp->name))
12937     {
12938       dwp_file->sections.tu_index.s.section = sectp;
12939       dwp_file->sections.tu_index.size = bfd_section_size (sectp);
12940     }
12941 }
12942
12943 /* This function is mapped across the sections and remembers the offset and
12944    size of each of the DWP version 2 debugging sections that we are interested
12945    in.  This is split into a separate function because we don't know if we
12946    have version 1 or 2 or 5 until we parse the cu_index/tu_index sections.  */
12947
12948 static void
12949 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12950 {
12951   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12952   const struct dwop_section_names *names = &dwop_section_names;
12953   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12954
12955   /* Record the ELF section number for later lookup: this is what the
12956      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12957   gdb_assert (elf_section_nr < dwp_file->num_sections);
12958   dwp_file->elf_sections[elf_section_nr] = sectp;
12959
12960   /* Look for specific sections that we need.  */
12961   if (names->abbrev_dwo.matches (sectp->name))
12962     {
12963       dwp_file->sections.abbrev.s.section = sectp;
12964       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
12965     }
12966   else if (names->info_dwo.matches (sectp->name))
12967     {
12968       dwp_file->sections.info.s.section = sectp;
12969       dwp_file->sections.info.size = bfd_section_size (sectp);
12970     }
12971   else if (names->line_dwo.matches (sectp->name))
12972     {
12973       dwp_file->sections.line.s.section = sectp;
12974       dwp_file->sections.line.size = bfd_section_size (sectp);
12975     }
12976   else if (names->loc_dwo.matches (sectp->name))
12977     {
12978       dwp_file->sections.loc.s.section = sectp;
12979       dwp_file->sections.loc.size = bfd_section_size (sectp);
12980     }
12981   else if (names->macinfo_dwo.matches (sectp->name))
12982     {
12983       dwp_file->sections.macinfo.s.section = sectp;
12984       dwp_file->sections.macinfo.size = bfd_section_size (sectp);
12985     }
12986   else if (names->macro_dwo.matches (sectp->name))
12987     {
12988       dwp_file->sections.macro.s.section = sectp;
12989       dwp_file->sections.macro.size = bfd_section_size (sectp);
12990     }
12991   else if (names->str_offsets_dwo.matches (sectp->name))
12992     {
12993       dwp_file->sections.str_offsets.s.section = sectp;
12994       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
12995     }
12996   else if (names->types_dwo.matches (sectp->name))
12997     {
12998       dwp_file->sections.types.s.section = sectp;
12999       dwp_file->sections.types.size = bfd_section_size (sectp);
13000     }
13001 }
13002
13003 /* This function is mapped across the sections and remembers the offset and
13004    size of each of the DWP version 5 debugging sections that we are interested
13005    in.  This is split into a separate function because we don't know if we
13006    have version 1 or 2 or 5 until we parse the cu_index/tu_index sections.  */
13007
13008 static void
13009 dwarf2_locate_v5_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13010 {
13011   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13012   const struct dwop_section_names *names = &dwop_section_names;
13013   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13014
13015   /* Record the ELF section number for later lookup: this is what the
13016      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13017   gdb_assert (elf_section_nr < dwp_file->num_sections);
13018   dwp_file->elf_sections[elf_section_nr] = sectp;
13019
13020   /* Look for specific sections that we need.  */
13021   if (names->abbrev_dwo.matches (sectp->name))
13022     {
13023       dwp_file->sections.abbrev.s.section = sectp;
13024       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
13025     }
13026   else if (names->info_dwo.matches (sectp->name))
13027     {
13028       dwp_file->sections.info.s.section = sectp;
13029       dwp_file->sections.info.size = bfd_section_size (sectp);
13030     }
13031   else if (names->line_dwo.matches (sectp->name))
13032    {
13033      dwp_file->sections.line.s.section = sectp;
13034      dwp_file->sections.line.size = bfd_section_size (sectp);
13035     }
13036   else if (names->loclists_dwo.matches (sectp->name))
13037     {
13038       dwp_file->sections.loclists.s.section = sectp;
13039       dwp_file->sections.loclists.size = bfd_section_size (sectp);
13040     }
13041   else if (names->macro_dwo.matches (sectp->name))
13042     {
13043       dwp_file->sections.macro.s.section = sectp;
13044       dwp_file->sections.macro.size = bfd_section_size (sectp);
13045     }
13046   else if (names->rnglists_dwo.matches (sectp->name))
13047     {
13048       dwp_file->sections.rnglists.s.section = sectp;
13049       dwp_file->sections.rnglists.size = bfd_section_size (sectp);
13050     }
13051   else if (names->str_offsets_dwo.matches (sectp->name))
13052     {
13053       dwp_file->sections.str_offsets.s.section = sectp;
13054       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
13055     }
13056 }
13057
13058 /* Hash function for dwp_file loaded CUs/TUs.  */
13059
13060 static hashval_t
13061 hash_dwp_loaded_cutus (const void *item)
13062 {
13063   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13064
13065   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13066   return dwo_unit->signature;
13067 }
13068
13069 /* Equality function for dwp_file loaded CUs/TUs.  */
13070
13071 static int
13072 eq_dwp_loaded_cutus (const void *a, const void *b)
13073 {
13074   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13075   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13076
13077   return dua->signature == dub->signature;
13078 }
13079
13080 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13081
13082 static htab_up
13083 allocate_dwp_loaded_cutus_table ()
13084 {
13085   return htab_up (htab_create_alloc (3,
13086                                      hash_dwp_loaded_cutus,
13087                                      eq_dwp_loaded_cutus,
13088                                      NULL, xcalloc, xfree));
13089 }
13090
13091 /* Try to open DWP file FILE_NAME.
13092    The result is the bfd handle of the file.
13093    If there is a problem finding or opening the file, return NULL.
13094    Upon success, the canonicalized path of the file is stored in the bfd,
13095    same as symfile_bfd_open.  */
13096
13097 static gdb_bfd_ref_ptr
13098 open_dwp_file (dwarf2_per_objfile *per_objfile, const char *file_name)
13099 {
13100   gdb_bfd_ref_ptr abfd (try_open_dwop_file (per_objfile, file_name,
13101                                             1 /*is_dwp*/,
13102                                             1 /*search_cwd*/));
13103   if (abfd != NULL)
13104     return abfd;
13105
13106   /* Work around upstream bug 15652.
13107      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13108      [Whether that's a "bug" is debatable, but it is getting in our way.]
13109      We have no real idea where the dwp file is, because gdb's realpath-ing
13110      of the executable's path may have discarded the needed info.
13111      [IWBN if the dwp file name was recorded in the executable, akin to
13112      .gnu_debuglink, but that doesn't exist yet.]
13113      Strip the directory from FILE_NAME and search again.  */
13114   if (*debug_file_directory != '\0')
13115     {
13116       /* Don't implicitly search the current directory here.
13117          If the user wants to search "." to handle this case,
13118          it must be added to debug-file-directory.  */
13119       return try_open_dwop_file (per_objfile, lbasename (file_name),
13120                                  1 /*is_dwp*/,
13121                                  0 /*search_cwd*/);
13122     }
13123
13124   return NULL;
13125 }
13126
13127 /* Initialize the use of the DWP file for the current objfile.
13128    By convention the name of the DWP file is ${objfile}.dwp.
13129    The result is NULL if it can't be found.  */
13130
13131 static std::unique_ptr<struct dwp_file>
13132 open_and_init_dwp_file (dwarf2_per_objfile *per_objfile)
13133 {
13134   struct objfile *objfile = per_objfile->objfile;
13135
13136   /* Try to find first .dwp for the binary file before any symbolic links
13137      resolving.  */
13138
13139   /* If the objfile is a debug file, find the name of the real binary
13140      file and get the name of dwp file from there.  */
13141   std::string dwp_name;
13142   if (objfile->separate_debug_objfile_backlink != NULL)
13143     {
13144       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13145       const char *backlink_basename = lbasename (backlink->original_name);
13146
13147       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13148     }
13149   else
13150     dwp_name = objfile->original_name;
13151
13152   dwp_name += ".dwp";
13153
13154   gdb_bfd_ref_ptr dbfd (open_dwp_file (per_objfile, dwp_name.c_str ()));
13155   if (dbfd == NULL
13156       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13157     {
13158       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13159       dwp_name = objfile_name (objfile);
13160       dwp_name += ".dwp";
13161       dbfd = open_dwp_file (per_objfile, dwp_name.c_str ());
13162     }
13163
13164   if (dbfd == NULL)
13165     {
13166       dwarf_read_debug_printf ("DWP file not found: %s", dwp_name.c_str ());
13167
13168       return std::unique_ptr<dwp_file> ();
13169     }
13170
13171   const char *name = bfd_get_filename (dbfd.get ());
13172   std::unique_ptr<struct dwp_file> dwp_file
13173     (new struct dwp_file (name, std::move (dbfd)));
13174
13175   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
13176   dwp_file->elf_sections =
13177     OBSTACK_CALLOC (&per_objfile->per_bfd->obstack,
13178                     dwp_file->num_sections, asection *);
13179
13180   for (asection *sec : gdb_bfd_sections (dwp_file->dbfd))
13181     dwarf2_locate_common_dwp_sections (dwp_file->dbfd.get (), sec,
13182                                        dwp_file.get ());
13183
13184   dwp_file->cus = create_dwp_hash_table (per_objfile, dwp_file.get (), 0);
13185
13186   dwp_file->tus = create_dwp_hash_table (per_objfile, dwp_file.get (), 1);
13187
13188   /* The DWP file version is stored in the hash table.  Oh well.  */
13189   if (dwp_file->cus && dwp_file->tus
13190       && dwp_file->cus->version != dwp_file->tus->version)
13191     {
13192       /* Technically speaking, we should try to limp along, but this is
13193          pretty bizarre.  We use pulongest here because that's the established
13194          portability solution (e.g, we cannot use %u for uint32_t).  */
13195       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13196                " TU version %s [in DWP file %s]"),
13197              pulongest (dwp_file->cus->version),
13198              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13199     }
13200
13201   if (dwp_file->cus)
13202     dwp_file->version = dwp_file->cus->version;
13203   else if (dwp_file->tus)
13204     dwp_file->version = dwp_file->tus->version;
13205   else
13206     dwp_file->version = 2;
13207
13208   for (asection *sec : gdb_bfd_sections (dwp_file->dbfd))
13209     {
13210       if (dwp_file->version == 2)
13211         dwarf2_locate_v2_dwp_sections (dwp_file->dbfd.get (), sec,
13212                                        dwp_file.get ());
13213       else
13214         dwarf2_locate_v5_dwp_sections (dwp_file->dbfd.get (), sec,
13215                                        dwp_file.get ());
13216     }
13217
13218   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table ();
13219   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table ();
13220
13221   dwarf_read_debug_printf ("DWP file found: %s", dwp_file->name);
13222   dwarf_read_debug_printf ("    %s CUs, %s TUs",
13223                            pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13224                            pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13225
13226   return dwp_file;
13227 }
13228
13229 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13230
13231 static struct dwp_file *
13232 get_dwp_file (dwarf2_per_objfile *per_objfile)
13233 {
13234   if (!per_objfile->per_bfd->dwp_checked)
13235     {
13236       per_objfile->per_bfd->dwp_file = open_and_init_dwp_file (per_objfile);
13237       per_objfile->per_bfd->dwp_checked = 1;
13238     }
13239   return per_objfile->per_bfd->dwp_file.get ();
13240 }
13241
13242 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13243    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13244    or in the DWP file for the objfile, referenced by THIS_UNIT.
13245    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13246    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13247
13248    This is called, for example, when wanting to read a variable with a
13249    complex location.  Therefore we don't want to do file i/o for every call.
13250    Therefore we don't want to look for a DWO file on every call.
13251    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13252    then we check if we've already seen DWO_NAME, and only THEN do we check
13253    for a DWO file.
13254
13255    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13256    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13257
13258 static struct dwo_unit *
13259 lookup_dwo_cutu (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
13260                  ULONGEST signature, int is_debug_types)
13261 {
13262   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13263   struct objfile *objfile = per_objfile->objfile;
13264   const char *kind = is_debug_types ? "TU" : "CU";
13265   void **dwo_file_slot;
13266   struct dwo_file *dwo_file;
13267   struct dwp_file *dwp_file;
13268
13269   /* First see if there's a DWP file.
13270      If we have a DWP file but didn't find the DWO inside it, don't
13271      look for the original DWO file.  It makes gdb behave differently
13272      depending on whether one is debugging in the build tree.  */
13273
13274   dwp_file = get_dwp_file (per_objfile);
13275   if (dwp_file != NULL)
13276     {
13277       const struct dwp_hash_table *dwp_htab =
13278         is_debug_types ? dwp_file->tus : dwp_file->cus;
13279
13280       if (dwp_htab != NULL)
13281         {
13282           struct dwo_unit *dwo_cutu =
13283             lookup_dwo_unit_in_dwp (per_objfile, dwp_file, comp_dir, signature,
13284                                     is_debug_types);
13285
13286           if (dwo_cutu != NULL)
13287             {
13288               dwarf_read_debug_printf ("Virtual DWO %s %s found: @%s",
13289                                        kind, hex_string (signature),
13290                                        host_address_to_string (dwo_cutu));
13291
13292               return dwo_cutu;
13293             }
13294         }
13295     }
13296   else
13297     {
13298       /* No DWP file, look for the DWO file.  */
13299
13300       dwo_file_slot = lookup_dwo_file_slot (per_objfile, dwo_name, comp_dir);
13301       if (*dwo_file_slot == NULL)
13302         {
13303           /* Read in the file and build a table of the CUs/TUs it contains.  */
13304           *dwo_file_slot = open_and_init_dwo_file (cu, dwo_name, comp_dir);
13305         }
13306       /* NOTE: This will be NULL if unable to open the file.  */
13307       dwo_file = (struct dwo_file *) *dwo_file_slot;
13308
13309       if (dwo_file != NULL)
13310         {
13311           struct dwo_unit *dwo_cutu = NULL;
13312
13313           if (is_debug_types && dwo_file->tus)
13314             {
13315               struct dwo_unit find_dwo_cutu;
13316
13317               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13318               find_dwo_cutu.signature = signature;
13319               dwo_cutu
13320                 = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
13321                                                  &find_dwo_cutu);
13322             }
13323           else if (!is_debug_types && dwo_file->cus)
13324             {
13325               struct dwo_unit find_dwo_cutu;
13326
13327               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13328               find_dwo_cutu.signature = signature;
13329               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus.get (),
13330                                                        &find_dwo_cutu);
13331             }
13332
13333           if (dwo_cutu != NULL)
13334             {
13335               dwarf_read_debug_printf ("DWO %s %s(%s) found: @%s",
13336                                        kind, dwo_name, hex_string (signature),
13337                                        host_address_to_string (dwo_cutu));
13338
13339               return dwo_cutu;
13340             }
13341         }
13342     }
13343
13344   /* We didn't find it.  This could mean a dwo_id mismatch, or
13345      someone deleted the DWO/DWP file, or the search path isn't set up
13346      correctly to find the file.  */
13347
13348   dwarf_read_debug_printf ("DWO %s %s(%s) not found",
13349                            kind, dwo_name, hex_string (signature));
13350
13351   /* This is a warning and not a complaint because it can be caused by
13352      pilot error (e.g., user accidentally deleting the DWO).  */
13353   {
13354     /* Print the name of the DWP file if we looked there, helps the user
13355        better diagnose the problem.  */
13356     std::string dwp_text;
13357
13358     if (dwp_file != NULL)
13359       dwp_text = string_printf (" [in DWP file %s]",
13360                                 lbasename (dwp_file->name));
13361
13362     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13363                " [in module %s]"),
13364              kind, dwo_name, hex_string (signature), dwp_text.c_str (), kind,
13365              sect_offset_str (cu->per_cu->sect_off), objfile_name (objfile));
13366   }
13367   return NULL;
13368 }
13369
13370 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13371    See lookup_dwo_cutu_unit for details.  */
13372
13373 static struct dwo_unit *
13374 lookup_dwo_comp_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
13375                       ULONGEST signature)
13376 {
13377   gdb_assert (!cu->per_cu->is_debug_types);
13378
13379   return lookup_dwo_cutu (cu, dwo_name, comp_dir, signature, 0);
13380 }
13381
13382 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13383    See lookup_dwo_cutu_unit for details.  */
13384
13385 static struct dwo_unit *
13386 lookup_dwo_type_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir)
13387 {
13388   gdb_assert (cu->per_cu->is_debug_types);
13389
13390   signatured_type *sig_type = (signatured_type *) cu->per_cu;
13391
13392   return lookup_dwo_cutu (cu, dwo_name, comp_dir, sig_type->signature, 1);
13393 }
13394
13395 /* Traversal function for queue_and_load_all_dwo_tus.  */
13396
13397 static int
13398 queue_and_load_dwo_tu (void **slot, void *info)
13399 {
13400   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13401   dwarf2_cu *cu = (dwarf2_cu *) info;
13402   ULONGEST signature = dwo_unit->signature;
13403   signatured_type *sig_type = lookup_dwo_signatured_type (cu, signature);
13404
13405   if (sig_type != NULL)
13406     {
13407       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13408
13409       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13410          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13411          while processing PER_CU.  */
13412       if (maybe_queue_comp_unit (NULL, sig_cu, cu->per_objfile, cu->language))
13413         load_full_type_unit (sig_cu, cu->per_objfile);
13414       cu->per_cu->imported_symtabs_push (sig_cu);
13415     }
13416
13417   return 1;
13418 }
13419
13420 /* Queue all TUs contained in the DWO of CU to be read in.
13421    The DWO may have the only definition of the type, though it may not be
13422    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13423    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13424
13425 static void
13426 queue_and_load_all_dwo_tus (dwarf2_cu *cu)
13427 {
13428   struct dwo_unit *dwo_unit;
13429   struct dwo_file *dwo_file;
13430
13431   gdb_assert (cu != nullptr);
13432   gdb_assert (!cu->per_cu->is_debug_types);
13433   gdb_assert (get_dwp_file (cu->per_objfile) == nullptr);
13434
13435   dwo_unit = cu->dwo_unit;
13436   gdb_assert (dwo_unit != NULL);
13437
13438   dwo_file = dwo_unit->dwo_file;
13439   if (dwo_file->tus != NULL)
13440     htab_traverse_noresize (dwo_file->tus.get (), queue_and_load_dwo_tu, cu);
13441 }
13442
13443 /* Read in various DIEs.  */
13444
13445 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13446    Inherit only the children of the DW_AT_abstract_origin DIE not being
13447    already referenced by DW_AT_abstract_origin from the children of the
13448    current DIE.  */
13449
13450 static void
13451 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13452 {
13453   struct die_info *child_die;
13454   sect_offset *offsetp;
13455   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13456   struct die_info *origin_die;
13457   /* Iterator of the ORIGIN_DIE children.  */
13458   struct die_info *origin_child_die;
13459   struct attribute *attr;
13460   struct dwarf2_cu *origin_cu;
13461   struct pending **origin_previous_list_in_scope;
13462
13463   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13464   if (!attr)
13465     return;
13466
13467   /* Note that following die references may follow to a die in a
13468      different cu.  */
13469
13470   origin_cu = cu;
13471   origin_die = follow_die_ref (die, attr, &origin_cu);
13472
13473   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13474      symbols in.  */
13475   origin_previous_list_in_scope = origin_cu->list_in_scope;
13476   origin_cu->list_in_scope = cu->list_in_scope;
13477
13478   if (die->tag != origin_die->tag
13479       && !(die->tag == DW_TAG_inlined_subroutine
13480            && origin_die->tag == DW_TAG_subprogram))
13481     complaint (_("DIE %s and its abstract origin %s have different tags"),
13482                sect_offset_str (die->sect_off),
13483                sect_offset_str (origin_die->sect_off));
13484
13485   std::vector<sect_offset> offsets;
13486
13487   for (child_die = die->child;
13488        child_die && child_die->tag;
13489        child_die = child_die->sibling)
13490     {
13491       struct die_info *child_origin_die;
13492       struct dwarf2_cu *child_origin_cu;
13493
13494       /* We are trying to process concrete instance entries:
13495          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13496          it's not relevant to our analysis here. i.e. detecting DIEs that are
13497          present in the abstract instance but not referenced in the concrete
13498          one.  */
13499       if (child_die->tag == DW_TAG_call_site
13500           || child_die->tag == DW_TAG_GNU_call_site)
13501         continue;
13502
13503       /* For each CHILD_DIE, find the corresponding child of
13504          ORIGIN_DIE.  If there is more than one layer of
13505          DW_AT_abstract_origin, follow them all; there shouldn't be,
13506          but GCC versions at least through 4.4 generate this (GCC PR
13507          40573).  */
13508       child_origin_die = child_die;
13509       child_origin_cu = cu;
13510       while (1)
13511         {
13512           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13513                               child_origin_cu);
13514           if (attr == NULL)
13515             break;
13516           child_origin_die = follow_die_ref (child_origin_die, attr,
13517                                              &child_origin_cu);
13518         }
13519
13520       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13521          counterpart may exist.  */
13522       if (child_origin_die != child_die)
13523         {
13524           if (child_die->tag != child_origin_die->tag
13525               && !(child_die->tag == DW_TAG_inlined_subroutine
13526                    && child_origin_die->tag == DW_TAG_subprogram))
13527             complaint (_("Child DIE %s and its abstract origin %s have "
13528                          "different tags"),
13529                        sect_offset_str (child_die->sect_off),
13530                        sect_offset_str (child_origin_die->sect_off));
13531           if (child_origin_die->parent != origin_die)
13532             complaint (_("Child DIE %s and its abstract origin %s have "
13533                          "different parents"),
13534                        sect_offset_str (child_die->sect_off),
13535                        sect_offset_str (child_origin_die->sect_off));
13536           else
13537             offsets.push_back (child_origin_die->sect_off);
13538         }
13539     }
13540   std::sort (offsets.begin (), offsets.end ());
13541   sect_offset *offsets_end = offsets.data () + offsets.size ();
13542   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13543     if (offsetp[-1] == *offsetp)
13544       complaint (_("Multiple children of DIE %s refer "
13545                    "to DIE %s as their abstract origin"),
13546                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13547
13548   offsetp = offsets.data ();
13549   origin_child_die = origin_die->child;
13550   while (origin_child_die && origin_child_die->tag)
13551     {
13552       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13553       while (offsetp < offsets_end
13554              && *offsetp < origin_child_die->sect_off)
13555         offsetp++;
13556       if (offsetp >= offsets_end
13557           || *offsetp > origin_child_die->sect_off)
13558         {
13559           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13560              Check whether we're already processing ORIGIN_CHILD_DIE.
13561              This can happen with mutually referenced abstract_origins.
13562              PR 16581.  */
13563           if (!origin_child_die->in_process)
13564             process_die (origin_child_die, origin_cu);
13565         }
13566       origin_child_die = origin_child_die->sibling;
13567     }
13568   origin_cu->list_in_scope = origin_previous_list_in_scope;
13569
13570   if (cu != origin_cu)
13571     compute_delayed_physnames (origin_cu);
13572 }
13573
13574 static void
13575 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13576 {
13577   struct objfile *objfile = cu->per_objfile->objfile;
13578   struct gdbarch *gdbarch = objfile->arch ();
13579   struct context_stack *newobj;
13580   CORE_ADDR lowpc;
13581   CORE_ADDR highpc;
13582   struct die_info *child_die;
13583   struct attribute *attr, *call_line, *call_file;
13584   const char *name;
13585   CORE_ADDR baseaddr;
13586   struct block *block;
13587   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13588   std::vector<struct symbol *> template_args;
13589   struct template_symbol *templ_func = NULL;
13590
13591   if (inlined_func)
13592     {
13593       /* If we do not have call site information, we can't show the
13594          caller of this inlined function.  That's too confusing, so
13595          only use the scope for local variables.  */
13596       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13597       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13598       if (call_line == NULL || call_file == NULL)
13599         {
13600           read_lexical_block_scope (die, cu);
13601           return;
13602         }
13603     }
13604
13605   baseaddr = objfile->text_section_offset ();
13606
13607   name = dwarf2_name (die, cu);
13608
13609   /* Ignore functions with missing or empty names.  These are actually
13610      illegal according to the DWARF standard.  */
13611   if (name == NULL)
13612     {
13613       complaint (_("missing name for subprogram DIE at %s"),
13614                  sect_offset_str (die->sect_off));
13615       return;
13616     }
13617
13618   /* Ignore functions with missing or invalid low and high pc attributes.  */
13619   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13620       <= PC_BOUNDS_INVALID)
13621     {
13622       attr = dwarf2_attr (die, DW_AT_external, cu);
13623       if (attr == nullptr || !attr->as_boolean ())
13624         complaint (_("cannot get low and high bounds "
13625                      "for subprogram DIE at %s"),
13626                    sect_offset_str (die->sect_off));
13627       return;
13628     }
13629
13630   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13631   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13632
13633   /* If we have any template arguments, then we must allocate a
13634      different sort of symbol.  */
13635   for (child_die = die->child; child_die; child_die = child_die->sibling)
13636     {
13637       if (child_die->tag == DW_TAG_template_type_param
13638           || child_die->tag == DW_TAG_template_value_param)
13639         {
13640           templ_func = new (&objfile->objfile_obstack) template_symbol;
13641           templ_func->subclass = SYMBOL_TEMPLATE;
13642           break;
13643         }
13644     }
13645
13646   gdb_assert (cu->get_builder () != nullptr);
13647   newobj = cu->get_builder ()->push_context (0, lowpc);
13648   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13649                              (struct symbol *) templ_func);
13650
13651   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
13652     set_objfile_main_name (objfile, newobj->name->linkage_name (),
13653                            cu->language);
13654
13655   /* If there is a location expression for DW_AT_frame_base, record
13656      it.  */
13657   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13658   if (attr != nullptr)
13659     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13660
13661   /* If there is a location for the static link, record it.  */
13662   newobj->static_link = NULL;
13663   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13664   if (attr != nullptr)
13665     {
13666       newobj->static_link
13667         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13668       attr_to_dynamic_prop (attr, die, cu, newobj->static_link,
13669                             cu->addr_type ());
13670     }
13671
13672   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13673
13674   if (die->child != NULL)
13675     {
13676       child_die = die->child;
13677       while (child_die && child_die->tag)
13678         {
13679           if (child_die->tag == DW_TAG_template_type_param
13680               || child_die->tag == DW_TAG_template_value_param)
13681             {
13682               struct symbol *arg = new_symbol (child_die, NULL, cu);
13683
13684               if (arg != NULL)
13685                 template_args.push_back (arg);
13686             }
13687           else
13688             process_die (child_die, cu);
13689           child_die = child_die->sibling;
13690         }
13691     }
13692
13693   inherit_abstract_dies (die, cu);
13694
13695   /* If we have a DW_AT_specification, we might need to import using
13696      directives from the context of the specification DIE.  See the
13697      comment in determine_prefix.  */
13698   if (cu->language == language_cplus
13699       && dwarf2_attr (die, DW_AT_specification, cu))
13700     {
13701       struct dwarf2_cu *spec_cu = cu;
13702       struct die_info *spec_die = die_specification (die, &spec_cu);
13703
13704       while (spec_die)
13705         {
13706           child_die = spec_die->child;
13707           while (child_die && child_die->tag)
13708             {
13709               if (child_die->tag == DW_TAG_imported_module)
13710                 process_die (child_die, spec_cu);
13711               child_die = child_die->sibling;
13712             }
13713
13714           /* In some cases, GCC generates specification DIEs that
13715              themselves contain DW_AT_specification attributes.  */
13716           spec_die = die_specification (spec_die, &spec_cu);
13717         }
13718     }
13719
13720   struct context_stack cstk = cu->get_builder ()->pop_context ();
13721   /* Make a block for the local symbols within.  */
13722   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13723                                      cstk.static_link, lowpc, highpc);
13724
13725   /* For C++, set the block's scope.  */
13726   if ((cu->language == language_cplus
13727        || cu->language == language_fortran
13728        || cu->language == language_d
13729        || cu->language == language_rust)
13730       && cu->processing_has_namespace_info)
13731     block_set_scope (block, determine_prefix (die, cu),
13732                      &objfile->objfile_obstack);
13733
13734   /* If we have address ranges, record them.  */
13735   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13736
13737   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13738
13739   /* Attach template arguments to function.  */
13740   if (!template_args.empty ())
13741     {
13742       gdb_assert (templ_func != NULL);
13743
13744       templ_func->n_template_arguments = template_args.size ();
13745       templ_func->template_arguments
13746         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13747                      templ_func->n_template_arguments);
13748       memcpy (templ_func->template_arguments,
13749               template_args.data (),
13750               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13751
13752       /* Make sure that the symtab is set on the new symbols.  Even
13753          though they don't appear in this symtab directly, other parts
13754          of gdb assume that symbols do, and this is reasonably
13755          true.  */
13756       for (symbol *sym : template_args)
13757         symbol_set_symtab (sym, symbol_symtab (templ_func));
13758     }
13759
13760   /* In C++, we can have functions nested inside functions (e.g., when
13761      a function declares a class that has methods).  This means that
13762      when we finish processing a function scope, we may need to go
13763      back to building a containing block's symbol lists.  */
13764   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13765   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13766
13767   /* If we've finished processing a top-level function, subsequent
13768      symbols go in the file symbol list.  */
13769   if (cu->get_builder ()->outermost_context_p ())
13770     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13771 }
13772
13773 /* Process all the DIES contained within a lexical block scope.  Start
13774    a new scope, process the dies, and then close the scope.  */
13775
13776 static void
13777 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13778 {
13779   struct objfile *objfile = cu->per_objfile->objfile;
13780   struct gdbarch *gdbarch = objfile->arch ();
13781   CORE_ADDR lowpc, highpc;
13782   struct die_info *child_die;
13783   CORE_ADDR baseaddr;
13784
13785   baseaddr = objfile->text_section_offset ();
13786
13787   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13788   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13789      as multiple lexical blocks?  Handling children in a sane way would
13790      be nasty.  Might be easier to properly extend generic blocks to
13791      describe ranges.  */
13792   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13793     {
13794     case PC_BOUNDS_NOT_PRESENT:
13795       /* DW_TAG_lexical_block has no attributes, process its children as if
13796          there was no wrapping by that DW_TAG_lexical_block.
13797          GCC does no longer produces such DWARF since GCC r224161.  */
13798       for (child_die = die->child;
13799            child_die != NULL && child_die->tag;
13800            child_die = child_die->sibling)
13801         {
13802           /* We might already be processing this DIE.  This can happen
13803              in an unusual circumstance -- where a subroutine A
13804              appears lexically in another subroutine B, but A actually
13805              inlines B.  The recursion is broken here, rather than in
13806              inherit_abstract_dies, because it seems better to simply
13807              drop concrete children here.  */
13808           if (!child_die->in_process)
13809             process_die (child_die, cu);
13810         }
13811       return;
13812     case PC_BOUNDS_INVALID:
13813       return;
13814     }
13815   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13816   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13817
13818   cu->get_builder ()->push_context (0, lowpc);
13819   if (die->child != NULL)
13820     {
13821       child_die = die->child;
13822       while (child_die && child_die->tag)
13823         {
13824           process_die (child_die, cu);
13825           child_die = child_die->sibling;
13826         }
13827     }
13828   inherit_abstract_dies (die, cu);
13829   struct context_stack cstk = cu->get_builder ()->pop_context ();
13830
13831   if (*cu->get_builder ()->get_local_symbols () != NULL
13832       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13833     {
13834       struct block *block
13835         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13836                                      cstk.start_addr, highpc);
13837
13838       /* Note that recording ranges after traversing children, as we
13839          do here, means that recording a parent's ranges entails
13840          walking across all its children's ranges as they appear in
13841          the address map, which is quadratic behavior.
13842
13843          It would be nicer to record the parent's ranges before
13844          traversing its children, simply overriding whatever you find
13845          there.  But since we don't even decide whether to create a
13846          block until after we've traversed its children, that's hard
13847          to do.  */
13848       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13849     }
13850   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13851   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13852 }
13853
13854 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13855
13856 static void
13857 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13858 {
13859   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13860   struct objfile *objfile = per_objfile->objfile;
13861   struct gdbarch *gdbarch = objfile->arch ();
13862   CORE_ADDR pc, baseaddr;
13863   struct attribute *attr;
13864   struct call_site *call_site, call_site_local;
13865   void **slot;
13866   int nparams;
13867   struct die_info *child_die;
13868
13869   baseaddr = objfile->text_section_offset ();
13870
13871   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13872   if (attr == NULL)
13873     {
13874       /* This was a pre-DWARF-5 GNU extension alias
13875          for DW_AT_call_return_pc.  */
13876       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13877     }
13878   if (!attr)
13879     {
13880       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13881                    "DIE %s [in module %s]"),
13882                  sect_offset_str (die->sect_off), objfile_name (objfile));
13883       return;
13884     }
13885   pc = attr->as_address () + baseaddr;
13886   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13887
13888   if (cu->call_site_htab == NULL)
13889     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13890                                                NULL, &objfile->objfile_obstack,
13891                                                hashtab_obstack_allocate, NULL);
13892   call_site_local.pc = pc;
13893   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13894   if (*slot != NULL)
13895     {
13896       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13897                    "DIE %s [in module %s]"),
13898                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13899                  objfile_name (objfile));
13900       return;
13901     }
13902
13903   /* Count parameters at the caller.  */
13904
13905   nparams = 0;
13906   for (child_die = die->child; child_die && child_die->tag;
13907        child_die = child_die->sibling)
13908     {
13909       if (child_die->tag != DW_TAG_call_site_parameter
13910           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13911         {
13912           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13913                        "DW_TAG_call_site child DIE %s [in module %s]"),
13914                      child_die->tag, sect_offset_str (child_die->sect_off),
13915                      objfile_name (objfile));
13916           continue;
13917         }
13918
13919       nparams++;
13920     }
13921
13922   call_site
13923     = ((struct call_site *)
13924        obstack_alloc (&objfile->objfile_obstack,
13925                       sizeof (*call_site)
13926                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13927   *slot = call_site;
13928   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13929   call_site->pc = pc;
13930
13931   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13932       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13933     {
13934       struct die_info *func_die;
13935
13936       /* Skip also over DW_TAG_inlined_subroutine.  */
13937       for (func_die = die->parent;
13938            func_die && func_die->tag != DW_TAG_subprogram
13939            && func_die->tag != DW_TAG_subroutine_type;
13940            func_die = func_die->parent);
13941
13942       /* DW_AT_call_all_calls is a superset
13943          of DW_AT_call_all_tail_calls.  */
13944       if (func_die
13945           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13946           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13947           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13948           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13949         {
13950           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13951              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13952              both the initial caller containing the real return address PC and
13953              the final callee containing the current PC of a chain of tail
13954              calls do not need to have the tail call list complete.  But any
13955              function candidate for a virtual tail call frame searched via
13956              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13957              determined unambiguously.  */
13958         }
13959       else
13960         {
13961           struct type *func_type = NULL;
13962
13963           if (func_die)
13964             func_type = get_die_type (func_die, cu);
13965           if (func_type != NULL)
13966             {
13967               gdb_assert (func_type->code () == TYPE_CODE_FUNC);
13968
13969               /* Enlist this call site to the function.  */
13970               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13971               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13972             }
13973           else
13974             complaint (_("Cannot find function owning DW_TAG_call_site "
13975                          "DIE %s [in module %s]"),
13976                        sect_offset_str (die->sect_off), objfile_name (objfile));
13977         }
13978     }
13979
13980   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13981   if (attr == NULL)
13982     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13983   if (attr == NULL)
13984     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13985   if (attr == NULL)
13986     {
13987       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13988       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13989     }
13990   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13991   if (!attr || (attr->form_is_block () && attr->as_block ()->size == 0))
13992     /* Keep NULL DWARF_BLOCK.  */;
13993   else if (attr->form_is_block ())
13994     {
13995       struct dwarf2_locexpr_baton *dlbaton;
13996       struct dwarf_block *block = attr->as_block ();
13997
13998       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13999       dlbaton->data = block->data;
14000       dlbaton->size = block->size;
14001       dlbaton->per_objfile = per_objfile;
14002       dlbaton->per_cu = cu->per_cu;
14003
14004       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14005     }
14006   else if (attr->form_is_ref ())
14007     {
14008       struct dwarf2_cu *target_cu = cu;
14009       struct die_info *target_die;
14010
14011       target_die = follow_die_ref (die, attr, &target_cu);
14012       gdb_assert (target_cu->per_objfile->objfile == objfile);
14013       if (die_is_declaration (target_die, target_cu))
14014         {
14015           const char *target_physname;
14016
14017           /* Prefer the mangled name; otherwise compute the demangled one.  */
14018           target_physname = dw2_linkage_name (target_die, target_cu);
14019           if (target_physname == NULL)
14020             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14021           if (target_physname == NULL)
14022             complaint (_("DW_AT_call_target target DIE has invalid "
14023                          "physname, for referencing DIE %s [in module %s]"),
14024                        sect_offset_str (die->sect_off), objfile_name (objfile));
14025           else
14026             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14027         }
14028       else
14029         {
14030           CORE_ADDR lowpc;
14031
14032           /* DW_AT_entry_pc should be preferred.  */
14033           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14034               <= PC_BOUNDS_INVALID)
14035             complaint (_("DW_AT_call_target target DIE has invalid "
14036                          "low pc, for referencing DIE %s [in module %s]"),
14037                        sect_offset_str (die->sect_off), objfile_name (objfile));
14038           else
14039             {
14040               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14041               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14042             }
14043         }
14044     }
14045   else
14046     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14047                  "block nor reference, for DIE %s [in module %s]"),
14048                sect_offset_str (die->sect_off), objfile_name (objfile));
14049
14050   call_site->per_cu = cu->per_cu;
14051   call_site->per_objfile = per_objfile;
14052
14053   for (child_die = die->child;
14054        child_die && child_die->tag;
14055        child_die = child_die->sibling)
14056     {
14057       struct call_site_parameter *parameter;
14058       struct attribute *loc, *origin;
14059
14060       if (child_die->tag != DW_TAG_call_site_parameter
14061           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14062         {
14063           /* Already printed the complaint above.  */
14064           continue;
14065         }
14066
14067       gdb_assert (call_site->parameter_count < nparams);
14068       parameter = &call_site->parameter[call_site->parameter_count];
14069
14070       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14071          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14072          register is contained in DW_AT_call_value.  */
14073
14074       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14075       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14076       if (origin == NULL)
14077         {
14078           /* This was a pre-DWARF-5 GNU extension alias
14079              for DW_AT_call_parameter.  */
14080           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14081         }
14082       if (loc == NULL && origin != NULL && origin->form_is_ref ())
14083         {
14084           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14085
14086           sect_offset sect_off = origin->get_ref_die_offset ();
14087           if (!cu->header.offset_in_cu_p (sect_off))
14088             {
14089               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14090                  binding can be done only inside one CU.  Such referenced DIE
14091                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14092               complaint (_("DW_AT_call_parameter offset is not in CU for "
14093                            "DW_TAG_call_site child DIE %s [in module %s]"),
14094                          sect_offset_str (child_die->sect_off),
14095                          objfile_name (objfile));
14096               continue;
14097             }
14098           parameter->u.param_cu_off
14099             = (cu_offset) (sect_off - cu->header.sect_off);
14100         }
14101       else if (loc == NULL || origin != NULL || !loc->form_is_block ())
14102         {
14103           complaint (_("No DW_FORM_block* DW_AT_location for "
14104                        "DW_TAG_call_site child DIE %s [in module %s]"),
14105                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14106           continue;
14107         }
14108       else
14109         {
14110           struct dwarf_block *block = loc->as_block ();
14111
14112           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14113             (block->data, &block->data[block->size]);
14114           if (parameter->u.dwarf_reg != -1)
14115             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14116           else if (dwarf_block_to_sp_offset (gdbarch, block->data,
14117                                     &block->data[block->size],
14118                                              &parameter->u.fb_offset))
14119             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14120           else
14121             {
14122               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14123                            "for DW_FORM_block* DW_AT_location is supported for "
14124                            "DW_TAG_call_site child DIE %s "
14125                            "[in module %s]"),
14126                          sect_offset_str (child_die->sect_off),
14127                          objfile_name (objfile));
14128               continue;
14129             }
14130         }
14131
14132       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14133       if (attr == NULL)
14134         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14135       if (attr == NULL || !attr->form_is_block ())
14136         {
14137           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14138                        "DW_TAG_call_site child DIE %s [in module %s]"),
14139                      sect_offset_str (child_die->sect_off),
14140                      objfile_name (objfile));
14141           continue;
14142         }
14143
14144       struct dwarf_block *block = attr->as_block ();
14145       parameter->value = block->data;
14146       parameter->value_size = block->size;
14147
14148       /* Parameters are not pre-cleared by memset above.  */
14149       parameter->data_value = NULL;
14150       parameter->data_value_size = 0;
14151       call_site->parameter_count++;
14152
14153       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14154       if (attr == NULL)
14155         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14156       if (attr != nullptr)
14157         {
14158           if (!attr->form_is_block ())
14159             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14160                          "DW_TAG_call_site child DIE %s [in module %s]"),
14161                        sect_offset_str (child_die->sect_off),
14162                        objfile_name (objfile));
14163           else
14164             {
14165               block = attr->as_block ();
14166               parameter->data_value = block->data;
14167               parameter->data_value_size = block->size;
14168             }
14169         }
14170     }
14171 }
14172
14173 /* Helper function for read_variable.  If DIE represents a virtual
14174    table, then return the type of the concrete object that is
14175    associated with the virtual table.  Otherwise, return NULL.  */
14176
14177 static struct type *
14178 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14179 {
14180   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14181   if (attr == NULL)
14182     return NULL;
14183
14184   /* Find the type DIE.  */
14185   struct die_info *type_die = NULL;
14186   struct dwarf2_cu *type_cu = cu;
14187
14188   if (attr->form_is_ref ())
14189     type_die = follow_die_ref (die, attr, &type_cu);
14190   if (type_die == NULL)
14191     return NULL;
14192
14193   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14194     return NULL;
14195   return die_containing_type (type_die, type_cu);
14196 }
14197
14198 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14199
14200 static void
14201 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14202 {
14203   struct rust_vtable_symbol *storage = NULL;
14204
14205   if (cu->language == language_rust)
14206     {
14207       struct type *containing_type = rust_containing_type (die, cu);
14208
14209       if (containing_type != NULL)
14210         {
14211           struct objfile *objfile = cu->per_objfile->objfile;
14212
14213           storage = new (&objfile->objfile_obstack) rust_vtable_symbol;
14214           storage->concrete_type = containing_type;
14215           storage->subclass = SYMBOL_RUST_VTABLE;
14216         }
14217     }
14218
14219   struct symbol *res = new_symbol (die, NULL, cu, storage);
14220   struct attribute *abstract_origin
14221     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14222   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
14223   if (res == NULL && loc && abstract_origin)
14224     {
14225       /* We have a variable without a name, but with a location and an abstract
14226          origin.  This may be a concrete instance of an abstract variable
14227          referenced from an DW_OP_GNU_variable_value, so save it to find it back
14228          later.  */
14229       struct dwarf2_cu *origin_cu = cu;
14230       struct die_info *origin_die
14231         = follow_die_ref (die, abstract_origin, &origin_cu);
14232       dwarf2_per_objfile *per_objfile = cu->per_objfile;
14233       per_objfile->per_bfd->abstract_to_concrete
14234         [origin_die->sect_off].push_back (die->sect_off);
14235     }
14236 }
14237
14238 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14239    reading .debug_rnglists.
14240    Callback's type should be:
14241     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14242    Return true if the attributes are present and valid, otherwise,
14243    return false.  */
14244
14245 template <typename Callback>
14246 static bool
14247 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14248                          dwarf_tag tag, Callback &&callback)
14249 {
14250   dwarf2_per_objfile *per_objfile = cu->per_objfile;
14251   struct objfile *objfile = per_objfile->objfile;
14252   bfd *obfd = objfile->obfd;
14253   /* Base address selection entry.  */
14254   gdb::optional<CORE_ADDR> base;
14255   const gdb_byte *buffer;
14256   CORE_ADDR baseaddr;
14257   bool overflow = false;
14258   ULONGEST addr_index;
14259   struct dwarf2_section_info *rnglists_section;
14260
14261   base = cu->base_address;
14262   rnglists_section = cu_debug_rnglists_section (cu, tag);
14263   rnglists_section->read (objfile);
14264
14265   if (offset >= rnglists_section->size)
14266     {
14267       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14268                  offset);
14269       return false;
14270     }
14271   buffer = rnglists_section->buffer + offset;
14272
14273   baseaddr = objfile->text_section_offset ();
14274
14275   while (1)
14276     {
14277       /* Initialize it due to a false compiler warning.  */
14278       CORE_ADDR range_beginning = 0, range_end = 0;
14279       const gdb_byte *buf_end = (rnglists_section->buffer
14280                                  + rnglists_section->size);
14281       unsigned int bytes_read;
14282
14283       if (buffer == buf_end)
14284         {
14285           overflow = true;
14286           break;
14287         }
14288       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14289       switch (rlet)
14290         {
14291         case DW_RLE_end_of_list:
14292           break;
14293         case DW_RLE_base_address:
14294           if (buffer + cu->header.addr_size > buf_end)
14295             {
14296               overflow = true;
14297               break;
14298             }
14299           base = cu->header.read_address (obfd, buffer, &bytes_read);
14300           buffer += bytes_read;
14301           break;
14302         case DW_RLE_base_addressx:
14303           addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14304           buffer += bytes_read;
14305           base = read_addr_index (cu, addr_index);
14306           break;
14307         case DW_RLE_start_length:
14308           if (buffer + cu->header.addr_size > buf_end)
14309             {
14310               overflow = true;
14311               break;
14312             }
14313           range_beginning = cu->header.read_address (obfd, buffer,
14314                                                      &bytes_read);
14315           buffer += bytes_read;
14316           range_end = (range_beginning
14317                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14318           buffer += bytes_read;
14319           if (buffer > buf_end)
14320             {
14321               overflow = true;
14322               break;
14323             }
14324           break;
14325         case DW_RLE_startx_length:
14326           addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14327           buffer += bytes_read;
14328           range_beginning = read_addr_index (cu, addr_index);
14329           if (buffer > buf_end)
14330             {
14331               overflow = true;
14332               break;
14333             }
14334           range_end = (range_beginning
14335                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14336           buffer += bytes_read;
14337           break;
14338         case DW_RLE_offset_pair:
14339           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14340           buffer += bytes_read;
14341           if (buffer > buf_end)
14342             {
14343               overflow = true;
14344               break;
14345             }
14346           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14347           buffer += bytes_read;
14348           if (buffer > buf_end)
14349             {
14350               overflow = true;
14351               break;
14352             }
14353           break;
14354         case DW_RLE_start_end:
14355           if (buffer + 2 * cu->header.addr_size > buf_end)
14356             {
14357               overflow = true;
14358               break;
14359             }
14360           range_beginning = cu->header.read_address (obfd, buffer,
14361                                                      &bytes_read);
14362           buffer += bytes_read;
14363           range_end = cu->header.read_address (obfd, buffer, &bytes_read);
14364           buffer += bytes_read;
14365           break;
14366         case DW_RLE_startx_endx:
14367           addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14368           buffer += bytes_read;
14369           range_beginning = read_addr_index (cu, addr_index);
14370           if (buffer > buf_end)
14371             {
14372               overflow = true;
14373               break;
14374             }
14375           addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14376           buffer += bytes_read;
14377           range_end = read_addr_index (cu, addr_index);
14378           break;
14379         default:
14380           complaint (_("Invalid .debug_rnglists data (no base address)"));
14381           return false;
14382         }
14383       if (rlet == DW_RLE_end_of_list || overflow)
14384         break;
14385       if (rlet == DW_RLE_base_address)
14386         continue;
14387
14388       if (range_beginning > range_end)
14389         {
14390           /* Inverted range entries are invalid.  */
14391           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14392           return false;
14393         }
14394
14395       /* Empty range entries have no effect.  */
14396       if (range_beginning == range_end)
14397         continue;
14398
14399       /* Only DW_RLE_offset_pair needs the base address added.  */
14400       if (rlet == DW_RLE_offset_pair)
14401         {
14402           if (!base.has_value ())
14403             {
14404               /* We have no valid base address for the DW_RLE_offset_pair.  */
14405               complaint (_("Invalid .debug_rnglists data (no base address for "
14406                            "DW_RLE_offset_pair)"));
14407               return false;
14408             }
14409
14410           range_beginning += *base;
14411           range_end += *base;
14412         }
14413
14414       /* A not-uncommon case of bad debug info.
14415          Don't pollute the addrmap with bad data.  */
14416       if (range_beginning + baseaddr == 0
14417           && !per_objfile->per_bfd->has_section_at_zero)
14418         {
14419           complaint (_(".debug_rnglists entry has start address of zero"
14420                        " [in module %s]"), objfile_name (objfile));
14421           continue;
14422         }
14423
14424       callback (range_beginning, range_end);
14425     }
14426
14427   if (overflow)
14428     {
14429       complaint (_("Offset %d is not terminated "
14430                    "for DW_AT_ranges attribute"),
14431                  offset);
14432       return false;
14433     }
14434
14435   return true;
14436 }
14437
14438 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14439    Callback's type should be:
14440     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14441    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14442
14443 template <typename Callback>
14444 static int
14445 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu, dwarf_tag tag,
14446                        Callback &&callback)
14447 {
14448   dwarf2_per_objfile *per_objfile = cu->per_objfile;
14449   struct objfile *objfile = per_objfile->objfile;
14450   struct comp_unit_head *cu_header = &cu->header;
14451   bfd *obfd = objfile->obfd;
14452   unsigned int addr_size = cu_header->addr_size;
14453   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14454   /* Base address selection entry.  */
14455   gdb::optional<CORE_ADDR> base;
14456   unsigned int dummy;
14457   const gdb_byte *buffer;
14458   CORE_ADDR baseaddr;
14459
14460   if (cu_header->version >= 5)
14461     return dwarf2_rnglists_process (offset, cu, tag, callback);
14462
14463   base = cu->base_address;
14464
14465   per_objfile->per_bfd->ranges.read (objfile);
14466   if (offset >= per_objfile->per_bfd->ranges.size)
14467     {
14468       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14469                  offset);
14470       return 0;
14471     }
14472   buffer = per_objfile->per_bfd->ranges.buffer + offset;
14473
14474   baseaddr = objfile->text_section_offset ();
14475
14476   while (1)
14477     {
14478       CORE_ADDR range_beginning, range_end;
14479
14480       range_beginning = cu->header.read_address (obfd, buffer, &dummy);
14481       buffer += addr_size;
14482       range_end = cu->header.read_address (obfd, buffer, &dummy);
14483       buffer += addr_size;
14484       offset += 2 * addr_size;
14485
14486       /* An end of list marker is a pair of zero addresses.  */
14487       if (range_beginning == 0 && range_end == 0)
14488         /* Found the end of list entry.  */
14489         break;
14490
14491       /* Each base address selection entry is a pair of 2 values.
14492          The first is the largest possible address, the second is
14493          the base address.  Check for a base address here.  */
14494       if ((range_beginning & mask) == mask)
14495         {
14496           /* If we found the largest possible address, then we already
14497              have the base address in range_end.  */
14498           base = range_end;
14499           continue;
14500         }
14501
14502       if (!base.has_value ())
14503         {
14504           /* We have no valid base address for the ranges
14505              data.  */
14506           complaint (_("Invalid .debug_ranges data (no base address)"));
14507           return 0;
14508         }
14509
14510       if (range_beginning > range_end)
14511         {
14512           /* Inverted range entries are invalid.  */
14513           complaint (_("Invalid .debug_ranges data (inverted range)"));
14514           return 0;
14515         }
14516
14517       /* Empty range entries have no effect.  */
14518       if (range_beginning == range_end)
14519         continue;
14520
14521       range_beginning += *base;
14522       range_end += *base;
14523
14524       /* A not-uncommon case of bad debug info.
14525          Don't pollute the addrmap with bad data.  */
14526       if (range_beginning + baseaddr == 0
14527           && !per_objfile->per_bfd->has_section_at_zero)
14528         {
14529           complaint (_(".debug_ranges entry has start address of zero"
14530                        " [in module %s]"), objfile_name (objfile));
14531           continue;
14532         }
14533
14534       callback (range_beginning, range_end);
14535     }
14536
14537   return 1;
14538 }
14539
14540 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14541    Return 1 if the attributes are present and valid, otherwise, return 0.
14542    If RANGES_PST is not NULL we should set up the `psymtabs_addrmap'.  */
14543
14544 static int
14545 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14546                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14547                     dwarf2_psymtab *ranges_pst, dwarf_tag tag)
14548 {
14549   struct objfile *objfile = cu->per_objfile->objfile;
14550   dwarf2_per_bfd *per_bfd = cu->per_objfile->per_bfd;
14551   struct gdbarch *gdbarch = objfile->arch ();
14552   const CORE_ADDR baseaddr = objfile->text_section_offset ();
14553   int low_set = 0;
14554   CORE_ADDR low = 0;
14555   CORE_ADDR high = 0;
14556   int retval;
14557
14558   retval = dwarf2_ranges_process (offset, cu, tag,
14559     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14560     {
14561       if (ranges_pst != NULL)
14562         {
14563           CORE_ADDR lowpc;
14564           CORE_ADDR highpc;
14565
14566           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14567                                                range_beginning + baseaddr)
14568                    - baseaddr);
14569           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14570                                                 range_end + baseaddr)
14571                     - baseaddr);
14572           addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
14573                              lowpc, highpc - 1, ranges_pst);
14574         }
14575
14576       /* FIXME: This is recording everything as a low-high
14577          segment of consecutive addresses.  We should have a
14578          data structure for discontiguous block ranges
14579          instead.  */
14580       if (! low_set)
14581         {
14582           low = range_beginning;
14583           high = range_end;
14584           low_set = 1;
14585         }
14586       else
14587         {
14588           if (range_beginning < low)
14589             low = range_beginning;
14590           if (range_end > high)
14591             high = range_end;
14592         }
14593     });
14594   if (!retval)
14595     return 0;
14596
14597   if (! low_set)
14598     /* If the first entry is an end-of-list marker, the range
14599        describes an empty scope, i.e. no instructions.  */
14600     return 0;
14601
14602   if (low_return)
14603     *low_return = low;
14604   if (high_return)
14605     *high_return = high;
14606   return 1;
14607 }
14608
14609 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14610    definition for the return value.  *LOWPC and *HIGHPC are set iff
14611    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14612
14613 static enum pc_bounds_kind
14614 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14615                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14616                       dwarf2_psymtab *pst)
14617 {
14618   dwarf2_per_objfile *per_objfile = cu->per_objfile;
14619   struct attribute *attr;
14620   struct attribute *attr_high;
14621   CORE_ADDR low = 0;
14622   CORE_ADDR high = 0;
14623   enum pc_bounds_kind ret;
14624
14625   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14626   if (attr_high)
14627     {
14628       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14629       if (attr != nullptr)
14630         {
14631           low = attr->as_address ();
14632           high = attr_high->as_address ();
14633           if (cu->header.version >= 4 && attr_high->form_is_constant ())
14634             high += low;
14635         }
14636       else
14637         /* Found high w/o low attribute.  */
14638         return PC_BOUNDS_INVALID;
14639
14640       /* Found consecutive range of addresses.  */
14641       ret = PC_BOUNDS_HIGH_LOW;
14642     }
14643   else
14644     {
14645       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14646       if (attr != nullptr && attr->form_is_unsigned ())
14647         {
14648           /* Offset in the .debug_ranges or .debug_rnglist section (depending
14649              on DWARF version).  */
14650           ULONGEST ranges_offset = attr->as_unsigned ();
14651
14652           /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
14653              this value.  */
14654           if (die->tag != DW_TAG_compile_unit)
14655             ranges_offset += cu->gnu_ranges_base;
14656
14657           /* Value of the DW_AT_ranges attribute is the offset in the
14658              .debug_ranges section.  */
14659           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst,
14660                                    die->tag))
14661             return PC_BOUNDS_INVALID;
14662           /* Found discontinuous range of addresses.  */
14663           ret = PC_BOUNDS_RANGES;
14664         }
14665       else
14666         return PC_BOUNDS_NOT_PRESENT;
14667     }
14668
14669   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14670   if (high <= low)
14671     return PC_BOUNDS_INVALID;
14672
14673   /* When using the GNU linker, .gnu.linkonce. sections are used to
14674      eliminate duplicate copies of functions and vtables and such.
14675      The linker will arbitrarily choose one and discard the others.
14676      The AT_*_pc values for such functions refer to local labels in
14677      these sections.  If the section from that file was discarded, the
14678      labels are not in the output, so the relocs get a value of 0.
14679      If this is a discarded function, mark the pc bounds as invalid,
14680      so that GDB will ignore it.  */
14681   if (low == 0 && !per_objfile->per_bfd->has_section_at_zero)
14682     return PC_BOUNDS_INVALID;
14683
14684   *lowpc = low;
14685   if (highpc)
14686     *highpc = high;
14687   return ret;
14688 }
14689
14690 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14691    its low and high PC addresses.  Do nothing if these addresses could not
14692    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14693    and HIGHPC to the high address if greater than HIGHPC.  */
14694
14695 static void
14696 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14697                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14698                                  struct dwarf2_cu *cu)
14699 {
14700   CORE_ADDR low, high;
14701   struct die_info *child = die->child;
14702
14703   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14704     {
14705       *lowpc = std::min (*lowpc, low);
14706       *highpc = std::max (*highpc, high);
14707     }
14708
14709   /* If the language does not allow nested subprograms (either inside
14710      subprograms or lexical blocks), we're done.  */
14711   if (cu->language != language_ada)
14712     return;
14713
14714   /* Check all the children of the given DIE.  If it contains nested
14715      subprograms, then check their pc bounds.  Likewise, we need to
14716      check lexical blocks as well, as they may also contain subprogram
14717      definitions.  */
14718   while (child && child->tag)
14719     {
14720       if (child->tag == DW_TAG_subprogram
14721           || child->tag == DW_TAG_lexical_block)
14722         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14723       child = child->sibling;
14724     }
14725 }
14726
14727 /* Get the low and high pc's represented by the scope DIE, and store
14728    them in *LOWPC and *HIGHPC.  If the correct values can't be
14729    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14730
14731 static void
14732 get_scope_pc_bounds (struct die_info *die,
14733                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14734                      struct dwarf2_cu *cu)
14735 {
14736   CORE_ADDR best_low = (CORE_ADDR) -1;
14737   CORE_ADDR best_high = (CORE_ADDR) 0;
14738   CORE_ADDR current_low, current_high;
14739
14740   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14741       >= PC_BOUNDS_RANGES)
14742     {
14743       best_low = current_low;
14744       best_high = current_high;
14745     }
14746   else
14747     {
14748       struct die_info *child = die->child;
14749
14750       while (child && child->tag)
14751         {
14752           switch (child->tag) {
14753           case DW_TAG_subprogram:
14754             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14755             break;
14756           case DW_TAG_namespace:
14757           case DW_TAG_module:
14758             /* FIXME: carlton/2004-01-16: Should we do this for
14759                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14760                that current GCC's always emit the DIEs corresponding
14761                to definitions of methods of classes as children of a
14762                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14763                the DIEs giving the declarations, which could be
14764                anywhere).  But I don't see any reason why the
14765                standards says that they have to be there.  */
14766             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14767
14768             if (current_low != ((CORE_ADDR) -1))
14769               {
14770                 best_low = std::min (best_low, current_low);
14771                 best_high = std::max (best_high, current_high);
14772               }
14773             break;
14774           default:
14775             /* Ignore.  */
14776             break;
14777           }
14778
14779           child = child->sibling;
14780         }
14781     }
14782
14783   *lowpc = best_low;
14784   *highpc = best_high;
14785 }
14786
14787 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14788    in DIE.  */
14789
14790 static void
14791 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14792                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14793 {
14794   struct objfile *objfile = cu->per_objfile->objfile;
14795   struct gdbarch *gdbarch = objfile->arch ();
14796   struct attribute *attr;
14797   struct attribute *attr_high;
14798
14799   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14800   if (attr_high)
14801     {
14802       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14803       if (attr != nullptr)
14804         {
14805           CORE_ADDR low = attr->as_address ();
14806           CORE_ADDR high = attr_high->as_address ();
14807
14808           if (cu->header.version >= 4 && attr_high->form_is_constant ())
14809             high += low;
14810
14811           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14812           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14813           cu->get_builder ()->record_block_range (block, low, high - 1);
14814         }
14815     }
14816
14817   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14818   if (attr != nullptr && attr->form_is_unsigned ())
14819     {
14820       /* Offset in the .debug_ranges or .debug_rnglist section (depending
14821          on DWARF version).  */
14822       ULONGEST ranges_offset = attr->as_unsigned ();
14823
14824       /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
14825          this value.  */
14826       if (die->tag != DW_TAG_compile_unit)
14827         ranges_offset += cu->gnu_ranges_base;
14828
14829       std::vector<blockrange> blockvec;
14830       dwarf2_ranges_process (ranges_offset, cu, die->tag,
14831         [&] (CORE_ADDR start, CORE_ADDR end)
14832         {
14833           start += baseaddr;
14834           end += baseaddr;
14835           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14836           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14837           cu->get_builder ()->record_block_range (block, start, end - 1);
14838           blockvec.emplace_back (start, end);
14839         });
14840
14841       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14842     }
14843 }
14844
14845 /* Check whether the producer field indicates either of GCC < 4.6, or the
14846    Intel C/C++ compiler, and cache the result in CU.  */
14847
14848 static void
14849 check_producer (struct dwarf2_cu *cu)
14850 {
14851   int major, minor;
14852
14853   if (cu->producer == NULL)
14854     {
14855       /* For unknown compilers expect their behavior is DWARF version
14856          compliant.
14857
14858          GCC started to support .debug_types sections by -gdwarf-4 since
14859          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14860          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14861          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14862          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14863     }
14864   else if (producer_is_gcc (cu->producer, &major, &minor))
14865     {
14866       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14867       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14868     }
14869   else if (producer_is_icc (cu->producer, &major, &minor))
14870     {
14871       cu->producer_is_icc = true;
14872       cu->producer_is_icc_lt_14 = major < 14;
14873     }
14874   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14875     cu->producer_is_codewarrior = true;
14876   else
14877     {
14878       /* For other non-GCC compilers, expect their behavior is DWARF version
14879          compliant.  */
14880     }
14881
14882   cu->checked_producer = true;
14883 }
14884
14885 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14886    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14887    during 4.6.0 experimental.  */
14888
14889 static bool
14890 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14891 {
14892   if (!cu->checked_producer)
14893     check_producer (cu);
14894
14895   return cu->producer_is_gxx_lt_4_6;
14896 }
14897
14898
14899 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14900    with incorrect is_stmt attributes.  */
14901
14902 static bool
14903 producer_is_codewarrior (struct dwarf2_cu *cu)
14904 {
14905   if (!cu->checked_producer)
14906     check_producer (cu);
14907
14908   return cu->producer_is_codewarrior;
14909 }
14910
14911 /* Return the accessibility of DIE, as given by DW_AT_accessibility.
14912    If that attribute is not available, return the appropriate
14913    default.  */
14914
14915 static enum dwarf_access_attribute
14916 dwarf2_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14917 {
14918   attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14919   if (attr != nullptr)
14920     {
14921       LONGEST value = attr->constant_value (-1);
14922       if (value == DW_ACCESS_public
14923           || value == DW_ACCESS_protected
14924           || value == DW_ACCESS_private)
14925         return (dwarf_access_attribute) value;
14926       complaint (_("Unhandled DW_AT_accessibility value (%s)"),
14927                  plongest (value));
14928     }
14929
14930   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14931     {
14932       /* The default DWARF 2 accessibility for members is public, the default
14933          accessibility for inheritance is private.  */
14934
14935       if (die->tag != DW_TAG_inheritance)
14936         return DW_ACCESS_public;
14937       else
14938         return DW_ACCESS_private;
14939     }
14940   else
14941     {
14942       /* DWARF 3+ defines the default accessibility a different way.  The same
14943          rules apply now for DW_TAG_inheritance as for the members and it only
14944          depends on the container kind.  */
14945
14946       if (die->parent->tag == DW_TAG_class_type)
14947         return DW_ACCESS_private;
14948       else
14949         return DW_ACCESS_public;
14950     }
14951 }
14952
14953 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14954    offset.  If the attribute was not found return 0, otherwise return
14955    1.  If it was found but could not properly be handled, set *OFFSET
14956    to 0.  */
14957
14958 static int
14959 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14960                              LONGEST *offset)
14961 {
14962   struct attribute *attr;
14963
14964   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14965   if (attr != NULL)
14966     {
14967       *offset = 0;
14968
14969       /* Note that we do not check for a section offset first here.
14970          This is because DW_AT_data_member_location is new in DWARF 4,
14971          so if we see it, we can assume that a constant form is really
14972          a constant and not a section offset.  */
14973       if (attr->form_is_constant ())
14974         *offset = attr->constant_value (0);
14975       else if (attr->form_is_section_offset ())
14976         dwarf2_complex_location_expr_complaint ();
14977       else if (attr->form_is_block ())
14978         *offset = decode_locdesc (attr->as_block (), cu);
14979       else
14980         dwarf2_complex_location_expr_complaint ();
14981
14982       return 1;
14983     }
14984
14985   return 0;
14986 }
14987
14988 /* Look for DW_AT_data_member_location and store the results in FIELD.  */
14989
14990 static void
14991 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14992                              struct field *field)
14993 {
14994   struct attribute *attr;
14995
14996   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14997   if (attr != NULL)
14998     {
14999       if (attr->form_is_constant ())
15000         {
15001           LONGEST offset = attr->constant_value (0);
15002           SET_FIELD_BITPOS (*field, offset * bits_per_byte);
15003         }
15004       else if (attr->form_is_section_offset ())
15005         dwarf2_complex_location_expr_complaint ();
15006       else if (attr->form_is_block ())
15007         {
15008           bool handled;
15009           CORE_ADDR offset = decode_locdesc (attr->as_block (), cu, &handled);
15010           if (handled)
15011             SET_FIELD_BITPOS (*field, offset * bits_per_byte);
15012           else
15013             {
15014               dwarf2_per_objfile *per_objfile = cu->per_objfile;
15015               struct objfile *objfile = per_objfile->objfile;
15016               struct dwarf2_locexpr_baton *dlbaton
15017                 = XOBNEW (&objfile->objfile_obstack,
15018                           struct dwarf2_locexpr_baton);
15019               dlbaton->data = attr->as_block ()->data;
15020               dlbaton->size = attr->as_block ()->size;
15021               /* When using this baton, we want to compute the address
15022                  of the field, not the value.  This is why
15023                  is_reference is set to false here.  */
15024               dlbaton->is_reference = false;
15025               dlbaton->per_objfile = per_objfile;
15026               dlbaton->per_cu = cu->per_cu;
15027
15028               SET_FIELD_DWARF_BLOCK (*field, dlbaton);
15029             }
15030         }
15031       else
15032         dwarf2_complex_location_expr_complaint ();
15033     }
15034 }
15035
15036 /* Add an aggregate field to the field list.  */
15037
15038 static void
15039 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15040                   struct dwarf2_cu *cu)
15041 {
15042   struct objfile *objfile = cu->per_objfile->objfile;
15043   struct gdbarch *gdbarch = objfile->arch ();
15044   struct nextfield *new_field;
15045   struct attribute *attr;
15046   struct field *fp;
15047   const char *fieldname = "";
15048
15049   if (die->tag == DW_TAG_inheritance)
15050     {
15051       fip->baseclasses.emplace_back ();
15052       new_field = &fip->baseclasses.back ();
15053     }
15054   else
15055     {
15056       fip->fields.emplace_back ();
15057       new_field = &fip->fields.back ();
15058     }
15059
15060   new_field->offset = die->sect_off;
15061
15062   new_field->accessibility = dwarf2_access_attribute (die, cu);
15063   if (new_field->accessibility != DW_ACCESS_public)
15064     fip->non_public_fields = true;
15065
15066   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15067   if (attr != nullptr)
15068     new_field->virtuality = attr->as_virtuality ();
15069   else
15070     new_field->virtuality = DW_VIRTUALITY_none;
15071
15072   fp = &new_field->field;
15073
15074   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15075     {
15076       /* Data member other than a C++ static data member.  */
15077
15078       /* Get type of field.  */
15079       fp->set_type (die_type (die, cu));
15080
15081       SET_FIELD_BITPOS (*fp, 0);
15082
15083       /* Get bit size of field (zero if none).  */
15084       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15085       if (attr != nullptr)
15086         {
15087           FIELD_BITSIZE (*fp) = attr->constant_value (0);
15088         }
15089       else
15090         {
15091           FIELD_BITSIZE (*fp) = 0;
15092         }
15093
15094       /* Get bit offset of field.  */
15095       handle_data_member_location (die, cu, fp);
15096       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15097       if (attr != nullptr && attr->form_is_constant ())
15098         {
15099           if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
15100             {
15101               /* For big endian bits, the DW_AT_bit_offset gives the
15102                  additional bit offset from the MSB of the containing
15103                  anonymous object to the MSB of the field.  We don't
15104                  have to do anything special since we don't need to
15105                  know the size of the anonymous object.  */
15106               SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15107                                       + attr->constant_value (0)));
15108             }
15109           else
15110             {
15111               /* For little endian bits, compute the bit offset to the
15112                  MSB of the anonymous object, subtract off the number of
15113                  bits from the MSB of the field to the MSB of the
15114                  object, and then subtract off the number of bits of
15115                  the field itself.  The result is the bit offset of
15116                  the LSB of the field.  */
15117               int anonymous_size;
15118               int bit_offset = attr->constant_value (0);
15119
15120               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15121               if (attr != nullptr && attr->form_is_constant ())
15122                 {
15123                   /* The size of the anonymous object containing
15124                      the bit field is explicit, so use the
15125                      indicated size (in bytes).  */
15126                   anonymous_size = attr->constant_value (0);
15127                 }
15128               else
15129                 {
15130                   /* The size of the anonymous object containing
15131                      the bit field must be inferred from the type
15132                      attribute of the data member containing the
15133                      bit field.  */
15134                   anonymous_size = TYPE_LENGTH (fp->type ());
15135                 }
15136               SET_FIELD_BITPOS (*fp,
15137                                 (FIELD_BITPOS (*fp)
15138                                  + anonymous_size * bits_per_byte
15139                                  - bit_offset - FIELD_BITSIZE (*fp)));
15140             }
15141         }
15142       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15143       if (attr != NULL)
15144         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15145                                 + attr->constant_value (0)));
15146
15147       /* Get name of field.  */
15148       fieldname = dwarf2_name (die, cu);
15149       if (fieldname == NULL)
15150         fieldname = "";
15151
15152       /* The name is already allocated along with this objfile, so we don't
15153          need to duplicate it for the type.  */
15154       fp->name = fieldname;
15155
15156       /* Change accessibility for artificial fields (e.g. virtual table
15157          pointer or virtual base class pointer) to private.  */
15158       if (dwarf2_attr (die, DW_AT_artificial, cu))
15159         {
15160           FIELD_ARTIFICIAL (*fp) = 1;
15161           new_field->accessibility = DW_ACCESS_private;
15162           fip->non_public_fields = true;
15163         }
15164     }
15165   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15166     {
15167       /* C++ static member.  */
15168
15169       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15170          is a declaration, but all versions of G++ as of this writing
15171          (so through at least 3.2.1) incorrectly generate
15172          DW_TAG_variable tags.  */
15173
15174       const char *physname;
15175
15176       /* Get name of field.  */
15177       fieldname = dwarf2_name (die, cu);
15178       if (fieldname == NULL)
15179         return;
15180
15181       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15182       if (attr
15183           /* Only create a symbol if this is an external value.
15184              new_symbol checks this and puts the value in the global symbol
15185              table, which we want.  If it is not external, new_symbol
15186              will try to put the value in cu->list_in_scope which is wrong.  */
15187           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15188         {
15189           /* A static const member, not much different than an enum as far as
15190              we're concerned, except that we can support more types.  */
15191           new_symbol (die, NULL, cu);
15192         }
15193
15194       /* Get physical name.  */
15195       physname = dwarf2_physname (fieldname, die, cu);
15196
15197       /* The name is already allocated along with this objfile, so we don't
15198          need to duplicate it for the type.  */
15199       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15200       fp->set_type (die_type (die, cu));
15201       FIELD_NAME (*fp) = fieldname;
15202     }
15203   else if (die->tag == DW_TAG_inheritance)
15204     {
15205       /* C++ base class field.  */
15206       handle_data_member_location (die, cu, fp);
15207       FIELD_BITSIZE (*fp) = 0;
15208       fp->set_type (die_type (die, cu));
15209       FIELD_NAME (*fp) = fp->type ()->name ();
15210     }
15211   else
15212     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15213 }
15214
15215 /* Can the type given by DIE define another type?  */
15216
15217 static bool
15218 type_can_define_types (const struct die_info *die)
15219 {
15220   switch (die->tag)
15221     {
15222     case DW_TAG_typedef:
15223     case DW_TAG_class_type:
15224     case DW_TAG_structure_type:
15225     case DW_TAG_union_type:
15226     case DW_TAG_enumeration_type:
15227       return true;
15228
15229     default:
15230       return false;
15231     }
15232 }
15233
15234 /* Add a type definition defined in the scope of the FIP's class.  */
15235
15236 static void
15237 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15238                       struct dwarf2_cu *cu)
15239 {
15240   struct decl_field fp;
15241   memset (&fp, 0, sizeof (fp));
15242
15243   gdb_assert (type_can_define_types (die));
15244
15245   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15246   fp.name = dwarf2_name (die, cu);
15247   fp.type = read_type_die (die, cu);
15248
15249   /* Save accessibility.  */
15250   dwarf_access_attribute accessibility = dwarf2_access_attribute (die, cu);
15251   switch (accessibility)
15252     {
15253     case DW_ACCESS_public:
15254       /* The assumed value if neither private nor protected.  */
15255       break;
15256     case DW_ACCESS_private:
15257       fp.is_private = 1;
15258       break;
15259     case DW_ACCESS_protected:
15260       fp.is_protected = 1;
15261       break;
15262     }
15263
15264   if (die->tag == DW_TAG_typedef)
15265     fip->typedef_field_list.push_back (fp);
15266   else
15267     fip->nested_types_list.push_back (fp);
15268 }
15269
15270 /* A convenience typedef that's used when finding the discriminant
15271    field for a variant part.  */
15272 typedef std::unordered_map<sect_offset, int, gdb::hash_enum<sect_offset>>
15273   offset_map_type;
15274
15275 /* Compute the discriminant range for a given variant.  OBSTACK is
15276    where the results will be stored.  VARIANT is the variant to
15277    process.  IS_UNSIGNED indicates whether the discriminant is signed
15278    or unsigned.  */
15279
15280 static const gdb::array_view<discriminant_range>
15281 convert_variant_range (struct obstack *obstack, const variant_field &variant,
15282                        bool is_unsigned)
15283 {
15284   std::vector<discriminant_range> ranges;
15285
15286   if (variant.default_branch)
15287     return {};
15288
15289   if (variant.discr_list_data == nullptr)
15290     {
15291       discriminant_range r
15292         = {variant.discriminant_value, variant.discriminant_value};
15293       ranges.push_back (r);
15294     }
15295   else
15296     {
15297       gdb::array_view<const gdb_byte> data (variant.discr_list_data->data,
15298                                             variant.discr_list_data->size);
15299       while (!data.empty ())
15300         {
15301           if (data[0] != DW_DSC_range && data[0] != DW_DSC_label)
15302             {
15303               complaint (_("invalid discriminant marker: %d"), data[0]);
15304               break;
15305             }
15306           bool is_range = data[0] == DW_DSC_range;
15307           data = data.slice (1);
15308
15309           ULONGEST low, high;
15310           unsigned int bytes_read;
15311
15312           if (data.empty ())
15313             {
15314               complaint (_("DW_AT_discr_list missing low value"));
15315               break;
15316             }
15317           if (is_unsigned)
15318             low = read_unsigned_leb128 (nullptr, data.data (), &bytes_read);
15319           else
15320             low = (ULONGEST) read_signed_leb128 (nullptr, data.data (),
15321                                                  &bytes_read);
15322           data = data.slice (bytes_read);
15323
15324           if (is_range)
15325             {
15326               if (data.empty ())
15327                 {
15328                   complaint (_("DW_AT_discr_list missing high value"));
15329                   break;
15330                 }
15331               if (is_unsigned)
15332                 high = read_unsigned_leb128 (nullptr, data.data (),
15333                                              &bytes_read);
15334               else
15335                 high = (LONGEST) read_signed_leb128 (nullptr, data.data (),
15336                                                      &bytes_read);
15337               data = data.slice (bytes_read);
15338             }
15339           else
15340             high = low;
15341
15342           ranges.push_back ({ low, high });
15343         }
15344     }
15345
15346   discriminant_range *result = XOBNEWVEC (obstack, discriminant_range,
15347                                           ranges.size ());
15348   std::copy (ranges.begin (), ranges.end (), result);
15349   return gdb::array_view<discriminant_range> (result, ranges.size ());
15350 }
15351
15352 static const gdb::array_view<variant_part> create_variant_parts
15353   (struct obstack *obstack,
15354    const offset_map_type &offset_map,
15355    struct field_info *fi,
15356    const std::vector<variant_part_builder> &variant_parts);
15357
15358 /* Fill in a "struct variant" for a given variant field.  RESULT is
15359    the variant to fill in.  OBSTACK is where any needed allocations
15360    will be done.  OFFSET_MAP holds the mapping from section offsets to
15361    fields for the type.  FI describes the fields of the type we're
15362    processing.  FIELD is the variant field we're converting.  */
15363
15364 static void
15365 create_one_variant (variant &result, struct obstack *obstack,
15366                     const offset_map_type &offset_map,
15367                     struct field_info *fi, const variant_field &field)
15368 {
15369   result.discriminants = convert_variant_range (obstack, field, false);
15370   result.first_field = field.first_field + fi->baseclasses.size ();
15371   result.last_field = field.last_field + fi->baseclasses.size ();
15372   result.parts = create_variant_parts (obstack, offset_map, fi,
15373                                        field.variant_parts);
15374 }
15375
15376 /* Fill in a "struct variant_part" for a given variant part.  RESULT
15377    is the variant part to fill in.  OBSTACK is where any needed
15378    allocations will be done.  OFFSET_MAP holds the mapping from
15379    section offsets to fields for the type.  FI describes the fields of
15380    the type we're processing.  BUILDER is the variant part to be
15381    converted.  */
15382
15383 static void
15384 create_one_variant_part (variant_part &result,
15385                          struct obstack *obstack,
15386                          const offset_map_type &offset_map,
15387                          struct field_info *fi,
15388                          const variant_part_builder &builder)
15389 {
15390   auto iter = offset_map.find (builder.discriminant_offset);
15391   if (iter == offset_map.end ())
15392     {
15393       result.discriminant_index = -1;
15394       /* Doesn't matter.  */
15395       result.is_unsigned = false;
15396     }
15397   else
15398     {
15399       result.discriminant_index = iter->second;
15400       result.is_unsigned
15401         = fi->fields[result.discriminant_index].field.type ()->is_unsigned ();
15402     }
15403
15404   size_t n = builder.variants.size ();
15405   variant *output = new (obstack) variant[n];
15406   for (size_t i = 0; i < n; ++i)
15407     create_one_variant (output[i], obstack, offset_map, fi,
15408                         builder.variants[i]);
15409
15410   result.variants = gdb::array_view<variant> (output, n);
15411 }
15412
15413 /* Create a vector of variant parts that can be attached to a type.
15414    OBSTACK is where any needed allocations will be done.  OFFSET_MAP
15415    holds the mapping from section offsets to fields for the type.  FI
15416    describes the fields of the type we're processing.  VARIANT_PARTS
15417    is the vector to convert.  */
15418
15419 static const gdb::array_view<variant_part>
15420 create_variant_parts (struct obstack *obstack,
15421                       const offset_map_type &offset_map,
15422                       struct field_info *fi,
15423                       const std::vector<variant_part_builder> &variant_parts)
15424 {
15425   if (variant_parts.empty ())
15426     return {};
15427
15428   size_t n = variant_parts.size ();
15429   variant_part *result = new (obstack) variant_part[n];
15430   for (size_t i = 0; i < n; ++i)
15431     create_one_variant_part (result[i], obstack, offset_map, fi,
15432                              variant_parts[i]);
15433
15434   return gdb::array_view<variant_part> (result, n);
15435 }
15436
15437 /* Compute the variant part vector for FIP, attaching it to TYPE when
15438    done.  */
15439
15440 static void
15441 add_variant_property (struct field_info *fip, struct type *type,
15442                       struct dwarf2_cu *cu)
15443 {
15444   /* Map section offsets of fields to their field index.  Note the
15445      field index here does not take the number of baseclasses into
15446      account.  */
15447   offset_map_type offset_map;
15448   for (int i = 0; i < fip->fields.size (); ++i)
15449     offset_map[fip->fields[i].offset] = i;
15450
15451   struct objfile *objfile = cu->per_objfile->objfile;
15452   gdb::array_view<variant_part> parts
15453     = create_variant_parts (&objfile->objfile_obstack, offset_map, fip,
15454                             fip->variant_parts);
15455
15456   struct dynamic_prop prop;
15457   prop.set_variant_parts ((gdb::array_view<variant_part> *)
15458                           obstack_copy (&objfile->objfile_obstack, &parts,
15459                                         sizeof (parts)));
15460
15461   type->add_dyn_prop (DYN_PROP_VARIANT_PARTS, prop);
15462 }
15463
15464 /* Create the vector of fields, and attach it to the type.  */
15465
15466 static void
15467 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15468                               struct dwarf2_cu *cu)
15469 {
15470   int nfields = fip->nfields ();
15471
15472   /* Record the field count, allocate space for the array of fields,
15473      and create blank accessibility bitfields if necessary.  */
15474   type->set_num_fields (nfields);
15475   type->set_fields
15476     ((struct field *) TYPE_ZALLOC (type, sizeof (struct field) * nfields));
15477
15478   if (fip->non_public_fields && cu->language != language_ada)
15479     {
15480       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15481
15482       TYPE_FIELD_PRIVATE_BITS (type) =
15483         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15484       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15485
15486       TYPE_FIELD_PROTECTED_BITS (type) =
15487         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15488       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15489
15490       TYPE_FIELD_IGNORE_BITS (type) =
15491         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15492       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15493     }
15494
15495   /* If the type has baseclasses, allocate and clear a bit vector for
15496      TYPE_FIELD_VIRTUAL_BITS.  */
15497   if (!fip->baseclasses.empty () && cu->language != language_ada)
15498     {
15499       int num_bytes = B_BYTES (fip->baseclasses.size ());
15500       unsigned char *pointer;
15501
15502       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15503       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15504       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15505       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15506       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15507     }
15508
15509   if (!fip->variant_parts.empty ())
15510     add_variant_property (fip, type, cu);
15511
15512   /* Copy the saved-up fields into the field vector.  */
15513   for (int i = 0; i < nfields; ++i)
15514     {
15515       struct nextfield &field
15516         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15517            : fip->fields[i - fip->baseclasses.size ()]);
15518
15519       type->field (i) = field.field;
15520       switch (field.accessibility)
15521         {
15522         case DW_ACCESS_private:
15523           if (cu->language != language_ada)
15524             SET_TYPE_FIELD_PRIVATE (type, i);
15525           break;
15526
15527         case DW_ACCESS_protected:
15528           if (cu->language != language_ada)
15529             SET_TYPE_FIELD_PROTECTED (type, i);
15530           break;
15531
15532         case DW_ACCESS_public:
15533           break;
15534
15535         default:
15536           /* Unknown accessibility.  Complain and treat it as public.  */
15537           {
15538             complaint (_("unsupported accessibility %d"),
15539                        field.accessibility);
15540           }
15541           break;
15542         }
15543       if (i < fip->baseclasses.size ())
15544         {
15545           switch (field.virtuality)
15546             {
15547             case DW_VIRTUALITY_virtual:
15548             case DW_VIRTUALITY_pure_virtual:
15549               if (cu->language == language_ada)
15550                 error (_("unexpected virtuality in component of Ada type"));
15551               SET_TYPE_FIELD_VIRTUAL (type, i);
15552               break;
15553             }
15554         }
15555     }
15556 }
15557
15558 /* Return true if this member function is a constructor, false
15559    otherwise.  */
15560
15561 static int
15562 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15563 {
15564   const char *fieldname;
15565   const char *type_name;
15566   int len;
15567
15568   if (die->parent == NULL)
15569     return 0;
15570
15571   if (die->parent->tag != DW_TAG_structure_type
15572       && die->parent->tag != DW_TAG_union_type
15573       && die->parent->tag != DW_TAG_class_type)
15574     return 0;
15575
15576   fieldname = dwarf2_name (die, cu);
15577   type_name = dwarf2_name (die->parent, cu);
15578   if (fieldname == NULL || type_name == NULL)
15579     return 0;
15580
15581   len = strlen (fieldname);
15582   return (strncmp (fieldname, type_name, len) == 0
15583           && (type_name[len] == '\0' || type_name[len] == '<'));
15584 }
15585
15586 /* Add a member function to the proper fieldlist.  */
15587
15588 static void
15589 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15590                       struct type *type, struct dwarf2_cu *cu)
15591 {
15592   struct objfile *objfile = cu->per_objfile->objfile;
15593   struct attribute *attr;
15594   int i;
15595   struct fnfieldlist *flp = nullptr;
15596   struct fn_field *fnp;
15597   const char *fieldname;
15598   struct type *this_type;
15599
15600   if (cu->language == language_ada)
15601     error (_("unexpected member function in Ada type"));
15602
15603   /* Get name of member function.  */
15604   fieldname = dwarf2_name (die, cu);
15605   if (fieldname == NULL)
15606     return;
15607
15608   /* Look up member function name in fieldlist.  */
15609   for (i = 0; i < fip->fnfieldlists.size (); i++)
15610     {
15611       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15612         {
15613           flp = &fip->fnfieldlists[i];
15614           break;
15615         }
15616     }
15617
15618   /* Create a new fnfieldlist if necessary.  */
15619   if (flp == nullptr)
15620     {
15621       fip->fnfieldlists.emplace_back ();
15622       flp = &fip->fnfieldlists.back ();
15623       flp->name = fieldname;
15624       i = fip->fnfieldlists.size () - 1;
15625     }
15626
15627   /* Create a new member function field and add it to the vector of
15628      fnfieldlists.  */
15629   flp->fnfields.emplace_back ();
15630   fnp = &flp->fnfields.back ();
15631
15632   /* Delay processing of the physname until later.  */
15633   if (cu->language == language_cplus)
15634     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15635                         die, cu);
15636   else
15637     {
15638       const char *physname = dwarf2_physname (fieldname, die, cu);
15639       fnp->physname = physname ? physname : "";
15640     }
15641
15642   fnp->type = alloc_type (objfile);
15643   this_type = read_type_die (die, cu);
15644   if (this_type && this_type->code () == TYPE_CODE_FUNC)
15645     {
15646       int nparams = this_type->num_fields ();
15647
15648       /* TYPE is the domain of this method, and THIS_TYPE is the type
15649            of the method itself (TYPE_CODE_METHOD).  */
15650       smash_to_method_type (fnp->type, type,
15651                             TYPE_TARGET_TYPE (this_type),
15652                             this_type->fields (),
15653                             this_type->num_fields (),
15654                             this_type->has_varargs ());
15655
15656       /* Handle static member functions.
15657          Dwarf2 has no clean way to discern C++ static and non-static
15658          member functions.  G++ helps GDB by marking the first
15659          parameter for non-static member functions (which is the this
15660          pointer) as artificial.  We obtain this information from
15661          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15662       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15663         fnp->voffset = VOFFSET_STATIC;
15664     }
15665   else
15666     complaint (_("member function type missing for '%s'"),
15667                dwarf2_full_name (fieldname, die, cu));
15668
15669   /* Get fcontext from DW_AT_containing_type if present.  */
15670   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15671     fnp->fcontext = die_containing_type (die, cu);
15672
15673   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15674      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15675
15676   /* Get accessibility.  */
15677   dwarf_access_attribute accessibility = dwarf2_access_attribute (die, cu);
15678   switch (accessibility)
15679     {
15680     case DW_ACCESS_private:
15681       fnp->is_private = 1;
15682       break;
15683     case DW_ACCESS_protected:
15684       fnp->is_protected = 1;
15685       break;
15686     }
15687
15688   /* Check for artificial methods.  */
15689   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15690   if (attr && attr->as_boolean ())
15691     fnp->is_artificial = 1;
15692
15693   /* Check for defaulted methods.  */
15694   attr = dwarf2_attr (die, DW_AT_defaulted, cu);
15695   if (attr != nullptr)
15696     fnp->defaulted = attr->defaulted ();
15697
15698   /* Check for deleted methods.  */
15699   attr = dwarf2_attr (die, DW_AT_deleted, cu);
15700   if (attr != nullptr && attr->as_boolean ())
15701     fnp->is_deleted = 1;
15702
15703   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15704
15705   /* Get index in virtual function table if it is a virtual member
15706      function.  For older versions of GCC, this is an offset in the
15707      appropriate virtual table, as specified by DW_AT_containing_type.
15708      For everyone else, it is an expression to be evaluated relative
15709      to the object address.  */
15710
15711   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15712   if (attr != nullptr)
15713     {
15714       if (attr->form_is_block () && attr->as_block ()->size > 0)
15715         {
15716           struct dwarf_block *block = attr->as_block ();
15717
15718           if (block->data[0] == DW_OP_constu)
15719             {
15720               /* Old-style GCC.  */
15721               fnp->voffset = decode_locdesc (block, cu) + 2;
15722             }
15723           else if (block->data[0] == DW_OP_deref
15724                    || (block->size > 1
15725                        && block->data[0] == DW_OP_deref_size
15726                        && block->data[1] == cu->header.addr_size))
15727             {
15728               fnp->voffset = decode_locdesc (block, cu);
15729               if ((fnp->voffset % cu->header.addr_size) != 0)
15730                 dwarf2_complex_location_expr_complaint ();
15731               else
15732                 fnp->voffset /= cu->header.addr_size;
15733               fnp->voffset += 2;
15734             }
15735           else
15736             dwarf2_complex_location_expr_complaint ();
15737
15738           if (!fnp->fcontext)
15739             {
15740               /* If there is no `this' field and no DW_AT_containing_type,
15741                  we cannot actually find a base class context for the
15742                  vtable!  */
15743               if (this_type->num_fields () == 0
15744                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15745                 {
15746                   complaint (_("cannot determine context for virtual member "
15747                                "function \"%s\" (offset %s)"),
15748                              fieldname, sect_offset_str (die->sect_off));
15749                 }
15750               else
15751                 {
15752                   fnp->fcontext
15753                     = TYPE_TARGET_TYPE (this_type->field (0).type ());
15754                 }
15755             }
15756         }
15757       else if (attr->form_is_section_offset ())
15758         {
15759           dwarf2_complex_location_expr_complaint ();
15760         }
15761       else
15762         {
15763           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15764                                                  fieldname);
15765         }
15766     }
15767   else
15768     {
15769       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15770       if (attr != nullptr && attr->as_virtuality () != DW_VIRTUALITY_none)
15771         {
15772           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15773           complaint (_("Member function \"%s\" (offset %s) is virtual "
15774                        "but the vtable offset is not specified"),
15775                      fieldname, sect_offset_str (die->sect_off));
15776           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15777           TYPE_CPLUS_DYNAMIC (type) = 1;
15778         }
15779     }
15780 }
15781
15782 /* Create the vector of member function fields, and attach it to the type.  */
15783
15784 static void
15785 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15786                                  struct dwarf2_cu *cu)
15787 {
15788   if (cu->language == language_ada)
15789     error (_("unexpected member functions in Ada type"));
15790
15791   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15792   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15793     TYPE_ALLOC (type,
15794                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15795
15796   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15797     {
15798       struct fnfieldlist &nf = fip->fnfieldlists[i];
15799       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15800
15801       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15802       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15803       fn_flp->fn_fields = (struct fn_field *)
15804         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15805
15806       for (int k = 0; k < nf.fnfields.size (); ++k)
15807         fn_flp->fn_fields[k] = nf.fnfields[k];
15808     }
15809
15810   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15811 }
15812
15813 /* Returns non-zero if NAME is the name of a vtable member in CU's
15814    language, zero otherwise.  */
15815 static int
15816 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15817 {
15818   static const char vptr[] = "_vptr";
15819
15820   /* Look for the C++ form of the vtable.  */
15821   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15822     return 1;
15823
15824   return 0;
15825 }
15826
15827 /* GCC outputs unnamed structures that are really pointers to member
15828    functions, with the ABI-specified layout.  If TYPE describes
15829    such a structure, smash it into a member function type.
15830
15831    GCC shouldn't do this; it should just output pointer to member DIEs.
15832    This is GCC PR debug/28767.  */
15833
15834 static void
15835 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15836 {
15837   struct type *pfn_type, *self_type, *new_type;
15838
15839   /* Check for a structure with no name and two children.  */
15840   if (type->code () != TYPE_CODE_STRUCT || type->num_fields () != 2)
15841     return;
15842
15843   /* Check for __pfn and __delta members.  */
15844   if (TYPE_FIELD_NAME (type, 0) == NULL
15845       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15846       || TYPE_FIELD_NAME (type, 1) == NULL
15847       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15848     return;
15849
15850   /* Find the type of the method.  */
15851   pfn_type = type->field (0).type ();
15852   if (pfn_type == NULL
15853       || pfn_type->code () != TYPE_CODE_PTR
15854       || TYPE_TARGET_TYPE (pfn_type)->code () != TYPE_CODE_FUNC)
15855     return;
15856
15857   /* Look for the "this" argument.  */
15858   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15859   if (pfn_type->num_fields () == 0
15860       /* || pfn_type->field (0).type () == NULL */
15861       || pfn_type->field (0).type ()->code () != TYPE_CODE_PTR)
15862     return;
15863
15864   self_type = TYPE_TARGET_TYPE (pfn_type->field (0).type ());
15865   new_type = alloc_type (objfile);
15866   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15867                         pfn_type->fields (), pfn_type->num_fields (),
15868                         pfn_type->has_varargs ());
15869   smash_to_methodptr_type (type, new_type);
15870 }
15871
15872 /* Helper for quirk_ada_thick_pointer.  If TYPE is an array type that
15873    requires rewriting, then copy it and return the updated copy.
15874    Otherwise return nullptr.  */
15875
15876 static struct type *
15877 rewrite_array_type (struct type *type)
15878 {
15879   if (type->code () != TYPE_CODE_ARRAY)
15880     return nullptr;
15881
15882   struct type *index_type = type->index_type ();
15883   range_bounds *current_bounds = index_type->bounds ();
15884
15885   /* Handle multi-dimensional arrays.  */
15886   struct type *new_target = rewrite_array_type (TYPE_TARGET_TYPE (type));
15887   if (new_target == nullptr)
15888     {
15889       /* Maybe we don't need to rewrite this array.  */
15890       if (current_bounds->low.kind () == PROP_CONST
15891           && current_bounds->high.kind () == PROP_CONST)
15892         return nullptr;
15893     }
15894
15895   /* Either the target type was rewritten, or the bounds have to be
15896      updated.  Either way we want to copy the type and update
15897      everything.  */
15898   struct type *copy = copy_type (type);
15899   int nfields = copy->num_fields ();
15900   field *new_fields
15901     = ((struct field *) TYPE_ZALLOC (copy,
15902                                      nfields * sizeof (struct field)));
15903   memcpy (new_fields, copy->fields (), nfields * sizeof (struct field));
15904   copy->set_fields (new_fields);
15905   if (new_target != nullptr)
15906     TYPE_TARGET_TYPE (copy) = new_target;
15907
15908   struct type *index_copy = copy_type (index_type);
15909   range_bounds *bounds
15910     = (struct range_bounds *) TYPE_ZALLOC (index_copy,
15911                                            sizeof (range_bounds));
15912   *bounds = *current_bounds;
15913   bounds->low.set_const_val (1);
15914   bounds->high.set_const_val (0);
15915   index_copy->set_bounds (bounds);
15916   copy->set_index_type (index_copy);
15917
15918   return copy;
15919 }
15920
15921 /* While some versions of GCC will generate complicated DWARF for an
15922    array (see quirk_ada_thick_pointer), more recent versions were
15923    modified to emit an explicit thick pointer structure.  However, in
15924    this case, the array still has DWARF expressions for its ranges,
15925    and these must be ignored.  */
15926
15927 static void
15928 quirk_ada_thick_pointer_struct (struct die_info *die, struct dwarf2_cu *cu,
15929                                 struct type *type)
15930 {
15931   gdb_assert (cu->language == language_ada);
15932
15933   /* Check for a structure with two children.  */
15934   if (type->code () != TYPE_CODE_STRUCT || type->num_fields () != 2)
15935     return;
15936
15937   /* Check for P_ARRAY and P_BOUNDS members.  */
15938   if (TYPE_FIELD_NAME (type, 0) == NULL
15939       || strcmp (TYPE_FIELD_NAME (type, 0), "P_ARRAY") != 0
15940       || TYPE_FIELD_NAME (type, 1) == NULL
15941       || strcmp (TYPE_FIELD_NAME (type, 1), "P_BOUNDS") != 0)
15942     return;
15943
15944   /* Make sure we're looking at a pointer to an array.  */
15945   if (type->field (0).type ()->code () != TYPE_CODE_PTR)
15946     return;
15947
15948   /* The Ada code already knows how to handle these types, so all that
15949      we need to do is turn the bounds into static bounds.  However, we
15950      don't want to rewrite existing array or index types in-place,
15951      because those may be referenced in other contexts where this
15952      rewriting is undesirable.  */
15953   struct type *new_ary_type
15954     = rewrite_array_type (TYPE_TARGET_TYPE (type->field (0).type ()));
15955   if (new_ary_type != nullptr)
15956     type->field (0).set_type (lookup_pointer_type (new_ary_type));
15957 }
15958
15959 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15960    appropriate error checking and issuing complaints if there is a
15961    problem.  */
15962
15963 static ULONGEST
15964 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15965 {
15966   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15967
15968   if (attr == nullptr)
15969     return 0;
15970
15971   if (!attr->form_is_constant ())
15972     {
15973       complaint (_("DW_AT_alignment must have constant form"
15974                    " - DIE at %s [in module %s]"),
15975                  sect_offset_str (die->sect_off),
15976                  objfile_name (cu->per_objfile->objfile));
15977       return 0;
15978     }
15979
15980   LONGEST val = attr->constant_value (0);
15981   if (val < 0)
15982     {
15983       complaint (_("DW_AT_alignment value must not be negative"
15984                    " - DIE at %s [in module %s]"),
15985                  sect_offset_str (die->sect_off),
15986                  objfile_name (cu->per_objfile->objfile));
15987       return 0;
15988     }
15989   ULONGEST align = val;
15990
15991   if (align == 0)
15992     {
15993       complaint (_("DW_AT_alignment value must not be zero"
15994                    " - DIE at %s [in module %s]"),
15995                  sect_offset_str (die->sect_off),
15996                  objfile_name (cu->per_objfile->objfile));
15997       return 0;
15998     }
15999   if ((align & (align - 1)) != 0)
16000     {
16001       complaint (_("DW_AT_alignment value must be a power of 2"
16002                    " - DIE at %s [in module %s]"),
16003                  sect_offset_str (die->sect_off),
16004                  objfile_name (cu->per_objfile->objfile));
16005       return 0;
16006     }
16007
16008   return align;
16009 }
16010
16011 /* If the DIE has a DW_AT_alignment attribute, use its value to set
16012    the alignment for TYPE.  */
16013
16014 static void
16015 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
16016                      struct type *type)
16017 {
16018   if (!set_type_align (type, get_alignment (cu, die)))
16019     complaint (_("DW_AT_alignment value too large"
16020                  " - DIE at %s [in module %s]"),
16021                sect_offset_str (die->sect_off),
16022                objfile_name (cu->per_objfile->objfile));
16023 }
16024
16025 /* Check if the given VALUE is a valid enum dwarf_calling_convention
16026    constant for a type, according to DWARF5 spec, Table 5.5.  */
16027
16028 static bool
16029 is_valid_DW_AT_calling_convention_for_type (ULONGEST value)
16030 {
16031   switch (value)
16032     {
16033     case DW_CC_normal:
16034     case DW_CC_pass_by_reference:
16035     case DW_CC_pass_by_value:
16036       return true;
16037
16038     default:
16039       complaint (_("unrecognized DW_AT_calling_convention value "
16040                    "(%s) for a type"), pulongest (value));
16041       return false;
16042     }
16043 }
16044
16045 /* Check if the given VALUE is a valid enum dwarf_calling_convention
16046    constant for a subroutine, according to DWARF5 spec, Table 3.3, and
16047    also according to GNU-specific values (see include/dwarf2.h).  */
16048
16049 static bool
16050 is_valid_DW_AT_calling_convention_for_subroutine (ULONGEST value)
16051 {
16052   switch (value)
16053     {
16054     case DW_CC_normal:
16055     case DW_CC_program:
16056     case DW_CC_nocall:
16057       return true;
16058
16059     case DW_CC_GNU_renesas_sh:
16060     case DW_CC_GNU_borland_fastcall_i386:
16061     case DW_CC_GDB_IBM_OpenCL:
16062       return true;
16063
16064     default:
16065       complaint (_("unrecognized DW_AT_calling_convention value "
16066                    "(%s) for a subroutine"), pulongest (value));
16067       return false;
16068     }
16069 }
16070
16071 /* Called when we find the DIE that starts a structure or union scope
16072    (definition) to create a type for the structure or union.  Fill in
16073    the type's name and general properties; the members will not be
16074    processed until process_structure_scope.  A symbol table entry for
16075    the type will also not be done until process_structure_scope (assuming
16076    the type has a name).
16077
16078    NOTE: we need to call these functions regardless of whether or not the
16079    DIE has a DW_AT_name attribute, since it might be an anonymous
16080    structure or union.  This gets the type entered into our set of
16081    user defined types.  */
16082
16083 static struct type *
16084 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
16085 {
16086   struct objfile *objfile = cu->per_objfile->objfile;
16087   struct type *type;
16088   struct attribute *attr;
16089   const char *name;
16090
16091   /* If the definition of this type lives in .debug_types, read that type.
16092      Don't follow DW_AT_specification though, that will take us back up
16093      the chain and we want to go down.  */
16094   attr = die->attr (DW_AT_signature);
16095   if (attr != nullptr)
16096     {
16097       type = get_DW_AT_signature_type (die, attr, cu);
16098
16099       /* The type's CU may not be the same as CU.
16100          Ensure TYPE is recorded with CU in die_type_hash.  */
16101       return set_die_type (die, type, cu);
16102     }
16103
16104   type = alloc_type (objfile);
16105   INIT_CPLUS_SPECIFIC (type);
16106
16107   name = dwarf2_name (die, cu);
16108   if (name != NULL)
16109     {
16110       if (cu->language == language_cplus
16111           || cu->language == language_d
16112           || cu->language == language_rust)
16113         {
16114           const char *full_name = dwarf2_full_name (name, die, cu);
16115
16116           /* dwarf2_full_name might have already finished building the DIE's
16117              type.  If so, there is no need to continue.  */
16118           if (get_die_type (die, cu) != NULL)
16119             return get_die_type (die, cu);
16120
16121           type->set_name (full_name);
16122         }
16123       else
16124         {
16125           /* The name is already allocated along with this objfile, so
16126              we don't need to duplicate it for the type.  */
16127           type->set_name (name);
16128         }
16129     }
16130
16131   if (die->tag == DW_TAG_structure_type)
16132     {
16133       type->set_code (TYPE_CODE_STRUCT);
16134     }
16135   else if (die->tag == DW_TAG_union_type)
16136     {
16137       type->set_code (TYPE_CODE_UNION);
16138     }
16139   else
16140     {
16141       type->set_code (TYPE_CODE_STRUCT);
16142     }
16143
16144   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
16145     TYPE_DECLARED_CLASS (type) = 1;
16146
16147   /* Store the calling convention in the type if it's available in
16148      the die.  Otherwise the calling convention remains set to
16149      the default value DW_CC_normal.  */
16150   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
16151   if (attr != nullptr
16152       && is_valid_DW_AT_calling_convention_for_type (attr->constant_value (0)))
16153     {
16154       ALLOCATE_CPLUS_STRUCT_TYPE (type);
16155       TYPE_CPLUS_CALLING_CONVENTION (type)
16156         = (enum dwarf_calling_convention) (attr->constant_value (0));
16157     }
16158
16159   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16160   if (attr != nullptr)
16161     {
16162       if (attr->form_is_constant ())
16163         TYPE_LENGTH (type) = attr->constant_value (0);
16164       else
16165         {
16166           struct dynamic_prop prop;
16167           if (attr_to_dynamic_prop (attr, die, cu, &prop, cu->addr_type ()))
16168             type->add_dyn_prop (DYN_PROP_BYTE_SIZE, prop);
16169           TYPE_LENGTH (type) = 0;
16170         }
16171     }
16172   else
16173     {
16174       TYPE_LENGTH (type) = 0;
16175     }
16176
16177   maybe_set_alignment (cu, die, type);
16178
16179   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
16180     {
16181       /* ICC<14 does not output the required DW_AT_declaration on
16182          incomplete types, but gives them a size of zero.  */
16183       type->set_is_stub (true);
16184     }
16185   else
16186     type->set_stub_is_supported (true);
16187
16188   if (die_is_declaration (die, cu))
16189     type->set_is_stub (true);
16190   else if (attr == NULL && die->child == NULL
16191            && producer_is_realview (cu->producer))
16192     /* RealView does not output the required DW_AT_declaration
16193        on incomplete types.  */
16194     type->set_is_stub (true);
16195
16196   /* We need to add the type field to the die immediately so we don't
16197      infinitely recurse when dealing with pointers to the structure
16198      type within the structure itself.  */
16199   set_die_type (die, type, cu);
16200
16201   /* set_die_type should be already done.  */
16202   set_descriptive_type (type, die, cu);
16203
16204   return type;
16205 }
16206
16207 static void handle_struct_member_die
16208   (struct die_info *child_die,
16209    struct type *type,
16210    struct field_info *fi,
16211    std::vector<struct symbol *> *template_args,
16212    struct dwarf2_cu *cu);
16213
16214 /* A helper for handle_struct_member_die that handles
16215    DW_TAG_variant_part.  */
16216
16217 static void
16218 handle_variant_part (struct die_info *die, struct type *type,
16219                      struct field_info *fi,
16220                      std::vector<struct symbol *> *template_args,
16221                      struct dwarf2_cu *cu)
16222 {
16223   variant_part_builder *new_part;
16224   if (fi->current_variant_part == nullptr)
16225     {
16226       fi->variant_parts.emplace_back ();
16227       new_part = &fi->variant_parts.back ();
16228     }
16229   else if (!fi->current_variant_part->processing_variant)
16230     {
16231       complaint (_("nested DW_TAG_variant_part seen "
16232                    "- DIE at %s [in module %s]"),
16233                  sect_offset_str (die->sect_off),
16234                  objfile_name (cu->per_objfile->objfile));
16235       return;
16236     }
16237   else
16238     {
16239       variant_field &current = fi->current_variant_part->variants.back ();
16240       current.variant_parts.emplace_back ();
16241       new_part = &current.variant_parts.back ();
16242     }
16243
16244   /* When we recurse, we want callees to add to this new variant
16245      part.  */
16246   scoped_restore save_current_variant_part
16247     = make_scoped_restore (&fi->current_variant_part, new_part);
16248
16249   struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
16250   if (discr == NULL)
16251     {
16252       /* It's a univariant form, an extension we support.  */
16253     }
16254   else if (discr->form_is_ref ())
16255     {
16256       struct dwarf2_cu *target_cu = cu;
16257       struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
16258
16259       new_part->discriminant_offset = target_die->sect_off;
16260     }
16261   else
16262     {
16263       complaint (_("DW_AT_discr does not have DIE reference form"
16264                    " - DIE at %s [in module %s]"),
16265                  sect_offset_str (die->sect_off),
16266                  objfile_name (cu->per_objfile->objfile));
16267     }
16268
16269   for (die_info *child_die = die->child;
16270        child_die != NULL;
16271        child_die = child_die->sibling)
16272     handle_struct_member_die (child_die, type, fi, template_args, cu);
16273 }
16274
16275 /* A helper for handle_struct_member_die that handles
16276    DW_TAG_variant.  */
16277
16278 static void
16279 handle_variant (struct die_info *die, struct type *type,
16280                 struct field_info *fi,
16281                 std::vector<struct symbol *> *template_args,
16282                 struct dwarf2_cu *cu)
16283 {
16284   if (fi->current_variant_part == nullptr)
16285     {
16286       complaint (_("saw DW_TAG_variant outside DW_TAG_variant_part "
16287                    "- DIE at %s [in module %s]"),
16288                  sect_offset_str (die->sect_off),
16289                  objfile_name (cu->per_objfile->objfile));
16290       return;
16291     }
16292   if (fi->current_variant_part->processing_variant)
16293     {
16294       complaint (_("nested DW_TAG_variant seen "
16295                    "- DIE at %s [in module %s]"),
16296                  sect_offset_str (die->sect_off),
16297                  objfile_name (cu->per_objfile->objfile));
16298       return;
16299     }
16300
16301   scoped_restore save_processing_variant
16302     = make_scoped_restore (&fi->current_variant_part->processing_variant,
16303                            true);
16304
16305   fi->current_variant_part->variants.emplace_back ();
16306   variant_field &variant = fi->current_variant_part->variants.back ();
16307   variant.first_field = fi->fields.size ();
16308
16309   /* In a variant we want to get the discriminant and also add a
16310      field for our sole member child.  */
16311   struct attribute *discr = dwarf2_attr (die, DW_AT_discr_value, cu);
16312   if (discr == nullptr || !discr->form_is_constant ())
16313     {
16314       discr = dwarf2_attr (die, DW_AT_discr_list, cu);
16315       if (discr == nullptr || discr->as_block ()->size == 0)
16316         variant.default_branch = true;
16317       else
16318         variant.discr_list_data = discr->as_block ();
16319     }
16320   else
16321     variant.discriminant_value = discr->constant_value (0);
16322
16323   for (die_info *variant_child = die->child;
16324        variant_child != NULL;
16325        variant_child = variant_child->sibling)
16326     handle_struct_member_die (variant_child, type, fi, template_args, cu);
16327
16328   variant.last_field = fi->fields.size ();
16329 }
16330
16331 /* A helper for process_structure_scope that handles a single member
16332    DIE.  */
16333
16334 static void
16335 handle_struct_member_die (struct die_info *child_die, struct type *type,
16336                           struct field_info *fi,
16337                           std::vector<struct symbol *> *template_args,
16338                           struct dwarf2_cu *cu)
16339 {
16340   if (child_die->tag == DW_TAG_member
16341       || child_die->tag == DW_TAG_variable)
16342     {
16343       /* NOTE: carlton/2002-11-05: A C++ static data member
16344          should be a DW_TAG_member that is a declaration, but
16345          all versions of G++ as of this writing (so through at
16346          least 3.2.1) incorrectly generate DW_TAG_variable
16347          tags for them instead.  */
16348       dwarf2_add_field (fi, child_die, cu);
16349     }
16350   else if (child_die->tag == DW_TAG_subprogram)
16351     {
16352       /* Rust doesn't have member functions in the C++ sense.
16353          However, it does emit ordinary functions as children
16354          of a struct DIE.  */
16355       if (cu->language == language_rust)
16356         read_func_scope (child_die, cu);
16357       else
16358         {
16359           /* C++ member function.  */
16360           dwarf2_add_member_fn (fi, child_die, type, cu);
16361         }
16362     }
16363   else if (child_die->tag == DW_TAG_inheritance)
16364     {
16365       /* C++ base class field.  */
16366       dwarf2_add_field (fi, child_die, cu);
16367     }
16368   else if (type_can_define_types (child_die))
16369     dwarf2_add_type_defn (fi, child_die, cu);
16370   else if (child_die->tag == DW_TAG_template_type_param
16371            || child_die->tag == DW_TAG_template_value_param)
16372     {
16373       struct symbol *arg = new_symbol (child_die, NULL, cu);
16374
16375       if (arg != NULL)
16376         template_args->push_back (arg);
16377     }
16378   else if (child_die->tag == DW_TAG_variant_part)
16379     handle_variant_part (child_die, type, fi, template_args, cu);
16380   else if (child_die->tag == DW_TAG_variant)
16381     handle_variant (child_die, type, fi, template_args, cu);
16382 }
16383
16384 /* Finish creating a structure or union type, including filling in
16385    its members and creating a symbol for it.  */
16386
16387 static void
16388 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
16389 {
16390   struct objfile *objfile = cu->per_objfile->objfile;
16391   struct die_info *child_die;
16392   struct type *type;
16393
16394   type = get_die_type (die, cu);
16395   if (type == NULL)
16396     type = read_structure_type (die, cu);
16397
16398   bool has_template_parameters = false;
16399   if (die->child != NULL && ! die_is_declaration (die, cu))
16400     {
16401       struct field_info fi;
16402       std::vector<struct symbol *> template_args;
16403
16404       child_die = die->child;
16405
16406       while (child_die && child_die->tag)
16407         {
16408           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
16409           child_die = child_die->sibling;
16410         }
16411
16412       /* Attach template arguments to type.  */
16413       if (!template_args.empty ())
16414         {
16415           has_template_parameters = true;
16416           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16417           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16418           TYPE_TEMPLATE_ARGUMENTS (type)
16419             = XOBNEWVEC (&objfile->objfile_obstack,
16420                          struct symbol *,
16421                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16422           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16423                   template_args.data (),
16424                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16425                    * sizeof (struct symbol *)));
16426         }
16427
16428       /* Attach fields and member functions to the type.  */
16429       if (fi.nfields () > 0)
16430         dwarf2_attach_fields_to_type (&fi, type, cu);
16431       if (!fi.fnfieldlists.empty ())
16432         {
16433           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16434
16435           /* Get the type which refers to the base class (possibly this
16436              class itself) which contains the vtable pointer for the current
16437              class from the DW_AT_containing_type attribute.  This use of
16438              DW_AT_containing_type is a GNU extension.  */
16439
16440           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16441             {
16442               struct type *t = die_containing_type (die, cu);
16443
16444               set_type_vptr_basetype (type, t);
16445               if (type == t)
16446                 {
16447                   int i;
16448
16449                   /* Our own class provides vtbl ptr.  */
16450                   for (i = t->num_fields () - 1;
16451                        i >= TYPE_N_BASECLASSES (t);
16452                        --i)
16453                     {
16454                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16455
16456                       if (is_vtable_name (fieldname, cu))
16457                         {
16458                           set_type_vptr_fieldno (type, i);
16459                           break;
16460                         }
16461                     }
16462
16463                   /* Complain if virtual function table field not found.  */
16464                   if (i < TYPE_N_BASECLASSES (t))
16465                     complaint (_("virtual function table pointer "
16466                                  "not found when defining class '%s'"),
16467                                type->name () ? type->name () : "");
16468                 }
16469               else
16470                 {
16471                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16472                 }
16473             }
16474           else if (cu->producer
16475                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16476             {
16477               /* The IBM XLC compiler does not provide direct indication
16478                  of the containing type, but the vtable pointer is
16479                  always named __vfp.  */
16480
16481               int i;
16482
16483               for (i = type->num_fields () - 1;
16484                    i >= TYPE_N_BASECLASSES (type);
16485                    --i)
16486                 {
16487                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16488                     {
16489                       set_type_vptr_fieldno (type, i);
16490                       set_type_vptr_basetype (type, type);
16491                       break;
16492                     }
16493                 }
16494             }
16495         }
16496
16497       /* Copy fi.typedef_field_list linked list elements content into the
16498          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16499       if (!fi.typedef_field_list.empty ())
16500         {
16501           int count = fi.typedef_field_list.size ();
16502
16503           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16504           TYPE_TYPEDEF_FIELD_ARRAY (type)
16505             = ((struct decl_field *)
16506                TYPE_ALLOC (type,
16507                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16508           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16509
16510           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16511             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16512         }
16513
16514       /* Copy fi.nested_types_list linked list elements content into the
16515          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16516       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16517         {
16518           int count = fi.nested_types_list.size ();
16519
16520           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16521           TYPE_NESTED_TYPES_ARRAY (type)
16522             = ((struct decl_field *)
16523                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16524           TYPE_NESTED_TYPES_COUNT (type) = count;
16525
16526           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16527             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16528         }
16529     }
16530
16531   quirk_gcc_member_function_pointer (type, objfile);
16532   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16533     cu->rust_unions.push_back (type);
16534   else if (cu->language == language_ada)
16535     quirk_ada_thick_pointer_struct (die, cu, type);
16536
16537   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16538      snapshots) has been known to create a die giving a declaration
16539      for a class that has, as a child, a die giving a definition for a
16540      nested class.  So we have to process our children even if the
16541      current die is a declaration.  Normally, of course, a declaration
16542      won't have any children at all.  */
16543
16544   child_die = die->child;
16545
16546   while (child_die != NULL && child_die->tag)
16547     {
16548       if (child_die->tag == DW_TAG_member
16549           || child_die->tag == DW_TAG_variable
16550           || child_die->tag == DW_TAG_inheritance
16551           || child_die->tag == DW_TAG_template_value_param
16552           || child_die->tag == DW_TAG_template_type_param)
16553         {
16554           /* Do nothing.  */
16555         }
16556       else
16557         process_die (child_die, cu);
16558
16559       child_die = child_die->sibling;
16560     }
16561
16562   /* Do not consider external references.  According to the DWARF standard,
16563      these DIEs are identified by the fact that they have no byte_size
16564      attribute, and a declaration attribute.  */
16565   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16566       || !die_is_declaration (die, cu)
16567       || dwarf2_attr (die, DW_AT_signature, cu) != NULL)
16568     {
16569       struct symbol *sym = new_symbol (die, type, cu);
16570
16571       if (has_template_parameters)
16572         {
16573           struct symtab *symtab;
16574           if (sym != nullptr)
16575             symtab = symbol_symtab (sym);
16576           else if (cu->line_header != nullptr)
16577             {
16578               /* Any related symtab will do.  */
16579               symtab
16580                 = cu->line_header->file_names ()[0].symtab;
16581             }
16582           else
16583             {
16584               symtab = nullptr;
16585               complaint (_("could not find suitable "
16586                            "symtab for template parameter"
16587                            " - DIE at %s [in module %s]"),
16588                          sect_offset_str (die->sect_off),
16589                          objfile_name (objfile));
16590             }
16591
16592           if (symtab != nullptr)
16593             {
16594               /* Make sure that the symtab is set on the new symbols.
16595                  Even though they don't appear in this symtab directly,
16596                  other parts of gdb assume that symbols do, and this is
16597                  reasonably true.  */
16598               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16599                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
16600             }
16601         }
16602     }
16603 }
16604
16605 /* Assuming DIE is an enumeration type, and TYPE is its associated
16606    type, update TYPE using some information only available in DIE's
16607    children.  In particular, the fields are computed.  */
16608
16609 static void
16610 update_enumeration_type_from_children (struct die_info *die,
16611                                        struct type *type,
16612                                        struct dwarf2_cu *cu)
16613 {
16614   struct die_info *child_die;
16615   int unsigned_enum = 1;
16616   int flag_enum = 1;
16617
16618   auto_obstack obstack;
16619   std::vector<struct field> fields;
16620
16621   for (child_die = die->child;
16622        child_die != NULL && child_die->tag;
16623        child_die = child_die->sibling)
16624     {
16625       struct attribute *attr;
16626       LONGEST value;
16627       const gdb_byte *bytes;
16628       struct dwarf2_locexpr_baton *baton;
16629       const char *name;
16630
16631       if (child_die->tag != DW_TAG_enumerator)
16632         continue;
16633
16634       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16635       if (attr == NULL)
16636         continue;
16637
16638       name = dwarf2_name (child_die, cu);
16639       if (name == NULL)
16640         name = "<anonymous enumerator>";
16641
16642       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16643                                &value, &bytes, &baton);
16644       if (value < 0)
16645         {
16646           unsigned_enum = 0;
16647           flag_enum = 0;
16648         }
16649       else
16650         {
16651           if (count_one_bits_ll (value) >= 2)
16652             flag_enum = 0;
16653         }
16654
16655       fields.emplace_back ();
16656       struct field &field = fields.back ();
16657       FIELD_NAME (field) = dwarf2_physname (name, child_die, cu);
16658       SET_FIELD_ENUMVAL (field, value);
16659     }
16660
16661   if (!fields.empty ())
16662     {
16663       type->set_num_fields (fields.size ());
16664       type->set_fields
16665         ((struct field *)
16666          TYPE_ALLOC (type, sizeof (struct field) * fields.size ()));
16667       memcpy (type->fields (), fields.data (),
16668               sizeof (struct field) * fields.size ());
16669     }
16670
16671   if (unsigned_enum)
16672     type->set_is_unsigned (true);
16673
16674   if (flag_enum)
16675     TYPE_FLAG_ENUM (type) = 1;
16676 }
16677
16678 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16679    complete the type's fields yet, or create any symbols.  */
16680
16681 static struct type *
16682 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16683 {
16684   struct objfile *objfile = cu->per_objfile->objfile;
16685   struct type *type;
16686   struct attribute *attr;
16687   const char *name;
16688
16689   /* If the definition of this type lives in .debug_types, read that type.
16690      Don't follow DW_AT_specification though, that will take us back up
16691      the chain and we want to go down.  */
16692   attr = die->attr (DW_AT_signature);
16693   if (attr != nullptr)
16694     {
16695       type = get_DW_AT_signature_type (die, attr, cu);
16696
16697       /* The type's CU may not be the same as CU.
16698          Ensure TYPE is recorded with CU in die_type_hash.  */
16699       return set_die_type (die, type, cu);
16700     }
16701
16702   type = alloc_type (objfile);
16703
16704   type->set_code (TYPE_CODE_ENUM);
16705   name = dwarf2_full_name (NULL, die, cu);
16706   if (name != NULL)
16707     type->set_name (name);
16708
16709   attr = dwarf2_attr (die, DW_AT_type, cu);
16710   if (attr != NULL)
16711     {
16712       struct type *underlying_type = die_type (die, cu);
16713
16714       TYPE_TARGET_TYPE (type) = underlying_type;
16715     }
16716
16717   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16718   if (attr != nullptr)
16719     {
16720       TYPE_LENGTH (type) = attr->constant_value (0);
16721     }
16722   else
16723     {
16724       TYPE_LENGTH (type) = 0;
16725     }
16726
16727   maybe_set_alignment (cu, die, type);
16728
16729   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16730      declared as private in the package spec, and then defined only
16731      inside the package body.  Such types are known as Taft Amendment
16732      Types.  When another package uses such a type, an incomplete DIE
16733      may be generated by the compiler.  */
16734   if (die_is_declaration (die, cu))
16735     type->set_is_stub (true);
16736
16737   /* If this type has an underlying type that is not a stub, then we
16738      may use its attributes.  We always use the "unsigned" attribute
16739      in this situation, because ordinarily we guess whether the type
16740      is unsigned -- but the guess can be wrong and the underlying type
16741      can tell us the reality.  However, we defer to a local size
16742      attribute if one exists, because this lets the compiler override
16743      the underlying type if needed.  */
16744   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_TARGET_TYPE (type)->is_stub ())
16745     {
16746       struct type *underlying_type = TYPE_TARGET_TYPE (type);
16747       underlying_type = check_typedef (underlying_type);
16748
16749       type->set_is_unsigned (underlying_type->is_unsigned ());
16750
16751       if (TYPE_LENGTH (type) == 0)
16752         TYPE_LENGTH (type) = TYPE_LENGTH (underlying_type);
16753
16754       if (TYPE_RAW_ALIGN (type) == 0
16755           && TYPE_RAW_ALIGN (underlying_type) != 0)
16756         set_type_align (type, TYPE_RAW_ALIGN (underlying_type));
16757     }
16758
16759   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16760
16761   set_die_type (die, type, cu);
16762
16763   /* Finish the creation of this type by using the enum's children.
16764      Note that, as usual, this must come after set_die_type to avoid
16765      infinite recursion when trying to compute the names of the
16766      enumerators.  */
16767   update_enumeration_type_from_children (die, type, cu);
16768
16769   return type;
16770 }
16771
16772 /* Given a pointer to a die which begins an enumeration, process all
16773    the dies that define the members of the enumeration, and create the
16774    symbol for the enumeration type.
16775
16776    NOTE: We reverse the order of the element list.  */
16777
16778 static void
16779 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16780 {
16781   struct type *this_type;
16782
16783   this_type = get_die_type (die, cu);
16784   if (this_type == NULL)
16785     this_type = read_enumeration_type (die, cu);
16786
16787   if (die->child != NULL)
16788     {
16789       struct die_info *child_die;
16790       const char *name;
16791
16792       child_die = die->child;
16793       while (child_die && child_die->tag)
16794         {
16795           if (child_die->tag != DW_TAG_enumerator)
16796             {
16797               process_die (child_die, cu);
16798             }
16799           else
16800             {
16801               name = dwarf2_name (child_die, cu);
16802               if (name)
16803                 new_symbol (child_die, this_type, cu);
16804             }
16805
16806           child_die = child_die->sibling;
16807         }
16808     }
16809
16810   /* If we are reading an enum from a .debug_types unit, and the enum
16811      is a declaration, and the enum is not the signatured type in the
16812      unit, then we do not want to add a symbol for it.  Adding a
16813      symbol would in some cases obscure the true definition of the
16814      enum, giving users an incomplete type when the definition is
16815      actually available.  Note that we do not want to do this for all
16816      enums which are just declarations, because C++0x allows forward
16817      enum declarations.  */
16818   if (cu->per_cu->is_debug_types
16819       && die_is_declaration (die, cu))
16820     {
16821       struct signatured_type *sig_type;
16822
16823       sig_type = (struct signatured_type *) cu->per_cu;
16824       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16825       if (sig_type->type_offset_in_section != die->sect_off)
16826         return;
16827     }
16828
16829   new_symbol (die, this_type, cu);
16830 }
16831
16832 /* Helper function for quirk_ada_thick_pointer that examines a bounds
16833    expression for an index type and finds the corresponding field
16834    offset in the hidden "P_BOUNDS" structure.  Returns true on success
16835    and updates *FIELD, false if it fails to recognize an
16836    expression.  */
16837
16838 static bool
16839 recognize_bound_expression (struct die_info *die, enum dwarf_attribute name,
16840                             int *bounds_offset, struct field *field,
16841                             struct dwarf2_cu *cu)
16842 {
16843   struct attribute *attr = dwarf2_attr (die, name, cu);
16844   if (attr == nullptr || !attr->form_is_block ())
16845     return false;
16846
16847   const struct dwarf_block *block = attr->as_block ();
16848   const gdb_byte *start = block->data;
16849   const gdb_byte *end = block->data + block->size;
16850
16851   /* The expression to recognize generally looks like:
16852
16853      (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16854      DW_OP_plus_uconst: 4; DW_OP_deref_size: 4)
16855
16856      However, the second "plus_uconst" may be missing:
16857
16858      (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16859      DW_OP_deref_size: 4)
16860
16861      This happens when the field is at the start of the structure.
16862
16863      Also, the final deref may not be sized:
16864
16865      (DW_OP_push_object_address; DW_OP_plus_uconst: 4; DW_OP_deref;
16866      DW_OP_deref)
16867
16868      This happens when the size of the index type happens to be the
16869      same as the architecture's word size.  This can occur with or
16870      without the second plus_uconst.  */
16871
16872   if (end - start < 2)
16873     return false;
16874   if (*start++ != DW_OP_push_object_address)
16875     return false;
16876   if (*start++ != DW_OP_plus_uconst)
16877     return false;
16878
16879   uint64_t this_bound_off;
16880   start = gdb_read_uleb128 (start, end, &this_bound_off);
16881   if (start == nullptr || (int) this_bound_off != this_bound_off)
16882     return false;
16883   /* Update *BOUNDS_OFFSET if needed, or alternatively verify that it
16884      is consistent among all bounds.  */
16885   if (*bounds_offset == -1)
16886     *bounds_offset = this_bound_off;
16887   else if (*bounds_offset != this_bound_off)
16888     return false;
16889
16890   if (start == end || *start++ != DW_OP_deref)
16891     return false;
16892
16893   int offset = 0;
16894   if (start ==end)
16895     return false;
16896   else if (*start == DW_OP_deref_size || *start == DW_OP_deref)
16897     {
16898       /* This means an offset of 0.  */
16899     }
16900   else if (*start++ != DW_OP_plus_uconst)
16901     return false;
16902   else
16903     {
16904       /* The size is the parameter to DW_OP_plus_uconst.  */
16905       uint64_t val;
16906       start = gdb_read_uleb128 (start, end, &val);
16907       if (start == nullptr)
16908         return false;
16909       if ((int) val != val)
16910         return false;
16911       offset = val;
16912     }
16913
16914   if (start == end)
16915     return false;
16916
16917   uint64_t size;
16918   if (*start == DW_OP_deref_size)
16919     {
16920       start = gdb_read_uleb128 (start + 1, end, &size);
16921       if (start == nullptr)
16922         return false;
16923     }
16924   else if (*start == DW_OP_deref)
16925     {
16926       size = cu->header.addr_size;
16927       ++start;
16928     }
16929   else
16930     return false;
16931
16932   SET_FIELD_BITPOS (*field, 8 * offset);
16933   if (size != TYPE_LENGTH (field->type ()))
16934     FIELD_BITSIZE (*field) = 8 * size;
16935
16936   return true;
16937 }
16938
16939 /* With -fgnat-encodings=minimal, gcc will emit some unusual DWARF for
16940    some kinds of Ada arrays:
16941
16942    <1><11db>: Abbrev Number: 7 (DW_TAG_array_type)
16943       <11dc>   DW_AT_name        : (indirect string, offset: 0x1bb8): string
16944       <11e0>   DW_AT_data_location: 2 byte block: 97 6
16945           (DW_OP_push_object_address; DW_OP_deref)
16946       <11e3>   DW_AT_type        : <0x1173>
16947       <11e7>   DW_AT_sibling     : <0x1201>
16948    <2><11eb>: Abbrev Number: 8 (DW_TAG_subrange_type)
16949       <11ec>   DW_AT_type        : <0x1206>
16950       <11f0>   DW_AT_lower_bound : 6 byte block: 97 23 8 6 94 4
16951           (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16952            DW_OP_deref_size: 4)
16953       <11f7>   DW_AT_upper_bound : 8 byte block: 97 23 8 6 23 4 94 4
16954           (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16955            DW_OP_plus_uconst: 4; DW_OP_deref_size: 4)
16956
16957    This actually represents a "thick pointer", which is a structure
16958    with two elements: one that is a pointer to the array data, and one
16959    that is a pointer to another structure; this second structure holds
16960    the array bounds.
16961
16962    This returns a new type on success, or nullptr if this didn't
16963    recognize the type.  */
16964
16965 static struct type *
16966 quirk_ada_thick_pointer (struct die_info *die, struct dwarf2_cu *cu,
16967                          struct type *type)
16968 {
16969   struct attribute *attr = dwarf2_attr (die, DW_AT_data_location, cu);
16970   /* So far we've only seen this with block form.  */
16971   if (attr == nullptr || !attr->form_is_block ())
16972     return nullptr;
16973
16974   /* Note that this will fail if the structure layout is changed by
16975      the compiler.  However, we have no good way to recognize some
16976      other layout, because we don't know what expression the compiler
16977      might choose to emit should this happen.  */
16978   struct dwarf_block *blk = attr->as_block ();
16979   if (blk->size != 2
16980       || blk->data[0] != DW_OP_push_object_address
16981       || blk->data[1] != DW_OP_deref)
16982     return nullptr;
16983
16984   int bounds_offset = -1;
16985   int max_align = -1;
16986   std::vector<struct field> range_fields;
16987   for (struct die_info *child_die = die->child;
16988        child_die;
16989        child_die = child_die->sibling)
16990     {
16991       if (child_die->tag == DW_TAG_subrange_type)
16992         {
16993           struct type *underlying = read_subrange_index_type (child_die, cu);
16994
16995           int this_align = type_align (underlying);
16996           if (this_align > max_align)
16997             max_align = this_align;
16998
16999           range_fields.emplace_back ();
17000           range_fields.emplace_back ();
17001
17002           struct field &lower = range_fields[range_fields.size () - 2];
17003           struct field &upper = range_fields[range_fields.size () - 1];
17004
17005           lower.set_type (underlying);
17006           FIELD_ARTIFICIAL (lower) = 1;
17007
17008           upper.set_type (underlying);
17009           FIELD_ARTIFICIAL (upper) = 1;
17010
17011           if (!recognize_bound_expression (child_die, DW_AT_lower_bound,
17012                                            &bounds_offset, &lower, cu)
17013               || !recognize_bound_expression (child_die, DW_AT_upper_bound,
17014                                               &bounds_offset, &upper, cu))
17015             return nullptr;
17016         }
17017     }
17018
17019   /* This shouldn't really happen, but double-check that we found
17020      where the bounds are stored.  */
17021   if (bounds_offset == -1)
17022     return nullptr;
17023
17024   struct objfile *objfile = cu->per_objfile->objfile;
17025   for (int i = 0; i < range_fields.size (); i += 2)
17026     {
17027       char name[20];
17028
17029       /* Set the name of each field in the bounds.  */
17030       xsnprintf (name, sizeof (name), "LB%d", i / 2);
17031       FIELD_NAME (range_fields[i]) = objfile->intern (name);
17032       xsnprintf (name, sizeof (name), "UB%d", i / 2);
17033       FIELD_NAME (range_fields[i + 1]) = objfile->intern (name);
17034     }
17035
17036   struct type *bounds = alloc_type (objfile);
17037   bounds->set_code (TYPE_CODE_STRUCT);
17038
17039   bounds->set_num_fields (range_fields.size ());
17040   bounds->set_fields
17041     ((struct field *) TYPE_ALLOC (bounds, (bounds->num_fields ()
17042                                            * sizeof (struct field))));
17043   memcpy (bounds->fields (), range_fields.data (),
17044           bounds->num_fields () * sizeof (struct field));
17045
17046   int last_fieldno = range_fields.size () - 1;
17047   int bounds_size = (TYPE_FIELD_BITPOS (bounds, last_fieldno) / 8
17048                      + TYPE_LENGTH (bounds->field (last_fieldno).type ()));
17049   TYPE_LENGTH (bounds) = align_up (bounds_size, max_align);
17050
17051   /* Rewrite the existing array type in place.  Specifically, we
17052      remove any dynamic properties we might have read, and we replace
17053      the index types.  */
17054   struct type *iter = type;
17055   for (int i = 0; i < range_fields.size (); i += 2)
17056     {
17057       gdb_assert (iter->code () == TYPE_CODE_ARRAY);
17058       iter->main_type->dyn_prop_list = nullptr;
17059       iter->set_index_type
17060         (create_static_range_type (NULL, bounds->field (i).type (), 1, 0));
17061       iter = TYPE_TARGET_TYPE (iter);
17062     }
17063
17064   struct type *result = alloc_type (objfile);
17065   result->set_code (TYPE_CODE_STRUCT);
17066
17067   result->set_num_fields (2);
17068   result->set_fields
17069     ((struct field *) TYPE_ZALLOC (result, (result->num_fields ()
17070                                             * sizeof (struct field))));
17071
17072   /* The names are chosen to coincide with what the compiler does with
17073      -fgnat-encodings=all, which the Ada code in gdb already
17074      understands.  */
17075   TYPE_FIELD_NAME (result, 0) = "P_ARRAY";
17076   result->field (0).set_type (lookup_pointer_type (type));
17077
17078   TYPE_FIELD_NAME (result, 1) = "P_BOUNDS";
17079   result->field (1).set_type (lookup_pointer_type (bounds));
17080   SET_FIELD_BITPOS (result->field (1), 8 * bounds_offset);
17081
17082   result->set_name (type->name ());
17083   TYPE_LENGTH (result) = (TYPE_LENGTH (result->field (0).type ())
17084                           + TYPE_LENGTH (result->field (1).type ()));
17085
17086   return result;
17087 }
17088
17089 /* Extract all information from a DW_TAG_array_type DIE and put it in
17090    the DIE's type field.  For now, this only handles one dimensional
17091    arrays.  */
17092
17093 static struct type *
17094 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
17095 {
17096   struct objfile *objfile = cu->per_objfile->objfile;
17097   struct die_info *child_die;
17098   struct type *type;
17099   struct type *element_type, *range_type, *index_type;
17100   struct attribute *attr;
17101   const char *name;
17102   struct dynamic_prop *byte_stride_prop = NULL;
17103   unsigned int bit_stride = 0;
17104
17105   element_type = die_type (die, cu);
17106
17107   /* The die_type call above may have already set the type for this DIE.  */
17108   type = get_die_type (die, cu);
17109   if (type)
17110     return type;
17111
17112   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
17113   if (attr != NULL)
17114     {
17115       int stride_ok;
17116       struct type *prop_type = cu->addr_sized_int_type (false);
17117
17118       byte_stride_prop
17119         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
17120       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop,
17121                                         prop_type);
17122       if (!stride_ok)
17123         {
17124           complaint (_("unable to read array DW_AT_byte_stride "
17125                        " - DIE at %s [in module %s]"),
17126                      sect_offset_str (die->sect_off),
17127                      objfile_name (cu->per_objfile->objfile));
17128           /* Ignore this attribute.  We will likely not be able to print
17129              arrays of this type correctly, but there is little we can do
17130              to help if we cannot read the attribute's value.  */
17131           byte_stride_prop = NULL;
17132         }
17133     }
17134
17135   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
17136   if (attr != NULL)
17137     bit_stride = attr->constant_value (0);
17138
17139   /* Irix 6.2 native cc creates array types without children for
17140      arrays with unspecified length.  */
17141   if (die->child == NULL)
17142     {
17143       index_type = objfile_type (objfile)->builtin_int;
17144       range_type = create_static_range_type (NULL, index_type, 0, -1);
17145       type = create_array_type_with_stride (NULL, element_type, range_type,
17146                                             byte_stride_prop, bit_stride);
17147       return set_die_type (die, type, cu);
17148     }
17149
17150   std::vector<struct type *> range_types;
17151   child_die = die->child;
17152   while (child_die && child_die->tag)
17153     {
17154       if (child_die->tag == DW_TAG_subrange_type)
17155         {
17156           struct type *child_type = read_type_die (child_die, cu);
17157
17158           if (child_type != NULL)
17159             {
17160               /* The range type was succesfully read.  Save it for the
17161                  array type creation.  */
17162               range_types.push_back (child_type);
17163             }
17164         }
17165       child_die = child_die->sibling;
17166     }
17167
17168   if (range_types.empty ())
17169     {
17170       complaint (_("unable to find array range - DIE at %s [in module %s]"),
17171                  sect_offset_str (die->sect_off),
17172                  objfile_name (cu->per_objfile->objfile));
17173       return NULL;
17174     }
17175
17176   /* Dwarf2 dimensions are output from left to right, create the
17177      necessary array types in backwards order.  */
17178
17179   type = element_type;
17180
17181   if (read_array_order (die, cu) == DW_ORD_col_major)
17182     {
17183       int i = 0;
17184
17185       while (i < range_types.size ())
17186         {
17187           type = create_array_type_with_stride (NULL, type, range_types[i++],
17188                                                 byte_stride_prop, bit_stride);
17189           bit_stride = 0;
17190           byte_stride_prop = nullptr;
17191         }
17192     }
17193   else
17194     {
17195       size_t ndim = range_types.size ();
17196       while (ndim-- > 0)
17197         {
17198           type = create_array_type_with_stride (NULL, type, range_types[ndim],
17199                                                 byte_stride_prop, bit_stride);
17200           bit_stride = 0;
17201           byte_stride_prop = nullptr;
17202         }
17203     }
17204
17205   gdb_assert (type != element_type);
17206
17207   /* Understand Dwarf2 support for vector types (like they occur on
17208      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
17209      array type.  This is not part of the Dwarf2/3 standard yet, but a
17210      custom vendor extension.  The main difference between a regular
17211      array and the vector variant is that vectors are passed by value
17212      to functions.  */
17213   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
17214   if (attr != nullptr)
17215     make_vector_type (type);
17216
17217   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
17218      implementation may choose to implement triple vectors using this
17219      attribute.  */
17220   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17221   if (attr != nullptr && attr->form_is_unsigned ())
17222     {
17223       if (attr->as_unsigned () >= TYPE_LENGTH (type))
17224         TYPE_LENGTH (type) = attr->as_unsigned ();
17225       else
17226         complaint (_("DW_AT_byte_size for array type smaller "
17227                      "than the total size of elements"));
17228     }
17229
17230   name = dwarf2_name (die, cu);
17231   if (name)
17232     type->set_name (name);
17233
17234   maybe_set_alignment (cu, die, type);
17235
17236   struct type *replacement_type = nullptr;
17237   if (cu->language == language_ada)
17238     {
17239       replacement_type = quirk_ada_thick_pointer (die, cu, type);
17240       if (replacement_type != nullptr)
17241         type = replacement_type;
17242     }
17243
17244   /* Install the type in the die.  */
17245   set_die_type (die, type, cu, replacement_type != nullptr);
17246
17247   /* set_die_type should be already done.  */
17248   set_descriptive_type (type, die, cu);
17249
17250   return type;
17251 }
17252
17253 static enum dwarf_array_dim_ordering
17254 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
17255 {
17256   struct attribute *attr;
17257
17258   attr = dwarf2_attr (die, DW_AT_ordering, cu);
17259
17260   if (attr != nullptr)
17261     {
17262       LONGEST val = attr->constant_value (-1);
17263       if (val == DW_ORD_row_major || val == DW_ORD_col_major)
17264         return (enum dwarf_array_dim_ordering) val;
17265     }
17266
17267   /* GNU F77 is a special case, as at 08/2004 array type info is the
17268      opposite order to the dwarf2 specification, but data is still
17269      laid out as per normal fortran.
17270
17271      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
17272      version checking.  */
17273
17274   if (cu->language == language_fortran
17275       && cu->producer && strstr (cu->producer, "GNU F77"))
17276     {
17277       return DW_ORD_row_major;
17278     }
17279
17280   switch (cu->language_defn->array_ordering ())
17281     {
17282     case array_column_major:
17283       return DW_ORD_col_major;
17284     case array_row_major:
17285     default:
17286       return DW_ORD_row_major;
17287     };
17288 }
17289
17290 /* Extract all information from a DW_TAG_set_type DIE and put it in
17291    the DIE's type field.  */
17292
17293 static struct type *
17294 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
17295 {
17296   struct type *domain_type, *set_type;
17297   struct attribute *attr;
17298
17299   domain_type = die_type (die, cu);
17300
17301   /* The die_type call above may have already set the type for this DIE.  */
17302   set_type = get_die_type (die, cu);
17303   if (set_type)
17304     return set_type;
17305
17306   set_type = create_set_type (NULL, domain_type);
17307
17308   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17309   if (attr != nullptr && attr->form_is_unsigned ())
17310     TYPE_LENGTH (set_type) = attr->as_unsigned ();
17311
17312   maybe_set_alignment (cu, die, set_type);
17313
17314   return set_die_type (die, set_type, cu);
17315 }
17316
17317 /* A helper for read_common_block that creates a locexpr baton.
17318    SYM is the symbol which we are marking as computed.
17319    COMMON_DIE is the DIE for the common block.
17320    COMMON_LOC is the location expression attribute for the common
17321    block itself.
17322    MEMBER_LOC is the location expression attribute for the particular
17323    member of the common block that we are processing.
17324    CU is the CU from which the above come.  */
17325
17326 static void
17327 mark_common_block_symbol_computed (struct symbol *sym,
17328                                    struct die_info *common_die,
17329                                    struct attribute *common_loc,
17330                                    struct attribute *member_loc,
17331                                    struct dwarf2_cu *cu)
17332 {
17333   dwarf2_per_objfile *per_objfile = cu->per_objfile;
17334   struct objfile *objfile = per_objfile->objfile;
17335   struct dwarf2_locexpr_baton *baton;
17336   gdb_byte *ptr;
17337   unsigned int cu_off;
17338   enum bfd_endian byte_order = gdbarch_byte_order (objfile->arch ());
17339   LONGEST offset = 0;
17340
17341   gdb_assert (common_loc && member_loc);
17342   gdb_assert (common_loc->form_is_block ());
17343   gdb_assert (member_loc->form_is_block ()
17344               || member_loc->form_is_constant ());
17345
17346   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
17347   baton->per_objfile = per_objfile;
17348   baton->per_cu = cu->per_cu;
17349   gdb_assert (baton->per_cu);
17350
17351   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
17352
17353   if (member_loc->form_is_constant ())
17354     {
17355       offset = member_loc->constant_value (0);
17356       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
17357     }
17358   else
17359     baton->size += member_loc->as_block ()->size;
17360
17361   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
17362   baton->data = ptr;
17363
17364   *ptr++ = DW_OP_call4;
17365   cu_off = common_die->sect_off - cu->per_cu->sect_off;
17366   store_unsigned_integer (ptr, 4, byte_order, cu_off);
17367   ptr += 4;
17368
17369   if (member_loc->form_is_constant ())
17370     {
17371       *ptr++ = DW_OP_addr;
17372       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
17373       ptr += cu->header.addr_size;
17374     }
17375   else
17376     {
17377       /* We have to copy the data here, because DW_OP_call4 will only
17378          use a DW_AT_location attribute.  */
17379       struct dwarf_block *block = member_loc->as_block ();
17380       memcpy (ptr, block->data, block->size);
17381       ptr += block->size;
17382     }
17383
17384   *ptr++ = DW_OP_plus;
17385   gdb_assert (ptr - baton->data == baton->size);
17386
17387   SYMBOL_LOCATION_BATON (sym) = baton;
17388   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17389 }
17390
17391 /* Create appropriate locally-scoped variables for all the
17392    DW_TAG_common_block entries.  Also create a struct common_block
17393    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
17394    is used to separate the common blocks name namespace from regular
17395    variable names.  */
17396
17397 static void
17398 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
17399 {
17400   struct attribute *attr;
17401
17402   attr = dwarf2_attr (die, DW_AT_location, cu);
17403   if (attr != nullptr)
17404     {
17405       /* Support the .debug_loc offsets.  */
17406       if (attr->form_is_block ())
17407         {
17408           /* Ok.  */
17409         }
17410       else if (attr->form_is_section_offset ())
17411         {
17412           dwarf2_complex_location_expr_complaint ();
17413           attr = NULL;
17414         }
17415       else
17416         {
17417           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17418                                                  "common block member");
17419           attr = NULL;
17420         }
17421     }
17422
17423   if (die->child != NULL)
17424     {
17425       struct objfile *objfile = cu->per_objfile->objfile;
17426       struct die_info *child_die;
17427       size_t n_entries = 0, size;
17428       struct common_block *common_block;
17429       struct symbol *sym;
17430
17431       for (child_die = die->child;
17432            child_die && child_die->tag;
17433            child_die = child_die->sibling)
17434         ++n_entries;
17435
17436       size = (sizeof (struct common_block)
17437               + (n_entries - 1) * sizeof (struct symbol *));
17438       common_block
17439         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
17440                                                  size);
17441       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
17442       common_block->n_entries = 0;
17443
17444       for (child_die = die->child;
17445            child_die && child_die->tag;
17446            child_die = child_die->sibling)
17447         {
17448           /* Create the symbol in the DW_TAG_common_block block in the current
17449              symbol scope.  */
17450           sym = new_symbol (child_die, NULL, cu);
17451           if (sym != NULL)
17452             {
17453               struct attribute *member_loc;
17454
17455               common_block->contents[common_block->n_entries++] = sym;
17456
17457               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
17458                                         cu);
17459               if (member_loc)
17460                 {
17461                   /* GDB has handled this for a long time, but it is
17462                      not specified by DWARF.  It seems to have been
17463                      emitted by gfortran at least as recently as:
17464                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
17465                   complaint (_("Variable in common block has "
17466                                "DW_AT_data_member_location "
17467                                "- DIE at %s [in module %s]"),
17468                                sect_offset_str (child_die->sect_off),
17469                              objfile_name (objfile));
17470
17471                   if (member_loc->form_is_section_offset ())
17472                     dwarf2_complex_location_expr_complaint ();
17473                   else if (member_loc->form_is_constant ()
17474                            || member_loc->form_is_block ())
17475                     {
17476                       if (attr != nullptr)
17477                         mark_common_block_symbol_computed (sym, die, attr,
17478                                                            member_loc, cu);
17479                     }
17480                   else
17481                     dwarf2_complex_location_expr_complaint ();
17482                 }
17483             }
17484         }
17485
17486       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
17487       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
17488     }
17489 }
17490
17491 /* Create a type for a C++ namespace.  */
17492
17493 static struct type *
17494 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
17495 {
17496   struct objfile *objfile = cu->per_objfile->objfile;
17497   const char *previous_prefix, *name;
17498   int is_anonymous;
17499   struct type *type;
17500
17501   /* For extensions, reuse the type of the original namespace.  */
17502   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
17503     {
17504       struct die_info *ext_die;
17505       struct dwarf2_cu *ext_cu = cu;
17506
17507       ext_die = dwarf2_extension (die, &ext_cu);
17508       type = read_type_die (ext_die, ext_cu);
17509
17510       /* EXT_CU may not be the same as CU.
17511          Ensure TYPE is recorded with CU in die_type_hash.  */
17512       return set_die_type (die, type, cu);
17513     }
17514
17515   name = namespace_name (die, &is_anonymous, cu);
17516
17517   /* Now build the name of the current namespace.  */
17518
17519   previous_prefix = determine_prefix (die, cu);
17520   if (previous_prefix[0] != '\0')
17521     name = typename_concat (&objfile->objfile_obstack,
17522                             previous_prefix, name, 0, cu);
17523
17524   /* Create the type.  */
17525   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
17526
17527   return set_die_type (die, type, cu);
17528 }
17529
17530 /* Read a namespace scope.  */
17531
17532 static void
17533 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
17534 {
17535   struct objfile *objfile = cu->per_objfile->objfile;
17536   int is_anonymous;
17537
17538   /* Add a symbol associated to this if we haven't seen the namespace
17539      before.  Also, add a using directive if it's an anonymous
17540      namespace.  */
17541
17542   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
17543     {
17544       struct type *type;
17545
17546       type = read_type_die (die, cu);
17547       new_symbol (die, type, cu);
17548
17549       namespace_name (die, &is_anonymous, cu);
17550       if (is_anonymous)
17551         {
17552           const char *previous_prefix = determine_prefix (die, cu);
17553
17554           std::vector<const char *> excludes;
17555           add_using_directive (using_directives (cu),
17556                                previous_prefix, type->name (), NULL,
17557                                NULL, excludes, 0, &objfile->objfile_obstack);
17558         }
17559     }
17560
17561   if (die->child != NULL)
17562     {
17563       struct die_info *child_die = die->child;
17564
17565       while (child_die && child_die->tag)
17566         {
17567           process_die (child_die, cu);
17568           child_die = child_die->sibling;
17569         }
17570     }
17571 }
17572
17573 /* Read a Fortran module as type.  This DIE can be only a declaration used for
17574    imported module.  Still we need that type as local Fortran "use ... only"
17575    declaration imports depend on the created type in determine_prefix.  */
17576
17577 static struct type *
17578 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
17579 {
17580   struct objfile *objfile = cu->per_objfile->objfile;
17581   const char *module_name;
17582   struct type *type;
17583
17584   module_name = dwarf2_name (die, cu);
17585   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
17586
17587   return set_die_type (die, type, cu);
17588 }
17589
17590 /* Read a Fortran module.  */
17591
17592 static void
17593 read_module (struct die_info *die, struct dwarf2_cu *cu)
17594 {
17595   struct die_info *child_die = die->child;
17596   struct type *type;
17597
17598   type = read_type_die (die, cu);
17599   new_symbol (die, type, cu);
17600
17601   while (child_die && child_die->tag)
17602     {
17603       process_die (child_die, cu);
17604       child_die = child_die->sibling;
17605     }
17606 }
17607
17608 /* Return the name of the namespace represented by DIE.  Set
17609    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
17610    namespace.  */
17611
17612 static const char *
17613 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
17614 {
17615   struct die_info *current_die;
17616   const char *name = NULL;
17617
17618   /* Loop through the extensions until we find a name.  */
17619
17620   for (current_die = die;
17621        current_die != NULL;
17622        current_die = dwarf2_extension (die, &cu))
17623     {
17624       /* We don't use dwarf2_name here so that we can detect the absence
17625          of a name -> anonymous namespace.  */
17626       name = dwarf2_string_attr (die, DW_AT_name, cu);
17627
17628       if (name != NULL)
17629         break;
17630     }
17631
17632   /* Is it an anonymous namespace?  */
17633
17634   *is_anonymous = (name == NULL);
17635   if (*is_anonymous)
17636     name = CP_ANONYMOUS_NAMESPACE_STR;
17637
17638   return name;
17639 }
17640
17641 /* Extract all information from a DW_TAG_pointer_type DIE and add to
17642    the user defined type vector.  */
17643
17644 static struct type *
17645 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
17646 {
17647   struct gdbarch *gdbarch = cu->per_objfile->objfile->arch ();
17648   struct comp_unit_head *cu_header = &cu->header;
17649   struct type *type;
17650   struct attribute *attr_byte_size;
17651   struct attribute *attr_address_class;
17652   int byte_size, addr_class;
17653   struct type *target_type;
17654
17655   target_type = die_type (die, cu);
17656
17657   /* The die_type call above may have already set the type for this DIE.  */
17658   type = get_die_type (die, cu);
17659   if (type)
17660     return type;
17661
17662   type = lookup_pointer_type (target_type);
17663
17664   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17665   if (attr_byte_size)
17666     byte_size = attr_byte_size->constant_value (cu_header->addr_size);
17667   else
17668     byte_size = cu_header->addr_size;
17669
17670   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17671   if (attr_address_class)
17672     addr_class = attr_address_class->constant_value (DW_ADDR_none);
17673   else
17674     addr_class = DW_ADDR_none;
17675
17676   ULONGEST alignment = get_alignment (cu, die);
17677
17678   /* If the pointer size, alignment, or address class is different
17679      than the default, create a type variant marked as such and set
17680      the length accordingly.  */
17681   if (TYPE_LENGTH (type) != byte_size
17682       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
17683           && alignment != TYPE_RAW_ALIGN (type))
17684       || addr_class != DW_ADDR_none)
17685     {
17686       if (gdbarch_address_class_type_flags_p (gdbarch))
17687         {
17688           type_instance_flags type_flags
17689             = gdbarch_address_class_type_flags (gdbarch, byte_size,
17690                                                 addr_class);
17691           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17692                       == 0);
17693           type = make_type_with_address_space (type, type_flags);
17694         }
17695       else if (TYPE_LENGTH (type) != byte_size)
17696         {
17697           complaint (_("invalid pointer size %d"), byte_size);
17698         }
17699       else if (TYPE_RAW_ALIGN (type) != alignment)
17700         {
17701           complaint (_("Invalid DW_AT_alignment"
17702                        " - DIE at %s [in module %s]"),
17703                      sect_offset_str (die->sect_off),
17704                      objfile_name (cu->per_objfile->objfile));
17705         }
17706       else
17707         {
17708           /* Should we also complain about unhandled address classes?  */
17709         }
17710     }
17711
17712   TYPE_LENGTH (type) = byte_size;
17713   set_type_align (type, alignment);
17714   return set_die_type (die, type, cu);
17715 }
17716
17717 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17718    the user defined type vector.  */
17719
17720 static struct type *
17721 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17722 {
17723   struct type *type;
17724   struct type *to_type;
17725   struct type *domain;
17726
17727   to_type = die_type (die, cu);
17728   domain = die_containing_type (die, cu);
17729
17730   /* The calls above may have already set the type for this DIE.  */
17731   type = get_die_type (die, cu);
17732   if (type)
17733     return type;
17734
17735   if (check_typedef (to_type)->code () == TYPE_CODE_METHOD)
17736     type = lookup_methodptr_type (to_type);
17737   else if (check_typedef (to_type)->code () == TYPE_CODE_FUNC)
17738     {
17739       struct type *new_type = alloc_type (cu->per_objfile->objfile);
17740
17741       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17742                             to_type->fields (), to_type->num_fields (),
17743                             to_type->has_varargs ());
17744       type = lookup_methodptr_type (new_type);
17745     }
17746   else
17747     type = lookup_memberptr_type (to_type, domain);
17748
17749   return set_die_type (die, type, cu);
17750 }
17751
17752 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17753    the user defined type vector.  */
17754
17755 static struct type *
17756 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17757                           enum type_code refcode)
17758 {
17759   struct comp_unit_head *cu_header = &cu->header;
17760   struct type *type, *target_type;
17761   struct attribute *attr;
17762
17763   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17764
17765   target_type = die_type (die, cu);
17766
17767   /* The die_type call above may have already set the type for this DIE.  */
17768   type = get_die_type (die, cu);
17769   if (type)
17770     return type;
17771
17772   type = lookup_reference_type (target_type, refcode);
17773   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17774   if (attr != nullptr)
17775     {
17776       TYPE_LENGTH (type) = attr->constant_value (cu_header->addr_size);
17777     }
17778   else
17779     {
17780       TYPE_LENGTH (type) = cu_header->addr_size;
17781     }
17782   maybe_set_alignment (cu, die, type);
17783   return set_die_type (die, type, cu);
17784 }
17785
17786 /* Add the given cv-qualifiers to the element type of the array.  GCC
17787    outputs DWARF type qualifiers that apply to an array, not the
17788    element type.  But GDB relies on the array element type to carry
17789    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17790    specification.  */
17791
17792 static struct type *
17793 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17794                    struct type *base_type, int cnst, int voltl)
17795 {
17796   struct type *el_type, *inner_array;
17797
17798   base_type = copy_type (base_type);
17799   inner_array = base_type;
17800
17801   while (TYPE_TARGET_TYPE (inner_array)->code () == TYPE_CODE_ARRAY)
17802     {
17803       TYPE_TARGET_TYPE (inner_array) =
17804         copy_type (TYPE_TARGET_TYPE (inner_array));
17805       inner_array = TYPE_TARGET_TYPE (inner_array);
17806     }
17807
17808   el_type = TYPE_TARGET_TYPE (inner_array);
17809   cnst |= TYPE_CONST (el_type);
17810   voltl |= TYPE_VOLATILE (el_type);
17811   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17812
17813   return set_die_type (die, base_type, cu);
17814 }
17815
17816 static struct type *
17817 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17818 {
17819   struct type *base_type, *cv_type;
17820
17821   base_type = die_type (die, cu);
17822
17823   /* The die_type call above may have already set the type for this DIE.  */
17824   cv_type = get_die_type (die, cu);
17825   if (cv_type)
17826     return cv_type;
17827
17828   /* In case the const qualifier is applied to an array type, the element type
17829      is so qualified, not the array type (section 6.7.3 of C99).  */
17830   if (base_type->code () == TYPE_CODE_ARRAY)
17831     return add_array_cv_type (die, cu, base_type, 1, 0);
17832
17833   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17834   return set_die_type (die, cv_type, cu);
17835 }
17836
17837 static struct type *
17838 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17839 {
17840   struct type *base_type, *cv_type;
17841
17842   base_type = die_type (die, cu);
17843
17844   /* The die_type call above may have already set the type for this DIE.  */
17845   cv_type = get_die_type (die, cu);
17846   if (cv_type)
17847     return cv_type;
17848
17849   /* In case the volatile qualifier is applied to an array type, the
17850      element type is so qualified, not the array type (section 6.7.3
17851      of C99).  */
17852   if (base_type->code () == TYPE_CODE_ARRAY)
17853     return add_array_cv_type (die, cu, base_type, 0, 1);
17854
17855   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17856   return set_die_type (die, cv_type, cu);
17857 }
17858
17859 /* Handle DW_TAG_restrict_type.  */
17860
17861 static struct type *
17862 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17863 {
17864   struct type *base_type, *cv_type;
17865
17866   base_type = die_type (die, cu);
17867
17868   /* The die_type call above may have already set the type for this DIE.  */
17869   cv_type = get_die_type (die, cu);
17870   if (cv_type)
17871     return cv_type;
17872
17873   cv_type = make_restrict_type (base_type);
17874   return set_die_type (die, cv_type, cu);
17875 }
17876
17877 /* Handle DW_TAG_atomic_type.  */
17878
17879 static struct type *
17880 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17881 {
17882   struct type *base_type, *cv_type;
17883
17884   base_type = die_type (die, cu);
17885
17886   /* The die_type call above may have already set the type for this DIE.  */
17887   cv_type = get_die_type (die, cu);
17888   if (cv_type)
17889     return cv_type;
17890
17891   cv_type = make_atomic_type (base_type);
17892   return set_die_type (die, cv_type, cu);
17893 }
17894
17895 /* Extract all information from a DW_TAG_string_type DIE and add to
17896    the user defined type vector.  It isn't really a user defined type,
17897    but it behaves like one, with other DIE's using an AT_user_def_type
17898    attribute to reference it.  */
17899
17900 static struct type *
17901 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17902 {
17903   struct objfile *objfile = cu->per_objfile->objfile;
17904   struct gdbarch *gdbarch = objfile->arch ();
17905   struct type *type, *range_type, *index_type, *char_type;
17906   struct attribute *attr;
17907   struct dynamic_prop prop;
17908   bool length_is_constant = true;
17909   LONGEST length;
17910
17911   /* There are a couple of places where bit sizes might be made use of
17912      when parsing a DW_TAG_string_type, however, no producer that we know
17913      of make use of these.  Handling bit sizes that are a multiple of the
17914      byte size is easy enough, but what about other bit sizes?  Lets deal
17915      with that problem when we have to.  Warn about these attributes being
17916      unsupported, then parse the type and ignore them like we always
17917      have.  */
17918   if (dwarf2_attr (die, DW_AT_bit_size, cu) != nullptr
17919       || dwarf2_attr (die, DW_AT_string_length_bit_size, cu) != nullptr)
17920     {
17921       static bool warning_printed = false;
17922       if (!warning_printed)
17923         {
17924           warning (_("DW_AT_bit_size and DW_AT_string_length_bit_size not "
17925                      "currently supported on DW_TAG_string_type."));
17926           warning_printed = true;
17927         }
17928     }
17929
17930   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17931   if (attr != nullptr && !attr->form_is_constant ())
17932     {
17933       /* The string length describes the location at which the length of
17934          the string can be found.  The size of the length field can be
17935          specified with one of the attributes below.  */
17936       struct type *prop_type;
17937       struct attribute *len
17938         = dwarf2_attr (die, DW_AT_string_length_byte_size, cu);
17939       if (len == nullptr)
17940         len = dwarf2_attr (die, DW_AT_byte_size, cu);
17941       if (len != nullptr && len->form_is_constant ())
17942         {
17943           /* Pass 0 as the default as we know this attribute is constant
17944              and the default value will not be returned.  */
17945           LONGEST sz = len->constant_value (0);
17946           prop_type = cu->per_objfile->int_type (sz, true);
17947         }
17948       else
17949         {
17950           /* If the size is not specified then we assume it is the size of
17951              an address on this target.  */
17952           prop_type = cu->addr_sized_int_type (true);
17953         }
17954
17955       /* Convert the attribute into a dynamic property.  */
17956       if (!attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
17957         length = 1;
17958       else
17959         length_is_constant = false;
17960     }
17961   else if (attr != nullptr)
17962     {
17963       /* This DW_AT_string_length just contains the length with no
17964          indirection.  There's no need to create a dynamic property in this
17965          case.  Pass 0 for the default value as we know it will not be
17966          returned in this case.  */
17967       length = attr->constant_value (0);
17968     }
17969   else if ((attr = dwarf2_attr (die, DW_AT_byte_size, cu)) != nullptr)
17970     {
17971       /* We don't currently support non-constant byte sizes for strings.  */
17972       length = attr->constant_value (1);
17973     }
17974   else
17975     {
17976       /* Use 1 as a fallback length if we have nothing else.  */
17977       length = 1;
17978     }
17979
17980   index_type = objfile_type (objfile)->builtin_int;
17981   if (length_is_constant)
17982     range_type = create_static_range_type (NULL, index_type, 1, length);
17983   else
17984     {
17985       struct dynamic_prop low_bound;
17986
17987       low_bound.set_const_val (1);
17988       range_type = create_range_type (NULL, index_type, &low_bound, &prop, 0);
17989     }
17990   char_type = language_string_char_type (cu->language_defn, gdbarch);
17991   type = create_string_type (NULL, char_type, range_type);
17992
17993   return set_die_type (die, type, cu);
17994 }
17995
17996 /* Assuming that DIE corresponds to a function, returns nonzero
17997    if the function is prototyped.  */
17998
17999 static int
18000 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
18001 {
18002   struct attribute *attr;
18003
18004   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
18005   if (attr && attr->as_boolean ())
18006     return 1;
18007
18008   /* The DWARF standard implies that the DW_AT_prototyped attribute
18009      is only meaningful for C, but the concept also extends to other
18010      languages that allow unprototyped functions (Eg: Objective C).
18011      For all other languages, assume that functions are always
18012      prototyped.  */
18013   if (cu->language != language_c
18014       && cu->language != language_objc
18015       && cu->language != language_opencl)
18016     return 1;
18017
18018   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
18019      prototyped and unprototyped functions; default to prototyped,
18020      since that is more common in modern code (and RealView warns
18021      about unprototyped functions).  */
18022   if (producer_is_realview (cu->producer))
18023     return 1;
18024
18025   return 0;
18026 }
18027
18028 /* Handle DIES due to C code like:
18029
18030    struct foo
18031    {
18032    int (*funcp)(int a, long l);
18033    int b;
18034    };
18035
18036    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
18037
18038 static struct type *
18039 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
18040 {
18041   struct objfile *objfile = cu->per_objfile->objfile;
18042   struct type *type;            /* Type that this function returns.  */
18043   struct type *ftype;           /* Function that returns above type.  */
18044   struct attribute *attr;
18045
18046   type = die_type (die, cu);
18047
18048   /* The die_type call above may have already set the type for this DIE.  */
18049   ftype = get_die_type (die, cu);
18050   if (ftype)
18051     return ftype;
18052
18053   ftype = lookup_function_type (type);
18054
18055   if (prototyped_function_p (die, cu))
18056     ftype->set_is_prototyped (true);
18057
18058   /* Store the calling convention in the type if it's available in
18059      the subroutine die.  Otherwise set the calling convention to
18060      the default value DW_CC_normal.  */
18061   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
18062   if (attr != nullptr
18063       && is_valid_DW_AT_calling_convention_for_subroutine (attr->constant_value (0)))
18064     TYPE_CALLING_CONVENTION (ftype)
18065       = (enum dwarf_calling_convention) attr->constant_value (0);
18066   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
18067     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
18068   else
18069     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
18070
18071   /* Record whether the function returns normally to its caller or not
18072      if the DWARF producer set that information.  */
18073   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
18074   if (attr && attr->as_boolean ())
18075     TYPE_NO_RETURN (ftype) = 1;
18076
18077   /* We need to add the subroutine type to the die immediately so
18078      we don't infinitely recurse when dealing with parameters
18079      declared as the same subroutine type.  */
18080   set_die_type (die, ftype, cu);
18081
18082   if (die->child != NULL)
18083     {
18084       struct type *void_type = objfile_type (objfile)->builtin_void;
18085       struct die_info *child_die;
18086       int nparams, iparams;
18087
18088       /* Count the number of parameters.
18089          FIXME: GDB currently ignores vararg functions, but knows about
18090          vararg member functions.  */
18091       nparams = 0;
18092       child_die = die->child;
18093       while (child_die && child_die->tag)
18094         {
18095           if (child_die->tag == DW_TAG_formal_parameter)
18096             nparams++;
18097           else if (child_die->tag == DW_TAG_unspecified_parameters)
18098             ftype->set_has_varargs (true);
18099
18100           child_die = child_die->sibling;
18101         }
18102
18103       /* Allocate storage for parameters and fill them in.  */
18104       ftype->set_num_fields (nparams);
18105       ftype->set_fields
18106         ((struct field *) TYPE_ZALLOC (ftype, nparams * sizeof (struct field)));
18107
18108       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
18109          even if we error out during the parameters reading below.  */
18110       for (iparams = 0; iparams < nparams; iparams++)
18111         ftype->field (iparams).set_type (void_type);
18112
18113       iparams = 0;
18114       child_die = die->child;
18115       while (child_die && child_die->tag)
18116         {
18117           if (child_die->tag == DW_TAG_formal_parameter)
18118             {
18119               struct type *arg_type;
18120
18121               /* DWARF version 2 has no clean way to discern C++
18122                  static and non-static member functions.  G++ helps
18123                  GDB by marking the first parameter for non-static
18124                  member functions (which is the this pointer) as
18125                  artificial.  We pass this information to
18126                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
18127
18128                  DWARF version 3 added DW_AT_object_pointer, which GCC
18129                  4.5 does not yet generate.  */
18130               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
18131               if (attr != nullptr)
18132                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = attr->as_boolean ();
18133               else
18134                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
18135               arg_type = die_type (child_die, cu);
18136
18137               /* RealView does not mark THIS as const, which the testsuite
18138                  expects.  GCC marks THIS as const in method definitions,
18139                  but not in the class specifications (GCC PR 43053).  */
18140               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
18141                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
18142                 {
18143                   int is_this = 0;
18144                   struct dwarf2_cu *arg_cu = cu;
18145                   const char *name = dwarf2_name (child_die, cu);
18146
18147                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
18148                   if (attr != nullptr)
18149                     {
18150                       /* If the compiler emits this, use it.  */
18151                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
18152                         is_this = 1;
18153                     }
18154                   else if (name && strcmp (name, "this") == 0)
18155                     /* Function definitions will have the argument names.  */
18156                     is_this = 1;
18157                   else if (name == NULL && iparams == 0)
18158                     /* Declarations may not have the names, so like
18159                        elsewhere in GDB, assume an artificial first
18160                        argument is "this".  */
18161                     is_this = 1;
18162
18163                   if (is_this)
18164                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
18165                                              arg_type, 0);
18166                 }
18167
18168               ftype->field (iparams).set_type (arg_type);
18169               iparams++;
18170             }
18171           child_die = child_die->sibling;
18172         }
18173     }
18174
18175   return ftype;
18176 }
18177
18178 static struct type *
18179 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
18180 {
18181   struct objfile *objfile = cu->per_objfile->objfile;
18182   const char *name = NULL;
18183   struct type *this_type, *target_type;
18184
18185   name = dwarf2_full_name (NULL, die, cu);
18186   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
18187   this_type->set_target_is_stub (true);
18188   set_die_type (die, this_type, cu);
18189   target_type = die_type (die, cu);
18190   if (target_type != this_type)
18191     TYPE_TARGET_TYPE (this_type) = target_type;
18192   else
18193     {
18194       /* Self-referential typedefs are, it seems, not allowed by the DWARF
18195          spec and cause infinite loops in GDB.  */
18196       complaint (_("Self-referential DW_TAG_typedef "
18197                    "- DIE at %s [in module %s]"),
18198                  sect_offset_str (die->sect_off), objfile_name (objfile));
18199       TYPE_TARGET_TYPE (this_type) = NULL;
18200     }
18201   if (name == NULL)
18202     {
18203       /* Gcc-7 and before supports -feliminate-dwarf2-dups, which generates
18204          anonymous typedefs, which is, strictly speaking, invalid DWARF.
18205          Handle these by just returning the target type, rather than
18206          constructing an anonymous typedef type and trying to handle this
18207          elsewhere.  */
18208       set_die_type (die, target_type, cu);
18209       return target_type;
18210     }
18211   return this_type;
18212 }
18213
18214 /* Helper for get_dwarf2_rational_constant that computes the value of
18215    a given gmp_mpz given an attribute.  */
18216
18217 static void
18218 get_mpz (struct dwarf2_cu *cu, gdb_mpz *value, struct attribute *attr)
18219 {
18220   /* GCC will sometimes emit a 16-byte constant value as a DWARF
18221      location expression that pushes an implicit value.  */
18222   if (attr->form == DW_FORM_exprloc)
18223     {
18224       dwarf_block *blk = attr->as_block ();
18225       if (blk->size > 0 && blk->data[0] == DW_OP_implicit_value)
18226         {
18227           uint64_t len;
18228           const gdb_byte *ptr = safe_read_uleb128 (blk->data + 1,
18229                                                    blk->data + blk->size,
18230                                                    &len);
18231           if (ptr - blk->data + len <= blk->size)
18232             {
18233               mpz_import (value->val, len,
18234                           bfd_big_endian (cu->per_objfile->objfile->obfd) ? 1 : -1,
18235                           1, 0, 0, ptr);
18236               return;
18237             }
18238         }
18239
18240       /* On failure set it to 1.  */
18241       *value = gdb_mpz (1);
18242     }
18243   else if (attr->form_is_block ())
18244     {
18245       dwarf_block *blk = attr->as_block ();
18246       mpz_import (value->val, blk->size,
18247                   bfd_big_endian (cu->per_objfile->objfile->obfd) ? 1 : -1,
18248                   1, 0, 0, blk->data);
18249     }
18250   else
18251     *value = gdb_mpz (attr->constant_value (1));
18252 }
18253
18254 /* Assuming DIE is a rational DW_TAG_constant, read the DIE's
18255    numerator and denominator into NUMERATOR and DENOMINATOR (resp).
18256
18257    If the numerator and/or numerator attribute is missing,
18258    a complaint is filed, and NUMERATOR and DENOMINATOR are left
18259    untouched.  */
18260
18261 static void
18262 get_dwarf2_rational_constant (struct die_info *die, struct dwarf2_cu *cu,
18263                               gdb_mpz *numerator, gdb_mpz *denominator)
18264 {
18265   struct attribute *num_attr, *denom_attr;
18266
18267   num_attr = dwarf2_attr (die, DW_AT_GNU_numerator, cu);
18268   if (num_attr == nullptr)
18269     complaint (_("DW_AT_GNU_numerator missing in %s DIE at %s"),
18270                dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
18271
18272   denom_attr = dwarf2_attr (die, DW_AT_GNU_denominator, cu);
18273   if (denom_attr == nullptr)
18274     complaint (_("DW_AT_GNU_denominator missing in %s DIE at %s"),
18275                dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
18276
18277   if (num_attr == nullptr || denom_attr == nullptr)
18278     return;
18279
18280   get_mpz (cu, numerator, num_attr);
18281   get_mpz (cu, denominator, denom_attr);
18282 }
18283
18284 /* Same as get_dwarf2_rational_constant, but extracting an unsigned
18285    rational constant, rather than a signed one.
18286
18287    If the rational constant has a negative value, a complaint
18288    is filed, and NUMERATOR and DENOMINATOR are left untouched.  */
18289
18290 static void
18291 get_dwarf2_unsigned_rational_constant (struct die_info *die,
18292                                        struct dwarf2_cu *cu,
18293                                        gdb_mpz *numerator,
18294                                        gdb_mpz *denominator)
18295 {
18296   gdb_mpz num (1);
18297   gdb_mpz denom (1);
18298
18299   get_dwarf2_rational_constant (die, cu, &num, &denom);
18300   if (mpz_sgn (num.val) == -1 && mpz_sgn (denom.val) == -1)
18301     {
18302       mpz_neg (num.val, num.val);
18303       mpz_neg (denom.val, denom.val);
18304     }
18305   else if (mpz_sgn (num.val) == -1)
18306     {
18307       complaint (_("unexpected negative value for DW_AT_GNU_numerator"
18308                    " in DIE at %s"),
18309                  sect_offset_str (die->sect_off));
18310       return;
18311     }
18312   else if (mpz_sgn (denom.val) == -1)
18313     {
18314       complaint (_("unexpected negative value for DW_AT_GNU_denominator"
18315                    " in DIE at %s"),
18316                  sect_offset_str (die->sect_off));
18317       return;
18318     }
18319
18320   *numerator = std::move (num);
18321   *denominator = std::move (denom);
18322 }
18323
18324 /* Assuming that ENCODING is a string whose contents starting at the
18325    K'th character is "_nn" where "nn" is a decimal number, scan that
18326    number and set RESULT to the value. K is updated to point to the
18327    character immediately following the number.
18328
18329    If the string does not conform to the format described above, false
18330    is returned, and K may or may not be changed.  */
18331
18332 static bool
18333 ada_get_gnat_encoded_number (const char *encoding, int &k, gdb_mpz *result)
18334 {
18335   /* The next character should be an underscore ('_') followed
18336      by a digit.  */
18337   if (encoding[k] != '_' || !isdigit (encoding[k + 1]))
18338     return false;
18339
18340   /* Skip the underscore.  */
18341   k++;
18342   int start = k;
18343
18344   /* Determine the number of digits for our number.  */
18345   while (isdigit (encoding[k]))
18346     k++;
18347   if (k == start)
18348     return false;
18349
18350   std::string copy (&encoding[start], k - start);
18351   if (mpz_set_str (result->val, copy.c_str (), 10) == -1)
18352     return false;
18353
18354   return true;
18355 }
18356
18357 /* Scan two numbers from ENCODING at OFFSET, assuming the string is of
18358    the form _NN_DD, where NN and DD are decimal numbers.  Set NUM and
18359    DENOM, update OFFSET, and return true on success.  Return false on
18360    failure.  */
18361
18362 static bool
18363 ada_get_gnat_encoded_ratio (const char *encoding, int &offset,
18364                             gdb_mpz *num, gdb_mpz *denom)
18365 {
18366   if (!ada_get_gnat_encoded_number (encoding, offset, num))
18367     return false;
18368   return ada_get_gnat_encoded_number (encoding, offset, denom);
18369 }
18370
18371 /* Assuming DIE corresponds to a fixed point type, finish the creation
18372    of the corresponding TYPE by setting its type-specific data.  CU is
18373    the DIE's CU.  SUFFIX is the "XF" type name suffix coming from GNAT
18374    encodings.  It is nullptr if the GNAT encoding should be
18375    ignored.  */
18376
18377 static void
18378 finish_fixed_point_type (struct type *type, const char *suffix,
18379                          struct die_info *die, struct dwarf2_cu *cu)
18380 {
18381   gdb_assert (type->code () == TYPE_CODE_FIXED_POINT
18382               && TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_FIXED_POINT);
18383
18384   /* If GNAT encodings are preferred, don't examine the
18385      attributes.  */
18386   struct attribute *attr = nullptr;
18387   if (suffix == nullptr)
18388     {
18389       attr = dwarf2_attr (die, DW_AT_binary_scale, cu);
18390       if (attr == nullptr)
18391         attr = dwarf2_attr (die, DW_AT_decimal_scale, cu);
18392       if (attr == nullptr)
18393         attr = dwarf2_attr (die, DW_AT_small, cu);
18394     }
18395
18396   /* Numerator and denominator of our fixed-point type's scaling factor.
18397      The default is a scaling factor of 1, which we use as a fallback
18398      when we are not able to decode it (problem with the debugging info,
18399      unsupported forms, bug in GDB, etc...).  Using that as the default
18400      allows us to at least print the unscaled value, which might still
18401      be useful to a user.  */
18402   gdb_mpz scale_num (1);
18403   gdb_mpz scale_denom (1);
18404
18405   if (attr == nullptr)
18406     {
18407       int offset = 0;
18408       if (suffix != nullptr
18409           && ada_get_gnat_encoded_ratio (suffix, offset, &scale_num,
18410                                          &scale_denom)
18411           /* The number might be encoded as _nn_dd_nn_dd, where the
18412              second ratio is the 'small value.  In this situation, we
18413              want the second value.  */
18414           && (suffix[offset] != '_'
18415               || ada_get_gnat_encoded_ratio (suffix, offset, &scale_num,
18416                                              &scale_denom)))
18417         {
18418           /* Found it.  */
18419         }
18420       else
18421         {
18422           /* Scaling factor not found.  Assume a scaling factor of 1,
18423              and hope for the best.  At least the user will be able to
18424              see the encoded value.  */
18425           scale_num = 1;
18426           scale_denom = 1;
18427           complaint (_("no scale found for fixed-point type (DIE at %s)"),
18428                      sect_offset_str (die->sect_off));
18429         }
18430     }
18431   else if (attr->name == DW_AT_binary_scale)
18432     {
18433       LONGEST scale_exp = attr->constant_value (0);
18434       gdb_mpz *num_or_denom = scale_exp > 0 ? &scale_num : &scale_denom;
18435
18436       mpz_mul_2exp (num_or_denom->val, num_or_denom->val, std::abs (scale_exp));
18437     }
18438   else if (attr->name == DW_AT_decimal_scale)
18439     {
18440       LONGEST scale_exp = attr->constant_value (0);
18441       gdb_mpz *num_or_denom = scale_exp > 0 ? &scale_num : &scale_denom;
18442
18443       mpz_ui_pow_ui (num_or_denom->val, 10, std::abs (scale_exp));
18444     }
18445   else if (attr->name == DW_AT_small)
18446     {
18447       struct die_info *scale_die;
18448       struct dwarf2_cu *scale_cu = cu;
18449
18450       scale_die = follow_die_ref (die, attr, &scale_cu);
18451       if (scale_die->tag == DW_TAG_constant)
18452         get_dwarf2_unsigned_rational_constant (scale_die, scale_cu,
18453                                                &scale_num, &scale_denom);
18454       else
18455         complaint (_("%s DIE not supported as target of DW_AT_small attribute"
18456                      " (DIE at %s)"),
18457                    dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
18458     }
18459   else
18460     {
18461       complaint (_("unsupported scale attribute %s for fixed-point type"
18462                    " (DIE at %s)"),
18463                  dwarf_attr_name (attr->name),
18464                  sect_offset_str (die->sect_off));
18465     }
18466
18467   gdb_mpq &scaling_factor = type->fixed_point_info ().scaling_factor;
18468   mpz_set (mpq_numref (scaling_factor.val), scale_num.val);
18469   mpz_set (mpq_denref (scaling_factor.val), scale_denom.val);
18470   mpq_canonicalize (scaling_factor.val);
18471 }
18472
18473 /* The gnat-encoding suffix for fixed point.  */
18474
18475 #define GNAT_FIXED_POINT_SUFFIX "___XF_"
18476
18477 /* If NAME encodes an Ada fixed-point type, return a pointer to the
18478    "XF" suffix of the name.  The text after this is what encodes the
18479    'small and 'delta information.  Otherwise, return nullptr.  */
18480
18481 static const char *
18482 gnat_encoded_fixed_point_type_info (const char *name)
18483 {
18484   return strstr (name, GNAT_FIXED_POINT_SUFFIX);
18485 }
18486
18487 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
18488    (which may be different from NAME) to the architecture back-end to allow
18489    it to guess the correct format if necessary.  */
18490
18491 static struct type *
18492 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
18493                         const char *name_hint, enum bfd_endian byte_order)
18494 {
18495   struct gdbarch *gdbarch = objfile->arch ();
18496   const struct floatformat **format;
18497   struct type *type;
18498
18499   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
18500   if (format)
18501     type = init_float_type (objfile, bits, name, format, byte_order);
18502   else
18503     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
18504
18505   return type;
18506 }
18507
18508 /* Allocate an integer type of size BITS and name NAME.  */
18509
18510 static struct type *
18511 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
18512                           int bits, int unsigned_p, const char *name)
18513 {
18514   struct type *type;
18515
18516   /* Versions of Intel's C Compiler generate an integer type called "void"
18517      instead of using DW_TAG_unspecified_type.  This has been seen on
18518      at least versions 14, 17, and 18.  */
18519   if (bits == 0 && producer_is_icc (cu) && name != nullptr
18520       && strcmp (name, "void") == 0)
18521     type = objfile_type (objfile)->builtin_void;
18522   else
18523     type = init_integer_type (objfile, bits, unsigned_p, name);
18524
18525   return type;
18526 }
18527
18528 /* Return true if DIE has a DW_AT_small attribute whose value is
18529    a constant rational, where both the numerator and denominator
18530    are equal to zero.
18531
18532    CU is the DIE's Compilation Unit.  */
18533
18534 static bool
18535 has_zero_over_zero_small_attribute (struct die_info *die,
18536                                     struct dwarf2_cu *cu)
18537 {
18538   struct attribute *attr = dwarf2_attr (die, DW_AT_small, cu);
18539   if (attr == nullptr)
18540     return false;
18541
18542   struct dwarf2_cu *scale_cu = cu;
18543   struct die_info *scale_die
18544     = follow_die_ref (die, attr, &scale_cu);
18545
18546   if (scale_die->tag != DW_TAG_constant)
18547     return false;
18548
18549   gdb_mpz num (1), denom (1);
18550   get_dwarf2_rational_constant (scale_die, cu, &num, &denom);
18551   return mpz_sgn (num.val) == 0 && mpz_sgn (denom.val) == 0;
18552 }
18553
18554 /* Initialise and return a floating point type of size BITS suitable for
18555    use as a component of a complex number.  The NAME_HINT is passed through
18556    when initialising the floating point type and is the name of the complex
18557    type.
18558
18559    As DWARF doesn't currently provide an explicit name for the components
18560    of a complex number, but it can be helpful to have these components
18561    named, we try to select a suitable name based on the size of the
18562    component.  */
18563 static struct type *
18564 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
18565                                  struct objfile *objfile,
18566                                  int bits, const char *name_hint,
18567                                  enum bfd_endian byte_order)
18568 {
18569   gdbarch *gdbarch = objfile->arch ();
18570   struct type *tt = nullptr;
18571
18572   /* Try to find a suitable floating point builtin type of size BITS.
18573      We're going to use the name of this type as the name for the complex
18574      target type that we are about to create.  */
18575   switch (cu->language)
18576     {
18577     case language_fortran:
18578       switch (bits)
18579         {
18580         case 32:
18581           tt = builtin_f_type (gdbarch)->builtin_real;
18582           break;
18583         case 64:
18584           tt = builtin_f_type (gdbarch)->builtin_real_s8;
18585           break;
18586         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
18587         case 128:
18588           tt = builtin_f_type (gdbarch)->builtin_real_s16;
18589           break;
18590         }
18591       break;
18592     default:
18593       switch (bits)
18594         {
18595         case 32:
18596           tt = builtin_type (gdbarch)->builtin_float;
18597           break;
18598         case 64:
18599           tt = builtin_type (gdbarch)->builtin_double;
18600           break;
18601         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
18602         case 128:
18603           tt = builtin_type (gdbarch)->builtin_long_double;
18604           break;
18605         }
18606       break;
18607     }
18608
18609   /* If the type we found doesn't match the size we were looking for, then
18610      pretend we didn't find a type at all, the complex target type we
18611      create will then be nameless.  */
18612   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
18613     tt = nullptr;
18614
18615   const char *name = (tt == nullptr) ? nullptr : tt->name ();
18616   return dwarf2_init_float_type (objfile, bits, name, name_hint, byte_order);
18617 }
18618
18619 /* Find a representation of a given base type and install
18620    it in the TYPE field of the die.  */
18621
18622 static struct type *
18623 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
18624 {
18625   struct objfile *objfile = cu->per_objfile->objfile;
18626   struct type *type;
18627   struct attribute *attr;
18628   int encoding = 0, bits = 0;
18629   const char *name;
18630   gdbarch *arch;
18631
18632   attr = dwarf2_attr (die, DW_AT_encoding, cu);
18633   if (attr != nullptr && attr->form_is_constant ())
18634     encoding = attr->constant_value (0);
18635   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
18636   if (attr != nullptr)
18637     bits = attr->constant_value (0) * TARGET_CHAR_BIT;
18638   name = dwarf2_name (die, cu);
18639   if (!name)
18640     complaint (_("DW_AT_name missing from DW_TAG_base_type"));
18641
18642   arch = objfile->arch ();
18643   enum bfd_endian byte_order = gdbarch_byte_order (arch);
18644
18645   attr = dwarf2_attr (die, DW_AT_endianity, cu);
18646   if (attr != nullptr && attr->form_is_constant ())
18647     {
18648       int endianity = attr->constant_value (0);
18649
18650       switch (endianity)
18651         {
18652         case DW_END_big:
18653           byte_order = BFD_ENDIAN_BIG;
18654           break;
18655         case DW_END_little:
18656           byte_order = BFD_ENDIAN_LITTLE;
18657           break;
18658         default:
18659           complaint (_("DW_AT_endianity has unrecognized value %d"), endianity);
18660           break;
18661         }
18662     }
18663
18664   if ((encoding == DW_ATE_signed_fixed || encoding == DW_ATE_unsigned_fixed)
18665       && cu->language == language_ada
18666       && has_zero_over_zero_small_attribute (die, cu))
18667     {
18668       /* brobecker/2018-02-24: This is a fixed point type for which
18669          the scaling factor is represented as fraction whose value
18670          does not make sense (zero divided by zero), so we should
18671          normally never see these.  However, there is a small category
18672          of fixed point types for which GNAT is unable to provide
18673          the scaling factor via the standard DWARF mechanisms, and
18674          for which the info is provided via the GNAT encodings instead.
18675          This is likely what this DIE is about.  */
18676       encoding = (encoding == DW_ATE_signed_fixed
18677                   ? DW_ATE_signed
18678                   : DW_ATE_unsigned);
18679     }
18680
18681   /* With GNAT encodings, fixed-point information will be encoded in
18682      the type name.  Note that this can also occur with the above
18683      zero-over-zero case, which is why this is a separate "if" rather
18684      than an "else if".  */
18685   const char *gnat_encoding_suffix = nullptr;
18686   if ((encoding == DW_ATE_signed || encoding == DW_ATE_unsigned)
18687       && cu->language == language_ada
18688       && name != nullptr)
18689     {
18690       gnat_encoding_suffix = gnat_encoded_fixed_point_type_info (name);
18691       if (gnat_encoding_suffix != nullptr)
18692         {
18693           gdb_assert (startswith (gnat_encoding_suffix,
18694                                   GNAT_FIXED_POINT_SUFFIX));
18695           name = obstack_strndup (&cu->per_objfile->objfile->objfile_obstack,
18696                                   name, gnat_encoding_suffix - name);
18697           /* Use -1 here so that SUFFIX points at the "_" after the
18698              "XF".  */
18699           gnat_encoding_suffix += strlen (GNAT_FIXED_POINT_SUFFIX) - 1;
18700
18701           encoding = (encoding == DW_ATE_signed
18702                       ? DW_ATE_signed_fixed
18703                       : DW_ATE_unsigned_fixed);
18704         }
18705     }
18706
18707   switch (encoding)
18708     {
18709       case DW_ATE_address:
18710         /* Turn DW_ATE_address into a void * pointer.  */
18711         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
18712         type = init_pointer_type (objfile, bits, name, type);
18713         break;
18714       case DW_ATE_boolean:
18715         type = init_boolean_type (objfile, bits, 1, name);
18716         break;
18717       case DW_ATE_complex_float:
18718         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name,
18719                                                 byte_order);
18720         if (type->code () == TYPE_CODE_ERROR)
18721           {
18722             if (name == nullptr)
18723               {
18724                 struct obstack *obstack
18725                   = &cu->per_objfile->objfile->objfile_obstack;
18726                 name = obconcat (obstack, "_Complex ", type->name (),
18727                                  nullptr);
18728               }
18729             type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
18730           }
18731         else
18732           type = init_complex_type (name, type);
18733         break;
18734       case DW_ATE_decimal_float:
18735         type = init_decfloat_type (objfile, bits, name);
18736         break;
18737       case DW_ATE_float:
18738         type = dwarf2_init_float_type (objfile, bits, name, name, byte_order);
18739         break;
18740       case DW_ATE_signed:
18741         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
18742         break;
18743       case DW_ATE_unsigned:
18744         if (cu->language == language_fortran
18745             && name
18746             && startswith (name, "character("))
18747           type = init_character_type (objfile, bits, 1, name);
18748         else
18749           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18750         break;
18751       case DW_ATE_signed_char:
18752         if (cu->language == language_ada || cu->language == language_m2
18753             || cu->language == language_pascal
18754             || cu->language == language_fortran)
18755           type = init_character_type (objfile, bits, 0, name);
18756         else
18757           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
18758         break;
18759       case DW_ATE_unsigned_char:
18760         if (cu->language == language_ada || cu->language == language_m2
18761             || cu->language == language_pascal
18762             || cu->language == language_fortran
18763             || cu->language == language_rust)
18764           type = init_character_type (objfile, bits, 1, name);
18765         else
18766           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18767         break;
18768       case DW_ATE_UTF:
18769         {
18770           if (bits == 16)
18771             type = builtin_type (arch)->builtin_char16;
18772           else if (bits == 32)
18773             type = builtin_type (arch)->builtin_char32;
18774           else
18775             {
18776               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
18777                          bits);
18778               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18779             }
18780           return set_die_type (die, type, cu);
18781         }
18782         break;
18783       case DW_ATE_signed_fixed:
18784         type = init_fixed_point_type (objfile, bits, 0, name);
18785         finish_fixed_point_type (type, gnat_encoding_suffix, die, cu);
18786         break;
18787       case DW_ATE_unsigned_fixed:
18788         type = init_fixed_point_type (objfile, bits, 1, name);
18789         finish_fixed_point_type (type, gnat_encoding_suffix, die, cu);
18790         break;
18791
18792       default:
18793         complaint (_("unsupported DW_AT_encoding: '%s'"),
18794                    dwarf_type_encoding_name (encoding));
18795         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
18796         break;
18797     }
18798
18799   if (name && strcmp (name, "char") == 0)
18800     type->set_has_no_signedness (true);
18801
18802   maybe_set_alignment (cu, die, type);
18803
18804   type->set_endianity_is_not_default (gdbarch_byte_order (arch) != byte_order);
18805
18806   if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_INT)
18807     {
18808       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
18809       if (attr != nullptr && attr->as_unsigned () <= 8 * TYPE_LENGTH (type))
18810         {
18811           unsigned real_bit_size = attr->as_unsigned ();
18812           attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
18813           /* Only use the attributes if they make sense together.  */
18814           if (attr == nullptr
18815               || (attr->as_unsigned () + real_bit_size
18816                   <= 8 * TYPE_LENGTH (type)))
18817             {
18818               TYPE_MAIN_TYPE (type)->type_specific.int_stuff.bit_size
18819                 = real_bit_size;
18820               if (attr != nullptr)
18821                 TYPE_MAIN_TYPE (type)->type_specific.int_stuff.bit_offset
18822                   = attr->as_unsigned ();
18823             }
18824         }
18825     }
18826
18827   return set_die_type (die, type, cu);
18828 }
18829
18830 /* Parse dwarf attribute if it's a block, reference or constant and put the
18831    resulting value of the attribute into struct bound_prop.
18832    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
18833
18834 static int
18835 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
18836                       struct dwarf2_cu *cu, struct dynamic_prop *prop,
18837                       struct type *default_type)
18838 {
18839   struct dwarf2_property_baton *baton;
18840   dwarf2_per_objfile *per_objfile = cu->per_objfile;
18841   struct objfile *objfile = per_objfile->objfile;
18842   struct obstack *obstack = &objfile->objfile_obstack;
18843
18844   gdb_assert (default_type != NULL);
18845
18846   if (attr == NULL || prop == NULL)
18847     return 0;
18848
18849   if (attr->form_is_block ())
18850     {
18851       baton = XOBNEW (obstack, struct dwarf2_property_baton);
18852       baton->property_type = default_type;
18853       baton->locexpr.per_cu = cu->per_cu;
18854       baton->locexpr.per_objfile = per_objfile;
18855
18856       struct dwarf_block *block = attr->as_block ();
18857       baton->locexpr.size = block->size;
18858       baton->locexpr.data = block->data;
18859       switch (attr->name)
18860         {
18861         case DW_AT_string_length:
18862           baton->locexpr.is_reference = true;
18863           break;
18864         default:
18865           baton->locexpr.is_reference = false;
18866           break;
18867         }
18868
18869       prop->set_locexpr (baton);
18870       gdb_assert (prop->baton () != NULL);
18871     }
18872   else if (attr->form_is_ref ())
18873     {
18874       struct dwarf2_cu *target_cu = cu;
18875       struct die_info *target_die;
18876       struct attribute *target_attr;
18877
18878       target_die = follow_die_ref (die, attr, &target_cu);
18879       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
18880       if (target_attr == NULL)
18881         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
18882                                    target_cu);
18883       if (target_attr == NULL)
18884         return 0;
18885
18886       switch (target_attr->name)
18887         {
18888           case DW_AT_location:
18889             if (target_attr->form_is_section_offset ())
18890               {
18891                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
18892                 baton->property_type = die_type (target_die, target_cu);
18893                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
18894                 prop->set_loclist (baton);
18895                 gdb_assert (prop->baton () != NULL);
18896               }
18897             else if (target_attr->form_is_block ())
18898               {
18899                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
18900                 baton->property_type = die_type (target_die, target_cu);
18901                 baton->locexpr.per_cu = cu->per_cu;
18902                 baton->locexpr.per_objfile = per_objfile;
18903                 struct dwarf_block *block = target_attr->as_block ();
18904                 baton->locexpr.size = block->size;
18905                 baton->locexpr.data = block->data;
18906                 baton->locexpr.is_reference = true;
18907                 prop->set_locexpr (baton);
18908                 gdb_assert (prop->baton () != NULL);
18909               }
18910             else
18911               {
18912                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18913                                                        "dynamic property");
18914                 return 0;
18915               }
18916             break;
18917           case DW_AT_data_member_location:
18918             {
18919               LONGEST offset;
18920
18921               if (!handle_data_member_location (target_die, target_cu,
18922                                                 &offset))
18923                 return 0;
18924
18925               baton = XOBNEW (obstack, struct dwarf2_property_baton);
18926               baton->property_type = read_type_die (target_die->parent,
18927                                                       target_cu);
18928               baton->offset_info.offset = offset;
18929               baton->offset_info.type = die_type (target_die, target_cu);
18930               prop->set_addr_offset (baton);
18931               break;
18932             }
18933         }
18934     }
18935   else if (attr->form_is_constant ())
18936     prop->set_const_val (attr->constant_value (0));
18937   else
18938     {
18939       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
18940                                              dwarf2_name (die, cu));
18941       return 0;
18942     }
18943
18944   return 1;
18945 }
18946
18947 /* See read.h.  */
18948
18949 struct type *
18950 dwarf2_per_objfile::int_type (int size_in_bytes, bool unsigned_p) const
18951 {
18952   struct type *int_type;
18953
18954   /* Helper macro to examine the various builtin types.  */
18955 #define TRY_TYPE(F)                                                     \
18956   int_type = (unsigned_p                                                \
18957               ? objfile_type (objfile)->builtin_unsigned_ ## F          \
18958               : objfile_type (objfile)->builtin_ ## F);                 \
18959   if (int_type != NULL && TYPE_LENGTH (int_type) == size_in_bytes)      \
18960     return int_type
18961
18962   TRY_TYPE (char);
18963   TRY_TYPE (short);
18964   TRY_TYPE (int);
18965   TRY_TYPE (long);
18966   TRY_TYPE (long_long);
18967
18968 #undef TRY_TYPE
18969
18970   gdb_assert_not_reached ("unable to find suitable integer type");
18971 }
18972
18973 /* See read.h.  */
18974
18975 struct type *
18976 dwarf2_cu::addr_sized_int_type (bool unsigned_p) const
18977 {
18978   int addr_size = this->per_cu->addr_size ();
18979   return this->per_objfile->int_type (addr_size, unsigned_p);
18980 }
18981
18982 /* Read the DW_AT_type attribute for a sub-range.  If this attribute is not
18983    present (which is valid) then compute the default type based on the
18984    compilation units address size.  */
18985
18986 static struct type *
18987 read_subrange_index_type (struct die_info *die, struct dwarf2_cu *cu)
18988 {
18989   struct type *index_type = die_type (die, cu);
18990
18991   /* Dwarf-2 specifications explicitly allows to create subrange types
18992      without specifying a base type.
18993      In that case, the base type must be set to the type of
18994      the lower bound, upper bound or count, in that order, if any of these
18995      three attributes references an object that has a type.
18996      If no base type is found, the Dwarf-2 specifications say that
18997      a signed integer type of size equal to the size of an address should
18998      be used.
18999      For the following C code: `extern char gdb_int [];'
19000      GCC produces an empty range DIE.
19001      FIXME: muller/2010-05-28: Possible references to object for low bound,
19002      high bound or count are not yet handled by this code.  */
19003   if (index_type->code () == TYPE_CODE_VOID)
19004     index_type = cu->addr_sized_int_type (false);
19005
19006   return index_type;
19007 }
19008
19009 /* Read the given DW_AT_subrange DIE.  */
19010
19011 static struct type *
19012 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
19013 {
19014   struct type *base_type, *orig_base_type;
19015   struct type *range_type;
19016   struct attribute *attr;
19017   struct dynamic_prop low, high;
19018   int low_default_is_valid;
19019   int high_bound_is_count = 0;
19020   const char *name;
19021   ULONGEST negative_mask;
19022
19023   orig_base_type = read_subrange_index_type (die, cu);
19024
19025   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
19026      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
19027      creating the range type, but we use the result of check_typedef
19028      when examining properties of the type.  */
19029   base_type = check_typedef (orig_base_type);
19030
19031   /* The die_type call above may have already set the type for this DIE.  */
19032   range_type = get_die_type (die, cu);
19033   if (range_type)
19034     return range_type;
19035
19036   high.set_const_val (0);
19037
19038   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
19039      omitting DW_AT_lower_bound.  */
19040   switch (cu->language)
19041     {
19042     case language_c:
19043     case language_cplus:
19044       low.set_const_val (0);
19045       low_default_is_valid = 1;
19046       break;
19047     case language_fortran:
19048       low.set_const_val (1);
19049       low_default_is_valid = 1;
19050       break;
19051     case language_d:
19052     case language_objc:
19053     case language_rust:
19054       low.set_const_val (0);
19055       low_default_is_valid = (cu->header.version >= 4);
19056       break;
19057     case language_ada:
19058     case language_m2:
19059     case language_pascal:
19060       low.set_const_val (1);
19061       low_default_is_valid = (cu->header.version >= 4);
19062       break;
19063     default:
19064       low.set_const_val (0);
19065       low_default_is_valid = 0;
19066       break;
19067     }
19068
19069   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
19070   if (attr != nullptr)
19071     attr_to_dynamic_prop (attr, die, cu, &low, base_type);
19072   else if (!low_default_is_valid)
19073     complaint (_("Missing DW_AT_lower_bound "
19074                                       "- DIE at %s [in module %s]"),
19075                sect_offset_str (die->sect_off),
19076                objfile_name (cu->per_objfile->objfile));
19077
19078   struct attribute *attr_ub, *attr_count;
19079   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
19080   if (!attr_to_dynamic_prop (attr, die, cu, &high, base_type))
19081     {
19082       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
19083       if (attr_to_dynamic_prop (attr, die, cu, &high, base_type))
19084         {
19085           /* If bounds are constant do the final calculation here.  */
19086           if (low.kind () == PROP_CONST && high.kind () == PROP_CONST)
19087             high.set_const_val (low.const_val () + high.const_val () - 1);
19088           else
19089             high_bound_is_count = 1;
19090         }
19091       else
19092         {
19093           if (attr_ub != NULL)
19094             complaint (_("Unresolved DW_AT_upper_bound "
19095                          "- DIE at %s [in module %s]"),
19096                        sect_offset_str (die->sect_off),
19097                        objfile_name (cu->per_objfile->objfile));
19098           if (attr_count != NULL)
19099             complaint (_("Unresolved DW_AT_count "
19100                          "- DIE at %s [in module %s]"),
19101                        sect_offset_str (die->sect_off),
19102                        objfile_name (cu->per_objfile->objfile));
19103         }
19104     }
19105
19106   LONGEST bias = 0;
19107   struct attribute *bias_attr = dwarf2_attr (die, DW_AT_GNU_bias, cu);
19108   if (bias_attr != nullptr && bias_attr->form_is_constant ())
19109     bias = bias_attr->constant_value (0);
19110
19111   /* Normally, the DWARF producers are expected to use a signed
19112      constant form (Eg. DW_FORM_sdata) to express negative bounds.
19113      But this is unfortunately not always the case, as witnessed
19114      with GCC, for instance, where the ambiguous DW_FORM_dataN form
19115      is used instead.  To work around that ambiguity, we treat
19116      the bounds as signed, and thus sign-extend their values, when
19117      the base type is signed.  */
19118   negative_mask =
19119     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
19120   if (low.kind () == PROP_CONST
19121       && !base_type->is_unsigned () && (low.const_val () & negative_mask))
19122     low.set_const_val (low.const_val () | negative_mask);
19123   if (high.kind () == PROP_CONST
19124       && !base_type->is_unsigned () && (high.const_val () & negative_mask))
19125     high.set_const_val (high.const_val () | negative_mask);
19126
19127   /* Check for bit and byte strides.  */
19128   struct dynamic_prop byte_stride_prop;
19129   attribute *attr_byte_stride = dwarf2_attr (die, DW_AT_byte_stride, cu);
19130   if (attr_byte_stride != nullptr)
19131     {
19132       struct type *prop_type = cu->addr_sized_int_type (false);
19133       attr_to_dynamic_prop (attr_byte_stride, die, cu, &byte_stride_prop,
19134                             prop_type);
19135     }
19136
19137   struct dynamic_prop bit_stride_prop;
19138   attribute *attr_bit_stride = dwarf2_attr (die, DW_AT_bit_stride, cu);
19139   if (attr_bit_stride != nullptr)
19140     {
19141       /* It only makes sense to have either a bit or byte stride.  */
19142       if (attr_byte_stride != nullptr)
19143         {
19144           complaint (_("Found DW_AT_bit_stride and DW_AT_byte_stride "
19145                        "- DIE at %s [in module %s]"),
19146                      sect_offset_str (die->sect_off),
19147                      objfile_name (cu->per_objfile->objfile));
19148           attr_bit_stride = nullptr;
19149         }
19150       else
19151         {
19152           struct type *prop_type = cu->addr_sized_int_type (false);
19153           attr_to_dynamic_prop (attr_bit_stride, die, cu, &bit_stride_prop,
19154                                 prop_type);
19155         }
19156     }
19157
19158   if (attr_byte_stride != nullptr
19159       || attr_bit_stride != nullptr)
19160     {
19161       bool byte_stride_p = (attr_byte_stride != nullptr);
19162       struct dynamic_prop *stride
19163         = byte_stride_p ? &byte_stride_prop : &bit_stride_prop;
19164
19165       range_type
19166         = create_range_type_with_stride (NULL, orig_base_type, &low,
19167                                          &high, bias, stride, byte_stride_p);
19168     }
19169   else
19170     range_type = create_range_type (NULL, orig_base_type, &low, &high, bias);
19171
19172   if (high_bound_is_count)
19173     range_type->bounds ()->flag_upper_bound_is_count = 1;
19174
19175   /* Ada expects an empty array on no boundary attributes.  */
19176   if (attr == NULL && cu->language != language_ada)
19177     range_type->bounds ()->high.set_undefined ();
19178
19179   name = dwarf2_name (die, cu);
19180   if (name)
19181     range_type->set_name (name);
19182
19183   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
19184   if (attr != nullptr)
19185     TYPE_LENGTH (range_type) = attr->constant_value (0);
19186
19187   maybe_set_alignment (cu, die, range_type);
19188
19189   set_die_type (die, range_type, cu);
19190
19191   /* set_die_type should be already done.  */
19192   set_descriptive_type (range_type, die, cu);
19193
19194   return range_type;
19195 }
19196
19197 static struct type *
19198 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
19199 {
19200   struct type *type;
19201
19202   type = init_type (cu->per_objfile->objfile, TYPE_CODE_VOID, 0, NULL);
19203   type->set_name (dwarf2_name (die, cu));
19204
19205   /* In Ada, an unspecified type is typically used when the description
19206      of the type is deferred to a different unit.  When encountering
19207      such a type, we treat it as a stub, and try to resolve it later on,
19208      when needed.  */
19209   if (cu->language == language_ada)
19210     type->set_is_stub (true);
19211
19212   return set_die_type (die, type, cu);
19213 }
19214
19215 /* Read a single die and all its descendents.  Set the die's sibling
19216    field to NULL; set other fields in the die correctly, and set all
19217    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
19218    location of the info_ptr after reading all of those dies.  PARENT
19219    is the parent of the die in question.  */
19220
19221 static struct die_info *
19222 read_die_and_children (const struct die_reader_specs *reader,
19223                        const gdb_byte *info_ptr,
19224                        const gdb_byte **new_info_ptr,
19225                        struct die_info *parent)
19226 {
19227   struct die_info *die;
19228   const gdb_byte *cur_ptr;
19229
19230   cur_ptr = read_full_die_1 (reader, &die, info_ptr, 0);
19231   if (die == NULL)
19232     {
19233       *new_info_ptr = cur_ptr;
19234       return NULL;
19235     }
19236   store_in_ref_table (die, reader->cu);
19237
19238   if (die->has_children)
19239     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
19240   else
19241     {
19242       die->child = NULL;
19243       *new_info_ptr = cur_ptr;
19244     }
19245
19246   die->sibling = NULL;
19247   die->parent = parent;
19248   return die;
19249 }
19250
19251 /* Read a die, all of its descendents, and all of its siblings; set
19252    all of the fields of all of the dies correctly.  Arguments are as
19253    in read_die_and_children.  */
19254
19255 static struct die_info *
19256 read_die_and_siblings_1 (const struct die_reader_specs *reader,
19257                          const gdb_byte *info_ptr,
19258                          const gdb_byte **new_info_ptr,
19259                          struct die_info *parent)
19260 {
19261   struct die_info *first_die, *last_sibling;
19262   const gdb_byte *cur_ptr;
19263
19264   cur_ptr = info_ptr;
19265   first_die = last_sibling = NULL;
19266
19267   while (1)
19268     {
19269       struct die_info *die
19270         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
19271
19272       if (die == NULL)
19273         {
19274           *new_info_ptr = cur_ptr;
19275           return first_die;
19276         }
19277
19278       if (!first_die)
19279         first_die = die;
19280       else
19281         last_sibling->sibling = die;
19282
19283       last_sibling = die;
19284     }
19285 }
19286
19287 /* Read a die, all of its descendents, and all of its siblings; set
19288    all of the fields of all of the dies correctly.  Arguments are as
19289    in read_die_and_children.
19290    This the main entry point for reading a DIE and all its children.  */
19291
19292 static struct die_info *
19293 read_die_and_siblings (const struct die_reader_specs *reader,
19294                        const gdb_byte *info_ptr,
19295                        const gdb_byte **new_info_ptr,
19296                        struct die_info *parent)
19297 {
19298   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
19299                                                   new_info_ptr, parent);
19300
19301   if (dwarf_die_debug)
19302     {
19303       fprintf_unfiltered (gdb_stdlog,
19304                           "Read die from %s@0x%x of %s:\n",
19305                           reader->die_section->get_name (),
19306                           (unsigned) (info_ptr - reader->die_section->buffer),
19307                           bfd_get_filename (reader->abfd));
19308       dump_die (die, dwarf_die_debug);
19309     }
19310
19311   return die;
19312 }
19313
19314 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
19315    attributes.
19316    The caller is responsible for filling in the extra attributes
19317    and updating (*DIEP)->num_attrs.
19318    Set DIEP to point to a newly allocated die with its information,
19319    except for its child, sibling, and parent fields.  */
19320
19321 static const gdb_byte *
19322 read_full_die_1 (const struct die_reader_specs *reader,
19323                  struct die_info **diep, const gdb_byte *info_ptr,
19324                  int num_extra_attrs)
19325 {
19326   unsigned int abbrev_number, bytes_read, i;
19327   const struct abbrev_info *abbrev;
19328   struct die_info *die;
19329   struct dwarf2_cu *cu = reader->cu;
19330   bfd *abfd = reader->abfd;
19331
19332   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
19333   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19334   info_ptr += bytes_read;
19335   if (!abbrev_number)
19336     {
19337       *diep = NULL;
19338       return info_ptr;
19339     }
19340
19341   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
19342   if (!abbrev)
19343     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
19344            abbrev_number,
19345            bfd_get_filename (abfd));
19346
19347   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
19348   die->sect_off = sect_off;
19349   die->tag = abbrev->tag;
19350   die->abbrev = abbrev_number;
19351   die->has_children = abbrev->has_children;
19352
19353   /* Make the result usable.
19354      The caller needs to update num_attrs after adding the extra
19355      attributes.  */
19356   die->num_attrs = abbrev->num_attrs;
19357
19358   bool any_need_reprocess = false;
19359   for (i = 0; i < abbrev->num_attrs; ++i)
19360     {
19361       info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
19362                                  info_ptr);
19363       if (die->attrs[i].requires_reprocessing_p ())
19364         any_need_reprocess = true;
19365     }
19366
19367   struct attribute *attr = die->attr (DW_AT_str_offsets_base);
19368   if (attr != nullptr && attr->form_is_unsigned ())
19369     cu->str_offsets_base = attr->as_unsigned ();
19370
19371   attr = die->attr (DW_AT_loclists_base);
19372   if (attr != nullptr)
19373     cu->loclist_base = attr->as_unsigned ();
19374
19375   auto maybe_addr_base = die->addr_base ();
19376   if (maybe_addr_base.has_value ())
19377     cu->addr_base = *maybe_addr_base;
19378
19379   attr = die->attr (DW_AT_rnglists_base);
19380   if (attr != nullptr)
19381     cu->rnglists_base = attr->as_unsigned ();
19382
19383   if (any_need_reprocess)
19384     {
19385       for (i = 0; i < abbrev->num_attrs; ++i)
19386         {
19387           if (die->attrs[i].requires_reprocessing_p ())
19388             read_attribute_reprocess (reader, &die->attrs[i], die->tag);
19389         }
19390     }
19391   *diep = die;
19392   return info_ptr;
19393 }
19394
19395 /* Read a die and all its attributes.
19396    Set DIEP to point to a newly allocated die with its information,
19397    except for its child, sibling, and parent fields.  */
19398
19399 static const gdb_byte *
19400 read_full_die (const struct die_reader_specs *reader,
19401                struct die_info **diep, const gdb_byte *info_ptr)
19402 {
19403   const gdb_byte *result;
19404
19405   result = read_full_die_1 (reader, diep, info_ptr, 0);
19406
19407   if (dwarf_die_debug)
19408     {
19409       fprintf_unfiltered (gdb_stdlog,
19410                           "Read die from %s@0x%x of %s:\n",
19411                           reader->die_section->get_name (),
19412                           (unsigned) (info_ptr - reader->die_section->buffer),
19413                           bfd_get_filename (reader->abfd));
19414       dump_die (*diep, dwarf_die_debug);
19415     }
19416
19417   return result;
19418 }
19419 \f
19420
19421 /* Returns nonzero if TAG represents a type that we might generate a partial
19422    symbol for.  */
19423
19424 static int
19425 is_type_tag_for_partial (int tag, enum language lang)
19426 {
19427   switch (tag)
19428     {
19429 #if 0
19430     /* Some types that would be reasonable to generate partial symbols for,
19431        that we don't at present.  Note that normally this does not
19432        matter, mainly because C compilers don't give names to these
19433        types, but instead emit DW_TAG_typedef.  */
19434     case DW_TAG_file_type:
19435     case DW_TAG_ptr_to_member_type:
19436     case DW_TAG_set_type:
19437     case DW_TAG_string_type:
19438     case DW_TAG_subroutine_type:
19439 #endif
19440
19441       /* GNAT may emit an array with a name, but no typedef, so we
19442          need to make a symbol in this case.  */
19443     case DW_TAG_array_type:
19444       return lang == language_ada;
19445
19446     case DW_TAG_base_type:
19447     case DW_TAG_class_type:
19448     case DW_TAG_interface_type:
19449     case DW_TAG_enumeration_type:
19450     case DW_TAG_structure_type:
19451     case DW_TAG_subrange_type:
19452     case DW_TAG_typedef:
19453     case DW_TAG_union_type:
19454       return 1;
19455     default:
19456       return 0;
19457     }
19458 }
19459
19460 /* Load all DIEs that are interesting for partial symbols into memory.  */
19461
19462 static struct partial_die_info *
19463 load_partial_dies (const struct die_reader_specs *reader,
19464                    const gdb_byte *info_ptr, int building_psymtab)
19465 {
19466   struct dwarf2_cu *cu = reader->cu;
19467   struct objfile *objfile = cu->per_objfile->objfile;
19468   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
19469   unsigned int bytes_read;
19470   unsigned int load_all = 0;
19471   int nesting_level = 1;
19472
19473   parent_die = NULL;
19474   last_die = NULL;
19475
19476   gdb_assert (cu->per_cu != NULL);
19477   if (cu->per_cu->load_all_dies)
19478     load_all = 1;
19479
19480   cu->partial_dies
19481     = htab_create_alloc_ex (cu->header.length / 12,
19482                             partial_die_hash,
19483                             partial_die_eq,
19484                             NULL,
19485                             &cu->comp_unit_obstack,
19486                             hashtab_obstack_allocate,
19487                             dummy_obstack_deallocate);
19488
19489   while (1)
19490     {
19491       const abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr,
19492                                                    &bytes_read);
19493
19494       /* A NULL abbrev means the end of a series of children.  */
19495       if (abbrev == NULL)
19496         {
19497           if (--nesting_level == 0)
19498             return first_die;
19499
19500           info_ptr += bytes_read;
19501           last_die = parent_die;
19502           parent_die = parent_die->die_parent;
19503           continue;
19504         }
19505
19506       /* Check for template arguments.  We never save these; if
19507          they're seen, we just mark the parent, and go on our way.  */
19508       if (parent_die != NULL
19509           && cu->language == language_cplus
19510           && (abbrev->tag == DW_TAG_template_type_param
19511               || abbrev->tag == DW_TAG_template_value_param))
19512         {
19513           parent_die->has_template_arguments = 1;
19514
19515           if (!load_all)
19516             {
19517               /* We don't need a partial DIE for the template argument.  */
19518               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
19519               continue;
19520             }
19521         }
19522
19523       /* We only recurse into c++ subprograms looking for template arguments.
19524          Skip their other children.  */
19525       if (!load_all
19526           && cu->language == language_cplus
19527           && parent_die != NULL
19528           && parent_die->tag == DW_TAG_subprogram
19529           && abbrev->tag != DW_TAG_inlined_subroutine)
19530         {
19531           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
19532           continue;
19533         }
19534
19535       /* Check whether this DIE is interesting enough to save.  Normally
19536          we would not be interested in members here, but there may be
19537          later variables referencing them via DW_AT_specification (for
19538          static members).  */
19539       if (!load_all
19540           && !is_type_tag_for_partial (abbrev->tag, cu->language)
19541           && abbrev->tag != DW_TAG_constant
19542           && abbrev->tag != DW_TAG_enumerator
19543           && abbrev->tag != DW_TAG_subprogram
19544           && abbrev->tag != DW_TAG_inlined_subroutine
19545           && abbrev->tag != DW_TAG_lexical_block
19546           && abbrev->tag != DW_TAG_variable
19547           && abbrev->tag != DW_TAG_namespace
19548           && abbrev->tag != DW_TAG_module
19549           && abbrev->tag != DW_TAG_member
19550           && abbrev->tag != DW_TAG_imported_unit
19551           && abbrev->tag != DW_TAG_imported_declaration)
19552         {
19553           /* Otherwise we skip to the next sibling, if any.  */
19554           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
19555           continue;
19556         }
19557
19558       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
19559                                    abbrev);
19560
19561       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
19562
19563       /* This two-pass algorithm for processing partial symbols has a
19564          high cost in cache pressure.  Thus, handle some simple cases
19565          here which cover the majority of C partial symbols.  DIEs
19566          which neither have specification tags in them, nor could have
19567          specification tags elsewhere pointing at them, can simply be
19568          processed and discarded.
19569
19570          This segment is also optional; scan_partial_symbols and
19571          add_partial_symbol will handle these DIEs if we chain
19572          them in normally.  When compilers which do not emit large
19573          quantities of duplicate debug information are more common,
19574          this code can probably be removed.  */
19575
19576       /* Any complete simple types at the top level (pretty much all
19577          of them, for a language without namespaces), can be processed
19578          directly.  */
19579       if (parent_die == NULL
19580           && pdi.has_specification == 0
19581           && pdi.is_declaration == 0
19582           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
19583               || pdi.tag == DW_TAG_base_type
19584               || pdi.tag == DW_TAG_array_type
19585               || pdi.tag == DW_TAG_subrange_type))
19586         {
19587           if (building_psymtab && pdi.raw_name != NULL)
19588             add_partial_symbol (&pdi, cu);
19589
19590           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
19591           continue;
19592         }
19593
19594       /* The exception for DW_TAG_typedef with has_children above is
19595          a workaround of GCC PR debug/47510.  In the case of this complaint
19596          type_name_or_error will error on such types later.
19597
19598          GDB skipped children of DW_TAG_typedef by the shortcut above and then
19599          it could not find the child DIEs referenced later, this is checked
19600          above.  In correct DWARF DW_TAG_typedef should have no children.  */
19601
19602       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
19603         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
19604                      "- DIE at %s [in module %s]"),
19605                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
19606
19607       /* If we're at the second level, and we're an enumerator, and
19608          our parent has no specification (meaning possibly lives in a
19609          namespace elsewhere), then we can add the partial symbol now
19610          instead of queueing it.  */
19611       if (pdi.tag == DW_TAG_enumerator
19612           && parent_die != NULL
19613           && parent_die->die_parent == NULL
19614           && parent_die->tag == DW_TAG_enumeration_type
19615           && parent_die->has_specification == 0)
19616         {
19617           if (pdi.raw_name == NULL)
19618             complaint (_("malformed enumerator DIE ignored"));
19619           else if (building_psymtab)
19620             add_partial_symbol (&pdi, cu);
19621
19622           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
19623           continue;
19624         }
19625
19626       struct partial_die_info *part_die
19627         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
19628
19629       /* We'll save this DIE so link it in.  */
19630       part_die->die_parent = parent_die;
19631       part_die->die_sibling = NULL;
19632       part_die->die_child = NULL;
19633
19634       if (last_die && last_die == parent_die)
19635         last_die->die_child = part_die;
19636       else if (last_die)
19637         last_die->die_sibling = part_die;
19638
19639       last_die = part_die;
19640
19641       if (first_die == NULL)
19642         first_die = part_die;
19643
19644       /* Maybe add the DIE to the hash table.  Not all DIEs that we
19645          find interesting need to be in the hash table, because we
19646          also have the parent/sibling/child chains; only those that we
19647          might refer to by offset later during partial symbol reading.
19648
19649          For now this means things that might have be the target of a
19650          DW_AT_specification, DW_AT_abstract_origin, or
19651          DW_AT_extension.  DW_AT_extension will refer only to
19652          namespaces; DW_AT_abstract_origin refers to functions (and
19653          many things under the function DIE, but we do not recurse
19654          into function DIEs during partial symbol reading) and
19655          possibly variables as well; DW_AT_specification refers to
19656          declarations.  Declarations ought to have the DW_AT_declaration
19657          flag.  It happens that GCC forgets to put it in sometimes, but
19658          only for functions, not for types.
19659
19660          Adding more things than necessary to the hash table is harmless
19661          except for the performance cost.  Adding too few will result in
19662          wasted time in find_partial_die, when we reread the compilation
19663          unit with load_all_dies set.  */
19664
19665       if (load_all
19666           || abbrev->tag == DW_TAG_constant
19667           || abbrev->tag == DW_TAG_subprogram
19668           || abbrev->tag == DW_TAG_variable
19669           || abbrev->tag == DW_TAG_namespace
19670           || part_die->is_declaration)
19671         {
19672           void **slot;
19673
19674           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
19675                                            to_underlying (part_die->sect_off),
19676                                            INSERT);
19677           *slot = part_die;
19678         }
19679
19680       /* For some DIEs we want to follow their children (if any).  For C
19681          we have no reason to follow the children of structures; for other
19682          languages we have to, so that we can get at method physnames
19683          to infer fully qualified class names, for DW_AT_specification,
19684          and for C++ template arguments.  For C++, we also look one level
19685          inside functions to find template arguments (if the name of the
19686          function does not already contain the template arguments).
19687
19688          For Ada and Fortran, we need to scan the children of subprograms
19689          and lexical blocks as well because these languages allow the
19690          definition of nested entities that could be interesting for the
19691          debugger, such as nested subprograms for instance.  */
19692       if (last_die->has_children
19693           && (load_all
19694               || last_die->tag == DW_TAG_namespace
19695               || last_die->tag == DW_TAG_module
19696               || last_die->tag == DW_TAG_enumeration_type
19697               || (cu->language == language_cplus
19698                   && last_die->tag == DW_TAG_subprogram
19699                   && (last_die->raw_name == NULL
19700                       || strchr (last_die->raw_name, '<') == NULL))
19701               || (cu->language != language_c
19702                   && (last_die->tag == DW_TAG_class_type
19703                       || last_die->tag == DW_TAG_interface_type
19704                       || last_die->tag == DW_TAG_structure_type
19705                       || last_die->tag == DW_TAG_union_type))
19706               || ((cu->language == language_ada
19707                    || cu->language == language_fortran)
19708                   && (last_die->tag == DW_TAG_subprogram
19709                       || last_die->tag == DW_TAG_lexical_block))))
19710         {
19711           nesting_level++;
19712           parent_die = last_die;
19713           continue;
19714         }
19715
19716       /* Otherwise we skip to the next sibling, if any.  */
19717       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
19718
19719       /* Back to the top, do it again.  */
19720     }
19721 }
19722
19723 partial_die_info::partial_die_info (sect_offset sect_off_,
19724                                     const struct abbrev_info *abbrev)
19725   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
19726 {
19727 }
19728
19729 /* See class definition.  */
19730
19731 const char *
19732 partial_die_info::name (dwarf2_cu *cu)
19733 {
19734   if (!canonical_name && raw_name != nullptr)
19735     {
19736       struct objfile *objfile = cu->per_objfile->objfile;
19737       raw_name = dwarf2_canonicalize_name (raw_name, cu, objfile);
19738       canonical_name = 1;
19739     }
19740
19741   return raw_name;
19742 }
19743
19744 /* Read a minimal amount of information into the minimal die structure.
19745    INFO_PTR should point just after the initial uleb128 of a DIE.  */
19746
19747 const gdb_byte *
19748 partial_die_info::read (const struct die_reader_specs *reader,
19749                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
19750 {
19751   struct dwarf2_cu *cu = reader->cu;
19752   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19753   unsigned int i;
19754   int has_low_pc_attr = 0;
19755   int has_high_pc_attr = 0;
19756   int high_pc_relative = 0;
19757
19758   for (i = 0; i < abbrev.num_attrs; ++i)
19759     {
19760       attribute attr;
19761       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
19762       /* String and address offsets that need to do the reprocessing have
19763          already been read at this point, so there is no need to wait until
19764          the loop terminates to do the reprocessing.  */
19765       if (attr.requires_reprocessing_p ())
19766         read_attribute_reprocess (reader, &attr, tag);
19767       /* Store the data if it is of an attribute we want to keep in a
19768          partial symbol table.  */
19769       switch (attr.name)
19770         {
19771         case DW_AT_name:
19772           switch (tag)
19773             {
19774             case DW_TAG_compile_unit:
19775             case DW_TAG_partial_unit:
19776             case DW_TAG_type_unit:
19777               /* Compilation units have a DW_AT_name that is a filename, not
19778                  a source language identifier.  */
19779             case DW_TAG_enumeration_type:
19780             case DW_TAG_enumerator:
19781               /* These tags always have simple identifiers already; no need
19782                  to canonicalize them.  */
19783               canonical_name = 1;
19784               raw_name = attr.as_string ();
19785               break;
19786             default:
19787               canonical_name = 0;
19788               raw_name = attr.as_string ();
19789               break;
19790             }
19791           break;
19792         case DW_AT_linkage_name:
19793         case DW_AT_MIPS_linkage_name:
19794           /* Note that both forms of linkage name might appear.  We
19795              assume they will be the same, and we only store the last
19796              one we see.  */
19797           linkage_name = attr.as_string ();
19798           break;
19799         case DW_AT_low_pc:
19800           has_low_pc_attr = 1;
19801           lowpc = attr.as_address ();
19802           break;
19803         case DW_AT_high_pc:
19804           has_high_pc_attr = 1;
19805           highpc = attr.as_address ();
19806           if (cu->header.version >= 4 && attr.form_is_constant ())
19807                 high_pc_relative = 1;
19808           break;
19809         case DW_AT_location:
19810           /* Support the .debug_loc offsets.  */
19811           if (attr.form_is_block ())
19812             {
19813               d.locdesc = attr.as_block ();
19814             }
19815           else if (attr.form_is_section_offset ())
19816             {
19817               dwarf2_complex_location_expr_complaint ();
19818             }
19819           else
19820             {
19821               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
19822                                                      "partial symbol information");
19823             }
19824           break;
19825         case DW_AT_external:
19826           is_external = attr.as_boolean ();
19827           break;
19828         case DW_AT_declaration:
19829           is_declaration = attr.as_boolean ();
19830           break;
19831         case DW_AT_type:
19832           has_type = 1;
19833           break;
19834         case DW_AT_abstract_origin:
19835         case DW_AT_specification:
19836         case DW_AT_extension:
19837           has_specification = 1;
19838           spec_offset = attr.get_ref_die_offset ();
19839           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19840                                    || cu->per_cu->is_dwz);
19841           break;
19842         case DW_AT_sibling:
19843           /* Ignore absolute siblings, they might point outside of
19844              the current compile unit.  */
19845           if (attr.form == DW_FORM_ref_addr)
19846             complaint (_("ignoring absolute DW_AT_sibling"));
19847           else
19848             {
19849               const gdb_byte *buffer = reader->buffer;
19850               sect_offset off = attr.get_ref_die_offset ();
19851               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
19852
19853               if (sibling_ptr < info_ptr)
19854                 complaint (_("DW_AT_sibling points backwards"));
19855               else if (sibling_ptr > reader->buffer_end)
19856                 reader->die_section->overflow_complaint ();
19857               else
19858                 sibling = sibling_ptr;
19859             }
19860           break;
19861         case DW_AT_byte_size:
19862           has_byte_size = 1;
19863           break;
19864         case DW_AT_const_value:
19865           has_const_value = 1;
19866           break;
19867         case DW_AT_calling_convention:
19868           /* DWARF doesn't provide a way to identify a program's source-level
19869              entry point.  DW_AT_calling_convention attributes are only meant
19870              to describe functions' calling conventions.
19871
19872              However, because it's a necessary piece of information in
19873              Fortran, and before DWARF 4 DW_CC_program was the only
19874              piece of debugging information whose definition refers to
19875              a 'main program' at all, several compilers marked Fortran
19876              main programs with DW_CC_program --- even when those
19877              functions use the standard calling conventions.
19878
19879              Although DWARF now specifies a way to provide this
19880              information, we support this practice for backward
19881              compatibility.  */
19882           if (attr.constant_value (0) == DW_CC_program
19883               && cu->language == language_fortran)
19884             main_subprogram = 1;
19885           break;
19886         case DW_AT_inline:
19887           {
19888             LONGEST value = attr.constant_value (-1);
19889             if (value == DW_INL_inlined
19890                 || value == DW_INL_declared_inlined)
19891               may_be_inlined = 1;
19892           }
19893           break;
19894
19895         case DW_AT_import:
19896           if (tag == DW_TAG_imported_unit)
19897             {
19898               d.sect_off = attr.get_ref_die_offset ();
19899               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19900                                   || cu->per_cu->is_dwz);
19901             }
19902           break;
19903
19904         case DW_AT_main_subprogram:
19905           main_subprogram = attr.as_boolean ();
19906           break;
19907
19908         case DW_AT_ranges:
19909           {
19910             /* Offset in the .debug_ranges or .debug_rnglist section (depending
19911                on DWARF version).  */
19912             ULONGEST ranges_offset = attr.as_unsigned ();
19913
19914             /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
19915                this value.  */
19916             if (tag != DW_TAG_compile_unit)
19917               ranges_offset += cu->gnu_ranges_base;
19918
19919             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
19920                                     nullptr, tag))
19921               has_pc_info = 1;
19922           }
19923           break;
19924
19925         default:
19926           break;
19927         }
19928     }
19929
19930   /* For Ada, if both the name and the linkage name appear, we prefer
19931      the latter.  This lets "catch exception" work better, regardless
19932      of the order in which the name and linkage name were emitted.
19933      Really, though, this is just a workaround for the fact that gdb
19934      doesn't store both the name and the linkage name.  */
19935   if (cu->language == language_ada && linkage_name != nullptr)
19936     raw_name = linkage_name;
19937
19938   if (high_pc_relative)
19939     highpc += lowpc;
19940
19941   if (has_low_pc_attr && has_high_pc_attr)
19942     {
19943       /* When using the GNU linker, .gnu.linkonce. sections are used to
19944          eliminate duplicate copies of functions and vtables and such.
19945          The linker will arbitrarily choose one and discard the others.
19946          The AT_*_pc values for such functions refer to local labels in
19947          these sections.  If the section from that file was discarded, the
19948          labels are not in the output, so the relocs get a value of 0.
19949          If this is a discarded function, mark the pc bounds as invalid,
19950          so that GDB will ignore it.  */
19951       if (lowpc == 0 && !per_objfile->per_bfd->has_section_at_zero)
19952         {
19953           struct objfile *objfile = per_objfile->objfile;
19954           struct gdbarch *gdbarch = objfile->arch ();
19955
19956           complaint (_("DW_AT_low_pc %s is zero "
19957                        "for DIE at %s [in module %s]"),
19958                      paddress (gdbarch, lowpc),
19959                      sect_offset_str (sect_off),
19960                      objfile_name (objfile));
19961         }
19962       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
19963       else if (lowpc >= highpc)
19964         {
19965           struct objfile *objfile = per_objfile->objfile;
19966           struct gdbarch *gdbarch = objfile->arch ();
19967
19968           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
19969                        "for DIE at %s [in module %s]"),
19970                      paddress (gdbarch, lowpc),
19971                      paddress (gdbarch, highpc),
19972                      sect_offset_str (sect_off),
19973                      objfile_name (objfile));
19974         }
19975       else
19976         has_pc_info = 1;
19977     }
19978
19979   return info_ptr;
19980 }
19981
19982 /* Find a cached partial DIE at OFFSET in CU.  */
19983
19984 struct partial_die_info *
19985 dwarf2_cu::find_partial_die (sect_offset sect_off)
19986 {
19987   struct partial_die_info *lookup_die = NULL;
19988   struct partial_die_info part_die (sect_off);
19989
19990   lookup_die = ((struct partial_die_info *)
19991                 htab_find_with_hash (partial_dies, &part_die,
19992                                      to_underlying (sect_off)));
19993
19994   return lookup_die;
19995 }
19996
19997 /* Find a partial DIE at OFFSET, which may or may not be in CU,
19998    except in the case of .debug_types DIEs which do not reference
19999    outside their CU (they do however referencing other types via
20000    DW_FORM_ref_sig8).  */
20001
20002 static const struct cu_partial_die_info
20003 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
20004 {
20005   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20006   struct objfile *objfile = per_objfile->objfile;
20007   struct partial_die_info *pd = NULL;
20008
20009   if (offset_in_dwz == cu->per_cu->is_dwz
20010       && cu->header.offset_in_cu_p (sect_off))
20011     {
20012       pd = cu->find_partial_die (sect_off);
20013       if (pd != NULL)
20014         return { cu, pd };
20015       /* We missed recording what we needed.
20016          Load all dies and try again.  */
20017     }
20018   else
20019     {
20020       /* TUs don't reference other CUs/TUs (except via type signatures).  */
20021       if (cu->per_cu->is_debug_types)
20022         {
20023           error (_("Dwarf Error: Type Unit at offset %s contains"
20024                    " external reference to offset %s [in module %s].\n"),
20025                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
20026                  bfd_get_filename (objfile->obfd));
20027         }
20028       dwarf2_per_cu_data *per_cu
20029         = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20030                                             per_objfile);
20031
20032       cu = per_objfile->get_cu (per_cu);
20033       if (cu == NULL || cu->partial_dies == NULL)
20034         load_partial_comp_unit (per_cu, per_objfile, nullptr);
20035
20036       cu = per_objfile->get_cu (per_cu);
20037
20038       cu->last_used = 0;
20039       pd = cu->find_partial_die (sect_off);
20040     }
20041
20042   /* If we didn't find it, and not all dies have been loaded,
20043      load them all and try again.  */
20044
20045   if (pd == NULL && cu->per_cu->load_all_dies == 0)
20046     {
20047       cu->per_cu->load_all_dies = 1;
20048
20049       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
20050          THIS_CU->cu may already be in use.  So we can't just free it and
20051          replace its DIEs with the ones we read in.  Instead, we leave those
20052          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
20053          and clobber THIS_CU->cu->partial_dies with the hash table for the new
20054          set.  */
20055       load_partial_comp_unit (cu->per_cu, per_objfile, cu);
20056
20057       pd = cu->find_partial_die (sect_off);
20058     }
20059
20060   if (pd == NULL)
20061     error (_("Dwarf Error: Cannot not find DIE at %s [from module %s]\n"),
20062                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
20063   return { cu, pd };
20064 }
20065
20066 /* See if we can figure out if the class lives in a namespace.  We do
20067    this by looking for a member function; its demangled name will
20068    contain namespace info, if there is any.  */
20069
20070 static void
20071 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
20072                                   struct dwarf2_cu *cu)
20073 {
20074   /* NOTE: carlton/2003-10-07: Getting the info this way changes
20075      what template types look like, because the demangler
20076      frequently doesn't give the same name as the debug info.  We
20077      could fix this by only using the demangled name to get the
20078      prefix (but see comment in read_structure_type).  */
20079
20080   struct partial_die_info *real_pdi;
20081   struct partial_die_info *child_pdi;
20082
20083   /* If this DIE (this DIE's specification, if any) has a parent, then
20084      we should not do this.  We'll prepend the parent's fully qualified
20085      name when we create the partial symbol.  */
20086
20087   real_pdi = struct_pdi;
20088   while (real_pdi->has_specification)
20089     {
20090       auto res = find_partial_die (real_pdi->spec_offset,
20091                                    real_pdi->spec_is_dwz, cu);
20092       real_pdi = res.pdi;
20093       cu = res.cu;
20094     }
20095
20096   if (real_pdi->die_parent != NULL)
20097     return;
20098
20099   for (child_pdi = struct_pdi->die_child;
20100        child_pdi != NULL;
20101        child_pdi = child_pdi->die_sibling)
20102     {
20103       if (child_pdi->tag == DW_TAG_subprogram
20104           && child_pdi->linkage_name != NULL)
20105         {
20106           gdb::unique_xmalloc_ptr<char> actual_class_name
20107             (cu->language_defn->class_name_from_physname
20108              (child_pdi->linkage_name));
20109           if (actual_class_name != NULL)
20110             {
20111               struct objfile *objfile = cu->per_objfile->objfile;
20112               struct_pdi->raw_name = objfile->intern (actual_class_name.get ());
20113               struct_pdi->canonical_name = 1;
20114             }
20115           break;
20116         }
20117     }
20118 }
20119
20120 /* Return true if a DIE with TAG may have the DW_AT_const_value
20121    attribute.  */
20122
20123 static bool
20124 can_have_DW_AT_const_value_p (enum dwarf_tag tag)
20125 {
20126   switch (tag)
20127     {
20128     case DW_TAG_constant:
20129     case DW_TAG_enumerator:
20130     case DW_TAG_formal_parameter:
20131     case DW_TAG_template_value_param:
20132     case DW_TAG_variable:
20133       return true;
20134     }
20135
20136   return false;
20137 }
20138
20139 void
20140 partial_die_info::fixup (struct dwarf2_cu *cu)
20141 {
20142   /* Once we've fixed up a die, there's no point in doing so again.
20143      This also avoids a memory leak if we were to call
20144      guess_partial_die_structure_name multiple times.  */
20145   if (fixup_called)
20146     return;
20147
20148   /* If we found a reference attribute and the DIE has no name, try
20149      to find a name in the referred to DIE.  */
20150
20151   if (raw_name == NULL && has_specification)
20152     {
20153       struct partial_die_info *spec_die;
20154
20155       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
20156       spec_die = res.pdi;
20157       cu = res.cu;
20158
20159       spec_die->fixup (cu);
20160
20161       if (spec_die->raw_name)
20162         {
20163           raw_name = spec_die->raw_name;
20164           canonical_name = spec_die->canonical_name;
20165
20166           /* Copy DW_AT_external attribute if it is set.  */
20167           if (spec_die->is_external)
20168             is_external = spec_die->is_external;
20169         }
20170     }
20171
20172   if (!has_const_value && has_specification
20173       && can_have_DW_AT_const_value_p (tag))
20174     {
20175       struct partial_die_info *spec_die;
20176
20177       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
20178       spec_die = res.pdi;
20179       cu = res.cu;
20180
20181       spec_die->fixup (cu);
20182
20183       if (spec_die->has_const_value)
20184         {
20185           /* Copy DW_AT_const_value attribute if it is set.  */
20186           has_const_value = spec_die->has_const_value;
20187         }
20188     }
20189
20190   /* Set default names for some unnamed DIEs.  */
20191
20192   if (raw_name == NULL && tag == DW_TAG_namespace)
20193     {
20194       raw_name = CP_ANONYMOUS_NAMESPACE_STR;
20195       canonical_name = 1;
20196     }
20197
20198   /* If there is no parent die to provide a namespace, and there are
20199      children, see if we can determine the namespace from their linkage
20200      name.  */
20201   if (cu->language == language_cplus
20202       && !cu->per_objfile->per_bfd->types.empty ()
20203       && die_parent == NULL
20204       && has_children
20205       && (tag == DW_TAG_class_type
20206           || tag == DW_TAG_structure_type
20207           || tag == DW_TAG_union_type))
20208     guess_partial_die_structure_name (this, cu);
20209
20210   /* GCC might emit a nameless struct or union that has a linkage
20211      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20212   if (raw_name == NULL
20213       && (tag == DW_TAG_class_type
20214           || tag == DW_TAG_interface_type
20215           || tag == DW_TAG_structure_type
20216           || tag == DW_TAG_union_type)
20217       && linkage_name != NULL)
20218     {
20219       gdb::unique_xmalloc_ptr<char> demangled
20220         (gdb_demangle (linkage_name, DMGL_TYPES));
20221       if (demangled != nullptr)
20222         {
20223           const char *base;
20224
20225           /* Strip any leading namespaces/classes, keep only the base name.
20226              DW_AT_name for named DIEs does not contain the prefixes.  */
20227           base = strrchr (demangled.get (), ':');
20228           if (base && base > demangled.get () && base[-1] == ':')
20229             base++;
20230           else
20231             base = demangled.get ();
20232
20233           struct objfile *objfile = cu->per_objfile->objfile;
20234           raw_name = objfile->intern (base);
20235           canonical_name = 1;
20236         }
20237     }
20238
20239   fixup_called = 1;
20240 }
20241
20242 /* Read the .debug_loclists or .debug_rnglists header (they are the same format)
20243    contents from the given SECTION in the HEADER.
20244
20245    HEADER_OFFSET is the offset of the header in the section.  */
20246 static void
20247 read_loclists_rnglists_header (struct loclists_rnglists_header *header,
20248                                struct dwarf2_section_info *section,
20249                                sect_offset header_offset)
20250 {
20251   unsigned int bytes_read;
20252   bfd *abfd = section->get_bfd_owner ();
20253   const gdb_byte *info_ptr = section->buffer + to_underlying (header_offset);
20254
20255   header->length = read_initial_length (abfd, info_ptr, &bytes_read);
20256   info_ptr += bytes_read;
20257
20258   header->version = read_2_bytes (abfd, info_ptr);
20259   info_ptr += 2;
20260
20261   header->addr_size = read_1_byte (abfd, info_ptr);
20262   info_ptr += 1;
20263
20264   header->segment_collector_size = read_1_byte (abfd, info_ptr);
20265   info_ptr += 1;
20266
20267   header->offset_entry_count = read_4_bytes (abfd, info_ptr);
20268 }
20269
20270 /* Return the DW_AT_loclists_base value for the CU.  */
20271 static ULONGEST
20272 lookup_loclist_base (struct dwarf2_cu *cu)
20273 {
20274   /* For the .dwo unit, the loclist_base points to the first offset following
20275      the header. The header consists of the following entities-
20276      1. Unit Length (4 bytes for 32 bit DWARF format, and 12 bytes for the 64
20277          bit format)
20278      2. version (2 bytes)
20279      3. address size (1 byte)
20280      4. segment selector size (1 byte)
20281      5. offset entry count (4 bytes)
20282      These sizes are derived as per the DWARFv5 standard.  */
20283   if (cu->dwo_unit != nullptr)
20284     {
20285       if (cu->header.initial_length_size == 4)
20286          return LOCLIST_HEADER_SIZE32;
20287       return LOCLIST_HEADER_SIZE64;
20288     }
20289   return cu->loclist_base;
20290 }
20291
20292 /* Given a DW_FORM_loclistx value LOCLIST_INDEX, fetch the offset from the
20293    array of offsets in the .debug_loclists section.  */
20294
20295 static sect_offset
20296 read_loclist_index (struct dwarf2_cu *cu, ULONGEST loclist_index)
20297 {
20298   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20299   struct objfile *objfile = per_objfile->objfile;
20300   bfd *abfd = objfile->obfd;
20301   ULONGEST loclist_header_size =
20302     (cu->header.initial_length_size == 4 ? LOCLIST_HEADER_SIZE32
20303      : LOCLIST_HEADER_SIZE64);
20304   ULONGEST loclist_base = lookup_loclist_base (cu);
20305
20306   /* Offset in .debug_loclists of the offset for LOCLIST_INDEX.  */
20307   ULONGEST start_offset =
20308     loclist_base + loclist_index * cu->header.offset_size;
20309
20310   /* Get loclists section.  */
20311   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20312
20313   /* Read the loclists section content.  */
20314   section->read (objfile);
20315   if (section->buffer == NULL)
20316     error (_("DW_FORM_loclistx used without .debug_loclists "
20317              "section [in module %s]"), objfile_name (objfile));
20318
20319   /* DW_AT_loclists_base points after the .debug_loclists contribution header,
20320      so if loclist_base is smaller than the header size, we have a problem.  */
20321   if (loclist_base < loclist_header_size)
20322     error (_("DW_AT_loclists_base is smaller than header size [in module %s]"),
20323            objfile_name (objfile));
20324
20325   /* Read the header of the loclists contribution.  */
20326   struct loclists_rnglists_header header;
20327   read_loclists_rnglists_header (&header, section,
20328                                  (sect_offset) (loclist_base - loclist_header_size));
20329
20330   /* Verify the loclist index is valid.  */
20331   if (loclist_index >= header.offset_entry_count)
20332     error (_("DW_FORM_loclistx pointing outside of "
20333              ".debug_loclists offset array [in module %s]"),
20334            objfile_name (objfile));
20335
20336   /* Validate that reading won't go beyond the end of the section.  */
20337   if (start_offset + cu->header.offset_size > section->size)
20338     error (_("Reading DW_FORM_loclistx index beyond end of"
20339              ".debug_loclists section [in module %s]"),
20340            objfile_name (objfile));
20341
20342   const gdb_byte *info_ptr = section->buffer + start_offset;
20343
20344   if (cu->header.offset_size == 4)
20345     return (sect_offset) (bfd_get_32 (abfd, info_ptr) + loclist_base);
20346   else
20347     return (sect_offset) (bfd_get_64 (abfd, info_ptr) + loclist_base);
20348 }
20349
20350 /* Given a DW_FORM_rnglistx value RNGLIST_INDEX, fetch the offset from the
20351    array of offsets in the .debug_rnglists section.  */
20352
20353 static sect_offset
20354 read_rnglist_index (struct dwarf2_cu *cu, ULONGEST rnglist_index,
20355                     dwarf_tag tag)
20356 {
20357   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->per_objfile;
20358   struct objfile *objfile = dwarf2_per_objfile->objfile;
20359   bfd *abfd = objfile->obfd;
20360   ULONGEST rnglist_header_size =
20361     (cu->header.initial_length_size == 4 ? RNGLIST_HEADER_SIZE32
20362      : RNGLIST_HEADER_SIZE64);
20363
20364   /* When reading a DW_FORM_rnglistx from a DWO, we read from the DWO's
20365      .debug_rnglists.dwo section.  The rnglists base given in the skeleton
20366      doesn't apply.  */
20367   ULONGEST rnglist_base =
20368       (cu->dwo_unit != nullptr) ? rnglist_header_size : cu->rnglists_base;
20369
20370   /* Offset in .debug_rnglists of the offset for RNGLIST_INDEX.  */
20371   ULONGEST start_offset =
20372     rnglist_base + rnglist_index * cu->header.offset_size;
20373
20374   /* Get rnglists section.  */
20375   struct dwarf2_section_info *section = cu_debug_rnglists_section (cu, tag);
20376
20377   /* Read the rnglists section content.  */
20378   section->read (objfile);
20379   if (section->buffer == nullptr)
20380     error (_("DW_FORM_rnglistx used without .debug_rnglists section "
20381              "[in module %s]"),
20382            objfile_name (objfile));
20383
20384   /* DW_AT_rnglists_base points after the .debug_rnglists contribution header,
20385      so if rnglist_base is smaller than the header size, we have a problem.  */
20386   if (rnglist_base < rnglist_header_size)
20387     error (_("DW_AT_rnglists_base is smaller than header size [in module %s]"),
20388            objfile_name (objfile));
20389
20390   /* Read the header of the rnglists contribution.  */
20391   struct loclists_rnglists_header header;
20392   read_loclists_rnglists_header (&header, section,
20393                                  (sect_offset) (rnglist_base - rnglist_header_size));
20394
20395   /* Verify the rnglist index is valid.  */
20396   if (rnglist_index >= header.offset_entry_count)
20397     error (_("DW_FORM_rnglistx index pointing outside of "
20398              ".debug_rnglists offset array [in module %s]"),
20399            objfile_name (objfile));
20400
20401   /* Validate that reading won't go beyond the end of the section.  */
20402   if (start_offset + cu->header.offset_size > section->size)
20403     error (_("Reading DW_FORM_rnglistx index beyond end of"
20404              ".debug_rnglists section [in module %s]"),
20405            objfile_name (objfile));
20406
20407   const gdb_byte *info_ptr = section->buffer + start_offset;
20408
20409   if (cu->header.offset_size == 4)
20410     return (sect_offset) (read_4_bytes (abfd, info_ptr) + rnglist_base);
20411   else
20412     return (sect_offset) (read_8_bytes (abfd, info_ptr) + rnglist_base);
20413 }
20414
20415 /* Process the attributes that had to be skipped in the first round. These
20416    attributes are the ones that need str_offsets_base or addr_base attributes.
20417    They could not have been processed in the first round, because at the time
20418    the values of str_offsets_base or addr_base may not have been known.  */
20419 static void
20420 read_attribute_reprocess (const struct die_reader_specs *reader,
20421                           struct attribute *attr, dwarf_tag tag)
20422 {
20423   struct dwarf2_cu *cu = reader->cu;
20424   switch (attr->form)
20425     {
20426       case DW_FORM_addrx:
20427       case DW_FORM_GNU_addr_index:
20428         attr->set_address (read_addr_index (cu,
20429                                             attr->as_unsigned_reprocess ()));
20430         break;
20431       case DW_FORM_loclistx:
20432         {
20433           sect_offset loclists_sect_off
20434             = read_loclist_index (cu, attr->as_unsigned_reprocess ());
20435
20436           attr->set_unsigned (to_underlying (loclists_sect_off));
20437         }
20438         break;
20439       case DW_FORM_rnglistx:
20440         {
20441           sect_offset rnglists_sect_off
20442             = read_rnglist_index (cu, attr->as_unsigned_reprocess (), tag);
20443
20444           attr->set_unsigned (to_underlying (rnglists_sect_off));
20445         }
20446         break;
20447       case DW_FORM_strx:
20448       case DW_FORM_strx1:
20449       case DW_FORM_strx2:
20450       case DW_FORM_strx3:
20451       case DW_FORM_strx4:
20452       case DW_FORM_GNU_str_index:
20453         {
20454           unsigned int str_index = attr->as_unsigned_reprocess ();
20455           gdb_assert (!attr->canonical_string_p ());
20456           if (reader->dwo_file != NULL)
20457             attr->set_string_noncanonical (read_dwo_str_index (reader,
20458                                                                str_index));
20459           else
20460             attr->set_string_noncanonical (read_stub_str_index (cu,
20461                                                                 str_index));
20462           break;
20463         }
20464       default:
20465         gdb_assert_not_reached (_("Unexpected DWARF form."));
20466     }
20467 }
20468
20469 /* Read an attribute value described by an attribute form.  */
20470
20471 static const gdb_byte *
20472 read_attribute_value (const struct die_reader_specs *reader,
20473                       struct attribute *attr, unsigned form,
20474                       LONGEST implicit_const, const gdb_byte *info_ptr)
20475 {
20476   struct dwarf2_cu *cu = reader->cu;
20477   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20478   struct objfile *objfile = per_objfile->objfile;
20479   bfd *abfd = reader->abfd;
20480   struct comp_unit_head *cu_header = &cu->header;
20481   unsigned int bytes_read;
20482   struct dwarf_block *blk;
20483
20484   attr->form = (enum dwarf_form) form;
20485   switch (form)
20486     {
20487     case DW_FORM_ref_addr:
20488       if (cu_header->version == 2)
20489         attr->set_unsigned (cu_header->read_address (abfd, info_ptr,
20490                                                      &bytes_read));
20491       else
20492         attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
20493                                                     &bytes_read));
20494       info_ptr += bytes_read;
20495       break;
20496     case DW_FORM_GNU_ref_alt:
20497       attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
20498                                                   &bytes_read));
20499       info_ptr += bytes_read;
20500       break;
20501     case DW_FORM_addr:
20502       {
20503         struct gdbarch *gdbarch = objfile->arch ();
20504         CORE_ADDR addr = cu_header->read_address (abfd, info_ptr, &bytes_read);
20505         addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr);
20506         attr->set_address (addr);
20507         info_ptr += bytes_read;
20508       }
20509       break;
20510     case DW_FORM_block2:
20511       blk = dwarf_alloc_block (cu);
20512       blk->size = read_2_bytes (abfd, info_ptr);
20513       info_ptr += 2;
20514       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
20515       info_ptr += blk->size;
20516       attr->set_block (blk);
20517       break;
20518     case DW_FORM_block4:
20519       blk = dwarf_alloc_block (cu);
20520       blk->size = read_4_bytes (abfd, info_ptr);
20521       info_ptr += 4;
20522       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
20523       info_ptr += blk->size;
20524       attr->set_block (blk);
20525       break;
20526     case DW_FORM_data2:
20527       attr->set_unsigned (read_2_bytes (abfd, info_ptr));
20528       info_ptr += 2;
20529       break;
20530     case DW_FORM_data4:
20531       attr->set_unsigned (read_4_bytes (abfd, info_ptr));
20532       info_ptr += 4;
20533       break;
20534     case DW_FORM_data8:
20535       attr->set_unsigned (read_8_bytes (abfd, info_ptr));
20536       info_ptr += 8;
20537       break;
20538     case DW_FORM_data16:
20539       blk = dwarf_alloc_block (cu);
20540       blk->size = 16;
20541       blk->data = read_n_bytes (abfd, info_ptr, 16);
20542       info_ptr += 16;
20543       attr->set_block (blk);
20544       break;
20545     case DW_FORM_sec_offset:
20546       attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
20547                                                   &bytes_read));
20548       info_ptr += bytes_read;
20549       break;
20550     case DW_FORM_loclistx:
20551       {
20552         attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
20553                                                             &bytes_read));
20554         info_ptr += bytes_read;
20555       }
20556       break;
20557     case DW_FORM_string:
20558       attr->set_string_noncanonical (read_direct_string (abfd, info_ptr,
20559                                                          &bytes_read));
20560       info_ptr += bytes_read;
20561       break;
20562     case DW_FORM_strp:
20563       if (!cu->per_cu->is_dwz)
20564         {
20565           attr->set_string_noncanonical
20566             (read_indirect_string (per_objfile,
20567                                    abfd, info_ptr, cu_header,
20568                                    &bytes_read));
20569           info_ptr += bytes_read;
20570           break;
20571         }
20572       /* FALLTHROUGH */
20573     case DW_FORM_line_strp:
20574       if (!cu->per_cu->is_dwz)
20575         {
20576           attr->set_string_noncanonical
20577             (per_objfile->read_line_string (info_ptr, cu_header,
20578                                             &bytes_read));
20579           info_ptr += bytes_read;
20580           break;
20581         }
20582       /* FALLTHROUGH */
20583     case DW_FORM_GNU_strp_alt:
20584       {
20585         dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd, true);
20586         LONGEST str_offset = cu_header->read_offset (abfd, info_ptr,
20587                                                      &bytes_read);
20588
20589         attr->set_string_noncanonical
20590           (dwz->read_string (objfile, str_offset));
20591         info_ptr += bytes_read;
20592       }
20593       break;
20594     case DW_FORM_exprloc:
20595     case DW_FORM_block:
20596       blk = dwarf_alloc_block (cu);
20597       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
20598       info_ptr += bytes_read;
20599       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
20600       info_ptr += blk->size;
20601       attr->set_block (blk);
20602       break;
20603     case DW_FORM_block1:
20604       blk = dwarf_alloc_block (cu);
20605       blk->size = read_1_byte (abfd, info_ptr);
20606       info_ptr += 1;
20607       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
20608       info_ptr += blk->size;
20609       attr->set_block (blk);
20610       break;
20611     case DW_FORM_data1:
20612     case DW_FORM_flag:
20613       attr->set_unsigned (read_1_byte (abfd, info_ptr));
20614       info_ptr += 1;
20615       break;
20616     case DW_FORM_flag_present:
20617       attr->set_unsigned (1);
20618       break;
20619     case DW_FORM_sdata:
20620       attr->set_signed (read_signed_leb128 (abfd, info_ptr, &bytes_read));
20621       info_ptr += bytes_read;
20622       break;
20623     case DW_FORM_rnglistx:
20624       {
20625         attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
20626                                                             &bytes_read));
20627         info_ptr += bytes_read;
20628       }
20629       break;
20630     case DW_FORM_udata:
20631       attr->set_unsigned (read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
20632       info_ptr += bytes_read;
20633       break;
20634     case DW_FORM_ref1:
20635       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20636                            + read_1_byte (abfd, info_ptr)));
20637       info_ptr += 1;
20638       break;
20639     case DW_FORM_ref2:
20640       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20641                            + read_2_bytes (abfd, info_ptr)));
20642       info_ptr += 2;
20643       break;
20644     case DW_FORM_ref4:
20645       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20646                            + read_4_bytes (abfd, info_ptr)));
20647       info_ptr += 4;
20648       break;
20649     case DW_FORM_ref8:
20650       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20651                            + read_8_bytes (abfd, info_ptr)));
20652       info_ptr += 8;
20653       break;
20654     case DW_FORM_ref_sig8:
20655       attr->set_signature (read_8_bytes (abfd, info_ptr));
20656       info_ptr += 8;
20657       break;
20658     case DW_FORM_ref_udata:
20659       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20660                            + read_unsigned_leb128 (abfd, info_ptr,
20661                                                    &bytes_read)));
20662       info_ptr += bytes_read;
20663       break;
20664     case DW_FORM_indirect:
20665       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
20666       info_ptr += bytes_read;
20667       if (form == DW_FORM_implicit_const)
20668         {
20669           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
20670           info_ptr += bytes_read;
20671         }
20672       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
20673                                        info_ptr);
20674       break;
20675     case DW_FORM_implicit_const:
20676       attr->set_signed (implicit_const);
20677       break;
20678     case DW_FORM_addrx:
20679     case DW_FORM_GNU_addr_index:
20680       attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
20681                                                           &bytes_read));
20682       info_ptr += bytes_read;
20683       break;
20684     case DW_FORM_strx:
20685     case DW_FORM_strx1:
20686     case DW_FORM_strx2:
20687     case DW_FORM_strx3:
20688     case DW_FORM_strx4:
20689     case DW_FORM_GNU_str_index:
20690       {
20691         ULONGEST str_index;
20692         if (form == DW_FORM_strx1)
20693           {
20694             str_index = read_1_byte (abfd, info_ptr);
20695             info_ptr += 1;
20696           }
20697         else if (form == DW_FORM_strx2)
20698           {
20699             str_index = read_2_bytes (abfd, info_ptr);
20700             info_ptr += 2;
20701           }
20702         else if (form == DW_FORM_strx3)
20703           {
20704             str_index = read_3_bytes (abfd, info_ptr);
20705             info_ptr += 3;
20706           }
20707         else if (form == DW_FORM_strx4)
20708           {
20709             str_index = read_4_bytes (abfd, info_ptr);
20710             info_ptr += 4;
20711           }
20712         else
20713           {
20714             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
20715             info_ptr += bytes_read;
20716           }
20717         attr->set_unsigned_reprocess (str_index);
20718       }
20719       break;
20720     default:
20721       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
20722              dwarf_form_name (form),
20723              bfd_get_filename (abfd));
20724     }
20725
20726   /* Super hack.  */
20727   if (cu->per_cu->is_dwz && attr->form_is_ref ())
20728     attr->form = DW_FORM_GNU_ref_alt;
20729
20730   /* We have seen instances where the compiler tried to emit a byte
20731      size attribute of -1 which ended up being encoded as an unsigned
20732      0xffffffff.  Although 0xffffffff is technically a valid size value,
20733      an object of this size seems pretty unlikely so we can relatively
20734      safely treat these cases as if the size attribute was invalid and
20735      treat them as zero by default.  */
20736   if (attr->name == DW_AT_byte_size
20737       && form == DW_FORM_data4
20738       && attr->as_unsigned () >= 0xffffffff)
20739     {
20740       complaint
20741         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
20742          hex_string (attr->as_unsigned ()));
20743       attr->set_unsigned (0);
20744     }
20745
20746   return info_ptr;
20747 }
20748
20749 /* Read an attribute described by an abbreviated attribute.  */
20750
20751 static const gdb_byte *
20752 read_attribute (const struct die_reader_specs *reader,
20753                 struct attribute *attr, const struct attr_abbrev *abbrev,
20754                 const gdb_byte *info_ptr)
20755 {
20756   attr->name = abbrev->name;
20757   attr->string_is_canonical = 0;
20758   attr->requires_reprocessing = 0;
20759   return read_attribute_value (reader, attr, abbrev->form,
20760                                abbrev->implicit_const, info_ptr);
20761 }
20762
20763 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
20764
20765 static const char *
20766 read_indirect_string_at_offset (dwarf2_per_objfile *per_objfile,
20767                                 LONGEST str_offset)
20768 {
20769   return per_objfile->per_bfd->str.read_string (per_objfile->objfile,
20770                                                 str_offset, "DW_FORM_strp");
20771 }
20772
20773 /* Return pointer to string at .debug_str offset as read from BUF.
20774    BUF is assumed to be in a compilation unit described by CU_HEADER.
20775    Return *BYTES_READ_PTR count of bytes read from BUF.  */
20776
20777 static const char *
20778 read_indirect_string (dwarf2_per_objfile *per_objfile, bfd *abfd,
20779                       const gdb_byte *buf,
20780                       const struct comp_unit_head *cu_header,
20781                       unsigned int *bytes_read_ptr)
20782 {
20783   LONGEST str_offset = cu_header->read_offset (abfd, buf, bytes_read_ptr);
20784
20785   return read_indirect_string_at_offset (per_objfile, str_offset);
20786 }
20787
20788 /* See read.h.  */
20789
20790 const char *
20791 dwarf2_per_objfile::read_line_string (const gdb_byte *buf,
20792                                       const struct comp_unit_head *cu_header,
20793                                       unsigned int *bytes_read_ptr)
20794 {
20795   bfd *abfd = objfile->obfd;
20796   LONGEST str_offset = cu_header->read_offset (abfd, buf, bytes_read_ptr);
20797
20798   return per_bfd->line_str.read_string (objfile, str_offset, "DW_FORM_line_strp");
20799 }
20800
20801 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
20802    ADDR_BASE is the DW_AT_addr_base (DW_AT_GNU_addr_base) attribute or zero.
20803    ADDR_SIZE is the size of addresses from the CU header.  */
20804
20805 static CORE_ADDR
20806 read_addr_index_1 (dwarf2_per_objfile *per_objfile, unsigned int addr_index,
20807                    gdb::optional<ULONGEST> addr_base, int addr_size)
20808 {
20809   struct objfile *objfile = per_objfile->objfile;
20810   bfd *abfd = objfile->obfd;
20811   const gdb_byte *info_ptr;
20812   ULONGEST addr_base_or_zero = addr_base.has_value () ? *addr_base : 0;
20813
20814   per_objfile->per_bfd->addr.read (objfile);
20815   if (per_objfile->per_bfd->addr.buffer == NULL)
20816     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
20817            objfile_name (objfile));
20818   if (addr_base_or_zero + addr_index * addr_size
20819       >= per_objfile->per_bfd->addr.size)
20820     error (_("DW_FORM_addr_index pointing outside of "
20821              ".debug_addr section [in module %s]"),
20822            objfile_name (objfile));
20823   info_ptr = (per_objfile->per_bfd->addr.buffer + addr_base_or_zero
20824               + addr_index * addr_size);
20825   if (addr_size == 4)
20826     return bfd_get_32 (abfd, info_ptr);
20827   else
20828     return bfd_get_64 (abfd, info_ptr);
20829 }
20830
20831 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
20832
20833 static CORE_ADDR
20834 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
20835 {
20836   return read_addr_index_1 (cu->per_objfile, addr_index,
20837                             cu->addr_base, cu->header.addr_size);
20838 }
20839
20840 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
20841
20842 static CORE_ADDR
20843 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
20844                              unsigned int *bytes_read)
20845 {
20846   bfd *abfd = cu->per_objfile->objfile->obfd;
20847   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
20848
20849   return read_addr_index (cu, addr_index);
20850 }
20851
20852 /* See read.h.  */
20853
20854 CORE_ADDR
20855 dwarf2_read_addr_index (dwarf2_per_cu_data *per_cu,
20856                         dwarf2_per_objfile *per_objfile,
20857                         unsigned int addr_index)
20858 {
20859   struct dwarf2_cu *cu = per_objfile->get_cu (per_cu);
20860   gdb::optional<ULONGEST> addr_base;
20861   int addr_size;
20862
20863   /* We need addr_base and addr_size.
20864      If we don't have PER_CU->cu, we have to get it.
20865      Nasty, but the alternative is storing the needed info in PER_CU,
20866      which at this point doesn't seem justified: it's not clear how frequently
20867      it would get used and it would increase the size of every PER_CU.
20868      Entry points like dwarf2_per_cu_addr_size do a similar thing
20869      so we're not in uncharted territory here.
20870      Alas we need to be a bit more complicated as addr_base is contained
20871      in the DIE.
20872
20873      We don't need to read the entire CU(/TU).
20874      We just need the header and top level die.
20875
20876      IWBN to use the aging mechanism to let us lazily later discard the CU.
20877      For now we skip this optimization.  */
20878
20879   if (cu != NULL)
20880     {
20881       addr_base = cu->addr_base;
20882       addr_size = cu->header.addr_size;
20883     }
20884   else
20885     {
20886       cutu_reader reader (per_cu, per_objfile, nullptr, nullptr, false);
20887       addr_base = reader.cu->addr_base;
20888       addr_size = reader.cu->header.addr_size;
20889     }
20890
20891   return read_addr_index_1 (per_objfile, addr_index, addr_base, addr_size);
20892 }
20893
20894 /* Given a DW_FORM_GNU_str_index value STR_INDEX, fetch the string.
20895    STR_SECTION, STR_OFFSETS_SECTION can be from a Fission stub or a
20896    DWO file.  */
20897
20898 static const char *
20899 read_str_index (struct dwarf2_cu *cu,
20900                 struct dwarf2_section_info *str_section,
20901                 struct dwarf2_section_info *str_offsets_section,
20902                 ULONGEST str_offsets_base, ULONGEST str_index)
20903 {
20904   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20905   struct objfile *objfile = per_objfile->objfile;
20906   const char *objf_name = objfile_name (objfile);
20907   bfd *abfd = objfile->obfd;
20908   const gdb_byte *info_ptr;
20909   ULONGEST str_offset;
20910   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
20911
20912   str_section->read (objfile);
20913   str_offsets_section->read (objfile);
20914   if (str_section->buffer == NULL)
20915     error (_("%s used without %s section"
20916              " in CU at offset %s [in module %s]"),
20917            form_name, str_section->get_name (),
20918            sect_offset_str (cu->header.sect_off), objf_name);
20919   if (str_offsets_section->buffer == NULL)
20920     error (_("%s used without %s section"
20921              " in CU at offset %s [in module %s]"),
20922            form_name, str_section->get_name (),
20923            sect_offset_str (cu->header.sect_off), objf_name);
20924   info_ptr = (str_offsets_section->buffer
20925               + str_offsets_base
20926               + str_index * cu->header.offset_size);
20927   if (cu->header.offset_size == 4)
20928     str_offset = bfd_get_32 (abfd, info_ptr);
20929   else
20930     str_offset = bfd_get_64 (abfd, info_ptr);
20931   if (str_offset >= str_section->size)
20932     error (_("Offset from %s pointing outside of"
20933              " .debug_str.dwo section in CU at offset %s [in module %s]"),
20934            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20935   return (const char *) (str_section->buffer + str_offset);
20936 }
20937
20938 /* Given a DW_FORM_GNU_str_index from a DWO file, fetch the string.  */
20939
20940 static const char *
20941 read_dwo_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
20942 {
20943   ULONGEST str_offsets_base = reader->cu->header.version >= 5
20944                               ? reader->cu->header.addr_size : 0;
20945   return read_str_index (reader->cu,
20946                          &reader->dwo_file->sections.str,
20947                          &reader->dwo_file->sections.str_offsets,
20948                          str_offsets_base, str_index);
20949 }
20950
20951 /* Given a DW_FORM_GNU_str_index from a Fission stub, fetch the string.  */
20952
20953 static const char *
20954 read_stub_str_index (struct dwarf2_cu *cu, ULONGEST str_index)
20955 {
20956   struct objfile *objfile = cu->per_objfile->objfile;
20957   const char *objf_name = objfile_name (objfile);
20958   static const char form_name[] = "DW_FORM_GNU_str_index";
20959   static const char str_offsets_attr_name[] = "DW_AT_str_offsets";
20960
20961   if (!cu->str_offsets_base.has_value ())
20962     error (_("%s used in Fission stub without %s"
20963              " in CU at offset 0x%lx [in module %s]"),
20964            form_name, str_offsets_attr_name,
20965            (long) cu->header.offset_size, objf_name);
20966
20967   return read_str_index (cu,
20968                          &cu->per_objfile->per_bfd->str,
20969                          &cu->per_objfile->per_bfd->str_offsets,
20970                          *cu->str_offsets_base, str_index);
20971 }
20972
20973 /* Return the length of an LEB128 number in BUF.  */
20974
20975 static int
20976 leb128_size (const gdb_byte *buf)
20977 {
20978   const gdb_byte *begin = buf;
20979   gdb_byte byte;
20980
20981   while (1)
20982     {
20983       byte = *buf++;
20984       if ((byte & 128) == 0)
20985         return buf - begin;
20986     }
20987 }
20988
20989 static void
20990 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
20991 {
20992   switch (lang)
20993     {
20994     case DW_LANG_C89:
20995     case DW_LANG_C99:
20996     case DW_LANG_C11:
20997     case DW_LANG_C:
20998     case DW_LANG_UPC:
20999       cu->language = language_c;
21000       break;
21001     case DW_LANG_Java:
21002     case DW_LANG_C_plus_plus:
21003     case DW_LANG_C_plus_plus_11:
21004     case DW_LANG_C_plus_plus_14:
21005       cu->language = language_cplus;
21006       break;
21007     case DW_LANG_D:
21008       cu->language = language_d;
21009       break;
21010     case DW_LANG_Fortran77:
21011     case DW_LANG_Fortran90:
21012     case DW_LANG_Fortran95:
21013     case DW_LANG_Fortran03:
21014     case DW_LANG_Fortran08:
21015       cu->language = language_fortran;
21016       break;
21017     case DW_LANG_Go:
21018       cu->language = language_go;
21019       break;
21020     case DW_LANG_Mips_Assembler:
21021       cu->language = language_asm;
21022       break;
21023     case DW_LANG_Ada83:
21024     case DW_LANG_Ada95:
21025       cu->language = language_ada;
21026       break;
21027     case DW_LANG_Modula2:
21028       cu->language = language_m2;
21029       break;
21030     case DW_LANG_Pascal83:
21031       cu->language = language_pascal;
21032       break;
21033     case DW_LANG_ObjC:
21034       cu->language = language_objc;
21035       break;
21036     case DW_LANG_Rust:
21037     case DW_LANG_Rust_old:
21038       cu->language = language_rust;
21039       break;
21040     case DW_LANG_Cobol74:
21041     case DW_LANG_Cobol85:
21042     default:
21043       cu->language = language_minimal;
21044       break;
21045     }
21046   cu->language_defn = language_def (cu->language);
21047 }
21048
21049 /* Return the named attribute or NULL if not there.  */
21050
21051 static struct attribute *
21052 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
21053 {
21054   for (;;)
21055     {
21056       unsigned int i;
21057       struct attribute *spec = NULL;
21058
21059       for (i = 0; i < die->num_attrs; ++i)
21060         {
21061           if (die->attrs[i].name == name)
21062             return &die->attrs[i];
21063           if (die->attrs[i].name == DW_AT_specification
21064               || die->attrs[i].name == DW_AT_abstract_origin)
21065             spec = &die->attrs[i];
21066         }
21067
21068       if (!spec)
21069         break;
21070
21071       die = follow_die_ref (die, spec, &cu);
21072     }
21073
21074   return NULL;
21075 }
21076
21077 /* Return the string associated with a string-typed attribute, or NULL if it
21078    is either not found or is of an incorrect type.  */
21079
21080 static const char *
21081 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
21082 {
21083   struct attribute *attr;
21084   const char *str = NULL;
21085
21086   attr = dwarf2_attr (die, name, cu);
21087
21088   if (attr != NULL)
21089     {
21090       str = attr->as_string ();
21091       if (str == nullptr)
21092         complaint (_("string type expected for attribute %s for "
21093                      "DIE at %s in module %s"),
21094                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
21095                    objfile_name (cu->per_objfile->objfile));
21096     }
21097
21098   return str;
21099 }
21100
21101 /* Return the dwo name or NULL if not present. If present, it is in either
21102    DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.  */
21103 static const char *
21104 dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu)
21105 {
21106   const char *dwo_name = dwarf2_string_attr (die, DW_AT_GNU_dwo_name, cu);
21107   if (dwo_name == nullptr)
21108     dwo_name = dwarf2_string_attr (die, DW_AT_dwo_name, cu);
21109   return dwo_name;
21110 }
21111
21112 /* Return non-zero iff the attribute NAME is defined for the given DIE,
21113    and holds a non-zero value.  This function should only be used for
21114    DW_FORM_flag or DW_FORM_flag_present attributes.  */
21115
21116 static int
21117 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
21118 {
21119   struct attribute *attr = dwarf2_attr (die, name, cu);
21120
21121   return attr != nullptr && attr->as_boolean ();
21122 }
21123
21124 static int
21125 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
21126 {
21127   /* A DIE is a declaration if it has a DW_AT_declaration attribute
21128      which value is non-zero.  However, we have to be careful with
21129      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
21130      (via dwarf2_flag_true_p) follows this attribute.  So we may
21131      end up accidently finding a declaration attribute that belongs
21132      to a different DIE referenced by the specification attribute,
21133      even though the given DIE does not have a declaration attribute.  */
21134   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
21135           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
21136 }
21137
21138 /* Return the die giving the specification for DIE, if there is
21139    one.  *SPEC_CU is the CU containing DIE on input, and the CU
21140    containing the return value on output.  If there is no
21141    specification, but there is an abstract origin, that is
21142    returned.  */
21143
21144 static struct die_info *
21145 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
21146 {
21147   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
21148                                              *spec_cu);
21149
21150   if (spec_attr == NULL)
21151     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
21152
21153   if (spec_attr == NULL)
21154     return NULL;
21155   else
21156     return follow_die_ref (die, spec_attr, spec_cu);
21157 }
21158
21159 /* Stub for free_line_header to match void * callback types.  */
21160
21161 static void
21162 free_line_header_voidp (void *arg)
21163 {
21164   struct line_header *lh = (struct line_header *) arg;
21165
21166   delete lh;
21167 }
21168
21169 /* A convenience function to find the proper .debug_line section for a CU.  */
21170
21171 static struct dwarf2_section_info *
21172 get_debug_line_section (struct dwarf2_cu *cu)
21173 {
21174   struct dwarf2_section_info *section;
21175   dwarf2_per_objfile *per_objfile = cu->per_objfile;
21176
21177   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
21178      DWO file.  */
21179   if (cu->dwo_unit && cu->per_cu->is_debug_types)
21180     section = &cu->dwo_unit->dwo_file->sections.line;
21181   else if (cu->per_cu->is_dwz)
21182     {
21183       dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd, true);
21184
21185       section = &dwz->line;
21186     }
21187   else
21188     section = &per_objfile->per_bfd->line;
21189
21190   return section;
21191 }
21192
21193 /* Read the statement program header starting at OFFSET in
21194    .debug_line, or .debug_line.dwo.  Return a pointer
21195    to a struct line_header, allocated using xmalloc.
21196    Returns NULL if there is a problem reading the header, e.g., if it
21197    has a version we don't understand.
21198
21199    NOTE: the strings in the include directory and file name tables of
21200    the returned object point into the dwarf line section buffer,
21201    and must not be freed.  */
21202
21203 static line_header_up
21204 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
21205 {
21206   struct dwarf2_section_info *section;
21207   dwarf2_per_objfile *per_objfile = cu->per_objfile;
21208
21209   section = get_debug_line_section (cu);
21210   section->read (per_objfile->objfile);
21211   if (section->buffer == NULL)
21212     {
21213       if (cu->dwo_unit && cu->per_cu->is_debug_types)
21214         complaint (_("missing .debug_line.dwo section"));
21215       else
21216         complaint (_("missing .debug_line section"));
21217       return 0;
21218     }
21219
21220   return dwarf_decode_line_header (sect_off, cu->per_cu->is_dwz,
21221                                    per_objfile, section, &cu->header);
21222 }
21223
21224 /* Subroutine of dwarf_decode_lines to simplify it.
21225    Return the file name of the psymtab for the given file_entry.
21226    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21227    If space for the result is malloc'd, *NAME_HOLDER will be set.
21228    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
21229
21230 static const char *
21231 psymtab_include_file_name (const struct line_header *lh, const file_entry &fe,
21232                            const dwarf2_psymtab *pst,
21233                            const char *comp_dir,
21234                            gdb::unique_xmalloc_ptr<char> *name_holder)
21235 {
21236   const char *include_name = fe.name;
21237   const char *include_name_to_compare = include_name;
21238   const char *pst_filename;
21239   int file_is_pst;
21240
21241   const char *dir_name = fe.include_dir (lh);
21242
21243   gdb::unique_xmalloc_ptr<char> hold_compare;
21244   if (!IS_ABSOLUTE_PATH (include_name)
21245       && (dir_name != NULL || comp_dir != NULL))
21246     {
21247       /* Avoid creating a duplicate psymtab for PST.
21248          We do this by comparing INCLUDE_NAME and PST_FILENAME.
21249          Before we do the comparison, however, we need to account
21250          for DIR_NAME and COMP_DIR.
21251          First prepend dir_name (if non-NULL).  If we still don't
21252          have an absolute path prepend comp_dir (if non-NULL).
21253          However, the directory we record in the include-file's
21254          psymtab does not contain COMP_DIR (to match the
21255          corresponding symtab(s)).
21256
21257          Example:
21258
21259          bash$ cd /tmp
21260          bash$ gcc -g ./hello.c
21261          include_name = "hello.c"
21262          dir_name = "."
21263          DW_AT_comp_dir = comp_dir = "/tmp"
21264          DW_AT_name = "./hello.c"
21265
21266       */
21267
21268       if (dir_name != NULL)
21269         {
21270           name_holder->reset (concat (dir_name, SLASH_STRING,
21271                                       include_name, (char *) NULL));
21272           include_name = name_holder->get ();
21273           include_name_to_compare = include_name;
21274         }
21275       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
21276         {
21277           hold_compare.reset (concat (comp_dir, SLASH_STRING,
21278                                       include_name, (char *) NULL));
21279           include_name_to_compare = hold_compare.get ();
21280         }
21281     }
21282
21283   pst_filename = pst->filename;
21284   gdb::unique_xmalloc_ptr<char> copied_name;
21285   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
21286     {
21287       copied_name.reset (concat (pst->dirname, SLASH_STRING,
21288                                  pst_filename, (char *) NULL));
21289       pst_filename = copied_name.get ();
21290     }
21291
21292   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
21293
21294   if (file_is_pst)
21295     return NULL;
21296   return include_name;
21297 }
21298
21299 /* State machine to track the state of the line number program.  */
21300
21301 class lnp_state_machine
21302 {
21303 public:
21304   /* Initialize a machine state for the start of a line number
21305      program.  */
21306   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
21307                      bool record_lines_p);
21308
21309   file_entry *current_file ()
21310   {
21311     /* lh->file_names is 0-based, but the file name numbers in the
21312        statement program are 1-based.  */
21313     return m_line_header->file_name_at (m_file);
21314   }
21315
21316   /* Record the line in the state machine.  END_SEQUENCE is true if
21317      we're processing the end of a sequence.  */
21318   void record_line (bool end_sequence);
21319
21320   /* Check ADDRESS is -1, or zero and less than UNRELOCATED_LOWPC, and if true
21321      nop-out rest of the lines in this sequence.  */
21322   void check_line_address (struct dwarf2_cu *cu,
21323                            const gdb_byte *line_ptr,
21324                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
21325
21326   void handle_set_discriminator (unsigned int discriminator)
21327   {
21328     m_discriminator = discriminator;
21329     m_line_has_non_zero_discriminator |= discriminator != 0;
21330   }
21331
21332   /* Handle DW_LNE_set_address.  */
21333   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
21334   {
21335     m_op_index = 0;
21336     address += baseaddr;
21337     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
21338   }
21339
21340   /* Handle DW_LNS_advance_pc.  */
21341   void handle_advance_pc (CORE_ADDR adjust);
21342
21343   /* Handle a special opcode.  */
21344   void handle_special_opcode (unsigned char op_code);
21345
21346   /* Handle DW_LNS_advance_line.  */
21347   void handle_advance_line (int line_delta)
21348   {
21349     advance_line (line_delta);
21350   }
21351
21352   /* Handle DW_LNS_set_file.  */
21353   void handle_set_file (file_name_index file);
21354
21355   /* Handle DW_LNS_negate_stmt.  */
21356   void handle_negate_stmt ()
21357   {
21358     m_is_stmt = !m_is_stmt;
21359   }
21360
21361   /* Handle DW_LNS_const_add_pc.  */
21362   void handle_const_add_pc ();
21363
21364   /* Handle DW_LNS_fixed_advance_pc.  */
21365   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
21366   {
21367     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
21368     m_op_index = 0;
21369   }
21370
21371   /* Handle DW_LNS_copy.  */
21372   void handle_copy ()
21373   {
21374     record_line (false);
21375     m_discriminator = 0;
21376   }
21377
21378   /* Handle DW_LNE_end_sequence.  */
21379   void handle_end_sequence ()
21380   {
21381     m_currently_recording_lines = true;
21382   }
21383
21384 private:
21385   /* Advance the line by LINE_DELTA.  */
21386   void advance_line (int line_delta)
21387   {
21388     m_line += line_delta;
21389
21390     if (line_delta != 0)
21391       m_line_has_non_zero_discriminator = m_discriminator != 0;
21392   }
21393
21394   struct dwarf2_cu *m_cu;
21395
21396   gdbarch *m_gdbarch;
21397
21398   /* True if we're recording lines.
21399      Otherwise we're building partial symtabs and are just interested in
21400      finding include files mentioned by the line number program.  */
21401   bool m_record_lines_p;
21402
21403   /* The line number header.  */
21404   line_header *m_line_header;
21405
21406   /* These are part of the standard DWARF line number state machine,
21407      and initialized according to the DWARF spec.  */
21408
21409   unsigned char m_op_index = 0;
21410   /* The line table index of the current file.  */
21411   file_name_index m_file = 1;
21412   unsigned int m_line = 1;
21413
21414   /* These are initialized in the constructor.  */
21415
21416   CORE_ADDR m_address;
21417   bool m_is_stmt;
21418   unsigned int m_discriminator;
21419
21420   /* Additional bits of state we need to track.  */
21421
21422   /* The last file that we called dwarf2_start_subfile for.
21423      This is only used for TLLs.  */
21424   unsigned int m_last_file = 0;
21425   /* The last file a line number was recorded for.  */
21426   struct subfile *m_last_subfile = NULL;
21427
21428   /* The address of the last line entry.  */
21429   CORE_ADDR m_last_address;
21430
21431   /* Set to true when a previous line at the same address (using
21432      m_last_address) had m_is_stmt true.  This is reset to false when a
21433      line entry at a new address (m_address different to m_last_address) is
21434      processed.  */
21435   bool m_stmt_at_address = false;
21436
21437   /* When true, record the lines we decode.  */
21438   bool m_currently_recording_lines = false;
21439
21440   /* The last line number that was recorded, used to coalesce
21441      consecutive entries for the same line.  This can happen, for
21442      example, when discriminators are present.  PR 17276.  */
21443   unsigned int m_last_line = 0;
21444   bool m_line_has_non_zero_discriminator = false;
21445 };
21446
21447 void
21448 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
21449 {
21450   CORE_ADDR addr_adj = (((m_op_index + adjust)
21451                          / m_line_header->maximum_ops_per_instruction)
21452                         * m_line_header->minimum_instruction_length);
21453   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
21454   m_op_index = ((m_op_index + adjust)
21455                 % m_line_header->maximum_ops_per_instruction);
21456 }
21457
21458 void
21459 lnp_state_machine::handle_special_opcode (unsigned char op_code)
21460 {
21461   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
21462   unsigned char adj_opcode_d = adj_opcode / m_line_header->line_range;
21463   unsigned char adj_opcode_r = adj_opcode % m_line_header->line_range;
21464   CORE_ADDR addr_adj = (((m_op_index + adj_opcode_d)
21465                          / m_line_header->maximum_ops_per_instruction)
21466                         * m_line_header->minimum_instruction_length);
21467   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
21468   m_op_index = ((m_op_index + adj_opcode_d)
21469                 % m_line_header->maximum_ops_per_instruction);
21470
21471   int line_delta = m_line_header->line_base + adj_opcode_r;
21472   advance_line (line_delta);
21473   record_line (false);
21474   m_discriminator = 0;
21475 }
21476
21477 void
21478 lnp_state_machine::handle_set_file (file_name_index file)
21479 {
21480   m_file = file;
21481
21482   const file_entry *fe = current_file ();
21483   if (fe == NULL)
21484     dwarf2_debug_line_missing_file_complaint ();
21485   else if (m_record_lines_p)
21486     {
21487       const char *dir = fe->include_dir (m_line_header);
21488
21489       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
21490       m_line_has_non_zero_discriminator = m_discriminator != 0;
21491       dwarf2_start_subfile (m_cu, fe->name, dir);
21492     }
21493 }
21494
21495 void
21496 lnp_state_machine::handle_const_add_pc ()
21497 {
21498   CORE_ADDR adjust
21499     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
21500
21501   CORE_ADDR addr_adj
21502     = (((m_op_index + adjust)
21503         / m_line_header->maximum_ops_per_instruction)
21504        * m_line_header->minimum_instruction_length);
21505
21506   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
21507   m_op_index = ((m_op_index + adjust)
21508                 % m_line_header->maximum_ops_per_instruction);
21509 }
21510
21511 /* Return non-zero if we should add LINE to the line number table.
21512    LINE is the line to add, LAST_LINE is the last line that was added,
21513    LAST_SUBFILE is the subfile for LAST_LINE.
21514    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
21515    had a non-zero discriminator.
21516
21517    We have to be careful in the presence of discriminators.
21518    E.g., for this line:
21519
21520      for (i = 0; i < 100000; i++);
21521
21522    clang can emit four line number entries for that one line,
21523    each with a different discriminator.
21524    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
21525
21526    However, we want gdb to coalesce all four entries into one.
21527    Otherwise the user could stepi into the middle of the line and
21528    gdb would get confused about whether the pc really was in the
21529    middle of the line.
21530
21531    Things are further complicated by the fact that two consecutive
21532    line number entries for the same line is a heuristic used by gcc
21533    to denote the end of the prologue.  So we can't just discard duplicate
21534    entries, we have to be selective about it.  The heuristic we use is
21535    that we only collapse consecutive entries for the same line if at least
21536    one of those entries has a non-zero discriminator.  PR 17276.
21537
21538    Note: Addresses in the line number state machine can never go backwards
21539    within one sequence, thus this coalescing is ok.  */
21540
21541 static int
21542 dwarf_record_line_p (struct dwarf2_cu *cu,
21543                      unsigned int line, unsigned int last_line,
21544                      int line_has_non_zero_discriminator,
21545                      struct subfile *last_subfile)
21546 {
21547   if (cu->get_builder ()->get_current_subfile () != last_subfile)
21548     return 1;
21549   if (line != last_line)
21550     return 1;
21551   /* Same line for the same file that we've seen already.
21552      As a last check, for pr 17276, only record the line if the line
21553      has never had a non-zero discriminator.  */
21554   if (!line_has_non_zero_discriminator)
21555     return 1;
21556   return 0;
21557 }
21558
21559 /* Use the CU's builder to record line number LINE beginning at
21560    address ADDRESS in the line table of subfile SUBFILE.  */
21561
21562 static void
21563 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
21564                      unsigned int line, CORE_ADDR address, bool is_stmt,
21565                      struct dwarf2_cu *cu)
21566 {
21567   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
21568
21569   if (dwarf_line_debug)
21570     {
21571       fprintf_unfiltered (gdb_stdlog,
21572                           "Recording line %u, file %s, address %s\n",
21573                           line, lbasename (subfile->name),
21574                           paddress (gdbarch, address));
21575     }
21576
21577   if (cu != nullptr)
21578     cu->get_builder ()->record_line (subfile, line, addr, is_stmt);
21579 }
21580
21581 /* Subroutine of dwarf_decode_lines_1 to simplify it.
21582    Mark the end of a set of line number records.
21583    The arguments are the same as for dwarf_record_line_1.
21584    If SUBFILE is NULL the request is ignored.  */
21585
21586 static void
21587 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
21588                    CORE_ADDR address, struct dwarf2_cu *cu)
21589 {
21590   if (subfile == NULL)
21591     return;
21592
21593   if (dwarf_line_debug)
21594     {
21595       fprintf_unfiltered (gdb_stdlog,
21596                           "Finishing current line, file %s, address %s\n",
21597                           lbasename (subfile->name),
21598                           paddress (gdbarch, address));
21599     }
21600
21601   dwarf_record_line_1 (gdbarch, subfile, 0, address, true, cu);
21602 }
21603
21604 void
21605 lnp_state_machine::record_line (bool end_sequence)
21606 {
21607   if (dwarf_line_debug)
21608     {
21609       fprintf_unfiltered (gdb_stdlog,
21610                           "Processing actual line %u: file %u,"
21611                           " address %s, is_stmt %u, discrim %u%s\n",
21612                           m_line, m_file,
21613                           paddress (m_gdbarch, m_address),
21614                           m_is_stmt, m_discriminator,
21615                           (end_sequence ? "\t(end sequence)" : ""));
21616     }
21617
21618   file_entry *fe = current_file ();
21619
21620   if (fe == NULL)
21621     dwarf2_debug_line_missing_file_complaint ();
21622   /* For now we ignore lines not starting on an instruction boundary.
21623      But not when processing end_sequence for compatibility with the
21624      previous version of the code.  */
21625   else if (m_op_index == 0 || end_sequence)
21626     {
21627       fe->included_p = 1;
21628       if (m_record_lines_p)
21629         {
21630           /* When we switch files we insert an end maker in the first file,
21631              switch to the second file and add a new line entry.  The
21632              problem is that the end marker inserted in the first file will
21633              discard any previous line entries at the same address.  If the
21634              line entries in the first file are marked as is-stmt, while
21635              the new line in the second file is non-stmt, then this means
21636              the end marker will discard is-stmt lines so we can have a
21637              non-stmt line.  This means that there are less addresses at
21638              which the user can insert a breakpoint.
21639
21640              To improve this we track the last address in m_last_address,
21641              and whether we have seen an is-stmt at this address.  Then
21642              when switching files, if we have seen a stmt at the current
21643              address, and we are switching to create a non-stmt line, then
21644              discard the new line.  */
21645           bool file_changed
21646             = m_last_subfile != m_cu->get_builder ()->get_current_subfile ();
21647           bool ignore_this_line
21648            = ((file_changed && !end_sequence && m_last_address == m_address
21649                && !m_is_stmt && m_stmt_at_address)
21650               || (!end_sequence && m_line == 0));
21651
21652           if ((file_changed && !ignore_this_line) || end_sequence)
21653             {
21654               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
21655                                  m_currently_recording_lines ? m_cu : nullptr);
21656             }
21657
21658           if (!end_sequence && !ignore_this_line)
21659             {
21660               bool is_stmt = producer_is_codewarrior (m_cu) || m_is_stmt;
21661
21662               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
21663                                        m_line_has_non_zero_discriminator,
21664                                        m_last_subfile))
21665                 {
21666                   buildsym_compunit *builder = m_cu->get_builder ();
21667                   dwarf_record_line_1 (m_gdbarch,
21668                                        builder->get_current_subfile (),
21669                                        m_line, m_address, is_stmt,
21670                                        m_currently_recording_lines ? m_cu : nullptr);
21671                 }
21672               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
21673               m_last_line = m_line;
21674             }
21675         }
21676     }
21677
21678   /* Track whether we have seen any m_is_stmt true at m_address in case we
21679      have multiple line table entries all at m_address.  */
21680   if (m_last_address != m_address)
21681     {
21682       m_stmt_at_address = false;
21683       m_last_address = m_address;
21684     }
21685   m_stmt_at_address |= m_is_stmt;
21686 }
21687
21688 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
21689                                       line_header *lh, bool record_lines_p)
21690 {
21691   m_cu = cu;
21692   m_gdbarch = arch;
21693   m_record_lines_p = record_lines_p;
21694   m_line_header = lh;
21695
21696   m_currently_recording_lines = true;
21697
21698   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
21699      was a line entry for it so that the backend has a chance to adjust it
21700      and also record it in case it needs it.  This is currently used by MIPS
21701      code, cf. `mips_adjust_dwarf2_line'.  */
21702   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
21703   m_is_stmt = lh->default_is_stmt;
21704   m_discriminator = 0;
21705
21706   m_last_address = m_address;
21707   m_stmt_at_address = false;
21708 }
21709
21710 void
21711 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
21712                                        const gdb_byte *line_ptr,
21713                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
21714 {
21715   /* Linkers resolve a symbolic relocation referencing a GC'd function to 0 or
21716      -1.  If ADDRESS is 0, ignoring the opcode will err if the text section is
21717      located at 0x0.  In this case, additionally check that if
21718      ADDRESS < UNRELOCATED_LOWPC.  */
21719
21720   if ((address == 0 && address < unrelocated_lowpc)
21721       || address == (CORE_ADDR) -1)
21722     {
21723       /* This line table is for a function which has been
21724          GCd by the linker.  Ignore it.  PR gdb/12528 */
21725
21726       struct objfile *objfile = cu->per_objfile->objfile;
21727       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
21728
21729       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
21730                  line_offset, objfile_name (objfile));
21731       m_currently_recording_lines = false;
21732       /* Note: m_currently_recording_lines is left as false until we see
21733          DW_LNE_end_sequence.  */
21734     }
21735 }
21736
21737 /* Subroutine of dwarf_decode_lines to simplify it.
21738    Process the line number information in LH.
21739    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21740    program in order to set included_p for every referenced header.  */
21741
21742 static void
21743 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21744                       const int decode_for_pst_p, CORE_ADDR lowpc)
21745 {
21746   const gdb_byte *line_ptr, *extended_end;
21747   const gdb_byte *line_end;
21748   unsigned int bytes_read, extended_len;
21749   unsigned char op_code, extended_op;
21750   CORE_ADDR baseaddr;
21751   struct objfile *objfile = cu->per_objfile->objfile;
21752   bfd *abfd = objfile->obfd;
21753   struct gdbarch *gdbarch = objfile->arch ();
21754   /* True if we're recording line info (as opposed to building partial
21755      symtabs and just interested in finding include files mentioned by
21756      the line number program).  */
21757   bool record_lines_p = !decode_for_pst_p;
21758
21759   baseaddr = objfile->text_section_offset ();
21760
21761   line_ptr = lh->statement_program_start;
21762   line_end = lh->statement_program_end;
21763
21764   /* Read the statement sequences until there's nothing left.  */
21765   while (line_ptr < line_end)
21766     {
21767       /* The DWARF line number program state machine.  Reset the state
21768          machine at the start of each sequence.  */
21769       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
21770       bool end_sequence = false;
21771
21772       if (record_lines_p)
21773         {
21774           /* Start a subfile for the current file of the state
21775              machine.  */
21776           const file_entry *fe = state_machine.current_file ();
21777
21778           if (fe != NULL)
21779             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
21780         }
21781
21782       /* Decode the table.  */
21783       while (line_ptr < line_end && !end_sequence)
21784         {
21785           op_code = read_1_byte (abfd, line_ptr);
21786           line_ptr += 1;
21787
21788           if (op_code >= lh->opcode_base)
21789             {
21790               /* Special opcode.  */
21791               state_machine.handle_special_opcode (op_code);
21792             }
21793           else switch (op_code)
21794             {
21795             case DW_LNS_extended_op:
21796               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21797                                                    &bytes_read);
21798               line_ptr += bytes_read;
21799               extended_end = line_ptr + extended_len;
21800               extended_op = read_1_byte (abfd, line_ptr);
21801               line_ptr += 1;
21802               if (DW_LNE_lo_user <= extended_op
21803                   && extended_op <= DW_LNE_hi_user)
21804                 {
21805                   /* Vendor extension, ignore.  */
21806                   line_ptr = extended_end;
21807                   break;
21808                 }
21809               switch (extended_op)
21810                 {
21811                 case DW_LNE_end_sequence:
21812                   state_machine.handle_end_sequence ();
21813                   end_sequence = true;
21814                   break;
21815                 case DW_LNE_set_address:
21816                   {
21817                     CORE_ADDR address
21818                       = cu->header.read_address (abfd, line_ptr, &bytes_read);
21819                     line_ptr += bytes_read;
21820
21821                     state_machine.check_line_address (cu, line_ptr,
21822                                                       lowpc - baseaddr, address);
21823                     state_machine.handle_set_address (baseaddr, address);
21824                   }
21825                   break;
21826                 case DW_LNE_define_file:
21827                   {
21828                     const char *cur_file;
21829                     unsigned int mod_time, length;
21830                     dir_index dindex;
21831
21832                     cur_file = read_direct_string (abfd, line_ptr,
21833                                                    &bytes_read);
21834                     line_ptr += bytes_read;
21835                     dindex = (dir_index)
21836                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21837                     line_ptr += bytes_read;
21838                     mod_time =
21839                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21840                     line_ptr += bytes_read;
21841                     length =
21842                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21843                     line_ptr += bytes_read;
21844                     lh->add_file_name (cur_file, dindex, mod_time, length);
21845                   }
21846                   break;
21847                 case DW_LNE_set_discriminator:
21848                   {
21849                     /* The discriminator is not interesting to the
21850                        debugger; just ignore it.  We still need to
21851                        check its value though:
21852                        if there are consecutive entries for the same
21853                        (non-prologue) line we want to coalesce them.
21854                        PR 17276.  */
21855                     unsigned int discr
21856                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21857                     line_ptr += bytes_read;
21858
21859                     state_machine.handle_set_discriminator (discr);
21860                   }
21861                   break;
21862                 default:
21863                   complaint (_("mangled .debug_line section"));
21864                   return;
21865                 }
21866               /* Make sure that we parsed the extended op correctly.  If e.g.
21867                  we expected a different address size than the producer used,
21868                  we may have read the wrong number of bytes.  */
21869               if (line_ptr != extended_end)
21870                 {
21871                   complaint (_("mangled .debug_line section"));
21872                   return;
21873                 }
21874               break;
21875             case DW_LNS_copy:
21876               state_machine.handle_copy ();
21877               break;
21878             case DW_LNS_advance_pc:
21879               {
21880                 CORE_ADDR adjust
21881                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21882                 line_ptr += bytes_read;
21883
21884                 state_machine.handle_advance_pc (adjust);
21885               }
21886               break;
21887             case DW_LNS_advance_line:
21888               {
21889                 int line_delta
21890                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21891                 line_ptr += bytes_read;
21892
21893                 state_machine.handle_advance_line (line_delta);
21894               }
21895               break;
21896             case DW_LNS_set_file:
21897               {
21898                 file_name_index file
21899                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21900                                                             &bytes_read);
21901                 line_ptr += bytes_read;
21902
21903                 state_machine.handle_set_file (file);
21904               }
21905               break;
21906             case DW_LNS_set_column:
21907               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21908               line_ptr += bytes_read;
21909               break;
21910             case DW_LNS_negate_stmt:
21911               state_machine.handle_negate_stmt ();
21912               break;
21913             case DW_LNS_set_basic_block:
21914               break;
21915             /* Add to the address register of the state machine the
21916                address increment value corresponding to special opcode
21917                255.  I.e., this value is scaled by the minimum
21918                instruction length since special opcode 255 would have
21919                scaled the increment.  */
21920             case DW_LNS_const_add_pc:
21921               state_machine.handle_const_add_pc ();
21922               break;
21923             case DW_LNS_fixed_advance_pc:
21924               {
21925                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21926                 line_ptr += 2;
21927
21928                 state_machine.handle_fixed_advance_pc (addr_adj);
21929               }
21930               break;
21931             default:
21932               {
21933                 /* Unknown standard opcode, ignore it.  */
21934                 int i;
21935
21936                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21937                   {
21938                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21939                     line_ptr += bytes_read;
21940                   }
21941               }
21942             }
21943         }
21944
21945       if (!end_sequence)
21946         dwarf2_debug_line_missing_end_sequence_complaint ();
21947
21948       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21949          in which case we still finish recording the last line).  */
21950       state_machine.record_line (true);
21951     }
21952 }
21953
21954 /* Decode the Line Number Program (LNP) for the given line_header
21955    structure and CU.  The actual information extracted and the type
21956    of structures created from the LNP depends on the value of PST.
21957
21958    1. If PST is NULL, then this procedure uses the data from the program
21959       to create all necessary symbol tables, and their linetables.
21960
21961    2. If PST is not NULL, this procedure reads the program to determine
21962       the list of files included by the unit represented by PST, and
21963       builds all the associated partial symbol tables.
21964
21965    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21966    It is used for relative paths in the line table.
21967    NOTE: When processing partial symtabs (pst != NULL),
21968    comp_dir == pst->dirname.
21969
21970    NOTE: It is important that psymtabs have the same file name (via strcmp)
21971    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21972    symtab we don't use it in the name of the psymtabs we create.
21973    E.g. expand_line_sal requires this when finding psymtabs to expand.
21974    A good testcase for this is mb-inline.exp.
21975
21976    LOWPC is the lowest address in CU (or 0 if not known).
21977
21978    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21979    for its PC<->lines mapping information.  Otherwise only the filename
21980    table is read in.  */
21981
21982 static void
21983 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21984                     struct dwarf2_cu *cu, dwarf2_psymtab *pst,
21985                     CORE_ADDR lowpc, int decode_mapping)
21986 {
21987   struct objfile *objfile = cu->per_objfile->objfile;
21988   const int decode_for_pst_p = (pst != NULL);
21989
21990   if (decode_mapping)
21991     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21992
21993   if (decode_for_pst_p)
21994     {
21995       /* Now that we're done scanning the Line Header Program, we can
21996          create the psymtab of each included file.  */
21997       for (auto &file_entry : lh->file_names ())
21998         if (file_entry.included_p == 1)
21999           {
22000             gdb::unique_xmalloc_ptr<char> name_holder;
22001             const char *include_name =
22002               psymtab_include_file_name (lh, file_entry, pst,
22003                                          comp_dir, &name_holder);
22004             if (include_name != NULL)
22005               dwarf2_create_include_psymtab
22006                 (cu->per_objfile->per_bfd, include_name, pst,
22007                  cu->per_objfile->per_bfd->partial_symtabs.get (),
22008                  objfile);
22009           }
22010     }
22011   else
22012     {
22013       /* Make sure a symtab is created for every file, even files
22014          which contain only variables (i.e. no code with associated
22015          line numbers).  */
22016       buildsym_compunit *builder = cu->get_builder ();
22017       struct compunit_symtab *cust = builder->get_compunit_symtab ();
22018
22019       for (auto &fe : lh->file_names ())
22020         {
22021           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
22022           if (builder->get_current_subfile ()->symtab == NULL)
22023             {
22024               builder->get_current_subfile ()->symtab
22025                 = allocate_symtab (cust,
22026                                    builder->get_current_subfile ()->name);
22027             }
22028           fe.symtab = builder->get_current_subfile ()->symtab;
22029         }
22030     }
22031 }
22032
22033 /* Start a subfile for DWARF.  FILENAME is the name of the file and
22034    DIRNAME the name of the source directory which contains FILENAME
22035    or NULL if not known.
22036    This routine tries to keep line numbers from identical absolute and
22037    relative file names in a common subfile.
22038
22039    Using the `list' example from the GDB testsuite, which resides in
22040    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
22041    of /srcdir/list0.c yields the following debugging information for list0.c:
22042
22043    DW_AT_name:          /srcdir/list0.c
22044    DW_AT_comp_dir:      /compdir
22045    files.files[0].name: list0.h
22046    files.files[0].dir:  /srcdir
22047    files.files[1].name: list0.c
22048    files.files[1].dir:  /srcdir
22049
22050    The line number information for list0.c has to end up in a single
22051    subfile, so that `break /srcdir/list0.c:1' works as expected.
22052    start_subfile will ensure that this happens provided that we pass the
22053    concatenation of files.files[1].dir and files.files[1].name as the
22054    subfile's name.  */
22055
22056 static void
22057 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
22058                       const char *dirname)
22059 {
22060   gdb::unique_xmalloc_ptr<char> copy;
22061
22062   /* In order not to lose the line information directory,
22063      we concatenate it to the filename when it makes sense.
22064      Note that the Dwarf3 standard says (speaking of filenames in line
22065      information): ``The directory index is ignored for file names
22066      that represent full path names''.  Thus ignoring dirname in the
22067      `else' branch below isn't an issue.  */
22068
22069   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
22070     {
22071       copy.reset (concat (dirname, SLASH_STRING, filename, (char *) NULL));
22072       filename = copy.get ();
22073     }
22074
22075   cu->get_builder ()->start_subfile (filename);
22076 }
22077
22078 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
22079    buildsym_compunit constructor.  */
22080
22081 struct compunit_symtab *
22082 dwarf2_cu::start_symtab (const char *name, const char *comp_dir,
22083                          CORE_ADDR low_pc)
22084 {
22085   gdb_assert (m_builder == nullptr);
22086
22087   m_builder.reset (new struct buildsym_compunit
22088                    (this->per_objfile->objfile,
22089                     name, comp_dir, language, low_pc));
22090
22091   list_in_scope = get_builder ()->get_file_symbols ();
22092
22093   get_builder ()->record_debugformat ("DWARF 2");
22094   get_builder ()->record_producer (producer);
22095
22096   processing_has_namespace_info = false;
22097
22098   return get_builder ()->get_compunit_symtab ();
22099 }
22100
22101 static void
22102 var_decode_location (struct attribute *attr, struct symbol *sym,
22103                      struct dwarf2_cu *cu)
22104 {
22105   struct objfile *objfile = cu->per_objfile->objfile;
22106   struct comp_unit_head *cu_header = &cu->header;
22107
22108   /* NOTE drow/2003-01-30: There used to be a comment and some special
22109      code here to turn a symbol with DW_AT_external and a
22110      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
22111      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
22112      with some versions of binutils) where shared libraries could have
22113      relocations against symbols in their debug information - the
22114      minimal symbol would have the right address, but the debug info
22115      would not.  It's no longer necessary, because we will explicitly
22116      apply relocations when we read in the debug information now.  */
22117
22118   /* A DW_AT_location attribute with no contents indicates that a
22119      variable has been optimized away.  */
22120   if (attr->form_is_block () && attr->as_block ()->size == 0)
22121     {
22122       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
22123       return;
22124     }
22125
22126   /* Handle one degenerate form of location expression specially, to
22127      preserve GDB's previous behavior when section offsets are
22128      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
22129      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
22130
22131   if (attr->form_is_block ())
22132     {
22133       struct dwarf_block *block = attr->as_block ();
22134
22135       if ((block->data[0] == DW_OP_addr
22136            && block->size == 1 + cu_header->addr_size)
22137           || ((block->data[0] == DW_OP_GNU_addr_index
22138                || block->data[0] == DW_OP_addrx)
22139               && (block->size
22140                   == 1 + leb128_size (&block->data[1]))))
22141         {
22142           unsigned int dummy;
22143
22144           if (block->data[0] == DW_OP_addr)
22145             SET_SYMBOL_VALUE_ADDRESS
22146               (sym, cu->header.read_address (objfile->obfd,
22147                                              block->data + 1,
22148                                              &dummy));
22149           else
22150             SET_SYMBOL_VALUE_ADDRESS
22151               (sym, read_addr_index_from_leb128 (cu, block->data + 1,
22152                                                  &dummy));
22153           SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
22154           fixup_symbol_section (sym, objfile);
22155           SET_SYMBOL_VALUE_ADDRESS
22156             (sym,
22157              SYMBOL_VALUE_ADDRESS (sym)
22158              + objfile->section_offsets[sym->section_index ()]);
22159           return;
22160         }
22161     }
22162
22163   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
22164      expression evaluator, and use LOC_COMPUTED only when necessary
22165      (i.e. when the value of a register or memory location is
22166      referenced, or a thread-local block, etc.).  Then again, it might
22167      not be worthwhile.  I'm assuming that it isn't unless performance
22168      or memory numbers show me otherwise.  */
22169
22170   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
22171
22172   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
22173     cu->has_loclist = true;
22174 }
22175
22176 /* Given a pointer to a DWARF information entry, figure out if we need
22177    to make a symbol table entry for it, and if so, create a new entry
22178    and return a pointer to it.
22179    If TYPE is NULL, determine symbol type from the die, otherwise
22180    used the passed type.
22181    If SPACE is not NULL, use it to hold the new symbol.  If it is
22182    NULL, allocate a new symbol on the objfile's obstack.  */
22183
22184 static struct symbol *
22185 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
22186             struct symbol *space)
22187 {
22188   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22189   struct objfile *objfile = per_objfile->objfile;
22190   struct gdbarch *gdbarch = objfile->arch ();
22191   struct symbol *sym = NULL;
22192   const char *name;
22193   struct attribute *attr = NULL;
22194   struct attribute *attr2 = NULL;
22195   CORE_ADDR baseaddr;
22196   struct pending **list_to_add = NULL;
22197
22198   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
22199
22200   baseaddr = objfile->text_section_offset ();
22201
22202   name = dwarf2_name (die, cu);
22203   if (name)
22204     {
22205       int suppress_add = 0;
22206
22207       if (space)
22208         sym = space;
22209       else
22210         sym = new (&objfile->objfile_obstack) symbol;
22211       OBJSTAT (objfile, n_syms++);
22212
22213       /* Cache this symbol's name and the name's demangled form (if any).  */
22214       sym->set_language (cu->language, &objfile->objfile_obstack);
22215       /* Fortran does not have mangling standard and the mangling does differ
22216          between gfortran, iFort etc.  */
22217       const char *physname
22218         = (cu->language == language_fortran
22219            ? dwarf2_full_name (name, die, cu)
22220            : dwarf2_physname (name, die, cu));
22221       const char *linkagename = dw2_linkage_name (die, cu);
22222
22223       if (linkagename == nullptr || cu->language == language_ada)
22224         sym->set_linkage_name (physname);
22225       else
22226         {
22227           sym->set_demangled_name (physname, &objfile->objfile_obstack);
22228           sym->set_linkage_name (linkagename);
22229         }
22230
22231       /* Default assumptions.
22232          Use the passed type or decode it from the die.  */
22233       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
22234       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
22235       if (type != NULL)
22236         SYMBOL_TYPE (sym) = type;
22237       else
22238         SYMBOL_TYPE (sym) = die_type (die, cu);
22239       attr = dwarf2_attr (die,
22240                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
22241                           cu);
22242       if (attr != nullptr)
22243         SYMBOL_LINE (sym) = attr->constant_value (0);
22244
22245       attr = dwarf2_attr (die,
22246                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
22247                           cu);
22248       if (attr != nullptr && attr->is_nonnegative ())
22249         {
22250           file_name_index file_index
22251             = (file_name_index) attr->as_nonnegative ();
22252           struct file_entry *fe;
22253
22254           if (cu->line_header != NULL)
22255             fe = cu->line_header->file_name_at (file_index);
22256           else
22257             fe = NULL;
22258
22259           if (fe == NULL)
22260             complaint (_("file index out of range"));
22261           else
22262             symbol_set_symtab (sym, fe->symtab);
22263         }
22264
22265       switch (die->tag)
22266         {
22267         case DW_TAG_label:
22268           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
22269           if (attr != nullptr)
22270             {
22271               CORE_ADDR addr;
22272
22273               addr = attr->as_address ();
22274               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
22275               SET_SYMBOL_VALUE_ADDRESS (sym, addr);
22276               SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
22277             }
22278           else
22279             SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
22280           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
22281           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
22282           add_symbol_to_list (sym, cu->list_in_scope);
22283           break;
22284         case DW_TAG_subprogram:
22285           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
22286              finish_block.  */
22287           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
22288           attr2 = dwarf2_attr (die, DW_AT_external, cu);
22289           if ((attr2 != nullptr && attr2->as_boolean ())
22290               || cu->language == language_ada
22291               || cu->language == language_fortran)
22292             {
22293               /* Subprograms marked external are stored as a global symbol.
22294                  Ada and Fortran subprograms, whether marked external or
22295                  not, are always stored as a global symbol, because we want
22296                  to be able to access them globally.  For instance, we want
22297                  to be able to break on a nested subprogram without having
22298                  to specify the context.  */
22299               list_to_add = cu->get_builder ()->get_global_symbols ();
22300             }
22301           else
22302             {
22303               list_to_add = cu->list_in_scope;
22304             }
22305           break;
22306         case DW_TAG_inlined_subroutine:
22307           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
22308              finish_block.  */
22309           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
22310           SYMBOL_INLINED (sym) = 1;
22311           list_to_add = cu->list_in_scope;
22312           break;
22313         case DW_TAG_template_value_param:
22314           suppress_add = 1;
22315           /* Fall through.  */
22316         case DW_TAG_constant:
22317         case DW_TAG_variable:
22318         case DW_TAG_member:
22319           /* Compilation with minimal debug info may result in
22320              variables with missing type entries.  Change the
22321              misleading `void' type to something sensible.  */
22322           if (SYMBOL_TYPE (sym)->code () == TYPE_CODE_VOID)
22323             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
22324
22325           attr = dwarf2_attr (die, DW_AT_const_value, cu);
22326           /* In the case of DW_TAG_member, we should only be called for
22327              static const members.  */
22328           if (die->tag == DW_TAG_member)
22329             {
22330               /* dwarf2_add_field uses die_is_declaration,
22331                  so we do the same.  */
22332               gdb_assert (die_is_declaration (die, cu));
22333               gdb_assert (attr);
22334             }
22335           if (attr != nullptr)
22336             {
22337               dwarf2_const_value (attr, sym, cu);
22338               attr2 = dwarf2_attr (die, DW_AT_external, cu);
22339               if (!suppress_add)
22340                 {
22341                   if (attr2 != nullptr && attr2->as_boolean ())
22342                     list_to_add = cu->get_builder ()->get_global_symbols ();
22343                   else
22344                     list_to_add = cu->list_in_scope;
22345                 }
22346               break;
22347             }
22348           attr = dwarf2_attr (die, DW_AT_location, cu);
22349           if (attr != nullptr)
22350             {
22351               var_decode_location (attr, sym, cu);
22352               attr2 = dwarf2_attr (die, DW_AT_external, cu);
22353
22354               /* Fortran explicitly imports any global symbols to the local
22355                  scope by DW_TAG_common_block.  */
22356               if (cu->language == language_fortran && die->parent
22357                   && die->parent->tag == DW_TAG_common_block)
22358                 attr2 = NULL;
22359
22360               if (SYMBOL_CLASS (sym) == LOC_STATIC
22361                   && SYMBOL_VALUE_ADDRESS (sym) == 0
22362                   && !per_objfile->per_bfd->has_section_at_zero)
22363                 {
22364                   /* When a static variable is eliminated by the linker,
22365                      the corresponding debug information is not stripped
22366                      out, but the variable address is set to null;
22367                      do not add such variables into symbol table.  */
22368                 }
22369               else if (attr2 != nullptr && attr2->as_boolean ())
22370                 {
22371                   if (SYMBOL_CLASS (sym) == LOC_STATIC
22372                       && (objfile->flags & OBJF_MAINLINE) == 0
22373                       && per_objfile->per_bfd->can_copy)
22374                     {
22375                       /* A global static variable might be subject to
22376                          copy relocation.  We first check for a local
22377                          minsym, though, because maybe the symbol was
22378                          marked hidden, in which case this would not
22379                          apply.  */
22380                       bound_minimal_symbol found
22381                         = (lookup_minimal_symbol_linkage
22382                            (sym->linkage_name (), objfile));
22383                       if (found.minsym != nullptr)
22384                         sym->maybe_copied = 1;
22385                     }
22386
22387                   /* A variable with DW_AT_external is never static,
22388                      but it may be block-scoped.  */
22389                   list_to_add
22390                     = ((cu->list_in_scope
22391                         == cu->get_builder ()->get_file_symbols ())
22392                        ? cu->get_builder ()->get_global_symbols ()
22393                        : cu->list_in_scope);
22394                 }
22395               else
22396                 list_to_add = cu->list_in_scope;
22397             }
22398           else
22399             {
22400               /* We do not know the address of this symbol.
22401                  If it is an external symbol and we have type information
22402                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
22403                  The address of the variable will then be determined from
22404                  the minimal symbol table whenever the variable is
22405                  referenced.  */
22406               attr2 = dwarf2_attr (die, DW_AT_external, cu);
22407
22408               /* Fortran explicitly imports any global symbols to the local
22409                  scope by DW_TAG_common_block.  */
22410               if (cu->language == language_fortran && die->parent
22411                   && die->parent->tag == DW_TAG_common_block)
22412                 {
22413                   /* SYMBOL_CLASS doesn't matter here because
22414                      read_common_block is going to reset it.  */
22415                   if (!suppress_add)
22416                     list_to_add = cu->list_in_scope;
22417                 }
22418               else if (attr2 != nullptr && attr2->as_boolean ()
22419                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
22420                 {
22421                   /* A variable with DW_AT_external is never static, but it
22422                      may be block-scoped.  */
22423                   list_to_add
22424                     = ((cu->list_in_scope
22425                         == cu->get_builder ()->get_file_symbols ())
22426                        ? cu->get_builder ()->get_global_symbols ()
22427                        : cu->list_in_scope);
22428
22429                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
22430                 }
22431               else if (!die_is_declaration (die, cu))
22432                 {
22433                   /* Use the default LOC_OPTIMIZED_OUT class.  */
22434                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
22435                   if (!suppress_add)
22436                     list_to_add = cu->list_in_scope;
22437                 }
22438             }
22439           break;
22440         case DW_TAG_formal_parameter:
22441           {
22442             /* If we are inside a function, mark this as an argument.  If
22443                not, we might be looking at an argument to an inlined function
22444                when we do not have enough information to show inlined frames;
22445                pretend it's a local variable in that case so that the user can
22446                still see it.  */
22447             struct context_stack *curr
22448               = cu->get_builder ()->get_current_context_stack ();
22449             if (curr != nullptr && curr->name != nullptr)
22450               SYMBOL_IS_ARGUMENT (sym) = 1;
22451             attr = dwarf2_attr (die, DW_AT_location, cu);
22452             if (attr != nullptr)
22453               {
22454                 var_decode_location (attr, sym, cu);
22455               }
22456             attr = dwarf2_attr (die, DW_AT_const_value, cu);
22457             if (attr != nullptr)
22458               {
22459                 dwarf2_const_value (attr, sym, cu);
22460               }
22461
22462             list_to_add = cu->list_in_scope;
22463           }
22464           break;
22465         case DW_TAG_unspecified_parameters:
22466           /* From varargs functions; gdb doesn't seem to have any
22467              interest in this information, so just ignore it for now.
22468              (FIXME?) */
22469           break;
22470         case DW_TAG_template_type_param:
22471           suppress_add = 1;
22472           /* Fall through.  */
22473         case DW_TAG_class_type:
22474         case DW_TAG_interface_type:
22475         case DW_TAG_structure_type:
22476         case DW_TAG_union_type:
22477         case DW_TAG_set_type:
22478         case DW_TAG_enumeration_type:
22479           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22480           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
22481
22482           {
22483             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
22484                really ever be static objects: otherwise, if you try
22485                to, say, break of a class's method and you're in a file
22486                which doesn't mention that class, it won't work unless
22487                the check for all static symbols in lookup_symbol_aux
22488                saves you.  See the OtherFileClass tests in
22489                gdb.c++/namespace.exp.  */
22490
22491             if (!suppress_add)
22492               {
22493                 buildsym_compunit *builder = cu->get_builder ();
22494                 list_to_add
22495                   = (cu->list_in_scope == builder->get_file_symbols ()
22496                      && cu->language == language_cplus
22497                      ? builder->get_global_symbols ()
22498                      : cu->list_in_scope);
22499
22500                 /* The semantics of C++ state that "struct foo {
22501                    ... }" also defines a typedef for "foo".  */
22502                 if (cu->language == language_cplus
22503                     || cu->language == language_ada
22504                     || cu->language == language_d
22505                     || cu->language == language_rust)
22506                   {
22507                     /* The symbol's name is already allocated along
22508                        with this objfile, so we don't need to
22509                        duplicate it for the type.  */
22510                     if (SYMBOL_TYPE (sym)->name () == 0)
22511                       SYMBOL_TYPE (sym)->set_name (sym->search_name ());
22512                   }
22513               }
22514           }
22515           break;
22516         case DW_TAG_typedef:
22517           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22518           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
22519           list_to_add = cu->list_in_scope;
22520           break;
22521         case DW_TAG_array_type:
22522         case DW_TAG_base_type:
22523         case DW_TAG_subrange_type:
22524           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22525           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
22526           list_to_add = cu->list_in_scope;
22527           break;
22528         case DW_TAG_enumerator:
22529           attr = dwarf2_attr (die, DW_AT_const_value, cu);
22530           if (attr != nullptr)
22531             {
22532               dwarf2_const_value (attr, sym, cu);
22533             }
22534           {
22535             /* NOTE: carlton/2003-11-10: See comment above in the
22536                DW_TAG_class_type, etc. block.  */
22537
22538             list_to_add
22539               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
22540                  && cu->language == language_cplus
22541                  ? cu->get_builder ()->get_global_symbols ()
22542                  : cu->list_in_scope);
22543           }
22544           break;
22545         case DW_TAG_imported_declaration:
22546         case DW_TAG_namespace:
22547           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22548           list_to_add = cu->get_builder ()->get_global_symbols ();
22549           break;
22550         case DW_TAG_module:
22551           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22552           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
22553           list_to_add = cu->get_builder ()->get_global_symbols ();
22554           break;
22555         case DW_TAG_common_block:
22556           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
22557           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
22558           add_symbol_to_list (sym, cu->list_in_scope);
22559           break;
22560         default:
22561           /* Not a tag we recognize.  Hopefully we aren't processing
22562              trash data, but since we must specifically ignore things
22563              we don't recognize, there is nothing else we should do at
22564              this point.  */
22565           complaint (_("unsupported tag: '%s'"),
22566                      dwarf_tag_name (die->tag));
22567           break;
22568         }
22569
22570       if (suppress_add)
22571         {
22572           sym->hash_next = objfile->template_symbols;
22573           objfile->template_symbols = sym;
22574           list_to_add = NULL;
22575         }
22576
22577       if (list_to_add != NULL)
22578         add_symbol_to_list (sym, list_to_add);
22579
22580       /* For the benefit of old versions of GCC, check for anonymous
22581          namespaces based on the demangled name.  */
22582       if (!cu->processing_has_namespace_info
22583           && cu->language == language_cplus)
22584         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
22585     }
22586   return (sym);
22587 }
22588
22589 /* Given an attr with a DW_FORM_dataN value in host byte order,
22590    zero-extend it as appropriate for the symbol's type.  The DWARF
22591    standard (v4) is not entirely clear about the meaning of using
22592    DW_FORM_dataN for a constant with a signed type, where the type is
22593    wider than the data.  The conclusion of a discussion on the DWARF
22594    list was that this is unspecified.  We choose to always zero-extend
22595    because that is the interpretation long in use by GCC.  */
22596
22597 static gdb_byte *
22598 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
22599                          struct dwarf2_cu *cu, LONGEST *value, int bits)
22600 {
22601   struct objfile *objfile = cu->per_objfile->objfile;
22602   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
22603                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
22604   LONGEST l = attr->constant_value (0);
22605
22606   if (bits < sizeof (*value) * 8)
22607     {
22608       l &= ((LONGEST) 1 << bits) - 1;
22609       *value = l;
22610     }
22611   else if (bits == sizeof (*value) * 8)
22612     *value = l;
22613   else
22614     {
22615       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
22616       store_unsigned_integer (bytes, bits / 8, byte_order, l);
22617       return bytes;
22618     }
22619
22620   return NULL;
22621 }
22622
22623 /* Read a constant value from an attribute.  Either set *VALUE, or if
22624    the value does not fit in *VALUE, set *BYTES - either already
22625    allocated on the objfile obstack, or newly allocated on OBSTACK,
22626    or, set *BATON, if we translated the constant to a location
22627    expression.  */
22628
22629 static void
22630 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
22631                          const char *name, struct obstack *obstack,
22632                          struct dwarf2_cu *cu,
22633                          LONGEST *value, const gdb_byte **bytes,
22634                          struct dwarf2_locexpr_baton **baton)
22635 {
22636   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22637   struct objfile *objfile = per_objfile->objfile;
22638   struct comp_unit_head *cu_header = &cu->header;
22639   struct dwarf_block *blk;
22640   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
22641                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22642
22643   *value = 0;
22644   *bytes = NULL;
22645   *baton = NULL;
22646
22647   switch (attr->form)
22648     {
22649     case DW_FORM_addr:
22650     case DW_FORM_addrx:
22651     case DW_FORM_GNU_addr_index:
22652       {
22653         gdb_byte *data;
22654
22655         if (TYPE_LENGTH (type) != cu_header->addr_size)
22656           dwarf2_const_value_length_mismatch_complaint (name,
22657                                                         cu_header->addr_size,
22658                                                         TYPE_LENGTH (type));
22659         /* Symbols of this form are reasonably rare, so we just
22660            piggyback on the existing location code rather than writing
22661            a new implementation of symbol_computed_ops.  */
22662         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
22663         (*baton)->per_objfile = per_objfile;
22664         (*baton)->per_cu = cu->per_cu;
22665         gdb_assert ((*baton)->per_cu);
22666
22667         (*baton)->size = 2 + cu_header->addr_size;
22668         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
22669         (*baton)->data = data;
22670
22671         data[0] = DW_OP_addr;
22672         store_unsigned_integer (&data[1], cu_header->addr_size,
22673                                 byte_order, attr->as_address ());
22674         data[cu_header->addr_size + 1] = DW_OP_stack_value;
22675       }
22676       break;
22677     case DW_FORM_string:
22678     case DW_FORM_strp:
22679     case DW_FORM_strx:
22680     case DW_FORM_GNU_str_index:
22681     case DW_FORM_GNU_strp_alt:
22682       /* The string is already allocated on the objfile obstack, point
22683          directly to it.  */
22684       *bytes = (const gdb_byte *) attr->as_string ();
22685       break;
22686     case DW_FORM_block1:
22687     case DW_FORM_block2:
22688     case DW_FORM_block4:
22689     case DW_FORM_block:
22690     case DW_FORM_exprloc:
22691     case DW_FORM_data16:
22692       blk = attr->as_block ();
22693       if (TYPE_LENGTH (type) != blk->size)
22694         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
22695                                                       TYPE_LENGTH (type));
22696       *bytes = blk->data;
22697       break;
22698
22699       /* The DW_AT_const_value attributes are supposed to carry the
22700          symbol's value "represented as it would be on the target
22701          architecture."  By the time we get here, it's already been
22702          converted to host endianness, so we just need to sign- or
22703          zero-extend it as appropriate.  */
22704     case DW_FORM_data1:
22705       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
22706       break;
22707     case DW_FORM_data2:
22708       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
22709       break;
22710     case DW_FORM_data4:
22711       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
22712       break;
22713     case DW_FORM_data8:
22714       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
22715       break;
22716
22717     case DW_FORM_sdata:
22718     case DW_FORM_implicit_const:
22719       *value = attr->as_signed ();
22720       break;
22721
22722     case DW_FORM_udata:
22723       *value = attr->as_unsigned ();
22724       break;
22725
22726     default:
22727       complaint (_("unsupported const value attribute form: '%s'"),
22728                  dwarf_form_name (attr->form));
22729       *value = 0;
22730       break;
22731     }
22732 }
22733
22734
22735 /* Copy constant value from an attribute to a symbol.  */
22736
22737 static void
22738 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
22739                     struct dwarf2_cu *cu)
22740 {
22741   struct objfile *objfile = cu->per_objfile->objfile;
22742   LONGEST value;
22743   const gdb_byte *bytes;
22744   struct dwarf2_locexpr_baton *baton;
22745
22746   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
22747                            sym->print_name (),
22748                            &objfile->objfile_obstack, cu,
22749                            &value, &bytes, &baton);
22750
22751   if (baton != NULL)
22752     {
22753       SYMBOL_LOCATION_BATON (sym) = baton;
22754       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22755     }
22756   else if (bytes != NULL)
22757      {
22758       SYMBOL_VALUE_BYTES (sym) = bytes;
22759       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22760     }
22761   else
22762     {
22763       SYMBOL_VALUE (sym) = value;
22764       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22765     }
22766 }
22767
22768 /* Return the type of the die in question using its DW_AT_type attribute.  */
22769
22770 static struct type *
22771 die_type (struct die_info *die, struct dwarf2_cu *cu)
22772 {
22773   struct attribute *type_attr;
22774
22775   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22776   if (!type_attr)
22777     {
22778       struct objfile *objfile = cu->per_objfile->objfile;
22779       /* A missing DW_AT_type represents a void type.  */
22780       return objfile_type (objfile)->builtin_void;
22781     }
22782
22783   return lookup_die_type (die, type_attr, cu);
22784 }
22785
22786 /* True iff CU's producer generates GNAT Ada auxiliary information
22787    that allows to find parallel types through that information instead
22788    of having to do expensive parallel lookups by type name.  */
22789
22790 static int
22791 need_gnat_info (struct dwarf2_cu *cu)
22792 {
22793   /* Assume that the Ada compiler was GNAT, which always produces
22794      the auxiliary information.  */
22795   return (cu->language == language_ada);
22796 }
22797
22798 /* Return the auxiliary type of the die in question using its
22799    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22800    attribute is not present.  */
22801
22802 static struct type *
22803 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22804 {
22805   struct attribute *type_attr;
22806
22807   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22808   if (!type_attr)
22809     return NULL;
22810
22811   return lookup_die_type (die, type_attr, cu);
22812 }
22813
22814 /* If DIE has a descriptive_type attribute, then set the TYPE's
22815    descriptive type accordingly.  */
22816
22817 static void
22818 set_descriptive_type (struct type *type, struct die_info *die,
22819                       struct dwarf2_cu *cu)
22820 {
22821   struct type *descriptive_type = die_descriptive_type (die, cu);
22822
22823   if (descriptive_type)
22824     {
22825       ALLOCATE_GNAT_AUX_TYPE (type);
22826       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22827     }
22828 }
22829
22830 /* Return the containing type of the die in question using its
22831    DW_AT_containing_type attribute.  */
22832
22833 static struct type *
22834 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22835 {
22836   struct attribute *type_attr;
22837   struct objfile *objfile = cu->per_objfile->objfile;
22838
22839   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22840   if (!type_attr)
22841     error (_("Dwarf Error: Problem turning containing type into gdb type "
22842              "[in module %s]"), objfile_name (objfile));
22843
22844   return lookup_die_type (die, type_attr, cu);
22845 }
22846
22847 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22848
22849 static struct type *
22850 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22851 {
22852   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22853   struct objfile *objfile = per_objfile->objfile;
22854   char *saved;
22855
22856   std::string message
22857     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
22858                      objfile_name (objfile),
22859                      sect_offset_str (cu->header.sect_off),
22860                      sect_offset_str (die->sect_off));
22861   saved = obstack_strdup (&objfile->objfile_obstack, message);
22862
22863   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22864 }
22865
22866 /* Look up the type of DIE in CU using its type attribute ATTR.
22867    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22868    DW_AT_containing_type.
22869    If there is no type substitute an error marker.  */
22870
22871 static struct type *
22872 lookup_die_type (struct die_info *die, const struct attribute *attr,
22873                  struct dwarf2_cu *cu)
22874 {
22875   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22876   struct objfile *objfile = per_objfile->objfile;
22877   struct type *this_type;
22878
22879   gdb_assert (attr->name == DW_AT_type
22880               || attr->name == DW_AT_GNAT_descriptive_type
22881               || attr->name == DW_AT_containing_type);
22882
22883   /* First see if we have it cached.  */
22884
22885   if (attr->form == DW_FORM_GNU_ref_alt)
22886     {
22887       struct dwarf2_per_cu_data *per_cu;
22888       sect_offset sect_off = attr->get_ref_die_offset ();
22889
22890       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, per_objfile);
22891       this_type = get_die_type_at_offset (sect_off, per_cu, per_objfile);
22892     }
22893   else if (attr->form_is_ref ())
22894     {
22895       sect_offset sect_off = attr->get_ref_die_offset ();
22896
22897       this_type = get_die_type_at_offset (sect_off, cu->per_cu, per_objfile);
22898     }
22899   else if (attr->form == DW_FORM_ref_sig8)
22900     {
22901       ULONGEST signature = attr->as_signature ();
22902
22903       return get_signatured_type (die, signature, cu);
22904     }
22905   else
22906     {
22907       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
22908                    " at %s [in module %s]"),
22909                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22910                  objfile_name (objfile));
22911       return build_error_marker_type (cu, die);
22912     }
22913
22914   /* If not cached we need to read it in.  */
22915
22916   if (this_type == NULL)
22917     {
22918       struct die_info *type_die = NULL;
22919       struct dwarf2_cu *type_cu = cu;
22920
22921       if (attr->form_is_ref ())
22922         type_die = follow_die_ref (die, attr, &type_cu);
22923       if (type_die == NULL)
22924         return build_error_marker_type (cu, die);
22925       /* If we find the type now, it's probably because the type came
22926          from an inter-CU reference and the type's CU got expanded before
22927          ours.  */
22928       this_type = read_type_die (type_die, type_cu);
22929     }
22930
22931   /* If we still don't have a type use an error marker.  */
22932
22933   if (this_type == NULL)
22934     return build_error_marker_type (cu, die);
22935
22936   return this_type;
22937 }
22938
22939 /* Return the type in DIE, CU.
22940    Returns NULL for invalid types.
22941
22942    This first does a lookup in die_type_hash,
22943    and only reads the die in if necessary.
22944
22945    NOTE: This can be called when reading in partial or full symbols.  */
22946
22947 static struct type *
22948 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22949 {
22950   struct type *this_type;
22951
22952   this_type = get_die_type (die, cu);
22953   if (this_type)
22954     return this_type;
22955
22956   return read_type_die_1 (die, cu);
22957 }
22958
22959 /* Read the type in DIE, CU.
22960    Returns NULL for invalid types.  */
22961
22962 static struct type *
22963 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22964 {
22965   struct type *this_type = NULL;
22966
22967   switch (die->tag)
22968     {
22969     case DW_TAG_class_type:
22970     case DW_TAG_interface_type:
22971     case DW_TAG_structure_type:
22972     case DW_TAG_union_type:
22973       this_type = read_structure_type (die, cu);
22974       break;
22975     case DW_TAG_enumeration_type:
22976       this_type = read_enumeration_type (die, cu);
22977       break;
22978     case DW_TAG_subprogram:
22979     case DW_TAG_subroutine_type:
22980     case DW_TAG_inlined_subroutine:
22981       this_type = read_subroutine_type (die, cu);
22982       break;
22983     case DW_TAG_array_type:
22984       this_type = read_array_type (die, cu);
22985       break;
22986     case DW_TAG_set_type:
22987       this_type = read_set_type (die, cu);
22988       break;
22989     case DW_TAG_pointer_type:
22990       this_type = read_tag_pointer_type (die, cu);
22991       break;
22992     case DW_TAG_ptr_to_member_type:
22993       this_type = read_tag_ptr_to_member_type (die, cu);
22994       break;
22995     case DW_TAG_reference_type:
22996       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22997       break;
22998     case DW_TAG_rvalue_reference_type:
22999       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
23000       break;
23001     case DW_TAG_const_type:
23002       this_type = read_tag_const_type (die, cu);
23003       break;
23004     case DW_TAG_volatile_type:
23005       this_type = read_tag_volatile_type (die, cu);
23006       break;
23007     case DW_TAG_restrict_type:
23008       this_type = read_tag_restrict_type (die, cu);
23009       break;
23010     case DW_TAG_string_type:
23011       this_type = read_tag_string_type (die, cu);
23012       break;
23013     case DW_TAG_typedef:
23014       this_type = read_typedef (die, cu);
23015       break;
23016     case DW_TAG_subrange_type:
23017       this_type = read_subrange_type (die, cu);
23018       break;
23019     case DW_TAG_base_type:
23020       this_type = read_base_type (die, cu);
23021       break;
23022     case DW_TAG_unspecified_type:
23023       this_type = read_unspecified_type (die, cu);
23024       break;
23025     case DW_TAG_namespace:
23026       this_type = read_namespace_type (die, cu);
23027       break;
23028     case DW_TAG_module:
23029       this_type = read_module_type (die, cu);
23030       break;
23031     case DW_TAG_atomic_type:
23032       this_type = read_tag_atomic_type (die, cu);
23033       break;
23034     default:
23035       complaint (_("unexpected tag in read_type_die: '%s'"),
23036                  dwarf_tag_name (die->tag));
23037       break;
23038     }
23039
23040   return this_type;
23041 }
23042
23043 /* See if we can figure out if the class lives in a namespace.  We do
23044    this by looking for a member function; its demangled name will
23045    contain namespace info, if there is any.
23046    Return the computed name or NULL.
23047    Space for the result is allocated on the objfile's obstack.
23048    This is the full-die version of guess_partial_die_structure_name.
23049    In this case we know DIE has no useful parent.  */
23050
23051 static const char *
23052 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
23053 {
23054   struct die_info *spec_die;
23055   struct dwarf2_cu *spec_cu;
23056   struct die_info *child;
23057   struct objfile *objfile = cu->per_objfile->objfile;
23058
23059   spec_cu = cu;
23060   spec_die = die_specification (die, &spec_cu);
23061   if (spec_die != NULL)
23062     {
23063       die = spec_die;
23064       cu = spec_cu;
23065     }
23066
23067   for (child = die->child;
23068        child != NULL;
23069        child = child->sibling)
23070     {
23071       if (child->tag == DW_TAG_subprogram)
23072         {
23073           const char *linkage_name = dw2_linkage_name (child, cu);
23074
23075           if (linkage_name != NULL)
23076             {
23077               gdb::unique_xmalloc_ptr<char> actual_name
23078                 (cu->language_defn->class_name_from_physname (linkage_name));
23079               const char *name = NULL;
23080
23081               if (actual_name != NULL)
23082                 {
23083                   const char *die_name = dwarf2_name (die, cu);
23084
23085                   if (die_name != NULL
23086                       && strcmp (die_name, actual_name.get ()) != 0)
23087                     {
23088                       /* Strip off the class name from the full name.
23089                          We want the prefix.  */
23090                       int die_name_len = strlen (die_name);
23091                       int actual_name_len = strlen (actual_name.get ());
23092                       const char *ptr = actual_name.get ();
23093
23094                       /* Test for '::' as a sanity check.  */
23095                       if (actual_name_len > die_name_len + 2
23096                           && ptr[actual_name_len - die_name_len - 1] == ':')
23097                         name = obstack_strndup (
23098                           &objfile->per_bfd->storage_obstack,
23099                           ptr, actual_name_len - die_name_len - 2);
23100                     }
23101                 }
23102               return name;
23103             }
23104         }
23105     }
23106
23107   return NULL;
23108 }
23109
23110 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
23111    prefix part in such case.  See
23112    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
23113
23114 static const char *
23115 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
23116 {
23117   struct attribute *attr;
23118   const char *base;
23119
23120   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
23121       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
23122     return NULL;
23123
23124   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
23125     return NULL;
23126
23127   attr = dw2_linkage_name_attr (die, cu);
23128   const char *attr_name = attr->as_string ();
23129   if (attr == NULL || attr_name == NULL)
23130     return NULL;
23131
23132   /* dwarf2_name had to be already called.  */
23133   gdb_assert (attr->canonical_string_p ());
23134
23135   /* Strip the base name, keep any leading namespaces/classes.  */
23136   base = strrchr (attr_name, ':');
23137   if (base == NULL || base == attr_name || base[-1] != ':')
23138     return "";
23139
23140   struct objfile *objfile = cu->per_objfile->objfile;
23141   return obstack_strndup (&objfile->per_bfd->storage_obstack,
23142                           attr_name,
23143                           &base[-1] - attr_name);
23144 }
23145
23146 /* Return the name of the namespace/class that DIE is defined within,
23147    or "" if we can't tell.  The caller should not xfree the result.
23148
23149    For example, if we're within the method foo() in the following
23150    code:
23151
23152    namespace N {
23153      class C {
23154        void foo () {
23155        }
23156      };
23157    }
23158
23159    then determine_prefix on foo's die will return "N::C".  */
23160
23161 static const char *
23162 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
23163 {
23164   dwarf2_per_objfile *per_objfile = cu->per_objfile;
23165   struct die_info *parent, *spec_die;
23166   struct dwarf2_cu *spec_cu;
23167   struct type *parent_type;
23168   const char *retval;
23169
23170   if (cu->language != language_cplus
23171       && cu->language != language_fortran && cu->language != language_d
23172       && cu->language != language_rust)
23173     return "";
23174
23175   retval = anonymous_struct_prefix (die, cu);
23176   if (retval)
23177     return retval;
23178
23179   /* We have to be careful in the presence of DW_AT_specification.
23180      For example, with GCC 3.4, given the code
23181
23182      namespace N {
23183        void foo() {
23184          // Definition of N::foo.
23185        }
23186      }
23187
23188      then we'll have a tree of DIEs like this:
23189
23190      1: DW_TAG_compile_unit
23191        2: DW_TAG_namespace        // N
23192          3: DW_TAG_subprogram     // declaration of N::foo
23193        4: DW_TAG_subprogram       // definition of N::foo
23194             DW_AT_specification   // refers to die #3
23195
23196      Thus, when processing die #4, we have to pretend that we're in
23197      the context of its DW_AT_specification, namely the contex of die
23198      #3.  */
23199   spec_cu = cu;
23200   spec_die = die_specification (die, &spec_cu);
23201   if (spec_die == NULL)
23202     parent = die->parent;
23203   else
23204     {
23205       parent = spec_die->parent;
23206       cu = spec_cu;
23207     }
23208
23209   if (parent == NULL)
23210     return "";
23211   else if (parent->building_fullname)
23212     {
23213       const char *name;
23214       const char *parent_name;
23215
23216       /* It has been seen on RealView 2.2 built binaries,
23217          DW_TAG_template_type_param types actually _defined_ as
23218          children of the parent class:
23219
23220          enum E {};
23221          template class <class Enum> Class{};
23222          Class<enum E> class_e;
23223
23224          1: DW_TAG_class_type (Class)
23225            2: DW_TAG_enumeration_type (E)
23226              3: DW_TAG_enumerator (enum1:0)
23227              3: DW_TAG_enumerator (enum2:1)
23228              ...
23229            2: DW_TAG_template_type_param
23230               DW_AT_type  DW_FORM_ref_udata (E)
23231
23232          Besides being broken debug info, it can put GDB into an
23233          infinite loop.  Consider:
23234
23235          When we're building the full name for Class<E>, we'll start
23236          at Class, and go look over its template type parameters,
23237          finding E.  We'll then try to build the full name of E, and
23238          reach here.  We're now trying to build the full name of E,
23239          and look over the parent DIE for containing scope.  In the
23240          broken case, if we followed the parent DIE of E, we'd again
23241          find Class, and once again go look at its template type
23242          arguments, etc., etc.  Simply don't consider such parent die
23243          as source-level parent of this die (it can't be, the language
23244          doesn't allow it), and break the loop here.  */
23245       name = dwarf2_name (die, cu);
23246       parent_name = dwarf2_name (parent, cu);
23247       complaint (_("template param type '%s' defined within parent '%s'"),
23248                  name ? name : "<unknown>",
23249                  parent_name ? parent_name : "<unknown>");
23250       return "";
23251     }
23252   else
23253     switch (parent->tag)
23254       {
23255       case DW_TAG_namespace:
23256         parent_type = read_type_die (parent, cu);
23257         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
23258            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
23259            Work around this problem here.  */
23260         if (cu->language == language_cplus
23261             && strcmp (parent_type->name (), "::") == 0)
23262           return "";
23263         /* We give a name to even anonymous namespaces.  */
23264         return parent_type->name ();
23265       case DW_TAG_class_type:
23266       case DW_TAG_interface_type:
23267       case DW_TAG_structure_type:
23268       case DW_TAG_union_type:
23269       case DW_TAG_module:
23270         parent_type = read_type_die (parent, cu);
23271         if (parent_type->name () != NULL)
23272           return parent_type->name ();
23273         else
23274           /* An anonymous structure is only allowed non-static data
23275              members; no typedefs, no member functions, et cetera.
23276              So it does not need a prefix.  */
23277           return "";
23278       case DW_TAG_compile_unit:
23279       case DW_TAG_partial_unit:
23280         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
23281         if (cu->language == language_cplus
23282             && !per_objfile->per_bfd->types.empty ()
23283             && die->child != NULL
23284             && (die->tag == DW_TAG_class_type
23285                 || die->tag == DW_TAG_structure_type
23286                 || die->tag == DW_TAG_union_type))
23287           {
23288             const char *name = guess_full_die_structure_name (die, cu);
23289             if (name != NULL)
23290               return name;
23291           }
23292         return "";
23293       case DW_TAG_subprogram:
23294         /* Nested subroutines in Fortran get a prefix with the name
23295            of the parent's subroutine.  */
23296         if (cu->language == language_fortran)
23297           {
23298             if ((die->tag ==  DW_TAG_subprogram)
23299                 && (dwarf2_name (parent, cu) != NULL))
23300               return dwarf2_name (parent, cu);
23301           }
23302         return determine_prefix (parent, cu);
23303       case DW_TAG_enumeration_type:
23304         parent_type = read_type_die (parent, cu);
23305         if (TYPE_DECLARED_CLASS (parent_type))
23306           {
23307             if (parent_type->name () != NULL)
23308               return parent_type->name ();
23309             return "";
23310           }
23311         /* Fall through.  */
23312       default:
23313         return determine_prefix (parent, cu);
23314       }
23315 }
23316
23317 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
23318    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
23319    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
23320    an obconcat, otherwise allocate storage for the result.  The CU argument is
23321    used to determine the language and hence, the appropriate separator.  */
23322
23323 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
23324
23325 static char *
23326 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
23327                  int physname, struct dwarf2_cu *cu)
23328 {
23329   const char *lead = "";
23330   const char *sep;
23331
23332   if (suffix == NULL || suffix[0] == '\0'
23333       || prefix == NULL || prefix[0] == '\0')
23334     sep = "";
23335   else if (cu->language == language_d)
23336     {
23337       /* For D, the 'main' function could be defined in any module, but it
23338          should never be prefixed.  */
23339       if (strcmp (suffix, "D main") == 0)
23340         {
23341           prefix = "";
23342           sep = "";
23343         }
23344       else
23345         sep = ".";
23346     }
23347   else if (cu->language == language_fortran && physname)
23348     {
23349       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
23350          DW_AT_MIPS_linkage_name is preferred and used instead.  */
23351
23352       lead = "__";
23353       sep = "_MOD_";
23354     }
23355   else
23356     sep = "::";
23357
23358   if (prefix == NULL)
23359     prefix = "";
23360   if (suffix == NULL)
23361     suffix = "";
23362
23363   if (obs == NULL)
23364     {
23365       char *retval
23366         = ((char *)
23367            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
23368
23369       strcpy (retval, lead);
23370       strcat (retval, prefix);
23371       strcat (retval, sep);
23372       strcat (retval, suffix);
23373       return retval;
23374     }
23375   else
23376     {
23377       /* We have an obstack.  */
23378       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
23379     }
23380 }
23381
23382 /* Get name of a die, return NULL if not found.  */
23383
23384 static const char *
23385 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
23386                           struct objfile *objfile)
23387 {
23388   if (name && cu->language == language_cplus)
23389     {
23390       gdb::unique_xmalloc_ptr<char> canon_name
23391         = cp_canonicalize_string (name);
23392
23393       if (canon_name != nullptr)
23394         name = objfile->intern (canon_name.get ());
23395     }
23396
23397   return name;
23398 }
23399
23400 /* Get name of a die, return NULL if not found.
23401    Anonymous namespaces are converted to their magic string.  */
23402
23403 static const char *
23404 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
23405 {
23406   struct attribute *attr;
23407   struct objfile *objfile = cu->per_objfile->objfile;
23408
23409   attr = dwarf2_attr (die, DW_AT_name, cu);
23410   const char *attr_name = attr == nullptr ? nullptr : attr->as_string ();
23411   if (attr_name == nullptr
23412       && die->tag != DW_TAG_namespace
23413       && die->tag != DW_TAG_class_type
23414       && die->tag != DW_TAG_interface_type
23415       && die->tag != DW_TAG_structure_type
23416       && die->tag != DW_TAG_union_type)
23417     return NULL;
23418
23419   switch (die->tag)
23420     {
23421     case DW_TAG_compile_unit:
23422     case DW_TAG_partial_unit:
23423       /* Compilation units have a DW_AT_name that is a filename, not
23424          a source language identifier.  */
23425     case DW_TAG_enumeration_type:
23426     case DW_TAG_enumerator:
23427       /* These tags always have simple identifiers already; no need
23428          to canonicalize them.  */
23429       return attr_name;
23430
23431     case DW_TAG_namespace:
23432       if (attr_name != nullptr)
23433         return attr_name;
23434       return CP_ANONYMOUS_NAMESPACE_STR;
23435
23436     case DW_TAG_class_type:
23437     case DW_TAG_interface_type:
23438     case DW_TAG_structure_type:
23439     case DW_TAG_union_type:
23440       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
23441          structures or unions.  These were of the form "._%d" in GCC 4.1,
23442          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
23443          and GCC 4.4.  We work around this problem by ignoring these.  */
23444       if (attr_name != nullptr
23445           && (startswith (attr_name, "._")
23446               || startswith (attr_name, "<anonymous")))
23447         return NULL;
23448
23449       /* GCC might emit a nameless typedef that has a linkage name.  See
23450          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
23451       if (!attr || attr_name == NULL)
23452         {
23453           attr = dw2_linkage_name_attr (die, cu);
23454           attr_name = attr == nullptr ? nullptr : attr->as_string ();
23455           if (attr == NULL || attr_name == NULL)
23456             return NULL;
23457
23458           /* Avoid demangling attr_name the second time on a second
23459              call for the same DIE.  */
23460           if (!attr->canonical_string_p ())
23461             {
23462               gdb::unique_xmalloc_ptr<char> demangled
23463                 (gdb_demangle (attr_name, DMGL_TYPES));
23464               if (demangled == nullptr)
23465                 return nullptr;
23466
23467               attr->set_string_canonical (objfile->intern (demangled.get ()));
23468               attr_name = attr->as_string ();
23469             }
23470
23471           /* Strip any leading namespaces/classes, keep only the
23472              base name.  DW_AT_name for named DIEs does not
23473              contain the prefixes.  */
23474           const char *base = strrchr (attr_name, ':');
23475           if (base && base > attr_name && base[-1] == ':')
23476             return &base[1];
23477           else
23478             return attr_name;
23479         }
23480       break;
23481
23482     default:
23483       break;
23484     }
23485
23486   if (!attr->canonical_string_p ())
23487     attr->set_string_canonical (dwarf2_canonicalize_name (attr_name, cu,
23488                                                           objfile));
23489   return attr->as_string ();
23490 }
23491
23492 /* Return the die that this die in an extension of, or NULL if there
23493    is none.  *EXT_CU is the CU containing DIE on input, and the CU
23494    containing the return value on output.  */
23495
23496 static struct die_info *
23497 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
23498 {
23499   struct attribute *attr;
23500
23501   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
23502   if (attr == NULL)
23503     return NULL;
23504
23505   return follow_die_ref (die, attr, ext_cu);
23506 }
23507
23508 static void
23509 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
23510 {
23511   unsigned int i;
23512
23513   print_spaces (indent, f);
23514   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
23515                       dwarf_tag_name (die->tag), die->abbrev,
23516                       sect_offset_str (die->sect_off));
23517
23518   if (die->parent != NULL)
23519     {
23520       print_spaces (indent, f);
23521       fprintf_unfiltered (f, "  parent at offset: %s\n",
23522                           sect_offset_str (die->parent->sect_off));
23523     }
23524
23525   print_spaces (indent, f);
23526   fprintf_unfiltered (f, "  has children: %s\n",
23527            dwarf_bool_name (die->child != NULL));
23528
23529   print_spaces (indent, f);
23530   fprintf_unfiltered (f, "  attributes:\n");
23531
23532   for (i = 0; i < die->num_attrs; ++i)
23533     {
23534       print_spaces (indent, f);
23535       fprintf_unfiltered (f, "    %s (%s) ",
23536                dwarf_attr_name (die->attrs[i].name),
23537                dwarf_form_name (die->attrs[i].form));
23538
23539       switch (die->attrs[i].form)
23540         {
23541         case DW_FORM_addr:
23542         case DW_FORM_addrx:
23543         case DW_FORM_GNU_addr_index:
23544           fprintf_unfiltered (f, "address: ");
23545           fputs_filtered (hex_string (die->attrs[i].as_address ()), f);
23546           break;
23547         case DW_FORM_block2:
23548         case DW_FORM_block4:
23549         case DW_FORM_block:
23550         case DW_FORM_block1:
23551           fprintf_unfiltered (f, "block: size %s",
23552                               pulongest (die->attrs[i].as_block ()->size));
23553           break;
23554         case DW_FORM_exprloc:
23555           fprintf_unfiltered (f, "expression: size %s",
23556                               pulongest (die->attrs[i].as_block ()->size));
23557           break;
23558         case DW_FORM_data16:
23559           fprintf_unfiltered (f, "constant of 16 bytes");
23560           break;
23561         case DW_FORM_ref_addr:
23562           fprintf_unfiltered (f, "ref address: ");
23563           fputs_filtered (hex_string (die->attrs[i].as_unsigned ()), f);
23564           break;
23565         case DW_FORM_GNU_ref_alt:
23566           fprintf_unfiltered (f, "alt ref address: ");
23567           fputs_filtered (hex_string (die->attrs[i].as_unsigned ()), f);
23568           break;
23569         case DW_FORM_ref1:
23570         case DW_FORM_ref2:
23571         case DW_FORM_ref4:
23572         case DW_FORM_ref8:
23573         case DW_FORM_ref_udata:
23574           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
23575                               (long) (die->attrs[i].as_unsigned ()));
23576           break;
23577         case DW_FORM_data1:
23578         case DW_FORM_data2:
23579         case DW_FORM_data4:
23580         case DW_FORM_data8:
23581         case DW_FORM_udata:
23582           fprintf_unfiltered (f, "constant: %s",
23583                               pulongest (die->attrs[i].as_unsigned ()));
23584           break;
23585         case DW_FORM_sec_offset:
23586           fprintf_unfiltered (f, "section offset: %s",
23587                               pulongest (die->attrs[i].as_unsigned ()));
23588           break;
23589         case DW_FORM_ref_sig8:
23590           fprintf_unfiltered (f, "signature: %s",
23591                               hex_string (die->attrs[i].as_signature ()));
23592           break;
23593         case DW_FORM_string:
23594         case DW_FORM_strp:
23595         case DW_FORM_line_strp:
23596         case DW_FORM_strx:
23597         case DW_FORM_GNU_str_index:
23598         case DW_FORM_GNU_strp_alt:
23599           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
23600                               die->attrs[i].as_string ()
23601                               ? die->attrs[i].as_string () : "",
23602                               die->attrs[i].canonical_string_p () ? "is" : "not");
23603           break;
23604         case DW_FORM_flag:
23605           if (die->attrs[i].as_boolean ())
23606             fprintf_unfiltered (f, "flag: TRUE");
23607           else
23608             fprintf_unfiltered (f, "flag: FALSE");
23609           break;
23610         case DW_FORM_flag_present:
23611           fprintf_unfiltered (f, "flag: TRUE");
23612           break;
23613         case DW_FORM_indirect:
23614           /* The reader will have reduced the indirect form to
23615              the "base form" so this form should not occur.  */
23616           fprintf_unfiltered (f,
23617                               "unexpected attribute form: DW_FORM_indirect");
23618           break;
23619         case DW_FORM_sdata:
23620         case DW_FORM_implicit_const:
23621           fprintf_unfiltered (f, "constant: %s",
23622                               plongest (die->attrs[i].as_signed ()));
23623           break;
23624         default:
23625           fprintf_unfiltered (f, "unsupported attribute form: %d.",
23626                    die->attrs[i].form);
23627           break;
23628         }
23629       fprintf_unfiltered (f, "\n");
23630     }
23631 }
23632
23633 static void
23634 dump_die_for_error (struct die_info *die)
23635 {
23636   dump_die_shallow (gdb_stderr, 0, die);
23637 }
23638
23639 static void
23640 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
23641 {
23642   int indent = level * 4;
23643
23644   gdb_assert (die != NULL);
23645
23646   if (level >= max_level)
23647     return;
23648
23649   dump_die_shallow (f, indent, die);
23650
23651   if (die->child != NULL)
23652     {
23653       print_spaces (indent, f);
23654       fprintf_unfiltered (f, "  Children:");
23655       if (level + 1 < max_level)
23656         {
23657           fprintf_unfiltered (f, "\n");
23658           dump_die_1 (f, level + 1, max_level, die->child);
23659         }
23660       else
23661         {
23662           fprintf_unfiltered (f,
23663                               " [not printed, max nesting level reached]\n");
23664         }
23665     }
23666
23667   if (die->sibling != NULL && level > 0)
23668     {
23669       dump_die_1 (f, level, max_level, die->sibling);
23670     }
23671 }
23672
23673 /* This is called from the pdie macro in gdbinit.in.
23674    It's not static so gcc will keep a copy callable from gdb.  */
23675
23676 void
23677 dump_die (struct die_info *die, int max_level)
23678 {
23679   dump_die_1 (gdb_stdlog, 0, max_level, die);
23680 }
23681
23682 static void
23683 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23684 {
23685   void **slot;
23686
23687   slot = htab_find_slot_with_hash (cu->die_hash, die,
23688                                    to_underlying (die->sect_off),
23689                                    INSERT);
23690
23691   *slot = die;
23692 }
23693
23694 /* Follow reference or signature attribute ATTR of SRC_DIE.
23695    On entry *REF_CU is the CU of SRC_DIE.
23696    On exit *REF_CU is the CU of the result.  */
23697
23698 static struct die_info *
23699 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23700                        struct dwarf2_cu **ref_cu)
23701 {
23702   struct die_info *die;
23703
23704   if (attr->form_is_ref ())
23705     die = follow_die_ref (src_die, attr, ref_cu);
23706   else if (attr->form == DW_FORM_ref_sig8)
23707     die = follow_die_sig (src_die, attr, ref_cu);
23708   else
23709     {
23710       dump_die_for_error (src_die);
23711       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23712              objfile_name ((*ref_cu)->per_objfile->objfile));
23713     }
23714
23715   return die;
23716 }
23717
23718 /* Follow reference OFFSET.
23719    On entry *REF_CU is the CU of the source die referencing OFFSET.
23720    On exit *REF_CU is the CU of the result.
23721    Returns NULL if OFFSET is invalid.  */
23722
23723 static struct die_info *
23724 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23725                    struct dwarf2_cu **ref_cu)
23726 {
23727   struct die_info temp_die;
23728   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23729   dwarf2_per_objfile *per_objfile = cu->per_objfile;
23730
23731   gdb_assert (cu->per_cu != NULL);
23732
23733   target_cu = cu;
23734
23735   dwarf_read_debug_printf_v ("source CU offset: %s, target offset: %s, "
23736                              "source CU contains target offset: %d",
23737                              sect_offset_str (cu->per_cu->sect_off),
23738                              sect_offset_str (sect_off),
23739                              cu->header.offset_in_cu_p (sect_off));
23740
23741   if (cu->per_cu->is_debug_types)
23742     {
23743       /* .debug_types CUs cannot reference anything outside their CU.
23744          If they need to, they have to reference a signatured type via
23745          DW_FORM_ref_sig8.  */
23746       if (!cu->header.offset_in_cu_p (sect_off))
23747         return NULL;
23748     }
23749   else if (offset_in_dwz != cu->per_cu->is_dwz
23750            || !cu->header.offset_in_cu_p (sect_off))
23751     {
23752       struct dwarf2_per_cu_data *per_cu;
23753
23754       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23755                                                  per_objfile);
23756
23757       dwarf_read_debug_printf_v ("target CU offset: %s, "
23758                                  "target CU DIEs loaded: %d",
23759                                  sect_offset_str (per_cu->sect_off),
23760                                  per_objfile->get_cu (per_cu) != nullptr);
23761
23762       /* If necessary, add it to the queue and load its DIEs.
23763
23764          Even if maybe_queue_comp_unit doesn't require us to load the CU's DIEs,
23765          it doesn't mean they are currently loaded.  Since we require them
23766          to be loaded, we must check for ourselves.  */
23767       if (maybe_queue_comp_unit (cu, per_cu, per_objfile, cu->language)
23768           || per_objfile->get_cu (per_cu) == nullptr)
23769         load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
23770                              false, cu->language);
23771
23772       target_cu = per_objfile->get_cu (per_cu);
23773       gdb_assert (target_cu != nullptr);
23774     }
23775   else if (cu->dies == NULL)
23776     {
23777       /* We're loading full DIEs during partial symbol reading.  */
23778       gdb_assert (per_objfile->per_bfd->reading_partial_symbols);
23779       load_full_comp_unit (cu->per_cu, per_objfile, cu, false,
23780                            language_minimal);
23781     }
23782
23783   *ref_cu = target_cu;
23784   temp_die.sect_off = sect_off;
23785
23786   if (target_cu != cu)
23787     target_cu->ancestor = cu;
23788
23789   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23790                                                   &temp_die,
23791                                                   to_underlying (sect_off));
23792 }
23793
23794 /* Follow reference attribute ATTR of SRC_DIE.
23795    On entry *REF_CU is the CU of SRC_DIE.
23796    On exit *REF_CU is the CU of the result.  */
23797
23798 static struct die_info *
23799 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23800                 struct dwarf2_cu **ref_cu)
23801 {
23802   sect_offset sect_off = attr->get_ref_die_offset ();
23803   struct dwarf2_cu *cu = *ref_cu;
23804   struct die_info *die;
23805
23806   die = follow_die_offset (sect_off,
23807                            (attr->form == DW_FORM_GNU_ref_alt
23808                             || cu->per_cu->is_dwz),
23809                            ref_cu);
23810   if (!die)
23811     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23812            "at %s [in module %s]"),
23813            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23814            objfile_name (cu->per_objfile->objfile));
23815
23816   return die;
23817 }
23818
23819 /* See read.h.  */
23820
23821 struct dwarf2_locexpr_baton
23822 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23823                                dwarf2_per_cu_data *per_cu,
23824                                dwarf2_per_objfile *per_objfile,
23825                                gdb::function_view<CORE_ADDR ()> get_frame_pc,
23826                                bool resolve_abstract_p)
23827 {
23828   struct die_info *die;
23829   struct attribute *attr;
23830   struct dwarf2_locexpr_baton retval;
23831   struct objfile *objfile = per_objfile->objfile;
23832
23833   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
23834   if (cu == nullptr)
23835     cu = load_cu (per_cu, per_objfile, false);
23836
23837   if (cu == nullptr)
23838     {
23839       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23840          Instead just throw an error, not much else we can do.  */
23841       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23842              sect_offset_str (sect_off), objfile_name (objfile));
23843     }
23844
23845   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23846   if (!die)
23847     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23848            sect_offset_str (sect_off), objfile_name (objfile));
23849
23850   attr = dwarf2_attr (die, DW_AT_location, cu);
23851   if (!attr && resolve_abstract_p
23852       && (per_objfile->per_bfd->abstract_to_concrete.find (die->sect_off)
23853           != per_objfile->per_bfd->abstract_to_concrete.end ()))
23854     {
23855       CORE_ADDR pc = get_frame_pc ();
23856       CORE_ADDR baseaddr = objfile->text_section_offset ();
23857       struct gdbarch *gdbarch = objfile->arch ();
23858
23859       for (const auto &cand_off
23860              : per_objfile->per_bfd->abstract_to_concrete[die->sect_off])
23861         {
23862           struct dwarf2_cu *cand_cu = cu;
23863           struct die_info *cand
23864             = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
23865           if (!cand
23866               || !cand->parent
23867               || cand->parent->tag != DW_TAG_subprogram)
23868             continue;
23869
23870           CORE_ADDR pc_low, pc_high;
23871           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
23872           if (pc_low == ((CORE_ADDR) -1))
23873             continue;
23874           pc_low = gdbarch_adjust_dwarf2_addr (gdbarch, pc_low + baseaddr);
23875           pc_high = gdbarch_adjust_dwarf2_addr (gdbarch, pc_high + baseaddr);
23876           if (!(pc_low <= pc && pc < pc_high))
23877             continue;
23878
23879           die = cand;
23880           attr = dwarf2_attr (die, DW_AT_location, cu);
23881           break;
23882         }
23883     }
23884
23885   if (!attr)
23886     {
23887       /* DWARF: "If there is no such attribute, then there is no effect.".
23888          DATA is ignored if SIZE is 0.  */
23889
23890       retval.data = NULL;
23891       retval.size = 0;
23892     }
23893   else if (attr->form_is_section_offset ())
23894     {
23895       struct dwarf2_loclist_baton loclist_baton;
23896       CORE_ADDR pc = get_frame_pc ();
23897       size_t size;
23898
23899       fill_in_loclist_baton (cu, &loclist_baton, attr);
23900
23901       retval.data = dwarf2_find_location_expression (&loclist_baton,
23902                                                      &size, pc);
23903       retval.size = size;
23904     }
23905   else
23906     {
23907       if (!attr->form_is_block ())
23908         error (_("Dwarf Error: DIE at %s referenced in module %s "
23909                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23910                sect_offset_str (sect_off), objfile_name (objfile));
23911
23912       struct dwarf_block *block = attr->as_block ();
23913       retval.data = block->data;
23914       retval.size = block->size;
23915     }
23916   retval.per_objfile = per_objfile;
23917   retval.per_cu = cu->per_cu;
23918
23919   per_objfile->age_comp_units ();
23920
23921   return retval;
23922 }
23923
23924 /* See read.h.  */
23925
23926 struct dwarf2_locexpr_baton
23927 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23928                              dwarf2_per_cu_data *per_cu,
23929                              dwarf2_per_objfile *per_objfile,
23930                              gdb::function_view<CORE_ADDR ()> get_frame_pc)
23931 {
23932   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23933
23934   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, per_objfile,
23935                                         get_frame_pc);
23936 }
23937
23938 /* Write a constant of a given type as target-ordered bytes into
23939    OBSTACK.  */
23940
23941 static const gdb_byte *
23942 write_constant_as_bytes (struct obstack *obstack,
23943                          enum bfd_endian byte_order,
23944                          struct type *type,
23945                          ULONGEST value,
23946                          LONGEST *len)
23947 {
23948   gdb_byte *result;
23949
23950   *len = TYPE_LENGTH (type);
23951   result = (gdb_byte *) obstack_alloc (obstack, *len);
23952   store_unsigned_integer (result, *len, byte_order, value);
23953
23954   return result;
23955 }
23956
23957 /* See read.h.  */
23958
23959 const gdb_byte *
23960 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23961                              dwarf2_per_cu_data *per_cu,
23962                              dwarf2_per_objfile *per_objfile,
23963                              obstack *obstack,
23964                              LONGEST *len)
23965 {
23966   struct die_info *die;
23967   struct attribute *attr;
23968   const gdb_byte *result = NULL;
23969   struct type *type;
23970   LONGEST value;
23971   enum bfd_endian byte_order;
23972   struct objfile *objfile = per_objfile->objfile;
23973
23974   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
23975   if (cu == nullptr)
23976     cu = load_cu (per_cu, per_objfile, false);
23977
23978   if (cu == nullptr)
23979     {
23980       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23981          Instead just throw an error, not much else we can do.  */
23982       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23983              sect_offset_str (sect_off), objfile_name (objfile));
23984     }
23985
23986   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23987   if (!die)
23988     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23989            sect_offset_str (sect_off), objfile_name (objfile));
23990
23991   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23992   if (attr == NULL)
23993     return NULL;
23994
23995   byte_order = (bfd_big_endian (objfile->obfd)
23996                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23997
23998   switch (attr->form)
23999     {
24000     case DW_FORM_addr:
24001     case DW_FORM_addrx:
24002     case DW_FORM_GNU_addr_index:
24003       {
24004         gdb_byte *tem;
24005
24006         *len = cu->header.addr_size;
24007         tem = (gdb_byte *) obstack_alloc (obstack, *len);
24008         store_unsigned_integer (tem, *len, byte_order, attr->as_address ());
24009         result = tem;
24010       }
24011       break;
24012     case DW_FORM_string:
24013     case DW_FORM_strp:
24014     case DW_FORM_strx:
24015     case DW_FORM_GNU_str_index:
24016     case DW_FORM_GNU_strp_alt:
24017       /* The string is already allocated on the objfile obstack, point
24018          directly to it.  */
24019       {
24020         const char *attr_name = attr->as_string ();
24021         result = (const gdb_byte *) attr_name;
24022         *len = strlen (attr_name);
24023       }
24024       break;
24025     case DW_FORM_block1:
24026     case DW_FORM_block2:
24027     case DW_FORM_block4:
24028     case DW_FORM_block:
24029     case DW_FORM_exprloc:
24030     case DW_FORM_data16:
24031       {
24032         struct dwarf_block *block = attr->as_block ();
24033         result = block->data;
24034         *len = block->size;
24035       }
24036       break;
24037
24038       /* The DW_AT_const_value attributes are supposed to carry the
24039          symbol's value "represented as it would be on the target
24040          architecture."  By the time we get here, it's already been
24041          converted to host endianness, so we just need to sign- or
24042          zero-extend it as appropriate.  */
24043     case DW_FORM_data1:
24044       type = die_type (die, cu);
24045       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
24046       if (result == NULL)
24047         result = write_constant_as_bytes (obstack, byte_order,
24048                                           type, value, len);
24049       break;
24050     case DW_FORM_data2:
24051       type = die_type (die, cu);
24052       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
24053       if (result == NULL)
24054         result = write_constant_as_bytes (obstack, byte_order,
24055                                           type, value, len);
24056       break;
24057     case DW_FORM_data4:
24058       type = die_type (die, cu);
24059       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
24060       if (result == NULL)
24061         result = write_constant_as_bytes (obstack, byte_order,
24062                                           type, value, len);
24063       break;
24064     case DW_FORM_data8:
24065       type = die_type (die, cu);
24066       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
24067       if (result == NULL)
24068         result = write_constant_as_bytes (obstack, byte_order,
24069                                           type, value, len);
24070       break;
24071
24072     case DW_FORM_sdata:
24073     case DW_FORM_implicit_const:
24074       type = die_type (die, cu);
24075       result = write_constant_as_bytes (obstack, byte_order,
24076                                         type, attr->as_signed (), len);
24077       break;
24078
24079     case DW_FORM_udata:
24080       type = die_type (die, cu);
24081       result = write_constant_as_bytes (obstack, byte_order,
24082                                         type, attr->as_unsigned (), len);
24083       break;
24084
24085     default:
24086       complaint (_("unsupported const value attribute form: '%s'"),
24087                  dwarf_form_name (attr->form));
24088       break;
24089     }
24090
24091   return result;
24092 }
24093
24094 /* See read.h.  */
24095
24096 struct type *
24097 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
24098                                 dwarf2_per_cu_data *per_cu,
24099                                 dwarf2_per_objfile *per_objfile)
24100 {
24101   struct die_info *die;
24102
24103   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
24104   if (cu == nullptr)
24105     cu = load_cu (per_cu, per_objfile, false);
24106
24107   if (cu == nullptr)
24108     return nullptr;
24109
24110   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
24111   if (!die)
24112     return NULL;
24113
24114   return die_type (die, cu);
24115 }
24116
24117 /* See read.h.  */
24118
24119 struct type *
24120 dwarf2_get_die_type (cu_offset die_offset,
24121                      dwarf2_per_cu_data *per_cu,
24122                      dwarf2_per_objfile *per_objfile)
24123 {
24124   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
24125   return get_die_type_at_offset (die_offset_sect, per_cu, per_objfile);
24126 }
24127
24128 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
24129    On entry *REF_CU is the CU of SRC_DIE.
24130    On exit *REF_CU is the CU of the result.
24131    Returns NULL if the referenced DIE isn't found.  */
24132
24133 static struct die_info *
24134 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
24135                   struct dwarf2_cu **ref_cu)
24136 {
24137   struct die_info temp_die;
24138   struct dwarf2_cu *sig_cu, *cu = *ref_cu;
24139   struct die_info *die;
24140   dwarf2_per_objfile *per_objfile = (*ref_cu)->per_objfile;
24141
24142
24143   /* While it might be nice to assert sig_type->type == NULL here,
24144      we can get here for DW_AT_imported_declaration where we need
24145      the DIE not the type.  */
24146
24147   /* If necessary, add it to the queue and load its DIEs.
24148
24149      Even if maybe_queue_comp_unit doesn't require us to load the CU's DIEs,
24150      it doesn't mean they are currently loaded.  Since we require them
24151      to be loaded, we must check for ourselves.  */
24152   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, per_objfile,
24153                              language_minimal)
24154       || per_objfile->get_cu (&sig_type->per_cu) == nullptr)
24155     read_signatured_type (sig_type, per_objfile);
24156
24157   sig_cu = per_objfile->get_cu (&sig_type->per_cu);
24158   gdb_assert (sig_cu != NULL);
24159   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
24160   temp_die.sect_off = sig_type->type_offset_in_section;
24161   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
24162                                                  to_underlying (temp_die.sect_off));
24163   if (die)
24164     {
24165       /* For .gdb_index version 7 keep track of included TUs.
24166          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
24167       if (per_objfile->per_bfd->index_table != NULL
24168           && per_objfile->per_bfd->index_table->version <= 7)
24169         {
24170           (*ref_cu)->per_cu->imported_symtabs_push (sig_cu->per_cu);
24171         }
24172
24173       *ref_cu = sig_cu;
24174       if (sig_cu != cu)
24175         sig_cu->ancestor = cu;
24176
24177       return die;
24178     }
24179
24180   return NULL;
24181 }
24182
24183 /* Follow signatured type referenced by ATTR in SRC_DIE.
24184    On entry *REF_CU is the CU of SRC_DIE.
24185    On exit *REF_CU is the CU of the result.
24186    The result is the DIE of the type.
24187    If the referenced type cannot be found an error is thrown.  */
24188
24189 static struct die_info *
24190 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
24191                 struct dwarf2_cu **ref_cu)
24192 {
24193   ULONGEST signature = attr->as_signature ();
24194   struct signatured_type *sig_type;
24195   struct die_info *die;
24196
24197   gdb_assert (attr->form == DW_FORM_ref_sig8);
24198
24199   sig_type = lookup_signatured_type (*ref_cu, signature);
24200   /* sig_type will be NULL if the signatured type is missing from
24201      the debug info.  */
24202   if (sig_type == NULL)
24203     {
24204       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
24205                " from DIE at %s [in module %s]"),
24206              hex_string (signature), sect_offset_str (src_die->sect_off),
24207              objfile_name ((*ref_cu)->per_objfile->objfile));
24208     }
24209
24210   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
24211   if (die == NULL)
24212     {
24213       dump_die_for_error (src_die);
24214       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
24215                " from DIE at %s [in module %s]"),
24216              hex_string (signature), sect_offset_str (src_die->sect_off),
24217              objfile_name ((*ref_cu)->per_objfile->objfile));
24218     }
24219
24220   return die;
24221 }
24222
24223 /* Get the type specified by SIGNATURE referenced in DIE/CU,
24224    reading in and processing the type unit if necessary.  */
24225
24226 static struct type *
24227 get_signatured_type (struct die_info *die, ULONGEST signature,
24228                      struct dwarf2_cu *cu)
24229 {
24230   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24231   struct signatured_type *sig_type;
24232   struct dwarf2_cu *type_cu;
24233   struct die_info *type_die;
24234   struct type *type;
24235
24236   sig_type = lookup_signatured_type (cu, signature);
24237   /* sig_type will be NULL if the signatured type is missing from
24238      the debug info.  */
24239   if (sig_type == NULL)
24240     {
24241       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
24242                    " from DIE at %s [in module %s]"),
24243                  hex_string (signature), sect_offset_str (die->sect_off),
24244                  objfile_name (per_objfile->objfile));
24245       return build_error_marker_type (cu, die);
24246     }
24247
24248   /* If we already know the type we're done.  */
24249   type = per_objfile->get_type_for_signatured_type (sig_type);
24250   if (type != nullptr)
24251     return type;
24252
24253   type_cu = cu;
24254   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
24255   if (type_die != NULL)
24256     {
24257       /* N.B. We need to call get_die_type to ensure only one type for this DIE
24258          is created.  This is important, for example, because for c++ classes
24259          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
24260       type = read_type_die (type_die, type_cu);
24261       if (type == NULL)
24262         {
24263           complaint (_("Dwarf Error: Cannot build signatured type %s"
24264                        " referenced from DIE at %s [in module %s]"),
24265                      hex_string (signature), sect_offset_str (die->sect_off),
24266                      objfile_name (per_objfile->objfile));
24267           type = build_error_marker_type (cu, die);
24268         }
24269     }
24270   else
24271     {
24272       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
24273                    " from DIE at %s [in module %s]"),
24274                  hex_string (signature), sect_offset_str (die->sect_off),
24275                  objfile_name (per_objfile->objfile));
24276       type = build_error_marker_type (cu, die);
24277     }
24278
24279   per_objfile->set_type_for_signatured_type (sig_type, type);
24280
24281   return type;
24282 }
24283
24284 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
24285    reading in and processing the type unit if necessary.  */
24286
24287 static struct type *
24288 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
24289                           struct dwarf2_cu *cu) /* ARI: editCase function */
24290 {
24291   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
24292   if (attr->form_is_ref ())
24293     {
24294       struct dwarf2_cu *type_cu = cu;
24295       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
24296
24297       return read_type_die (type_die, type_cu);
24298     }
24299   else if (attr->form == DW_FORM_ref_sig8)
24300     {
24301       return get_signatured_type (die, attr->as_signature (), cu);
24302     }
24303   else
24304     {
24305       dwarf2_per_objfile *per_objfile = cu->per_objfile;
24306
24307       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
24308                    " at %s [in module %s]"),
24309                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
24310                  objfile_name (per_objfile->objfile));
24311       return build_error_marker_type (cu, die);
24312     }
24313 }
24314
24315 /* Load the DIEs associated with type unit PER_CU into memory.  */
24316
24317 static void
24318 load_full_type_unit (dwarf2_per_cu_data *per_cu,
24319                      dwarf2_per_objfile *per_objfile)
24320 {
24321   struct signatured_type *sig_type;
24322
24323   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
24324   gdb_assert (! per_cu->type_unit_group_p ());
24325
24326   /* We have the per_cu, but we need the signatured_type.
24327      Fortunately this is an easy translation.  */
24328   gdb_assert (per_cu->is_debug_types);
24329   sig_type = (struct signatured_type *) per_cu;
24330
24331   gdb_assert (per_objfile->get_cu (per_cu) == nullptr);
24332
24333   read_signatured_type (sig_type, per_objfile);
24334
24335   gdb_assert (per_objfile->get_cu (per_cu) != nullptr);
24336 }
24337
24338 /* Read in a signatured type and build its CU and DIEs.
24339    If the type is a stub for the real type in a DWO file,
24340    read in the real type from the DWO file as well.  */
24341
24342 static void
24343 read_signatured_type (signatured_type *sig_type,
24344                       dwarf2_per_objfile *per_objfile)
24345 {
24346   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
24347
24348   gdb_assert (per_cu->is_debug_types);
24349   gdb_assert (per_objfile->get_cu (per_cu) == nullptr);
24350
24351   cutu_reader reader (per_cu, per_objfile, nullptr, nullptr, false);
24352
24353   if (!reader.dummy_p)
24354     {
24355       struct dwarf2_cu *cu = reader.cu;
24356       const gdb_byte *info_ptr = reader.info_ptr;
24357
24358       gdb_assert (cu->die_hash == NULL);
24359       cu->die_hash =
24360         htab_create_alloc_ex (cu->header.length / 12,
24361                               die_hash,
24362                               die_eq,
24363                               NULL,
24364                               &cu->comp_unit_obstack,
24365                               hashtab_obstack_allocate,
24366                               dummy_obstack_deallocate);
24367
24368       if (reader.comp_unit_die->has_children)
24369         reader.comp_unit_die->child
24370           = read_die_and_siblings (&reader, info_ptr, &info_ptr,
24371                                    reader.comp_unit_die);
24372       cu->dies = reader.comp_unit_die;
24373       /* comp_unit_die is not stored in die_hash, no need.  */
24374
24375       /* We try not to read any attributes in this function, because
24376          not all CUs needed for references have been loaded yet, and
24377          symbol table processing isn't initialized.  But we have to
24378          set the CU language, or we won't be able to build types
24379          correctly.  Similarly, if we do not read the producer, we can
24380          not apply producer-specific interpretation.  */
24381       prepare_one_comp_unit (cu, cu->dies, language_minimal);
24382
24383       reader.keep ();
24384     }
24385
24386   sig_type->per_cu.tu_read = 1;
24387 }
24388
24389 /* Decode simple location descriptions.
24390    Given a pointer to a dwarf block that defines a location, compute
24391    the location and return the value.  If COMPUTED is non-null, it is
24392    set to true to indicate that decoding was successful, and false
24393    otherwise.  If COMPUTED is null, then this function may emit a
24394    complaint.  */
24395
24396 static CORE_ADDR
24397 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu, bool *computed)
24398 {
24399   struct objfile *objfile = cu->per_objfile->objfile;
24400   size_t i;
24401   size_t size = blk->size;
24402   const gdb_byte *data = blk->data;
24403   CORE_ADDR stack[64];
24404   int stacki;
24405   unsigned int bytes_read, unsnd;
24406   gdb_byte op;
24407
24408   if (computed != nullptr)
24409     *computed = false;
24410
24411   i = 0;
24412   stacki = 0;
24413   stack[stacki] = 0;
24414   stack[++stacki] = 0;
24415
24416   while (i < size)
24417     {
24418       op = data[i++];
24419       switch (op)
24420         {
24421         case DW_OP_lit0:
24422         case DW_OP_lit1:
24423         case DW_OP_lit2:
24424         case DW_OP_lit3:
24425         case DW_OP_lit4:
24426         case DW_OP_lit5:
24427         case DW_OP_lit6:
24428         case DW_OP_lit7:
24429         case DW_OP_lit8:
24430         case DW_OP_lit9:
24431         case DW_OP_lit10:
24432         case DW_OP_lit11:
24433         case DW_OP_lit12:
24434         case DW_OP_lit13:
24435         case DW_OP_lit14:
24436         case DW_OP_lit15:
24437         case DW_OP_lit16:
24438         case DW_OP_lit17:
24439         case DW_OP_lit18:
24440         case DW_OP_lit19:
24441         case DW_OP_lit20:
24442         case DW_OP_lit21:
24443         case DW_OP_lit22:
24444         case DW_OP_lit23:
24445         case DW_OP_lit24:
24446         case DW_OP_lit25:
24447         case DW_OP_lit26:
24448         case DW_OP_lit27:
24449         case DW_OP_lit28:
24450         case DW_OP_lit29:
24451         case DW_OP_lit30:
24452         case DW_OP_lit31:
24453           stack[++stacki] = op - DW_OP_lit0;
24454           break;
24455
24456         case DW_OP_reg0:
24457         case DW_OP_reg1:
24458         case DW_OP_reg2:
24459         case DW_OP_reg3:
24460         case DW_OP_reg4:
24461         case DW_OP_reg5:
24462         case DW_OP_reg6:
24463         case DW_OP_reg7:
24464         case DW_OP_reg8:
24465         case DW_OP_reg9:
24466         case DW_OP_reg10:
24467         case DW_OP_reg11:
24468         case DW_OP_reg12:
24469         case DW_OP_reg13:
24470         case DW_OP_reg14:
24471         case DW_OP_reg15:
24472         case DW_OP_reg16:
24473         case DW_OP_reg17:
24474         case DW_OP_reg18:
24475         case DW_OP_reg19:
24476         case DW_OP_reg20:
24477         case DW_OP_reg21:
24478         case DW_OP_reg22:
24479         case DW_OP_reg23:
24480         case DW_OP_reg24:
24481         case DW_OP_reg25:
24482         case DW_OP_reg26:
24483         case DW_OP_reg27:
24484         case DW_OP_reg28:
24485         case DW_OP_reg29:
24486         case DW_OP_reg30:
24487         case DW_OP_reg31:
24488           stack[++stacki] = op - DW_OP_reg0;
24489           if (i < size)
24490             {
24491               if (computed == nullptr)
24492                 dwarf2_complex_location_expr_complaint ();
24493               else
24494                 return 0;
24495             }
24496           break;
24497
24498         case DW_OP_regx:
24499           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
24500           i += bytes_read;
24501           stack[++stacki] = unsnd;
24502           if (i < size)
24503             {
24504               if (computed == nullptr)
24505                 dwarf2_complex_location_expr_complaint ();
24506               else
24507                 return 0;
24508             }
24509           break;
24510
24511         case DW_OP_addr:
24512           stack[++stacki] = cu->header.read_address (objfile->obfd, &data[i],
24513                                                      &bytes_read);
24514           i += bytes_read;
24515           break;
24516
24517         case DW_OP_const1u:
24518           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
24519           i += 1;
24520           break;
24521
24522         case DW_OP_const1s:
24523           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
24524           i += 1;
24525           break;
24526
24527         case DW_OP_const2u:
24528           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
24529           i += 2;
24530           break;
24531
24532         case DW_OP_const2s:
24533           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
24534           i += 2;
24535           break;
24536
24537         case DW_OP_const4u:
24538           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
24539           i += 4;
24540           break;
24541
24542         case DW_OP_const4s:
24543           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
24544           i += 4;
24545           break;
24546
24547         case DW_OP_const8u:
24548           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
24549           i += 8;
24550           break;
24551
24552         case DW_OP_constu:
24553           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
24554                                                   &bytes_read);
24555           i += bytes_read;
24556           break;
24557
24558         case DW_OP_consts:
24559           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
24560           i += bytes_read;
24561           break;
24562
24563         case DW_OP_dup:
24564           stack[stacki + 1] = stack[stacki];
24565           stacki++;
24566           break;
24567
24568         case DW_OP_plus:
24569           stack[stacki - 1] += stack[stacki];
24570           stacki--;
24571           break;
24572
24573         case DW_OP_plus_uconst:
24574           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
24575                                                  &bytes_read);
24576           i += bytes_read;
24577           break;
24578
24579         case DW_OP_minus:
24580           stack[stacki - 1] -= stack[stacki];
24581           stacki--;
24582           break;
24583
24584         case DW_OP_deref:
24585           /* If we're not the last op, then we definitely can't encode
24586              this using GDB's address_class enum.  This is valid for partial
24587              global symbols, although the variable's address will be bogus
24588              in the psymtab.  */
24589           if (i < size)
24590             {
24591               if (computed == nullptr)
24592                 dwarf2_complex_location_expr_complaint ();
24593               else
24594                 return 0;
24595             }
24596           break;
24597
24598         case DW_OP_GNU_push_tls_address:
24599         case DW_OP_form_tls_address:
24600           /* The top of the stack has the offset from the beginning
24601              of the thread control block at which the variable is located.  */
24602           /* Nothing should follow this operator, so the top of stack would
24603              be returned.  */
24604           /* This is valid for partial global symbols, but the variable's
24605              address will be bogus in the psymtab.  Make it always at least
24606              non-zero to not look as a variable garbage collected by linker
24607              which have DW_OP_addr 0.  */
24608           if (i < size)
24609             {
24610               if (computed == nullptr)
24611                 dwarf2_complex_location_expr_complaint ();
24612               else
24613                 return 0;
24614             }
24615           stack[stacki]++;
24616           break;
24617
24618         case DW_OP_GNU_uninit:
24619           if (computed != nullptr)
24620             return 0;
24621           break;
24622
24623         case DW_OP_addrx:
24624         case DW_OP_GNU_addr_index:
24625         case DW_OP_GNU_const_index:
24626           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
24627                                                          &bytes_read);
24628           i += bytes_read;
24629           break;
24630
24631         default:
24632           if (computed == nullptr)
24633             {
24634               const char *name = get_DW_OP_name (op);
24635
24636               if (name)
24637                 complaint (_("unsupported stack op: '%s'"),
24638                            name);
24639               else
24640                 complaint (_("unsupported stack op: '%02x'"),
24641                            op);
24642             }
24643
24644           return (stack[stacki]);
24645         }
24646
24647       /* Enforce maximum stack depth of SIZE-1 to avoid writing
24648          outside of the allocated space.  Also enforce minimum>0.  */
24649       if (stacki >= ARRAY_SIZE (stack) - 1)
24650         {
24651           if (computed == nullptr)
24652             complaint (_("location description stack overflow"));
24653           return 0;
24654         }
24655
24656       if (stacki <= 0)
24657         {
24658           if (computed == nullptr)
24659             complaint (_("location description stack underflow"));
24660           return 0;
24661         }
24662     }
24663
24664   if (computed != nullptr)
24665     *computed = true;
24666   return (stack[stacki]);
24667 }
24668
24669 /* memory allocation interface */
24670
24671 static struct dwarf_block *
24672 dwarf_alloc_block (struct dwarf2_cu *cu)
24673 {
24674   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24675 }
24676
24677 static struct die_info *
24678 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24679 {
24680   struct die_info *die;
24681   size_t size = sizeof (struct die_info);
24682
24683   if (num_attrs > 1)
24684     size += (num_attrs - 1) * sizeof (struct attribute);
24685
24686   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24687   memset (die, 0, sizeof (struct die_info));
24688   return (die);
24689 }
24690
24691 \f
24692
24693 /* Macro support.  */
24694
24695 /* An overload of dwarf_decode_macros that finds the correct section
24696    and ensures it is read in before calling the other overload.  */
24697
24698 static void
24699 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24700                      int section_is_gnu)
24701 {
24702   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24703   struct objfile *objfile = per_objfile->objfile;
24704   const struct line_header *lh = cu->line_header;
24705   unsigned int offset_size = cu->header.offset_size;
24706   struct dwarf2_section_info *section;
24707   const char *section_name;
24708
24709   if (cu->dwo_unit != nullptr)
24710     {
24711       if (section_is_gnu)
24712         {
24713           section = &cu->dwo_unit->dwo_file->sections.macro;
24714           section_name = ".debug_macro.dwo";
24715         }
24716       else
24717         {
24718           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24719           section_name = ".debug_macinfo.dwo";
24720         }
24721     }
24722   else
24723     {
24724       if (section_is_gnu)
24725         {
24726           section = &per_objfile->per_bfd->macro;
24727           section_name = ".debug_macro";
24728         }
24729       else
24730         {
24731           section = &per_objfile->per_bfd->macinfo;
24732           section_name = ".debug_macinfo";
24733         }
24734     }
24735
24736   section->read (objfile);
24737   if (section->buffer == nullptr)
24738     {
24739       complaint (_("missing %s section"), section_name);
24740       return;
24741     }
24742
24743   buildsym_compunit *builder = cu->get_builder ();
24744
24745   struct dwarf2_section_info *str_offsets_section;
24746   struct dwarf2_section_info *str_section;
24747   ULONGEST str_offsets_base;
24748
24749   if (cu->dwo_unit != nullptr)
24750     {
24751       str_offsets_section = &cu->dwo_unit->dwo_file
24752                                ->sections.str_offsets;
24753       str_section = &cu->dwo_unit->dwo_file->sections.str;
24754       str_offsets_base = cu->header.addr_size;
24755     }
24756   else
24757     {
24758       str_offsets_section = &per_objfile->per_bfd->str_offsets;
24759       str_section = &per_objfile->per_bfd->str;
24760       str_offsets_base = *cu->str_offsets_base;
24761     }
24762
24763   dwarf_decode_macros (per_objfile, builder, section, lh,
24764                        offset_size, offset, str_section, str_offsets_section,
24765                        str_offsets_base, section_is_gnu);
24766 }
24767
24768 /* Return the .debug_loc section to use for CU.
24769    For DWO files use .debug_loc.dwo.  */
24770
24771 static struct dwarf2_section_info *
24772 cu_debug_loc_section (struct dwarf2_cu *cu)
24773 {
24774   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24775
24776   if (cu->dwo_unit)
24777     {
24778       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24779
24780       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24781     }
24782   return (cu->header.version >= 5 ? &per_objfile->per_bfd->loclists
24783                                   : &per_objfile->per_bfd->loc);
24784 }
24785
24786 /* Return the .debug_rnglists section to use for CU.  */
24787 static struct dwarf2_section_info *
24788 cu_debug_rnglists_section (struct dwarf2_cu *cu, dwarf_tag tag)
24789 {
24790   if (cu->header.version < 5)
24791     error (_(".debug_rnglists section cannot be used in DWARF %d"),
24792            cu->header.version);
24793   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->per_objfile;
24794
24795   /* Make sure we read the .debug_rnglists section from the file that
24796      contains the DW_AT_ranges attribute we are reading.  Normally that
24797      would be the .dwo file, if there is one.  However for DW_TAG_compile_unit
24798      or DW_TAG_skeleton unit, we always want to read from objfile/linked
24799      program.  */
24800   if (cu->dwo_unit != nullptr
24801       && tag != DW_TAG_compile_unit
24802       && tag != DW_TAG_skeleton_unit)
24803     {
24804       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24805
24806       if (sections->rnglists.size > 0)
24807         return &sections->rnglists;
24808       else
24809         error (_(".debug_rnglists section is missing from .dwo file."));
24810     }
24811   return &dwarf2_per_objfile->per_bfd->rnglists;
24812 }
24813
24814 /* A helper function that fills in a dwarf2_loclist_baton.  */
24815
24816 static void
24817 fill_in_loclist_baton (struct dwarf2_cu *cu,
24818                        struct dwarf2_loclist_baton *baton,
24819                        const struct attribute *attr)
24820 {
24821   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24822   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24823
24824   section->read (per_objfile->objfile);
24825
24826   baton->per_objfile = per_objfile;
24827   baton->per_cu = cu->per_cu;
24828   gdb_assert (baton->per_cu);
24829   /* We don't know how long the location list is, but make sure we
24830      don't run off the edge of the section.  */
24831   baton->size = section->size - attr->as_unsigned ();
24832   baton->data = section->buffer + attr->as_unsigned ();
24833   if (cu->base_address.has_value ())
24834     baton->base_address = *cu->base_address;
24835   else
24836     baton->base_address = 0;
24837   baton->from_dwo = cu->dwo_unit != NULL;
24838 }
24839
24840 static void
24841 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24842                              struct dwarf2_cu *cu, int is_block)
24843 {
24844   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24845   struct objfile *objfile = per_objfile->objfile;
24846   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24847
24848   if (attr->form_is_section_offset ()
24849       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24850          the section.  If so, fall through to the complaint in the
24851          other branch.  */
24852       && attr->as_unsigned () < section->get_size (objfile))
24853     {
24854       struct dwarf2_loclist_baton *baton;
24855
24856       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24857
24858       fill_in_loclist_baton (cu, baton, attr);
24859
24860       if (!cu->base_address.has_value ())
24861         complaint (_("Location list used without "
24862                      "specifying the CU base address."));
24863
24864       SYMBOL_ACLASS_INDEX (sym) = (is_block
24865                                    ? dwarf2_loclist_block_index
24866                                    : dwarf2_loclist_index);
24867       SYMBOL_LOCATION_BATON (sym) = baton;
24868     }
24869   else
24870     {
24871       struct dwarf2_locexpr_baton *baton;
24872
24873       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24874       baton->per_objfile = per_objfile;
24875       baton->per_cu = cu->per_cu;
24876       gdb_assert (baton->per_cu);
24877
24878       if (attr->form_is_block ())
24879         {
24880           /* Note that we're just copying the block's data pointer
24881              here, not the actual data.  We're still pointing into the
24882              info_buffer for SYM's objfile; right now we never release
24883              that buffer, but when we do clean up properly this may
24884              need to change.  */
24885           struct dwarf_block *block = attr->as_block ();
24886           baton->size = block->size;
24887           baton->data = block->data;
24888         }
24889       else
24890         {
24891           dwarf2_invalid_attrib_class_complaint ("location description",
24892                                                  sym->natural_name ());
24893           baton->size = 0;
24894         }
24895
24896       SYMBOL_ACLASS_INDEX (sym) = (is_block
24897                                    ? dwarf2_locexpr_block_index
24898                                    : dwarf2_locexpr_index);
24899       SYMBOL_LOCATION_BATON (sym) = baton;
24900     }
24901 }
24902
24903 /* See read.h.  */
24904
24905 const comp_unit_head *
24906 dwarf2_per_cu_data::get_header () const
24907 {
24908   if (!m_header_read_in)
24909     {
24910       const gdb_byte *info_ptr
24911         = this->section->buffer + to_underlying (this->sect_off);
24912
24913       memset (&m_header, 0, sizeof (m_header));
24914
24915       read_comp_unit_head (&m_header, info_ptr, this->section,
24916                            rcuh_kind::COMPILE);
24917
24918       m_header_read_in = true;
24919     }
24920
24921   return &m_header;
24922 }
24923
24924 /* See read.h.  */
24925
24926 int
24927 dwarf2_per_cu_data::addr_size () const
24928 {
24929   return this->get_header ()->addr_size;
24930 }
24931
24932 /* See read.h.  */
24933
24934 int
24935 dwarf2_per_cu_data::offset_size () const
24936 {
24937   return this->get_header ()->offset_size;
24938 }
24939
24940 /* See read.h.  */
24941
24942 int
24943 dwarf2_per_cu_data::ref_addr_size () const
24944 {
24945   const comp_unit_head *header = this->get_header ();
24946
24947   if (header->version == 2)
24948     return header->addr_size;
24949   else
24950     return header->offset_size;
24951 }
24952
24953 /* See read.h.  */
24954
24955 struct type *
24956 dwarf2_cu::addr_type () const
24957 {
24958   struct objfile *objfile = this->per_objfile->objfile;
24959   struct type *void_type = objfile_type (objfile)->builtin_void;
24960   struct type *addr_type = lookup_pointer_type (void_type);
24961   int addr_size = this->per_cu->addr_size ();
24962
24963   if (TYPE_LENGTH (addr_type) == addr_size)
24964     return addr_type;
24965
24966   addr_type = addr_sized_int_type (addr_type->is_unsigned ());
24967   return addr_type;
24968 }
24969
24970 /* A helper function for dwarf2_find_containing_comp_unit that returns
24971    the index of the result, and that searches a vector.  It will
24972    return a result even if the offset in question does not actually
24973    occur in any CU.  This is separate so that it can be unit
24974    tested.  */
24975
24976 static int
24977 dwarf2_find_containing_comp_unit
24978   (sect_offset sect_off,
24979    unsigned int offset_in_dwz,
24980    const std::vector<dwarf2_per_cu_data *> &all_comp_units)
24981 {
24982   int low, high;
24983
24984   low = 0;
24985   high = all_comp_units.size () - 1;
24986   while (high > low)
24987     {
24988       struct dwarf2_per_cu_data *mid_cu;
24989       int mid = low + (high - low) / 2;
24990
24991       mid_cu = all_comp_units[mid];
24992       if (mid_cu->is_dwz > offset_in_dwz
24993           || (mid_cu->is_dwz == offset_in_dwz
24994               && mid_cu->sect_off + mid_cu->length > sect_off))
24995         high = mid;
24996       else
24997         low = mid + 1;
24998     }
24999   gdb_assert (low == high);
25000   return low;
25001 }
25002
25003 /* Locate the .debug_info compilation unit from CU's objfile which contains
25004    the DIE at OFFSET.  Raises an error on failure.  */
25005
25006 static struct dwarf2_per_cu_data *
25007 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25008                                   unsigned int offset_in_dwz,
25009                                   dwarf2_per_objfile *per_objfile)
25010 {
25011   int low = dwarf2_find_containing_comp_unit
25012     (sect_off, offset_in_dwz, per_objfile->per_bfd->all_comp_units);
25013   dwarf2_per_cu_data *this_cu = per_objfile->per_bfd->all_comp_units[low];
25014
25015   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
25016     {
25017       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25018         error (_("Dwarf Error: could not find partial DIE containing "
25019                "offset %s [in module %s]"),
25020                sect_offset_str (sect_off),
25021                bfd_get_filename (per_objfile->objfile->obfd));
25022
25023       gdb_assert (per_objfile->per_bfd->all_comp_units[low-1]->sect_off
25024                   <= sect_off);
25025       return per_objfile->per_bfd->all_comp_units[low-1];
25026     }
25027   else
25028     {
25029       if (low == per_objfile->per_bfd->all_comp_units.size () - 1
25030           && sect_off >= this_cu->sect_off + this_cu->length)
25031         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25032       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25033       return this_cu;
25034     }
25035 }
25036
25037 #if GDB_SELF_TEST
25038
25039 namespace selftests {
25040 namespace find_containing_comp_unit {
25041
25042 static void
25043 run_test ()
25044 {
25045   struct dwarf2_per_cu_data one {};
25046   struct dwarf2_per_cu_data two {};
25047   struct dwarf2_per_cu_data three {};
25048   struct dwarf2_per_cu_data four {};
25049
25050   one.length = 5;
25051   two.sect_off = sect_offset (one.length);
25052   two.length = 7;
25053
25054   three.length = 5;
25055   three.is_dwz = 1;
25056   four.sect_off = sect_offset (three.length);
25057   four.length = 7;
25058   four.is_dwz = 1;
25059
25060   std::vector<dwarf2_per_cu_data *> units;
25061   units.push_back (&one);
25062   units.push_back (&two);
25063   units.push_back (&three);
25064   units.push_back (&four);
25065
25066   int result;
25067
25068   result = dwarf2_find_containing_comp_unit (sect_offset (0), 0, units);
25069   SELF_CHECK (units[result] == &one);
25070   result = dwarf2_find_containing_comp_unit (sect_offset (3), 0, units);
25071   SELF_CHECK (units[result] == &one);
25072   result = dwarf2_find_containing_comp_unit (sect_offset (5), 0, units);
25073   SELF_CHECK (units[result] == &two);
25074
25075   result = dwarf2_find_containing_comp_unit (sect_offset (0), 1, units);
25076   SELF_CHECK (units[result] == &three);
25077   result = dwarf2_find_containing_comp_unit (sect_offset (3), 1, units);
25078   SELF_CHECK (units[result] == &three);
25079   result = dwarf2_find_containing_comp_unit (sect_offset (5), 1, units);
25080   SELF_CHECK (units[result] == &four);
25081 }
25082
25083 }
25084 }
25085
25086 #endif /* GDB_SELF_TEST */
25087
25088 /* Initialize dwarf2_cu to read PER_CU, in the context of PER_OBJFILE.  */
25089
25090 dwarf2_cu::dwarf2_cu (dwarf2_per_cu_data *per_cu,
25091                       dwarf2_per_objfile *per_objfile)
25092   : per_cu (per_cu),
25093     per_objfile (per_objfile),
25094     mark (false),
25095     has_loclist (false),
25096     checked_producer (false),
25097     producer_is_gxx_lt_4_6 (false),
25098     producer_is_gcc_lt_4_3 (false),
25099     producer_is_icc (false),
25100     producer_is_icc_lt_14 (false),
25101     producer_is_codewarrior (false),
25102     processing_has_namespace_info (false)
25103 {
25104 }
25105
25106 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25107
25108 static void
25109 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25110                        enum language pretend_language)
25111 {
25112   struct attribute *attr;
25113
25114   /* Set the language we're debugging.  */
25115   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25116   if (attr != nullptr)
25117     set_cu_language (attr->constant_value (0), cu);
25118   else
25119     {
25120       cu->language = pretend_language;
25121       cu->language_defn = language_def (cu->language);
25122     }
25123
25124   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25125 }
25126
25127 /* See read.h.  */
25128
25129 dwarf2_cu *
25130 dwarf2_per_objfile::get_cu (dwarf2_per_cu_data *per_cu)
25131 {
25132   auto it = m_dwarf2_cus.find (per_cu);
25133   if (it == m_dwarf2_cus.end ())
25134     return nullptr;
25135
25136   return it->second;
25137 }
25138
25139 /* See read.h.  */
25140
25141 void
25142 dwarf2_per_objfile::set_cu (dwarf2_per_cu_data *per_cu, dwarf2_cu *cu)
25143 {
25144   gdb_assert (this->get_cu (per_cu) == nullptr);
25145
25146   m_dwarf2_cus[per_cu] = cu;
25147 }
25148
25149 /* See read.h.  */
25150
25151 void
25152 dwarf2_per_objfile::age_comp_units ()
25153 {
25154   dwarf_read_debug_printf_v ("running");
25155
25156   /* This is not expected to be called in the middle of CU expansion.  There is
25157      an invariant that if a CU is in the CUs-to-expand queue, its DIEs are
25158      loaded in memory.  Calling age_comp_units while the queue is in use could
25159      make us free the DIEs for a CU that is in the queue and therefore break
25160      that invariant.  */
25161   gdb_assert (!this->per_bfd->queue.has_value ());
25162
25163   /* Start by clearing all marks.  */
25164   for (auto pair : m_dwarf2_cus)
25165     pair.second->mark = false;
25166
25167   /* Traverse all CUs, mark them and their dependencies if used recently
25168      enough.  */
25169   for (auto pair : m_dwarf2_cus)
25170     {
25171       dwarf2_cu *cu = pair.second;
25172
25173       cu->last_used++;
25174       if (cu->last_used <= dwarf_max_cache_age)
25175         dwarf2_mark (cu);
25176     }
25177
25178   /* Delete all CUs still not marked.  */
25179   for (auto it = m_dwarf2_cus.begin (); it != m_dwarf2_cus.end ();)
25180     {
25181       dwarf2_cu *cu = it->second;
25182
25183       if (!cu->mark)
25184         {
25185           dwarf_read_debug_printf_v ("deleting old CU %s",
25186                                      sect_offset_str (cu->per_cu->sect_off));
25187           delete cu;
25188           it = m_dwarf2_cus.erase (it);
25189         }
25190       else
25191         it++;
25192     }
25193 }
25194
25195 /* See read.h.  */
25196
25197 void
25198 dwarf2_per_objfile::remove_cu (dwarf2_per_cu_data *per_cu)
25199 {
25200   auto it = m_dwarf2_cus.find (per_cu);
25201   if (it == m_dwarf2_cus.end ())
25202     return;
25203
25204   delete it->second;
25205
25206   m_dwarf2_cus.erase (it);
25207 }
25208
25209 dwarf2_per_objfile::~dwarf2_per_objfile ()
25210 {
25211   remove_all_cus ();
25212 }
25213
25214 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25215    We store these in a hash table separate from the DIEs, and preserve them
25216    when the DIEs are flushed out of cache.
25217
25218    The CU "per_cu" pointer is needed because offset alone is not enough to
25219    uniquely identify the type.  A file may have multiple .debug_types sections,
25220    or the type may come from a DWO file.  Furthermore, while it's more logical
25221    to use per_cu->section+offset, with Fission the section with the data is in
25222    the DWO file but we don't know that section at the point we need it.
25223    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25224    because we can enter the lookup routine, get_die_type_at_offset, from
25225    outside this file, and thus won't necessarily have PER_CU->cu.
25226    Fortunately, PER_CU is stable for the life of the objfile.  */
25227
25228 struct dwarf2_per_cu_offset_and_type
25229 {
25230   const struct dwarf2_per_cu_data *per_cu;
25231   sect_offset sect_off;
25232   struct type *type;
25233 };
25234
25235 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25236
25237 static hashval_t
25238 per_cu_offset_and_type_hash (const void *item)
25239 {
25240   const struct dwarf2_per_cu_offset_and_type *ofs
25241     = (const struct dwarf2_per_cu_offset_and_type *) item;
25242
25243   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25244 }
25245
25246 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25247
25248 static int
25249 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25250 {
25251   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25252     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25253   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25254     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25255
25256   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25257           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25258 }
25259
25260 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25261    table if necessary.  For convenience, return TYPE.
25262
25263    The DIEs reading must have careful ordering to:
25264     * Not cause infinite loops trying to read in DIEs as a prerequisite for
25265       reading current DIE.
25266     * Not trying to dereference contents of still incompletely read in types
25267       while reading in other DIEs.
25268     * Enable referencing still incompletely read in types just by a pointer to
25269       the type without accessing its fields.
25270
25271    Therefore caller should follow these rules:
25272      * Try to fetch any prerequisite types we may need to build this DIE type
25273        before building the type and calling set_die_type.
25274      * After building type call set_die_type for current DIE as soon as
25275        possible before fetching more types to complete the current type.
25276      * Make the type as complete as possible before fetching more types.  */
25277
25278 static struct type *
25279 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
25280               bool skip_data_location)
25281 {
25282   dwarf2_per_objfile *per_objfile = cu->per_objfile;
25283   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25284   struct objfile *objfile = per_objfile->objfile;
25285   struct attribute *attr;
25286   struct dynamic_prop prop;
25287
25288   /* For Ada types, make sure that the gnat-specific data is always
25289      initialized (if not already set).  There are a few types where
25290      we should not be doing so, because the type-specific area is
25291      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25292      where the type-specific area is used to store the floatformat).
25293      But this is not a problem, because the gnat-specific information
25294      is actually not needed for these types.  */
25295   if (need_gnat_info (cu)
25296       && type->code () != TYPE_CODE_FUNC
25297       && type->code () != TYPE_CODE_FLT
25298       && type->code () != TYPE_CODE_METHODPTR
25299       && type->code () != TYPE_CODE_MEMBERPTR
25300       && type->code () != TYPE_CODE_METHOD
25301       && type->code () != TYPE_CODE_FIXED_POINT
25302       && !HAVE_GNAT_AUX_INFO (type))
25303     INIT_GNAT_SPECIFIC (type);
25304
25305   /* Read DW_AT_allocated and set in type.  */
25306   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25307   if (attr != NULL)
25308     {
25309       struct type *prop_type = cu->addr_sized_int_type (false);
25310       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
25311         type->add_dyn_prop (DYN_PROP_ALLOCATED, prop);
25312     }
25313
25314   /* Read DW_AT_associated and set in type.  */
25315   attr = dwarf2_attr (die, DW_AT_associated, cu);
25316   if (attr != NULL)
25317     {
25318       struct type *prop_type = cu->addr_sized_int_type (false);
25319       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
25320         type->add_dyn_prop (DYN_PROP_ASSOCIATED, prop);
25321     }
25322
25323   /* Read DW_AT_data_location and set in type.  */
25324   if (!skip_data_location)
25325     {
25326       attr = dwarf2_attr (die, DW_AT_data_location, cu);
25327       if (attr_to_dynamic_prop (attr, die, cu, &prop, cu->addr_type ()))
25328         type->add_dyn_prop (DYN_PROP_DATA_LOCATION, prop);
25329     }
25330
25331   if (per_objfile->die_type_hash == NULL)
25332     per_objfile->die_type_hash
25333       = htab_up (htab_create_alloc (127,
25334                                     per_cu_offset_and_type_hash,
25335                                     per_cu_offset_and_type_eq,
25336                                     NULL, xcalloc, xfree));
25337
25338   ofs.per_cu = cu->per_cu;
25339   ofs.sect_off = die->sect_off;
25340   ofs.type = type;
25341   slot = (struct dwarf2_per_cu_offset_and_type **)
25342     htab_find_slot (per_objfile->die_type_hash.get (), &ofs, INSERT);
25343   if (*slot)
25344     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25345                sect_offset_str (die->sect_off));
25346   *slot = XOBNEW (&objfile->objfile_obstack,
25347                   struct dwarf2_per_cu_offset_and_type);
25348   **slot = ofs;
25349   return type;
25350 }
25351
25352 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25353    or return NULL if the die does not have a saved type.  */
25354
25355 static struct type *
25356 get_die_type_at_offset (sect_offset sect_off,
25357                         dwarf2_per_cu_data *per_cu,
25358                         dwarf2_per_objfile *per_objfile)
25359 {
25360   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25361
25362   if (per_objfile->die_type_hash == NULL)
25363     return NULL;
25364
25365   ofs.per_cu = per_cu;
25366   ofs.sect_off = sect_off;
25367   slot = ((struct dwarf2_per_cu_offset_and_type *)
25368           htab_find (per_objfile->die_type_hash.get (), &ofs));
25369   if (slot)
25370     return slot->type;
25371   else
25372     return NULL;
25373 }
25374
25375 /* Look up the type for DIE in CU in die_type_hash,
25376    or return NULL if DIE does not have a saved type.  */
25377
25378 static struct type *
25379 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25380 {
25381   return get_die_type_at_offset (die->sect_off, cu->per_cu, cu->per_objfile);
25382 }
25383
25384 /* Add a dependence relationship from CU to REF_PER_CU.  */
25385
25386 static void
25387 dwarf2_add_dependence (struct dwarf2_cu *cu,
25388                        struct dwarf2_per_cu_data *ref_per_cu)
25389 {
25390   void **slot;
25391
25392   if (cu->dependencies == NULL)
25393     cu->dependencies
25394       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25395                               NULL, &cu->comp_unit_obstack,
25396                               hashtab_obstack_allocate,
25397                               dummy_obstack_deallocate);
25398
25399   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25400   if (*slot == NULL)
25401     *slot = ref_per_cu;
25402 }
25403
25404 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25405    Set the mark field in every compilation unit in the
25406    cache that we must keep because we are keeping CU.
25407
25408    DATA is the dwarf2_per_objfile object in which to look up CUs.  */
25409
25410 static int
25411 dwarf2_mark_helper (void **slot, void *data)
25412 {
25413   dwarf2_per_cu_data *per_cu = (dwarf2_per_cu_data *) *slot;
25414   dwarf2_per_objfile *per_objfile = (dwarf2_per_objfile *) data;
25415   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
25416
25417   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25418      reading of the chain.  As such dependencies remain valid it is not much
25419      useful to track and undo them during QUIT cleanups.  */
25420   if (cu == nullptr)
25421     return 1;
25422
25423   if (cu->mark)
25424     return 1;
25425
25426   cu->mark = true;
25427
25428   if (cu->dependencies != nullptr)
25429     htab_traverse (cu->dependencies, dwarf2_mark_helper, per_objfile);
25430
25431   return 1;
25432 }
25433
25434 /* Set the mark field in CU and in every other compilation unit in the
25435    cache that we must keep because we are keeping CU.  */
25436
25437 static void
25438 dwarf2_mark (struct dwarf2_cu *cu)
25439 {
25440   if (cu->mark)
25441     return;
25442
25443   cu->mark = true;
25444
25445   if (cu->dependencies != nullptr)
25446     htab_traverse (cu->dependencies, dwarf2_mark_helper, cu->per_objfile);
25447 }
25448
25449 /* Trivial hash function for partial_die_info: the hash value of a DIE
25450    is its offset in .debug_info for this objfile.  */
25451
25452 static hashval_t
25453 partial_die_hash (const void *item)
25454 {
25455   const struct partial_die_info *part_die
25456     = (const struct partial_die_info *) item;
25457
25458   return to_underlying (part_die->sect_off);
25459 }
25460
25461 /* Trivial comparison function for partial_die_info structures: two DIEs
25462    are equal if they have the same offset.  */
25463
25464 static int
25465 partial_die_eq (const void *item_lhs, const void *item_rhs)
25466 {
25467   const struct partial_die_info *part_die_lhs
25468     = (const struct partial_die_info *) item_lhs;
25469   const struct partial_die_info *part_die_rhs
25470     = (const struct partial_die_info *) item_rhs;
25471
25472   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25473 }
25474
25475 struct cmd_list_element *set_dwarf_cmdlist;
25476 struct cmd_list_element *show_dwarf_cmdlist;
25477
25478 static void
25479 show_check_physname (struct ui_file *file, int from_tty,
25480                      struct cmd_list_element *c, const char *value)
25481 {
25482   fprintf_filtered (file,
25483                     _("Whether to check \"physname\" is %s.\n"),
25484                     value);
25485 }
25486
25487 void _initialize_dwarf2_read ();
25488 void
25489 _initialize_dwarf2_read ()
25490 {
25491   add_basic_prefix_cmd ("dwarf", class_maintenance, _("\
25492 Set DWARF specific variables.\n\
25493 Configure DWARF variables such as the cache size."),
25494                         &set_dwarf_cmdlist, "maintenance set dwarf ",
25495                         0/*allow-unknown*/, &maintenance_set_cmdlist);
25496
25497   add_show_prefix_cmd ("dwarf", class_maintenance, _("\
25498 Show DWARF specific variables.\n\
25499 Show DWARF variables such as the cache size."),
25500                        &show_dwarf_cmdlist, "maintenance show dwarf ",
25501                        0/*allow-unknown*/, &maintenance_show_cmdlist);
25502
25503   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25504                             &dwarf_max_cache_age, _("\
25505 Set the upper bound on the age of cached DWARF compilation units."), _("\
25506 Show the upper bound on the age of cached DWARF compilation units."), _("\
25507 A higher limit means that cached compilation units will be stored\n\
25508 in memory longer, and more total memory will be used.  Zero disables\n\
25509 caching, which can slow down startup."),
25510                             NULL,
25511                             show_dwarf_max_cache_age,
25512                             &set_dwarf_cmdlist,
25513                             &show_dwarf_cmdlist);
25514
25515   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25516 Set debugging of the DWARF reader."), _("\
25517 Show debugging of the DWARF reader."), _("\
25518 When enabled (non-zero), debugging messages are printed during DWARF\n\
25519 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25520 information.  A value greater than 1 provides more verbose information."),
25521                             NULL,
25522                             NULL,
25523                             &setdebuglist, &showdebuglist);
25524
25525   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25526 Set debugging of the DWARF DIE reader."), _("\
25527 Show debugging of the DWARF DIE reader."), _("\
25528 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25529 The value is the maximum depth to print."),
25530                              NULL,
25531                              NULL,
25532                              &setdebuglist, &showdebuglist);
25533
25534   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25535 Set debugging of the dwarf line reader."), _("\
25536 Show debugging of the dwarf line reader."), _("\
25537 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25538 A value of 1 (one) provides basic information.\n\
25539 A value greater than 1 provides more verbose information."),
25540                              NULL,
25541                              NULL,
25542                              &setdebuglist, &showdebuglist);
25543
25544   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25545 Set cross-checking of \"physname\" code against demangler."), _("\
25546 Show cross-checking of \"physname\" code against demangler."), _("\
25547 When enabled, GDB's internal \"physname\" code is checked against\n\
25548 the demangler."),
25549                            NULL, show_check_physname,
25550                            &setdebuglist, &showdebuglist);
25551
25552   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25553                            no_class, &use_deprecated_index_sections, _("\
25554 Set whether to use deprecated gdb_index sections."), _("\
25555 Show whether to use deprecated gdb_index sections."), _("\
25556 When enabled, deprecated .gdb_index sections are used anyway.\n\
25557 Normally they are ignored either because of a missing feature or\n\
25558 performance issue.\n\
25559 Warning: This option must be enabled before gdb reads the file."),
25560                            NULL,
25561                            NULL,
25562                            &setlist, &showlist);
25563
25564   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25565                                                         &dwarf2_locexpr_funcs);
25566   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25567                                                         &dwarf2_loclist_funcs);
25568
25569   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25570                                         &dwarf2_block_frame_base_locexpr_funcs);
25571   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25572                                         &dwarf2_block_frame_base_loclist_funcs);
25573
25574 #if GDB_SELF_TEST
25575   selftests::register_test ("dw2_expand_symtabs_matching",
25576                             selftests::dw2_expand_symtabs_matching::run_test);
25577   selftests::register_test ("dwarf2_find_containing_comp_unit",
25578                             selftests::find_containing_comp_unit::run_test);
25579 #endif
25580 }
This page took 1.507184 seconds and 4 git commands to generate.