]> Git Repo - binutils.git/blob - gdb/dwarf2/read.c
Simplify file_and_directory storage management
[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-head.h"
36 #include "dwarf2/cu.h"
37 #include "dwarf2/index-cache.h"
38 #include "dwarf2/index-common.h"
39 #include "dwarf2/leb.h"
40 #include "dwarf2/line-header.h"
41 #include "dwarf2/dwz.h"
42 #include "dwarf2/macro.h"
43 #include "dwarf2/die.h"
44 #include "dwarf2/sect-names.h"
45 #include "dwarf2/stringify.h"
46 #include "dwarf2/public.h"
47 #include "bfd.h"
48 #include "elf-bfd.h"
49 #include "symtab.h"
50 #include "gdbtypes.h"
51 #include "objfiles.h"
52 #include "dwarf2.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 #include <unordered_set>
92
93 /* When == 1, print basic high level tracing messages.
94    When > 1, be more verbose.
95    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
96 static unsigned int dwarf_read_debug = 0;
97
98 /* Print a "dwarf-read" debug statement if dwarf_read_debug is >= 1.  */
99
100 #define dwarf_read_debug_printf(fmt, ...) \
101   debug_prefixed_printf_cond (dwarf_read_debug >= 1, "dwarf-read", fmt, \
102                               ##__VA_ARGS__)
103
104 /* Print a "dwarf-read" debug statement if dwarf_read_debug is >= 2.  */
105
106 #define dwarf_read_debug_printf_v(fmt, ...) \
107   debug_prefixed_printf_cond (dwarf_read_debug >= 2, "dwarf-read", fmt, \
108                               ##__VA_ARGS__)
109
110 /* When non-zero, dump DIEs after they are read in.  */
111 static unsigned int dwarf_die_debug = 0;
112
113 /* When non-zero, dump line number entries as they are read in.  */
114 unsigned int dwarf_line_debug = 0;
115
116 /* When true, cross-check physname against demangler.  */
117 static bool check_physname = false;
118
119 /* When true, do not reject deprecated .gdb_index sections.  */
120 static bool use_deprecated_index_sections = false;
121
122 /* This is used to store the data that is always per objfile.  */
123 static const objfile_key<dwarf2_per_objfile> dwarf2_objfile_data_key;
124
125 /* These are used to store the dwarf2_per_bfd objects.
126
127    objfiles having the same BFD, which doesn't require relocations, are going to
128    share a dwarf2_per_bfd object, which is held in the _bfd_data_key version.
129
130    Other objfiles are not going to share a dwarf2_per_bfd with any other
131    objfiles, so they'll have their own version kept in the _objfile_data_key
132    version.  */
133 static const struct bfd_key<dwarf2_per_bfd> dwarf2_per_bfd_bfd_data_key;
134 static const struct objfile_key<dwarf2_per_bfd> dwarf2_per_bfd_objfile_data_key;
135
136 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
137
138 static int dwarf2_locexpr_index;
139 static int dwarf2_loclist_index;
140 static int dwarf2_locexpr_block_index;
141 static int dwarf2_loclist_block_index;
142
143 /* Size of .debug_loclists section header for 32-bit DWARF format.  */
144 #define LOCLIST_HEADER_SIZE32 12
145
146 /* Size of .debug_loclists section header for 64-bit DWARF format.  */
147 #define LOCLIST_HEADER_SIZE64 20
148
149 /* Size of .debug_rnglists section header for 32-bit DWARF format.  */
150 #define RNGLIST_HEADER_SIZE32 12
151
152 /* Size of .debug_rnglists section header for 64-bit DWARF format.  */
153 #define RNGLIST_HEADER_SIZE64 20
154
155 /* An index into a (C++) symbol name component in a symbol name as
156    recorded in the mapped_index's symbol table.  For each C++ symbol
157    in the symbol table, we record one entry for the start of each
158    component in the symbol in a table of name components, and then
159    sort the table, in order to be able to binary search symbol names,
160    ignoring leading namespaces, both completion and regular look up.
161    For example, for symbol "A::B::C", we'll have an entry that points
162    to "A::B::C", another that points to "B::C", and another for "C".
163    Note that function symbols in GDB index have no parameter
164    information, just the function/method names.  You can convert a
165    name_component to a "const char *" using the
166    'mapped_index::symbol_name_at(offset_type)' method.  */
167
168 struct name_component
169 {
170   /* Offset in the symbol name where the component starts.  Stored as
171      a (32-bit) offset instead of a pointer to save memory and improve
172      locality on 64-bit architectures.  */
173   offset_type name_offset;
174
175   /* The symbol's index in the symbol and constant pool tables of a
176      mapped_index.  */
177   offset_type idx;
178 };
179
180 /* Base class containing bits shared by both .gdb_index and
181    .debug_name indexes.  */
182
183 struct mapped_index_base
184 {
185   mapped_index_base () = default;
186   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
187
188   /* The name_component table (a sorted vector).  See name_component's
189      description above.  */
190   std::vector<name_component> name_components;
191
192   /* How NAME_COMPONENTS is sorted.  */
193   enum case_sensitivity name_components_casing;
194
195   /* Return the number of names in the symbol table.  */
196   virtual size_t symbol_name_count () const = 0;
197
198   /* Get the name of the symbol at IDX in the symbol table.  */
199   virtual const char *symbol_name_at
200     (offset_type idx, dwarf2_per_objfile *per_objfile) const = 0;
201
202   /* Return whether the name at IDX in the symbol table should be
203      ignored.  */
204   virtual bool symbol_name_slot_invalid (offset_type idx) const
205   {
206     return false;
207   }
208
209   /* Build the symbol name component sorted vector, if we haven't
210      yet.  */
211   void build_name_components (dwarf2_per_objfile *per_objfile);
212
213   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
214      possible matches for LN_NO_PARAMS in the name component
215      vector.  */
216   std::pair<std::vector<name_component>::const_iterator,
217             std::vector<name_component>::const_iterator>
218     find_name_components_bounds (const lookup_name_info &ln_no_params,
219                                  enum language lang,
220                                  dwarf2_per_objfile *per_objfile) const;
221
222   /* Prevent deleting/destroying via a base class pointer.  */
223 protected:
224   ~mapped_index_base() = default;
225 };
226
227 /* This is a view into the index that converts from bytes to an
228    offset_type, and allows indexing.  Unaligned bytes are specifically
229    allowed here, and handled via unpacking.  */
230
231 class offset_view
232 {
233 public:
234   offset_view () = default;
235
236   explicit offset_view (gdb::array_view<const gdb_byte> bytes)
237     : m_bytes (bytes)
238   {
239   }
240
241   /* Extract the INDEXth offset_type from the array.  */
242   offset_type operator[] (size_t index) const
243   {
244     const gdb_byte *bytes = &m_bytes[index * sizeof (offset_type)];
245     return (offset_type) extract_unsigned_integer (bytes,
246                                                    sizeof (offset_type),
247                                                    BFD_ENDIAN_LITTLE);
248   }
249
250   /* Return the number of offset_types in this array.  */
251   size_t size () const
252   {
253     return m_bytes.size () / sizeof (offset_type);
254   }
255
256   /* Return true if this view is empty.  */
257   bool empty () const
258   {
259     return m_bytes.empty ();
260   }
261
262 private:
263   /* The underlying bytes.  */
264   gdb::array_view<const gdb_byte> m_bytes;
265 };
266
267 /* A description of the mapped index.  The file format is described in
268    a comment by the code that writes the index.  */
269 struct mapped_index final : public mapped_index_base
270 {
271   /* Index data format version.  */
272   int version = 0;
273
274   /* The address table data.  */
275   gdb::array_view<const gdb_byte> address_table;
276
277   /* The symbol table, implemented as a hash table.  */
278   offset_view symbol_table;
279
280   /* A pointer to the constant pool.  */
281   gdb::array_view<const gdb_byte> constant_pool;
282
283   /* Return the index into the constant pool of the name of the IDXth
284      symbol in the symbol table.  */
285   offset_type symbol_name_index (offset_type idx) const
286   {
287     return symbol_table[2 * idx];
288   }
289
290   /* Return the index into the constant pool of the CU vector of the
291      IDXth symbol in the symbol table.  */
292   offset_type symbol_vec_index (offset_type idx) const
293   {
294     return symbol_table[2 * idx + 1];
295   }
296
297   bool symbol_name_slot_invalid (offset_type idx) const override
298   {
299     return (symbol_name_index (idx) == 0
300             && symbol_vec_index (idx) == 0);
301   }
302
303   /* Convenience method to get at the name of the symbol at IDX in the
304      symbol table.  */
305   const char *symbol_name_at
306     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
307   {
308     return (const char *) (this->constant_pool.data ()
309                            + symbol_name_index (idx));
310   }
311
312   size_t symbol_name_count () const override
313   { return this->symbol_table.size () / 2; }
314 };
315
316 /* A description of the mapped .debug_names.
317    Uninitialized map has CU_COUNT 0.  */
318 struct mapped_debug_names final : public mapped_index_base
319 {
320   bfd_endian dwarf5_byte_order;
321   bool dwarf5_is_dwarf64;
322   bool augmentation_is_gdb;
323   uint8_t offset_size;
324   uint32_t cu_count = 0;
325   uint32_t tu_count, bucket_count, name_count;
326   const gdb_byte *cu_table_reordered, *tu_table_reordered;
327   const uint32_t *bucket_table_reordered, *hash_table_reordered;
328   const gdb_byte *name_table_string_offs_reordered;
329   const gdb_byte *name_table_entry_offs_reordered;
330   const gdb_byte *entry_pool;
331
332   struct index_val
333   {
334     ULONGEST dwarf_tag;
335     struct attr
336     {
337       /* Attribute name DW_IDX_*.  */
338       ULONGEST dw_idx;
339
340       /* Attribute form DW_FORM_*.  */
341       ULONGEST form;
342
343       /* Value if FORM is DW_FORM_implicit_const.  */
344       LONGEST implicit_const;
345     };
346     std::vector<attr> attr_vec;
347   };
348
349   std::unordered_map<ULONGEST, index_val> abbrev_map;
350
351   const char *namei_to_name
352     (uint32_t namei, dwarf2_per_objfile *per_objfile) const;
353
354   /* Implementation of the mapped_index_base virtual interface, for
355      the name_components cache.  */
356
357   const char *symbol_name_at
358     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
359   { return namei_to_name (idx, per_objfile); }
360
361   size_t symbol_name_count () const override
362   { return this->name_count; }
363 };
364
365 /* See dwarf2read.h.  */
366
367 dwarf2_per_objfile *
368 get_dwarf2_per_objfile (struct objfile *objfile)
369 {
370   return dwarf2_objfile_data_key.get (objfile);
371 }
372
373 /* Default names of the debugging sections.  */
374
375 /* Note that if the debugging section has been compressed, it might
376    have a name like .zdebug_info.  */
377
378 const struct dwarf2_debug_sections dwarf2_elf_names =
379 {
380   { ".debug_info", ".zdebug_info" },
381   { ".debug_abbrev", ".zdebug_abbrev" },
382   { ".debug_line", ".zdebug_line" },
383   { ".debug_loc", ".zdebug_loc" },
384   { ".debug_loclists", ".zdebug_loclists" },
385   { ".debug_macinfo", ".zdebug_macinfo" },
386   { ".debug_macro", ".zdebug_macro" },
387   { ".debug_str", ".zdebug_str" },
388   { ".debug_str_offsets", ".zdebug_str_offsets" },
389   { ".debug_line_str", ".zdebug_line_str" },
390   { ".debug_ranges", ".zdebug_ranges" },
391   { ".debug_rnglists", ".zdebug_rnglists" },
392   { ".debug_types", ".zdebug_types" },
393   { ".debug_addr", ".zdebug_addr" },
394   { ".debug_frame", ".zdebug_frame" },
395   { ".eh_frame", NULL },
396   { ".gdb_index", ".zgdb_index" },
397   { ".debug_names", ".zdebug_names" },
398   { ".debug_aranges", ".zdebug_aranges" },
399   23
400 };
401
402 /* List of DWO/DWP sections.  */
403
404 static const struct dwop_section_names
405 {
406   struct dwarf2_section_names abbrev_dwo;
407   struct dwarf2_section_names info_dwo;
408   struct dwarf2_section_names line_dwo;
409   struct dwarf2_section_names loc_dwo;
410   struct dwarf2_section_names loclists_dwo;
411   struct dwarf2_section_names macinfo_dwo;
412   struct dwarf2_section_names macro_dwo;
413   struct dwarf2_section_names rnglists_dwo;
414   struct dwarf2_section_names str_dwo;
415   struct dwarf2_section_names str_offsets_dwo;
416   struct dwarf2_section_names types_dwo;
417   struct dwarf2_section_names cu_index;
418   struct dwarf2_section_names tu_index;
419 }
420 dwop_section_names =
421 {
422   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
423   { ".debug_info.dwo", ".zdebug_info.dwo" },
424   { ".debug_line.dwo", ".zdebug_line.dwo" },
425   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
426   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
427   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
428   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
429   { ".debug_rnglists.dwo", ".zdebug_rnglists.dwo" },
430   { ".debug_str.dwo", ".zdebug_str.dwo" },
431   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
432   { ".debug_types.dwo", ".zdebug_types.dwo" },
433   { ".debug_cu_index", ".zdebug_cu_index" },
434   { ".debug_tu_index", ".zdebug_tu_index" },
435 };
436
437 /* local data types */
438
439 /* The location list and range list sections (.debug_loclists & .debug_rnglists)
440    begin with a header,  which contains the following information.  */
441 struct loclists_rnglists_header
442 {
443   /* A 4-byte or 12-byte length containing the length of the
444      set of entries for this compilation unit, not including the
445      length field itself.  */
446   unsigned int length;
447
448   /* A 2-byte version identifier.  */
449   short version;
450
451   /* A 1-byte unsigned integer containing the size in bytes of an address on
452      the target system.  */
453   unsigned char addr_size;
454
455   /* A 1-byte unsigned integer containing the size in bytes of a segment selector
456      on the target system.  */
457   unsigned char segment_collector_size;
458
459   /* A 4-byte count of the number of offsets that follow the header.  */
460   unsigned int offset_entry_count;
461 };
462
463 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
464    This includes type_unit_group and quick_file_names.  */
465
466 struct stmt_list_hash
467 {
468   /* The DWO unit this table is from or NULL if there is none.  */
469   struct dwo_unit *dwo_unit;
470
471   /* Offset in .debug_line or .debug_line.dwo.  */
472   sect_offset line_sect_off;
473 };
474
475 /* Each element of dwarf2_per_bfd->type_unit_groups is a pointer to
476    an object of this type.  This contains elements of type unit groups
477    that can be shared across objfiles.  The non-shareable parts are in
478    type_unit_group_unshareable.  */
479
480 struct type_unit_group : public dwarf2_per_cu_data
481 {
482   /* The TUs that share this DW_AT_stmt_list entry.
483      This is added to while parsing type units to build partial symtabs,
484      and is deleted afterwards and not used again.  */
485   std::vector<signatured_type *> *tus = nullptr;
486
487   /* The data used to construct the hash key.  */
488   struct stmt_list_hash hash {};
489 };
490
491 /* These sections are what may appear in a (real or virtual) DWO file.  */
492
493 struct dwo_sections
494 {
495   struct dwarf2_section_info abbrev;
496   struct dwarf2_section_info line;
497   struct dwarf2_section_info loc;
498   struct dwarf2_section_info loclists;
499   struct dwarf2_section_info macinfo;
500   struct dwarf2_section_info macro;
501   struct dwarf2_section_info rnglists;
502   struct dwarf2_section_info str;
503   struct dwarf2_section_info str_offsets;
504   /* In the case of a virtual DWO file, these two are unused.  */
505   struct dwarf2_section_info info;
506   std::vector<dwarf2_section_info> types;
507 };
508
509 /* CUs/TUs in DWP/DWO files.  */
510
511 struct dwo_unit
512 {
513   /* Backlink to the containing struct dwo_file.  */
514   struct dwo_file *dwo_file;
515
516   /* The "id" that distinguishes this CU/TU.
517      .debug_info calls this "dwo_id", .debug_types calls this "signature".
518      Since signatures came first, we stick with it for consistency.  */
519   ULONGEST signature;
520
521   /* The section this CU/TU lives in, in the DWO file.  */
522   struct dwarf2_section_info *section;
523
524   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
525   sect_offset sect_off;
526   unsigned int length;
527
528   /* For types, offset in the type's DIE of the type defined by this TU.  */
529   cu_offset type_offset_in_tu;
530 };
531
532 /* include/dwarf2.h defines the DWP section codes.
533    It defines a max value but it doesn't define a min value, which we
534    use for error checking, so provide one.  */
535
536 enum dwp_v2_section_ids
537 {
538   DW_SECT_MIN = 1
539 };
540
541 /* Data for one DWO file.
542
543    This includes virtual DWO files (a virtual DWO file is a DWO file as it
544    appears in a DWP file).  DWP files don't really have DWO files per se -
545    comdat folding of types "loses" the DWO file they came from, and from
546    a high level view DWP files appear to contain a mass of random types.
547    However, to maintain consistency with the non-DWP case we pretend DWP
548    files contain virtual DWO files, and we assign each TU with one virtual
549    DWO file (generally based on the line and abbrev section offsets -
550    a heuristic that seems to work in practice).  */
551
552 struct dwo_file
553 {
554   dwo_file () = default;
555   DISABLE_COPY_AND_ASSIGN (dwo_file);
556
557   /* The DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.
558      For virtual DWO files the name is constructed from the section offsets
559      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
560      from related CU+TUs.  */
561   const char *dwo_name = nullptr;
562
563   /* The DW_AT_comp_dir attribute.  */
564   const char *comp_dir = nullptr;
565
566   /* The bfd, when the file is open.  Otherwise this is NULL.
567      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
568   gdb_bfd_ref_ptr dbfd;
569
570   /* The sections that make up this DWO file.
571      Remember that for virtual DWO files in DWP V2 or DWP V5, these are virtual
572      sections (for lack of a better name).  */
573   struct dwo_sections sections {};
574
575   /* The CUs in the file.
576      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
577      an extension to handle LLVM's Link Time Optimization output (where
578      multiple source files may be compiled into a single object/dwo pair). */
579   htab_up cus;
580
581   /* Table of TUs in the file.
582      Each element is a struct dwo_unit.  */
583   htab_up tus;
584 };
585
586 /* These sections are what may appear in a DWP file.  */
587
588 struct dwp_sections
589 {
590   /* These are used by all DWP versions (1, 2 and 5).  */
591   struct dwarf2_section_info str;
592   struct dwarf2_section_info cu_index;
593   struct dwarf2_section_info tu_index;
594
595   /* These are only used by DWP version 2 and version 5 files.
596      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
597      sections are referenced by section number, and are not recorded here.
598      In DWP version 2 or 5 there is at most one copy of all these sections,
599      each section being (effectively) comprised of the concatenation of all of
600      the individual sections that exist in the version 1 format.
601      To keep the code simple we treat each of these concatenated pieces as a
602      section itself (a virtual section?).  */
603   struct dwarf2_section_info abbrev;
604   struct dwarf2_section_info info;
605   struct dwarf2_section_info line;
606   struct dwarf2_section_info loc;
607   struct dwarf2_section_info loclists;
608   struct dwarf2_section_info macinfo;
609   struct dwarf2_section_info macro;
610   struct dwarf2_section_info rnglists;
611   struct dwarf2_section_info str_offsets;
612   struct dwarf2_section_info types;
613 };
614
615 /* These sections are what may appear in a virtual DWO file in DWP version 1.
616    A virtual DWO file is a DWO file as it appears in a DWP file.  */
617
618 struct virtual_v1_dwo_sections
619 {
620   struct dwarf2_section_info abbrev;
621   struct dwarf2_section_info line;
622   struct dwarf2_section_info loc;
623   struct dwarf2_section_info macinfo;
624   struct dwarf2_section_info macro;
625   struct dwarf2_section_info str_offsets;
626   /* Each DWP hash table entry records one CU or one TU.
627      That is recorded here, and copied to dwo_unit.section.  */
628   struct dwarf2_section_info info_or_types;
629 };
630
631 /* Similar to virtual_v1_dwo_sections, but for DWP version 2 or 5.
632    In version 2, the sections of the DWO files are concatenated together
633    and stored in one section of that name.  Thus each ELF section contains
634    several "virtual" sections.  */
635
636 struct virtual_v2_or_v5_dwo_sections
637 {
638   bfd_size_type abbrev_offset;
639   bfd_size_type abbrev_size;
640
641   bfd_size_type line_offset;
642   bfd_size_type line_size;
643
644   bfd_size_type loc_offset;
645   bfd_size_type loc_size;
646
647   bfd_size_type loclists_offset;
648   bfd_size_type loclists_size;
649
650   bfd_size_type macinfo_offset;
651   bfd_size_type macinfo_size;
652
653   bfd_size_type macro_offset;
654   bfd_size_type macro_size;
655
656   bfd_size_type rnglists_offset;
657   bfd_size_type rnglists_size;
658
659   bfd_size_type str_offsets_offset;
660   bfd_size_type str_offsets_size;
661
662   /* Each DWP hash table entry records one CU or one TU.
663      That is recorded here, and copied to dwo_unit.section.  */
664   bfd_size_type info_or_types_offset;
665   bfd_size_type info_or_types_size;
666 };
667
668 /* Contents of DWP hash tables.  */
669
670 struct dwp_hash_table
671 {
672   uint32_t version, nr_columns;
673   uint32_t nr_units, nr_slots;
674   const gdb_byte *hash_table, *unit_table;
675   union
676   {
677     struct
678     {
679       const gdb_byte *indices;
680     } v1;
681     struct
682     {
683       /* This is indexed by column number and gives the id of the section
684          in that column.  */
685 #define MAX_NR_V2_DWO_SECTIONS \
686   (1 /* .debug_info or .debug_types */ \
687    + 1 /* .debug_abbrev */ \
688    + 1 /* .debug_line */ \
689    + 1 /* .debug_loc */ \
690    + 1 /* .debug_str_offsets */ \
691    + 1 /* .debug_macro or .debug_macinfo */)
692       int section_ids[MAX_NR_V2_DWO_SECTIONS];
693       const gdb_byte *offsets;
694       const gdb_byte *sizes;
695     } v2;
696     struct
697     {
698       /* This is indexed by column number and gives the id of the section
699          in that column.  */
700 #define MAX_NR_V5_DWO_SECTIONS \
701   (1 /* .debug_info */ \
702    + 1 /* .debug_abbrev */ \
703    + 1 /* .debug_line */ \
704    + 1 /* .debug_loclists */ \
705    + 1 /* .debug_str_offsets */ \
706    + 1 /* .debug_macro */ \
707    + 1 /* .debug_rnglists */)
708       int section_ids[MAX_NR_V5_DWO_SECTIONS];
709       const gdb_byte *offsets;
710       const gdb_byte *sizes;
711     } v5;
712   } section_pool;
713 };
714
715 /* Data for one DWP file.  */
716
717 struct dwp_file
718 {
719   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
720     : name (name_),
721       dbfd (std::move (abfd))
722   {
723   }
724
725   /* Name of the file.  */
726   const char *name;
727
728   /* File format version.  */
729   int version = 0;
730
731   /* The bfd.  */
732   gdb_bfd_ref_ptr dbfd;
733
734   /* Section info for this file.  */
735   struct dwp_sections sections {};
736
737   /* Table of CUs in the file.  */
738   const struct dwp_hash_table *cus = nullptr;
739
740   /* Table of TUs in the file.  */
741   const struct dwp_hash_table *tus = nullptr;
742
743   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
744   htab_up loaded_cus;
745   htab_up loaded_tus;
746
747   /* Table to map ELF section numbers to their sections.
748      This is only needed for the DWP V1 file format.  */
749   unsigned int num_sections = 0;
750   asection **elf_sections = nullptr;
751 };
752
753 /* Struct used to pass misc. parameters to read_die_and_children, et
754    al.  which are used for both .debug_info and .debug_types dies.
755    All parameters here are unchanging for the life of the call.  This
756    struct exists to abstract away the constant parameters of die reading.  */
757
758 struct die_reader_specs
759 {
760   /* The bfd of die_section.  */
761   bfd *abfd;
762
763   /* The CU of the DIE we are parsing.  */
764   struct dwarf2_cu *cu;
765
766   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
767   struct dwo_file *dwo_file;
768
769   /* The section the die comes from.
770      This is either .debug_info or .debug_types, or the .dwo variants.  */
771   struct dwarf2_section_info *die_section;
772
773   /* die_section->buffer.  */
774   const gdb_byte *buffer;
775
776   /* The end of the buffer.  */
777   const gdb_byte *buffer_end;
778
779   /* The abbreviation table to use when reading the DIEs.  */
780   struct abbrev_table *abbrev_table;
781 };
782
783 /* A subclass of die_reader_specs that holds storage and has complex
784    constructor and destructor behavior.  */
785
786 class cutu_reader : public die_reader_specs
787 {
788 public:
789
790   cutu_reader (dwarf2_per_cu_data *this_cu,
791                dwarf2_per_objfile *per_objfile,
792                struct abbrev_table *abbrev_table,
793                dwarf2_cu *existing_cu,
794                bool skip_partial);
795
796   explicit cutu_reader (struct dwarf2_per_cu_data *this_cu,
797                         dwarf2_per_objfile *per_objfile,
798                         struct dwarf2_cu *parent_cu = nullptr,
799                         struct dwo_file *dwo_file = nullptr);
800
801   DISABLE_COPY_AND_ASSIGN (cutu_reader);
802
803   const gdb_byte *info_ptr = nullptr;
804   struct die_info *comp_unit_die = nullptr;
805   bool dummy_p = false;
806
807   /* Release the new CU, putting it on the chain.  This cannot be done
808      for dummy CUs.  */
809   void keep ();
810
811 private:
812   void init_tu_and_read_dwo_dies (dwarf2_per_cu_data *this_cu,
813                                   dwarf2_per_objfile *per_objfile,
814                                   dwarf2_cu *existing_cu);
815
816   struct dwarf2_per_cu_data *m_this_cu;
817   std::unique_ptr<dwarf2_cu> m_new_cu;
818
819   /* The ordinary abbreviation table.  */
820   abbrev_table_up m_abbrev_table_holder;
821
822   /* The DWO abbreviation table.  */
823   abbrev_table_up m_dwo_abbrev_table;
824 };
825
826 /* When we construct a partial symbol table entry we only
827    need this much information.  */
828 struct partial_die_info : public allocate_on_obstack
829   {
830     partial_die_info (sect_offset sect_off, const struct abbrev_info *abbrev);
831
832     /* Disable assign but still keep copy ctor, which is needed
833        load_partial_dies.   */
834     partial_die_info& operator=(const partial_die_info& rhs) = delete;
835     partial_die_info (const partial_die_info &) = default;
836
837     /* Adjust the partial die before generating a symbol for it.  This
838        function may set the is_external flag or change the DIE's
839        name.  */
840     void fixup (struct dwarf2_cu *cu);
841
842     /* Read a minimal amount of information into the minimal die
843        structure.  */
844     const gdb_byte *read (const struct die_reader_specs *reader,
845                           const struct abbrev_info &abbrev,
846                           const gdb_byte *info_ptr);
847
848     /* Compute the name of this partial DIE.  This memoizes the
849        result, so it is safe to call multiple times.  */
850     const char *name (dwarf2_cu *cu);
851
852     /* Offset of this DIE.  */
853     const sect_offset sect_off;
854
855     /* DWARF-2 tag for this DIE.  */
856     const ENUM_BITFIELD(dwarf_tag) tag : 16;
857
858     /* Assorted flags describing the data found in this DIE.  */
859     const unsigned int has_children : 1;
860
861     unsigned int is_external : 1;
862     unsigned int is_declaration : 1;
863     unsigned int has_type : 1;
864     unsigned int has_specification : 1;
865     unsigned int has_pc_info : 1;
866     unsigned int may_be_inlined : 1;
867
868     /* This DIE has been marked DW_AT_main_subprogram.  */
869     unsigned int main_subprogram : 1;
870
871     /* Flag set if the SCOPE field of this structure has been
872        computed.  */
873     unsigned int scope_set : 1;
874
875     /* Flag set if the DIE has a byte_size attribute.  */
876     unsigned int has_byte_size : 1;
877
878     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
879     unsigned int has_const_value : 1;
880
881     /* Flag set if any of the DIE's children are template arguments.  */
882     unsigned int has_template_arguments : 1;
883
884     /* Flag set if fixup has been called on this die.  */
885     unsigned int fixup_called : 1;
886
887     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
888     unsigned int is_dwz : 1;
889
890     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
891     unsigned int spec_is_dwz : 1;
892
893     unsigned int canonical_name : 1;
894
895     /* The name of this DIE.  Normally the value of DW_AT_name, but
896        sometimes a default name for unnamed DIEs.  */
897     const char *raw_name = nullptr;
898
899     /* The linkage name, if present.  */
900     const char *linkage_name = nullptr;
901
902     /* The scope to prepend to our children.  This is generally
903        allocated on the comp_unit_obstack, so will disappear
904        when this compilation unit leaves the cache.  */
905     const char *scope = nullptr;
906
907     /* Some data associated with the partial DIE.  The tag determines
908        which field is live.  */
909     union
910     {
911       /* The location description associated with this DIE, if any.  */
912       struct dwarf_block *locdesc;
913       /* The offset of an import, for DW_TAG_imported_unit.  */
914       sect_offset sect_off;
915     } d {};
916
917     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
918     CORE_ADDR lowpc = 0;
919     CORE_ADDR highpc = 0;
920
921     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
922        DW_AT_sibling, if any.  */
923     /* NOTE: This member isn't strictly necessary, partial_die_info::read
924        could return DW_AT_sibling values to its caller load_partial_dies.  */
925     const gdb_byte *sibling = nullptr;
926
927     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
928        DW_AT_specification (or DW_AT_abstract_origin or
929        DW_AT_extension).  */
930     sect_offset spec_offset {};
931
932     /* Pointers to this DIE's parent, first child, and next sibling,
933        if any.  */
934     struct partial_die_info *die_parent = nullptr;
935     struct partial_die_info *die_child = nullptr;
936     struct partial_die_info *die_sibling = nullptr;
937
938     friend struct partial_die_info *
939     dwarf2_cu::find_partial_die (sect_offset sect_off);
940
941   private:
942     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
943     partial_die_info (sect_offset sect_off)
944       : partial_die_info (sect_off, DW_TAG_padding, 0)
945     {
946     }
947
948     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
949                       int has_children_)
950       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
951     {
952       is_external = 0;
953       is_declaration = 0;
954       has_type = 0;
955       has_specification = 0;
956       has_pc_info = 0;
957       may_be_inlined = 0;
958       main_subprogram = 0;
959       scope_set = 0;
960       has_byte_size = 0;
961       has_const_value = 0;
962       has_template_arguments = 0;
963       fixup_called = 0;
964       is_dwz = 0;
965       spec_is_dwz = 0;
966       canonical_name = 0;
967     }
968   };
969
970 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
971    but this would require a corresponding change in unpack_field_as_long
972    and friends.  */
973 static int bits_per_byte = 8;
974
975 struct variant_part_builder;
976
977 /* When reading a variant, we track a bit more information about the
978    field, and store it in an object of this type.  */
979
980 struct variant_field
981 {
982   int first_field = -1;
983   int last_field = -1;
984
985   /* A variant can contain other variant parts.  */
986   std::vector<variant_part_builder> variant_parts;
987
988   /* If we see a DW_TAG_variant, then this will be set if this is the
989      default branch.  */
990   bool default_branch = false;
991   /* If we see a DW_AT_discr_value, then this will be the discriminant
992      value.  */
993   ULONGEST discriminant_value = 0;
994   /* If we see a DW_AT_discr_list, then this is a pointer to the list
995      data.  */
996   struct dwarf_block *discr_list_data = nullptr;
997 };
998
999 /* This represents a DW_TAG_variant_part.  */
1000
1001 struct variant_part_builder
1002 {
1003   /* The offset of the discriminant field.  */
1004   sect_offset discriminant_offset {};
1005
1006   /* Variants that are direct children of this variant part.  */
1007   std::vector<variant_field> variants;
1008
1009   /* True if we're currently reading a variant.  */
1010   bool processing_variant = false;
1011 };
1012
1013 struct nextfield
1014 {
1015   int accessibility = 0;
1016   int virtuality = 0;
1017   /* Variant parts need to find the discriminant, which is a DIE
1018      reference.  We track the section offset of each field to make
1019      this link.  */
1020   sect_offset offset;
1021   struct field field {};
1022 };
1023
1024 struct fnfieldlist
1025 {
1026   const char *name = nullptr;
1027   std::vector<struct fn_field> fnfields;
1028 };
1029
1030 /* The routines that read and process dies for a C struct or C++ class
1031    pass lists of data member fields and lists of member function fields
1032    in an instance of a field_info structure, as defined below.  */
1033 struct field_info
1034 {
1035   /* List of data member and baseclasses fields.  */
1036   std::vector<struct nextfield> fields;
1037   std::vector<struct nextfield> baseclasses;
1038
1039   /* Set if the accessibility of one of the fields is not public.  */
1040   bool non_public_fields = false;
1041
1042   /* Member function fieldlist array, contains name of possibly overloaded
1043      member function, number of overloaded member functions and a pointer
1044      to the head of the member function field chain.  */
1045   std::vector<struct fnfieldlist> fnfieldlists;
1046
1047   /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1048      a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1049   std::vector<struct decl_field> typedef_field_list;
1050
1051   /* Nested types defined by this class and the number of elements in this
1052      list.  */
1053   std::vector<struct decl_field> nested_types_list;
1054
1055   /* If non-null, this is the variant part we are currently
1056      reading.  */
1057   variant_part_builder *current_variant_part = nullptr;
1058   /* This holds all the top-level variant parts attached to the type
1059      we're reading.  */
1060   std::vector<variant_part_builder> variant_parts;
1061
1062   /* Return the total number of fields (including baseclasses).  */
1063   int nfields () const
1064   {
1065     return fields.size () + baseclasses.size ();
1066   }
1067 };
1068
1069 /* Loaded secondary compilation units are kept in memory until they
1070    have not been referenced for the processing of this many
1071    compilation units.  Set this to zero to disable caching.  Cache
1072    sizes of up to at least twenty will improve startup time for
1073    typical inter-CU-reference binaries, at an obvious memory cost.  */
1074 static int dwarf_max_cache_age = 5;
1075 static void
1076 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1077                           struct cmd_list_element *c, const char *value)
1078 {
1079   fprintf_filtered (file, _("The upper bound on the age of cached "
1080                             "DWARF compilation units is %s.\n"),
1081                     value);
1082 }
1083 \f
1084 /* local function prototypes */
1085
1086 static void dwarf2_find_base_address (struct die_info *die,
1087                                       struct dwarf2_cu *cu);
1088
1089 static dwarf2_psymtab *create_partial_symtab
1090   (dwarf2_per_cu_data *per_cu, dwarf2_per_objfile *per_objfile,
1091    const char *name);
1092
1093 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1094                                         const gdb_byte *info_ptr,
1095                                         struct die_info *type_unit_die);
1096
1097 static void dwarf2_build_psymtabs_hard (dwarf2_per_objfile *per_objfile);
1098
1099 static void scan_partial_symbols (struct partial_die_info *,
1100                                   CORE_ADDR *, CORE_ADDR *,
1101                                   int, struct dwarf2_cu *);
1102
1103 static void add_partial_symbol (struct partial_die_info *,
1104                                 struct dwarf2_cu *);
1105
1106 static void add_partial_namespace (struct partial_die_info *pdi,
1107                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1108                                    int set_addrmap, struct dwarf2_cu *cu);
1109
1110 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1111                                 CORE_ADDR *highpc, int set_addrmap,
1112                                 struct dwarf2_cu *cu);
1113
1114 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1115                                      struct dwarf2_cu *cu);
1116
1117 static void add_partial_subprogram (struct partial_die_info *pdi,
1118                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1119                                     int need_pc, struct dwarf2_cu *cu);
1120
1121 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1122
1123 static struct partial_die_info *load_partial_dies
1124   (const struct die_reader_specs *, const gdb_byte *, int);
1125
1126 /* A pair of partial_die_info and compilation unit.  */
1127 struct cu_partial_die_info
1128 {
1129   /* The compilation unit of the partial_die_info.  */
1130   struct dwarf2_cu *cu;
1131   /* A partial_die_info.  */
1132   struct partial_die_info *pdi;
1133
1134   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1135     : cu (cu),
1136       pdi (pdi)
1137   { /* Nothing.  */ }
1138
1139 private:
1140   cu_partial_die_info () = delete;
1141 };
1142
1143 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1144                                                           struct dwarf2_cu *);
1145
1146 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1147                                        struct attribute *,
1148                                        const struct attr_abbrev *,
1149                                        const gdb_byte *);
1150
1151 static void read_attribute_reprocess (const struct die_reader_specs *reader,
1152                                       struct attribute *attr, dwarf_tag tag);
1153
1154 static CORE_ADDR read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index);
1155
1156 static sect_offset read_abbrev_offset (dwarf2_per_objfile *per_objfile,
1157                                        dwarf2_section_info *, sect_offset);
1158
1159 static const char *read_indirect_string
1160   (dwarf2_per_objfile *per_objfile, bfd *, const gdb_byte *,
1161    const struct comp_unit_head *, unsigned int *);
1162
1163 static const char *read_indirect_string_at_offset
1164   (dwarf2_per_objfile *per_objfile, LONGEST str_offset);
1165
1166 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1167                                               const gdb_byte *,
1168                                               unsigned int *);
1169
1170 static const char *read_dwo_str_index (const struct die_reader_specs *reader,
1171                                        ULONGEST str_index);
1172
1173 static const char *read_stub_str_index (struct dwarf2_cu *cu,
1174                                         ULONGEST str_index);
1175
1176 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1177                                       struct dwarf2_cu *);
1178
1179 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1180                                        struct dwarf2_cu *cu);
1181
1182 static const char *dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu);
1183
1184 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1185                                struct dwarf2_cu *cu);
1186
1187 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1188
1189 static struct die_info *die_specification (struct die_info *die,
1190                                            struct dwarf2_cu **);
1191
1192 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1193                                                 struct dwarf2_cu *cu);
1194
1195 struct file_and_directory;
1196 static void dwarf_decode_lines (struct line_header *,
1197                                 const file_and_directory &,
1198                                 struct dwarf2_cu *, dwarf2_psymtab *,
1199                                 CORE_ADDR, int decode_mapping);
1200
1201 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1202                                   const char *);
1203
1204 static struct symbol *new_symbol (struct die_info *, struct type *,
1205                                   struct dwarf2_cu *, struct symbol * = NULL);
1206
1207 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1208                                 struct dwarf2_cu *);
1209
1210 static void dwarf2_const_value_attr (const struct attribute *attr,
1211                                      struct type *type,
1212                                      const char *name,
1213                                      struct obstack *obstack,
1214                                      struct dwarf2_cu *cu, LONGEST *value,
1215                                      const gdb_byte **bytes,
1216                                      struct dwarf2_locexpr_baton **baton);
1217
1218 static struct type *read_subrange_index_type (struct die_info *die,
1219                                               struct dwarf2_cu *cu);
1220
1221 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1222
1223 static int need_gnat_info (struct dwarf2_cu *);
1224
1225 static struct type *die_descriptive_type (struct die_info *,
1226                                           struct dwarf2_cu *);
1227
1228 static void set_descriptive_type (struct type *, struct die_info *,
1229                                   struct dwarf2_cu *);
1230
1231 static struct type *die_containing_type (struct die_info *,
1232                                          struct dwarf2_cu *);
1233
1234 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1235                                      struct dwarf2_cu *);
1236
1237 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1238
1239 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1240
1241 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1242
1243 static char *typename_concat (struct obstack *obs, const char *prefix,
1244                               const char *suffix, int physname,
1245                               struct dwarf2_cu *cu);
1246
1247 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1248
1249 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1250
1251 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1252
1253 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1254
1255 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1256
1257 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1258
1259 /* Return the .debug_loclists section to use for cu.  */
1260 static struct dwarf2_section_info *cu_debug_loc_section (struct dwarf2_cu *cu);
1261
1262 /* Return the .debug_rnglists section to use for cu.  */
1263 static struct dwarf2_section_info *cu_debug_rnglists_section
1264   (struct dwarf2_cu *cu, dwarf_tag tag);
1265
1266 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1267    values.  Keep the items ordered with increasing constraints compliance.  */
1268 enum pc_bounds_kind
1269 {
1270   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1271   PC_BOUNDS_NOT_PRESENT,
1272
1273   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1274      were present but they do not form a valid range of PC addresses.  */
1275   PC_BOUNDS_INVALID,
1276
1277   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1278   PC_BOUNDS_RANGES,
1279
1280   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1281   PC_BOUNDS_HIGH_LOW,
1282 };
1283
1284 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1285                                                  CORE_ADDR *, CORE_ADDR *,
1286                                                  struct dwarf2_cu *,
1287                                                  dwarf2_psymtab *);
1288
1289 static void get_scope_pc_bounds (struct die_info *,
1290                                  CORE_ADDR *, CORE_ADDR *,
1291                                  struct dwarf2_cu *);
1292
1293 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1294                                         CORE_ADDR, struct dwarf2_cu *);
1295
1296 static void dwarf2_add_field (struct field_info *, struct die_info *,
1297                               struct dwarf2_cu *);
1298
1299 static void dwarf2_attach_fields_to_type (struct field_info *,
1300                                           struct type *, struct dwarf2_cu *);
1301
1302 static void dwarf2_add_member_fn (struct field_info *,
1303                                   struct die_info *, struct type *,
1304                                   struct dwarf2_cu *);
1305
1306 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1307                                              struct type *,
1308                                              struct dwarf2_cu *);
1309
1310 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1311
1312 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1313
1314 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1315
1316 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1317
1318 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1319
1320 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1321
1322 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1323
1324 static struct type *read_module_type (struct die_info *die,
1325                                       struct dwarf2_cu *cu);
1326
1327 static const char *namespace_name (struct die_info *die,
1328                                    int *is_anonymous, struct dwarf2_cu *);
1329
1330 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1331
1332 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *,
1333                                  bool * = nullptr);
1334
1335 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1336                                                        struct dwarf2_cu *);
1337
1338 static struct die_info *read_die_and_siblings_1
1339   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1340    struct die_info *);
1341
1342 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1343                                                const gdb_byte *info_ptr,
1344                                                const gdb_byte **new_info_ptr,
1345                                                struct die_info *parent);
1346
1347 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1348                                         struct die_info **, const gdb_byte *,
1349                                         int);
1350
1351 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1352                                       struct die_info **, const gdb_byte *);
1353
1354 static void process_die (struct die_info *, struct dwarf2_cu *);
1355
1356 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1357                                              struct objfile *);
1358
1359 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1360
1361 static const char *dwarf2_full_name (const char *name,
1362                                      struct die_info *die,
1363                                      struct dwarf2_cu *cu);
1364
1365 static const char *dwarf2_physname (const char *name, struct die_info *die,
1366                                     struct dwarf2_cu *cu);
1367
1368 static struct die_info *dwarf2_extension (struct die_info *die,
1369                                           struct dwarf2_cu **);
1370
1371 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1372
1373 static void dump_die_for_error (struct die_info *);
1374
1375 static void dump_die_1 (struct ui_file *, int level, int max_level,
1376                         struct die_info *);
1377
1378 /*static*/ void dump_die (struct die_info *, int max_level);
1379
1380 static void store_in_ref_table (struct die_info *,
1381                                 struct dwarf2_cu *);
1382
1383 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1384                                                const struct attribute *,
1385                                                struct dwarf2_cu **);
1386
1387 static struct die_info *follow_die_ref (struct die_info *,
1388                                         const struct attribute *,
1389                                         struct dwarf2_cu **);
1390
1391 static struct die_info *follow_die_sig (struct die_info *,
1392                                         const struct attribute *,
1393                                         struct dwarf2_cu **);
1394
1395 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1396                                          struct dwarf2_cu *);
1397
1398 static struct type *get_DW_AT_signature_type (struct die_info *,
1399                                               const struct attribute *,
1400                                               struct dwarf2_cu *);
1401
1402 static void load_full_type_unit (dwarf2_per_cu_data *per_cu,
1403                                  dwarf2_per_objfile *per_objfile);
1404
1405 static void read_signatured_type (signatured_type *sig_type,
1406                                   dwarf2_per_objfile *per_objfile);
1407
1408 static int attr_to_dynamic_prop (const struct attribute *attr,
1409                                  struct die_info *die, struct dwarf2_cu *cu,
1410                                  struct dynamic_prop *prop, struct type *type);
1411
1412 /* memory allocation interface */
1413
1414 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1415
1416 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1417
1418 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1419
1420 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1421                                    struct dwarf2_loclist_baton *baton,
1422                                    const struct attribute *attr);
1423
1424 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1425                                          struct symbol *sym,
1426                                          struct dwarf2_cu *cu,
1427                                          int is_block);
1428
1429 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1430                                      const gdb_byte *info_ptr,
1431                                      const struct abbrev_info *abbrev);
1432
1433 static hashval_t partial_die_hash (const void *item);
1434
1435 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1436
1437 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1438   (sect_offset sect_off, unsigned int offset_in_dwz,
1439    dwarf2_per_objfile *per_objfile);
1440
1441 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1442                                    struct die_info *comp_unit_die,
1443                                    enum language pretend_language);
1444
1445 static struct type *set_die_type (struct die_info *, struct type *,
1446                                   struct dwarf2_cu *, bool = false);
1447
1448 static void create_all_comp_units (dwarf2_per_objfile *per_objfile);
1449
1450 static void load_full_comp_unit (dwarf2_per_cu_data *per_cu,
1451                                  dwarf2_per_objfile *per_objfile,
1452                                  dwarf2_cu *existing_cu,
1453                                  bool skip_partial,
1454                                  enum language pretend_language);
1455
1456 static void process_full_comp_unit (dwarf2_cu *cu,
1457                                     enum language pretend_language);
1458
1459 static void process_full_type_unit (dwarf2_cu *cu,
1460                                     enum language pretend_language);
1461
1462 static struct type *get_die_type_at_offset (sect_offset,
1463                                             dwarf2_per_cu_data *per_cu,
1464                                             dwarf2_per_objfile *per_objfile);
1465
1466 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1467
1468 static void queue_comp_unit (dwarf2_per_cu_data *per_cu,
1469                              dwarf2_per_objfile *per_objfile,
1470                              enum language pretend_language);
1471
1472 static void process_queue (dwarf2_per_objfile *per_objfile);
1473
1474 /* Class, the destructor of which frees all allocated queue entries.  This
1475    will only have work to do if an error was thrown while processing the
1476    dwarf.  If no error was thrown then the queue entries should have all
1477    been processed, and freed, as we went along.  */
1478
1479 class dwarf2_queue_guard
1480 {
1481 public:
1482   explicit dwarf2_queue_guard (dwarf2_per_objfile *per_objfile)
1483     : m_per_objfile (per_objfile)
1484   {
1485     gdb_assert (!m_per_objfile->per_bfd->queue.has_value ());
1486
1487     m_per_objfile->per_bfd->queue.emplace ();
1488   }
1489
1490   /* Free any entries remaining on the queue.  There should only be
1491      entries left if we hit an error while processing the dwarf.  */
1492   ~dwarf2_queue_guard ()
1493   {
1494     gdb_assert (m_per_objfile->per_bfd->queue.has_value ());
1495
1496     m_per_objfile->per_bfd->queue.reset ();
1497   }
1498
1499   DISABLE_COPY_AND_ASSIGN (dwarf2_queue_guard);
1500
1501 private:
1502   dwarf2_per_objfile *m_per_objfile;
1503 };
1504
1505 dwarf2_queue_item::~dwarf2_queue_item ()
1506 {
1507   /* Anything still marked queued is likely to be in an
1508      inconsistent state, so discard it.  */
1509   if (per_cu->queued)
1510     {
1511       per_objfile->remove_cu (per_cu);
1512       per_cu->queued = 0;
1513     }
1514 }
1515
1516 /* See dwarf2/read.h.  */
1517
1518 void
1519 dwarf2_per_cu_data_deleter::operator() (dwarf2_per_cu_data *data)
1520 {
1521   if (data->is_debug_types)
1522     delete static_cast<signatured_type *> (data);
1523   else
1524     delete data;
1525 }
1526
1527 /* The return type of find_file_and_directory.  Note, the enclosed
1528    string pointers are only valid while this object is valid.  */
1529
1530 struct file_and_directory
1531 {
1532   /* The filename.  This is never NULL.  */
1533   const char *name;
1534
1535   /* The compilation directory.  NULL if not known.  If we needed to
1536      compute a new string, it will be stored in the per-BFD string
1537      bcache; otherwise, points directly to the DW_AT_comp_dir string
1538      attribute owned by the obstack that owns the DIE.  */
1539   const char *comp_dir;
1540 };
1541
1542 static file_and_directory find_file_and_directory (struct die_info *die,
1543                                                    struct dwarf2_cu *cu);
1544
1545 static htab_up allocate_signatured_type_table ();
1546
1547 static htab_up allocate_dwo_unit_table ();
1548
1549 static struct dwo_unit *lookup_dwo_unit_in_dwp
1550   (dwarf2_per_objfile *per_objfile, struct dwp_file *dwp_file,
1551    const char *comp_dir, ULONGEST signature, int is_debug_types);
1552
1553 static struct dwp_file *get_dwp_file (dwarf2_per_objfile *per_objfile);
1554
1555 static struct dwo_unit *lookup_dwo_comp_unit
1556   (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
1557    ULONGEST signature);
1558
1559 static struct dwo_unit *lookup_dwo_type_unit
1560   (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir);
1561
1562 static void queue_and_load_all_dwo_tus (dwarf2_cu *cu);
1563
1564 /* A unique pointer to a dwo_file.  */
1565
1566 typedef std::unique_ptr<struct dwo_file> dwo_file_up;
1567
1568 static void process_cu_includes (dwarf2_per_objfile *per_objfile);
1569
1570 static void check_producer (struct dwarf2_cu *cu);
1571 \f
1572 /* Various complaints about symbol reading that don't abort the process.  */
1573
1574 static void
1575 dwarf2_debug_line_missing_file_complaint (void)
1576 {
1577   complaint (_(".debug_line section has line data without a file"));
1578 }
1579
1580 static void
1581 dwarf2_debug_line_missing_end_sequence_complaint (void)
1582 {
1583   complaint (_(".debug_line section has line "
1584                "program sequence without an end"));
1585 }
1586
1587 static void
1588 dwarf2_complex_location_expr_complaint (void)
1589 {
1590   complaint (_("location expression too complex"));
1591 }
1592
1593 static void
1594 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1595                                               int arg3)
1596 {
1597   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
1598              arg1, arg2, arg3);
1599 }
1600
1601 static void
1602 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1603 {
1604   complaint (_("invalid attribute class or form for '%s' in '%s'"),
1605              arg1, arg2);
1606 }
1607
1608 /* Hash function for line_header_hash.  */
1609
1610 static hashval_t
1611 line_header_hash (const struct line_header *ofs)
1612 {
1613   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
1614 }
1615
1616 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
1617
1618 static hashval_t
1619 line_header_hash_voidp (const void *item)
1620 {
1621   const struct line_header *ofs = (const struct line_header *) item;
1622
1623   return line_header_hash (ofs);
1624 }
1625
1626 /* Equality function for line_header_hash.  */
1627
1628 static int
1629 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
1630 {
1631   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
1632   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
1633
1634   return (ofs_lhs->sect_off == ofs_rhs->sect_off
1635           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
1636 }
1637
1638 \f
1639
1640 /* See declaration.  */
1641
1642 dwarf2_per_bfd::dwarf2_per_bfd (bfd *obfd, const dwarf2_debug_sections *names,
1643                                 bool can_copy_)
1644   : obfd (obfd),
1645     can_copy (can_copy_)
1646 {
1647   if (names == NULL)
1648     names = &dwarf2_elf_names;
1649
1650   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
1651     locate_sections (obfd, sec, *names);
1652 }
1653
1654 dwarf2_per_bfd::~dwarf2_per_bfd ()
1655 {
1656   for (auto &per_cu : all_comp_units)
1657     per_cu->imported_symtabs_free ();
1658
1659   /* Everything else should be on this->obstack.  */
1660 }
1661
1662 /* See read.h.  */
1663
1664 void
1665 dwarf2_per_objfile::remove_all_cus ()
1666 {
1667   gdb_assert (!this->per_bfd->queue.has_value ());
1668
1669   for (auto pair : m_dwarf2_cus)
1670     delete pair.second;
1671
1672   m_dwarf2_cus.clear ();
1673 }
1674
1675 /* A helper class that calls free_cached_comp_units on
1676    destruction.  */
1677
1678 class free_cached_comp_units
1679 {
1680 public:
1681
1682   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
1683     : m_per_objfile (per_objfile)
1684   {
1685   }
1686
1687   ~free_cached_comp_units ()
1688   {
1689     m_per_objfile->remove_all_cus ();
1690   }
1691
1692   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
1693
1694 private:
1695
1696   dwarf2_per_objfile *m_per_objfile;
1697 };
1698
1699 /* See read.h.  */
1700
1701 bool
1702 dwarf2_per_objfile::symtab_set_p (const dwarf2_per_cu_data *per_cu) const
1703 {
1704   gdb_assert (per_cu->index < this->m_symtabs.size ());
1705
1706   return this->m_symtabs[per_cu->index] != nullptr;
1707 }
1708
1709 /* See read.h.  */
1710
1711 compunit_symtab *
1712 dwarf2_per_objfile::get_symtab (const dwarf2_per_cu_data *per_cu) const
1713 {
1714   gdb_assert (per_cu->index < this->m_symtabs.size ());
1715
1716   return this->m_symtabs[per_cu->index];
1717 }
1718
1719 /* See read.h.  */
1720
1721 void
1722 dwarf2_per_objfile::set_symtab (const dwarf2_per_cu_data *per_cu,
1723                                 compunit_symtab *symtab)
1724 {
1725   gdb_assert (per_cu->index < this->m_symtabs.size ());
1726   gdb_assert (this->m_symtabs[per_cu->index] == nullptr);
1727
1728   this->m_symtabs[per_cu->index] = symtab;
1729 }
1730
1731 /* Try to locate the sections we need for DWARF 2 debugging
1732    information and return true if we have enough to do something.
1733    NAMES points to the dwarf2 section names, or is NULL if the standard
1734    ELF names are used.  CAN_COPY is true for formats where symbol
1735    interposition is possible and so symbol values must follow copy
1736    relocation rules.  */
1737
1738 int
1739 dwarf2_has_info (struct objfile *objfile,
1740                  const struct dwarf2_debug_sections *names,
1741                  bool can_copy)
1742 {
1743   if (objfile->flags & OBJF_READNEVER)
1744     return 0;
1745
1746   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
1747
1748   if (per_objfile == NULL)
1749     {
1750       dwarf2_per_bfd *per_bfd;
1751
1752       /* We can share a "dwarf2_per_bfd" with other objfiles if the
1753          BFD doesn't require relocations.
1754
1755          We don't share with objfiles for which -readnow was requested,
1756          because it would complicate things when loading the same BFD with
1757          -readnow and then without -readnow.  */
1758       if (!gdb_bfd_requires_relocations (objfile->obfd)
1759           && (objfile->flags & OBJF_READNOW) == 0)
1760         {
1761           /* See if one has been created for this BFD yet.  */
1762           per_bfd = dwarf2_per_bfd_bfd_data_key.get (objfile->obfd);
1763
1764           if (per_bfd == nullptr)
1765             {
1766               /* No, create it now.  */
1767               per_bfd = new dwarf2_per_bfd (objfile->obfd, names, can_copy);
1768               dwarf2_per_bfd_bfd_data_key.set (objfile->obfd, per_bfd);
1769             }
1770         }
1771       else
1772         {
1773           /* No sharing possible, create one specifically for this objfile.  */
1774           per_bfd = new dwarf2_per_bfd (objfile->obfd, names, can_copy);
1775           dwarf2_per_bfd_objfile_data_key.set (objfile, per_bfd);
1776         }
1777
1778       per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile, per_bfd);
1779     }
1780
1781   return (!per_objfile->per_bfd->info.is_virtual
1782           && per_objfile->per_bfd->info.s.section != NULL
1783           && !per_objfile->per_bfd->abbrev.is_virtual
1784           && per_objfile->per_bfd->abbrev.s.section != NULL);
1785 }
1786
1787 /* See declaration.  */
1788
1789 void
1790 dwarf2_per_bfd::locate_sections (bfd *abfd, asection *sectp,
1791                                  const dwarf2_debug_sections &names)
1792 {
1793   flagword aflag = bfd_section_flags (sectp);
1794
1795   if ((aflag & SEC_HAS_CONTENTS) == 0)
1796     {
1797     }
1798   else if (elf_section_data (sectp)->this_hdr.sh_size
1799            > bfd_get_file_size (abfd))
1800     {
1801       bfd_size_type size = elf_section_data (sectp)->this_hdr.sh_size;
1802       warning (_("Discarding section %s which has a section size (%s"
1803                  ") larger than the file size [in module %s]"),
1804                bfd_section_name (sectp), phex_nz (size, sizeof (size)),
1805                bfd_get_filename (abfd));
1806     }
1807   else if (names.info.matches (sectp->name))
1808     {
1809       this->info.s.section = sectp;
1810       this->info.size = bfd_section_size (sectp);
1811     }
1812   else if (names.abbrev.matches (sectp->name))
1813     {
1814       this->abbrev.s.section = sectp;
1815       this->abbrev.size = bfd_section_size (sectp);
1816     }
1817   else if (names.line.matches (sectp->name))
1818     {
1819       this->line.s.section = sectp;
1820       this->line.size = bfd_section_size (sectp);
1821     }
1822   else if (names.loc.matches (sectp->name))
1823     {
1824       this->loc.s.section = sectp;
1825       this->loc.size = bfd_section_size (sectp);
1826     }
1827   else if (names.loclists.matches (sectp->name))
1828     {
1829       this->loclists.s.section = sectp;
1830       this->loclists.size = bfd_section_size (sectp);
1831     }
1832   else if (names.macinfo.matches (sectp->name))
1833     {
1834       this->macinfo.s.section = sectp;
1835       this->macinfo.size = bfd_section_size (sectp);
1836     }
1837   else if (names.macro.matches (sectp->name))
1838     {
1839       this->macro.s.section = sectp;
1840       this->macro.size = bfd_section_size (sectp);
1841     }
1842   else if (names.str.matches (sectp->name))
1843     {
1844       this->str.s.section = sectp;
1845       this->str.size = bfd_section_size (sectp);
1846     }
1847   else if (names.str_offsets.matches (sectp->name))
1848     {
1849       this->str_offsets.s.section = sectp;
1850       this->str_offsets.size = bfd_section_size (sectp);
1851     }
1852   else if (names.line_str.matches (sectp->name))
1853     {
1854       this->line_str.s.section = sectp;
1855       this->line_str.size = bfd_section_size (sectp);
1856     }
1857   else if (names.addr.matches (sectp->name))
1858     {
1859       this->addr.s.section = sectp;
1860       this->addr.size = bfd_section_size (sectp);
1861     }
1862   else if (names.frame.matches (sectp->name))
1863     {
1864       this->frame.s.section = sectp;
1865       this->frame.size = bfd_section_size (sectp);
1866     }
1867   else if (names.eh_frame.matches (sectp->name))
1868     {
1869       this->eh_frame.s.section = sectp;
1870       this->eh_frame.size = bfd_section_size (sectp);
1871     }
1872   else if (names.ranges.matches (sectp->name))
1873     {
1874       this->ranges.s.section = sectp;
1875       this->ranges.size = bfd_section_size (sectp);
1876     }
1877   else if (names.rnglists.matches (sectp->name))
1878     {
1879       this->rnglists.s.section = sectp;
1880       this->rnglists.size = bfd_section_size (sectp);
1881     }
1882   else if (names.types.matches (sectp->name))
1883     {
1884       struct dwarf2_section_info type_section;
1885
1886       memset (&type_section, 0, sizeof (type_section));
1887       type_section.s.section = sectp;
1888       type_section.size = bfd_section_size (sectp);
1889
1890       this->types.push_back (type_section);
1891     }
1892   else if (names.gdb_index.matches (sectp->name))
1893     {
1894       this->gdb_index.s.section = sectp;
1895       this->gdb_index.size = bfd_section_size (sectp);
1896     }
1897   else if (names.debug_names.matches (sectp->name))
1898     {
1899       this->debug_names.s.section = sectp;
1900       this->debug_names.size = bfd_section_size (sectp);
1901     }
1902   else if (names.debug_aranges.matches (sectp->name))
1903     {
1904       this->debug_aranges.s.section = sectp;
1905       this->debug_aranges.size = bfd_section_size (sectp);
1906     }
1907
1908   if ((bfd_section_flags (sectp) & (SEC_LOAD | SEC_ALLOC))
1909       && bfd_section_vma (sectp) == 0)
1910     this->has_section_at_zero = true;
1911 }
1912
1913 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1914    SECTION_NAME.  */
1915
1916 void
1917 dwarf2_get_section_info (struct objfile *objfile,
1918                          enum dwarf2_section_enum sect,
1919                          asection **sectp, const gdb_byte **bufp,
1920                          bfd_size_type *sizep)
1921 {
1922   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
1923   struct dwarf2_section_info *info;
1924
1925   /* We may see an objfile without any DWARF, in which case we just
1926      return nothing.  */
1927   if (per_objfile == NULL)
1928     {
1929       *sectp = NULL;
1930       *bufp = NULL;
1931       *sizep = 0;
1932       return;
1933     }
1934   switch (sect)
1935     {
1936     case DWARF2_DEBUG_FRAME:
1937       info = &per_objfile->per_bfd->frame;
1938       break;
1939     case DWARF2_EH_FRAME:
1940       info = &per_objfile->per_bfd->eh_frame;
1941       break;
1942     default:
1943       gdb_assert_not_reached ("unexpected section");
1944     }
1945
1946   info->read (objfile);
1947
1948   *sectp = info->get_bfd_section ();
1949   *bufp = info->buffer;
1950   *sizep = info->size;
1951 }
1952
1953 \f
1954 /* DWARF quick_symbol_functions support.  */
1955
1956 /* TUs can share .debug_line entries, and there can be a lot more TUs than
1957    unique line tables, so we maintain a separate table of all .debug_line
1958    derived entries to support the sharing.
1959    All the quick functions need is the list of file names.  We discard the
1960    line_header when we're done and don't need to record it here.  */
1961 struct quick_file_names
1962 {
1963   /* The data used to construct the hash key.  */
1964   struct stmt_list_hash hash;
1965
1966   /* The number of entries in file_names, real_names.  */
1967   unsigned int num_file_names;
1968
1969   /* The file names from the line table, after being run through
1970      file_full_name.  */
1971   const char **file_names;
1972
1973   /* The file names from the line table after being run through
1974      gdb_realpath.  These are computed lazily.  */
1975   const char **real_names;
1976 };
1977
1978 /* When using the index (and thus not using psymtabs), each CU has an
1979    object of this type.  This is used to hold information needed by
1980    the various "quick" methods.  */
1981 struct dwarf2_per_cu_quick_data
1982 {
1983   /* The file table.  This can be NULL if there was no file table
1984      or it's currently not read in.
1985      NOTE: This points into dwarf2_per_objfile->per_bfd->quick_file_names_table.  */
1986   struct quick_file_names *file_names;
1987
1988   /* A temporary mark bit used when iterating over all CUs in
1989      expand_symtabs_matching.  */
1990   unsigned int mark : 1;
1991
1992   /* True if we've tried to read the file table and found there isn't one.
1993      There will be no point in trying to read it again next time.  */
1994   unsigned int no_file_data : 1;
1995 };
1996
1997 /* A subclass of psymbol_functions that arranges to read the DWARF
1998    partial symbols when needed.  */
1999 struct lazy_dwarf_reader : public psymbol_functions
2000 {
2001   using psymbol_functions::psymbol_functions;
2002
2003   bool can_lazily_read_symbols () override
2004   {
2005     return true;
2006   }
2007
2008   void read_partial_symbols (struct objfile *objfile) override
2009   {
2010     if (dwarf2_has_info (objfile, nullptr))
2011       dwarf2_build_psymtabs (objfile, this);
2012   }
2013 };
2014
2015 static quick_symbol_functions_up
2016 make_lazy_dwarf_reader ()
2017 {
2018   return quick_symbol_functions_up (new lazy_dwarf_reader);
2019 }
2020
2021 struct dwarf2_base_index_functions : public quick_symbol_functions
2022 {
2023   bool has_symbols (struct objfile *objfile) override;
2024
2025   bool has_unexpanded_symtabs (struct objfile *objfile) override;
2026
2027   struct symtab *find_last_source_symtab (struct objfile *objfile) override;
2028
2029   void forget_cached_source_info (struct objfile *objfile) override;
2030
2031   enum language lookup_global_symbol_language (struct objfile *objfile,
2032                                                const char *name,
2033                                                domain_enum domain,
2034                                                bool *symbol_found_p) override
2035   {
2036     *symbol_found_p = false;
2037     return language_unknown;
2038   }
2039
2040   void print_stats (struct objfile *objfile, bool print_bcache) override;
2041
2042   void expand_all_symtabs (struct objfile *objfile) override;
2043
2044   struct compunit_symtab *find_pc_sect_compunit_symtab
2045     (struct objfile *objfile, struct bound_minimal_symbol msymbol,
2046      CORE_ADDR pc, struct obj_section *section, int warn_if_readin) override;
2047
2048   struct compunit_symtab *find_compunit_symtab_by_address
2049     (struct objfile *objfile, CORE_ADDR address) override
2050   {
2051     return nullptr;
2052   }
2053
2054   void map_symbol_filenames (struct objfile *objfile,
2055                              gdb::function_view<symbol_filename_ftype> fun,
2056                              bool need_fullname) override;
2057 };
2058
2059 struct dwarf2_gdb_index : public dwarf2_base_index_functions
2060 {
2061   void dump (struct objfile *objfile) override;
2062
2063   void expand_matching_symbols
2064     (struct objfile *,
2065      const lookup_name_info &lookup_name,
2066      domain_enum domain,
2067      int global,
2068      symbol_compare_ftype *ordered_compare) override;
2069
2070   bool expand_symtabs_matching
2071     (struct objfile *objfile,
2072      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
2073      const lookup_name_info *lookup_name,
2074      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
2075      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
2076      block_search_flags search_flags,
2077      domain_enum domain,
2078      enum search_domain kind) override;
2079 };
2080
2081 struct dwarf2_debug_names_index : public dwarf2_base_index_functions
2082 {
2083   void dump (struct objfile *objfile) override;
2084
2085   void expand_matching_symbols
2086     (struct objfile *,
2087      const lookup_name_info &lookup_name,
2088      domain_enum domain,
2089      int global,
2090      symbol_compare_ftype *ordered_compare) override;
2091
2092   bool expand_symtabs_matching
2093     (struct objfile *objfile,
2094      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
2095      const lookup_name_info *lookup_name,
2096      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
2097      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
2098      block_search_flags search_flags,
2099      domain_enum domain,
2100      enum search_domain kind) override;
2101 };
2102
2103 static quick_symbol_functions_up
2104 make_dwarf_gdb_index ()
2105 {
2106   return quick_symbol_functions_up (new dwarf2_gdb_index);
2107 }
2108
2109 static quick_symbol_functions_up
2110 make_dwarf_debug_names ()
2111 {
2112   return quick_symbol_functions_up (new dwarf2_debug_names_index);
2113 }
2114
2115 /* Utility hash function for a stmt_list_hash.  */
2116
2117 static hashval_t
2118 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2119 {
2120   hashval_t v = 0;
2121
2122   if (stmt_list_hash->dwo_unit != NULL)
2123     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2124   v += to_underlying (stmt_list_hash->line_sect_off);
2125   return v;
2126 }
2127
2128 /* Utility equality function for a stmt_list_hash.  */
2129
2130 static int
2131 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2132                     const struct stmt_list_hash *rhs)
2133 {
2134   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2135     return 0;
2136   if (lhs->dwo_unit != NULL
2137       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2138     return 0;
2139
2140   return lhs->line_sect_off == rhs->line_sect_off;
2141 }
2142
2143 /* Hash function for a quick_file_names.  */
2144
2145 static hashval_t
2146 hash_file_name_entry (const void *e)
2147 {
2148   const struct quick_file_names *file_data
2149     = (const struct quick_file_names *) e;
2150
2151   return hash_stmt_list_entry (&file_data->hash);
2152 }
2153
2154 /* Equality function for a quick_file_names.  */
2155
2156 static int
2157 eq_file_name_entry (const void *a, const void *b)
2158 {
2159   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2160   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2161
2162   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2163 }
2164
2165 /* Delete function for a quick_file_names.  */
2166
2167 static void
2168 delete_file_name_entry (void *e)
2169 {
2170   struct quick_file_names *file_data = (struct quick_file_names *) e;
2171   int i;
2172
2173   for (i = 0; i < file_data->num_file_names; ++i)
2174     {
2175       xfree ((void*) file_data->file_names[i]);
2176       if (file_data->real_names)
2177         xfree ((void*) file_data->real_names[i]);
2178     }
2179
2180   /* The space for the struct itself lives on the obstack, so we don't
2181      free it here.  */
2182 }
2183
2184 /* Create a quick_file_names hash table.  */
2185
2186 static htab_up
2187 create_quick_file_names_table (unsigned int nr_initial_entries)
2188 {
2189   return htab_up (htab_create_alloc (nr_initial_entries,
2190                                      hash_file_name_entry, eq_file_name_entry,
2191                                      delete_file_name_entry, xcalloc, xfree));
2192 }
2193
2194 /* Read in CU (dwarf2_cu object) for PER_CU in the context of PER_OBJFILE.  This
2195    function is unrelated to symtabs, symtab would have to be created afterwards.
2196    You should call age_cached_comp_units after processing the CU.  */
2197
2198 static dwarf2_cu *
2199 load_cu (dwarf2_per_cu_data *per_cu, dwarf2_per_objfile *per_objfile,
2200          bool skip_partial)
2201 {
2202   if (per_cu->is_debug_types)
2203     load_full_type_unit (per_cu, per_objfile);
2204   else
2205     load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
2206                          skip_partial, language_minimal);
2207
2208   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
2209   if (cu == nullptr)
2210     return nullptr;  /* Dummy CU.  */
2211
2212   dwarf2_find_base_address (cu->dies, cu);
2213
2214   return cu;
2215 }
2216
2217 /* Read in the symbols for PER_CU in the context of PER_OBJFILE.  */
2218
2219 static void
2220 dw2_do_instantiate_symtab (dwarf2_per_cu_data *per_cu,
2221                            dwarf2_per_objfile *per_objfile, bool skip_partial)
2222 {
2223   /* Skip type_unit_groups, reading the type units they contain
2224      is handled elsewhere.  */
2225   if (per_cu->type_unit_group_p ())
2226     return;
2227
2228   {
2229     /* The destructor of dwarf2_queue_guard frees any entries left on
2230        the queue.  After this point we're guaranteed to leave this function
2231        with the dwarf queue empty.  */
2232     dwarf2_queue_guard q_guard (per_objfile);
2233
2234     if (!per_objfile->symtab_set_p (per_cu))
2235       {
2236         queue_comp_unit (per_cu, per_objfile, language_minimal);
2237         dwarf2_cu *cu = load_cu (per_cu, per_objfile, skip_partial);
2238
2239         /* If we just loaded a CU from a DWO, and we're working with an index
2240            that may badly handle TUs, load all the TUs in that DWO as well.
2241            http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2242         if (!per_cu->is_debug_types
2243             && cu != NULL
2244             && cu->dwo_unit != NULL
2245             && per_objfile->per_bfd->index_table != NULL
2246             && per_objfile->per_bfd->index_table->version <= 7
2247             /* DWP files aren't supported yet.  */
2248             && get_dwp_file (per_objfile) == NULL)
2249           queue_and_load_all_dwo_tus (cu);
2250       }
2251
2252     process_queue (per_objfile);
2253   }
2254
2255   /* Age the cache, releasing compilation units that have not
2256      been used recently.  */
2257   per_objfile->age_comp_units ();
2258 }
2259
2260 /* Ensure that the symbols for PER_CU have been read in.  DWARF2_PER_OBJFILE is
2261    the per-objfile for which this symtab is instantiated.
2262
2263    Returns the resulting symbol table.  */
2264
2265 static struct compunit_symtab *
2266 dw2_instantiate_symtab (dwarf2_per_cu_data *per_cu,
2267                         dwarf2_per_objfile *per_objfile,
2268                         bool skip_partial)
2269 {
2270   gdb_assert (per_objfile->per_bfd->using_index);
2271
2272   if (!per_objfile->symtab_set_p (per_cu))
2273     {
2274       free_cached_comp_units freer (per_objfile);
2275       scoped_restore decrementer = increment_reading_symtab ();
2276       dw2_do_instantiate_symtab (per_cu, per_objfile, skip_partial);
2277       process_cu_includes (per_objfile);
2278     }
2279
2280   return per_objfile->get_symtab (per_cu);
2281 }
2282
2283 /* See read.h.  */
2284
2285 dwarf2_per_cu_data_up
2286 dwarf2_per_bfd::allocate_per_cu ()
2287 {
2288   dwarf2_per_cu_data_up result (new dwarf2_per_cu_data);
2289   result->per_bfd = this;
2290   result->index = all_comp_units.size ();
2291   return result;
2292 }
2293
2294 /* See read.h.  */
2295
2296 signatured_type_up
2297 dwarf2_per_bfd::allocate_signatured_type (ULONGEST signature)
2298 {
2299   signatured_type_up result (new signatured_type (signature));
2300   result->per_bfd = this;
2301   result->index = all_comp_units.size ();
2302   result->is_debug_types = true;
2303   tu_stats.nr_tus++;
2304   return result;
2305 }
2306
2307 /* Return a new dwarf2_per_cu_data allocated on the per-bfd
2308    obstack, and constructed with the specified field values.  */
2309
2310 static dwarf2_per_cu_data_up
2311 create_cu_from_index_list (dwarf2_per_bfd *per_bfd,
2312                            struct dwarf2_section_info *section,
2313                            int is_dwz,
2314                            sect_offset sect_off, ULONGEST length)
2315 {
2316   dwarf2_per_cu_data_up the_cu = per_bfd->allocate_per_cu ();
2317   the_cu->sect_off = sect_off;
2318   the_cu->length = length;
2319   the_cu->section = section;
2320   the_cu->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
2321                                     struct dwarf2_per_cu_quick_data);
2322   the_cu->is_dwz = is_dwz;
2323   return the_cu;
2324 }
2325
2326 /* A helper for create_cus_from_index that handles a given list of
2327    CUs.  */
2328
2329 static void
2330 create_cus_from_index_list (dwarf2_per_bfd *per_bfd,
2331                             const gdb_byte *cu_list, offset_type n_elements,
2332                             struct dwarf2_section_info *section,
2333                             int is_dwz)
2334 {
2335   for (offset_type i = 0; i < n_elements; i += 2)
2336     {
2337       gdb_static_assert (sizeof (ULONGEST) >= 8);
2338
2339       sect_offset sect_off
2340         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2341       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2342       cu_list += 2 * 8;
2343
2344       dwarf2_per_cu_data_up per_cu
2345         = create_cu_from_index_list (per_bfd, section, is_dwz, sect_off,
2346                                      length);
2347       per_bfd->all_comp_units.push_back (std::move (per_cu));
2348     }
2349 }
2350
2351 /* Read the CU list from the mapped index, and use it to create all
2352    the CU objects for PER_BFD.  */
2353
2354 static void
2355 create_cus_from_index (dwarf2_per_bfd *per_bfd,
2356                        const gdb_byte *cu_list, offset_type cu_list_elements,
2357                        const gdb_byte *dwz_list, offset_type dwz_elements)
2358 {
2359   gdb_assert (per_bfd->all_comp_units.empty ());
2360   per_bfd->all_comp_units.reserve ((cu_list_elements + dwz_elements) / 2);
2361
2362   create_cus_from_index_list (per_bfd, cu_list, cu_list_elements,
2363                               &per_bfd->info, 0);
2364
2365   if (dwz_elements == 0)
2366     return;
2367
2368   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
2369   create_cus_from_index_list (per_bfd, dwz_list, dwz_elements,
2370                               &dwz->info, 1);
2371 }
2372
2373 /* Create the signatured type hash table from the index.  */
2374
2375 static void
2376 create_signatured_type_table_from_index
2377   (dwarf2_per_bfd *per_bfd, struct dwarf2_section_info *section,
2378    const gdb_byte *bytes, offset_type elements)
2379 {
2380   htab_up sig_types_hash = allocate_signatured_type_table ();
2381
2382   for (offset_type i = 0; i < elements; i += 3)
2383     {
2384       signatured_type_up sig_type;
2385       ULONGEST signature;
2386       void **slot;
2387       cu_offset type_offset_in_tu;
2388
2389       gdb_static_assert (sizeof (ULONGEST) >= 8);
2390       sect_offset sect_off
2391         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2392       type_offset_in_tu
2393         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
2394                                                 BFD_ENDIAN_LITTLE);
2395       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2396       bytes += 3 * 8;
2397
2398       sig_type = per_bfd->allocate_signatured_type (signature);
2399       sig_type->type_offset_in_tu = type_offset_in_tu;
2400       sig_type->section = section;
2401       sig_type->sect_off = sect_off;
2402       sig_type->v.quick
2403         = OBSTACK_ZALLOC (&per_bfd->obstack,
2404                           struct dwarf2_per_cu_quick_data);
2405
2406       slot = htab_find_slot (sig_types_hash.get (), sig_type.get (), INSERT);
2407       *slot = sig_type.get ();
2408
2409       per_bfd->all_comp_units.emplace_back (sig_type.release ());
2410     }
2411
2412   per_bfd->signatured_types = std::move (sig_types_hash);
2413 }
2414
2415 /* Create the signatured type hash table from .debug_names.  */
2416
2417 static void
2418 create_signatured_type_table_from_debug_names
2419   (dwarf2_per_objfile *per_objfile,
2420    const mapped_debug_names &map,
2421    struct dwarf2_section_info *section,
2422    struct dwarf2_section_info *abbrev_section)
2423 {
2424   struct objfile *objfile = per_objfile->objfile;
2425
2426   section->read (objfile);
2427   abbrev_section->read (objfile);
2428
2429   htab_up sig_types_hash = allocate_signatured_type_table ();
2430
2431   for (uint32_t i = 0; i < map.tu_count; ++i)
2432     {
2433       signatured_type_up sig_type;
2434       void **slot;
2435
2436       sect_offset sect_off
2437         = (sect_offset) (extract_unsigned_integer
2438                          (map.tu_table_reordered + i * map.offset_size,
2439                           map.offset_size,
2440                           map.dwarf5_byte_order));
2441
2442       comp_unit_head cu_header;
2443       read_and_check_comp_unit_head (per_objfile, &cu_header, section,
2444                                      abbrev_section,
2445                                      section->buffer + to_underlying (sect_off),
2446                                      rcuh_kind::TYPE);
2447
2448       sig_type = per_objfile->per_bfd->allocate_signatured_type
2449         (cu_header.signature);
2450       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
2451       sig_type->section = section;
2452       sig_type->sect_off = sect_off;
2453       sig_type->v.quick
2454         = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack,
2455                           struct dwarf2_per_cu_quick_data);
2456
2457       slot = htab_find_slot (sig_types_hash.get (), sig_type.get (), INSERT);
2458       *slot = sig_type.get ();
2459
2460       per_objfile->per_bfd->all_comp_units.emplace_back (sig_type.release ());
2461     }
2462
2463   per_objfile->per_bfd->signatured_types = std::move (sig_types_hash);
2464 }
2465
2466 /* Read the address map data from the mapped index, and use it to
2467    populate the psymtabs_addrmap.  */
2468
2469 static void
2470 create_addrmap_from_index (dwarf2_per_objfile *per_objfile,
2471                            struct mapped_index *index)
2472 {
2473   struct objfile *objfile = per_objfile->objfile;
2474   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
2475   struct gdbarch *gdbarch = objfile->arch ();
2476   const gdb_byte *iter, *end;
2477   struct addrmap *mutable_map;
2478   CORE_ADDR baseaddr;
2479
2480   auto_obstack temp_obstack;
2481
2482   mutable_map = addrmap_create_mutable (&temp_obstack);
2483
2484   iter = index->address_table.data ();
2485   end = iter + index->address_table.size ();
2486
2487   baseaddr = objfile->text_section_offset ();
2488
2489   while (iter < end)
2490     {
2491       ULONGEST hi, lo, cu_index;
2492       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2493       iter += 8;
2494       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2495       iter += 8;
2496       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2497       iter += 4;
2498
2499       if (lo > hi)
2500         {
2501           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
2502                      hex_string (lo), hex_string (hi));
2503           continue;
2504         }
2505
2506       if (cu_index >= per_bfd->all_comp_units.size ())
2507         {
2508           complaint (_(".gdb_index address table has invalid CU number %u"),
2509                      (unsigned) cu_index);
2510           continue;
2511         }
2512
2513       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
2514       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
2515       addrmap_set_empty (mutable_map, lo, hi - 1,
2516                          per_bfd->get_cu (cu_index));
2517     }
2518
2519   per_bfd->index_addrmap = addrmap_create_fixed (mutable_map,
2520                                                  &per_bfd->obstack);
2521 }
2522
2523 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
2524    populate the psymtabs_addrmap.  */
2525
2526 static void
2527 create_addrmap_from_aranges (dwarf2_per_objfile *per_objfile,
2528                              struct dwarf2_section_info *section)
2529 {
2530   struct objfile *objfile = per_objfile->objfile;
2531   bfd *abfd = objfile->obfd;
2532   struct gdbarch *gdbarch = objfile->arch ();
2533   const CORE_ADDR baseaddr = objfile->text_section_offset ();
2534   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
2535
2536   auto_obstack temp_obstack;
2537   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
2538
2539   std::unordered_map<sect_offset,
2540                      dwarf2_per_cu_data *,
2541                      gdb::hash_enum<sect_offset>>
2542     debug_info_offset_to_per_cu;
2543   for (const auto &per_cu : per_bfd->all_comp_units)
2544     {
2545       const auto insertpair
2546         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off,
2547                                                per_cu.get ());
2548       if (!insertpair.second)
2549         {
2550           warning (_("Section .debug_aranges in %s has duplicate "
2551                      "debug_info_offset %s, ignoring .debug_aranges."),
2552                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
2553           return;
2554         }
2555     }
2556
2557   section->read (objfile);
2558
2559   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
2560
2561   const gdb_byte *addr = section->buffer;
2562
2563   while (addr < section->buffer + section->size)
2564     {
2565       const gdb_byte *const entry_addr = addr;
2566       unsigned int bytes_read;
2567
2568       const LONGEST entry_length = read_initial_length (abfd, addr,
2569                                                         &bytes_read);
2570       addr += bytes_read;
2571
2572       const gdb_byte *const entry_end = addr + entry_length;
2573       const bool dwarf5_is_dwarf64 = bytes_read != 4;
2574       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
2575       if (addr + entry_length > section->buffer + section->size)
2576         {
2577           warning (_("Section .debug_aranges in %s entry at offset %s "
2578                      "length %s exceeds section length %s, "
2579                      "ignoring .debug_aranges."),
2580                    objfile_name (objfile),
2581                    plongest (entry_addr - section->buffer),
2582                    plongest (bytes_read + entry_length),
2583                    pulongest (section->size));
2584           return;
2585         }
2586
2587       /* The version number.  */
2588       const uint16_t version = read_2_bytes (abfd, addr);
2589       addr += 2;
2590       if (version != 2)
2591         {
2592           warning (_("Section .debug_aranges in %s entry at offset %s "
2593                      "has unsupported version %d, ignoring .debug_aranges."),
2594                    objfile_name (objfile),
2595                    plongest (entry_addr - section->buffer), version);
2596           return;
2597         }
2598
2599       const uint64_t debug_info_offset
2600         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
2601       addr += offset_size;
2602       const auto per_cu_it
2603         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
2604       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
2605         {
2606           warning (_("Section .debug_aranges in %s entry at offset %s "
2607                      "debug_info_offset %s does not exists, "
2608                      "ignoring .debug_aranges."),
2609                    objfile_name (objfile),
2610                    plongest (entry_addr - section->buffer),
2611                    pulongest (debug_info_offset));
2612           return;
2613         }
2614       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
2615
2616       const uint8_t address_size = *addr++;
2617       if (address_size < 1 || address_size > 8)
2618         {
2619           warning (_("Section .debug_aranges in %s entry at offset %s "
2620                      "address_size %u is invalid, ignoring .debug_aranges."),
2621                    objfile_name (objfile),
2622                    plongest (entry_addr - section->buffer), address_size);
2623           return;
2624         }
2625
2626       const uint8_t segment_selector_size = *addr++;
2627       if (segment_selector_size != 0)
2628         {
2629           warning (_("Section .debug_aranges in %s entry at offset %s "
2630                      "segment_selector_size %u is not supported, "
2631                      "ignoring .debug_aranges."),
2632                    objfile_name (objfile),
2633                    plongest (entry_addr - section->buffer),
2634                    segment_selector_size);
2635           return;
2636         }
2637
2638       /* Must pad to an alignment boundary that is twice the address
2639          size.  It is undocumented by the DWARF standard but GCC does
2640          use it.  However, not every compiler does this.  We can see
2641          whether it has happened by looking at the total length of the
2642          contents of the aranges for this CU -- it if isn't a multiple
2643          of twice the address size, then we skip any leftover
2644          bytes.  */
2645       addr += (entry_end - addr) % (2 * address_size);
2646
2647       for (;;)
2648         {
2649           if (addr + 2 * address_size > entry_end)
2650             {
2651               warning (_("Section .debug_aranges in %s entry at offset %s "
2652                          "address list is not properly terminated, "
2653                          "ignoring .debug_aranges."),
2654                        objfile_name (objfile),
2655                        plongest (entry_addr - section->buffer));
2656               return;
2657             }
2658           ULONGEST start = extract_unsigned_integer (addr, address_size,
2659                                                      dwarf5_byte_order);
2660           addr += address_size;
2661           ULONGEST length = extract_unsigned_integer (addr, address_size,
2662                                                       dwarf5_byte_order);
2663           addr += address_size;
2664           if (start == 0 && length == 0)
2665             break;
2666           if (start == 0 && !per_bfd->has_section_at_zero)
2667             {
2668               /* Symbol was eliminated due to a COMDAT group.  */
2669               continue;
2670             }
2671           ULONGEST end = start + length;
2672           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
2673                    - baseaddr);
2674           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
2675                  - baseaddr);
2676           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
2677         }
2678     }
2679
2680   per_bfd->index_addrmap = addrmap_create_fixed (mutable_map,
2681                                                  &per_bfd->obstack);
2682 }
2683
2684 /* A helper function that reads the .gdb_index from BUFFER and fills
2685    in MAP.  FILENAME is the name of the file containing the data;
2686    it is used for error reporting.  DEPRECATED_OK is true if it is
2687    ok to use deprecated sections.
2688
2689    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2690    out parameters that are filled in with information about the CU and
2691    TU lists in the section.
2692
2693    Returns true if all went well, false otherwise.  */
2694
2695 static bool
2696 read_gdb_index_from_buffer (const char *filename,
2697                             bool deprecated_ok,
2698                             gdb::array_view<const gdb_byte> buffer,
2699                             struct mapped_index *map,
2700                             const gdb_byte **cu_list,
2701                             offset_type *cu_list_elements,
2702                             const gdb_byte **types_list,
2703                             offset_type *types_list_elements)
2704 {
2705   const gdb_byte *addr = &buffer[0];
2706   offset_view metadata (buffer);
2707
2708   /* Version check.  */
2709   offset_type version = metadata[0];
2710   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2711      causes the index to behave very poorly for certain requests.  Version 3
2712      contained incomplete addrmap.  So, it seems better to just ignore such
2713      indices.  */
2714   if (version < 4)
2715     {
2716       static int warning_printed = 0;
2717       if (!warning_printed)
2718         {
2719           warning (_("Skipping obsolete .gdb_index section in %s."),
2720                    filename);
2721           warning_printed = 1;
2722         }
2723       return 0;
2724     }
2725   /* Index version 4 uses a different hash function than index version
2726      5 and later.
2727
2728      Versions earlier than 6 did not emit psymbols for inlined
2729      functions.  Using these files will cause GDB not to be able to
2730      set breakpoints on inlined functions by name, so we ignore these
2731      indices unless the user has done
2732      "set use-deprecated-index-sections on".  */
2733   if (version < 6 && !deprecated_ok)
2734     {
2735       static int warning_printed = 0;
2736       if (!warning_printed)
2737         {
2738           warning (_("\
2739 Skipping deprecated .gdb_index section in %s.\n\
2740 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2741 to use the section anyway."),
2742                    filename);
2743           warning_printed = 1;
2744         }
2745       return 0;
2746     }
2747   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2748      of the TU (for symbols coming from TUs),
2749      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
2750      Plus gold-generated indices can have duplicate entries for global symbols,
2751      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
2752      These are just performance bugs, and we can't distinguish gdb-generated
2753      indices from gold-generated ones, so issue no warning here.  */
2754
2755   /* Indexes with higher version than the one supported by GDB may be no
2756      longer backward compatible.  */
2757   if (version > 8)
2758     return 0;
2759
2760   map->version = version;
2761
2762   int i = 1;
2763   *cu_list = addr + metadata[i];
2764   *cu_list_elements = (metadata[i + 1] - metadata[i]) / 8;
2765   ++i;
2766
2767   *types_list = addr + metadata[i];
2768   *types_list_elements = (metadata[i + 1] - metadata[i]) / 8;
2769   ++i;
2770
2771   const gdb_byte *address_table = addr + metadata[i];
2772   const gdb_byte *address_table_end = addr + metadata[i + 1];
2773   map->address_table
2774     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
2775   ++i;
2776
2777   const gdb_byte *symbol_table = addr + metadata[i];
2778   const gdb_byte *symbol_table_end = addr + metadata[i + 1];
2779   map->symbol_table
2780     = offset_view (gdb::array_view<const gdb_byte> (symbol_table,
2781                                                     symbol_table_end));
2782
2783   ++i;
2784   map->constant_pool = buffer.slice (metadata[i]);
2785
2786   return 1;
2787 }
2788
2789 /* Callback types for dwarf2_read_gdb_index.  */
2790
2791 typedef gdb::function_view
2792     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_bfd *)>
2793     get_gdb_index_contents_ftype;
2794 typedef gdb::function_view
2795     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
2796     get_gdb_index_contents_dwz_ftype;
2797
2798 /* Read .gdb_index.  If everything went ok, initialize the "quick"
2799    elements of all the CUs and return 1.  Otherwise, return 0.  */
2800
2801 static int
2802 dwarf2_read_gdb_index
2803   (dwarf2_per_objfile *per_objfile,
2804    get_gdb_index_contents_ftype get_gdb_index_contents,
2805    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
2806 {
2807   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2808   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2809   struct dwz_file *dwz;
2810   struct objfile *objfile = per_objfile->objfile;
2811   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
2812
2813   gdb::array_view<const gdb_byte> main_index_contents
2814     = get_gdb_index_contents (objfile, per_bfd);
2815
2816   if (main_index_contents.empty ())
2817     return 0;
2818
2819   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
2820   if (!read_gdb_index_from_buffer (objfile_name (objfile),
2821                                    use_deprecated_index_sections,
2822                                    main_index_contents, map.get (), &cu_list,
2823                                    &cu_list_elements, &types_list,
2824                                    &types_list_elements))
2825     return 0;
2826
2827   /* Don't use the index if it's empty.  */
2828   if (map->symbol_table.empty ())
2829     return 0;
2830
2831   /* If there is a .dwz file, read it so we can get its CU list as
2832      well.  */
2833   dwz = dwarf2_get_dwz_file (per_bfd);
2834   if (dwz != NULL)
2835     {
2836       struct mapped_index dwz_map;
2837       const gdb_byte *dwz_types_ignore;
2838       offset_type dwz_types_elements_ignore;
2839
2840       gdb::array_view<const gdb_byte> dwz_index_content
2841         = get_gdb_index_contents_dwz (objfile, dwz);
2842
2843       if (dwz_index_content.empty ())
2844         return 0;
2845
2846       if (!read_gdb_index_from_buffer (bfd_get_filename (dwz->dwz_bfd.get ()),
2847                                        1, dwz_index_content, &dwz_map,
2848                                        &dwz_list, &dwz_list_elements,
2849                                        &dwz_types_ignore,
2850                                        &dwz_types_elements_ignore))
2851         {
2852           warning (_("could not read '.gdb_index' section from %s; skipping"),
2853                    bfd_get_filename (dwz->dwz_bfd.get ()));
2854           return 0;
2855         }
2856     }
2857
2858   create_cus_from_index (per_bfd, cu_list, cu_list_elements, dwz_list,
2859                          dwz_list_elements);
2860
2861   if (types_list_elements)
2862     {
2863       /* We can only handle a single .debug_types when we have an
2864          index.  */
2865       if (per_bfd->types.size () != 1)
2866         return 0;
2867
2868       dwarf2_section_info *section = &per_bfd->types[0];
2869
2870       create_signatured_type_table_from_index (per_bfd, section, types_list,
2871                                                types_list_elements);
2872     }
2873
2874   create_addrmap_from_index (per_objfile, map.get ());
2875
2876   per_bfd->index_table = std::move (map);
2877   per_bfd->using_index = 1;
2878   per_bfd->quick_file_names_table =
2879     create_quick_file_names_table (per_bfd->all_comp_units.size ());
2880
2881   return 1;
2882 }
2883
2884 /* die_reader_func for dw2_get_file_names.  */
2885
2886 static void
2887 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2888                            struct die_info *comp_unit_die)
2889 {
2890   struct dwarf2_cu *cu = reader->cu;
2891   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
2892   dwarf2_per_objfile *per_objfile = cu->per_objfile;
2893   struct dwarf2_per_cu_data *lh_cu;
2894   struct attribute *attr;
2895   void **slot;
2896   struct quick_file_names *qfn;
2897
2898   gdb_assert (! this_cu->is_debug_types);
2899
2900   /* Our callers never want to match partial units -- instead they
2901      will match the enclosing full CU.  */
2902   if (comp_unit_die->tag == DW_TAG_partial_unit)
2903     {
2904       this_cu->v.quick->no_file_data = 1;
2905       return;
2906     }
2907
2908   lh_cu = this_cu;
2909   slot = NULL;
2910
2911   line_header_up lh;
2912   sect_offset line_offset {};
2913
2914   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2915   if (attr != nullptr && attr->form_is_unsigned ())
2916     {
2917       struct quick_file_names find_entry;
2918
2919       line_offset = (sect_offset) attr->as_unsigned ();
2920
2921       /* We may have already read in this line header (TU line header sharing).
2922          If we have we're done.  */
2923       find_entry.hash.dwo_unit = cu->dwo_unit;
2924       find_entry.hash.line_sect_off = line_offset;
2925       slot = htab_find_slot (per_objfile->per_bfd->quick_file_names_table.get (),
2926                              &find_entry, INSERT);
2927       if (*slot != NULL)
2928         {
2929           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
2930           return;
2931         }
2932
2933       lh = dwarf_decode_line_header (line_offset, cu);
2934     }
2935   if (lh == NULL)
2936     {
2937       lh_cu->v.quick->no_file_data = 1;
2938       return;
2939     }
2940
2941   qfn = XOBNEW (&per_objfile->per_bfd->obstack, struct quick_file_names);
2942   qfn->hash.dwo_unit = cu->dwo_unit;
2943   qfn->hash.line_sect_off = line_offset;
2944   gdb_assert (slot != NULL);
2945   *slot = qfn;
2946
2947   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
2948
2949   int offset = 0;
2950   if (strcmp (fnd.name, "<unknown>") != 0)
2951     ++offset;
2952
2953   qfn->num_file_names = offset + lh->file_names_size ();
2954   qfn->file_names =
2955     XOBNEWVEC (&per_objfile->per_bfd->obstack, const char *,
2956                qfn->num_file_names);
2957   if (offset != 0)
2958     qfn->file_names[0] = xstrdup (fnd.name);
2959   for (int i = 0; i < lh->file_names_size (); ++i)
2960     qfn->file_names[i + offset] = lh->file_full_name (i + 1,
2961                                                       fnd.comp_dir).release ();
2962   qfn->real_names = NULL;
2963
2964   lh_cu->v.quick->file_names = qfn;
2965 }
2966
2967 /* A helper for the "quick" functions which attempts to read the line
2968    table for THIS_CU.  */
2969
2970 static struct quick_file_names *
2971 dw2_get_file_names (dwarf2_per_cu_data *this_cu,
2972                     dwarf2_per_objfile *per_objfile)
2973 {
2974   /* This should never be called for TUs.  */
2975   gdb_assert (! this_cu->is_debug_types);
2976   /* Nor type unit groups.  */
2977   gdb_assert (! this_cu->type_unit_group_p ());
2978
2979   if (this_cu->v.quick->file_names != NULL)
2980     return this_cu->v.quick->file_names;
2981   /* If we know there is no line data, no point in looking again.  */
2982   if (this_cu->v.quick->no_file_data)
2983     return NULL;
2984
2985   cutu_reader reader (this_cu, per_objfile);
2986   if (!reader.dummy_p)
2987     dw2_get_file_names_reader (&reader, reader.comp_unit_die);
2988
2989   if (this_cu->v.quick->no_file_data)
2990     return NULL;
2991   return this_cu->v.quick->file_names;
2992 }
2993
2994 /* A helper for the "quick" functions which computes and caches the
2995    real path for a given file name from the line table.  */
2996
2997 static const char *
2998 dw2_get_real_path (dwarf2_per_objfile *per_objfile,
2999                    struct quick_file_names *qfn, int index)
3000 {
3001   if (qfn->real_names == NULL)
3002     qfn->real_names = OBSTACK_CALLOC (&per_objfile->per_bfd->obstack,
3003                                       qfn->num_file_names, const char *);
3004
3005   if (qfn->real_names[index] == NULL)
3006     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3007
3008   return qfn->real_names[index];
3009 }
3010
3011 struct symtab *
3012 dwarf2_base_index_functions::find_last_source_symtab (struct objfile *objfile)
3013 {
3014   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3015   dwarf2_per_cu_data *dwarf_cu
3016     = per_objfile->per_bfd->all_comp_units.back ().get ();
3017   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, per_objfile, false);
3018
3019   if (cust == NULL)
3020     return NULL;
3021
3022   return compunit_primary_filetab (cust);
3023 }
3024
3025 /* Traversal function for dw2_forget_cached_source_info.  */
3026
3027 static int
3028 dw2_free_cached_file_names (void **slot, void *info)
3029 {
3030   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3031
3032   if (file_data->real_names)
3033     {
3034       int i;
3035
3036       for (i = 0; i < file_data->num_file_names; ++i)
3037         {
3038           xfree ((void*) file_data->real_names[i]);
3039           file_data->real_names[i] = NULL;
3040         }
3041     }
3042
3043   return 1;
3044 }
3045
3046 void
3047 dwarf2_base_index_functions::forget_cached_source_info
3048      (struct objfile *objfile)
3049 {
3050   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3051
3052   htab_traverse_noresize (per_objfile->per_bfd->quick_file_names_table.get (),
3053                           dw2_free_cached_file_names, NULL);
3054 }
3055
3056 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3057
3058 struct dw2_symtab_iterator
3059 {
3060   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3061   dwarf2_per_objfile *per_objfile;
3062   /* If set, only look for symbols that match that block.  Valid values are
3063      GLOBAL_BLOCK and STATIC_BLOCK.  */
3064   gdb::optional<block_enum> block_index;
3065   /* The kind of symbol we're looking for.  */
3066   domain_enum domain;
3067   /* The list of CUs from the index entry of the symbol,
3068      or NULL if not found.  */
3069   offset_view vec;
3070   /* The next element in VEC to look at.  */
3071   int next;
3072   /* The number of elements in VEC, or zero if there is no match.  */
3073   int length;
3074   /* Have we seen a global version of the symbol?
3075      If so we can ignore all further global instances.
3076      This is to work around gold/15646, inefficient gold-generated
3077      indices.  */
3078   int global_seen;
3079 };
3080
3081 /* Initialize the index symtab iterator ITER, offset_type NAMEI variant.  */
3082
3083 static void
3084 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3085                       dwarf2_per_objfile *per_objfile,
3086                       gdb::optional<block_enum> block_index,
3087                       domain_enum domain, offset_type namei)
3088 {
3089   iter->per_objfile = per_objfile;
3090   iter->block_index = block_index;
3091   iter->domain = domain;
3092   iter->next = 0;
3093   iter->global_seen = 0;
3094   iter->vec = {};
3095   iter->length = 0;
3096
3097   mapped_index *index = per_objfile->per_bfd->index_table.get ();
3098   /* index is NULL if OBJF_READNOW.  */
3099   if (index == NULL)
3100     return;
3101
3102   gdb_assert (!index->symbol_name_slot_invalid (namei));
3103   offset_type vec_idx = index->symbol_vec_index (namei);
3104
3105   iter->vec = offset_view (index->constant_pool.slice (vec_idx));
3106   iter->length = iter->vec[0];
3107 }
3108
3109 /* Return the next matching CU or NULL if there are no more.  */
3110
3111 static struct dwarf2_per_cu_data *
3112 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3113 {
3114   dwarf2_per_objfile *per_objfile = iter->per_objfile;
3115
3116   for ( ; iter->next < iter->length; ++iter->next)
3117     {
3118       offset_type cu_index_and_attrs = iter->vec[iter->next + 1];
3119       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3120       gdb_index_symbol_kind symbol_kind =
3121         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3122       /* Only check the symbol attributes if they're present.
3123          Indices prior to version 7 don't record them,
3124          and indices >= 7 may elide them for certain symbols
3125          (gold does this).  */
3126       int attrs_valid =
3127         (per_objfile->per_bfd->index_table->version >= 7
3128          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3129
3130       /* Don't crash on bad data.  */
3131       if (cu_index >= per_objfile->per_bfd->all_comp_units.size ())
3132         {
3133           complaint (_(".gdb_index entry has bad CU index"
3134                        " [in module %s]"), objfile_name (per_objfile->objfile));
3135           continue;
3136         }
3137
3138       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cu (cu_index);
3139
3140       /* Skip if already read in.  */
3141       if (per_objfile->symtab_set_p (per_cu))
3142         continue;
3143
3144       /* Check static vs global.  */
3145       if (attrs_valid)
3146         {
3147           bool is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3148
3149           if (iter->block_index.has_value ())
3150             {
3151               bool want_static = *iter->block_index == STATIC_BLOCK;
3152
3153               if (is_static != want_static)
3154                 continue;
3155             }
3156
3157           /* Work around gold/15646.  */
3158           if (!is_static
3159               && symbol_kind == GDB_INDEX_SYMBOL_KIND_TYPE)
3160             {
3161               if (iter->global_seen)
3162                 continue;
3163
3164               iter->global_seen = 1;
3165             }
3166         }
3167
3168       /* Only check the symbol's kind if it has one.  */
3169       if (attrs_valid)
3170         {
3171           switch (iter->domain)
3172             {
3173             case VAR_DOMAIN:
3174               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3175                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3176                   /* Some types are also in VAR_DOMAIN.  */
3177                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3178                 continue;
3179               break;
3180             case STRUCT_DOMAIN:
3181               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3182                 continue;
3183               break;
3184             case LABEL_DOMAIN:
3185               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3186                 continue;
3187               break;
3188             case MODULE_DOMAIN:
3189               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3190                 continue;
3191               break;
3192             default:
3193               break;
3194             }
3195         }
3196
3197       ++iter->next;
3198       return per_cu;
3199     }
3200
3201   return NULL;
3202 }
3203
3204 void
3205 dwarf2_base_index_functions::print_stats (struct objfile *objfile,
3206                                           bool print_bcache)
3207 {
3208   if (print_bcache)
3209     return;
3210
3211   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3212   int total = per_objfile->per_bfd->all_comp_units.size ();
3213   int count = 0;
3214
3215   for (int i = 0; i < total; ++i)
3216     {
3217       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cu (i);
3218
3219       if (!per_objfile->symtab_set_p (per_cu))
3220         ++count;
3221     }
3222   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3223   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3224 }
3225
3226 /* This dumps minimal information about the index.
3227    It is called via "mt print objfiles".
3228    One use is to verify .gdb_index has been loaded by the
3229    gdb.dwarf2/gdb-index.exp testcase.  */
3230
3231 void
3232 dwarf2_gdb_index::dump (struct objfile *objfile)
3233 {
3234   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3235
3236   gdb_assert (per_objfile->per_bfd->using_index);
3237   printf_filtered (".gdb_index:");
3238   if (per_objfile->per_bfd->index_table != NULL)
3239     {
3240       printf_filtered (" version %d\n",
3241                        per_objfile->per_bfd->index_table->version);
3242     }
3243   else
3244     printf_filtered (" faked for \"readnow\"\n");
3245   printf_filtered ("\n");
3246 }
3247
3248 void
3249 dwarf2_base_index_functions::expand_all_symtabs (struct objfile *objfile)
3250 {
3251   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3252   int total_units = per_objfile->per_bfd->all_comp_units.size ();
3253
3254   for (int i = 0; i < total_units; ++i)
3255     {
3256       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cu (i);
3257
3258       /* We don't want to directly expand a partial CU, because if we
3259          read it with the wrong language, then assertion failures can
3260          be triggered later on.  See PR symtab/23010.  So, tell
3261          dw2_instantiate_symtab to skip partial CUs -- any important
3262          partial CU will be read via DW_TAG_imported_unit anyway.  */
3263       dw2_instantiate_symtab (per_cu, per_objfile, true);
3264     }
3265 }
3266
3267 static bool
3268 dw2_expand_symtabs_matching_symbol
3269   (mapped_index_base &index,
3270    const lookup_name_info &lookup_name_in,
3271    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
3272    gdb::function_view<bool (offset_type)> match_callback,
3273    dwarf2_per_objfile *per_objfile);
3274
3275 static bool
3276 dw2_expand_symtabs_matching_one
3277   (dwarf2_per_cu_data *per_cu,
3278    dwarf2_per_objfile *per_objfile,
3279    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
3280    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify);
3281
3282 void
3283 dwarf2_gdb_index::expand_matching_symbols
3284   (struct objfile *objfile,
3285    const lookup_name_info &name, domain_enum domain,
3286    int global,
3287    symbol_compare_ftype *ordered_compare)
3288 {
3289   /* Used for Ada.  */
3290   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
3291
3292   const block_enum block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
3293
3294   if (per_objfile->per_bfd->index_table != nullptr)
3295     {
3296       mapped_index &index = *per_objfile->per_bfd->index_table;
3297
3298       const char *match_name = name.ada ().lookup_name ().c_str ();
3299       auto matcher = [&] (const char *symname)
3300         {
3301           if (ordered_compare == nullptr)
3302             return true;
3303           return ordered_compare (symname, match_name) == 0;
3304         };
3305
3306       dw2_expand_symtabs_matching_symbol (index, name, matcher,
3307                                           [&] (offset_type namei)
3308       {
3309         struct dw2_symtab_iterator iter;
3310         struct dwarf2_per_cu_data *per_cu;
3311
3312         dw2_symtab_iter_init (&iter, per_objfile, block_kind, domain,
3313                               namei);
3314         while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3315           dw2_expand_symtabs_matching_one (per_cu, per_objfile, nullptr,
3316                                            nullptr);
3317         return true;
3318       }, per_objfile);
3319     }
3320   else
3321     {
3322       /* We have -readnow: no .gdb_index, but no partial symtabs either.  So,
3323          proceed assuming all symtabs have been read in.  */
3324     }
3325 }
3326
3327 /* Starting from a search name, return the string that finds the upper
3328    bound of all strings that start with SEARCH_NAME in a sorted name
3329    list.  Returns the empty string to indicate that the upper bound is
3330    the end of the list.  */
3331
3332 static std::string
3333 make_sort_after_prefix_name (const char *search_name)
3334 {
3335   /* When looking to complete "func", we find the upper bound of all
3336      symbols that start with "func" by looking for where we'd insert
3337      the closest string that would follow "func" in lexicographical
3338      order.  Usually, that's "func"-with-last-character-incremented,
3339      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
3340      will be UTF-8 multi-byte sequences, but we can't be certain.
3341      Especially mind the 0xff character, which is a valid character in
3342      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
3343      rule out compilers allowing it in identifiers.  Note that
3344      conveniently, strcmp/strcasecmp are specified to compare
3345      characters interpreted as unsigned char.  So what we do is treat
3346      the whole string as a base 256 number composed of a sequence of
3347      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
3348      to 0, and carries 1 to the following more-significant position.
3349      If the very first character in SEARCH_NAME ends up incremented
3350      and carries/overflows, then the upper bound is the end of the
3351      list.  The string after the empty string is also the empty
3352      string.
3353
3354      Some examples of this operation:
3355
3356        SEARCH_NAME  => "+1" RESULT
3357
3358        "abc"              => "abd"
3359        "ab\xff"           => "ac"
3360        "\xff" "a" "\xff"  => "\xff" "b"
3361        "\xff"             => ""
3362        "\xff\xff"         => ""
3363        ""                 => ""
3364
3365      Then, with these symbols for example:
3366
3367       func
3368       func1
3369       fund
3370
3371      completing "func" looks for symbols between "func" and
3372      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
3373      which finds "func" and "func1", but not "fund".
3374
3375      And with:
3376
3377       funcÿ     (Latin1 'ÿ' [0xff])
3378       funcÿ1
3379       fund
3380
3381      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
3382      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
3383
3384      And with:
3385
3386       ÿÿ        (Latin1 'ÿ' [0xff])
3387       ÿÿ1
3388
3389      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
3390      the end of the list.
3391   */
3392   std::string after = search_name;
3393   while (!after.empty () && (unsigned char) after.back () == 0xff)
3394     after.pop_back ();
3395   if (!after.empty ())
3396     after.back () = (unsigned char) after.back () + 1;
3397   return after;
3398 }
3399
3400 /* See declaration.  */
3401
3402 std::pair<std::vector<name_component>::const_iterator,
3403           std::vector<name_component>::const_iterator>
3404 mapped_index_base::find_name_components_bounds
3405   (const lookup_name_info &lookup_name_without_params, language lang,
3406    dwarf2_per_objfile *per_objfile) const
3407 {
3408   auto *name_cmp
3409     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3410
3411   const char *lang_name
3412     = lookup_name_without_params.language_lookup_name (lang);
3413
3414   /* Comparison function object for lower_bound that matches against a
3415      given symbol name.  */
3416   auto lookup_compare_lower = [&] (const name_component &elem,
3417                                    const char *name)
3418     {
3419       const char *elem_qualified = this->symbol_name_at (elem.idx, per_objfile);
3420       const char *elem_name = elem_qualified + elem.name_offset;
3421       return name_cmp (elem_name, name) < 0;
3422     };
3423
3424   /* Comparison function object for upper_bound that matches against a
3425      given symbol name.  */
3426   auto lookup_compare_upper = [&] (const char *name,
3427                                    const name_component &elem)
3428     {
3429       const char *elem_qualified = this->symbol_name_at (elem.idx, per_objfile);
3430       const char *elem_name = elem_qualified + elem.name_offset;
3431       return name_cmp (name, elem_name) < 0;
3432     };
3433
3434   auto begin = this->name_components.begin ();
3435   auto end = this->name_components.end ();
3436
3437   /* Find the lower bound.  */
3438   auto lower = [&] ()
3439     {
3440       if (lookup_name_without_params.completion_mode () && lang_name[0] == '\0')
3441         return begin;
3442       else
3443         return std::lower_bound (begin, end, lang_name, lookup_compare_lower);
3444     } ();
3445
3446   /* Find the upper bound.  */
3447   auto upper = [&] ()
3448     {
3449       if (lookup_name_without_params.completion_mode ())
3450         {
3451           /* In completion mode, we want UPPER to point past all
3452              symbols names that have the same prefix.  I.e., with
3453              these symbols, and completing "func":
3454
3455               function        << lower bound
3456               function1
3457               other_function  << upper bound
3458
3459              We find the upper bound by looking for the insertion
3460              point of "func"-with-last-character-incremented,
3461              i.e. "fund".  */
3462           std::string after = make_sort_after_prefix_name (lang_name);
3463           if (after.empty ())
3464             return end;
3465           return std::lower_bound (lower, end, after.c_str (),
3466                                    lookup_compare_lower);
3467         }
3468       else
3469         return std::upper_bound (lower, end, lang_name, lookup_compare_upper);
3470     } ();
3471
3472   return {lower, upper};
3473 }
3474
3475 /* See declaration.  */
3476
3477 void
3478 mapped_index_base::build_name_components (dwarf2_per_objfile *per_objfile)
3479 {
3480   if (!this->name_components.empty ())
3481     return;
3482
3483   this->name_components_casing = case_sensitivity;
3484   auto *name_cmp
3485     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
3486
3487   /* The code below only knows how to break apart components of C++
3488      symbol names (and other languages that use '::' as
3489      namespace/module separator) and Ada symbol names.  */
3490   auto count = this->symbol_name_count ();
3491   for (offset_type idx = 0; idx < count; idx++)
3492     {
3493       if (this->symbol_name_slot_invalid (idx))
3494         continue;
3495
3496       const char *name = this->symbol_name_at (idx, per_objfile);
3497
3498       /* Add each name component to the name component table.  */
3499       unsigned int previous_len = 0;
3500
3501       if (strstr (name, "::") != nullptr)
3502         {
3503           for (unsigned int current_len = cp_find_first_component (name);
3504                name[current_len] != '\0';
3505                current_len += cp_find_first_component (name + current_len))
3506             {
3507               gdb_assert (name[current_len] == ':');
3508               this->name_components.push_back ({previous_len, idx});
3509               /* Skip the '::'.  */
3510               current_len += 2;
3511               previous_len = current_len;
3512             }
3513         }
3514       else
3515         {
3516           /* Handle the Ada encoded (aka mangled) form here.  */
3517           for (const char *iter = strstr (name, "__");
3518                iter != nullptr;
3519                iter = strstr (iter, "__"))
3520             {
3521               this->name_components.push_back ({previous_len, idx});
3522               iter += 2;
3523               previous_len = iter - name;
3524             }
3525         }
3526
3527       this->name_components.push_back ({previous_len, idx});
3528     }
3529
3530   /* Sort name_components elements by name.  */
3531   auto name_comp_compare = [&] (const name_component &left,
3532                                 const name_component &right)
3533     {
3534       const char *left_qualified
3535         = this->symbol_name_at (left.idx, per_objfile);
3536       const char *right_qualified
3537         = this->symbol_name_at (right.idx, per_objfile);
3538
3539       const char *left_name = left_qualified + left.name_offset;
3540       const char *right_name = right_qualified + right.name_offset;
3541
3542       return name_cmp (left_name, right_name) < 0;
3543     };
3544
3545   std::sort (this->name_components.begin (),
3546              this->name_components.end (),
3547              name_comp_compare);
3548 }
3549
3550 /* Helper for dw2_expand_symtabs_matching that works with a
3551    mapped_index_base instead of the containing objfile.  This is split
3552    to a separate function in order to be able to unit test the
3553    name_components matching using a mock mapped_index_base.  For each
3554    symbol name that matches, calls MATCH_CALLBACK, passing it the
3555    symbol's index in the mapped_index_base symbol table.  */
3556
3557 static bool
3558 dw2_expand_symtabs_matching_symbol
3559   (mapped_index_base &index,
3560    const lookup_name_info &lookup_name_in,
3561    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
3562    gdb::function_view<bool (offset_type)> match_callback,
3563    dwarf2_per_objfile *per_objfile)
3564 {
3565   lookup_name_info lookup_name_without_params
3566     = lookup_name_in.make_ignore_params ();
3567
3568   /* Build the symbol name component sorted vector, if we haven't
3569      yet.  */
3570   index.build_name_components (per_objfile);
3571
3572   /* The same symbol may appear more than once in the range though.
3573      E.g., if we're looking for symbols that complete "w", and we have
3574      a symbol named "w1::w2", we'll find the two name components for
3575      that same symbol in the range.  To be sure we only call the
3576      callback once per symbol, we first collect the symbol name
3577      indexes that matched in a temporary vector and ignore
3578      duplicates.  */
3579   std::vector<offset_type> matches;
3580
3581   struct name_and_matcher
3582   {
3583     symbol_name_matcher_ftype *matcher;
3584     const char *name;
3585
3586     bool operator== (const name_and_matcher &other) const
3587     {
3588       return matcher == other.matcher && strcmp (name, other.name) == 0;
3589     }
3590   };
3591
3592   /* A vector holding all the different symbol name matchers, for all
3593      languages.  */
3594   std::vector<name_and_matcher> matchers;
3595
3596   for (int i = 0; i < nr_languages; i++)
3597     {
3598       enum language lang_e = (enum language) i;
3599
3600       const language_defn *lang = language_def (lang_e);
3601       symbol_name_matcher_ftype *name_matcher
3602         = lang->get_symbol_name_matcher (lookup_name_without_params);
3603
3604       name_and_matcher key {
3605          name_matcher,
3606          lookup_name_without_params.language_lookup_name (lang_e)
3607       };
3608
3609       /* Don't insert the same comparison routine more than once.
3610          Note that we do this linear walk.  This is not a problem in
3611          practice because the number of supported languages is
3612          low.  */
3613       if (std::find (matchers.begin (), matchers.end (), key)
3614           != matchers.end ())
3615         continue;
3616       matchers.push_back (std::move (key));
3617
3618       auto bounds
3619         = index.find_name_components_bounds (lookup_name_without_params,
3620                                              lang_e, per_objfile);
3621
3622       /* Now for each symbol name in range, check to see if we have a name
3623          match, and if so, call the MATCH_CALLBACK callback.  */
3624
3625       for (; bounds.first != bounds.second; ++bounds.first)
3626         {
3627           const char *qualified
3628             = index.symbol_name_at (bounds.first->idx, per_objfile);
3629
3630           if (!name_matcher (qualified, lookup_name_without_params, NULL)
3631               || (symbol_matcher != NULL && !symbol_matcher (qualified)))
3632             continue;
3633
3634           matches.push_back (bounds.first->idx);
3635         }
3636     }
3637
3638   std::sort (matches.begin (), matches.end ());
3639
3640   /* Finally call the callback, once per match.  */
3641   ULONGEST prev = -1;
3642   bool result = true;
3643   for (offset_type idx : matches)
3644     {
3645       if (prev != idx)
3646         {
3647           if (!match_callback (idx))
3648             {
3649               result = false;
3650               break;
3651             }
3652           prev = idx;
3653         }
3654     }
3655
3656   /* Above we use a type wider than idx's for 'prev', since 0 and
3657      (offset_type)-1 are both possible values.  */
3658   static_assert (sizeof (prev) > sizeof (offset_type), "");
3659
3660   return result;
3661 }
3662
3663 #if GDB_SELF_TEST
3664
3665 namespace selftests { namespace dw2_expand_symtabs_matching {
3666
3667 /* A mock .gdb_index/.debug_names-like name index table, enough to
3668    exercise dw2_expand_symtabs_matching_symbol, which works with the
3669    mapped_index_base interface.  Builds an index from the symbol list
3670    passed as parameter to the constructor.  */
3671 class mock_mapped_index : public mapped_index_base
3672 {
3673 public:
3674   mock_mapped_index (gdb::array_view<const char *> symbols)
3675     : m_symbol_table (symbols)
3676   {}
3677
3678   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
3679
3680   /* Return the number of names in the symbol table.  */
3681   size_t symbol_name_count () const override
3682   {
3683     return m_symbol_table.size ();
3684   }
3685
3686   /* Get the name of the symbol at IDX in the symbol table.  */
3687   const char *symbol_name_at
3688     (offset_type idx, dwarf2_per_objfile *per_objfile) const override
3689   {
3690     return m_symbol_table[idx];
3691   }
3692
3693 private:
3694   gdb::array_view<const char *> m_symbol_table;
3695 };
3696
3697 /* Convenience function that converts a NULL pointer to a "<null>"
3698    string, to pass to print routines.  */
3699
3700 static const char *
3701 string_or_null (const char *str)
3702 {
3703   return str != NULL ? str : "<null>";
3704 }
3705
3706 /* Check if a lookup_name_info built from
3707    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
3708    index.  EXPECTED_LIST is the list of expected matches, in expected
3709    matching order.  If no match expected, then an empty list is
3710    specified.  Returns true on success.  On failure prints a warning
3711    indicating the file:line that failed, and returns false.  */
3712
3713 static bool
3714 check_match (const char *file, int line,
3715              mock_mapped_index &mock_index,
3716              const char *name, symbol_name_match_type match_type,
3717              bool completion_mode,
3718              std::initializer_list<const char *> expected_list,
3719              dwarf2_per_objfile *per_objfile)
3720 {
3721   lookup_name_info lookup_name (name, match_type, completion_mode);
3722
3723   bool matched = true;
3724
3725   auto mismatch = [&] (const char *expected_str,
3726                        const char *got)
3727   {
3728     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
3729                "expected=\"%s\", got=\"%s\"\n"),
3730              file, line,
3731              (match_type == symbol_name_match_type::FULL
3732               ? "FULL" : "WILD"),
3733              name, string_or_null (expected_str), string_or_null (got));
3734     matched = false;
3735   };
3736
3737   auto expected_it = expected_list.begin ();
3738   auto expected_end = expected_list.end ();
3739
3740   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
3741                                       nullptr,
3742                                       [&] (offset_type idx)
3743   {
3744     const char *matched_name = mock_index.symbol_name_at (idx, per_objfile);
3745     const char *expected_str
3746       = expected_it == expected_end ? NULL : *expected_it++;
3747
3748     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
3749       mismatch (expected_str, matched_name);
3750     return true;
3751   }, per_objfile);
3752
3753   const char *expected_str
3754   = expected_it == expected_end ? NULL : *expected_it++;
3755   if (expected_str != NULL)
3756     mismatch (expected_str, NULL);
3757
3758   return matched;
3759 }
3760
3761 /* The symbols added to the mock mapped_index for testing (in
3762    canonical form).  */
3763 static const char *test_symbols[] = {
3764   "function",
3765   "std::bar",
3766   "std::zfunction",
3767   "std::zfunction2",
3768   "w1::w2",
3769   "ns::foo<char*>",
3770   "ns::foo<int>",
3771   "ns::foo<long>",
3772   "ns2::tmpl<int>::foo2",
3773   "(anonymous namespace)::A::B::C",
3774
3775   /* These are used to check that the increment-last-char in the
3776      matching algorithm for completion doesn't match "t1_fund" when
3777      completing "t1_func".  */
3778   "t1_func",
3779   "t1_func1",
3780   "t1_fund",
3781   "t1_fund1",
3782
3783   /* A UTF-8 name with multi-byte sequences to make sure that
3784      cp-name-parser understands this as a single identifier ("função"
3785      is "function" in PT).  */
3786   u8"u8função",
3787
3788   /* \377 (0xff) is Latin1 'ÿ'.  */
3789   "yfunc\377",
3790
3791   /* \377 (0xff) is Latin1 'ÿ'.  */
3792   "\377",
3793   "\377\377123",
3794
3795   /* A name with all sorts of complications.  Starts with "z" to make
3796      it easier for the completion tests below.  */
3797 #define Z_SYM_NAME \
3798   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
3799     "::tuple<(anonymous namespace)::ui*, " \
3800     "std::default_delete<(anonymous namespace)::ui>, void>"
3801
3802   Z_SYM_NAME
3803 };
3804
3805 /* Returns true if the mapped_index_base::find_name_component_bounds
3806    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
3807    in completion mode.  */
3808
3809 static bool
3810 check_find_bounds_finds (mapped_index_base &index,
3811                          const char *search_name,
3812                          gdb::array_view<const char *> expected_syms,
3813                          dwarf2_per_objfile *per_objfile)
3814 {
3815   lookup_name_info lookup_name (search_name,
3816                                 symbol_name_match_type::FULL, true);
3817
3818   auto bounds = index.find_name_components_bounds (lookup_name,
3819                                                    language_cplus,
3820                                                    per_objfile);
3821
3822   size_t distance = std::distance (bounds.first, bounds.second);
3823   if (distance != expected_syms.size ())
3824     return false;
3825
3826   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
3827     {
3828       auto nc_elem = bounds.first + exp_elem;
3829       const char *qualified = index.symbol_name_at (nc_elem->idx, per_objfile);
3830       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
3831         return false;
3832     }
3833
3834   return true;
3835 }
3836
3837 /* Test the lower-level mapped_index::find_name_component_bounds
3838    method.  */
3839
3840 static void
3841 test_mapped_index_find_name_component_bounds ()
3842 {
3843   mock_mapped_index mock_index (test_symbols);
3844
3845   mock_index.build_name_components (NULL /* per_objfile */);
3846
3847   /* Test the lower-level mapped_index::find_name_component_bounds
3848      method in completion mode.  */
3849   {
3850     static const char *expected_syms[] = {
3851       "t1_func",
3852       "t1_func1",
3853     };
3854
3855     SELF_CHECK (check_find_bounds_finds
3856                   (mock_index, "t1_func", expected_syms,
3857                    NULL /* per_objfile */));
3858   }
3859
3860   /* Check that the increment-last-char in the name matching algorithm
3861      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
3862   {
3863     static const char *expected_syms1[] = {
3864       "\377",
3865       "\377\377123",
3866     };
3867     SELF_CHECK (check_find_bounds_finds
3868                   (mock_index, "\377", expected_syms1, NULL /* per_objfile */));
3869
3870     static const char *expected_syms2[] = {
3871       "\377\377123",
3872     };
3873     SELF_CHECK (check_find_bounds_finds
3874                   (mock_index, "\377\377", expected_syms2,
3875                    NULL /* per_objfile */));
3876   }
3877 }
3878
3879 /* Test dw2_expand_symtabs_matching_symbol.  */
3880
3881 static void
3882 test_dw2_expand_symtabs_matching_symbol ()
3883 {
3884   mock_mapped_index mock_index (test_symbols);
3885
3886   /* We let all tests run until the end even if some fails, for debug
3887      convenience.  */
3888   bool any_mismatch = false;
3889
3890   /* Create the expected symbols list (an initializer_list).  Needed
3891      because lists have commas, and we need to pass them to CHECK,
3892      which is a macro.  */
3893 #define EXPECT(...) { __VA_ARGS__ }
3894
3895   /* Wrapper for check_match that passes down the current
3896      __FILE__/__LINE__.  */
3897 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
3898   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
3899                                 mock_index,                             \
3900                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
3901                                 EXPECTED_LIST, NULL)
3902
3903   /* Identity checks.  */
3904   for (const char *sym : test_symbols)
3905     {
3906       /* Should be able to match all existing symbols.  */
3907       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
3908                    EXPECT (sym));
3909
3910       /* Should be able to match all existing symbols with
3911          parameters.  */
3912       std::string with_params = std::string (sym) + "(int)";
3913       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
3914                    EXPECT (sym));
3915
3916       /* Should be able to match all existing symbols with
3917          parameters and qualifiers.  */
3918       with_params = std::string (sym) + " ( int ) const";
3919       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
3920                    EXPECT (sym));
3921
3922       /* This should really find sym, but cp-name-parser.y doesn't
3923          know about lvalue/rvalue qualifiers yet.  */
3924       with_params = std::string (sym) + " ( int ) &&";
3925       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
3926                    {});
3927     }
3928
3929   /* Check that the name matching algorithm for completion doesn't get
3930      confused with Latin1 'ÿ' / 0xff.  */
3931   {
3932     static const char str[] = "\377";
3933     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
3934                  EXPECT ("\377", "\377\377123"));
3935   }
3936
3937   /* Check that the increment-last-char in the matching algorithm for
3938      completion doesn't match "t1_fund" when completing "t1_func".  */
3939   {
3940     static const char str[] = "t1_func";
3941     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
3942                  EXPECT ("t1_func", "t1_func1"));
3943   }
3944
3945   /* Check that completion mode works at each prefix of the expected
3946      symbol name.  */
3947   {
3948     static const char str[] = "function(int)";
3949     size_t len = strlen (str);
3950     std::string lookup;
3951
3952     for (size_t i = 1; i < len; i++)
3953       {
3954         lookup.assign (str, i);
3955         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
3956                      EXPECT ("function"));
3957       }
3958   }
3959
3960   /* While "w" is a prefix of both components, the match function
3961      should still only be called once.  */
3962   {
3963     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
3964                  EXPECT ("w1::w2"));
3965     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
3966                  EXPECT ("w1::w2"));
3967   }
3968
3969   /* Same, with a "complicated" symbol.  */
3970   {
3971     static const char str[] = Z_SYM_NAME;
3972     size_t len = strlen (str);
3973     std::string lookup;
3974
3975     for (size_t i = 1; i < len; i++)
3976       {
3977         lookup.assign (str, i);
3978         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
3979                      EXPECT (Z_SYM_NAME));
3980       }
3981   }
3982
3983   /* In FULL mode, an incomplete symbol doesn't match.  */
3984   {
3985     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
3986                  {});
3987   }
3988
3989   /* A complete symbol with parameters matches any overload, since the
3990      index has no overload info.  */
3991   {
3992     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
3993                  EXPECT ("std::zfunction", "std::zfunction2"));
3994     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
3995                  EXPECT ("std::zfunction", "std::zfunction2"));
3996     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
3997                  EXPECT ("std::zfunction", "std::zfunction2"));
3998   }
3999
4000   /* Check that whitespace is ignored appropriately.  A symbol with a
4001      template argument list. */
4002   {
4003     static const char expected[] = "ns::foo<int>";
4004     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4005                  EXPECT (expected));
4006     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4007                  EXPECT (expected));
4008   }
4009
4010   /* Check that whitespace is ignored appropriately.  A symbol with a
4011      template argument list that includes a pointer.  */
4012   {
4013     static const char expected[] = "ns::foo<char*>";
4014     /* Try both completion and non-completion modes.  */
4015     static const bool completion_mode[2] = {false, true};
4016     for (size_t i = 0; i < 2; i++)
4017       {
4018         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4019                      completion_mode[i], EXPECT (expected));
4020         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4021                      completion_mode[i], EXPECT (expected));
4022
4023         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4024                      completion_mode[i], EXPECT (expected));
4025         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4026                      completion_mode[i], EXPECT (expected));
4027       }
4028   }
4029
4030   {
4031     /* Check method qualifiers are ignored.  */
4032     static const char expected[] = "ns::foo<char*>";
4033     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4034                  symbol_name_match_type::FULL, true, EXPECT (expected));
4035     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4036                  symbol_name_match_type::FULL, true, EXPECT (expected));
4037     CHECK_MATCH ("foo < char * >  ( int ) const",
4038                  symbol_name_match_type::WILD, true, EXPECT (expected));
4039     CHECK_MATCH ("foo < char * >  ( int ) &&",
4040                  symbol_name_match_type::WILD, true, EXPECT (expected));
4041   }
4042
4043   /* Test lookup names that don't match anything.  */
4044   {
4045     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4046                  {});
4047
4048     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4049                  {});
4050   }
4051
4052   /* Some wild matching tests, exercising "(anonymous namespace)",
4053      which should not be confused with a parameter list.  */
4054   {
4055     static const char *syms[] = {
4056       "A::B::C",
4057       "B::C",
4058       "C",
4059       "A :: B :: C ( int )",
4060       "B :: C ( int )",
4061       "C ( int )",
4062     };
4063
4064     for (const char *s : syms)
4065       {
4066         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4067                      EXPECT ("(anonymous namespace)::A::B::C"));
4068       }
4069   }
4070
4071   {
4072     static const char expected[] = "ns2::tmpl<int>::foo2";
4073     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4074                  EXPECT (expected));
4075     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4076                  EXPECT (expected));
4077   }
4078
4079   SELF_CHECK (!any_mismatch);
4080
4081 #undef EXPECT
4082 #undef CHECK_MATCH
4083 }
4084
4085 static void
4086 run_test ()
4087 {
4088   test_mapped_index_find_name_component_bounds ();
4089   test_dw2_expand_symtabs_matching_symbol ();
4090 }
4091
4092 }} // namespace selftests::dw2_expand_symtabs_matching
4093
4094 #endif /* GDB_SELF_TEST */
4095
4096 /* If FILE_MATCHER is NULL or if PER_CU has
4097    dwarf2_per_cu_quick_data::MARK set (see
4098    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4099    EXPANSION_NOTIFY on it.  */
4100
4101 static bool
4102 dw2_expand_symtabs_matching_one
4103   (dwarf2_per_cu_data *per_cu,
4104    dwarf2_per_objfile *per_objfile,
4105    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4106    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4107 {
4108   if (file_matcher == NULL || per_cu->v.quick->mark)
4109     {
4110       bool symtab_was_null = !per_objfile->symtab_set_p (per_cu);
4111
4112       compunit_symtab *symtab
4113         = dw2_instantiate_symtab (per_cu, per_objfile, false);
4114       gdb_assert (symtab != nullptr);
4115
4116       if (expansion_notify != NULL && symtab_was_null)
4117         return expansion_notify (symtab);
4118     }
4119   return true;
4120 }
4121
4122 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4123    matched, to expand corresponding CUs that were marked.  IDX is the
4124    index of the symbol name that matched.  */
4125
4126 static bool
4127 dw2_expand_marked_cus
4128   (dwarf2_per_objfile *per_objfile, offset_type idx,
4129    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4130    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4131    block_search_flags search_flags,
4132    search_domain kind)
4133 {
4134   offset_type vec_len, vec_idx;
4135   bool global_seen = false;
4136   mapped_index &index = *per_objfile->per_bfd->index_table;
4137
4138   offset_view vec (index.constant_pool.slice (index.symbol_vec_index (idx)));
4139   vec_len = vec[0];
4140   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4141     {
4142       offset_type cu_index_and_attrs = vec[vec_idx + 1];
4143       /* This value is only valid for index versions >= 7.  */
4144       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4145       gdb_index_symbol_kind symbol_kind =
4146         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4147       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4148       /* Only check the symbol attributes if they're present.
4149          Indices prior to version 7 don't record them,
4150          and indices >= 7 may elide them for certain symbols
4151          (gold does this).  */
4152       int attrs_valid =
4153         (index.version >= 7
4154          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4155
4156       /* Work around gold/15646.  */
4157       if (attrs_valid
4158           && !is_static
4159           && symbol_kind == GDB_INDEX_SYMBOL_KIND_TYPE)
4160         {
4161           if (global_seen)
4162             continue;
4163
4164           global_seen = true;
4165         }
4166
4167       /* Only check the symbol's kind if it has one.  */
4168       if (attrs_valid)
4169         {
4170           if (is_static)
4171             {
4172               if ((search_flags & SEARCH_STATIC_BLOCK) == 0)
4173                 continue;
4174             }
4175           else
4176             {
4177               if ((search_flags & SEARCH_GLOBAL_BLOCK) == 0)
4178                 continue;
4179             }
4180
4181           switch (kind)
4182             {
4183             case VARIABLES_DOMAIN:
4184               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4185                 continue;
4186               break;
4187             case FUNCTIONS_DOMAIN:
4188               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4189                 continue;
4190               break;
4191             case TYPES_DOMAIN:
4192               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4193                 continue;
4194               break;
4195             case MODULES_DOMAIN:
4196               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4197                 continue;
4198               break;
4199             default:
4200               break;
4201             }
4202         }
4203
4204       /* Don't crash on bad data.  */
4205       if (cu_index >= per_objfile->per_bfd->all_comp_units.size ())
4206         {
4207           complaint (_(".gdb_index entry has bad CU index"
4208                        " [in module %s]"), objfile_name (per_objfile->objfile));
4209           continue;
4210         }
4211
4212       dwarf2_per_cu_data *per_cu = per_objfile->per_bfd->get_cu (cu_index);
4213       if (!dw2_expand_symtabs_matching_one (per_cu, per_objfile, file_matcher,
4214                                             expansion_notify))
4215         return false;
4216     }
4217
4218   return true;
4219 }
4220
4221 /* If FILE_MATCHER is non-NULL, set all the
4222    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
4223    that match FILE_MATCHER.  */
4224
4225 static void
4226 dw_expand_symtabs_matching_file_matcher
4227   (dwarf2_per_objfile *per_objfile,
4228    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
4229 {
4230   if (file_matcher == NULL)
4231     return;
4232
4233   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4234                                             htab_eq_pointer,
4235                                             NULL, xcalloc, xfree));
4236   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4237                                                 htab_eq_pointer,
4238                                                 NULL, xcalloc, xfree));
4239
4240   /* The rule is CUs specify all the files, including those used by
4241      any TU, so there's no need to scan TUs here.  */
4242
4243   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
4244     {
4245       QUIT;
4246
4247       if (per_cu->is_debug_types)
4248         continue;
4249       per_cu->v.quick->mark = 0;
4250
4251       /* We only need to look at symtabs not already expanded.  */
4252       if (per_objfile->symtab_set_p (per_cu.get ()))
4253         continue;
4254
4255       quick_file_names *file_data = dw2_get_file_names (per_cu.get (),
4256                                                         per_objfile);
4257       if (file_data == NULL)
4258         continue;
4259
4260       if (htab_find (visited_not_found.get (), file_data) != NULL)
4261         continue;
4262       else if (htab_find (visited_found.get (), file_data) != NULL)
4263         {
4264           per_cu->v.quick->mark = 1;
4265           continue;
4266         }
4267
4268       for (int j = 0; j < file_data->num_file_names; ++j)
4269         {
4270           const char *this_real_name;
4271
4272           if (file_matcher (file_data->file_names[j], false))
4273             {
4274               per_cu->v.quick->mark = 1;
4275               break;
4276             }
4277
4278           /* Before we invoke realpath, which can get expensive when many
4279              files are involved, do a quick comparison of the basenames.  */
4280           if (!basenames_may_differ
4281               && !file_matcher (lbasename (file_data->file_names[j]),
4282                                 true))
4283             continue;
4284
4285           this_real_name = dw2_get_real_path (per_objfile, file_data, j);
4286           if (file_matcher (this_real_name, false))
4287             {
4288               per_cu->v.quick->mark = 1;
4289               break;
4290             }
4291         }
4292
4293       void **slot = htab_find_slot (per_cu->v.quick->mark
4294                                     ? visited_found.get ()
4295                                     : visited_not_found.get (),
4296                                     file_data, INSERT);
4297       *slot = file_data;
4298     }
4299 }
4300
4301 bool
4302 dwarf2_gdb_index::expand_symtabs_matching
4303     (struct objfile *objfile,
4304      gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4305      const lookup_name_info *lookup_name,
4306      gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4307      gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4308      block_search_flags search_flags,
4309      domain_enum domain,
4310      enum search_domain kind)
4311 {
4312   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4313
4314   /* index_table is NULL if OBJF_READNOW.  */
4315   if (!per_objfile->per_bfd->index_table)
4316     return true;
4317
4318   dw_expand_symtabs_matching_file_matcher (per_objfile, file_matcher);
4319
4320   /* This invariant is documented in quick-functions.h.  */
4321   gdb_assert (lookup_name != nullptr || symbol_matcher == nullptr);
4322   if (lookup_name == nullptr)
4323     {
4324       for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
4325         {
4326           QUIT;
4327
4328           if (!dw2_expand_symtabs_matching_one (per_cu.get (), per_objfile,
4329                                                 file_matcher,
4330                                                 expansion_notify))
4331             return false;
4332         }
4333       return true;
4334     }
4335
4336   mapped_index &index = *per_objfile->per_bfd->index_table;
4337
4338   bool result
4339     = dw2_expand_symtabs_matching_symbol (index, *lookup_name,
4340                                           symbol_matcher,
4341                                           [&] (offset_type idx)
4342     {
4343       if (!dw2_expand_marked_cus (per_objfile, idx, file_matcher,
4344                                   expansion_notify, search_flags, kind))
4345         return false;
4346       return true;
4347     }, per_objfile);
4348
4349   return result;
4350 }
4351
4352 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4353    symtab.  */
4354
4355 static struct compunit_symtab *
4356 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4357                                           CORE_ADDR pc)
4358 {
4359   int i;
4360
4361   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4362       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4363     return cust;
4364
4365   if (cust->includes == NULL)
4366     return NULL;
4367
4368   for (i = 0; cust->includes[i]; ++i)
4369     {
4370       struct compunit_symtab *s = cust->includes[i];
4371
4372       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4373       if (s != NULL)
4374         return s;
4375     }
4376
4377   return NULL;
4378 }
4379
4380 struct compunit_symtab *
4381 dwarf2_base_index_functions::find_pc_sect_compunit_symtab
4382      (struct objfile *objfile,
4383       struct bound_minimal_symbol msymbol,
4384       CORE_ADDR pc,
4385       struct obj_section *section,
4386       int warn_if_readin)
4387 {
4388   struct dwarf2_per_cu_data *data;
4389   struct compunit_symtab *result;
4390
4391   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4392   if (per_objfile->per_bfd->index_addrmap == nullptr)
4393     return NULL;
4394
4395   CORE_ADDR baseaddr = objfile->text_section_offset ();
4396   data = ((struct dwarf2_per_cu_data *)
4397           addrmap_find (per_objfile->per_bfd->index_addrmap,
4398                         pc - baseaddr));
4399   if (!data)
4400     return NULL;
4401
4402   if (warn_if_readin && per_objfile->symtab_set_p (data))
4403     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4404              paddress (objfile->arch (), pc));
4405
4406   result = recursively_find_pc_sect_compunit_symtab
4407     (dw2_instantiate_symtab (data, per_objfile, false), pc);
4408
4409   gdb_assert (result != NULL);
4410   return result;
4411 }
4412
4413 void
4414 dwarf2_base_index_functions::map_symbol_filenames
4415      (struct objfile *objfile,
4416       gdb::function_view<symbol_filename_ftype> fun,
4417       bool need_fullname)
4418 {
4419   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4420
4421   /* Use caches to ensure we only call FUN once for each filename.  */
4422   filename_seen_cache filenames_cache;
4423   std::unordered_set<quick_file_names *> qfn_cache;
4424
4425   /* The rule is CUs specify all the files, including those used by any TU,
4426      so there's no need to scan TUs here.  We can ignore file names coming
4427      from already-expanded CUs.  It is possible that an expanded CU might
4428      reuse the file names data from a currently unexpanded CU, in this
4429      case we don't want to report the files from the unexpanded CU.  */
4430
4431   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
4432     {
4433       if (per_objfile->symtab_set_p (per_cu.get ()))
4434         {
4435           if (per_cu->v.quick->file_names != nullptr)
4436             qfn_cache.insert (per_cu->v.quick->file_names);
4437         }
4438     }
4439
4440   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
4441     {
4442       /* We only need to look at symtabs not already expanded.  */
4443       if (per_objfile->symtab_set_p (per_cu.get ()))
4444         continue;
4445
4446       quick_file_names *file_data = dw2_get_file_names (per_cu.get (),
4447                                                         per_objfile);
4448       if (file_data == nullptr
4449           || qfn_cache.find (file_data) != qfn_cache.end ())
4450         continue;
4451
4452       for (int j = 0; j < file_data->num_file_names; ++j)
4453         {
4454           const char *filename = file_data->file_names[j];
4455           filenames_cache.seen (filename);
4456         }
4457     }
4458
4459   filenames_cache.traverse ([&] (const char *filename)
4460     {
4461       gdb::unique_xmalloc_ptr<char> this_real_name;
4462
4463       if (need_fullname)
4464         this_real_name = gdb_realpath (filename);
4465       fun (filename, this_real_name.get ());
4466     });
4467 }
4468
4469 bool
4470 dwarf2_base_index_functions::has_symbols (struct objfile *objfile)
4471 {
4472   return true;
4473 }
4474
4475 /* See quick_symbol_functions::has_unexpanded_symtabs in quick-symbol.h.  */
4476
4477 bool
4478 dwarf2_base_index_functions::has_unexpanded_symtabs (struct objfile *objfile)
4479 {
4480   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
4481
4482   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
4483     {
4484       /* Is this already expanded?  */
4485       if (per_objfile->symtab_set_p (per_cu.get ()))
4486         continue;
4487
4488       /* It has not yet been expanded.  */
4489       return true;
4490     }
4491
4492   return false;
4493 }
4494
4495 /* DWARF-5 debug_names reader.  */
4496
4497 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
4498 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
4499
4500 /* A helper function that reads the .debug_names section in SECTION
4501    and fills in MAP.  FILENAME is the name of the file containing the
4502    section; it is used for error reporting.
4503
4504    Returns true if all went well, false otherwise.  */
4505
4506 static bool
4507 read_debug_names_from_section (struct objfile *objfile,
4508                                const char *filename,
4509                                struct dwarf2_section_info *section,
4510                                mapped_debug_names &map)
4511 {
4512   if (section->empty ())
4513     return false;
4514
4515   /* Older elfutils strip versions could keep the section in the main
4516      executable while splitting it for the separate debug info file.  */
4517   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
4518     return false;
4519
4520   section->read (objfile);
4521
4522   map.dwarf5_byte_order = gdbarch_byte_order (objfile->arch ());
4523
4524   const gdb_byte *addr = section->buffer;
4525
4526   bfd *const abfd = section->get_bfd_owner ();
4527
4528   unsigned int bytes_read;
4529   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
4530   addr += bytes_read;
4531
4532   map.dwarf5_is_dwarf64 = bytes_read != 4;
4533   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
4534   if (bytes_read + length != section->size)
4535     {
4536       /* There may be multiple per-CU indices.  */
4537       warning (_("Section .debug_names in %s length %s does not match "
4538                  "section length %s, ignoring .debug_names."),
4539                filename, plongest (bytes_read + length),
4540                pulongest (section->size));
4541       return false;
4542     }
4543
4544   /* The version number.  */
4545   uint16_t version = read_2_bytes (abfd, addr);
4546   addr += 2;
4547   if (version != 5)
4548     {
4549       warning (_("Section .debug_names in %s has unsupported version %d, "
4550                  "ignoring .debug_names."),
4551                filename, version);
4552       return false;
4553     }
4554
4555   /* Padding.  */
4556   uint16_t padding = read_2_bytes (abfd, addr);
4557   addr += 2;
4558   if (padding != 0)
4559     {
4560       warning (_("Section .debug_names in %s has unsupported padding %d, "
4561                  "ignoring .debug_names."),
4562                filename, padding);
4563       return false;
4564     }
4565
4566   /* comp_unit_count - The number of CUs in the CU list.  */
4567   map.cu_count = read_4_bytes (abfd, addr);
4568   addr += 4;
4569
4570   /* local_type_unit_count - The number of TUs in the local TU
4571      list.  */
4572   map.tu_count = read_4_bytes (abfd, addr);
4573   addr += 4;
4574
4575   /* foreign_type_unit_count - The number of TUs in the foreign TU
4576      list.  */
4577   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
4578   addr += 4;
4579   if (foreign_tu_count != 0)
4580     {
4581       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
4582                  "ignoring .debug_names."),
4583                filename, static_cast<unsigned long> (foreign_tu_count));
4584       return false;
4585     }
4586
4587   /* bucket_count - The number of hash buckets in the hash lookup
4588      table.  */
4589   map.bucket_count = read_4_bytes (abfd, addr);
4590   addr += 4;
4591
4592   /* name_count - The number of unique names in the index.  */
4593   map.name_count = read_4_bytes (abfd, addr);
4594   addr += 4;
4595
4596   /* abbrev_table_size - The size in bytes of the abbreviations
4597      table.  */
4598   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
4599   addr += 4;
4600
4601   /* augmentation_string_size - The size in bytes of the augmentation
4602      string.  This value is rounded up to a multiple of 4.  */
4603   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
4604   addr += 4;
4605   map.augmentation_is_gdb = ((augmentation_string_size
4606                               == sizeof (dwarf5_augmentation))
4607                              && memcmp (addr, dwarf5_augmentation,
4608                                         sizeof (dwarf5_augmentation)) == 0);
4609   augmentation_string_size += (-augmentation_string_size) & 3;
4610   addr += augmentation_string_size;
4611
4612   /* List of CUs */
4613   map.cu_table_reordered = addr;
4614   addr += map.cu_count * map.offset_size;
4615
4616   /* List of Local TUs */
4617   map.tu_table_reordered = addr;
4618   addr += map.tu_count * map.offset_size;
4619
4620   /* Hash Lookup Table */
4621   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
4622   addr += map.bucket_count * 4;
4623   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
4624   addr += map.name_count * 4;
4625
4626   /* Name Table */
4627   map.name_table_string_offs_reordered = addr;
4628   addr += map.name_count * map.offset_size;
4629   map.name_table_entry_offs_reordered = addr;
4630   addr += map.name_count * map.offset_size;
4631
4632   const gdb_byte *abbrev_table_start = addr;
4633   for (;;)
4634     {
4635       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
4636       addr += bytes_read;
4637       if (index_num == 0)
4638         break;
4639
4640       const auto insertpair
4641         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
4642       if (!insertpair.second)
4643         {
4644           warning (_("Section .debug_names in %s has duplicate index %s, "
4645                      "ignoring .debug_names."),
4646                    filename, pulongest (index_num));
4647           return false;
4648         }
4649       mapped_debug_names::index_val &indexval = insertpair.first->second;
4650       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
4651       addr += bytes_read;
4652
4653       for (;;)
4654         {
4655           mapped_debug_names::index_val::attr attr;
4656           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
4657           addr += bytes_read;
4658           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
4659           addr += bytes_read;
4660           if (attr.form == DW_FORM_implicit_const)
4661             {
4662               attr.implicit_const = read_signed_leb128 (abfd, addr,
4663                                                         &bytes_read);
4664               addr += bytes_read;
4665             }
4666           if (attr.dw_idx == 0 && attr.form == 0)
4667             break;
4668           indexval.attr_vec.push_back (std::move (attr));
4669         }
4670     }
4671   if (addr != abbrev_table_start + abbrev_table_size)
4672     {
4673       warning (_("Section .debug_names in %s has abbreviation_table "
4674                  "of size %s vs. written as %u, ignoring .debug_names."),
4675                filename, plongest (addr - abbrev_table_start),
4676                abbrev_table_size);
4677       return false;
4678     }
4679   map.entry_pool = addr;
4680
4681   return true;
4682 }
4683
4684 /* A helper for create_cus_from_debug_names that handles the MAP's CU
4685    list.  */
4686
4687 static void
4688 create_cus_from_debug_names_list (dwarf2_per_bfd *per_bfd,
4689                                   const mapped_debug_names &map,
4690                                   dwarf2_section_info &section,
4691                                   bool is_dwz)
4692 {
4693   if (!map.augmentation_is_gdb)
4694     {
4695       for (uint32_t i = 0; i < map.cu_count; ++i)
4696         {
4697           sect_offset sect_off
4698             = (sect_offset) (extract_unsigned_integer
4699                              (map.cu_table_reordered + i * map.offset_size,
4700                               map.offset_size,
4701                               map.dwarf5_byte_order));
4702           /* We don't know the length of the CU, because the CU list in a
4703              .debug_names index can be incomplete, so we can't use the start
4704              of the next CU as end of this CU.  We create the CUs here with
4705              length 0, and in cutu_reader::cutu_reader we'll fill in the
4706              actual length.  */
4707           dwarf2_per_cu_data_up per_cu
4708             = create_cu_from_index_list (per_bfd, &section, is_dwz,
4709                                          sect_off, 0);
4710           per_bfd->all_comp_units.push_back (std::move (per_cu));
4711         }
4712       return;
4713     }
4714
4715   sect_offset sect_off_prev;
4716   for (uint32_t i = 0; i <= map.cu_count; ++i)
4717     {
4718       sect_offset sect_off_next;
4719       if (i < map.cu_count)
4720         {
4721           sect_off_next
4722             = (sect_offset) (extract_unsigned_integer
4723                              (map.cu_table_reordered + i * map.offset_size,
4724                               map.offset_size,
4725                               map.dwarf5_byte_order));
4726         }
4727       else
4728         sect_off_next = (sect_offset) section.size;
4729       if (i >= 1)
4730         {
4731           const ULONGEST length = sect_off_next - sect_off_prev;
4732           dwarf2_per_cu_data_up per_cu
4733             = create_cu_from_index_list (per_bfd, &section, is_dwz,
4734                                          sect_off_prev, length);
4735           per_bfd->all_comp_units.push_back (std::move (per_cu));
4736         }
4737       sect_off_prev = sect_off_next;
4738     }
4739 }
4740
4741 /* Read the CU list from the mapped index, and use it to create all
4742    the CU objects for this dwarf2_per_objfile.  */
4743
4744 static void
4745 create_cus_from_debug_names (dwarf2_per_bfd *per_bfd,
4746                              const mapped_debug_names &map,
4747                              const mapped_debug_names &dwz_map)
4748 {
4749   gdb_assert (per_bfd->all_comp_units.empty ());
4750   per_bfd->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
4751
4752   create_cus_from_debug_names_list (per_bfd, map, per_bfd->info,
4753                                     false /* is_dwz */);
4754
4755   if (dwz_map.cu_count == 0)
4756     return;
4757
4758   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
4759   create_cus_from_debug_names_list (per_bfd, dwz_map, dwz->info,
4760                                     true /* is_dwz */);
4761 }
4762
4763 /* Read .debug_names.  If everything went ok, initialize the "quick"
4764    elements of all the CUs and return true.  Otherwise, return false.  */
4765
4766 static bool
4767 dwarf2_read_debug_names (dwarf2_per_objfile *per_objfile)
4768 {
4769   std::unique_ptr<mapped_debug_names> map (new mapped_debug_names);
4770   mapped_debug_names dwz_map;
4771   struct objfile *objfile = per_objfile->objfile;
4772   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
4773
4774   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
4775                                       &per_bfd->debug_names, *map))
4776     return false;
4777
4778   /* Don't use the index if it's empty.  */
4779   if (map->name_count == 0)
4780     return false;
4781
4782   /* If there is a .dwz file, read it so we can get its CU list as
4783      well.  */
4784   dwz_file *dwz = dwarf2_get_dwz_file (per_bfd);
4785   if (dwz != NULL)
4786     {
4787       if (!read_debug_names_from_section (objfile,
4788                                           bfd_get_filename (dwz->dwz_bfd.get ()),
4789                                           &dwz->debug_names, dwz_map))
4790         {
4791           warning (_("could not read '.debug_names' section from %s; skipping"),
4792                    bfd_get_filename (dwz->dwz_bfd.get ()));
4793           return false;
4794         }
4795     }
4796
4797   create_cus_from_debug_names (per_bfd, *map, dwz_map);
4798
4799   if (map->tu_count != 0)
4800     {
4801       /* We can only handle a single .debug_types when we have an
4802          index.  */
4803       if (per_bfd->types.size () != 1)
4804         return false;
4805
4806       dwarf2_section_info *section = &per_bfd->types[0];
4807
4808       create_signatured_type_table_from_debug_names
4809         (per_objfile, *map, section, &per_bfd->abbrev);
4810     }
4811
4812   create_addrmap_from_aranges (per_objfile, &per_bfd->debug_aranges);
4813
4814   per_bfd->debug_names_table = std::move (map);
4815   per_bfd->using_index = 1;
4816   per_bfd->quick_file_names_table =
4817     create_quick_file_names_table (per_bfd->all_comp_units.size ());
4818
4819   return true;
4820 }
4821
4822 /* Type used to manage iterating over all CUs looking for a symbol for
4823    .debug_names.  */
4824
4825 class dw2_debug_names_iterator
4826 {
4827 public:
4828   dw2_debug_names_iterator (const mapped_debug_names &map,
4829                             block_search_flags block_index,
4830                             domain_enum domain,
4831                             const char *name, dwarf2_per_objfile *per_objfile)
4832     : m_map (map), m_block_index (block_index), m_domain (domain),
4833       m_addr (find_vec_in_debug_names (map, name, per_objfile)),
4834       m_per_objfile (per_objfile)
4835   {}
4836
4837   dw2_debug_names_iterator (const mapped_debug_names &map,
4838                             search_domain search, uint32_t namei,
4839                             dwarf2_per_objfile *per_objfile,
4840                             domain_enum domain = UNDEF_DOMAIN)
4841     : m_map (map),
4842       m_domain (domain),
4843       m_search (search),
4844       m_addr (find_vec_in_debug_names (map, namei, per_objfile)),
4845       m_per_objfile (per_objfile)
4846   {}
4847
4848   dw2_debug_names_iterator (const mapped_debug_names &map,
4849                             block_search_flags block_index, domain_enum domain,
4850                             uint32_t namei, dwarf2_per_objfile *per_objfile)
4851     : m_map (map), m_block_index (block_index), m_domain (domain),
4852       m_addr (find_vec_in_debug_names (map, namei, per_objfile)),
4853       m_per_objfile (per_objfile)
4854   {}
4855
4856   /* Return the next matching CU or NULL if there are no more.  */
4857   dwarf2_per_cu_data *next ();
4858
4859 private:
4860   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
4861                                                   const char *name,
4862                                                   dwarf2_per_objfile *per_objfile);
4863   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
4864                                                   uint32_t namei,
4865                                                   dwarf2_per_objfile *per_objfile);
4866
4867   /* The internalized form of .debug_names.  */
4868   const mapped_debug_names &m_map;
4869
4870   /* Restrict the search to these blocks.  */
4871   block_search_flags m_block_index = (SEARCH_GLOBAL_BLOCK
4872                                       | SEARCH_STATIC_BLOCK);
4873
4874   /* The kind of symbol we're looking for.  */
4875   const domain_enum m_domain = UNDEF_DOMAIN;
4876   const search_domain m_search = ALL_DOMAIN;
4877
4878   /* The list of CUs from the index entry of the symbol, or NULL if
4879      not found.  */
4880   const gdb_byte *m_addr;
4881
4882   dwarf2_per_objfile *m_per_objfile;
4883 };
4884
4885 const char *
4886 mapped_debug_names::namei_to_name
4887   (uint32_t namei, dwarf2_per_objfile *per_objfile) const
4888 {
4889   const ULONGEST namei_string_offs
4890     = extract_unsigned_integer ((name_table_string_offs_reordered
4891                                  + namei * offset_size),
4892                                 offset_size,
4893                                 dwarf5_byte_order);
4894   return read_indirect_string_at_offset (per_objfile, namei_string_offs);
4895 }
4896
4897 /* Find a slot in .debug_names for the object named NAME.  If NAME is
4898    found, return pointer to its pool data.  If NAME cannot be found,
4899    return NULL.  */
4900
4901 const gdb_byte *
4902 dw2_debug_names_iterator::find_vec_in_debug_names
4903   (const mapped_debug_names &map, const char *name,
4904    dwarf2_per_objfile *per_objfile)
4905 {
4906   int (*cmp) (const char *, const char *);
4907
4908   gdb::unique_xmalloc_ptr<char> without_params;
4909   if (current_language->la_language == language_cplus
4910       || current_language->la_language == language_fortran
4911       || current_language->la_language == language_d)
4912     {
4913       /* NAME is already canonical.  Drop any qualifiers as
4914          .debug_names does not contain any.  */
4915
4916       if (strchr (name, '(') != NULL)
4917         {
4918           without_params = cp_remove_params (name);
4919           if (without_params != NULL)
4920             name = without_params.get ();
4921         }
4922     }
4923
4924   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
4925
4926   const uint32_t full_hash = dwarf5_djb_hash (name);
4927   uint32_t namei
4928     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
4929                                 (map.bucket_table_reordered
4930                                  + (full_hash % map.bucket_count)), 4,
4931                                 map.dwarf5_byte_order);
4932   if (namei == 0)
4933     return NULL;
4934   --namei;
4935   if (namei >= map.name_count)
4936     {
4937       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
4938                    "[in module %s]"),
4939                  namei, map.name_count,
4940                  objfile_name (per_objfile->objfile));
4941       return NULL;
4942     }
4943
4944   for (;;)
4945     {
4946       const uint32_t namei_full_hash
4947         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
4948                                     (map.hash_table_reordered + namei), 4,
4949                                     map.dwarf5_byte_order);
4950       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
4951         return NULL;
4952
4953       if (full_hash == namei_full_hash)
4954         {
4955           const char *const namei_string = map.namei_to_name (namei, per_objfile);
4956
4957 #if 0 /* An expensive sanity check.  */
4958           if (namei_full_hash != dwarf5_djb_hash (namei_string))
4959             {
4960               complaint (_("Wrong .debug_names hash for string at index %u "
4961                            "[in module %s]"),
4962                          namei, objfile_name (dwarf2_per_objfile->objfile));
4963               return NULL;
4964             }
4965 #endif
4966
4967           if (cmp (namei_string, name) == 0)
4968             {
4969               const ULONGEST namei_entry_offs
4970                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
4971                                              + namei * map.offset_size),
4972                                             map.offset_size, map.dwarf5_byte_order);
4973               return map.entry_pool + namei_entry_offs;
4974             }
4975         }
4976
4977       ++namei;
4978       if (namei >= map.name_count)
4979         return NULL;
4980     }
4981 }
4982
4983 const gdb_byte *
4984 dw2_debug_names_iterator::find_vec_in_debug_names
4985   (const mapped_debug_names &map, uint32_t namei, dwarf2_per_objfile *per_objfile)
4986 {
4987   if (namei >= map.name_count)
4988     {
4989       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
4990                    "[in module %s]"),
4991                  namei, map.name_count,
4992                  objfile_name (per_objfile->objfile));
4993       return NULL;
4994     }
4995
4996   const ULONGEST namei_entry_offs
4997     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
4998                                  + namei * map.offset_size),
4999                                 map.offset_size, map.dwarf5_byte_order);
5000   return map.entry_pool + namei_entry_offs;
5001 }
5002
5003 /* See dw2_debug_names_iterator.  */
5004
5005 dwarf2_per_cu_data *
5006 dw2_debug_names_iterator::next ()
5007 {
5008   if (m_addr == NULL)
5009     return NULL;
5010
5011   dwarf2_per_bfd *per_bfd = m_per_objfile->per_bfd;
5012   struct objfile *objfile = m_per_objfile->objfile;
5013   bfd *const abfd = objfile->obfd;
5014
5015  again:
5016
5017   unsigned int bytes_read;
5018   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5019   m_addr += bytes_read;
5020   if (abbrev == 0)
5021     return NULL;
5022
5023   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5024   if (indexval_it == m_map.abbrev_map.cend ())
5025     {
5026       complaint (_("Wrong .debug_names undefined abbrev code %s "
5027                    "[in module %s]"),
5028                  pulongest (abbrev), objfile_name (objfile));
5029       return NULL;
5030     }
5031   const mapped_debug_names::index_val &indexval = indexval_it->second;
5032   enum class symbol_linkage {
5033     unknown,
5034     static_,
5035     extern_,
5036   } symbol_linkage_ = symbol_linkage::unknown;
5037   dwarf2_per_cu_data *per_cu = NULL;
5038   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5039     {
5040       ULONGEST ull;
5041       switch (attr.form)
5042         {
5043         case DW_FORM_implicit_const:
5044           ull = attr.implicit_const;
5045           break;
5046         case DW_FORM_flag_present:
5047           ull = 1;
5048           break;
5049         case DW_FORM_udata:
5050           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5051           m_addr += bytes_read;
5052           break;
5053         case DW_FORM_ref4:
5054           ull = read_4_bytes (abfd, m_addr);
5055           m_addr += 4;
5056           break;
5057         case DW_FORM_ref8:
5058           ull = read_8_bytes (abfd, m_addr);
5059           m_addr += 8;
5060           break;
5061         case DW_FORM_ref_sig8:
5062           ull = read_8_bytes (abfd, m_addr);
5063           m_addr += 8;
5064           break;
5065         default:
5066           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5067                      dwarf_form_name (attr.form),
5068                      objfile_name (objfile));
5069           return NULL;
5070         }
5071       switch (attr.dw_idx)
5072         {
5073         case DW_IDX_compile_unit:
5074           /* Don't crash on bad data.  */
5075           if (ull >= per_bfd->all_comp_units.size ())
5076             {
5077               complaint (_(".debug_names entry has bad CU index %s"
5078                            " [in module %s]"),
5079                          pulongest (ull),
5080                          objfile_name (objfile));
5081               continue;
5082             }
5083           per_cu = per_bfd->get_cu (ull);
5084           break;
5085         case DW_IDX_type_unit:
5086           /* Don't crash on bad data.  */
5087           if (ull >= per_bfd->tu_stats.nr_tus)
5088             {
5089               complaint (_(".debug_names entry has bad TU index %s"
5090                            " [in module %s]"),
5091                          pulongest (ull),
5092                          objfile_name (objfile));
5093               continue;
5094             }
5095           per_cu = per_bfd->get_cu (ull + per_bfd->tu_stats.nr_tus);
5096           break;
5097         case DW_IDX_die_offset:
5098           /* In a per-CU index (as opposed to a per-module index), index
5099              entries without CU attribute implicitly refer to the single CU.  */
5100           if (per_cu == NULL)
5101             per_cu = per_bfd->get_cu (0);
5102           break;
5103         case DW_IDX_GNU_internal:
5104           if (!m_map.augmentation_is_gdb)
5105             break;
5106           symbol_linkage_ = symbol_linkage::static_;
5107           break;
5108         case DW_IDX_GNU_external:
5109           if (!m_map.augmentation_is_gdb)
5110             break;
5111           symbol_linkage_ = symbol_linkage::extern_;
5112           break;
5113         }
5114     }
5115
5116   /* Skip if already read in.  */
5117   if (m_per_objfile->symtab_set_p (per_cu))
5118     goto again;
5119
5120   /* Check static vs global.  */
5121   if (symbol_linkage_ != symbol_linkage::unknown)
5122     {
5123       if (symbol_linkage_ == symbol_linkage::static_)
5124         {
5125           if ((m_block_index & SEARCH_STATIC_BLOCK) == 0)
5126             goto again;
5127         }
5128       else
5129         {
5130           if ((m_block_index & SEARCH_GLOBAL_BLOCK) == 0)
5131             goto again;
5132         }
5133     }
5134
5135   /* Match dw2_symtab_iter_next, symbol_kind
5136      and debug_names::psymbol_tag.  */
5137   switch (m_domain)
5138     {
5139     case VAR_DOMAIN:
5140       switch (indexval.dwarf_tag)
5141         {
5142         case DW_TAG_variable:
5143         case DW_TAG_subprogram:
5144         /* Some types are also in VAR_DOMAIN.  */
5145         case DW_TAG_typedef:
5146         case DW_TAG_structure_type:
5147           break;
5148         default:
5149           goto again;
5150         }
5151       break;
5152     case STRUCT_DOMAIN:
5153       switch (indexval.dwarf_tag)
5154         {
5155         case DW_TAG_typedef:
5156         case DW_TAG_structure_type:
5157           break;
5158         default:
5159           goto again;
5160         }
5161       break;
5162     case LABEL_DOMAIN:
5163       switch (indexval.dwarf_tag)
5164         {
5165         case 0:
5166         case DW_TAG_variable:
5167           break;
5168         default:
5169           goto again;
5170         }
5171       break;
5172     case MODULE_DOMAIN:
5173       switch (indexval.dwarf_tag)
5174         {
5175         case DW_TAG_module:
5176           break;
5177         default:
5178           goto again;
5179         }
5180       break;
5181     default:
5182       break;
5183     }
5184
5185   /* Match dw2_expand_symtabs_matching, symbol_kind and
5186      debug_names::psymbol_tag.  */
5187   switch (m_search)
5188     {
5189     case VARIABLES_DOMAIN:
5190       switch (indexval.dwarf_tag)
5191         {
5192         case DW_TAG_variable:
5193           break;
5194         default:
5195           goto again;
5196         }
5197       break;
5198     case FUNCTIONS_DOMAIN:
5199       switch (indexval.dwarf_tag)
5200         {
5201         case DW_TAG_subprogram:
5202           break;
5203         default:
5204           goto again;
5205         }
5206       break;
5207     case TYPES_DOMAIN:
5208       switch (indexval.dwarf_tag)
5209         {
5210         case DW_TAG_typedef:
5211         case DW_TAG_structure_type:
5212           break;
5213         default:
5214           goto again;
5215         }
5216       break;
5217     case MODULES_DOMAIN:
5218       switch (indexval.dwarf_tag)
5219         {
5220         case DW_TAG_module:
5221           break;
5222         default:
5223           goto again;
5224         }
5225     default:
5226       break;
5227     }
5228
5229   return per_cu;
5230 }
5231
5232 /* This dumps minimal information about .debug_names.  It is called
5233    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
5234    uses this to verify that .debug_names has been loaded.  */
5235
5236 void
5237 dwarf2_debug_names_index::dump (struct objfile *objfile)
5238 {
5239   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5240
5241   gdb_assert (per_objfile->per_bfd->using_index);
5242   printf_filtered (".debug_names:");
5243   if (per_objfile->per_bfd->debug_names_table)
5244     printf_filtered (" exists\n");
5245   else
5246     printf_filtered (" faked for \"readnow\"\n");
5247   printf_filtered ("\n");
5248 }
5249
5250 void
5251 dwarf2_debug_names_index::expand_matching_symbols
5252   (struct objfile *objfile,
5253    const lookup_name_info &name, domain_enum domain,
5254    int global,
5255    symbol_compare_ftype *ordered_compare)
5256 {
5257   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5258
5259   /* debug_names_table is NULL if OBJF_READNOW.  */
5260   if (!per_objfile->per_bfd->debug_names_table)
5261     return;
5262
5263   mapped_debug_names &map = *per_objfile->per_bfd->debug_names_table;
5264   const block_search_flags block_flags
5265     = global ? SEARCH_GLOBAL_BLOCK : SEARCH_STATIC_BLOCK;
5266
5267   const char *match_name = name.ada ().lookup_name ().c_str ();
5268   auto matcher = [&] (const char *symname)
5269     {
5270       if (ordered_compare == nullptr)
5271         return true;
5272       return ordered_compare (symname, match_name) == 0;
5273     };
5274
5275   dw2_expand_symtabs_matching_symbol (map, name, matcher,
5276                                       [&] (offset_type namei)
5277     {
5278       /* The name was matched, now expand corresponding CUs that were
5279          marked.  */
5280       dw2_debug_names_iterator iter (map, block_flags, domain, namei,
5281                                      per_objfile);
5282
5283       struct dwarf2_per_cu_data *per_cu;
5284       while ((per_cu = iter.next ()) != NULL)
5285         dw2_expand_symtabs_matching_one (per_cu, per_objfile, nullptr,
5286                                          nullptr);
5287       return true;
5288     }, per_objfile);
5289 }
5290
5291 bool
5292 dwarf2_debug_names_index::expand_symtabs_matching
5293   (struct objfile *objfile,
5294    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5295    const lookup_name_info *lookup_name,
5296    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5297    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5298    block_search_flags search_flags,
5299    domain_enum domain,
5300    enum search_domain kind)
5301 {
5302   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5303
5304   /* debug_names_table is NULL if OBJF_READNOW.  */
5305   if (!per_objfile->per_bfd->debug_names_table)
5306     return true;
5307
5308   dw_expand_symtabs_matching_file_matcher (per_objfile, file_matcher);
5309
5310   /* This invariant is documented in quick-functions.h.  */
5311   gdb_assert (lookup_name != nullptr || symbol_matcher == nullptr);
5312   if (lookup_name == nullptr)
5313     {
5314       for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
5315         {
5316           QUIT;
5317
5318           if (!dw2_expand_symtabs_matching_one (per_cu.get (), per_objfile,
5319                                                 file_matcher,
5320                                                 expansion_notify))
5321             return false;
5322         }
5323       return true;
5324     }
5325
5326   mapped_debug_names &map = *per_objfile->per_bfd->debug_names_table;
5327
5328   bool result
5329     = dw2_expand_symtabs_matching_symbol (map, *lookup_name,
5330                                           symbol_matcher,
5331                                           [&] (offset_type namei)
5332     {
5333       /* The name was matched, now expand corresponding CUs that were
5334          marked.  */
5335       dw2_debug_names_iterator iter (map, kind, namei, per_objfile, domain);
5336
5337       struct dwarf2_per_cu_data *per_cu;
5338       while ((per_cu = iter.next ()) != NULL)
5339         if (!dw2_expand_symtabs_matching_one (per_cu, per_objfile,
5340                                               file_matcher,
5341                                               expansion_notify))
5342           return false;
5343       return true;
5344     }, per_objfile);
5345
5346   return result;
5347 }
5348
5349 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
5350    to either a dwarf2_per_bfd or dwz_file object.  */
5351
5352 template <typename T>
5353 static gdb::array_view<const gdb_byte>
5354 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
5355 {
5356   dwarf2_section_info *section = &section_owner->gdb_index;
5357
5358   if (section->empty ())
5359     return {};
5360
5361   /* Older elfutils strip versions could keep the section in the main
5362      executable while splitting it for the separate debug info file.  */
5363   if ((section->get_flags () & SEC_HAS_CONTENTS) == 0)
5364     return {};
5365
5366   section->read (obj);
5367
5368   /* dwarf2_section_info::size is a bfd_size_type, while
5369      gdb::array_view works with size_t.  On 32-bit hosts, with
5370      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
5371      is 32-bit.  So we need an explicit narrowing conversion here.
5372      This is fine, because it's impossible to allocate or mmap an
5373      array/buffer larger than what size_t can represent.  */
5374   return gdb::make_array_view (section->buffer, section->size);
5375 }
5376
5377 /* Lookup the index cache for the contents of the index associated to
5378    DWARF2_OBJ.  */
5379
5380 static gdb::array_view<const gdb_byte>
5381 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_bfd *dwarf2_per_bfd)
5382 {
5383   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
5384   if (build_id == nullptr)
5385     return {};
5386
5387   return global_index_cache.lookup_gdb_index (build_id,
5388                                               &dwarf2_per_bfd->index_cache_res);
5389 }
5390
5391 /* Same as the above, but for DWZ.  */
5392
5393 static gdb::array_view<const gdb_byte>
5394 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
5395 {
5396   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
5397   if (build_id == nullptr)
5398     return {};
5399
5400   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
5401 }
5402
5403 /* See dwarf2/public.h.  */
5404
5405 void
5406 dwarf2_initialize_objfile (struct objfile *objfile)
5407 {
5408   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5409   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
5410
5411   dwarf_read_debug_printf ("called");
5412
5413   /* If we're about to read full symbols, don't bother with the
5414      indices.  In this case we also don't care if some other debug
5415      format is making psymtabs, because they are all about to be
5416      expanded anyway.  */
5417   if ((objfile->flags & OBJF_READNOW))
5418     {
5419       dwarf_read_debug_printf ("readnow requested");
5420
5421       /* When using READNOW, the using_index flag (set below) indicates that
5422          PER_BFD was already initialized, when we loaded some other objfile.  */
5423       if (per_bfd->using_index)
5424         {
5425           dwarf_read_debug_printf ("using_index already set");
5426           per_objfile->resize_symtabs ();
5427           objfile->qf.push_front (make_dwarf_gdb_index ());
5428           return;
5429         }
5430
5431       per_bfd->using_index = 1;
5432       create_all_comp_units (per_objfile);
5433       per_bfd->quick_file_names_table
5434         = create_quick_file_names_table (per_bfd->all_comp_units.size ());
5435       per_objfile->resize_symtabs ();
5436
5437       for (int i = 0; i < per_bfd->all_comp_units.size (); ++i)
5438         {
5439           dwarf2_per_cu_data *per_cu = per_bfd->get_cu (i);
5440
5441           per_cu->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
5442                                             struct dwarf2_per_cu_quick_data);
5443         }
5444
5445       /* Arrange for gdb to see the "quick" functions.  However, these
5446          functions will be no-ops because we will have expanded all
5447          symtabs.  */
5448       objfile->qf.push_front (make_dwarf_gdb_index ());
5449       return;
5450     }
5451
5452   /* Was a debug names index already read when we processed an objfile sharing
5453      PER_BFD?  */
5454   if (per_bfd->debug_names_table != nullptr)
5455     {
5456       dwarf_read_debug_printf ("re-using shared debug names table");
5457       per_objfile->resize_symtabs ();
5458       objfile->qf.push_front (make_dwarf_debug_names ());
5459       return;
5460     }
5461
5462   /* Was a GDB index already read when we processed an objfile sharing
5463      PER_BFD?  */
5464   if (per_bfd->index_table != nullptr)
5465     {
5466       dwarf_read_debug_printf ("re-using shared index table");
5467       per_objfile->resize_symtabs ();
5468       objfile->qf.push_front (make_dwarf_gdb_index ());
5469       return;
5470     }
5471
5472   /* There might already be partial symtabs built for this BFD.  This happens
5473      when loading the same binary twice with the index-cache enabled.  If so,
5474      don't try to read an index.  The objfile / per_objfile initialization will
5475      be completed in dwarf2_build_psymtabs, in the standard partial symtabs
5476      code path.  */
5477   if (per_bfd->partial_symtabs != nullptr)
5478     {
5479       dwarf_read_debug_printf ("re-using shared partial symtabs");
5480       objfile->qf.push_front (make_lazy_dwarf_reader ());
5481       return;
5482     }
5483
5484   if (dwarf2_read_debug_names (per_objfile))
5485     {
5486       dwarf_read_debug_printf ("found debug names");
5487       per_objfile->resize_symtabs ();
5488       objfile->qf.push_front (make_dwarf_debug_names ());
5489       return;
5490     }
5491
5492   if (dwarf2_read_gdb_index (per_objfile,
5493                              get_gdb_index_contents_from_section<struct dwarf2_per_bfd>,
5494                              get_gdb_index_contents_from_section<dwz_file>))
5495     {
5496       dwarf_read_debug_printf ("found gdb index from file");
5497       per_objfile->resize_symtabs ();
5498       objfile->qf.push_front (make_dwarf_gdb_index ());
5499       return;
5500     }
5501
5502   /* ... otherwise, try to find the index in the index cache.  */
5503   if (dwarf2_read_gdb_index (per_objfile,
5504                              get_gdb_index_contents_from_cache,
5505                              get_gdb_index_contents_from_cache_dwz))
5506     {
5507       dwarf_read_debug_printf ("found gdb index from cache");
5508       global_index_cache.hit ();
5509       per_objfile->resize_symtabs ();
5510       objfile->qf.push_front (make_dwarf_gdb_index ());
5511       return;
5512     }
5513
5514   global_index_cache.miss ();
5515   objfile->qf.push_front (make_lazy_dwarf_reader ());
5516 }
5517
5518 \f
5519
5520 /* Build a partial symbol table.  */
5521
5522 void
5523 dwarf2_build_psymtabs (struct objfile *objfile, psymbol_functions *psf)
5524 {
5525   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
5526   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
5527
5528   if (per_bfd->partial_symtabs != nullptr)
5529     {
5530       /* Partial symbols were already read, so now we can simply
5531          attach them.  */
5532       if (psf == nullptr)
5533         {
5534           psf = new psymbol_functions (per_bfd->partial_symtabs);
5535           objfile->qf.emplace_front (psf);
5536         }
5537       else
5538         psf->set_partial_symtabs (per_bfd->partial_symtabs);
5539       per_objfile->resize_symtabs ();
5540       return;
5541     }
5542
5543   if (psf == nullptr)
5544     {
5545       psf = new psymbol_functions;
5546       objfile->qf.emplace_front (psf);
5547     }
5548   const std::shared_ptr<psymtab_storage> &partial_symtabs
5549     = psf->get_partial_symtabs ();
5550
5551   /* Set the local reference to partial symtabs, so that we don't try
5552      to read them again if reading another objfile with the same BFD.
5553      If we can't in fact share, this won't make a difference anyway as
5554      the dwarf2_per_bfd object won't be shared.  */
5555   per_bfd->partial_symtabs = partial_symtabs;
5556
5557   try
5558     {
5559       /* This isn't really ideal: all the data we allocate on the
5560          objfile's obstack is still uselessly kept around.  However,
5561          freeing it seems unsafe.  */
5562       psymtab_discarder psymtabs (partial_symtabs.get ());
5563       dwarf2_build_psymtabs_hard (per_objfile);
5564       psymtabs.keep ();
5565
5566       per_objfile->resize_symtabs ();
5567
5568       /* (maybe) store an index in the cache.  */
5569       global_index_cache.store (per_objfile);
5570     }
5571   catch (const gdb_exception_error &except)
5572     {
5573       exception_print (gdb_stderr, except);
5574     }
5575 }
5576
5577 /* Find the base address of the compilation unit for range lists and
5578    location lists.  It will normally be specified by DW_AT_low_pc.
5579    In DWARF-3 draft 4, the base address could be overridden by
5580    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
5581    compilation units with discontinuous ranges.  */
5582
5583 static void
5584 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
5585 {
5586   struct attribute *attr;
5587
5588   cu->base_address.reset ();
5589
5590   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
5591   if (attr != nullptr)
5592     cu->base_address = attr->as_address ();
5593   else
5594     {
5595       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
5596       if (attr != nullptr)
5597         cu->base_address = attr->as_address ();
5598     }
5599 }
5600
5601 /* Helper function that returns the proper abbrev section for
5602    THIS_CU.  */
5603
5604 static struct dwarf2_section_info *
5605 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
5606 {
5607   struct dwarf2_section_info *abbrev;
5608   dwarf2_per_bfd *per_bfd = this_cu->per_bfd;
5609
5610   if (this_cu->is_dwz)
5611     abbrev = &dwarf2_get_dwz_file (per_bfd, true)->abbrev;
5612   else
5613     abbrev = &per_bfd->abbrev;
5614
5615   return abbrev;
5616 }
5617
5618 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5619
5620 static sect_offset
5621 read_abbrev_offset (dwarf2_per_objfile *per_objfile,
5622                     struct dwarf2_section_info *section,
5623                     sect_offset sect_off)
5624 {
5625   bfd *abfd = section->get_bfd_owner ();
5626   const gdb_byte *info_ptr;
5627   unsigned int initial_length_size, offset_size;
5628   uint16_t version;
5629
5630   section->read (per_objfile->objfile);
5631   info_ptr = section->buffer + to_underlying (sect_off);
5632   read_initial_length (abfd, info_ptr, &initial_length_size);
5633   offset_size = initial_length_size == 4 ? 4 : 8;
5634   info_ptr += initial_length_size;
5635
5636   version = read_2_bytes (abfd, info_ptr);
5637   info_ptr += 2;
5638   if (version >= 5)
5639     {
5640       /* Skip unit type and address size.  */
5641       info_ptr += 2;
5642     }
5643
5644   return (sect_offset) read_offset (abfd, info_ptr, offset_size);
5645 }
5646
5647 /* A partial symtab that is used only for include files.  */
5648 struct dwarf2_include_psymtab : public partial_symtab
5649 {
5650   dwarf2_include_psymtab (const char *filename,
5651                           psymtab_storage *partial_symtabs,
5652                           objfile_per_bfd_storage *objfile_per_bfd)
5653     : partial_symtab (filename, partial_symtabs, objfile_per_bfd)
5654   {
5655   }
5656
5657   void read_symtab (struct objfile *objfile) override
5658   {
5659     /* It's an include file, no symbols to read for it.
5660        Everything is in the includer symtab.  */
5661
5662     /* The expansion of a dwarf2_include_psymtab is just a trigger for
5663        expansion of the includer psymtab.  We use the dependencies[0] field to
5664        model the includer.  But if we go the regular route of calling
5665        expand_psymtab here, and having expand_psymtab call expand_dependencies
5666        to expand the includer, we'll only use expand_psymtab on the includer
5667        (making it a non-toplevel psymtab), while if we expand the includer via
5668        another path, we'll use read_symtab (making it a toplevel psymtab).
5669        So, don't pretend a dwarf2_include_psymtab is an actual toplevel
5670        psymtab, and trigger read_symtab on the includer here directly.  */
5671     includer ()->read_symtab (objfile);
5672   }
5673
5674   void expand_psymtab (struct objfile *objfile) override
5675   {
5676     /* This is not called by read_symtab, and should not be called by any
5677        expand_dependencies.  */
5678     gdb_assert (false);
5679   }
5680
5681   bool readin_p (struct objfile *objfile) const override
5682   {
5683     return includer ()->readin_p (objfile);
5684   }
5685
5686   compunit_symtab *get_compunit_symtab (struct objfile *objfile) const override
5687   {
5688     return nullptr;
5689   }
5690
5691 private:
5692   partial_symtab *includer () const
5693   {
5694     /* An include psymtab has exactly one dependency: the psymtab that
5695        includes it.  */
5696     gdb_assert (this->number_of_dependencies == 1);
5697     return this->dependencies[0];
5698   }
5699 };
5700
5701 /* Allocate a new partial symtab for file named NAME and mark this new
5702    partial symtab as being an include of PST.  */
5703
5704 static void
5705 dwarf2_create_include_psymtab (dwarf2_per_bfd *per_bfd,
5706                                const char *name,
5707                                dwarf2_psymtab *pst,
5708                                psymtab_storage *partial_symtabs,
5709                                objfile_per_bfd_storage *objfile_per_bfd)
5710 {
5711   dwarf2_include_psymtab *subpst
5712     = new dwarf2_include_psymtab (name, partial_symtabs, objfile_per_bfd);
5713
5714   if (!IS_ABSOLUTE_PATH (subpst->filename))
5715     subpst->dirname = pst->dirname;
5716
5717   subpst->dependencies = per_bfd->partial_symtabs->allocate_dependencies (1);
5718   subpst->dependencies[0] = pst;
5719   subpst->number_of_dependencies = 1;
5720 }
5721
5722 /* Read the Line Number Program data and extract the list of files
5723    included by the source file represented by PST.  Build an include
5724    partial symtab for each of these included files.  */
5725
5726 static void
5727 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5728                                struct die_info *die,
5729                                const file_and_directory &fnd,
5730                                dwarf2_psymtab *pst)
5731 {
5732   line_header_up lh;
5733   struct attribute *attr;
5734
5735   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5736   if (attr != nullptr && attr->form_is_unsigned ())
5737     lh = dwarf_decode_line_header ((sect_offset) attr->as_unsigned (), cu);
5738   if (lh == NULL)
5739     return;  /* No linetable, so no includes.  */
5740
5741   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
5742      that we pass in the raw text_low here; that is ok because we're
5743      only decoding the line table to make include partial symtabs, and
5744      so the addresses aren't really used.  */
5745   dwarf_decode_lines (lh.get (), fnd, cu, pst,
5746                       pst->raw_text_low (), 1);
5747 }
5748
5749 static hashval_t
5750 hash_signatured_type (const void *item)
5751 {
5752   const struct signatured_type *sig_type
5753     = (const struct signatured_type *) item;
5754
5755   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5756   return sig_type->signature;
5757 }
5758
5759 static int
5760 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5761 {
5762   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5763   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5764
5765   return lhs->signature == rhs->signature;
5766 }
5767
5768 /* Allocate a hash table for signatured types.  */
5769
5770 static htab_up
5771 allocate_signatured_type_table ()
5772 {
5773   return htab_up (htab_create_alloc (41,
5774                                      hash_signatured_type,
5775                                      eq_signatured_type,
5776                                      NULL, xcalloc, xfree));
5777 }
5778
5779 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5780    and fill them into TYPES_HTAB.  It will process only type units,
5781    therefore DW_UT_type.  */
5782
5783 static void
5784 create_debug_type_hash_table (dwarf2_per_objfile *per_objfile,
5785                               struct dwo_file *dwo_file,
5786                               dwarf2_section_info *section, htab_up &types_htab,
5787                               rcuh_kind section_kind)
5788 {
5789   struct objfile *objfile = per_objfile->objfile;
5790   struct dwarf2_section_info *abbrev_section;
5791   bfd *abfd;
5792   const gdb_byte *info_ptr, *end_ptr;
5793
5794   abbrev_section = &dwo_file->sections.abbrev;
5795
5796   dwarf_read_debug_printf ("Reading %s for %s",
5797                            section->get_name (),
5798                            abbrev_section->get_file_name ());
5799
5800   section->read (objfile);
5801   info_ptr = section->buffer;
5802
5803   if (info_ptr == NULL)
5804     return;
5805
5806   /* We can't set abfd until now because the section may be empty or
5807      not present, in which case the bfd is unknown.  */
5808   abfd = section->get_bfd_owner ();
5809
5810   /* We don't use cutu_reader here because we don't need to read
5811      any dies: the signature is in the header.  */
5812
5813   end_ptr = info_ptr + section->size;
5814   while (info_ptr < end_ptr)
5815     {
5816       signatured_type_up sig_type;
5817       struct dwo_unit *dwo_tu;
5818       void **slot;
5819       const gdb_byte *ptr = info_ptr;
5820       struct comp_unit_head header;
5821       unsigned int length;
5822
5823       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
5824
5825       /* Initialize it due to a false compiler warning.  */
5826       header.signature = -1;
5827       header.type_cu_offset_in_tu = (cu_offset) -1;
5828
5829       /* We need to read the type's signature in order to build the hash
5830          table, but we don't need anything else just yet.  */
5831
5832       ptr = read_and_check_comp_unit_head (per_objfile, &header, section,
5833                                            abbrev_section, ptr, section_kind);
5834
5835       length = header.get_length ();
5836
5837       /* Skip dummy type units.  */
5838       if (ptr >= info_ptr + length
5839           || peek_abbrev_code (abfd, ptr) == 0
5840           || (header.unit_type != DW_UT_type
5841               && header.unit_type != DW_UT_split_type))
5842         {
5843           info_ptr += length;
5844           continue;
5845         }
5846
5847       if (types_htab == NULL)
5848         types_htab = allocate_dwo_unit_table ();
5849
5850       dwo_tu = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, dwo_unit);
5851       dwo_tu->dwo_file = dwo_file;
5852       dwo_tu->signature = header.signature;
5853       dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
5854       dwo_tu->section = section;
5855       dwo_tu->sect_off = sect_off;
5856       dwo_tu->length = length;
5857
5858       slot = htab_find_slot (types_htab.get (), dwo_tu, INSERT);
5859       gdb_assert (slot != NULL);
5860       if (*slot != NULL)
5861         complaint (_("debug type entry at offset %s is duplicate to"
5862                      " the entry at offset %s, signature %s"),
5863                    sect_offset_str (sect_off),
5864                    sect_offset_str (dwo_tu->sect_off),
5865                    hex_string (header.signature));
5866       *slot = dwo_tu;
5867
5868       dwarf_read_debug_printf_v ("  offset %s, signature %s",
5869                                  sect_offset_str (sect_off),
5870                                  hex_string (header.signature));
5871
5872       info_ptr += length;
5873     }
5874 }
5875
5876 /* Create the hash table of all entries in the .debug_types
5877    (or .debug_types.dwo) section(s).
5878    DWO_FILE is a pointer to the DWO file object.
5879
5880    The result is a pointer to the hash table or NULL if there are no types.
5881
5882    Note: This function processes DWO files only, not DWP files.  */
5883
5884 static void
5885 create_debug_types_hash_table (dwarf2_per_objfile *per_objfile,
5886                                struct dwo_file *dwo_file,
5887                                gdb::array_view<dwarf2_section_info> type_sections,
5888                                htab_up &types_htab)
5889 {
5890   for (dwarf2_section_info &section : type_sections)
5891     create_debug_type_hash_table (per_objfile, dwo_file, &section, types_htab,
5892                                   rcuh_kind::TYPE);
5893 }
5894
5895 /* Add an entry for signature SIG to dwarf2_per_objfile->per_bfd->signatured_types.
5896    If SLOT is non-NULL, it is the entry to use in the hash table.
5897    Otherwise we find one.  */
5898
5899 static struct signatured_type *
5900 add_type_unit (dwarf2_per_objfile *per_objfile, ULONGEST sig, void **slot)
5901 {
5902   if (per_objfile->per_bfd->all_comp_units.size ()
5903       == per_objfile->per_bfd->all_comp_units.capacity ())
5904     ++per_objfile->per_bfd->tu_stats.nr_all_type_units_reallocs;
5905
5906   signatured_type_up sig_type_holder
5907     = per_objfile->per_bfd->allocate_signatured_type (sig);
5908   signatured_type *sig_type = sig_type_holder.get ();
5909
5910   per_objfile->resize_symtabs ();
5911
5912   per_objfile->per_bfd->all_comp_units.emplace_back
5913     (sig_type_holder.release ());
5914   if (per_objfile->per_bfd->using_index)
5915     {
5916       sig_type->v.quick =
5917         OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack,
5918                         struct dwarf2_per_cu_quick_data);
5919     }
5920
5921   if (slot == NULL)
5922     {
5923       slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
5924                              sig_type, INSERT);
5925     }
5926   gdb_assert (*slot == NULL);
5927   *slot = sig_type;
5928   /* The rest of sig_type must be filled in by the caller.  */
5929   return sig_type;
5930 }
5931
5932 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5933    Fill in SIG_ENTRY with DWO_ENTRY.  */
5934
5935 static void
5936 fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile *per_objfile,
5937                                   struct signatured_type *sig_entry,
5938                                   struct dwo_unit *dwo_entry)
5939 {
5940   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
5941
5942   /* Make sure we're not clobbering something we don't expect to.  */
5943   gdb_assert (! sig_entry->queued);
5944   gdb_assert (per_objfile->get_cu (sig_entry) == NULL);
5945   if (per_bfd->using_index)
5946     {
5947       gdb_assert (sig_entry->v.quick != NULL);
5948       gdb_assert (!per_objfile->symtab_set_p (sig_entry));
5949     }
5950   else
5951       gdb_assert (sig_entry->v.psymtab == NULL);
5952   gdb_assert (sig_entry->signature == dwo_entry->signature);
5953   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5954   gdb_assert (sig_entry->type_unit_group == NULL);
5955   gdb_assert (sig_entry->dwo_unit == NULL);
5956
5957   sig_entry->section = dwo_entry->section;
5958   sig_entry->sect_off = dwo_entry->sect_off;
5959   sig_entry->length = dwo_entry->length;
5960   sig_entry->reading_dwo_directly = 1;
5961   sig_entry->per_bfd = per_bfd;
5962   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5963   sig_entry->dwo_unit = dwo_entry;
5964 }
5965
5966 /* Subroutine of lookup_signatured_type.
5967    If we haven't read the TU yet, create the signatured_type data structure
5968    for a TU to be read in directly from a DWO file, bypassing the stub.
5969    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5970    using .gdb_index, then when reading a CU we want to stay in the DWO file
5971    containing that CU.  Otherwise we could end up reading several other DWO
5972    files (due to comdat folding) to process the transitive closure of all the
5973    mentioned TUs, and that can be slow.  The current DWO file will have every
5974    type signature that it needs.
5975    We only do this for .gdb_index because in the psymtab case we already have
5976    to read all the DWOs to build the type unit groups.  */
5977
5978 static struct signatured_type *
5979 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5980 {
5981   dwarf2_per_objfile *per_objfile = cu->per_objfile;
5982   struct dwo_file *dwo_file;
5983   struct dwo_unit find_dwo_entry, *dwo_entry;
5984   void **slot;
5985
5986   gdb_assert (cu->dwo_unit && per_objfile->per_bfd->using_index);
5987
5988   /* If TU skeletons have been removed then we may not have read in any
5989      TUs yet.  */
5990   if (per_objfile->per_bfd->signatured_types == NULL)
5991     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
5992
5993   /* We only ever need to read in one copy of a signatured type.
5994      Use the global signatured_types array to do our own comdat-folding
5995      of types.  If this is the first time we're reading this TU, and
5996      the TU has an entry in .gdb_index, replace the recorded data from
5997      .gdb_index with this TU.  */
5998
5999   signatured_type find_sig_entry (sig);
6000   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
6001                          &find_sig_entry, INSERT);
6002   signatured_type *sig_entry = (struct signatured_type *) *slot;
6003
6004   /* We can get here with the TU already read, *or* in the process of being
6005      read.  Don't reassign the global entry to point to this DWO if that's
6006      the case.  Also note that if the TU is already being read, it may not
6007      have come from a DWO, the program may be a mix of Fission-compiled
6008      code and non-Fission-compiled code.  */
6009
6010   /* Have we already tried to read this TU?
6011      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6012      needn't exist in the global table yet).  */
6013   if (sig_entry != NULL && sig_entry->tu_read)
6014     return sig_entry;
6015
6016   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6017      dwo_unit of the TU itself.  */
6018   dwo_file = cu->dwo_unit->dwo_file;
6019
6020   /* Ok, this is the first time we're reading this TU.  */
6021   if (dwo_file->tus == NULL)
6022     return NULL;
6023   find_dwo_entry.signature = sig;
6024   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
6025                                              &find_dwo_entry);
6026   if (dwo_entry == NULL)
6027     return NULL;
6028
6029   /* If the global table doesn't have an entry for this TU, add one.  */
6030   if (sig_entry == NULL)
6031     sig_entry = add_type_unit (per_objfile, sig, slot);
6032
6033   fill_in_sig_entry_from_dwo_entry (per_objfile, sig_entry, dwo_entry);
6034   sig_entry->tu_read = 1;
6035   return sig_entry;
6036 }
6037
6038 /* Subroutine of lookup_signatured_type.
6039    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6040    then try the DWP file.  If the TU stub (skeleton) has been removed then
6041    it won't be in .gdb_index.  */
6042
6043 static struct signatured_type *
6044 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6045 {
6046   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6047   struct dwp_file *dwp_file = get_dwp_file (per_objfile);
6048   struct dwo_unit *dwo_entry;
6049   void **slot;
6050
6051   gdb_assert (cu->dwo_unit && per_objfile->per_bfd->using_index);
6052   gdb_assert (dwp_file != NULL);
6053
6054   /* If TU skeletons have been removed then we may not have read in any
6055      TUs yet.  */
6056   if (per_objfile->per_bfd->signatured_types == NULL)
6057     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
6058
6059   signatured_type find_sig_entry (sig);
6060   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
6061                          &find_sig_entry, INSERT);
6062   signatured_type *sig_entry = (struct signatured_type *) *slot;
6063
6064   /* Have we already tried to read this TU?
6065      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6066      needn't exist in the global table yet).  */
6067   if (sig_entry != NULL)
6068     return sig_entry;
6069
6070   if (dwp_file->tus == NULL)
6071     return NULL;
6072   dwo_entry = lookup_dwo_unit_in_dwp (per_objfile, dwp_file, NULL, sig,
6073                                       1 /* is_debug_types */);
6074   if (dwo_entry == NULL)
6075     return NULL;
6076
6077   sig_entry = add_type_unit (per_objfile, sig, slot);
6078   fill_in_sig_entry_from_dwo_entry (per_objfile, sig_entry, dwo_entry);
6079
6080   return sig_entry;
6081 }
6082
6083 /* Lookup a signature based type for DW_FORM_ref_sig8.
6084    Returns NULL if signature SIG is not present in the table.
6085    It is up to the caller to complain about this.  */
6086
6087 static struct signatured_type *
6088 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6089 {
6090   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6091
6092   if (cu->dwo_unit && per_objfile->per_bfd->using_index)
6093     {
6094       /* We're in a DWO/DWP file, and we're using .gdb_index.
6095          These cases require special processing.  */
6096       if (get_dwp_file (per_objfile) == NULL)
6097         return lookup_dwo_signatured_type (cu, sig);
6098       else
6099         return lookup_dwp_signatured_type (cu, sig);
6100     }
6101   else
6102     {
6103       if (per_objfile->per_bfd->signatured_types == NULL)
6104         return NULL;
6105       signatured_type find_entry (sig);
6106       return ((struct signatured_type *)
6107               htab_find (per_objfile->per_bfd->signatured_types.get (),
6108                          &find_entry));
6109     }
6110 }
6111
6112 /* Low level DIE reading support.  */
6113
6114 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6115
6116 static void
6117 init_cu_die_reader (struct die_reader_specs *reader,
6118                     struct dwarf2_cu *cu,
6119                     struct dwarf2_section_info *section,
6120                     struct dwo_file *dwo_file,
6121                     struct abbrev_table *abbrev_table)
6122 {
6123   gdb_assert (section->readin && section->buffer != NULL);
6124   reader->abfd = section->get_bfd_owner ();
6125   reader->cu = cu;
6126   reader->dwo_file = dwo_file;
6127   reader->die_section = section;
6128   reader->buffer = section->buffer;
6129   reader->buffer_end = section->buffer + section->size;
6130   reader->abbrev_table = abbrev_table;
6131 }
6132
6133 /* Subroutine of cutu_reader to simplify it.
6134    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6135    There's just a lot of work to do, and cutu_reader is big enough
6136    already.
6137
6138    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6139    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6140    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6141    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6142    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6143    STUB_COMP_DIR may be non-NULL.
6144    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE
6145    are filled in with the info of the DIE from the DWO file.
6146    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
6147    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
6148    kept around for at least as long as *RESULT_READER.
6149
6150    The result is non-zero if a valid (non-dummy) DIE was found.  */
6151
6152 static int
6153 read_cutu_die_from_dwo (dwarf2_cu *cu,
6154                         struct dwo_unit *dwo_unit,
6155                         struct die_info *stub_comp_unit_die,
6156                         const char *stub_comp_dir,
6157                         struct die_reader_specs *result_reader,
6158                         const gdb_byte **result_info_ptr,
6159                         struct die_info **result_comp_unit_die,
6160                         abbrev_table_up *result_dwo_abbrev_table)
6161 {
6162   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6163   dwarf2_per_cu_data *per_cu = cu->per_cu;
6164   struct objfile *objfile = per_objfile->objfile;
6165   bfd *abfd;
6166   const gdb_byte *begin_info_ptr, *info_ptr;
6167   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6168   int i,num_extra_attrs;
6169   struct dwarf2_section_info *dwo_abbrev_section;
6170   struct die_info *comp_unit_die;
6171
6172   /* At most one of these may be provided.  */
6173   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6174
6175   /* These attributes aren't processed until later:
6176      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6177      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6178      referenced later.  However, these attributes are found in the stub
6179      which we won't have later.  In order to not impose this complication
6180      on the rest of the code, we read them here and copy them to the
6181      DWO CU/TU die.  */
6182
6183   stmt_list = NULL;
6184   low_pc = NULL;
6185   high_pc = NULL;
6186   ranges = NULL;
6187   comp_dir = NULL;
6188
6189   if (stub_comp_unit_die != NULL)
6190     {
6191       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6192          DWO file.  */
6193       if (!per_cu->is_debug_types)
6194         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6195       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6196       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6197       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6198       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6199
6200       cu->addr_base = stub_comp_unit_die->addr_base ();
6201
6202       /* There should be a DW_AT_GNU_ranges_base attribute here (if needed).
6203          We need the value before we can process DW_AT_ranges values from the
6204          DWO.  */
6205       cu->gnu_ranges_base = stub_comp_unit_die->gnu_ranges_base ();
6206
6207       /* For DWARF5: record the DW_AT_rnglists_base value from the skeleton.  If
6208          there are attributes of form DW_FORM_rnglistx in the skeleton, they'll
6209          need the rnglists base.  Attributes of form DW_FORM_rnglistx in the
6210          split unit don't use it, as the DWO has its own .debug_rnglists.dwo
6211          section.  */
6212       cu->rnglists_base = stub_comp_unit_die->rnglists_base ();
6213     }
6214   else if (stub_comp_dir != NULL)
6215     {
6216       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6217       comp_dir = OBSTACK_ZALLOC (&cu->comp_unit_obstack, struct attribute);
6218       comp_dir->name = DW_AT_comp_dir;
6219       comp_dir->form = DW_FORM_string;
6220       comp_dir->set_string_noncanonical (stub_comp_dir);
6221     }
6222
6223   /* Set up for reading the DWO CU/TU.  */
6224   cu->dwo_unit = dwo_unit;
6225   dwarf2_section_info *section = dwo_unit->section;
6226   section->read (objfile);
6227   abfd = section->get_bfd_owner ();
6228   begin_info_ptr = info_ptr = (section->buffer
6229                                + to_underlying (dwo_unit->sect_off));
6230   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
6231
6232   if (per_cu->is_debug_types)
6233     {
6234       signatured_type *sig_type = (struct signatured_type *) per_cu;
6235
6236       info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6237                                                 section, dwo_abbrev_section,
6238                                                 info_ptr, rcuh_kind::TYPE);
6239       /* This is not an assert because it can be caused by bad debug info.  */
6240       if (sig_type->signature != cu->header.signature)
6241         {
6242           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
6243                    " TU at offset %s [in module %s]"),
6244                  hex_string (sig_type->signature),
6245                  hex_string (cu->header.signature),
6246                  sect_offset_str (dwo_unit->sect_off),
6247                  bfd_get_filename (abfd));
6248         }
6249       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6250       /* For DWOs coming from DWP files, we don't know the CU length
6251          nor the type's offset in the TU until now.  */
6252       dwo_unit->length = cu->header.get_length ();
6253       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
6254
6255       /* Establish the type offset that can be used to lookup the type.
6256          For DWO files, we don't know it until now.  */
6257       sig_type->type_offset_in_section
6258         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
6259     }
6260   else
6261     {
6262       info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6263                                                 section, dwo_abbrev_section,
6264                                                 info_ptr, rcuh_kind::COMPILE);
6265       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6266       /* For DWOs coming from DWP files, we don't know the CU length
6267          until now.  */
6268       dwo_unit->length = cu->header.get_length ();
6269     }
6270
6271   dwo_abbrev_section->read (objfile);
6272   *result_dwo_abbrev_table
6273     = abbrev_table::read (dwo_abbrev_section, cu->header.abbrev_sect_off);
6274   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
6275                       result_dwo_abbrev_table->get ());
6276
6277   /* Read in the die, but leave space to copy over the attributes
6278      from the stub.  This has the benefit of simplifying the rest of
6279      the code - all the work to maintain the illusion of a single
6280      DW_TAG_{compile,type}_unit DIE is done here.  */
6281   num_extra_attrs = ((stmt_list != NULL)
6282                      + (low_pc != NULL)
6283                      + (high_pc != NULL)
6284                      + (ranges != NULL)
6285                      + (comp_dir != NULL));
6286   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
6287                               num_extra_attrs);
6288
6289   /* Copy over the attributes from the stub to the DIE we just read in.  */
6290   comp_unit_die = *result_comp_unit_die;
6291   i = comp_unit_die->num_attrs;
6292   if (stmt_list != NULL)
6293     comp_unit_die->attrs[i++] = *stmt_list;
6294   if (low_pc != NULL)
6295     comp_unit_die->attrs[i++] = *low_pc;
6296   if (high_pc != NULL)
6297     comp_unit_die->attrs[i++] = *high_pc;
6298   if (ranges != NULL)
6299     comp_unit_die->attrs[i++] = *ranges;
6300   if (comp_dir != NULL)
6301     comp_unit_die->attrs[i++] = *comp_dir;
6302   comp_unit_die->num_attrs += num_extra_attrs;
6303
6304   if (dwarf_die_debug)
6305     {
6306       fprintf_unfiltered (gdb_stdlog,
6307                           "Read die from %s@0x%x of %s:\n",
6308                           section->get_name (),
6309                           (unsigned) (begin_info_ptr - section->buffer),
6310                           bfd_get_filename (abfd));
6311       dump_die (comp_unit_die, dwarf_die_debug);
6312     }
6313
6314   /* Skip dummy compilation units.  */
6315   if (info_ptr >= begin_info_ptr + dwo_unit->length
6316       || peek_abbrev_code (abfd, info_ptr) == 0)
6317     return 0;
6318
6319   *result_info_ptr = info_ptr;
6320   return 1;
6321 }
6322
6323 /* Return the signature of the compile unit, if found. In DWARF 4 and before,
6324    the signature is in the DW_AT_GNU_dwo_id attribute. In DWARF 5 and later, the
6325    signature is part of the header.  */
6326 static gdb::optional<ULONGEST>
6327 lookup_dwo_id (struct dwarf2_cu *cu, struct die_info* comp_unit_die)
6328 {
6329   if (cu->header.version >= 5)
6330     return cu->header.signature;
6331   struct attribute *attr;
6332   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6333   if (attr == nullptr || !attr->form_is_unsigned ())
6334     return gdb::optional<ULONGEST> ();
6335   return attr->as_unsigned ();
6336 }
6337
6338 /* Subroutine of cutu_reader to simplify it.
6339    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
6340    Returns NULL if the specified DWO unit cannot be found.  */
6341
6342 static struct dwo_unit *
6343 lookup_dwo_unit (dwarf2_cu *cu, die_info *comp_unit_die, const char *dwo_name)
6344 {
6345   dwarf2_per_cu_data *per_cu = cu->per_cu;
6346   struct dwo_unit *dwo_unit;
6347   const char *comp_dir;
6348
6349   gdb_assert (cu != NULL);
6350
6351   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
6352   dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
6353   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6354
6355   if (per_cu->is_debug_types)
6356     dwo_unit = lookup_dwo_type_unit (cu, dwo_name, comp_dir);
6357   else
6358     {
6359       gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
6360
6361       if (!signature.has_value ())
6362         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
6363                  " [in module %s]"),
6364                dwo_name, bfd_get_filename (per_cu->per_bfd->obfd));
6365
6366       dwo_unit = lookup_dwo_comp_unit (cu, dwo_name, comp_dir, *signature);
6367     }
6368
6369   return dwo_unit;
6370 }
6371
6372 /* Subroutine of cutu_reader to simplify it.
6373    See it for a description of the parameters.
6374    Read a TU directly from a DWO file, bypassing the stub.  */
6375
6376 void
6377 cutu_reader::init_tu_and_read_dwo_dies (dwarf2_per_cu_data *this_cu,
6378                                         dwarf2_per_objfile *per_objfile,
6379                                         dwarf2_cu *existing_cu)
6380 {
6381   struct signatured_type *sig_type;
6382
6383   /* Verify we can do the following downcast, and that we have the
6384      data we need.  */
6385   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
6386   sig_type = (struct signatured_type *) this_cu;
6387   gdb_assert (sig_type->dwo_unit != NULL);
6388
6389   dwarf2_cu *cu;
6390
6391   if (existing_cu != nullptr)
6392     {
6393       cu = existing_cu;
6394       gdb_assert (cu->dwo_unit == sig_type->dwo_unit);
6395       /* There's no need to do the rereading_dwo_cu handling that
6396          cutu_reader does since we don't read the stub.  */
6397     }
6398   else
6399     {
6400       /* If an existing_cu is provided, a dwarf2_cu must not exist for this_cu
6401          in per_objfile yet.  */
6402       gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
6403       m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
6404       cu = m_new_cu.get ();
6405     }
6406
6407   /* A future optimization, if needed, would be to use an existing
6408      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
6409      could share abbrev tables.  */
6410
6411   if (read_cutu_die_from_dwo (cu, sig_type->dwo_unit,
6412                               NULL /* stub_comp_unit_die */,
6413                               sig_type->dwo_unit->dwo_file->comp_dir,
6414                               this, &info_ptr,
6415                               &comp_unit_die,
6416                               &m_dwo_abbrev_table) == 0)
6417     {
6418       /* Dummy die.  */
6419       dummy_p = true;
6420     }
6421 }
6422
6423 /* Initialize a CU (or TU) and read its DIEs.
6424    If the CU defers to a DWO file, read the DWO file as well.
6425
6426    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
6427    Otherwise the table specified in the comp unit header is read in and used.
6428    This is an optimization for when we already have the abbrev table.
6429
6430    If EXISTING_CU is non-NULL, then use it.  Otherwise, a new CU is
6431    allocated.  */
6432
6433 cutu_reader::cutu_reader (dwarf2_per_cu_data *this_cu,
6434                           dwarf2_per_objfile *per_objfile,
6435                           struct abbrev_table *abbrev_table,
6436                           dwarf2_cu *existing_cu,
6437                           bool skip_partial)
6438   : die_reader_specs {},
6439     m_this_cu (this_cu)
6440 {
6441   struct objfile *objfile = per_objfile->objfile;
6442   struct dwarf2_section_info *section = this_cu->section;
6443   bfd *abfd = section->get_bfd_owner ();
6444   const gdb_byte *begin_info_ptr;
6445   struct signatured_type *sig_type = NULL;
6446   struct dwarf2_section_info *abbrev_section;
6447   /* Non-zero if CU currently points to a DWO file and we need to
6448      reread it.  When this happens we need to reread the skeleton die
6449      before we can reread the DWO file (this only applies to CUs, not TUs).  */
6450   int rereading_dwo_cu = 0;
6451
6452   if (dwarf_die_debug)
6453     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
6454                         this_cu->is_debug_types ? "type" : "comp",
6455                         sect_offset_str (this_cu->sect_off));
6456
6457   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6458      file (instead of going through the stub), short-circuit all of this.  */
6459   if (this_cu->reading_dwo_directly)
6460     {
6461       /* Narrow down the scope of possibilities to have to understand.  */
6462       gdb_assert (this_cu->is_debug_types);
6463       gdb_assert (abbrev_table == NULL);
6464       init_tu_and_read_dwo_dies (this_cu, per_objfile, existing_cu);
6465       return;
6466     }
6467
6468   /* This is cheap if the section is already read in.  */
6469   section->read (objfile);
6470
6471   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6472
6473   abbrev_section = get_abbrev_section_for_cu (this_cu);
6474
6475   dwarf2_cu *cu;
6476
6477   if (existing_cu != nullptr)
6478     {
6479       cu = existing_cu;
6480       /* If this CU is from a DWO file we need to start over, we need to
6481          refetch the attributes from the skeleton CU.
6482          This could be optimized by retrieving those attributes from when we
6483          were here the first time: the previous comp_unit_die was stored in
6484          comp_unit_obstack.  But there's no data yet that we need this
6485          optimization.  */
6486       if (cu->dwo_unit != NULL)
6487         rereading_dwo_cu = 1;
6488     }
6489   else
6490     {
6491       /* If an existing_cu is provided, a dwarf2_cu must not exist for this_cu
6492          in per_objfile yet.  */
6493       gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
6494       m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
6495       cu = m_new_cu.get ();
6496     }
6497
6498   /* Get the header.  */
6499   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6500     {
6501       /* We already have the header, there's no need to read it in again.  */
6502       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6503     }
6504   else
6505     {
6506       if (this_cu->is_debug_types)
6507         {
6508           info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6509                                                     section, abbrev_section,
6510                                                     info_ptr, rcuh_kind::TYPE);
6511
6512           /* Since per_cu is the first member of struct signatured_type,
6513              we can go from a pointer to one to a pointer to the other.  */
6514           sig_type = (struct signatured_type *) this_cu;
6515           gdb_assert (sig_type->signature == cu->header.signature);
6516           gdb_assert (sig_type->type_offset_in_tu
6517                       == cu->header.type_cu_offset_in_tu);
6518           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6519
6520           /* LENGTH has not been set yet for type units if we're
6521              using .gdb_index.  */
6522           this_cu->length = cu->header.get_length ();
6523
6524           /* Establish the type offset that can be used to lookup the type.  */
6525           sig_type->type_offset_in_section =
6526             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6527
6528           this_cu->dwarf_version = cu->header.version;
6529         }
6530       else
6531         {
6532           info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header,
6533                                                     section, abbrev_section,
6534                                                     info_ptr,
6535                                                     rcuh_kind::COMPILE);
6536
6537           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6538           if (this_cu->length == 0)
6539             this_cu->length = cu->header.get_length ();
6540           else
6541             gdb_assert (this_cu->length == cu->header.get_length ());
6542           this_cu->dwarf_version = cu->header.version;
6543         }
6544     }
6545
6546   /* Skip dummy compilation units.  */
6547   if (info_ptr >= begin_info_ptr + this_cu->length
6548       || peek_abbrev_code (abfd, info_ptr) == 0)
6549     {
6550       dummy_p = true;
6551       return;
6552     }
6553
6554   /* If we don't have them yet, read the abbrevs for this compilation unit.
6555      And if we need to read them now, make sure they're freed when we're
6556      done.  */
6557   if (abbrev_table != NULL)
6558     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6559   else
6560     {
6561       abbrev_section->read (objfile);
6562       m_abbrev_table_holder
6563         = abbrev_table::read (abbrev_section, cu->header.abbrev_sect_off);
6564       abbrev_table = m_abbrev_table_holder.get ();
6565     }
6566
6567   /* Read the top level CU/TU die.  */
6568   init_cu_die_reader (this, cu, section, NULL, abbrev_table);
6569   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
6570
6571   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
6572     {
6573       dummy_p = true;
6574       return;
6575     }
6576
6577   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6578      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
6579      table from the DWO file and pass the ownership over to us.  It will be
6580      referenced from READER, so we must make sure to free it after we're done
6581      with READER.
6582
6583      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6584      DWO CU, that this test will fail (the attribute will not be present).  */
6585   const char *dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
6586   if (dwo_name != nullptr)
6587     {
6588       struct dwo_unit *dwo_unit;
6589       struct die_info *dwo_comp_unit_die;
6590
6591       if (comp_unit_die->has_children)
6592         {
6593           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
6594                        " has children (offset %s) [in module %s]"),
6595                      sect_offset_str (this_cu->sect_off),
6596                      bfd_get_filename (abfd));
6597         }
6598       dwo_unit = lookup_dwo_unit (cu, comp_unit_die, dwo_name);
6599       if (dwo_unit != NULL)
6600         {
6601           if (read_cutu_die_from_dwo (cu, dwo_unit,
6602                                       comp_unit_die, NULL,
6603                                       this, &info_ptr,
6604                                       &dwo_comp_unit_die,
6605                                       &m_dwo_abbrev_table) == 0)
6606             {
6607               /* Dummy die.  */
6608               dummy_p = true;
6609               return;
6610             }
6611           comp_unit_die = dwo_comp_unit_die;
6612         }
6613       else
6614         {
6615           /* Yikes, we couldn't find the rest of the DIE, we only have
6616              the stub.  A complaint has already been logged.  There's
6617              not much more we can do except pass on the stub DIE to
6618              die_reader_func.  We don't want to throw an error on bad
6619              debug info.  */
6620         }
6621     }
6622 }
6623
6624 void
6625 cutu_reader::keep ()
6626 {
6627   /* Done, clean up.  */
6628   gdb_assert (!dummy_p);
6629   if (m_new_cu != NULL)
6630     {
6631       /* Save this dwarf2_cu in the per_objfile.  The per_objfile owns it
6632          now.  */
6633       dwarf2_per_objfile *per_objfile = m_new_cu->per_objfile;
6634       per_objfile->set_cu (m_this_cu, m_new_cu.release ());
6635     }
6636 }
6637
6638 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name (DW_AT_dwo_name)
6639    if present. DWO_FILE, if non-NULL, is the DWO file to read (the caller is
6640    assumed to have already done the lookup to find the DWO file).
6641
6642    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6643    THIS_CU->is_debug_types, but nothing else.
6644
6645    We fill in THIS_CU->length.
6646
6647    THIS_CU->cu is always freed when done.
6648    This is done in order to not leave THIS_CU->cu in a state where we have
6649    to care whether it refers to the "main" CU or the DWO CU.
6650
6651    When parent_cu is passed, it is used to provide a default value for
6652    str_offsets_base and addr_base from the parent.  */
6653
6654 cutu_reader::cutu_reader (dwarf2_per_cu_data *this_cu,
6655                           dwarf2_per_objfile *per_objfile,
6656                           struct dwarf2_cu *parent_cu,
6657                           struct dwo_file *dwo_file)
6658   : die_reader_specs {},
6659     m_this_cu (this_cu)
6660 {
6661   struct objfile *objfile = per_objfile->objfile;
6662   struct dwarf2_section_info *section = this_cu->section;
6663   bfd *abfd = section->get_bfd_owner ();
6664   struct dwarf2_section_info *abbrev_section;
6665   const gdb_byte *begin_info_ptr, *info_ptr;
6666
6667   if (dwarf_die_debug)
6668     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
6669                         this_cu->is_debug_types ? "type" : "comp",
6670                         sect_offset_str (this_cu->sect_off));
6671
6672   gdb_assert (per_objfile->get_cu (this_cu) == nullptr);
6673
6674   abbrev_section = (dwo_file != NULL
6675                     ? &dwo_file->sections.abbrev
6676                     : get_abbrev_section_for_cu (this_cu));
6677
6678   /* This is cheap if the section is already read in.  */
6679   section->read (objfile);
6680
6681   m_new_cu.reset (new dwarf2_cu (this_cu, per_objfile));
6682
6683   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6684   info_ptr = read_and_check_comp_unit_head (per_objfile, &m_new_cu->header,
6685                                             section, abbrev_section, info_ptr,
6686                                             (this_cu->is_debug_types
6687                                              ? rcuh_kind::TYPE
6688                                              : rcuh_kind::COMPILE));
6689
6690   if (parent_cu != nullptr)
6691     {
6692       m_new_cu->str_offsets_base = parent_cu->str_offsets_base;
6693       m_new_cu->addr_base = parent_cu->addr_base;
6694     }
6695   this_cu->length = m_new_cu->header.get_length ();
6696
6697   /* Skip dummy compilation units.  */
6698   if (info_ptr >= begin_info_ptr + this_cu->length
6699       || peek_abbrev_code (abfd, info_ptr) == 0)
6700     {
6701       dummy_p = true;
6702       return;
6703     }
6704
6705   abbrev_section->read (objfile);
6706   m_abbrev_table_holder
6707     = abbrev_table::read (abbrev_section, m_new_cu->header.abbrev_sect_off);
6708
6709   init_cu_die_reader (this, m_new_cu.get (), section, dwo_file,
6710                       m_abbrev_table_holder.get ());
6711   info_ptr = read_full_die (this, &comp_unit_die, info_ptr);
6712 }
6713
6714 \f
6715 /* Type Unit Groups.
6716
6717    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6718    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6719    so that all types coming from the same compilation (.o file) are grouped
6720    together.  A future step could be to put the types in the same symtab as
6721    the CU the types ultimately came from.  */
6722
6723 static hashval_t
6724 hash_type_unit_group (const void *item)
6725 {
6726   const struct type_unit_group *tu_group
6727     = (const struct type_unit_group *) item;
6728
6729   return hash_stmt_list_entry (&tu_group->hash);
6730 }
6731
6732 static int
6733 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6734 {
6735   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6736   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6737
6738   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6739 }
6740
6741 /* Allocate a hash table for type unit groups.  */
6742
6743 static htab_up
6744 allocate_type_unit_groups_table ()
6745 {
6746   return htab_up (htab_create_alloc (3,
6747                                      hash_type_unit_group,
6748                                      eq_type_unit_group,
6749                                      htab_delete_entry<type_unit_group>,
6750                                      xcalloc, xfree));
6751 }
6752
6753 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6754    partial symtabs.  We combine several TUs per psymtab to not let the size
6755    of any one psymtab grow too big.  */
6756 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6757 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6758
6759 /* Helper routine for get_type_unit_group.
6760    Create the type_unit_group object used to hold one or more TUs.  */
6761
6762 static std::unique_ptr<type_unit_group>
6763 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6764 {
6765   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6766   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
6767
6768   std::unique_ptr<type_unit_group> tu_group (new type_unit_group);
6769   tu_group->per_bfd = per_bfd;
6770
6771   if (per_bfd->using_index)
6772     {
6773       tu_group->v.quick = OBSTACK_ZALLOC (&per_bfd->obstack,
6774                                           struct dwarf2_per_cu_quick_data);
6775     }
6776   else
6777     {
6778       unsigned int line_offset = to_underlying (line_offset_struct);
6779       dwarf2_psymtab *pst;
6780       std::string name;
6781
6782       /* Give the symtab a useful name for debug purposes.  */
6783       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6784         name = string_printf ("<type_units_%d>",
6785                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6786       else
6787         name = string_printf ("<type_units_at_0x%x>", line_offset);
6788
6789       pst = create_partial_symtab (tu_group.get (), per_objfile,
6790                                    name.c_str ());
6791       pst->anonymous = true;
6792     }
6793
6794   tu_group->hash.dwo_unit = cu->dwo_unit;
6795   tu_group->hash.line_sect_off = line_offset_struct;
6796
6797   return tu_group;
6798 }
6799
6800 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6801    STMT_LIST is a DW_AT_stmt_list attribute.  */
6802
6803 static struct type_unit_group *
6804 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6805 {
6806   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6807   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
6808   struct type_unit_group *tu_group;
6809   void **slot;
6810   unsigned int line_offset;
6811   struct type_unit_group type_unit_group_for_lookup;
6812
6813   if (per_objfile->per_bfd->type_unit_groups == NULL)
6814     per_objfile->per_bfd->type_unit_groups = allocate_type_unit_groups_table ();
6815
6816   /* Do we need to create a new group, or can we use an existing one?  */
6817
6818   if (stmt_list != nullptr && stmt_list->form_is_unsigned ())
6819     {
6820       line_offset = stmt_list->as_unsigned ();
6821       ++tu_stats->nr_symtab_sharers;
6822     }
6823   else
6824     {
6825       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6826          We can do various things here like create one group per TU or
6827          spread them over multiple groups to split up the expansion work.
6828          To avoid worst case scenarios (too many groups or too large groups)
6829          we, umm, group them in bunches.  */
6830       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6831                      | (tu_stats->nr_stmt_less_type_units
6832                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6833       ++tu_stats->nr_stmt_less_type_units;
6834     }
6835
6836   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6837   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6838   slot = htab_find_slot (per_objfile->per_bfd->type_unit_groups.get (),
6839                          &type_unit_group_for_lookup, INSERT);
6840   if (*slot == nullptr)
6841     {
6842       sect_offset line_offset_struct = (sect_offset) line_offset;
6843       std::unique_ptr<type_unit_group> grp
6844         = create_type_unit_group (cu, line_offset_struct);
6845       *slot = grp.release ();
6846       ++tu_stats->nr_symtabs;
6847     }
6848
6849   tu_group = (struct type_unit_group *) *slot;
6850   gdb_assert (tu_group != nullptr);
6851   return tu_group;
6852 }
6853 \f
6854 /* Partial symbol tables.  */
6855
6856 /* Create a psymtab named NAME and assign it to PER_CU.
6857
6858    The caller must fill in the following details:
6859    dirname, textlow, texthigh.  */
6860
6861 static dwarf2_psymtab *
6862 create_partial_symtab (dwarf2_per_cu_data *per_cu,
6863                        dwarf2_per_objfile *per_objfile,
6864                        const char *name)
6865 {
6866   dwarf2_psymtab *pst
6867     = new dwarf2_psymtab (name, per_objfile->per_bfd->partial_symtabs.get (),
6868                           per_objfile->objfile->per_bfd, per_cu);
6869
6870   pst->psymtabs_addrmap_supported = true;
6871
6872   /* This is the glue that links PST into GDB's symbol API.  */
6873   per_cu->v.psymtab = pst;
6874
6875   return pst;
6876 }
6877
6878 /* DIE reader function for process_psymtab_comp_unit.  */
6879
6880 static void
6881 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6882                                   const gdb_byte *info_ptr,
6883                                   struct die_info *comp_unit_die,
6884                                   enum language pretend_language)
6885 {
6886   struct dwarf2_cu *cu = reader->cu;
6887   dwarf2_per_objfile *per_objfile = cu->per_objfile;
6888   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
6889   struct objfile *objfile = per_objfile->objfile;
6890   struct gdbarch *gdbarch = objfile->arch ();
6891   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6892   CORE_ADDR baseaddr;
6893   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6894   dwarf2_psymtab *pst;
6895   enum pc_bounds_kind cu_bounds_kind;
6896
6897   gdb_assert (! per_cu->is_debug_types);
6898
6899   prepare_one_comp_unit (cu, comp_unit_die, pretend_language);
6900
6901   /* Allocate a new partial symbol table structure.  */
6902   gdb::unique_xmalloc_ptr<char> debug_filename;
6903   static const char artificial[] = "<artificial>";
6904   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
6905   if (strcmp (fnd.name, artificial) == 0)
6906     {
6907       debug_filename.reset (concat (artificial, "@",
6908                                     sect_offset_str (per_cu->sect_off),
6909                                     (char *) NULL));
6910       fnd.name = debug_filename.get ();
6911     }
6912
6913   pst = create_partial_symtab (per_cu, per_objfile, fnd.name);
6914
6915   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6916   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6917
6918   baseaddr = objfile->text_section_offset ();
6919
6920   dwarf2_find_base_address (comp_unit_die, cu);
6921
6922   /* Possibly set the default values of LOWPC and HIGHPC from
6923      `DW_AT_ranges'.  */
6924   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6925                                          &best_highpc, cu, pst);
6926   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6927     {
6928       CORE_ADDR low
6929         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
6930            - baseaddr);
6931       CORE_ADDR high
6932         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
6933            - baseaddr - 1);
6934       /* Store the contiguous range if it is not empty; it can be
6935          empty for CUs with no code.  */
6936       addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
6937                          low, high, pst);
6938     }
6939
6940   /* Check if comp unit has_children.
6941      If so, read the rest of the partial symbols from this comp unit.
6942      If not, there's no more debug_info for this comp unit.  */
6943   if (comp_unit_die->has_children)
6944     {
6945       struct partial_die_info *first_die;
6946       CORE_ADDR lowpc, highpc;
6947
6948       lowpc = ((CORE_ADDR) -1);
6949       highpc = ((CORE_ADDR) 0);
6950
6951       first_die = load_partial_dies (reader, info_ptr, 1);
6952
6953       scan_partial_symbols (first_die, &lowpc, &highpc,
6954                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6955
6956       /* If we didn't find a lowpc, set it to highpc to avoid
6957          complaints from `maint check'.  */
6958       if (lowpc == ((CORE_ADDR) -1))
6959         lowpc = highpc;
6960
6961       /* If the compilation unit didn't have an explicit address range,
6962          then use the information extracted from its child dies.  */
6963       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6964         {
6965           best_lowpc = lowpc;
6966           best_highpc = highpc;
6967         }
6968     }
6969   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
6970                                                  best_lowpc + baseaddr)
6971                      - baseaddr);
6972   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
6973                                                   best_highpc + baseaddr)
6974                       - baseaddr);
6975
6976   pst->end ();
6977
6978   if (!cu->per_cu->imported_symtabs_empty ())
6979     {
6980       int i;
6981       int len = cu->per_cu->imported_symtabs_size ();
6982
6983       /* Fill in 'dependencies' here; we fill in 'users' in a
6984          post-pass.  */
6985       pst->number_of_dependencies = len;
6986       pst->dependencies
6987         = per_bfd->partial_symtabs->allocate_dependencies (len);
6988       for (i = 0; i < len; ++i)
6989         {
6990           pst->dependencies[i]
6991             = cu->per_cu->imported_symtabs->at (i)->v.psymtab;
6992         }
6993
6994       cu->per_cu->imported_symtabs_free ();
6995     }
6996
6997   /* Get the list of files included in the current compilation unit,
6998      and build a psymtab for each of them.  */
6999   dwarf2_build_include_psymtabs (cu, comp_unit_die, fnd, pst);
7000
7001   dwarf_read_debug_printf ("Psymtab for %s unit @%s: %s - %s"
7002                            ", %d global, %d static syms",
7003                            per_cu->is_debug_types ? "type" : "comp",
7004                            sect_offset_str (per_cu->sect_off),
7005                            paddress (gdbarch, pst->text_low (objfile)),
7006                            paddress (gdbarch, pst->text_high (objfile)),
7007                            (int) pst->global_psymbols.size (),
7008                            (int) pst->static_psymbols.size ());
7009 }
7010
7011 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7012    Process compilation unit THIS_CU for a psymtab.  */
7013
7014 static void
7015 process_psymtab_comp_unit (dwarf2_per_cu_data *this_cu,
7016                            dwarf2_per_objfile *per_objfile,
7017                            bool want_partial_unit,
7018                            enum language pretend_language)
7019 {
7020   /* If this compilation unit was already read in, free the
7021      cached copy in order to read it in again.  This is
7022      necessary because we skipped some symbols when we first
7023      read in the compilation unit (see load_partial_dies).
7024      This problem could be avoided, but the benefit is unclear.  */
7025   per_objfile->remove_cu (this_cu);
7026
7027   cutu_reader reader (this_cu, per_objfile, nullptr, nullptr, false);
7028
7029   if (reader.comp_unit_die == nullptr)
7030     return;
7031
7032   switch (reader.comp_unit_die->tag)
7033     {
7034     case DW_TAG_compile_unit:
7035       this_cu->unit_type = DW_UT_compile;
7036       break;
7037     case DW_TAG_partial_unit:
7038       this_cu->unit_type = DW_UT_partial;
7039       break;
7040     case DW_TAG_type_unit:
7041       this_cu->unit_type = DW_UT_type;
7042       break;
7043     default:
7044       error (_("Dwarf Error: unexpected tag '%s' at offset %s [in module %s]"),
7045              dwarf_tag_name (reader.comp_unit_die->tag),
7046              sect_offset_str (reader.cu->per_cu->sect_off),
7047              objfile_name (per_objfile->objfile));
7048     }
7049
7050   if (reader.dummy_p)
7051     {
7052       /* Nothing.  */
7053     }
7054   else if (this_cu->is_debug_types)
7055     build_type_psymtabs_reader (&reader, reader.info_ptr,
7056                                 reader.comp_unit_die);
7057   else if (want_partial_unit
7058            || reader.comp_unit_die->tag != DW_TAG_partial_unit)
7059     process_psymtab_comp_unit_reader (&reader, reader.info_ptr,
7060                                       reader.comp_unit_die,
7061                                       pretend_language);
7062
7063   /* Age out any secondary CUs.  */
7064   per_objfile->age_comp_units ();
7065 }
7066
7067 /* Reader function for build_type_psymtabs.  */
7068
7069 static void
7070 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7071                             const gdb_byte *info_ptr,
7072                             struct die_info *type_unit_die)
7073 {
7074   dwarf2_per_objfile *per_objfile = reader->cu->per_objfile;
7075   struct dwarf2_cu *cu = reader->cu;
7076   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7077   struct signatured_type *sig_type;
7078   struct type_unit_group *tu_group;
7079   struct attribute *attr;
7080   struct partial_die_info *first_die;
7081   CORE_ADDR lowpc, highpc;
7082   dwarf2_psymtab *pst;
7083
7084   gdb_assert (per_cu->is_debug_types);
7085   sig_type = (struct signatured_type *) per_cu;
7086
7087   if (! type_unit_die->has_children)
7088     return;
7089
7090   attr = type_unit_die->attr (DW_AT_stmt_list);
7091   tu_group = get_type_unit_group (cu, attr);
7092
7093   if (tu_group->tus == nullptr)
7094     tu_group->tus = new std::vector<signatured_type *>;
7095   tu_group->tus->push_back (sig_type);
7096
7097   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7098   pst = create_partial_symtab (per_cu, per_objfile, "");
7099   pst->anonymous = true;
7100
7101   first_die = load_partial_dies (reader, info_ptr, 1);
7102
7103   lowpc = (CORE_ADDR) -1;
7104   highpc = (CORE_ADDR) 0;
7105   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7106
7107   pst->end ();
7108 }
7109
7110 /* Struct used to sort TUs by their abbreviation table offset.  */
7111
7112 struct tu_abbrev_offset
7113 {
7114   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
7115   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
7116   {}
7117
7118   /* This is used when sorting.  */
7119   bool operator< (const tu_abbrev_offset &other) const
7120   {
7121     return abbrev_offset < other.abbrev_offset;
7122   }
7123
7124   signatured_type *sig_type;
7125   sect_offset abbrev_offset;
7126 };
7127
7128 /* Efficiently read all the type units.
7129
7130    The efficiency is because we sort TUs by the abbrev table they use and
7131    only read each abbrev table once.  In one program there are 200K TUs
7132    sharing 8K abbrev tables.
7133
7134    The main purpose of this function is to support building the
7135    dwarf2_per_objfile->per_bfd->type_unit_groups table.
7136    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7137    can collapse the search space by grouping them by stmt_list.
7138    The savings can be significant, in the same program from above the 200K TUs
7139    share 8K stmt_list tables.
7140
7141    FUNC is expected to call get_type_unit_group, which will create the
7142    struct type_unit_group if necessary and add it to
7143    dwarf2_per_objfile->per_bfd->type_unit_groups.  */
7144
7145 static void
7146 build_type_psymtabs (dwarf2_per_objfile *per_objfile)
7147 {
7148   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
7149   abbrev_table_up abbrev_table;
7150   sect_offset abbrev_offset;
7151
7152   /* It's up to the caller to not call us multiple times.  */
7153   gdb_assert (per_objfile->per_bfd->type_unit_groups == NULL);
7154
7155   if (per_objfile->per_bfd->tu_stats.nr_tus == 0)
7156     return;
7157
7158   /* TUs typically share abbrev tables, and there can be way more TUs than
7159      abbrev tables.  Sort by abbrev table to reduce the number of times we
7160      read each abbrev table in.
7161      Alternatives are to punt or to maintain a cache of abbrev tables.
7162      This is simpler and efficient enough for now.
7163
7164      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7165      symtab to use).  Typically TUs with the same abbrev offset have the same
7166      stmt_list value too so in practice this should work well.
7167
7168      The basic algorithm here is:
7169
7170       sort TUs by abbrev table
7171       for each TU with same abbrev table:
7172         read abbrev table if first user
7173         read TU top level DIE
7174           [IWBN if DWO skeletons had DW_AT_stmt_list]
7175         call FUNC  */
7176
7177   dwarf_read_debug_printf ("Building type unit groups ...");
7178
7179   /* Sort in a separate table to maintain the order of all_comp_units
7180      for .gdb_index: TU indices directly index all_type_units.  */
7181   std::vector<tu_abbrev_offset> sorted_by_abbrev;
7182   sorted_by_abbrev.reserve (per_objfile->per_bfd->tu_stats.nr_tus);
7183
7184   for (const auto &cu : per_objfile->per_bfd->all_comp_units)
7185     {
7186       if (cu->is_debug_types)
7187         {
7188           auto sig_type = static_cast<signatured_type *> (cu.get ());
7189           sorted_by_abbrev.emplace_back
7190             (sig_type, read_abbrev_offset (per_objfile, sig_type->section,
7191                                            sig_type->sect_off));
7192         }
7193     }
7194
7195   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end ());
7196
7197   abbrev_offset = (sect_offset) ~(unsigned) 0;
7198
7199   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
7200     {
7201       /* Switch to the next abbrev table if necessary.  */
7202       if (abbrev_table == NULL
7203           || tu.abbrev_offset != abbrev_offset)
7204         {
7205           abbrev_offset = tu.abbrev_offset;
7206           per_objfile->per_bfd->abbrev.read (per_objfile->objfile);
7207           abbrev_table =
7208             abbrev_table::read (&per_objfile->per_bfd->abbrev, abbrev_offset);
7209           ++tu_stats->nr_uniq_abbrev_tables;
7210         }
7211
7212       cutu_reader reader (tu.sig_type, per_objfile,
7213                           abbrev_table.get (), nullptr, false);
7214       if (!reader.dummy_p)
7215         build_type_psymtabs_reader (&reader, reader.info_ptr,
7216                                     reader.comp_unit_die);
7217     }
7218 }
7219
7220 /* Print collected type unit statistics.  */
7221
7222 static void
7223 print_tu_stats (dwarf2_per_objfile *per_objfile)
7224 {
7225   struct tu_stats *tu_stats = &per_objfile->per_bfd->tu_stats;
7226
7227   dwarf_read_debug_printf ("Type unit statistics:");
7228   dwarf_read_debug_printf ("  %d TUs", tu_stats->nr_tus);
7229   dwarf_read_debug_printf ("  %d uniq abbrev tables",
7230                            tu_stats->nr_uniq_abbrev_tables);
7231   dwarf_read_debug_printf ("  %d symtabs from stmt_list entries",
7232                            tu_stats->nr_symtabs);
7233   dwarf_read_debug_printf ("  %d symtab sharers",
7234                            tu_stats->nr_symtab_sharers);
7235   dwarf_read_debug_printf ("  %d type units without a stmt_list",
7236                            tu_stats->nr_stmt_less_type_units);
7237   dwarf_read_debug_printf ("  %d all_type_units reallocs",
7238                            tu_stats->nr_all_type_units_reallocs);
7239 }
7240
7241 /* Traversal function for build_type_psymtabs.  */
7242
7243 static int
7244 build_type_psymtab_dependencies (void **slot, void *info)
7245 {
7246   dwarf2_per_objfile *per_objfile = (dwarf2_per_objfile *) info;
7247   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
7248   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
7249   dwarf2_psymtab *pst = tu_group->v.psymtab;
7250   int len = (tu_group->tus == nullptr) ? 0 : tu_group->tus->size ();
7251   int i;
7252
7253   gdb_assert (len > 0);
7254   gdb_assert (tu_group->type_unit_group_p ());
7255
7256   pst->number_of_dependencies = len;
7257   pst->dependencies = per_bfd->partial_symtabs->allocate_dependencies (len);
7258   for (i = 0; i < len; ++i)
7259     {
7260       struct signatured_type *iter = tu_group->tus->at (i);
7261       gdb_assert (iter->is_debug_types);
7262       pst->dependencies[i] = iter->v.psymtab;
7263       iter->type_unit_group = tu_group;
7264     }
7265
7266   delete tu_group->tus;
7267   tu_group->tus = nullptr;
7268
7269   return 1;
7270 }
7271
7272 /* Traversal function for process_skeletonless_type_unit.
7273    Read a TU in a DWO file and build partial symbols for it.  */
7274
7275 static int
7276 process_skeletonless_type_unit (void **slot, void *info)
7277 {
7278   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
7279   dwarf2_per_objfile *per_objfile = (dwarf2_per_objfile *) info;
7280
7281   /* If this TU doesn't exist in the global table, add it and read it in.  */
7282
7283   if (per_objfile->per_bfd->signatured_types == NULL)
7284     per_objfile->per_bfd->signatured_types = allocate_signatured_type_table ();
7285
7286   signatured_type find_entry (dwo_unit->signature);
7287   slot = htab_find_slot (per_objfile->per_bfd->signatured_types.get (),
7288                          &find_entry, INSERT);
7289   /* If we've already seen this type there's nothing to do.  What's happening
7290      is we're doing our own version of comdat-folding here.  */
7291   if (*slot != NULL)
7292     return 1;
7293
7294   /* This does the job that create_all_comp_units would have done for
7295      this TU.  */
7296   signatured_type *entry
7297     = add_type_unit (per_objfile, dwo_unit->signature, slot);
7298   fill_in_sig_entry_from_dwo_entry (per_objfile, entry, dwo_unit);
7299   *slot = entry;
7300
7301   /* This does the job that build_type_psymtabs would have done.  */
7302   cutu_reader reader (entry, per_objfile, nullptr, nullptr, false);
7303   if (!reader.dummy_p)
7304     build_type_psymtabs_reader (&reader, reader.info_ptr,
7305                                 reader.comp_unit_die);
7306
7307   return 1;
7308 }
7309
7310 /* Traversal function for process_skeletonless_type_units.  */
7311
7312 static int
7313 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
7314 {
7315   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7316
7317   if (dwo_file->tus != NULL)
7318     htab_traverse_noresize (dwo_file->tus.get (),
7319                             process_skeletonless_type_unit, info);
7320
7321   return 1;
7322 }
7323
7324 /* Scan all TUs of DWO files, verifying we've processed them.
7325    This is needed in case a TU was emitted without its skeleton.
7326    Note: This can't be done until we know what all the DWO files are.  */
7327
7328 static void
7329 process_skeletonless_type_units (dwarf2_per_objfile *per_objfile)
7330 {
7331   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
7332   if (get_dwp_file (per_objfile) == NULL
7333       && per_objfile->per_bfd->dwo_files != NULL)
7334     {
7335       htab_traverse_noresize (per_objfile->per_bfd->dwo_files.get (),
7336                               process_dwo_file_for_skeletonless_type_units,
7337                               per_objfile);
7338     }
7339 }
7340
7341 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
7342
7343 static void
7344 set_partial_user (dwarf2_per_objfile *per_objfile)
7345 {
7346   for (const auto &per_cu : per_objfile->per_bfd->all_comp_units)
7347     {
7348       dwarf2_psymtab *pst = per_cu->v.psymtab;
7349
7350       if (pst == NULL)
7351         continue;
7352
7353       for (int j = 0; j < pst->number_of_dependencies; ++j)
7354         {
7355           /* Set the 'user' field only if it is not already set.  */
7356           if (pst->dependencies[j]->user == NULL)
7357             pst->dependencies[j]->user = pst;
7358         }
7359     }
7360 }
7361
7362 /* Build the partial symbol table by doing a quick pass through the
7363    .debug_info and .debug_abbrev sections.  */
7364
7365 static void
7366 dwarf2_build_psymtabs_hard (dwarf2_per_objfile *per_objfile)
7367 {
7368   struct objfile *objfile = per_objfile->objfile;
7369   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
7370
7371   dwarf_read_debug_printf ("Building psymtabs of objfile %s ...",
7372                            objfile_name (objfile));
7373
7374   scoped_restore restore_reading_psyms
7375     = make_scoped_restore (&per_bfd->reading_partial_symbols, true);
7376
7377   per_bfd->info.read (objfile);
7378
7379   /* Any cached compilation units will be linked by the per-objfile
7380      read_in_chain.  Make sure to free them when we're done.  */
7381   free_cached_comp_units freer (per_objfile);
7382
7383   create_all_comp_units (per_objfile);
7384   build_type_psymtabs (per_objfile);
7385
7386   /* Create a temporary address map on a temporary obstack.  We later
7387      copy this to the final obstack.  */
7388   auto_obstack temp_obstack;
7389
7390   scoped_restore save_psymtabs_addrmap
7391     = make_scoped_restore (&per_bfd->partial_symtabs->psymtabs_addrmap,
7392                            addrmap_create_mutable (&temp_obstack));
7393
7394   for (const auto &per_cu : per_bfd->all_comp_units)
7395     {
7396       if (per_cu->v.psymtab != NULL)
7397         /* In case a forward DW_TAG_imported_unit has read the CU already.  */
7398         continue;
7399       process_psymtab_comp_unit (per_cu.get (), per_objfile, false,
7400                                  language_minimal);
7401     }
7402
7403   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7404   process_skeletonless_type_units (per_objfile);
7405
7406   /* Now that all TUs have been processed we can fill in the dependencies.  */
7407   if (per_bfd->type_unit_groups != NULL)
7408     {
7409       htab_traverse_noresize (per_bfd->type_unit_groups.get (),
7410                               build_type_psymtab_dependencies, per_objfile);
7411     }
7412
7413   if (dwarf_read_debug > 0)
7414     print_tu_stats (per_objfile);
7415
7416   set_partial_user (per_objfile);
7417
7418   per_bfd->partial_symtabs->psymtabs_addrmap
7419     = addrmap_create_fixed (per_bfd->partial_symtabs->psymtabs_addrmap,
7420                             per_bfd->partial_symtabs->obstack ());
7421   /* At this point we want to keep the address map.  */
7422   save_psymtabs_addrmap.release ();
7423
7424   dwarf_read_debug_printf ("Done building psymtabs of %s",
7425                            objfile_name (objfile));
7426 }
7427
7428 /* Load the partial DIEs for a secondary CU into memory.
7429    This is also used when rereading a primary CU with load_all_dies.  */
7430
7431 static void
7432 load_partial_comp_unit (dwarf2_per_cu_data *this_cu,
7433                         dwarf2_per_objfile *per_objfile,
7434                         dwarf2_cu *existing_cu)
7435 {
7436   cutu_reader reader (this_cu, per_objfile, nullptr, existing_cu, false);
7437
7438   if (!reader.dummy_p)
7439     {
7440       prepare_one_comp_unit (reader.cu, reader.comp_unit_die,
7441                              language_minimal);
7442
7443       /* Check if comp unit has_children.
7444          If so, read the rest of the partial symbols from this comp unit.
7445          If not, there's no more debug_info for this comp unit.  */
7446       if (reader.comp_unit_die->has_children)
7447         load_partial_dies (&reader, reader.info_ptr, 0);
7448
7449       reader.keep ();
7450     }
7451 }
7452
7453 static void
7454 read_comp_units_from_section (dwarf2_per_objfile *per_objfile,
7455                               struct dwarf2_section_info *section,
7456                               struct dwarf2_section_info *abbrev_section,
7457                               unsigned int is_dwz,
7458                               htab_up &types_htab,
7459                               rcuh_kind section_kind)
7460 {
7461   const gdb_byte *info_ptr;
7462   struct objfile *objfile = per_objfile->objfile;
7463
7464   dwarf_read_debug_printf ("Reading %s for %s",
7465                            section->get_name (),
7466                            section->get_file_name ());
7467
7468   section->read (objfile);
7469
7470   info_ptr = section->buffer;
7471
7472   while (info_ptr < section->buffer + section->size)
7473     {
7474       dwarf2_per_cu_data_up this_cu;
7475
7476       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7477
7478       comp_unit_head cu_header;
7479       read_and_check_comp_unit_head (per_objfile, &cu_header, section,
7480                                      abbrev_section, info_ptr,
7481                                      section_kind);
7482
7483       /* Save the compilation unit for later lookup.  */
7484       if (cu_header.unit_type != DW_UT_type)
7485         this_cu = per_objfile->per_bfd->allocate_per_cu ();
7486       else
7487         {
7488           if (types_htab == nullptr)
7489             types_htab = allocate_signatured_type_table ();
7490
7491           auto sig_type = per_objfile->per_bfd->allocate_signatured_type
7492             (cu_header.signature);
7493           signatured_type *sig_ptr = sig_type.get ();
7494           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7495           this_cu.reset (sig_type.release ());
7496
7497           void **slot = htab_find_slot (types_htab.get (), sig_ptr, INSERT);
7498           gdb_assert (slot != nullptr);
7499           if (*slot != nullptr)
7500             complaint (_("debug type entry at offset %s is duplicate to"
7501                          " the entry at offset %s, signature %s"),
7502                        sect_offset_str (sect_off),
7503                        sect_offset_str (sig_ptr->sect_off),
7504                        hex_string (sig_ptr->signature));
7505           *slot = sig_ptr;
7506         }
7507       this_cu->sect_off = sect_off;
7508       this_cu->length = cu_header.length + cu_header.initial_length_size;
7509       this_cu->is_dwz = is_dwz;
7510       this_cu->section = section;
7511
7512       info_ptr = info_ptr + this_cu->length;
7513       per_objfile->per_bfd->all_comp_units.push_back (std::move (this_cu));
7514     }
7515 }
7516
7517 /* Create a list of all compilation units in OBJFILE.
7518    This is only done for -readnow and building partial symtabs.  */
7519
7520 static void
7521 create_all_comp_units (dwarf2_per_objfile *per_objfile)
7522 {
7523   htab_up types_htab;
7524
7525   read_comp_units_from_section (per_objfile, &per_objfile->per_bfd->info,
7526                                 &per_objfile->per_bfd->abbrev, 0,
7527                                 types_htab, rcuh_kind::COMPILE);
7528   for (dwarf2_section_info &section : per_objfile->per_bfd->types)
7529     read_comp_units_from_section (per_objfile, &section,
7530                                   &per_objfile->per_bfd->abbrev, 0,
7531                                   types_htab, rcuh_kind::TYPE);
7532
7533   dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd);
7534   if (dwz != NULL)
7535     read_comp_units_from_section (per_objfile, &dwz->info, &dwz->abbrev, 1,
7536                                   types_htab, rcuh_kind::COMPILE);
7537
7538   per_objfile->per_bfd->signatured_types = std::move (types_htab);
7539 }
7540
7541 /* Process all loaded DIEs for compilation unit CU, starting at
7542    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7543    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7544    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7545    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7546
7547 static void
7548 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7549                       CORE_ADDR *highpc, int set_addrmap,
7550                       struct dwarf2_cu *cu)
7551 {
7552   struct partial_die_info *pdi;
7553
7554   /* Now, march along the PDI's, descending into ones which have
7555      interesting children but skipping the children of the other ones,
7556      until we reach the end of the compilation unit.  */
7557
7558   pdi = first_die;
7559
7560   while (pdi != NULL)
7561     {
7562       pdi->fixup (cu);
7563
7564       /* Anonymous namespaces or modules have no name but have interesting
7565          children, so we need to look at them.  Ditto for anonymous
7566          enums.  */
7567
7568       if (pdi->raw_name != NULL || pdi->tag == DW_TAG_namespace
7569           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7570           || pdi->tag == DW_TAG_imported_unit
7571           || pdi->tag == DW_TAG_inlined_subroutine)
7572         {
7573           switch (pdi->tag)
7574             {
7575             case DW_TAG_subprogram:
7576             case DW_TAG_inlined_subroutine:
7577               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7578               if (cu->per_cu->lang == language_cplus)
7579                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7580                                       set_addrmap, cu);
7581               break;
7582             case DW_TAG_constant:
7583             case DW_TAG_variable:
7584             case DW_TAG_typedef:
7585             case DW_TAG_union_type:
7586               if (!pdi->is_declaration
7587                   || (pdi->tag == DW_TAG_variable && pdi->is_external))
7588                 {
7589                   add_partial_symbol (pdi, cu);
7590                 }
7591               break;
7592             case DW_TAG_class_type:
7593             case DW_TAG_interface_type:
7594             case DW_TAG_structure_type:
7595               if (!pdi->is_declaration)
7596                 {
7597                   add_partial_symbol (pdi, cu);
7598                 }
7599               if ((cu->per_cu->lang == language_rust
7600                    || cu->per_cu->lang == language_cplus)
7601                   && pdi->has_children)
7602                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7603                                       set_addrmap, cu);
7604               break;
7605             case DW_TAG_enumeration_type:
7606               if (!pdi->is_declaration)
7607                 add_partial_enumeration (pdi, cu);
7608               break;
7609             case DW_TAG_base_type:
7610             case DW_TAG_subrange_type:
7611               /* File scope base type definitions are added to the partial
7612                  symbol table.  */
7613               add_partial_symbol (pdi, cu);
7614               break;
7615             case DW_TAG_namespace:
7616               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7617               break;
7618             case DW_TAG_module:
7619               if (!pdi->is_declaration)
7620                 add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7621               break;
7622             case DW_TAG_imported_unit:
7623               {
7624                 struct dwarf2_per_cu_data *per_cu;
7625
7626                 /* For now we don't handle imported units in type units.  */
7627                 if (cu->per_cu->is_debug_types)
7628                   {
7629                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
7630                              " supported in type units [in module %s]"),
7631                            objfile_name (cu->per_objfile->objfile));
7632                   }
7633
7634                 per_cu = dwarf2_find_containing_comp_unit
7635                            (pdi->d.sect_off, pdi->is_dwz, cu->per_objfile);
7636
7637                 /* Go read the partial unit, if needed.  */
7638                 if (per_cu->v.psymtab == NULL)
7639                   process_psymtab_comp_unit (per_cu, cu->per_objfile, true,
7640                                              cu->per_cu->lang);
7641
7642                 if (pdi->die_parent == nullptr
7643                     && per_cu->unit_type == DW_UT_compile
7644                     && per_cu->lang == language_cplus)
7645                   /* Regard import as hint.  See corresponding code in
7646                      process_imported_unit_die.  */
7647                   break;
7648
7649                 cu->per_cu->imported_symtabs_push (per_cu);
7650               }
7651               break;
7652             case DW_TAG_imported_declaration:
7653               add_partial_symbol (pdi, cu);
7654               break;
7655             default:
7656               break;
7657             }
7658         }
7659
7660       /* If the die has a sibling, skip to the sibling.  */
7661
7662       pdi = pdi->die_sibling;
7663     }
7664 }
7665
7666 /* Functions used to compute the fully scoped name of a partial DIE.
7667
7668    Normally, this is simple.  For C++, the parent DIE's fully scoped
7669    name is concatenated with "::" and the partial DIE's name.
7670    Enumerators are an exception; they use the scope of their parent
7671    enumeration type, i.e. the name of the enumeration type is not
7672    prepended to the enumerator.
7673
7674    There are two complexities.  One is DW_AT_specification; in this
7675    case "parent" means the parent of the target of the specification,
7676    instead of the direct parent of the DIE.  The other is compilers
7677    which do not emit DW_TAG_namespace; in this case we try to guess
7678    the fully qualified name of structure types from their members'
7679    linkage names.  This must be done using the DIE's children rather
7680    than the children of any DW_AT_specification target.  We only need
7681    to do this for structures at the top level, i.e. if the target of
7682    any DW_AT_specification (if any; otherwise the DIE itself) does not
7683    have a parent.  */
7684
7685 /* Compute the scope prefix associated with PDI's parent, in
7686    compilation unit CU.  The result will be allocated on CU's
7687    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7688    field.  NULL is returned if no prefix is necessary.  */
7689 static const char *
7690 partial_die_parent_scope (struct partial_die_info *pdi,
7691                           struct dwarf2_cu *cu)
7692 {
7693   const char *grandparent_scope;
7694   struct partial_die_info *parent, *real_pdi;
7695
7696   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7697      then this means the parent of the specification DIE.  */
7698
7699   real_pdi = pdi;
7700   while (real_pdi->has_specification)
7701     {
7702       auto res = find_partial_die (real_pdi->spec_offset,
7703                                    real_pdi->spec_is_dwz, cu);
7704       real_pdi = res.pdi;
7705       cu = res.cu;
7706     }
7707
7708   parent = real_pdi->die_parent;
7709   if (parent == NULL)
7710     return NULL;
7711
7712   if (parent->scope_set)
7713     return parent->scope;
7714
7715   parent->fixup (cu);
7716
7717   grandparent_scope = partial_die_parent_scope (parent, cu);
7718
7719   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7720      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7721      Work around this problem here.  */
7722   if (cu->per_cu->lang == language_cplus
7723       && parent->tag == DW_TAG_namespace
7724       && strcmp (parent->name (cu), "::") == 0
7725       && grandparent_scope == NULL)
7726     {
7727       parent->scope = NULL;
7728       parent->scope_set = 1;
7729       return NULL;
7730     }
7731
7732   /* Nested subroutines in Fortran get a prefix.  */
7733   if (pdi->tag == DW_TAG_enumerator)
7734     /* Enumerators should not get the name of the enumeration as a prefix.  */
7735     parent->scope = grandparent_scope;
7736   else if (parent->tag == DW_TAG_namespace
7737       || parent->tag == DW_TAG_module
7738       || parent->tag == DW_TAG_structure_type
7739       || parent->tag == DW_TAG_class_type
7740       || parent->tag == DW_TAG_interface_type
7741       || parent->tag == DW_TAG_union_type
7742       || parent->tag == DW_TAG_enumeration_type
7743       || (cu->per_cu->lang == language_fortran
7744           && parent->tag == DW_TAG_subprogram
7745           && pdi->tag == DW_TAG_subprogram))
7746     {
7747       if (grandparent_scope == NULL)
7748         parent->scope = parent->name (cu);
7749       else
7750         parent->scope = typename_concat (&cu->comp_unit_obstack,
7751                                          grandparent_scope,
7752                                          parent->name (cu), 0, cu);
7753     }
7754   else
7755     {
7756       /* FIXME drow/2004-04-01: What should we be doing with
7757          function-local names?  For partial symbols, we should probably be
7758          ignoring them.  */
7759       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
7760                  dwarf_tag_name (parent->tag),
7761                  sect_offset_str (pdi->sect_off));
7762       parent->scope = grandparent_scope;
7763     }
7764
7765   parent->scope_set = 1;
7766   return parent->scope;
7767 }
7768
7769 /* Return the fully scoped name associated with PDI, from compilation unit
7770    CU.  The result will be allocated with malloc.  */
7771
7772 static gdb::unique_xmalloc_ptr<char>
7773 partial_die_full_name (struct partial_die_info *pdi,
7774                        struct dwarf2_cu *cu)
7775 {
7776   const char *parent_scope;
7777
7778   /* If this is a template instantiation, we can not work out the
7779      template arguments from partial DIEs.  So, unfortunately, we have
7780      to go through the full DIEs.  At least any work we do building
7781      types here will be reused if full symbols are loaded later.  */
7782   if (pdi->has_template_arguments)
7783     {
7784       pdi->fixup (cu);
7785
7786       if (pdi->name (cu) != NULL && strchr (pdi->name (cu), '<') == NULL)
7787         {
7788           struct die_info *die;
7789           struct attribute attr;
7790           struct dwarf2_cu *ref_cu = cu;
7791
7792           /* DW_FORM_ref_addr is using section offset.  */
7793           attr.name = (enum dwarf_attribute) 0;
7794           attr.form = DW_FORM_ref_addr;
7795           attr.u.unsnd = to_underlying (pdi->sect_off);
7796           die = follow_die_ref (NULL, &attr, &ref_cu);
7797
7798           return make_unique_xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7799         }
7800     }
7801
7802   parent_scope = partial_die_parent_scope (pdi, cu);
7803   if (parent_scope == NULL)
7804     return NULL;
7805   else
7806     return gdb::unique_xmalloc_ptr<char> (typename_concat (NULL, parent_scope,
7807                                                            pdi->name (cu),
7808                                                            0, cu));
7809 }
7810
7811 static void
7812 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7813 {
7814   dwarf2_per_objfile *per_objfile = cu->per_objfile;
7815   struct objfile *objfile = per_objfile->objfile;
7816   struct gdbarch *gdbarch = objfile->arch ();
7817   CORE_ADDR addr = 0;
7818   const char *actual_name = NULL;
7819   CORE_ADDR baseaddr;
7820
7821   baseaddr = objfile->text_section_offset ();
7822
7823   gdb::unique_xmalloc_ptr<char> built_actual_name
7824     = partial_die_full_name (pdi, cu);
7825   if (built_actual_name != NULL)
7826     actual_name = built_actual_name.get ();
7827
7828   if (actual_name == NULL)
7829     actual_name = pdi->name (cu);
7830
7831   partial_symbol psymbol;
7832   memset (&psymbol, 0, sizeof (psymbol));
7833   psymbol.ginfo.set_language (cu->per_cu->lang,
7834                               &objfile->objfile_obstack);
7835   psymbol.ginfo.set_section_index (-1);
7836
7837   /* The code below indicates that the psymbol should be installed by
7838      setting this.  */
7839   gdb::optional<psymbol_placement> where;
7840
7841   switch (pdi->tag)
7842     {
7843     case DW_TAG_inlined_subroutine:
7844     case DW_TAG_subprogram:
7845       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
7846               - baseaddr);
7847       if (pdi->is_external
7848           || cu->per_cu->lang == language_ada
7849           || (cu->per_cu->lang == language_fortran
7850               && pdi->die_parent != NULL
7851               && pdi->die_parent->tag == DW_TAG_subprogram))
7852         {
7853           /* Normally, only "external" DIEs are part of the global scope.
7854              But in Ada and Fortran, we want to be able to access nested
7855              procedures globally.  So all Ada and Fortran subprograms are
7856              stored in the global scope.  */
7857           where = psymbol_placement::GLOBAL;
7858         }
7859       else
7860         where = psymbol_placement::STATIC;
7861
7862       psymbol.domain = VAR_DOMAIN;
7863       psymbol.aclass = LOC_BLOCK;
7864       psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
7865       psymbol.ginfo.value.address = addr;
7866
7867       if (pdi->main_subprogram && actual_name != NULL)
7868         set_objfile_main_name (objfile, actual_name, cu->per_cu->lang);
7869       break;
7870     case DW_TAG_constant:
7871       psymbol.domain = VAR_DOMAIN;
7872       psymbol.aclass = LOC_STATIC;
7873       where = (pdi->is_external
7874                ? psymbol_placement::GLOBAL
7875                : psymbol_placement::STATIC);
7876       break;
7877     case DW_TAG_variable:
7878       if (pdi->d.locdesc)
7879         addr = decode_locdesc (pdi->d.locdesc, cu);
7880
7881       if (pdi->d.locdesc
7882           && addr == 0
7883           && !per_objfile->per_bfd->has_section_at_zero)
7884         {
7885           /* A global or static variable may also have been stripped
7886              out by the linker if unused, in which case its address
7887              will be nullified; do not add such variables into partial
7888              symbol table then.  */
7889         }
7890       else if (pdi->is_external)
7891         {
7892           /* Global Variable.
7893              Don't enter into the minimal symbol tables as there is
7894              a minimal symbol table entry from the ELF symbols already.
7895              Enter into partial symbol table if it has a location
7896              descriptor or a type.
7897              If the location descriptor is missing, new_symbol will create
7898              a LOC_UNRESOLVED symbol, the address of the variable will then
7899              be determined from the minimal symbol table whenever the variable
7900              is referenced.
7901              The address for the partial symbol table entry is not
7902              used by GDB, but it comes in handy for debugging partial symbol
7903              table building.  */
7904
7905           if (pdi->d.locdesc || pdi->has_type)
7906             {
7907               psymbol.domain = VAR_DOMAIN;
7908               psymbol.aclass = LOC_STATIC;
7909               psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
7910               psymbol.ginfo.value.address = addr;
7911               where = psymbol_placement::GLOBAL;
7912             }
7913         }
7914       else
7915         {
7916           int has_loc = pdi->d.locdesc != NULL;
7917
7918           /* Static Variable.  Skip symbols whose value we cannot know (those
7919              without location descriptors or constant values).  */
7920           if (!has_loc && !pdi->has_const_value)
7921             return;
7922
7923           psymbol.domain = VAR_DOMAIN;
7924           psymbol.aclass = LOC_STATIC;
7925           psymbol.ginfo.set_section_index (SECT_OFF_TEXT (objfile));
7926           if (has_loc)
7927             psymbol.ginfo.value.address = addr;
7928           where = psymbol_placement::STATIC;
7929         }
7930       break;
7931     case DW_TAG_array_type:
7932     case DW_TAG_typedef:
7933     case DW_TAG_base_type:
7934     case DW_TAG_subrange_type:
7935       psymbol.domain = VAR_DOMAIN;
7936       psymbol.aclass = LOC_TYPEDEF;
7937       where = psymbol_placement::STATIC;
7938       break;
7939     case DW_TAG_imported_declaration:
7940     case DW_TAG_namespace:
7941       psymbol.domain = VAR_DOMAIN;
7942       psymbol.aclass = LOC_TYPEDEF;
7943       where = psymbol_placement::GLOBAL;
7944       break;
7945     case DW_TAG_module:
7946       /* With Fortran 77 there might be a "BLOCK DATA" module
7947          available without any name.  If so, we skip the module as it
7948          doesn't bring any value.  */
7949       if (actual_name != nullptr)
7950         {
7951           psymbol.domain = MODULE_DOMAIN;
7952           psymbol.aclass = LOC_TYPEDEF;
7953           where = psymbol_placement::GLOBAL;
7954         }
7955       break;
7956     case DW_TAG_class_type:
7957     case DW_TAG_interface_type:
7958     case DW_TAG_structure_type:
7959     case DW_TAG_union_type:
7960     case DW_TAG_enumeration_type:
7961       /* Skip external references.  The DWARF standard says in the section
7962          about "Structure, Union, and Class Type Entries": "An incomplete
7963          structure, union or class type is represented by a structure,
7964          union or class entry that does not have a byte size attribute
7965          and that has a DW_AT_declaration attribute."  */
7966       if (!pdi->has_byte_size && pdi->is_declaration)
7967         return;
7968
7969       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7970          static vs. global.  */
7971       psymbol.domain = STRUCT_DOMAIN;
7972       psymbol.aclass = LOC_TYPEDEF;
7973       where = (cu->per_cu->lang == language_cplus
7974                ? psymbol_placement::GLOBAL
7975                : psymbol_placement::STATIC);
7976       break;
7977     case DW_TAG_enumerator:
7978       psymbol.domain = VAR_DOMAIN;
7979       psymbol.aclass = LOC_CONST;
7980       where = (cu->per_cu->lang == language_cplus
7981                ? psymbol_placement::GLOBAL
7982                : psymbol_placement::STATIC);
7983       break;
7984     default:
7985       break;
7986     }
7987
7988   if (where.has_value ())
7989     {
7990       if (built_actual_name != nullptr)
7991         actual_name = objfile->intern (actual_name);
7992       if (pdi->linkage_name == nullptr
7993           || cu->per_cu->lang == language_ada)
7994         psymbol.ginfo.set_linkage_name (actual_name);
7995       else
7996         {
7997           psymbol.ginfo.set_demangled_name (actual_name,
7998                                             &objfile->objfile_obstack);
7999           psymbol.ginfo.set_linkage_name (pdi->linkage_name);
8000         }
8001       cu->per_cu->v.psymtab->add_psymbol
8002         (psymbol, *where, per_objfile->per_bfd->partial_symtabs.get (),
8003          objfile);
8004     }
8005 }
8006
8007 /* Read a partial die corresponding to a namespace; also, add a symbol
8008    corresponding to that namespace to the symbol table.  NAMESPACE is
8009    the name of the enclosing namespace.  */
8010
8011 static void
8012 add_partial_namespace (struct partial_die_info *pdi,
8013                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8014                        int set_addrmap, struct dwarf2_cu *cu)
8015 {
8016   /* Add a symbol for the namespace.  */
8017
8018   add_partial_symbol (pdi, cu);
8019
8020   /* Now scan partial symbols in that namespace.  */
8021
8022   if (pdi->has_children)
8023     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8024 }
8025
8026 /* Read a partial die corresponding to a Fortran module.  */
8027
8028 static void
8029 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8030                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8031 {
8032   /* Add a symbol for the namespace.  */
8033
8034   add_partial_symbol (pdi, cu);
8035
8036   /* Now scan partial symbols in that module.  */
8037
8038   if (pdi->has_children)
8039     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8040 }
8041
8042 /* Read a partial die corresponding to a subprogram or an inlined
8043    subprogram and create a partial symbol for that subprogram.
8044    When the CU language allows it, this routine also defines a partial
8045    symbol for each nested subprogram that this subprogram contains.
8046    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
8047    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
8048
8049    PDI may also be a lexical block, in which case we simply search
8050    recursively for subprograms defined inside that lexical block.
8051    Again, this is only performed when the CU language allows this
8052    type of definitions.  */
8053
8054 static void
8055 add_partial_subprogram (struct partial_die_info *pdi,
8056                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
8057                         int set_addrmap, struct dwarf2_cu *cu)
8058 {
8059   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
8060     {
8061       if (pdi->has_pc_info)
8062         {
8063           if (pdi->lowpc < *lowpc)
8064             *lowpc = pdi->lowpc;
8065           if (pdi->highpc > *highpc)
8066             *highpc = pdi->highpc;
8067           if (set_addrmap)
8068             {
8069               struct objfile *objfile = cu->per_objfile->objfile;
8070               dwarf2_per_bfd *per_bfd = cu->per_objfile->per_bfd;
8071               struct gdbarch *gdbarch = objfile->arch ();
8072               CORE_ADDR baseaddr;
8073               CORE_ADDR this_highpc;
8074               CORE_ADDR this_lowpc;
8075
8076               baseaddr = objfile->text_section_offset ();
8077               this_lowpc
8078                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8079                                                pdi->lowpc + baseaddr)
8080                    - baseaddr);
8081               this_highpc
8082                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
8083                                                pdi->highpc + baseaddr)
8084                    - baseaddr);
8085               addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
8086                                  this_lowpc, this_highpc - 1,
8087                                  cu->per_cu->v.psymtab);
8088             }
8089         }
8090
8091       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8092         {
8093           if (!pdi->is_declaration)
8094             /* Ignore subprogram DIEs that do not have a name, they are
8095                illegal.  Do not emit a complaint at this point, we will
8096                do so when we convert this psymtab into a symtab.  */
8097             if (pdi->name (cu))
8098               add_partial_symbol (pdi, cu);
8099         }
8100     }
8101
8102   if (! pdi->has_children)
8103     return;
8104
8105   if (cu->per_cu->lang == language_ada
8106       || cu->per_cu->lang == language_fortran)
8107     {
8108       pdi = pdi->die_child;
8109       while (pdi != NULL)
8110         {
8111           pdi->fixup (cu);
8112           if (pdi->tag == DW_TAG_subprogram
8113               || pdi->tag == DW_TAG_inlined_subroutine
8114               || pdi->tag == DW_TAG_lexical_block)
8115             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8116           pdi = pdi->die_sibling;
8117         }
8118     }
8119 }
8120
8121 /* Read a partial die corresponding to an enumeration type.  */
8122
8123 static void
8124 add_partial_enumeration (struct partial_die_info *enum_pdi,
8125                          struct dwarf2_cu *cu)
8126 {
8127   struct partial_die_info *pdi;
8128
8129   if (enum_pdi->name (cu) != NULL)
8130     add_partial_symbol (enum_pdi, cu);
8131
8132   pdi = enum_pdi->die_child;
8133   while (pdi)
8134     {
8135       if (pdi->tag != DW_TAG_enumerator || pdi->raw_name == NULL)
8136         complaint (_("malformed enumerator DIE ignored"));
8137       else
8138         add_partial_symbol (pdi, cu);
8139       pdi = pdi->die_sibling;
8140     }
8141 }
8142
8143 /* Return the initial uleb128 in the die at INFO_PTR.  */
8144
8145 static unsigned int
8146 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8147 {
8148   unsigned int bytes_read;
8149
8150   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8151 }
8152
8153 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
8154    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
8155
8156    Return the corresponding abbrev, or NULL if the number is zero (indicating
8157    an empty DIE).  In either case *BYTES_READ will be set to the length of
8158    the initial number.  */
8159
8160 static const struct abbrev_info *
8161 peek_die_abbrev (const die_reader_specs &reader,
8162                  const gdb_byte *info_ptr, unsigned int *bytes_read)
8163 {
8164   dwarf2_cu *cu = reader.cu;
8165   bfd *abfd = reader.abfd;
8166   unsigned int abbrev_number
8167     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8168
8169   if (abbrev_number == 0)
8170     return NULL;
8171
8172   const abbrev_info *abbrev
8173     = reader.abbrev_table->lookup_abbrev (abbrev_number);
8174   if (!abbrev)
8175     {
8176       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8177                " at offset %s [in module %s]"),
8178              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8179              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
8180     }
8181
8182   return abbrev;
8183 }
8184
8185 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8186    Returns a pointer to the end of a series of DIEs, terminated by an empty
8187    DIE.  Any children of the skipped DIEs will also be skipped.  */
8188
8189 static const gdb_byte *
8190 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8191 {
8192   while (1)
8193     {
8194       unsigned int bytes_read;
8195       const abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr,
8196                                                    &bytes_read);
8197
8198       if (abbrev == NULL)
8199         return info_ptr + bytes_read;
8200       else
8201         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8202     }
8203 }
8204
8205 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8206    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8207    abbrev corresponding to that skipped uleb128 should be passed in
8208    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8209    children.  */
8210
8211 static const gdb_byte *
8212 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8213               const struct abbrev_info *abbrev)
8214 {
8215   unsigned int bytes_read;
8216   struct attribute attr;
8217   bfd *abfd = reader->abfd;
8218   struct dwarf2_cu *cu = reader->cu;
8219   const gdb_byte *buffer = reader->buffer;
8220   const gdb_byte *buffer_end = reader->buffer_end;
8221   unsigned int form, i;
8222
8223   for (i = 0; i < abbrev->num_attrs; i++)
8224     {
8225       /* The only abbrev we care about is DW_AT_sibling.  */
8226       if (abbrev->attrs[i].name == DW_AT_sibling)
8227         {
8228           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
8229           if (attr.form == DW_FORM_ref_addr)
8230             complaint (_("ignoring absolute DW_AT_sibling"));
8231           else
8232             {
8233               sect_offset off = attr.get_ref_die_offset ();
8234               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8235
8236               if (sibling_ptr < info_ptr)
8237                 complaint (_("DW_AT_sibling points backwards"));
8238               else if (sibling_ptr > reader->buffer_end)
8239                 reader->die_section->overflow_complaint ();
8240               else
8241                 return sibling_ptr;
8242             }
8243         }
8244
8245       /* If it isn't DW_AT_sibling, skip this attribute.  */
8246       form = abbrev->attrs[i].form;
8247     skip_attribute:
8248       switch (form)
8249         {
8250         case DW_FORM_ref_addr:
8251           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8252              and later it is offset sized.  */
8253           if (cu->header.version == 2)
8254             info_ptr += cu->header.addr_size;
8255           else
8256             info_ptr += cu->header.offset_size;
8257           break;
8258         case DW_FORM_GNU_ref_alt:
8259           info_ptr += cu->header.offset_size;
8260           break;
8261         case DW_FORM_addr:
8262           info_ptr += cu->header.addr_size;
8263           break;
8264         case DW_FORM_data1:
8265         case DW_FORM_ref1:
8266         case DW_FORM_flag:
8267         case DW_FORM_strx1:
8268           info_ptr += 1;
8269           break;
8270         case DW_FORM_flag_present:
8271         case DW_FORM_implicit_const:
8272           break;
8273         case DW_FORM_data2:
8274         case DW_FORM_ref2:
8275         case DW_FORM_strx2:
8276           info_ptr += 2;
8277           break;
8278         case DW_FORM_strx3:
8279           info_ptr += 3;
8280           break;
8281         case DW_FORM_data4:
8282         case DW_FORM_ref4:
8283         case DW_FORM_strx4:
8284           info_ptr += 4;
8285           break;
8286         case DW_FORM_data8:
8287         case DW_FORM_ref8:
8288         case DW_FORM_ref_sig8:
8289           info_ptr += 8;
8290           break;
8291         case DW_FORM_data16:
8292           info_ptr += 16;
8293           break;
8294         case DW_FORM_string:
8295           read_direct_string (abfd, info_ptr, &bytes_read);
8296           info_ptr += bytes_read;
8297           break;
8298         case DW_FORM_sec_offset:
8299         case DW_FORM_strp:
8300         case DW_FORM_GNU_strp_alt:
8301           info_ptr += cu->header.offset_size;
8302           break;
8303         case DW_FORM_exprloc:
8304         case DW_FORM_block:
8305           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8306           info_ptr += bytes_read;
8307           break;
8308         case DW_FORM_block1:
8309           info_ptr += 1 + read_1_byte (abfd, info_ptr);
8310           break;
8311         case DW_FORM_block2:
8312           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
8313           break;
8314         case DW_FORM_block4:
8315           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
8316           break;
8317         case DW_FORM_addrx:
8318         case DW_FORM_strx:
8319         case DW_FORM_sdata:
8320         case DW_FORM_udata:
8321         case DW_FORM_ref_udata:
8322         case DW_FORM_GNU_addr_index:
8323         case DW_FORM_GNU_str_index:
8324         case DW_FORM_rnglistx:
8325         case DW_FORM_loclistx:
8326           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
8327           break;
8328         case DW_FORM_indirect:
8329           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8330           info_ptr += bytes_read;
8331           /* We need to continue parsing from here, so just go back to
8332              the top.  */
8333           goto skip_attribute;
8334
8335         default:
8336           error (_("Dwarf Error: Cannot handle %s "
8337                    "in DWARF reader [in module %s]"),
8338                  dwarf_form_name (form),
8339                  bfd_get_filename (abfd));
8340         }
8341     }
8342
8343   if (abbrev->has_children)
8344     return skip_children (reader, info_ptr);
8345   else
8346     return info_ptr;
8347 }
8348
8349 /* Locate ORIG_PDI's sibling.
8350    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
8351
8352 static const gdb_byte *
8353 locate_pdi_sibling (const struct die_reader_specs *reader,
8354                     struct partial_die_info *orig_pdi,
8355                     const gdb_byte *info_ptr)
8356 {
8357   /* Do we know the sibling already?  */
8358
8359   if (orig_pdi->sibling)
8360     return orig_pdi->sibling;
8361
8362   /* Are there any children to deal with?  */
8363
8364   if (!orig_pdi->has_children)
8365     return info_ptr;
8366
8367   /* Skip the children the long way.  */
8368
8369   return skip_children (reader, info_ptr);
8370 }
8371
8372 /* Expand this partial symbol table into a full symbol table.  SELF is
8373    not NULL.  */
8374
8375 void
8376 dwarf2_psymtab::read_symtab (struct objfile *objfile)
8377 {
8378   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
8379
8380   gdb_assert (!per_objfile->symtab_set_p (per_cu_data));
8381
8382   /* If this psymtab is constructed from a debug-only objfile, the
8383      has_section_at_zero flag will not necessarily be correct.  We
8384      can get the correct value for this flag by looking at the data
8385      associated with the (presumably stripped) associated objfile.  */
8386   if (objfile->separate_debug_objfile_backlink)
8387     {
8388       dwarf2_per_objfile *per_objfile_backlink
8389         = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
8390
8391       per_objfile->per_bfd->has_section_at_zero
8392         = per_objfile_backlink->per_bfd->has_section_at_zero;
8393     }
8394
8395   expand_psymtab (objfile);
8396
8397   process_cu_includes (per_objfile);
8398 }
8399 \f
8400 /* Reading in full CUs.  */
8401
8402 /* Add PER_CU to the queue.  */
8403
8404 static void
8405 queue_comp_unit (dwarf2_per_cu_data *per_cu,
8406                  dwarf2_per_objfile *per_objfile,
8407                  enum language pretend_language)
8408 {
8409   per_cu->queued = 1;
8410
8411   gdb_assert (per_objfile->per_bfd->queue.has_value ());
8412   per_cu->per_bfd->queue->emplace (per_cu, per_objfile, pretend_language);
8413 }
8414
8415 /* If PER_CU is not yet expanded of queued for expansion, add it to the queue.
8416
8417    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8418    dependency.
8419
8420    Return true if maybe_queue_comp_unit requires the caller to load the CU's
8421    DIEs, false otherwise.
8422
8423    Explanation: there is an invariant that if a CU is queued for expansion
8424    (present in `dwarf2_per_bfd::queue`), then its DIEs are loaded
8425    (a dwarf2_cu object exists for this CU, and `dwarf2_per_objfile::get_cu`
8426    returns non-nullptr).  If the CU gets enqueued by this function but its DIEs
8427    are not yet loaded, the the caller must load the CU's DIEs to ensure the
8428    invariant is respected.
8429
8430    The caller is therefore not required to load the CU's DIEs (we return false)
8431    if:
8432
8433      - the CU is already expanded, and therefore does not get enqueued
8434      - the CU gets enqueued for expansion, but its DIEs are already loaded
8435
8436    Note that the caller should not use this function's return value as an
8437    indicator of whether the CU's DIEs are loaded right now, it should check
8438    that by calling `dwarf2_per_objfile::get_cu` instead.  */
8439
8440 static int
8441 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8442                        dwarf2_per_cu_data *per_cu,
8443                        dwarf2_per_objfile *per_objfile,
8444                        enum language pretend_language)
8445 {
8446   /* We may arrive here during partial symbol reading, if we need full
8447      DIEs to process an unusual case (e.g. template arguments).  Do
8448      not queue PER_CU, just tell our caller to load its DIEs.  */
8449   if (per_cu->per_bfd->reading_partial_symbols)
8450     {
8451       dwarf2_cu *cu = per_objfile->get_cu (per_cu);
8452
8453       if (cu == NULL || cu->dies == NULL)
8454         return 1;
8455       return 0;
8456     }
8457
8458   /* Mark the dependence relation so that we don't flush PER_CU
8459      too early.  */
8460   if (dependent_cu != NULL)
8461     dependent_cu->add_dependence (per_cu);
8462
8463   /* If it's already on the queue, we have nothing to do.  */
8464   if (per_cu->queued)
8465     {
8466       /* Verify the invariant that if a CU is queued for expansion, its DIEs are
8467          loaded.  */
8468       gdb_assert (per_objfile->get_cu (per_cu) != nullptr);
8469
8470       /* If the CU is queued for expansion, it should not already be
8471          expanded.  */
8472       gdb_assert (!per_objfile->symtab_set_p (per_cu));
8473
8474       /* The DIEs are already loaded, the caller doesn't need to do it.  */
8475       return 0;
8476     }
8477
8478   bool queued = false;
8479   if (!per_objfile->symtab_set_p (per_cu))
8480     {
8481       /* Add it to the queue.  */
8482       queue_comp_unit (per_cu, per_objfile,  pretend_language);
8483       queued = true;
8484     }
8485
8486   /* If the compilation unit is already loaded, just mark it as
8487      used.  */
8488   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
8489   if (cu != nullptr)
8490     cu->last_used = 0;
8491
8492   /* Ask the caller to load the CU's DIEs if the CU got enqueued for expansion
8493      and the DIEs are not already loaded.  */
8494   return queued && cu == nullptr;
8495 }
8496
8497 /* Process the queue.  */
8498
8499 static void
8500 process_queue (dwarf2_per_objfile *per_objfile)
8501 {
8502   dwarf_read_debug_printf ("Expanding one or more symtabs of objfile %s ...",
8503                            objfile_name (per_objfile->objfile));
8504
8505   /* The queue starts out with one item, but following a DIE reference
8506      may load a new CU, adding it to the end of the queue.  */
8507   while (!per_objfile->per_bfd->queue->empty ())
8508     {
8509       dwarf2_queue_item &item = per_objfile->per_bfd->queue->front ();
8510       dwarf2_per_cu_data *per_cu = item.per_cu;
8511
8512       if (!per_objfile->symtab_set_p (per_cu))
8513         {
8514           dwarf2_cu *cu = per_objfile->get_cu (per_cu);
8515
8516           /* Skip dummy CUs.  */
8517           if (cu != nullptr)
8518             {
8519               unsigned int debug_print_threshold;
8520               char buf[100];
8521
8522               if (per_cu->is_debug_types)
8523                 {
8524                   struct signatured_type *sig_type =
8525                     (struct signatured_type *) per_cu;
8526
8527                   sprintf (buf, "TU %s at offset %s",
8528                            hex_string (sig_type->signature),
8529                            sect_offset_str (per_cu->sect_off));
8530                   /* There can be 100s of TUs.
8531                      Only print them in verbose mode.  */
8532                   debug_print_threshold = 2;
8533                 }
8534               else
8535                 {
8536                   sprintf (buf, "CU at offset %s",
8537                            sect_offset_str (per_cu->sect_off));
8538                   debug_print_threshold = 1;
8539                 }
8540
8541               if (dwarf_read_debug >= debug_print_threshold)
8542                 dwarf_read_debug_printf ("Expanding symtab of %s", buf);
8543
8544               if (per_cu->is_debug_types)
8545                 process_full_type_unit (cu, item.pretend_language);
8546               else
8547                 process_full_comp_unit (cu, item.pretend_language);
8548
8549               if (dwarf_read_debug >= debug_print_threshold)
8550                 dwarf_read_debug_printf ("Done expanding %s", buf);
8551             }
8552         }
8553
8554       per_cu->queued = 0;
8555       per_objfile->per_bfd->queue->pop ();
8556     }
8557
8558   dwarf_read_debug_printf ("Done expanding symtabs of %s.",
8559                            objfile_name (per_objfile->objfile));
8560 }
8561
8562 /* Read in full symbols for PST, and anything it depends on.  */
8563
8564 void
8565 dwarf2_psymtab::expand_psymtab (struct objfile *objfile)
8566 {
8567   gdb_assert (!readin_p (objfile));
8568
8569   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
8570   free_cached_comp_units freer (per_objfile);
8571   expand_dependencies (objfile);
8572
8573   dw2_do_instantiate_symtab (per_cu_data, per_objfile, false);
8574   gdb_assert (get_compunit_symtab (objfile) != nullptr);
8575 }
8576
8577 /* See psympriv.h.  */
8578
8579 bool
8580 dwarf2_psymtab::readin_p (struct objfile *objfile) const
8581 {
8582   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
8583   return per_objfile->symtab_set_p (per_cu_data);
8584 }
8585
8586 /* See psympriv.h.  */
8587
8588 compunit_symtab *
8589 dwarf2_psymtab::get_compunit_symtab (struct objfile *objfile) const
8590 {
8591   dwarf2_per_objfile *per_objfile = get_dwarf2_per_objfile (objfile);
8592   return per_objfile->get_symtab (per_cu_data);
8593 }
8594
8595 /* Trivial hash function for die_info: the hash value of a DIE
8596    is its offset in .debug_info for this objfile.  */
8597
8598 static hashval_t
8599 die_hash (const void *item)
8600 {
8601   const struct die_info *die = (const struct die_info *) item;
8602
8603   return to_underlying (die->sect_off);
8604 }
8605
8606 /* Trivial comparison function for die_info structures: two DIEs
8607    are equal if they have the same offset.  */
8608
8609 static int
8610 die_eq (const void *item_lhs, const void *item_rhs)
8611 {
8612   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8613   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8614
8615   return die_lhs->sect_off == die_rhs->sect_off;
8616 }
8617
8618 /* Load the DIEs associated with PER_CU into memory.
8619
8620    In some cases, the caller, while reading partial symbols, will need to load
8621    the full symbols for the CU for some reason.  It will already have a
8622    dwarf2_cu object for THIS_CU and pass it as EXISTING_CU, so it can be re-used
8623    rather than creating a new one.  */
8624
8625 static void
8626 load_full_comp_unit (dwarf2_per_cu_data *this_cu,
8627                      dwarf2_per_objfile *per_objfile,
8628                      dwarf2_cu *existing_cu,
8629                      bool skip_partial,
8630                      enum language pretend_language)
8631 {
8632   gdb_assert (! this_cu->is_debug_types);
8633
8634   cutu_reader reader (this_cu, per_objfile, NULL, existing_cu, skip_partial);
8635   if (reader.dummy_p)
8636     return;
8637
8638   struct dwarf2_cu *cu = reader.cu;
8639   const gdb_byte *info_ptr = reader.info_ptr;
8640
8641   gdb_assert (cu->die_hash == NULL);
8642   cu->die_hash =
8643     htab_create_alloc_ex (cu->header.length / 12,
8644                           die_hash,
8645                           die_eq,
8646                           NULL,
8647                           &cu->comp_unit_obstack,
8648                           hashtab_obstack_allocate,
8649                           dummy_obstack_deallocate);
8650
8651   if (reader.comp_unit_die->has_children)
8652     reader.comp_unit_die->child
8653       = read_die_and_siblings (&reader, reader.info_ptr,
8654                                &info_ptr, reader.comp_unit_die);
8655   cu->dies = reader.comp_unit_die;
8656   /* comp_unit_die is not stored in die_hash, no need.  */
8657
8658   /* We try not to read any attributes in this function, because not
8659      all CUs needed for references have been loaded yet, and symbol
8660      table processing isn't initialized.  But we have to set the CU language,
8661      or we won't be able to build types correctly.
8662      Similarly, if we do not read the producer, we can not apply
8663      producer-specific interpretation.  */
8664   prepare_one_comp_unit (cu, cu->dies, pretend_language);
8665
8666   reader.keep ();
8667 }
8668
8669 /* Add a DIE to the delayed physname list.  */
8670
8671 static void
8672 add_to_method_list (struct type *type, int fnfield_index, int index,
8673                     const char *name, struct die_info *die,
8674                     struct dwarf2_cu *cu)
8675 {
8676   struct delayed_method_info mi;
8677   mi.type = type;
8678   mi.fnfield_index = fnfield_index;
8679   mi.index = index;
8680   mi.name = name;
8681   mi.die = die;
8682   cu->method_list.push_back (mi);
8683 }
8684
8685 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8686    "const" / "volatile".  If so, decrements LEN by the length of the
8687    modifier and return true.  Otherwise return false.  */
8688
8689 template<size_t N>
8690 static bool
8691 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8692 {
8693   size_t mod_len = sizeof (mod) - 1;
8694   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8695     {
8696       len -= mod_len;
8697       return true;
8698     }
8699   return false;
8700 }
8701
8702 /* Compute the physnames of any methods on the CU's method list.
8703
8704    The computation of method physnames is delayed in order to avoid the
8705    (bad) condition that one of the method's formal parameters is of an as yet
8706    incomplete type.  */
8707
8708 static void
8709 compute_delayed_physnames (struct dwarf2_cu *cu)
8710 {
8711   /* Only C++ delays computing physnames.  */
8712   if (cu->method_list.empty ())
8713     return;
8714   gdb_assert (cu->per_cu->lang == language_cplus);
8715
8716   for (const delayed_method_info &mi : cu->method_list)
8717     {
8718       const char *physname;
8719       struct fn_fieldlist *fn_flp
8720         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
8721       physname = dwarf2_physname (mi.name, mi.die, cu);
8722       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
8723         = physname ? physname : "";
8724
8725       /* Since there's no tag to indicate whether a method is a
8726          const/volatile overload, extract that information out of the
8727          demangled name.  */
8728       if (physname != NULL)
8729         {
8730           size_t len = strlen (physname);
8731
8732           while (1)
8733             {
8734               if (physname[len] == ')') /* shortcut */
8735                 break;
8736               else if (check_modifier (physname, len, " const"))
8737                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
8738               else if (check_modifier (physname, len, " volatile"))
8739                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
8740               else
8741                 break;
8742             }
8743         }
8744     }
8745
8746   /* The list is no longer needed.  */
8747   cu->method_list.clear ();
8748 }
8749
8750 /* Go objects should be embedded in a DW_TAG_module DIE,
8751    and it's not clear if/how imported objects will appear.
8752    To keep Go support simple until that's worked out,
8753    go back through what we've read and create something usable.
8754    We could do this while processing each DIE, and feels kinda cleaner,
8755    but that way is more invasive.
8756    This is to, for example, allow the user to type "p var" or "b main"
8757    without having to specify the package name, and allow lookups
8758    of module.object to work in contexts that use the expression
8759    parser.  */
8760
8761 static void
8762 fixup_go_packaging (struct dwarf2_cu *cu)
8763 {
8764   gdb::unique_xmalloc_ptr<char> package_name;
8765   struct pending *list;
8766   int i;
8767
8768   for (list = *cu->get_builder ()->get_global_symbols ();
8769        list != NULL;
8770        list = list->next)
8771     {
8772       for (i = 0; i < list->nsyms; ++i)
8773         {
8774           struct symbol *sym = list->symbol[i];
8775
8776           if (sym->language () == language_go
8777               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8778             {
8779               gdb::unique_xmalloc_ptr<char> this_package_name
8780                 (go_symbol_package_name (sym));
8781
8782               if (this_package_name == NULL)
8783                 continue;
8784               if (package_name == NULL)
8785                 package_name = std::move (this_package_name);
8786               else
8787                 {
8788                   struct objfile *objfile = cu->per_objfile->objfile;
8789                   if (strcmp (package_name.get (), this_package_name.get ()) != 0)
8790                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
8791                                (symbol_symtab (sym) != NULL
8792                                 ? symtab_to_filename_for_display
8793                                     (symbol_symtab (sym))
8794                                 : objfile_name (objfile)),
8795                                this_package_name.get (), package_name.get ());
8796                 }
8797             }
8798         }
8799     }
8800
8801   if (package_name != NULL)
8802     {
8803       struct objfile *objfile = cu->per_objfile->objfile;
8804       const char *saved_package_name = objfile->intern (package_name.get ());
8805       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8806                                      saved_package_name);
8807       struct symbol *sym;
8808
8809       sym = new (&objfile->objfile_obstack) symbol;
8810       sym->set_language (language_go, &objfile->objfile_obstack);
8811       sym->compute_and_set_names (saved_package_name, false, objfile->per_bfd);
8812       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8813          e.g., "main" finds the "main" module and not C's main().  */
8814       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8815       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8816       SYMBOL_TYPE (sym) = type;
8817
8818       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
8819     }
8820 }
8821
8822 /* Allocate a fully-qualified name consisting of the two parts on the
8823    obstack.  */
8824
8825 static const char *
8826 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
8827 {
8828   return obconcat (obstack, p1, "::", p2, (char *) NULL);
8829 }
8830
8831 /* A helper that allocates a variant part to attach to a Rust enum
8832    type.  OBSTACK is where the results should be allocated.  TYPE is
8833    the type we're processing.  DISCRIMINANT_INDEX is the index of the
8834    discriminant.  It must be the index of one of the fields of TYPE,
8835    or -1 to mean there is no discriminant (univariant enum).
8836    DEFAULT_INDEX is the index of the default field; or -1 if there is
8837    no default.  RANGES is indexed by "effective" field number (the
8838    field index, but omitting the discriminant and default fields) and
8839    must hold the discriminant values used by the variants.  Note that
8840    RANGES must have a lifetime at least as long as OBSTACK -- either
8841    already allocated on it, or static.  */
8842
8843 static void
8844 alloc_rust_variant (struct obstack *obstack, struct type *type,
8845                     int discriminant_index, int default_index,
8846                     gdb::array_view<discriminant_range> ranges)
8847 {
8848   /* When DISCRIMINANT_INDEX == -1, we have a univariant enum.  */
8849   gdb_assert (discriminant_index == -1
8850               || (discriminant_index >= 0
8851                   && discriminant_index < type->num_fields ()));
8852   gdb_assert (default_index == -1
8853               || (default_index >= 0 && default_index < type->num_fields ()));
8854
8855   /* We have one variant for each non-discriminant field.  */
8856   int n_variants = type->num_fields ();
8857   if (discriminant_index != -1)
8858     --n_variants;
8859
8860   variant *variants = new (obstack) variant[n_variants];
8861   int var_idx = 0;
8862   int range_idx = 0;
8863   for (int i = 0; i < type->num_fields (); ++i)
8864     {
8865       if (i == discriminant_index)
8866         continue;
8867
8868       variants[var_idx].first_field = i;
8869       variants[var_idx].last_field = i + 1;
8870
8871       /* The default field does not need a range, but other fields do.
8872          We skipped the discriminant above.  */
8873       if (i != default_index)
8874         {
8875           variants[var_idx].discriminants = ranges.slice (range_idx, 1);
8876           ++range_idx;
8877         }
8878
8879       ++var_idx;
8880     }
8881
8882   gdb_assert (range_idx == ranges.size ());
8883   gdb_assert (var_idx == n_variants);
8884
8885   variant_part *part = new (obstack) variant_part;
8886   part->discriminant_index = discriminant_index;
8887   /* If there is no discriminant, then whether it is signed is of no
8888      consequence.  */
8889   part->is_unsigned
8890     = (discriminant_index == -1
8891        ? false
8892        : type->field (discriminant_index).type ()->is_unsigned ());
8893   part->variants = gdb::array_view<variant> (variants, n_variants);
8894
8895   void *storage = obstack_alloc (obstack, sizeof (gdb::array_view<variant_part>));
8896   gdb::array_view<variant_part> *prop_value
8897     = new (storage) gdb::array_view<variant_part> (part, 1);
8898
8899   struct dynamic_prop prop;
8900   prop.set_variant_parts (prop_value);
8901
8902   type->add_dyn_prop (DYN_PROP_VARIANT_PARTS, prop);
8903 }
8904
8905 /* Some versions of rustc emitted enums in an unusual way.
8906
8907    Ordinary enums were emitted as unions.  The first element of each
8908    structure in the union was named "RUST$ENUM$DISR".  This element
8909    held the discriminant.
8910
8911    These versions of Rust also implemented the "non-zero"
8912    optimization.  When the enum had two values, and one is empty and
8913    the other holds a pointer that cannot be zero, the pointer is used
8914    as the discriminant, with a zero value meaning the empty variant.
8915    Here, the union's first member is of the form
8916    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
8917    where the fieldnos are the indices of the fields that should be
8918    traversed in order to find the field (which may be several fields deep)
8919    and the variantname is the name of the variant of the case when the
8920    field is zero.
8921
8922    This function recognizes whether TYPE is of one of these forms,
8923    and, if so, smashes it to be a variant type.  */
8924
8925 static void
8926 quirk_rust_enum (struct type *type, struct objfile *objfile)
8927 {
8928   gdb_assert (type->code () == TYPE_CODE_UNION);
8929
8930   /* We don't need to deal with empty enums.  */
8931   if (type->num_fields () == 0)
8932     return;
8933
8934 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
8935   if (type->num_fields () == 1
8936       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
8937     {
8938       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
8939
8940       /* Decode the field name to find the offset of the
8941          discriminant.  */
8942       ULONGEST bit_offset = 0;
8943       struct type *field_type = type->field (0).type ();
8944       while (name[0] >= '0' && name[0] <= '9')
8945         {
8946           char *tail;
8947           unsigned long index = strtoul (name, &tail, 10);
8948           name = tail;
8949           if (*name != '$'
8950               || index >= field_type->num_fields ()
8951               || (TYPE_FIELD_LOC_KIND (field_type, index)
8952                   != FIELD_LOC_KIND_BITPOS))
8953             {
8954               complaint (_("Could not parse Rust enum encoding string \"%s\""
8955                            "[in module %s]"),
8956                          TYPE_FIELD_NAME (type, 0),
8957                          objfile_name (objfile));
8958               return;
8959             }
8960           ++name;
8961
8962           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
8963           field_type = field_type->field (index).type ();
8964         }
8965
8966       /* Smash this type to be a structure type.  We have to do this
8967          because the type has already been recorded.  */
8968       type->set_code (TYPE_CODE_STRUCT);
8969       type->set_num_fields (3);
8970       /* Save the field we care about.  */
8971       struct field saved_field = type->field (0);
8972       type->set_fields
8973         ((struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field)));
8974
8975       /* Put the discriminant at index 0.  */
8976       type->field (0).set_type (field_type);
8977       TYPE_FIELD_ARTIFICIAL (type, 0) = 1;
8978       TYPE_FIELD_NAME (type, 0) = "<<discriminant>>";
8979       SET_FIELD_BITPOS (type->field (0), bit_offset);
8980
8981       /* The order of fields doesn't really matter, so put the real
8982          field at index 1 and the data-less field at index 2.  */
8983       type->field (1) = saved_field;
8984       TYPE_FIELD_NAME (type, 1)
8985         = rust_last_path_segment (type->field (1).type ()->name ());
8986       type->field (1).type ()->set_name
8987         (rust_fully_qualify (&objfile->objfile_obstack, type->name (),
8988                              TYPE_FIELD_NAME (type, 1)));
8989
8990       const char *dataless_name
8991         = rust_fully_qualify (&objfile->objfile_obstack, type->name (),
8992                               name);
8993       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
8994                                               dataless_name);
8995       type->field (2).set_type (dataless_type);
8996       /* NAME points into the original discriminant name, which
8997          already has the correct lifetime.  */
8998       TYPE_FIELD_NAME (type, 2) = name;
8999       SET_FIELD_BITPOS (type->field (2), 0);
9000
9001       /* Indicate that this is a variant type.  */
9002       static discriminant_range ranges[1] = { { 0, 0 } };
9003       alloc_rust_variant (&objfile->objfile_obstack, type, 0, 1, ranges);
9004     }
9005   /* A union with a single anonymous field is probably an old-style
9006      univariant enum.  */
9007   else if (type->num_fields () == 1 && streq (TYPE_FIELD_NAME (type, 0), ""))
9008     {
9009       /* Smash this type to be a structure type.  We have to do this
9010          because the type has already been recorded.  */
9011       type->set_code (TYPE_CODE_STRUCT);
9012
9013       struct type *field_type = type->field (0).type ();
9014       const char *variant_name
9015         = rust_last_path_segment (field_type->name ());
9016       TYPE_FIELD_NAME (type, 0) = variant_name;
9017       field_type->set_name
9018         (rust_fully_qualify (&objfile->objfile_obstack,
9019                              type->name (), variant_name));
9020
9021       alloc_rust_variant (&objfile->objfile_obstack, type, -1, 0, {});
9022     }
9023   else
9024     {
9025       struct type *disr_type = nullptr;
9026       for (int i = 0; i < type->num_fields (); ++i)
9027         {
9028           disr_type = type->field (i).type ();
9029
9030           if (disr_type->code () != TYPE_CODE_STRUCT)
9031             {
9032               /* All fields of a true enum will be structs.  */
9033               return;
9034             }
9035           else if (disr_type->num_fields () == 0)
9036             {
9037               /* Could be data-less variant, so keep going.  */
9038               disr_type = nullptr;
9039             }
9040           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9041                            "RUST$ENUM$DISR") != 0)
9042             {
9043               /* Not a Rust enum.  */
9044               return;
9045             }
9046           else
9047             {
9048               /* Found one.  */
9049               break;
9050             }
9051         }
9052
9053       /* If we got here without a discriminant, then it's probably
9054          just a union.  */
9055       if (disr_type == nullptr)
9056         return;
9057
9058       /* Smash this type to be a structure type.  We have to do this
9059          because the type has already been recorded.  */
9060       type->set_code (TYPE_CODE_STRUCT);
9061
9062       /* Make space for the discriminant field.  */
9063       struct field *disr_field = &disr_type->field (0);
9064       field *new_fields
9065         = (struct field *) TYPE_ZALLOC (type, ((type->num_fields () + 1)
9066                                                * sizeof (struct field)));
9067       memcpy (new_fields + 1, type->fields (),
9068               type->num_fields () * sizeof (struct field));
9069       type->set_fields (new_fields);
9070       type->set_num_fields (type->num_fields () + 1);
9071
9072       /* Install the discriminant at index 0 in the union.  */
9073       type->field (0) = *disr_field;
9074       TYPE_FIELD_ARTIFICIAL (type, 0) = 1;
9075       TYPE_FIELD_NAME (type, 0) = "<<discriminant>>";
9076
9077       /* We need a way to find the correct discriminant given a
9078          variant name.  For convenience we build a map here.  */
9079       struct type *enum_type = disr_field->type ();
9080       std::unordered_map<std::string, ULONGEST> discriminant_map;
9081       for (int i = 0; i < enum_type->num_fields (); ++i)
9082         {
9083           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
9084             {
9085               const char *name
9086                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
9087               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
9088             }
9089         }
9090
9091       int n_fields = type->num_fields ();
9092       /* We don't need a range entry for the discriminant, but we do
9093          need one for every other field, as there is no default
9094          variant.  */
9095       discriminant_range *ranges = XOBNEWVEC (&objfile->objfile_obstack,
9096                                               discriminant_range,
9097                                               n_fields - 1);
9098       /* Skip the discriminant here.  */
9099       for (int i = 1; i < n_fields; ++i)
9100         {
9101           /* Find the final word in the name of this variant's type.
9102              That name can be used to look up the correct
9103              discriminant.  */
9104           const char *variant_name
9105             = rust_last_path_segment (type->field (i).type ()->name ());
9106
9107           auto iter = discriminant_map.find (variant_name);
9108           if (iter != discriminant_map.end ())
9109             {
9110               ranges[i - 1].low = iter->second;
9111               ranges[i - 1].high = iter->second;
9112             }
9113
9114           /* In Rust, each element should have the size of the
9115              enclosing enum.  */
9116           TYPE_LENGTH (type->field (i).type ()) = TYPE_LENGTH (type);
9117
9118           /* Remove the discriminant field, if it exists.  */
9119           struct type *sub_type = type->field (i).type ();
9120           if (sub_type->num_fields () > 0)
9121             {
9122               sub_type->set_num_fields (sub_type->num_fields () - 1);
9123               sub_type->set_fields (sub_type->fields () + 1);
9124             }
9125           TYPE_FIELD_NAME (type, i) = variant_name;
9126           sub_type->set_name
9127             (rust_fully_qualify (&objfile->objfile_obstack,
9128                                  type->name (), variant_name));
9129         }
9130
9131       /* Indicate that this is a variant type.  */
9132       alloc_rust_variant (&objfile->objfile_obstack, type, 0, -1,
9133                           gdb::array_view<discriminant_range> (ranges,
9134                                                                n_fields - 1));
9135     }
9136 }
9137
9138 /* Rewrite some Rust unions to be structures with variants parts.  */
9139
9140 static void
9141 rust_union_quirks (struct dwarf2_cu *cu)
9142 {
9143   gdb_assert (cu->per_cu->lang == language_rust);
9144   for (type *type_ : cu->rust_unions)
9145     quirk_rust_enum (type_, cu->per_objfile->objfile);
9146   /* We don't need this any more.  */
9147   cu->rust_unions.clear ();
9148 }
9149
9150 /* See read.h.  */
9151
9152 type_unit_group_unshareable *
9153 dwarf2_per_objfile::get_type_unit_group_unshareable (type_unit_group *tu_group)
9154 {
9155   auto iter = this->m_type_units.find (tu_group);
9156   if (iter != this->m_type_units.end ())
9157     return iter->second.get ();
9158
9159   type_unit_group_unshareable_up uniq (new type_unit_group_unshareable);
9160   type_unit_group_unshareable *result = uniq.get ();
9161   this->m_type_units[tu_group] = std::move (uniq);
9162   return result;
9163 }
9164
9165 struct type *
9166 dwarf2_per_objfile::get_type_for_signatured_type
9167   (signatured_type *sig_type) const
9168 {
9169   auto iter = this->m_type_map.find (sig_type);
9170   if (iter == this->m_type_map.end ())
9171     return nullptr;
9172
9173   return iter->second;
9174 }
9175
9176 void dwarf2_per_objfile::set_type_for_signatured_type
9177   (signatured_type *sig_type, struct type *type)
9178 {
9179   gdb_assert (this->m_type_map.find (sig_type) == this->m_type_map.end ());
9180
9181   this->m_type_map[sig_type] = type;
9182 }
9183
9184 /* A helper function for computing the list of all symbol tables
9185    included by PER_CU.  */
9186
9187 static void
9188 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
9189                                 htab_t all_children, htab_t all_type_symtabs,
9190                                 dwarf2_per_cu_data *per_cu,
9191                                 dwarf2_per_objfile *per_objfile,
9192                                 struct compunit_symtab *immediate_parent)
9193 {
9194   void **slot = htab_find_slot (all_children, per_cu, INSERT);
9195   if (*slot != NULL)
9196     {
9197       /* This inclusion and its children have been processed.  */
9198       return;
9199     }
9200
9201   *slot = per_cu;
9202
9203   /* Only add a CU if it has a symbol table.  */
9204   compunit_symtab *cust = per_objfile->get_symtab (per_cu);
9205   if (cust != NULL)
9206     {
9207       /* If this is a type unit only add its symbol table if we haven't
9208          seen it yet (type unit per_cu's can share symtabs).  */
9209       if (per_cu->is_debug_types)
9210         {
9211           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9212           if (*slot == NULL)
9213             {
9214               *slot = cust;
9215               result->push_back (cust);
9216               if (cust->user == NULL)
9217                 cust->user = immediate_parent;
9218             }
9219         }
9220       else
9221         {
9222           result->push_back (cust);
9223           if (cust->user == NULL)
9224             cust->user = immediate_parent;
9225         }
9226     }
9227
9228   if (!per_cu->imported_symtabs_empty ())
9229     for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9230       {
9231         recursively_compute_inclusions (result, all_children,
9232                                         all_type_symtabs, ptr, per_objfile,
9233                                         cust);
9234       }
9235 }
9236
9237 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9238    PER_CU.  */
9239
9240 static void
9241 compute_compunit_symtab_includes (dwarf2_per_cu_data *per_cu,
9242                                   dwarf2_per_objfile *per_objfile)
9243 {
9244   gdb_assert (! per_cu->is_debug_types);
9245
9246   if (!per_cu->imported_symtabs_empty ())
9247     {
9248       int len;
9249       std::vector<compunit_symtab *> result_symtabs;
9250       compunit_symtab *cust = per_objfile->get_symtab (per_cu);
9251
9252       /* If we don't have a symtab, we can just skip this case.  */
9253       if (cust == NULL)
9254         return;
9255
9256       htab_up all_children (htab_create_alloc (1, htab_hash_pointer,
9257                                                htab_eq_pointer,
9258                                                NULL, xcalloc, xfree));
9259       htab_up all_type_symtabs (htab_create_alloc (1, htab_hash_pointer,
9260                                                    htab_eq_pointer,
9261                                                    NULL, xcalloc, xfree));
9262
9263       for (dwarf2_per_cu_data *ptr : *per_cu->imported_symtabs)
9264         {
9265           recursively_compute_inclusions (&result_symtabs, all_children.get (),
9266                                           all_type_symtabs.get (), ptr,
9267                                           per_objfile, cust);
9268         }
9269
9270       /* Now we have a transitive closure of all the included symtabs.  */
9271       len = result_symtabs.size ();
9272       cust->includes
9273         = XOBNEWVEC (&per_objfile->objfile->objfile_obstack,
9274                      struct compunit_symtab *, len + 1);
9275       memcpy (cust->includes, result_symtabs.data (),
9276               len * sizeof (compunit_symtab *));
9277       cust->includes[len] = NULL;
9278     }
9279 }
9280
9281 /* Compute the 'includes' field for the symtabs of all the CUs we just
9282    read.  */
9283
9284 static void
9285 process_cu_includes (dwarf2_per_objfile *per_objfile)
9286 {
9287   for (dwarf2_per_cu_data *iter : per_objfile->per_bfd->just_read_cus)
9288     {
9289       if (! iter->is_debug_types)
9290         compute_compunit_symtab_includes (iter, per_objfile);
9291     }
9292
9293   per_objfile->per_bfd->just_read_cus.clear ();
9294 }
9295
9296 /* Generate full symbol information for CU, whose DIEs have
9297    already been loaded into memory.  */
9298
9299 static void
9300 process_full_comp_unit (dwarf2_cu *cu, enum language pretend_language)
9301 {
9302   dwarf2_per_objfile *per_objfile = cu->per_objfile;
9303   struct objfile *objfile = per_objfile->objfile;
9304   struct gdbarch *gdbarch = objfile->arch ();
9305   CORE_ADDR lowpc, highpc;
9306   struct compunit_symtab *cust;
9307   CORE_ADDR baseaddr;
9308   struct block *static_block;
9309   CORE_ADDR addr;
9310
9311   baseaddr = objfile->text_section_offset ();
9312
9313   /* Clear the list here in case something was left over.  */
9314   cu->method_list.clear ();
9315
9316   dwarf2_find_base_address (cu->dies, cu);
9317
9318   /* Before we start reading the top-level DIE, ensure it has a valid tag
9319      type.  */
9320   switch (cu->dies->tag)
9321     {
9322     case DW_TAG_compile_unit:
9323     case DW_TAG_partial_unit:
9324     case DW_TAG_type_unit:
9325       break;
9326     default:
9327       error (_("Dwarf Error: unexpected tag '%s' at offset %s [in module %s]"),
9328              dwarf_tag_name (cu->dies->tag),
9329              sect_offset_str (cu->per_cu->sect_off),
9330              objfile_name (per_objfile->objfile));
9331     }
9332
9333   /* Do line number decoding in read_file_scope () */
9334   process_die (cu->dies, cu);
9335
9336   /* For now fudge the Go package.  */
9337   if (cu->per_cu->lang == language_go)
9338     fixup_go_packaging (cu);
9339
9340   /* Now that we have processed all the DIEs in the CU, all the types
9341      should be complete, and it should now be safe to compute all of the
9342      physnames.  */
9343   compute_delayed_physnames (cu);
9344
9345   if (cu->per_cu->lang == language_rust)
9346     rust_union_quirks (cu);
9347
9348   /* Some compilers don't define a DW_AT_high_pc attribute for the
9349      compilation unit.  If the DW_AT_high_pc is missing, synthesize
9350      it, by scanning the DIE's below the compilation unit.  */
9351   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
9352
9353   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
9354   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
9355
9356   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
9357      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
9358      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
9359      addrmap to help ensure it has an accurate map of pc values belonging to
9360      this comp unit.  */
9361   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
9362
9363   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
9364                                                     SECT_OFF_TEXT (objfile),
9365                                                     0);
9366
9367   if (cust != NULL)
9368     {
9369       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
9370
9371       /* Set symtab language to language from DW_AT_language.  If the
9372          compilation is from a C file generated by language preprocessors, do
9373          not set the language if it was already deduced by start_subfile.  */
9374       if (!(cu->per_cu->lang == language_c
9375             && COMPUNIT_FILETABS (cust)->language != language_unknown))
9376         COMPUNIT_FILETABS (cust)->language = cu->per_cu->lang;
9377
9378       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
9379          produce DW_AT_location with location lists but it can be possibly
9380          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
9381          there were bugs in prologue debug info, fixed later in GCC-4.5
9382          by "unwind info for epilogues" patch (which is not directly related).
9383
9384          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
9385          needed, it would be wrong due to missing DW_AT_producer there.
9386
9387          Still one can confuse GDB by using non-standard GCC compilation
9388          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
9389          */
9390       if (cu->has_loclist && gcc_4_minor >= 5)
9391         cust->locations_valid = 1;
9392
9393       if (gcc_4_minor >= 5)
9394         cust->epilogue_unwind_valid = 1;
9395
9396       cust->call_site_htab = cu->call_site_htab;
9397     }
9398
9399   per_objfile->set_symtab (cu->per_cu, cust);
9400
9401   /* Push it for inclusion processing later.  */
9402   per_objfile->per_bfd->just_read_cus.push_back (cu->per_cu);
9403
9404   /* Not needed any more.  */
9405   cu->reset_builder ();
9406 }
9407
9408 /* Generate full symbol information for type unit CU, whose DIEs have
9409    already been loaded into memory.  */
9410
9411 static void
9412 process_full_type_unit (dwarf2_cu *cu,
9413                         enum language pretend_language)
9414 {
9415   dwarf2_per_objfile *per_objfile = cu->per_objfile;
9416   struct objfile *objfile = per_objfile->objfile;
9417   struct compunit_symtab *cust;
9418   struct signatured_type *sig_type;
9419
9420   gdb_assert (cu->per_cu->is_debug_types);
9421   sig_type = (struct signatured_type *) cu->per_cu;
9422
9423   /* Clear the list here in case something was left over.  */
9424   cu->method_list.clear ();
9425
9426   /* The symbol tables are set up in read_type_unit_scope.  */
9427   process_die (cu->dies, cu);
9428
9429   /* For now fudge the Go package.  */
9430   if (cu->per_cu->lang == language_go)
9431     fixup_go_packaging (cu);
9432
9433   /* Now that we have processed all the DIEs in the CU, all the types
9434      should be complete, and it should now be safe to compute all of the
9435      physnames.  */
9436   compute_delayed_physnames (cu);
9437
9438   if (cu->per_cu->lang == language_rust)
9439     rust_union_quirks (cu);
9440
9441   /* TUs share symbol tables.
9442      If this is the first TU to use this symtab, complete the construction
9443      of it with end_expandable_symtab.  Otherwise, complete the addition of
9444      this TU's symbols to the existing symtab.  */
9445   type_unit_group_unshareable *tug_unshare =
9446     per_objfile->get_type_unit_group_unshareable (sig_type->type_unit_group);
9447   if (tug_unshare->compunit_symtab == NULL)
9448     {
9449       buildsym_compunit *builder = cu->get_builder ();
9450       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
9451       tug_unshare->compunit_symtab = cust;
9452
9453       if (cust != NULL)
9454         {
9455           /* Set symtab language to language from DW_AT_language.  If the
9456              compilation is from a C file generated by language preprocessors,
9457              do not set the language if it was already deduced by
9458              start_subfile.  */
9459           if (!(cu->per_cu->lang == language_c
9460                 && COMPUNIT_FILETABS (cust)->language != language_c))
9461             COMPUNIT_FILETABS (cust)->language = cu->per_cu->lang;
9462         }
9463     }
9464   else
9465     {
9466       cu->get_builder ()->augment_type_symtab ();
9467       cust = tug_unshare->compunit_symtab;
9468     }
9469
9470   per_objfile->set_symtab (cu->per_cu, cust);
9471
9472   /* Not needed any more.  */
9473   cu->reset_builder ();
9474 }
9475
9476 /* Process an imported unit DIE.  */
9477
9478 static void
9479 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
9480 {
9481   struct attribute *attr;
9482
9483   /* For now we don't handle imported units in type units.  */
9484   if (cu->per_cu->is_debug_types)
9485     {
9486       error (_("Dwarf Error: DW_TAG_imported_unit is not"
9487                " supported in type units [in module %s]"),
9488              objfile_name (cu->per_objfile->objfile));
9489     }
9490
9491   attr = dwarf2_attr (die, DW_AT_import, cu);
9492   if (attr != NULL)
9493     {
9494       sect_offset sect_off = attr->get_ref_die_offset ();
9495       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
9496       dwarf2_per_objfile *per_objfile = cu->per_objfile;
9497       dwarf2_per_cu_data *per_cu
9498         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, per_objfile);
9499
9500       /* We're importing a C++ compilation unit with tag DW_TAG_compile_unit
9501          into another compilation unit, at root level.  Regard this as a hint,
9502          and ignore it.  */
9503       if (die->parent && die->parent->parent == NULL
9504           && per_cu->unit_type == DW_UT_compile
9505           && per_cu->lang == language_cplus)
9506         return;
9507
9508       /* If necessary, add it to the queue and load its DIEs.  */
9509       if (maybe_queue_comp_unit (cu, per_cu, per_objfile,
9510                                  cu->per_cu->lang))
9511         load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
9512                              false, cu->per_cu->lang);
9513
9514       cu->per_cu->imported_symtabs_push (per_cu);
9515     }
9516 }
9517
9518 /* RAII object that represents a process_die scope: i.e.,
9519    starts/finishes processing a DIE.  */
9520 class process_die_scope
9521 {
9522 public:
9523   process_die_scope (die_info *die, dwarf2_cu *cu)
9524     : m_die (die), m_cu (cu)
9525   {
9526     /* We should only be processing DIEs not already in process.  */
9527     gdb_assert (!m_die->in_process);
9528     m_die->in_process = true;
9529   }
9530
9531   ~process_die_scope ()
9532   {
9533     m_die->in_process = false;
9534
9535     /* If we're done processing the DIE for the CU that owns the line
9536        header, we don't need the line header anymore.  */
9537     if (m_cu->line_header_die_owner == m_die)
9538       {
9539         delete m_cu->line_header;
9540         m_cu->line_header = NULL;
9541         m_cu->line_header_die_owner = NULL;
9542       }
9543   }
9544
9545 private:
9546   die_info *m_die;
9547   dwarf2_cu *m_cu;
9548 };
9549
9550 /* Process a die and its children.  */
9551
9552 static void
9553 process_die (struct die_info *die, struct dwarf2_cu *cu)
9554 {
9555   process_die_scope scope (die, cu);
9556
9557   switch (die->tag)
9558     {
9559     case DW_TAG_padding:
9560       break;
9561     case DW_TAG_compile_unit:
9562     case DW_TAG_partial_unit:
9563       read_file_scope (die, cu);
9564       break;
9565     case DW_TAG_type_unit:
9566       read_type_unit_scope (die, cu);
9567       break;
9568     case DW_TAG_subprogram:
9569       /* Nested subprograms in Fortran get a prefix.  */
9570       if (cu->per_cu->lang == language_fortran
9571           && die->parent != NULL
9572           && die->parent->tag == DW_TAG_subprogram)
9573         cu->processing_has_namespace_info = true;
9574       /* Fall through.  */
9575     case DW_TAG_inlined_subroutine:
9576       read_func_scope (die, cu);
9577       break;
9578     case DW_TAG_lexical_block:
9579     case DW_TAG_try_block:
9580     case DW_TAG_catch_block:
9581       read_lexical_block_scope (die, cu);
9582       break;
9583     case DW_TAG_call_site:
9584     case DW_TAG_GNU_call_site:
9585       read_call_site_scope (die, cu);
9586       break;
9587     case DW_TAG_class_type:
9588     case DW_TAG_interface_type:
9589     case DW_TAG_structure_type:
9590     case DW_TAG_union_type:
9591       process_structure_scope (die, cu);
9592       break;
9593     case DW_TAG_enumeration_type:
9594       process_enumeration_scope (die, cu);
9595       break;
9596
9597     /* These dies have a type, but processing them does not create
9598        a symbol or recurse to process the children.  Therefore we can
9599        read them on-demand through read_type_die.  */
9600     case DW_TAG_subroutine_type:
9601     case DW_TAG_set_type:
9602     case DW_TAG_pointer_type:
9603     case DW_TAG_ptr_to_member_type:
9604     case DW_TAG_reference_type:
9605     case DW_TAG_rvalue_reference_type:
9606     case DW_TAG_string_type:
9607       break;
9608
9609     case DW_TAG_array_type:
9610       /* We only need to handle this case for Ada -- in other
9611          languages, it's normal for the compiler to emit a typedef
9612          instead.  */
9613       if (cu->per_cu->lang != language_ada)
9614         break;
9615       /* FALLTHROUGH */
9616     case DW_TAG_base_type:
9617     case DW_TAG_subrange_type:
9618     case DW_TAG_typedef:
9619       /* Add a typedef symbol for the type definition, if it has a
9620          DW_AT_name.  */
9621       new_symbol (die, read_type_die (die, cu), cu);
9622       break;
9623     case DW_TAG_common_block:
9624       read_common_block (die, cu);
9625       break;
9626     case DW_TAG_common_inclusion:
9627       break;
9628     case DW_TAG_namespace:
9629       cu->processing_has_namespace_info = true;
9630       read_namespace (die, cu);
9631       break;
9632     case DW_TAG_module:
9633       cu->processing_has_namespace_info = true;
9634       read_module (die, cu);
9635       break;
9636     case DW_TAG_imported_declaration:
9637       cu->processing_has_namespace_info = true;
9638       if (read_namespace_alias (die, cu))
9639         break;
9640       /* The declaration is not a global namespace alias.  */
9641       /* Fall through.  */
9642     case DW_TAG_imported_module:
9643       cu->processing_has_namespace_info = true;
9644       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
9645                                  || cu->per_cu->lang != language_fortran))
9646         complaint (_("Tag '%s' has unexpected children"),
9647                    dwarf_tag_name (die->tag));
9648       read_import_statement (die, cu);
9649       break;
9650
9651     case DW_TAG_imported_unit:
9652       process_imported_unit_die (die, cu);
9653       break;
9654
9655     case DW_TAG_variable:
9656       read_variable (die, cu);
9657       break;
9658
9659     default:
9660       new_symbol (die, NULL, cu);
9661       break;
9662     }
9663 }
9664 \f
9665 /* DWARF name computation.  */
9666
9667 /* A helper function for dwarf2_compute_name which determines whether DIE
9668    needs to have the name of the scope prepended to the name listed in the
9669    die.  */
9670
9671 static int
9672 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
9673 {
9674   struct attribute *attr;
9675
9676   switch (die->tag)
9677     {
9678     case DW_TAG_namespace:
9679     case DW_TAG_typedef:
9680     case DW_TAG_class_type:
9681     case DW_TAG_interface_type:
9682     case DW_TAG_structure_type:
9683     case DW_TAG_union_type:
9684     case DW_TAG_enumeration_type:
9685     case DW_TAG_enumerator:
9686     case DW_TAG_subprogram:
9687     case DW_TAG_inlined_subroutine:
9688     case DW_TAG_member:
9689     case DW_TAG_imported_declaration:
9690       return 1;
9691
9692     case DW_TAG_variable:
9693     case DW_TAG_constant:
9694       /* We only need to prefix "globally" visible variables.  These include
9695          any variable marked with DW_AT_external or any variable that
9696          lives in a namespace.  [Variables in anonymous namespaces
9697          require prefixing, but they are not DW_AT_external.]  */
9698
9699       if (dwarf2_attr (die, DW_AT_specification, cu))
9700         {
9701           struct dwarf2_cu *spec_cu = cu;
9702
9703           return die_needs_namespace (die_specification (die, &spec_cu),
9704                                       spec_cu);
9705         }
9706
9707       attr = dwarf2_attr (die, DW_AT_external, cu);
9708       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9709           && die->parent->tag != DW_TAG_module)
9710         return 0;
9711       /* A variable in a lexical block of some kind does not need a
9712          namespace, even though in C++ such variables may be external
9713          and have a mangled name.  */
9714       if (die->parent->tag ==  DW_TAG_lexical_block
9715           || die->parent->tag ==  DW_TAG_try_block
9716           || die->parent->tag ==  DW_TAG_catch_block
9717           || die->parent->tag == DW_TAG_subprogram)
9718         return 0;
9719       return 1;
9720
9721     default:
9722       return 0;
9723     }
9724 }
9725
9726 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9727    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9728    defined for the given DIE.  */
9729
9730 static struct attribute *
9731 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9732 {
9733   struct attribute *attr;
9734
9735   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9736   if (attr == NULL)
9737     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9738
9739   return attr;
9740 }
9741
9742 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9743    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9744    defined for the given DIE.  */
9745
9746 static const char *
9747 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9748 {
9749   const char *linkage_name;
9750
9751   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9752   if (linkage_name == NULL)
9753     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9754
9755   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9756      See https://github.com/rust-lang/rust/issues/32925.  */
9757   if (cu->per_cu->lang == language_rust && linkage_name != NULL
9758       && strchr (linkage_name, '{') != NULL)
9759     linkage_name = NULL;
9760
9761   return linkage_name;
9762 }
9763
9764 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9765    compute the physname for the object, which include a method's:
9766    - formal parameters (C++),
9767    - receiver type (Go),
9768
9769    The term "physname" is a bit confusing.
9770    For C++, for example, it is the demangled name.
9771    For Go, for example, it's the mangled name.
9772
9773    For Ada, return the DIE's linkage name rather than the fully qualified
9774    name.  PHYSNAME is ignored..
9775
9776    The result is allocated on the objfile->per_bfd's obstack and
9777    canonicalized.  */
9778
9779 static const char *
9780 dwarf2_compute_name (const char *name,
9781                      struct die_info *die, struct dwarf2_cu *cu,
9782                      int physname)
9783 {
9784   struct objfile *objfile = cu->per_objfile->objfile;
9785
9786   if (name == NULL)
9787     name = dwarf2_name (die, cu);
9788
9789   enum language lang = cu->per_cu->lang;
9790
9791   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9792      but otherwise compute it by typename_concat inside GDB.
9793      FIXME: Actually this is not really true, or at least not always true.
9794      It's all very confusing.  compute_and_set_names doesn't try to demangle
9795      Fortran names because there is no mangling standard.  So new_symbol
9796      will set the demangled name to the result of dwarf2_full_name, and it is
9797      the demangled name that GDB uses if it exists.  */
9798   if (lang == language_ada
9799       || (lang == language_fortran && physname))
9800     {
9801       /* For Ada unit, we prefer the linkage name over the name, as
9802          the former contains the exported name, which the user expects
9803          to be able to reference.  Ideally, we want the user to be able
9804          to reference this entity using either natural or linkage name,
9805          but we haven't started looking at this enhancement yet.  */
9806       const char *linkage_name = dw2_linkage_name (die, cu);
9807
9808       if (linkage_name != NULL)
9809         return linkage_name;
9810     }
9811
9812   /* These are the only languages we know how to qualify names in.  */
9813   if (name != NULL
9814       && (lang == language_cplus
9815           || lang == language_fortran || lang == language_d
9816           || lang == language_rust))
9817     {
9818       if (die_needs_namespace (die, cu))
9819         {
9820           const char *prefix;
9821           const char *canonical_name = NULL;
9822
9823           string_file buf;
9824
9825           prefix = determine_prefix (die, cu);
9826           if (*prefix != '\0')
9827             {
9828               gdb::unique_xmalloc_ptr<char> prefixed_name
9829                 (typename_concat (NULL, prefix, name, physname, cu));
9830
9831               buf.puts (prefixed_name.get ());
9832             }
9833           else
9834             buf.puts (name);
9835
9836           /* Template parameters may be specified in the DIE's DW_AT_name, or
9837              as children with DW_TAG_template_type_param or
9838              DW_TAG_value_type_param.  If the latter, add them to the name
9839              here.  If the name already has template parameters, then
9840              skip this step; some versions of GCC emit both, and
9841              it is more efficient to use the pre-computed name.
9842
9843              Something to keep in mind about this process: it is very
9844              unlikely, or in some cases downright impossible, to produce
9845              something that will match the mangled name of a function.
9846              If the definition of the function has the same debug info,
9847              we should be able to match up with it anyway.  But fallbacks
9848              using the minimal symbol, for instance to find a method
9849              implemented in a stripped copy of libstdc++, will not work.
9850              If we do not have debug info for the definition, we will have to
9851              match them up some other way.
9852
9853              When we do name matching there is a related problem with function
9854              templates; two instantiated function templates are allowed to
9855              differ only by their return types, which we do not add here.  */
9856
9857           if (lang == language_cplus && strchr (name, '<') == NULL)
9858             {
9859               struct attribute *attr;
9860               struct die_info *child;
9861               int first = 1;
9862
9863               die->building_fullname = 1;
9864
9865               for (child = die->child; child != NULL; child = child->sibling)
9866                 {
9867                   struct type *type;
9868                   LONGEST value;
9869                   const gdb_byte *bytes;
9870                   struct dwarf2_locexpr_baton *baton;
9871                   struct value *v;
9872
9873                   if (child->tag != DW_TAG_template_type_param
9874                       && child->tag != DW_TAG_template_value_param)
9875                     continue;
9876
9877                   if (first)
9878                     {
9879                       buf.puts ("<");
9880                       first = 0;
9881                     }
9882                   else
9883                     buf.puts (", ");
9884
9885                   attr = dwarf2_attr (child, DW_AT_type, cu);
9886                   if (attr == NULL)
9887                     {
9888                       complaint (_("template parameter missing DW_AT_type"));
9889                       buf.puts ("UNKNOWN_TYPE");
9890                       continue;
9891                     }
9892                   type = die_type (child, cu);
9893
9894                   if (child->tag == DW_TAG_template_type_param)
9895                     {
9896                       cu->language_defn->print_type (type, "", &buf, -1, 0,
9897                                                      &type_print_raw_options);
9898                       continue;
9899                     }
9900
9901                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
9902                   if (attr == NULL)
9903                     {
9904                       complaint (_("template parameter missing "
9905                                    "DW_AT_const_value"));
9906                       buf.puts ("UNKNOWN_VALUE");
9907                       continue;
9908                     }
9909
9910                   dwarf2_const_value_attr (attr, type, name,
9911                                            &cu->comp_unit_obstack, cu,
9912                                            &value, &bytes, &baton);
9913
9914                   if (type->has_no_signedness ())
9915                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
9916                        changed, this can use value_print instead.  */
9917                     cu->language_defn->printchar (value, type, &buf);
9918                   else
9919                     {
9920                       struct value_print_options opts;
9921
9922                       if (baton != NULL)
9923                         v = dwarf2_evaluate_loc_desc (type, NULL,
9924                                                       baton->data,
9925                                                       baton->size,
9926                                                       baton->per_cu,
9927                                                       baton->per_objfile);
9928                       else if (bytes != NULL)
9929                         {
9930                           v = allocate_value (type);
9931                           memcpy (value_contents_writeable (v), bytes,
9932                                   TYPE_LENGTH (type));
9933                         }
9934                       else
9935                         v = value_from_longest (type, value);
9936
9937                       /* Specify decimal so that we do not depend on
9938                          the radix.  */
9939                       get_formatted_print_options (&opts, 'd');
9940                       opts.raw = 1;
9941                       value_print (v, &buf, &opts);
9942                       release_value (v);
9943                     }
9944                 }
9945
9946               die->building_fullname = 0;
9947
9948               if (!first)
9949                 {
9950                   /* Close the argument list, with a space if necessary
9951                      (nested templates).  */
9952                   if (!buf.empty () && buf.string ().back () == '>')
9953                     buf.puts (" >");
9954                   else
9955                     buf.puts (">");
9956                 }
9957             }
9958
9959           /* For C++ methods, append formal parameter type
9960              information, if PHYSNAME.  */
9961
9962           if (physname && die->tag == DW_TAG_subprogram
9963               && lang == language_cplus)
9964             {
9965               struct type *type = read_type_die (die, cu);
9966
9967               c_type_print_args (type, &buf, 1, lang,
9968                                  &type_print_raw_options);
9969
9970               if (lang == language_cplus)
9971                 {
9972                   /* Assume that an artificial first parameter is
9973                      "this", but do not crash if it is not.  RealView
9974                      marks unnamed (and thus unused) parameters as
9975                      artificial; there is no way to differentiate
9976                      the two cases.  */
9977                   if (type->num_fields () > 0
9978                       && TYPE_FIELD_ARTIFICIAL (type, 0)
9979                       && type->field (0).type ()->code () == TYPE_CODE_PTR
9980                       && TYPE_CONST (TYPE_TARGET_TYPE (type->field (0).type ())))
9981                     buf.puts (" const");
9982                 }
9983             }
9984
9985           const std::string &intermediate_name = buf.string ();
9986
9987           if (lang == language_cplus)
9988             canonical_name
9989               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
9990                                           objfile);
9991
9992           /* If we only computed INTERMEDIATE_NAME, or if
9993              INTERMEDIATE_NAME is already canonical, then we need to
9994              intern it.  */
9995           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
9996             name = objfile->intern (intermediate_name);
9997           else
9998             name = canonical_name;
9999         }
10000     }
10001
10002   return name;
10003 }
10004
10005 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10006    If scope qualifiers are appropriate they will be added.  The result
10007    will be allocated on the storage_obstack, or NULL if the DIE does
10008    not have a name.  NAME may either be from a previous call to
10009    dwarf2_name or NULL.
10010
10011    The output string will be canonicalized (if C++).  */
10012
10013 static const char *
10014 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10015 {
10016   return dwarf2_compute_name (name, die, cu, 0);
10017 }
10018
10019 /* Construct a physname for the given DIE in CU.  NAME may either be
10020    from a previous call to dwarf2_name or NULL.  The result will be
10021    allocated on the objfile_objstack or NULL if the DIE does not have a
10022    name.
10023
10024    The output string will be canonicalized (if C++).  */
10025
10026 static const char *
10027 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10028 {
10029   struct objfile *objfile = cu->per_objfile->objfile;
10030   const char *retval, *mangled = NULL, *canon = NULL;
10031   int need_copy = 1;
10032
10033   /* In this case dwarf2_compute_name is just a shortcut not building anything
10034      on its own.  */
10035   if (!die_needs_namespace (die, cu))
10036     return dwarf2_compute_name (name, die, cu, 1);
10037
10038   if (cu->per_cu->lang != language_rust)
10039     mangled = dw2_linkage_name (die, cu);
10040
10041   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10042      has computed.  */
10043   gdb::unique_xmalloc_ptr<char> demangled;
10044   if (mangled != NULL)
10045     {
10046       if (cu->language_defn->store_sym_names_in_linkage_form_p ())
10047         {
10048           /* Do nothing (do not demangle the symbol name).  */
10049         }
10050       else
10051         {
10052           /* Use DMGL_RET_DROP for C++ template functions to suppress
10053              their return type.  It is easier for GDB users to search
10054              for such functions as `name(params)' than `long name(params)'.
10055              In such case the minimal symbol names do not match the full
10056              symbol names but for template functions there is never a need
10057              to look up their definition from their declaration so
10058              the only disadvantage remains the minimal symbol variant
10059              `long name(params)' does not have the proper inferior type.  */
10060           demangled.reset (gdb_demangle (mangled,
10061                                          (DMGL_PARAMS | DMGL_ANSI
10062                                           | DMGL_RET_DROP)));
10063         }
10064       if (demangled)
10065         canon = demangled.get ();
10066       else
10067         {
10068           canon = mangled;
10069           need_copy = 0;
10070         }
10071     }
10072
10073   if (canon == NULL || check_physname)
10074     {
10075       const char *physname = dwarf2_compute_name (name, die, cu, 1);
10076
10077       if (canon != NULL && strcmp (physname, canon) != 0)
10078         {
10079           /* It may not mean a bug in GDB.  The compiler could also
10080              compute DW_AT_linkage_name incorrectly.  But in such case
10081              GDB would need to be bug-to-bug compatible.  */
10082
10083           complaint (_("Computed physname <%s> does not match demangled <%s> "
10084                        "(from linkage <%s>) - DIE at %s [in module %s]"),
10085                      physname, canon, mangled, sect_offset_str (die->sect_off),
10086                      objfile_name (objfile));
10087
10088           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
10089              is available here - over computed PHYSNAME.  It is safer
10090              against both buggy GDB and buggy compilers.  */
10091
10092           retval = canon;
10093         }
10094       else
10095         {
10096           retval = physname;
10097           need_copy = 0;
10098         }
10099     }
10100   else
10101     retval = canon;
10102
10103   if (need_copy)
10104     retval = objfile->intern (retval);
10105
10106   return retval;
10107 }
10108
10109 /* Inspect DIE in CU for a namespace alias.  If one exists, record
10110    a new symbol for it.
10111
10112    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
10113
10114 static int
10115 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
10116 {
10117   struct attribute *attr;
10118
10119   /* If the die does not have a name, this is not a namespace
10120      alias.  */
10121   attr = dwarf2_attr (die, DW_AT_name, cu);
10122   if (attr != NULL)
10123     {
10124       int num;
10125       struct die_info *d = die;
10126       struct dwarf2_cu *imported_cu = cu;
10127
10128       /* If the compiler has nested DW_AT_imported_declaration DIEs,
10129          keep inspecting DIEs until we hit the underlying import.  */
10130 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
10131       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
10132         {
10133           attr = dwarf2_attr (d, DW_AT_import, cu);
10134           if (attr == NULL)
10135             break;
10136
10137           d = follow_die_ref (d, attr, &imported_cu);
10138           if (d->tag != DW_TAG_imported_declaration)
10139             break;
10140         }
10141
10142       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10143         {
10144           complaint (_("DIE at %s has too many recursively imported "
10145                        "declarations"), sect_offset_str (d->sect_off));
10146           return 0;
10147         }
10148
10149       if (attr != NULL)
10150         {
10151           struct type *type;
10152           sect_offset sect_off = attr->get_ref_die_offset ();
10153
10154           type = get_die_type_at_offset (sect_off, cu->per_cu, cu->per_objfile);
10155           if (type != NULL && type->code () == TYPE_CODE_NAMESPACE)
10156             {
10157               /* This declaration is a global namespace alias.  Add
10158                  a symbol for it whose type is the aliased namespace.  */
10159               new_symbol (die, type, cu);
10160               return 1;
10161             }
10162         }
10163     }
10164
10165   return 0;
10166 }
10167
10168 /* Return the using directives repository (global or local?) to use in the
10169    current context for CU.
10170
10171    For Ada, imported declarations can materialize renamings, which *may* be
10172    global.  However it is impossible (for now?) in DWARF to distinguish
10173    "external" imported declarations and "static" ones.  As all imported
10174    declarations seem to be static in all other languages, make them all CU-wide
10175    global only in Ada.  */
10176
10177 static struct using_direct **
10178 using_directives (struct dwarf2_cu *cu)
10179 {
10180   if (cu->per_cu->lang == language_ada
10181       && cu->get_builder ()->outermost_context_p ())
10182     return cu->get_builder ()->get_global_using_directives ();
10183   else
10184     return cu->get_builder ()->get_local_using_directives ();
10185 }
10186
10187 /* Read the import statement specified by the given die and record it.  */
10188
10189 static void
10190 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10191 {
10192   struct objfile *objfile = cu->per_objfile->objfile;
10193   struct attribute *import_attr;
10194   struct die_info *imported_die, *child_die;
10195   struct dwarf2_cu *imported_cu;
10196   const char *imported_name;
10197   const char *imported_name_prefix;
10198   const char *canonical_name;
10199   const char *import_alias;
10200   const char *imported_declaration = NULL;
10201   const char *import_prefix;
10202   std::vector<const char *> excludes;
10203
10204   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10205   if (import_attr == NULL)
10206     {
10207       complaint (_("Tag '%s' has no DW_AT_import"),
10208                  dwarf_tag_name (die->tag));
10209       return;
10210     }
10211
10212   imported_cu = cu;
10213   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10214   imported_name = dwarf2_name (imported_die, imported_cu);
10215   if (imported_name == NULL)
10216     {
10217       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10218
10219         The import in the following code:
10220         namespace A
10221           {
10222             typedef int B;
10223           }
10224
10225         int main ()
10226           {
10227             using A::B;
10228             B b;
10229             return b;
10230           }
10231
10232         ...
10233          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10234             <52>   DW_AT_decl_file   : 1
10235             <53>   DW_AT_decl_line   : 6
10236             <54>   DW_AT_import      : <0x75>
10237          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10238             <59>   DW_AT_name        : B
10239             <5b>   DW_AT_decl_file   : 1
10240             <5c>   DW_AT_decl_line   : 2
10241             <5d>   DW_AT_type        : <0x6e>
10242         ...
10243          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10244             <76>   DW_AT_byte_size   : 4
10245             <77>   DW_AT_encoding    : 5        (signed)
10246
10247         imports the wrong die ( 0x75 instead of 0x58 ).
10248         This case will be ignored until the gcc bug is fixed.  */
10249       return;
10250     }
10251
10252   /* Figure out the local name after import.  */
10253   import_alias = dwarf2_name (die, cu);
10254
10255   /* Figure out where the statement is being imported to.  */
10256   import_prefix = determine_prefix (die, cu);
10257
10258   /* Figure out what the scope of the imported die is and prepend it
10259      to the name of the imported die.  */
10260   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10261
10262   if (imported_die->tag != DW_TAG_namespace
10263       && imported_die->tag != DW_TAG_module)
10264     {
10265       imported_declaration = imported_name;
10266       canonical_name = imported_name_prefix;
10267     }
10268   else if (strlen (imported_name_prefix) > 0)
10269     canonical_name = obconcat (&objfile->objfile_obstack,
10270                                imported_name_prefix,
10271                                (cu->per_cu->lang == language_d
10272                                 ? "."
10273                                 : "::"),
10274                                imported_name, (char *) NULL);
10275   else
10276     canonical_name = imported_name;
10277
10278   if (die->tag == DW_TAG_imported_module
10279       && cu->per_cu->lang == language_fortran)
10280     for (child_die = die->child; child_die && child_die->tag;
10281          child_die = child_die->sibling)
10282       {
10283         /* DWARF-4: A Fortran use statement with a “rename list” may be
10284            represented by an imported module entry with an import attribute
10285            referring to the module and owned entries corresponding to those
10286            entities that are renamed as part of being imported.  */
10287
10288         if (child_die->tag != DW_TAG_imported_declaration)
10289           {
10290             complaint (_("child DW_TAG_imported_declaration expected "
10291                          "- DIE at %s [in module %s]"),
10292                        sect_offset_str (child_die->sect_off),
10293                        objfile_name (objfile));
10294             continue;
10295           }
10296
10297         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10298         if (import_attr == NULL)
10299           {
10300             complaint (_("Tag '%s' has no DW_AT_import"),
10301                        dwarf_tag_name (child_die->tag));
10302             continue;
10303           }
10304
10305         imported_cu = cu;
10306         imported_die = follow_die_ref_or_sig (child_die, import_attr,
10307                                               &imported_cu);
10308         imported_name = dwarf2_name (imported_die, imported_cu);
10309         if (imported_name == NULL)
10310           {
10311             complaint (_("child DW_TAG_imported_declaration has unknown "
10312                          "imported name - DIE at %s [in module %s]"),
10313                        sect_offset_str (child_die->sect_off),
10314                        objfile_name (objfile));
10315             continue;
10316           }
10317
10318         excludes.push_back (imported_name);
10319
10320         process_die (child_die, cu);
10321       }
10322
10323   add_using_directive (using_directives (cu),
10324                        import_prefix,
10325                        canonical_name,
10326                        import_alias,
10327                        imported_declaration,
10328                        excludes,
10329                        0,
10330                        &objfile->objfile_obstack);
10331 }
10332
10333 /* ICC<14 does not output the required DW_AT_declaration on incomplete
10334    types, but gives them a size of zero.  Starting with version 14,
10335    ICC is compatible with GCC.  */
10336
10337 static bool
10338 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
10339 {
10340   if (!cu->checked_producer)
10341     check_producer (cu);
10342
10343   return cu->producer_is_icc_lt_14;
10344 }
10345
10346 /* ICC generates a DW_AT_type for C void functions.  This was observed on
10347    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
10348    which says that void functions should not have a DW_AT_type.  */
10349
10350 static bool
10351 producer_is_icc (struct dwarf2_cu *cu)
10352 {
10353   if (!cu->checked_producer)
10354     check_producer (cu);
10355
10356   return cu->producer_is_icc;
10357 }
10358
10359 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
10360    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
10361    this, it was first present in GCC release 4.3.0.  */
10362
10363 static bool
10364 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
10365 {
10366   if (!cu->checked_producer)
10367     check_producer (cu);
10368
10369   return cu->producer_is_gcc_lt_4_3;
10370 }
10371
10372 static file_and_directory
10373 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
10374 {
10375   file_and_directory res;
10376
10377   /* Find the filename.  Do not use dwarf2_name here, since the filename
10378      is not a source language identifier.  */
10379   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
10380   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
10381
10382   if (res.comp_dir == NULL
10383       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
10384       && IS_ABSOLUTE_PATH (res.name))
10385     {
10386       std::string comp_dir_storage = ldirname (res.name);
10387       if (!comp_dir_storage.empty ())
10388         res.comp_dir
10389           = cu->per_objfile->objfile->intern (comp_dir_storage.c_str ());
10390     }
10391   if (res.comp_dir != NULL)
10392     {
10393       /* Irix 6.2 native cc prepends <machine>.: to the compilation
10394          directory, get rid of it.  */
10395       const char *cp = strchr (res.comp_dir, ':');
10396
10397       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
10398         res.comp_dir = cp + 1;
10399     }
10400
10401   if (res.name == NULL)
10402     res.name = "<unknown>";
10403
10404   return res;
10405 }
10406
10407 /* Handle DW_AT_stmt_list for a compilation unit.
10408    DIE is the DW_TAG_compile_unit die for CU.
10409    COMP_DIR is the compilation directory.  LOWPC is passed to
10410    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
10411
10412 static void
10413 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
10414                         const file_and_directory &fnd, CORE_ADDR lowpc) /* ARI: editCase function */
10415 {
10416   dwarf2_per_objfile *per_objfile = cu->per_objfile;
10417   struct attribute *attr;
10418   struct line_header line_header_local;
10419   hashval_t line_header_local_hash;
10420   void **slot;
10421   int decode_mapping;
10422
10423   gdb_assert (! cu->per_cu->is_debug_types);
10424
10425   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10426   if (attr == NULL || !attr->form_is_unsigned ())
10427     return;
10428
10429   sect_offset line_offset = (sect_offset) attr->as_unsigned ();
10430
10431   /* The line header hash table is only created if needed (it exists to
10432      prevent redundant reading of the line table for partial_units).
10433      If we're given a partial_unit, we'll need it.  If we're given a
10434      compile_unit, then use the line header hash table if it's already
10435      created, but don't create one just yet.  */
10436
10437   if (per_objfile->line_header_hash == NULL
10438       && die->tag == DW_TAG_partial_unit)
10439     {
10440       per_objfile->line_header_hash
10441         .reset (htab_create_alloc (127, line_header_hash_voidp,
10442                                    line_header_eq_voidp,
10443                                    htab_delete_entry<line_header>,
10444                                    xcalloc, xfree));
10445     }
10446
10447   line_header_local.sect_off = line_offset;
10448   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
10449   line_header_local_hash = line_header_hash (&line_header_local);
10450   if (per_objfile->line_header_hash != NULL)
10451     {
10452       slot = htab_find_slot_with_hash (per_objfile->line_header_hash.get (),
10453                                        &line_header_local,
10454                                        line_header_local_hash, NO_INSERT);
10455
10456       /* For DW_TAG_compile_unit we need info like symtab::linetable which
10457          is not present in *SLOT (since if there is something in *SLOT then
10458          it will be for a partial_unit).  */
10459       if (die->tag == DW_TAG_partial_unit && slot != NULL)
10460         {
10461           gdb_assert (*slot != NULL);
10462           cu->line_header = (struct line_header *) *slot;
10463           return;
10464         }
10465     }
10466
10467   /* dwarf_decode_line_header does not yet provide sufficient information.
10468      We always have to call also dwarf_decode_lines for it.  */
10469   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
10470   if (lh == NULL)
10471     return;
10472
10473   cu->line_header = lh.release ();
10474   cu->line_header_die_owner = die;
10475
10476   if (per_objfile->line_header_hash == NULL)
10477     slot = NULL;
10478   else
10479     {
10480       slot = htab_find_slot_with_hash (per_objfile->line_header_hash.get (),
10481                                        &line_header_local,
10482                                        line_header_local_hash, INSERT);
10483       gdb_assert (slot != NULL);
10484     }
10485   if (slot != NULL && *slot == NULL)
10486     {
10487       /* This newly decoded line number information unit will be owned
10488          by line_header_hash hash table.  */
10489       *slot = cu->line_header;
10490       cu->line_header_die_owner = NULL;
10491     }
10492   else
10493     {
10494       /* We cannot free any current entry in (*slot) as that struct line_header
10495          may be already used by multiple CUs.  Create only temporary decoded
10496          line_header for this CU - it may happen at most once for each line
10497          number information unit.  And if we're not using line_header_hash
10498          then this is what we want as well.  */
10499       gdb_assert (die->tag != DW_TAG_partial_unit);
10500     }
10501   decode_mapping = (die->tag != DW_TAG_partial_unit);
10502   dwarf_decode_lines (cu->line_header, fnd, cu, nullptr, lowpc,
10503                       decode_mapping);
10504
10505 }
10506
10507 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
10508
10509 static void
10510 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
10511 {
10512   dwarf2_per_objfile *per_objfile = cu->per_objfile;
10513   struct objfile *objfile = per_objfile->objfile;
10514   struct gdbarch *gdbarch = objfile->arch ();
10515   CORE_ADDR lowpc = ((CORE_ADDR) -1);
10516   CORE_ADDR highpc = ((CORE_ADDR) 0);
10517   struct attribute *attr;
10518   struct die_info *child_die;
10519   CORE_ADDR baseaddr;
10520
10521   prepare_one_comp_unit (cu, die, cu->per_cu->lang);
10522   baseaddr = objfile->text_section_offset ();
10523
10524   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
10525
10526   /* If we didn't find a lowpc, set it to highpc to avoid complaints
10527      from finish_block.  */
10528   if (lowpc == ((CORE_ADDR) -1))
10529     lowpc = highpc;
10530   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
10531
10532   file_and_directory fnd = find_file_and_directory (die, cu);
10533
10534   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
10535
10536   gdb_assert (per_objfile->sym_cu == nullptr);
10537   scoped_restore restore_sym_cu
10538     = make_scoped_restore (&per_objfile->sym_cu, cu);
10539
10540   /* Decode line number information if present.  We do this before
10541      processing child DIEs, so that the line header table is available
10542      for DW_AT_decl_file.  */
10543   handle_DW_AT_stmt_list (die, cu, fnd, lowpc);
10544
10545   /* Process all dies in compilation unit.  */
10546   if (die->child != NULL)
10547     {
10548       child_die = die->child;
10549       while (child_die && child_die->tag)
10550         {
10551           process_die (child_die, cu);
10552           child_die = child_die->sibling;
10553         }
10554     }
10555   per_objfile->sym_cu = nullptr;
10556
10557   /* Decode macro information, if present.  Dwarf 2 macro information
10558      refers to information in the line number info statement program
10559      header, so we can only read it if we've read the header
10560      successfully.  */
10561   attr = dwarf2_attr (die, DW_AT_macros, cu);
10562   if (attr == NULL)
10563     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
10564   if (attr != nullptr && attr->form_is_unsigned () && cu->line_header)
10565     {
10566       if (dwarf2_attr (die, DW_AT_macro_info, cu))
10567         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
10568
10569       dwarf_decode_macros (cu, attr->as_unsigned (), 1);
10570     }
10571   else
10572     {
10573       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
10574       if (attr != nullptr && attr->form_is_unsigned () && cu->line_header)
10575         {
10576           unsigned int macro_offset = attr->as_unsigned ();
10577
10578           dwarf_decode_macros (cu, macro_offset, 0);
10579         }
10580     }
10581 }
10582
10583 void
10584 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
10585 {
10586   struct type_unit_group *tu_group;
10587   int first_time;
10588   struct attribute *attr;
10589   unsigned int i;
10590   struct signatured_type *sig_type;
10591
10592   gdb_assert (per_cu->is_debug_types);
10593   sig_type = (struct signatured_type *) per_cu;
10594
10595   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
10596
10597   /* If we're using .gdb_index (includes -readnow) then
10598      per_cu->type_unit_group may not have been set up yet.  */
10599   if (sig_type->type_unit_group == NULL)
10600     sig_type->type_unit_group = get_type_unit_group (this, attr);
10601   tu_group = sig_type->type_unit_group;
10602
10603   /* If we've already processed this stmt_list there's no real need to
10604      do it again, we could fake it and just recreate the part we need
10605      (file name,index -> symtab mapping).  If data shows this optimization
10606      is useful we can do it then.  */
10607   type_unit_group_unshareable *tug_unshare
10608     = per_objfile->get_type_unit_group_unshareable (tu_group);
10609   first_time = tug_unshare->compunit_symtab == NULL;
10610
10611   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
10612      debug info.  */
10613   line_header_up lh;
10614   if (attr != NULL && attr->form_is_unsigned ())
10615     {
10616       sect_offset line_offset = (sect_offset) attr->as_unsigned ();
10617       lh = dwarf_decode_line_header (line_offset, this);
10618     }
10619   if (lh == NULL)
10620     {
10621       if (first_time)
10622         start_symtab ("", NULL, 0);
10623       else
10624         {
10625           gdb_assert (tug_unshare->symtabs == NULL);
10626           gdb_assert (m_builder == nullptr);
10627           struct compunit_symtab *cust = tug_unshare->compunit_symtab;
10628           m_builder.reset (new struct buildsym_compunit
10629                            (COMPUNIT_OBJFILE (cust), "",
10630                             COMPUNIT_DIRNAME (cust),
10631                             compunit_language (cust),
10632                             0, cust));
10633           list_in_scope = get_builder ()->get_file_symbols ();
10634         }
10635       return;
10636     }
10637
10638   line_header = lh.release ();
10639   line_header_die_owner = die;
10640
10641   if (first_time)
10642     {
10643       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
10644
10645       /* Note: We don't assign tu_group->compunit_symtab yet because we're
10646          still initializing it, and our caller (a few levels up)
10647          process_full_type_unit still needs to know if this is the first
10648          time.  */
10649
10650       tug_unshare->symtabs
10651         = XOBNEWVEC (&COMPUNIT_OBJFILE (cust)->objfile_obstack,
10652                      struct symtab *, line_header->file_names_size ());
10653
10654       auto &file_names = line_header->file_names ();
10655       for (i = 0; i < file_names.size (); ++i)
10656         {
10657           file_entry &fe = file_names[i];
10658           dwarf2_start_subfile (this, fe.name,
10659                                 fe.include_dir (line_header));
10660           buildsym_compunit *b = get_builder ();
10661           if (b->get_current_subfile ()->symtab == NULL)
10662             {
10663               /* NOTE: start_subfile will recognize when it's been
10664                  passed a file it has already seen.  So we can't
10665                  assume there's a simple mapping from
10666                  cu->line_header->file_names to subfiles, plus
10667                  cu->line_header->file_names may contain dups.  */
10668               b->get_current_subfile ()->symtab
10669                 = allocate_symtab (cust, b->get_current_subfile ()->name);
10670             }
10671
10672           fe.symtab = b->get_current_subfile ()->symtab;
10673           tug_unshare->symtabs[i] = fe.symtab;
10674         }
10675     }
10676   else
10677     {
10678       gdb_assert (m_builder == nullptr);
10679       struct compunit_symtab *cust = tug_unshare->compunit_symtab;
10680       m_builder.reset (new struct buildsym_compunit
10681                        (COMPUNIT_OBJFILE (cust), "",
10682                         COMPUNIT_DIRNAME (cust),
10683                         compunit_language (cust),
10684                         0, cust));
10685       list_in_scope = get_builder ()->get_file_symbols ();
10686
10687       auto &file_names = line_header->file_names ();
10688       for (i = 0; i < file_names.size (); ++i)
10689         {
10690           file_entry &fe = file_names[i];
10691           fe.symtab = tug_unshare->symtabs[i];
10692         }
10693     }
10694
10695   /* The main symtab is allocated last.  Type units don't have DW_AT_name
10696      so they don't have a "real" (so to speak) symtab anyway.
10697      There is later code that will assign the main symtab to all symbols
10698      that don't have one.  We need to handle the case of a symbol with a
10699      missing symtab (DW_AT_decl_file) anyway.  */
10700 }
10701
10702 /* Process DW_TAG_type_unit.
10703    For TUs we want to skip the first top level sibling if it's not the
10704    actual type being defined by this TU.  In this case the first top
10705    level sibling is there to provide context only.  */
10706
10707 static void
10708 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
10709 {
10710   struct die_info *child_die;
10711
10712   prepare_one_comp_unit (cu, die, language_minimal);
10713
10714   /* Initialize (or reinitialize) the machinery for building symtabs.
10715      We do this before processing child DIEs, so that the line header table
10716      is available for DW_AT_decl_file.  */
10717   cu->setup_type_unit_groups (die);
10718
10719   if (die->child != NULL)
10720     {
10721       child_die = die->child;
10722       while (child_die && child_die->tag)
10723         {
10724           process_die (child_die, cu);
10725           child_die = child_die->sibling;
10726         }
10727     }
10728 }
10729 \f
10730 /* DWO/DWP files.
10731
10732    http://gcc.gnu.org/wiki/DebugFission
10733    http://gcc.gnu.org/wiki/DebugFissionDWP
10734
10735    To simplify handling of both DWO files ("object" files with the DWARF info)
10736    and DWP files (a file with the DWOs packaged up into one file), we treat
10737    DWP files as having a collection of virtual DWO files.  */
10738
10739 static hashval_t
10740 hash_dwo_file (const void *item)
10741 {
10742   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10743   hashval_t hash;
10744
10745   hash = htab_hash_string (dwo_file->dwo_name);
10746   if (dwo_file->comp_dir != NULL)
10747     hash += htab_hash_string (dwo_file->comp_dir);
10748   return hash;
10749 }
10750
10751 static int
10752 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10753 {
10754   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10755   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10756
10757   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10758     return 0;
10759   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10760     return lhs->comp_dir == rhs->comp_dir;
10761   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10762 }
10763
10764 /* Allocate a hash table for DWO files.  */
10765
10766 static htab_up
10767 allocate_dwo_file_hash_table ()
10768 {
10769   return htab_up (htab_create_alloc (41,
10770                                      hash_dwo_file,
10771                                      eq_dwo_file,
10772                                      htab_delete_entry<dwo_file>,
10773                                      xcalloc, xfree));
10774 }
10775
10776 /* Lookup DWO file DWO_NAME.  */
10777
10778 static void **
10779 lookup_dwo_file_slot (dwarf2_per_objfile *per_objfile,
10780                       const char *dwo_name,
10781                       const char *comp_dir)
10782 {
10783   struct dwo_file find_entry;
10784   void **slot;
10785
10786   if (per_objfile->per_bfd->dwo_files == NULL)
10787     per_objfile->per_bfd->dwo_files = allocate_dwo_file_hash_table ();
10788
10789   find_entry.dwo_name = dwo_name;
10790   find_entry.comp_dir = comp_dir;
10791   slot = htab_find_slot (per_objfile->per_bfd->dwo_files.get (), &find_entry,
10792                          INSERT);
10793
10794   return slot;
10795 }
10796
10797 static hashval_t
10798 hash_dwo_unit (const void *item)
10799 {
10800   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10801
10802   /* This drops the top 32 bits of the id, but is ok for a hash.  */
10803   return dwo_unit->signature;
10804 }
10805
10806 static int
10807 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
10808 {
10809   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
10810   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
10811
10812   /* The signature is assumed to be unique within the DWO file.
10813      So while object file CU dwo_id's always have the value zero,
10814      that's OK, assuming each object file DWO file has only one CU,
10815      and that's the rule for now.  */
10816   return lhs->signature == rhs->signature;
10817 }
10818
10819 /* Allocate a hash table for DWO CUs,TUs.
10820    There is one of these tables for each of CUs,TUs for each DWO file.  */
10821
10822 static htab_up
10823 allocate_dwo_unit_table ()
10824 {
10825   /* Start out with a pretty small number.
10826      Generally DWO files contain only one CU and maybe some TUs.  */
10827   return htab_up (htab_create_alloc (3,
10828                                      hash_dwo_unit,
10829                                      eq_dwo_unit,
10830                                      NULL, xcalloc, xfree));
10831 }
10832
10833 /* die_reader_func for create_dwo_cu.  */
10834
10835 static void
10836 create_dwo_cu_reader (const struct die_reader_specs *reader,
10837                       const gdb_byte *info_ptr,
10838                       struct die_info *comp_unit_die,
10839                       struct dwo_file *dwo_file,
10840                       struct dwo_unit *dwo_unit)
10841 {
10842   struct dwarf2_cu *cu = reader->cu;
10843   sect_offset sect_off = cu->per_cu->sect_off;
10844   struct dwarf2_section_info *section = cu->per_cu->section;
10845
10846   gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
10847   if (!signature.has_value ())
10848     {
10849       complaint (_("Dwarf Error: debug entry at offset %s is missing"
10850                    " its dwo_id [in module %s]"),
10851                  sect_offset_str (sect_off), dwo_file->dwo_name);
10852       return;
10853     }
10854
10855   dwo_unit->dwo_file = dwo_file;
10856   dwo_unit->signature = *signature;
10857   dwo_unit->section = section;
10858   dwo_unit->sect_off = sect_off;
10859   dwo_unit->length = cu->per_cu->length;
10860
10861   dwarf_read_debug_printf ("  offset %s, dwo_id %s",
10862                            sect_offset_str (sect_off),
10863                            hex_string (dwo_unit->signature));
10864 }
10865
10866 /* Create the dwo_units for the CUs in a DWO_FILE.
10867    Note: This function processes DWO files only, not DWP files.  */
10868
10869 static void
10870 create_cus_hash_table (dwarf2_per_objfile *per_objfile,
10871                        dwarf2_cu *cu, struct dwo_file &dwo_file,
10872                        dwarf2_section_info &section, htab_up &cus_htab)
10873 {
10874   struct objfile *objfile = per_objfile->objfile;
10875   dwarf2_per_bfd *per_bfd = per_objfile->per_bfd;
10876   const gdb_byte *info_ptr, *end_ptr;
10877
10878   section.read (objfile);
10879   info_ptr = section.buffer;
10880
10881   if (info_ptr == NULL)
10882     return;
10883
10884   dwarf_read_debug_printf ("Reading %s for %s:",
10885                            section.get_name (),
10886                            section.get_file_name ());
10887
10888   end_ptr = info_ptr + section.size;
10889   while (info_ptr < end_ptr)
10890     {
10891       struct dwarf2_per_cu_data per_cu;
10892       struct dwo_unit read_unit {};
10893       struct dwo_unit *dwo_unit;
10894       void **slot;
10895       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
10896
10897       per_cu.per_bfd = per_bfd;
10898       per_cu.is_debug_types = 0;
10899       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
10900       per_cu.section = &section;
10901
10902       cutu_reader reader (&per_cu, per_objfile, cu, &dwo_file);
10903       if (!reader.dummy_p)
10904         create_dwo_cu_reader (&reader, reader.info_ptr, reader.comp_unit_die,
10905                               &dwo_file, &read_unit);
10906       info_ptr += per_cu.length;
10907
10908       // If the unit could not be parsed, skip it.
10909       if (read_unit.dwo_file == NULL)
10910         continue;
10911
10912       if (cus_htab == NULL)
10913         cus_htab = allocate_dwo_unit_table ();
10914
10915       dwo_unit = OBSTACK_ZALLOC (&per_bfd->obstack,
10916                                  struct dwo_unit);
10917       *dwo_unit = read_unit;
10918       slot = htab_find_slot (cus_htab.get (), dwo_unit, INSERT);
10919       gdb_assert (slot != NULL);
10920       if (*slot != NULL)
10921         {
10922           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
10923           sect_offset dup_sect_off = dup_cu->sect_off;
10924
10925           complaint (_("debug cu entry at offset %s is duplicate to"
10926                        " the entry at offset %s, signature %s"),
10927                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
10928                      hex_string (dwo_unit->signature));
10929         }
10930       *slot = (void *)dwo_unit;
10931     }
10932 }
10933
10934 /* DWP file .debug_{cu,tu}_index section format:
10935    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
10936    [ref: http://dwarfstd.org/doc/DWARF5.pdf, sect 7.3.5 "DWARF Package Files"]
10937
10938    DWP Versions 1 & 2 are older, pre-standard format versions.  The first
10939    officially standard DWP format was published with DWARF v5 and is called
10940    Version 5.  There are no versions 3 or 4.
10941
10942    DWP Version 1:
10943
10944    Both index sections have the same format, and serve to map a 64-bit
10945    signature to a set of section numbers.  Each section begins with a header,
10946    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
10947    indexes, and a pool of 32-bit section numbers.  The index sections will be
10948    aligned at 8-byte boundaries in the file.
10949
10950    The index section header consists of:
10951
10952     V, 32 bit version number
10953     -, 32 bits unused
10954     N, 32 bit number of compilation units or type units in the index
10955     M, 32 bit number of slots in the hash table
10956
10957    Numbers are recorded using the byte order of the application binary.
10958
10959    The hash table begins at offset 16 in the section, and consists of an array
10960    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
10961    order of the application binary).  Unused slots in the hash table are 0.
10962    (We rely on the extreme unlikeliness of a signature being exactly 0.)
10963
10964    The parallel table begins immediately after the hash table
10965    (at offset 16 + 8 * M from the beginning of the section), and consists of an
10966    array of 32-bit indexes (using the byte order of the application binary),
10967    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
10968    table contains a 32-bit index into the pool of section numbers.  For unused
10969    hash table slots, the corresponding entry in the parallel table will be 0.
10970
10971    The pool of section numbers begins immediately following the hash table
10972    (at offset 16 + 12 * M from the beginning of the section).  The pool of
10973    section numbers consists of an array of 32-bit words (using the byte order
10974    of the application binary).  Each item in the array is indexed starting
10975    from 0.  The hash table entry provides the index of the first section
10976    number in the set.  Additional section numbers in the set follow, and the
10977    set is terminated by a 0 entry (section number 0 is not used in ELF).
10978
10979    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
10980    section must be the first entry in the set, and the .debug_abbrev.dwo must
10981    be the second entry. Other members of the set may follow in any order.
10982
10983    ---
10984
10985    DWP Versions 2 and 5:
10986
10987    DWP Versions 2 and 5 combine all the .debug_info, etc. sections into one,
10988    and the entries in the index tables are now offsets into these sections.
10989    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
10990    section.
10991
10992    Index Section Contents:
10993     Header
10994     Hash Table of Signatures   dwp_hash_table.hash_table
10995     Parallel Table of Indices  dwp_hash_table.unit_table
10996     Table of Section Offsets   dwp_hash_table.{v2|v5}.{section_ids,offsets}
10997     Table of Section Sizes     dwp_hash_table.{v2|v5}.sizes
10998
10999    The index section header consists of:
11000
11001     V, 32 bit version number
11002     L, 32 bit number of columns in the table of section offsets
11003     N, 32 bit number of compilation units or type units in the index
11004     M, 32 bit number of slots in the hash table
11005
11006    Numbers are recorded using the byte order of the application binary.
11007
11008    The hash table has the same format as version 1.
11009    The parallel table of indices has the same format as version 1,
11010    except that the entries are origin-1 indices into the table of sections
11011    offsets and the table of section sizes.
11012
11013    The table of offsets begins immediately following the parallel table
11014    (at offset 16 + 12 * M from the beginning of the section).  The table is
11015    a two-dimensional array of 32-bit words (using the byte order of the
11016    application binary), with L columns and N+1 rows, in row-major order.
11017    Each row in the array is indexed starting from 0.  The first row provides
11018    a key to the remaining rows: each column in this row provides an identifier
11019    for a debug section, and the offsets in the same column of subsequent rows
11020    refer to that section.  The section identifiers for Version 2 are:
11021
11022     DW_SECT_INFO         1  .debug_info.dwo
11023     DW_SECT_TYPES        2  .debug_types.dwo
11024     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11025     DW_SECT_LINE         4  .debug_line.dwo
11026     DW_SECT_LOC          5  .debug_loc.dwo
11027     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11028     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11029     DW_SECT_MACRO        8  .debug_macro.dwo
11030
11031    The section identifiers for Version 5 are:
11032
11033     DW_SECT_INFO_V5         1  .debug_info.dwo
11034     DW_SECT_RESERVED_V5     2  --
11035     DW_SECT_ABBREV_V5       3  .debug_abbrev.dwo
11036     DW_SECT_LINE_V5         4  .debug_line.dwo
11037     DW_SECT_LOCLISTS_V5     5  .debug_loclists.dwo
11038     DW_SECT_STR_OFFSETS_V5  6  .debug_str_offsets.dwo
11039     DW_SECT_MACRO_V5        7  .debug_macro.dwo
11040     DW_SECT_RNGLISTS_V5     8  .debug_rnglists.dwo
11041
11042    The offsets provided by the CU and TU index sections are the base offsets
11043    for the contributions made by each CU or TU to the corresponding section
11044    in the package file.  Each CU and TU header contains an abbrev_offset
11045    field, used to find the abbreviations table for that CU or TU within the
11046    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11047    be interpreted as relative to the base offset given in the index section.
11048    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11049    should be interpreted as relative to the base offset for .debug_line.dwo,
11050    and offsets into other debug sections obtained from DWARF attributes should
11051    also be interpreted as relative to the corresponding base offset.
11052
11053    The table of sizes begins immediately following the table of offsets.
11054    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11055    with L columns and N rows, in row-major order.  Each row in the array is
11056    indexed starting from 1 (row 0 is shared by the two tables).
11057
11058    ---
11059
11060    Hash table lookup is handled the same in version 1 and 2:
11061
11062    We assume that N and M will not exceed 2^32 - 1.
11063    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11064
11065    Given a 64-bit compilation unit signature or a type signature S, an entry
11066    in the hash table is located as follows:
11067
11068    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11069       the low-order k bits all set to 1.
11070
11071    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11072
11073    3) If the hash table entry at index H matches the signature, use that
11074       entry.  If the hash table entry at index H is unused (all zeroes),
11075       terminate the search: the signature is not present in the table.
11076
11077    4) Let H = (H + H') modulo M. Repeat at Step 3.
11078
11079    Because M > N and H' and M are relatively prime, the search is guaranteed
11080    to stop at an unused slot or find the match.  */
11081
11082 /* Create a hash table to map DWO IDs to their CU/TU entry in
11083    .debug_{info,types}.dwo in DWP_FILE.
11084    Returns NULL if there isn't one.
11085    Note: This function processes DWP files only, not DWO files.  */
11086
11087 static struct dwp_hash_table *
11088 create_dwp_hash_table (dwarf2_per_objfile *per_objfile,
11089                        struct dwp_file *dwp_file, int is_debug_types)
11090 {
11091   struct objfile *objfile = per_objfile->objfile;
11092   bfd *dbfd = dwp_file->dbfd.get ();
11093   const gdb_byte *index_ptr, *index_end;
11094   struct dwarf2_section_info *index;
11095   uint32_t version, nr_columns, nr_units, nr_slots;
11096   struct dwp_hash_table *htab;
11097
11098   if (is_debug_types)
11099     index = &dwp_file->sections.tu_index;
11100   else
11101     index = &dwp_file->sections.cu_index;
11102
11103   if (index->empty ())
11104     return NULL;
11105   index->read (objfile);
11106
11107   index_ptr = index->buffer;
11108   index_end = index_ptr + index->size;
11109
11110   /* For Version 5, the version is really 2 bytes of data & 2 bytes of padding.
11111      For now it's safe to just read 4 bytes (particularly as it's difficult to
11112      tell if you're dealing with Version 5 before you've read the version).   */
11113   version = read_4_bytes (dbfd, index_ptr);
11114   index_ptr += 4;
11115   if (version == 2 || version == 5)
11116     nr_columns = read_4_bytes (dbfd, index_ptr);
11117   else
11118     nr_columns = 0;
11119   index_ptr += 4;
11120   nr_units = read_4_bytes (dbfd, index_ptr);
11121   index_ptr += 4;
11122   nr_slots = read_4_bytes (dbfd, index_ptr);
11123   index_ptr += 4;
11124
11125   if (version != 1 && version != 2 && version != 5)
11126     {
11127       error (_("Dwarf Error: unsupported DWP file version (%s)"
11128                " [in module %s]"),
11129              pulongest (version), dwp_file->name);
11130     }
11131   if (nr_slots != (nr_slots & -nr_slots))
11132     {
11133       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
11134                " is not power of 2 [in module %s]"),
11135              pulongest (nr_slots), dwp_file->name);
11136     }
11137
11138   htab = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwp_hash_table);
11139   htab->version = version;
11140   htab->nr_columns = nr_columns;
11141   htab->nr_units = nr_units;
11142   htab->nr_slots = nr_slots;
11143   htab->hash_table = index_ptr;
11144   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
11145
11146   /* Exit early if the table is empty.  */
11147   if (nr_slots == 0 || nr_units == 0
11148       || (version == 2 && nr_columns == 0)
11149       || (version == 5 && nr_columns == 0))
11150     {
11151       /* All must be zero.  */
11152       if (nr_slots != 0 || nr_units != 0
11153           || (version == 2 && nr_columns != 0)
11154           || (version == 5 && nr_columns != 0))
11155         {
11156           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
11157                        " all zero [in modules %s]"),
11158                      dwp_file->name);
11159         }
11160       return htab;
11161     }
11162
11163   if (version == 1)
11164     {
11165       htab->section_pool.v1.indices =
11166         htab->unit_table + sizeof (uint32_t) * nr_slots;
11167       /* It's harder to decide whether the section is too small in v1.
11168          V1 is deprecated anyway so we punt.  */
11169     }
11170   else if (version == 2)
11171     {
11172       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11173       int *ids = htab->section_pool.v2.section_ids;
11174       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
11175       /* Reverse map for error checking.  */
11176       int ids_seen[DW_SECT_MAX + 1];
11177       int i;
11178
11179       if (nr_columns < 2)
11180         {
11181           error (_("Dwarf Error: bad DWP hash table, too few columns"
11182                    " in section table [in module %s]"),
11183                  dwp_file->name);
11184         }
11185       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11186         {
11187           error (_("Dwarf Error: bad DWP hash table, too many columns"
11188                    " in section table [in module %s]"),
11189                  dwp_file->name);
11190         }
11191       memset (ids, 255, sizeof_ids);
11192       memset (ids_seen, 255, sizeof (ids_seen));
11193       for (i = 0; i < nr_columns; ++i)
11194         {
11195           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11196
11197           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11198             {
11199               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11200                        " in section table [in module %s]"),
11201                      id, dwp_file->name);
11202             }
11203           if (ids_seen[id] != -1)
11204             {
11205               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11206                        " id %d in section table [in module %s]"),
11207                      id, dwp_file->name);
11208             }
11209           ids_seen[id] = i;
11210           ids[i] = id;
11211         }
11212       /* Must have exactly one info or types section.  */
11213       if (((ids_seen[DW_SECT_INFO] != -1)
11214            + (ids_seen[DW_SECT_TYPES] != -1))
11215           != 1)
11216         {
11217           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11218                    " DWO info/types section [in module %s]"),
11219                  dwp_file->name);
11220         }
11221       /* Must have an abbrev section.  */
11222       if (ids_seen[DW_SECT_ABBREV] == -1)
11223         {
11224           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11225                    " section [in module %s]"),
11226                  dwp_file->name);
11227         }
11228       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11229       htab->section_pool.v2.sizes =
11230         htab->section_pool.v2.offsets + (sizeof (uint32_t)
11231                                          * nr_units * nr_columns);
11232       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11233                                           * nr_units * nr_columns))
11234           > index_end)
11235         {
11236           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11237                    " [in module %s]"),
11238                  dwp_file->name);
11239         }
11240     }
11241   else /* version == 5  */
11242     {
11243       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11244       int *ids = htab->section_pool.v5.section_ids;
11245       size_t sizeof_ids = sizeof (htab->section_pool.v5.section_ids);
11246       /* Reverse map for error checking.  */
11247       int ids_seen[DW_SECT_MAX_V5 + 1];
11248
11249       if (nr_columns < 2)
11250         {
11251           error (_("Dwarf Error: bad DWP hash table, too few columns"
11252                    " in section table [in module %s]"),
11253                  dwp_file->name);
11254         }
11255       if (nr_columns > MAX_NR_V5_DWO_SECTIONS)
11256         {
11257           error (_("Dwarf Error: bad DWP hash table, too many columns"
11258                    " in section table [in module %s]"),
11259                  dwp_file->name);
11260         }
11261       memset (ids, 255, sizeof_ids);
11262       memset (ids_seen, 255, sizeof (ids_seen));
11263       for (int i = 0; i < nr_columns; ++i)
11264         {
11265           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11266
11267           if (id < DW_SECT_MIN || id > DW_SECT_MAX_V5)
11268             {
11269               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11270                        " in section table [in module %s]"),
11271                      id, dwp_file->name);
11272             }
11273           if (ids_seen[id] != -1)
11274             {
11275               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11276                        " id %d in section table [in module %s]"),
11277                      id, dwp_file->name);
11278             }
11279           ids_seen[id] = i;
11280           ids[i] = id;
11281         }
11282       /* Must have seen an info section.  */
11283       if (ids_seen[DW_SECT_INFO_V5] == -1)
11284         {
11285           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11286                    " DWO info/types section [in module %s]"),
11287                  dwp_file->name);
11288         }
11289       /* Must have an abbrev section.  */
11290       if (ids_seen[DW_SECT_ABBREV_V5] == -1)
11291         {
11292           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11293                    " section [in module %s]"),
11294                  dwp_file->name);
11295         }
11296       htab->section_pool.v5.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11297       htab->section_pool.v5.sizes
11298         = htab->section_pool.v5.offsets + (sizeof (uint32_t)
11299                                          * nr_units * nr_columns);
11300       if ((htab->section_pool.v5.sizes + (sizeof (uint32_t)
11301                                           * nr_units * nr_columns))
11302           > index_end)
11303         {
11304           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11305                    " [in module %s]"),
11306                  dwp_file->name);
11307         }
11308     }
11309
11310   return htab;
11311 }
11312
11313 /* Update SECTIONS with the data from SECTP.
11314
11315    This function is like the other "locate" section routines, but in
11316    this context the sections to read comes from the DWP V1 hash table,
11317    not the full ELF section table.
11318
11319    The result is non-zero for success, or zero if an error was found.  */
11320
11321 static int
11322 locate_v1_virtual_dwo_sections (asection *sectp,
11323                                 struct virtual_v1_dwo_sections *sections)
11324 {
11325   const struct dwop_section_names *names = &dwop_section_names;
11326
11327   if (names->abbrev_dwo.matches (sectp->name))
11328     {
11329       /* There can be only one.  */
11330       if (sections->abbrev.s.section != NULL)
11331         return 0;
11332       sections->abbrev.s.section = sectp;
11333       sections->abbrev.size = bfd_section_size (sectp);
11334     }
11335   else if (names->info_dwo.matches (sectp->name)
11336            || names->types_dwo.matches (sectp->name))
11337     {
11338       /* There can be only one.  */
11339       if (sections->info_or_types.s.section != NULL)
11340         return 0;
11341       sections->info_or_types.s.section = sectp;
11342       sections->info_or_types.size = bfd_section_size (sectp);
11343     }
11344   else if (names->line_dwo.matches (sectp->name))
11345     {
11346       /* There can be only one.  */
11347       if (sections->line.s.section != NULL)
11348         return 0;
11349       sections->line.s.section = sectp;
11350       sections->line.size = bfd_section_size (sectp);
11351     }
11352   else if (names->loc_dwo.matches (sectp->name))
11353     {
11354       /* There can be only one.  */
11355       if (sections->loc.s.section != NULL)
11356         return 0;
11357       sections->loc.s.section = sectp;
11358       sections->loc.size = bfd_section_size (sectp);
11359     }
11360   else if (names->macinfo_dwo.matches (sectp->name))
11361     {
11362       /* There can be only one.  */
11363       if (sections->macinfo.s.section != NULL)
11364         return 0;
11365       sections->macinfo.s.section = sectp;
11366       sections->macinfo.size = bfd_section_size (sectp);
11367     }
11368   else if (names->macro_dwo.matches (sectp->name))
11369     {
11370       /* There can be only one.  */
11371       if (sections->macro.s.section != NULL)
11372         return 0;
11373       sections->macro.s.section = sectp;
11374       sections->macro.size = bfd_section_size (sectp);
11375     }
11376   else if (names->str_offsets_dwo.matches (sectp->name))
11377     {
11378       /* There can be only one.  */
11379       if (sections->str_offsets.s.section != NULL)
11380         return 0;
11381       sections->str_offsets.s.section = sectp;
11382       sections->str_offsets.size = bfd_section_size (sectp);
11383     }
11384   else
11385     {
11386       /* No other kind of section is valid.  */
11387       return 0;
11388     }
11389
11390   return 1;
11391 }
11392
11393 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11394    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11395    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11396    This is for DWP version 1 files.  */
11397
11398 static struct dwo_unit *
11399 create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile *per_objfile,
11400                            struct dwp_file *dwp_file,
11401                            uint32_t unit_index,
11402                            const char *comp_dir,
11403                            ULONGEST signature, int is_debug_types)
11404 {
11405   const struct dwp_hash_table *dwp_htab =
11406     is_debug_types ? dwp_file->tus : dwp_file->cus;
11407   bfd *dbfd = dwp_file->dbfd.get ();
11408   const char *kind = is_debug_types ? "TU" : "CU";
11409   struct dwo_file *dwo_file;
11410   struct dwo_unit *dwo_unit;
11411   struct virtual_v1_dwo_sections sections;
11412   void **dwo_file_slot;
11413   int i;
11414
11415   gdb_assert (dwp_file->version == 1);
11416
11417   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V1 file: %s",
11418                            kind, pulongest (unit_index), hex_string (signature),
11419                            dwp_file->name);
11420
11421   /* Fetch the sections of this DWO unit.
11422      Put a limit on the number of sections we look for so that bad data
11423      doesn't cause us to loop forever.  */
11424
11425 #define MAX_NR_V1_DWO_SECTIONS \
11426   (1 /* .debug_info or .debug_types */ \
11427    + 1 /* .debug_abbrev */ \
11428    + 1 /* .debug_line */ \
11429    + 1 /* .debug_loc */ \
11430    + 1 /* .debug_str_offsets */ \
11431    + 1 /* .debug_macro or .debug_macinfo */ \
11432    + 1 /* trailing zero */)
11433
11434   memset (&sections, 0, sizeof (sections));
11435
11436   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
11437     {
11438       asection *sectp;
11439       uint32_t section_nr =
11440         read_4_bytes (dbfd,
11441                       dwp_htab->section_pool.v1.indices
11442                       + (unit_index + i) * sizeof (uint32_t));
11443
11444       if (section_nr == 0)
11445         break;
11446       if (section_nr >= dwp_file->num_sections)
11447         {
11448           error (_("Dwarf Error: bad DWP hash table, section number too large"
11449                    " [in module %s]"),
11450                  dwp_file->name);
11451         }
11452
11453       sectp = dwp_file->elf_sections[section_nr];
11454       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
11455         {
11456           error (_("Dwarf Error: bad DWP hash table, invalid section found"
11457                    " [in module %s]"),
11458                  dwp_file->name);
11459         }
11460     }
11461
11462   if (i < 2
11463       || sections.info_or_types.empty ()
11464       || sections.abbrev.empty ())
11465     {
11466       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
11467                " [in module %s]"),
11468              dwp_file->name);
11469     }
11470   if (i == MAX_NR_V1_DWO_SECTIONS)
11471     {
11472       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
11473                " [in module %s]"),
11474              dwp_file->name);
11475     }
11476
11477   /* It's easier for the rest of the code if we fake a struct dwo_file and
11478      have dwo_unit "live" in that.  At least for now.
11479
11480      The DWP file can be made up of a random collection of CUs and TUs.
11481      However, for each CU + set of TUs that came from the same original DWO
11482      file, we can combine them back into a virtual DWO file to save space
11483      (fewer struct dwo_file objects to allocate).  Remember that for really
11484      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11485
11486   std::string virtual_dwo_name =
11487     string_printf ("virtual-dwo/%d-%d-%d-%d",
11488                    sections.abbrev.get_id (),
11489                    sections.line.get_id (),
11490                    sections.loc.get_id (),
11491                    sections.str_offsets.get_id ());
11492   /* Can we use an existing virtual DWO file?  */
11493   dwo_file_slot = lookup_dwo_file_slot (per_objfile, virtual_dwo_name.c_str (),
11494                                         comp_dir);
11495   /* Create one if necessary.  */
11496   if (*dwo_file_slot == NULL)
11497     {
11498       dwarf_read_debug_printf ("Creating virtual DWO: %s",
11499                                virtual_dwo_name.c_str ());
11500
11501       dwo_file = new struct dwo_file;
11502       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
11503       dwo_file->comp_dir = comp_dir;
11504       dwo_file->sections.abbrev = sections.abbrev;
11505       dwo_file->sections.line = sections.line;
11506       dwo_file->sections.loc = sections.loc;
11507       dwo_file->sections.macinfo = sections.macinfo;
11508       dwo_file->sections.macro = sections.macro;
11509       dwo_file->sections.str_offsets = sections.str_offsets;
11510       /* The "str" section is global to the entire DWP file.  */
11511       dwo_file->sections.str = dwp_file->sections.str;
11512       /* The info or types section is assigned below to dwo_unit,
11513          there's no need to record it in dwo_file.
11514          Also, we can't simply record type sections in dwo_file because
11515          we record a pointer into the vector in dwo_unit.  As we collect more
11516          types we'll grow the vector and eventually have to reallocate space
11517          for it, invalidating all copies of pointers into the previous
11518          contents.  */
11519       *dwo_file_slot = dwo_file;
11520     }
11521   else
11522     {
11523       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
11524                                virtual_dwo_name.c_str ());
11525
11526       dwo_file = (struct dwo_file *) *dwo_file_slot;
11527     }
11528
11529   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
11530   dwo_unit->dwo_file = dwo_file;
11531   dwo_unit->signature = signature;
11532   dwo_unit->section =
11533     XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
11534   *dwo_unit->section = sections.info_or_types;
11535   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11536
11537   return dwo_unit;
11538 }
11539
11540 /* Subroutine of create_dwo_unit_in_dwp_v2 and create_dwo_unit_in_dwp_v5 to
11541    simplify them.  Given a pointer to the containing section SECTION, and
11542    OFFSET,SIZE of the piece within that section used by a TU/CU, return a
11543    virtual section of just that piece.  */
11544
11545 static struct dwarf2_section_info
11546 create_dwp_v2_or_v5_section (dwarf2_per_objfile *per_objfile,
11547                              struct dwarf2_section_info *section,
11548                              bfd_size_type offset, bfd_size_type size)
11549 {
11550   struct dwarf2_section_info result;
11551   asection *sectp;
11552
11553   gdb_assert (section != NULL);
11554   gdb_assert (!section->is_virtual);
11555
11556   memset (&result, 0, sizeof (result));
11557   result.s.containing_section = section;
11558   result.is_virtual = true;
11559
11560   if (size == 0)
11561     return result;
11562
11563   sectp = section->get_bfd_section ();
11564
11565   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
11566      bounds of the real section.  This is a pretty-rare event, so just
11567      flag an error (easier) instead of a warning and trying to cope.  */
11568   if (sectp == NULL
11569       || offset + size > bfd_section_size (sectp))
11570     {
11571       error (_("Dwarf Error: Bad DWP V2 or V5 section info, doesn't fit"
11572                " in section %s [in module %s]"),
11573              sectp ? bfd_section_name (sectp) : "<unknown>",
11574              objfile_name (per_objfile->objfile));
11575     }
11576
11577   result.virtual_offset = offset;
11578   result.size = size;
11579   return result;
11580 }
11581
11582 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11583    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11584    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11585    This is for DWP version 2 files.  */
11586
11587 static struct dwo_unit *
11588 create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile *per_objfile,
11589                            struct dwp_file *dwp_file,
11590                            uint32_t unit_index,
11591                            const char *comp_dir,
11592                            ULONGEST signature, int is_debug_types)
11593 {
11594   const struct dwp_hash_table *dwp_htab =
11595     is_debug_types ? dwp_file->tus : dwp_file->cus;
11596   bfd *dbfd = dwp_file->dbfd.get ();
11597   const char *kind = is_debug_types ? "TU" : "CU";
11598   struct dwo_file *dwo_file;
11599   struct dwo_unit *dwo_unit;
11600   struct virtual_v2_or_v5_dwo_sections sections;
11601   void **dwo_file_slot;
11602   int i;
11603
11604   gdb_assert (dwp_file->version == 2);
11605
11606   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V2 file: %s",
11607                            kind, pulongest (unit_index), hex_string (signature),
11608                            dwp_file->name);
11609
11610   /* Fetch the section offsets of this DWO unit.  */
11611
11612   memset (&sections, 0, sizeof (sections));
11613
11614   for (i = 0; i < dwp_htab->nr_columns; ++i)
11615     {
11616       uint32_t offset = read_4_bytes (dbfd,
11617                                       dwp_htab->section_pool.v2.offsets
11618                                       + (((unit_index - 1) * dwp_htab->nr_columns
11619                                           + i)
11620                                          * sizeof (uint32_t)));
11621       uint32_t size = read_4_bytes (dbfd,
11622                                     dwp_htab->section_pool.v2.sizes
11623                                     + (((unit_index - 1) * dwp_htab->nr_columns
11624                                         + i)
11625                                        * sizeof (uint32_t)));
11626
11627       switch (dwp_htab->section_pool.v2.section_ids[i])
11628         {
11629         case DW_SECT_INFO:
11630         case DW_SECT_TYPES:
11631           sections.info_or_types_offset = offset;
11632           sections.info_or_types_size = size;
11633           break;
11634         case DW_SECT_ABBREV:
11635           sections.abbrev_offset = offset;
11636           sections.abbrev_size = size;
11637           break;
11638         case DW_SECT_LINE:
11639           sections.line_offset = offset;
11640           sections.line_size = size;
11641           break;
11642         case DW_SECT_LOC:
11643           sections.loc_offset = offset;
11644           sections.loc_size = size;
11645           break;
11646         case DW_SECT_STR_OFFSETS:
11647           sections.str_offsets_offset = offset;
11648           sections.str_offsets_size = size;
11649           break;
11650         case DW_SECT_MACINFO:
11651           sections.macinfo_offset = offset;
11652           sections.macinfo_size = size;
11653           break;
11654         case DW_SECT_MACRO:
11655           sections.macro_offset = offset;
11656           sections.macro_size = size;
11657           break;
11658         }
11659     }
11660
11661   /* It's easier for the rest of the code if we fake a struct dwo_file and
11662      have dwo_unit "live" in that.  At least for now.
11663
11664      The DWP file can be made up of a random collection of CUs and TUs.
11665      However, for each CU + set of TUs that came from the same original DWO
11666      file, we can combine them back into a virtual DWO file to save space
11667      (fewer struct dwo_file objects to allocate).  Remember that for really
11668      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11669
11670   std::string virtual_dwo_name =
11671     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
11672                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11673                    (long) (sections.line_size ? sections.line_offset : 0),
11674                    (long) (sections.loc_size ? sections.loc_offset : 0),
11675                    (long) (sections.str_offsets_size
11676                            ? sections.str_offsets_offset : 0));
11677   /* Can we use an existing virtual DWO file?  */
11678   dwo_file_slot = lookup_dwo_file_slot (per_objfile, virtual_dwo_name.c_str (),
11679                                         comp_dir);
11680   /* Create one if necessary.  */
11681   if (*dwo_file_slot == NULL)
11682     {
11683       dwarf_read_debug_printf ("Creating virtual DWO: %s",
11684                                virtual_dwo_name.c_str ());
11685
11686       dwo_file = new struct dwo_file;
11687       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
11688       dwo_file->comp_dir = comp_dir;
11689       dwo_file->sections.abbrev =
11690         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.abbrev,
11691                                      sections.abbrev_offset,
11692                                      sections.abbrev_size);
11693       dwo_file->sections.line =
11694         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.line,
11695                                      sections.line_offset,
11696                                      sections.line_size);
11697       dwo_file->sections.loc =
11698         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.loc,
11699                                      sections.loc_offset, sections.loc_size);
11700       dwo_file->sections.macinfo =
11701         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.macinfo,
11702                                      sections.macinfo_offset,
11703                                      sections.macinfo_size);
11704       dwo_file->sections.macro =
11705         create_dwp_v2_or_v5_section (per_objfile, &dwp_file->sections.macro,
11706                                      sections.macro_offset,
11707                                      sections.macro_size);
11708       dwo_file->sections.str_offsets =
11709         create_dwp_v2_or_v5_section (per_objfile,
11710                                      &dwp_file->sections.str_offsets,
11711                                      sections.str_offsets_offset,
11712                                      sections.str_offsets_size);
11713       /* The "str" section is global to the entire DWP file.  */
11714       dwo_file->sections.str = dwp_file->sections.str;
11715       /* The info or types section is assigned below to dwo_unit,
11716          there's no need to record it in dwo_file.
11717          Also, we can't simply record type sections in dwo_file because
11718          we record a pointer into the vector in dwo_unit.  As we collect more
11719          types we'll grow the vector and eventually have to reallocate space
11720          for it, invalidating all copies of pointers into the previous
11721          contents.  */
11722       *dwo_file_slot = dwo_file;
11723     }
11724   else
11725     {
11726       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
11727                                virtual_dwo_name.c_str ());
11728
11729       dwo_file = (struct dwo_file *) *dwo_file_slot;
11730     }
11731
11732   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
11733   dwo_unit->dwo_file = dwo_file;
11734   dwo_unit->signature = signature;
11735   dwo_unit->section =
11736     XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
11737   *dwo_unit->section = create_dwp_v2_or_v5_section
11738                          (per_objfile,
11739                           is_debug_types
11740                           ? &dwp_file->sections.types
11741                           : &dwp_file->sections.info,
11742                           sections.info_or_types_offset,
11743                           sections.info_or_types_size);
11744   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11745
11746   return dwo_unit;
11747 }
11748
11749 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11750    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11751    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11752    This is for DWP version 5 files.  */
11753
11754 static struct dwo_unit *
11755 create_dwo_unit_in_dwp_v5 (dwarf2_per_objfile *per_objfile,
11756                            struct dwp_file *dwp_file,
11757                            uint32_t unit_index,
11758                            const char *comp_dir,
11759                            ULONGEST signature, int is_debug_types)
11760 {
11761   const struct dwp_hash_table *dwp_htab
11762     = is_debug_types ? dwp_file->tus : dwp_file->cus;
11763   bfd *dbfd = dwp_file->dbfd.get ();
11764   const char *kind = is_debug_types ? "TU" : "CU";
11765   struct dwo_file *dwo_file;
11766   struct dwo_unit *dwo_unit;
11767   struct virtual_v2_or_v5_dwo_sections sections {};
11768   void **dwo_file_slot;
11769
11770   gdb_assert (dwp_file->version == 5);
11771
11772   dwarf_read_debug_printf ("Reading %s %s/%s in DWP V5 file: %s",
11773                            kind, pulongest (unit_index), hex_string (signature),
11774                            dwp_file->name);
11775
11776   /* Fetch the section offsets of this DWO unit.  */
11777
11778   /*  memset (&sections, 0, sizeof (sections)); */
11779
11780   for (int i = 0; i < dwp_htab->nr_columns; ++i)
11781     {
11782       uint32_t offset = read_4_bytes (dbfd,
11783                                       dwp_htab->section_pool.v5.offsets
11784                                       + (((unit_index - 1)
11785                                           * dwp_htab->nr_columns
11786                                           + i)
11787                                          * sizeof (uint32_t)));
11788       uint32_t size = read_4_bytes (dbfd,
11789                                     dwp_htab->section_pool.v5.sizes
11790                                     + (((unit_index - 1) * dwp_htab->nr_columns
11791                                         + i)
11792                                        * sizeof (uint32_t)));
11793
11794       switch (dwp_htab->section_pool.v5.section_ids[i])
11795         {
11796           case DW_SECT_ABBREV_V5:
11797             sections.abbrev_offset = offset;
11798             sections.abbrev_size = size;
11799             break;
11800           case DW_SECT_INFO_V5:
11801             sections.info_or_types_offset = offset;
11802             sections.info_or_types_size = size;
11803             break;
11804           case DW_SECT_LINE_V5:
11805             sections.line_offset = offset;
11806             sections.line_size = size;
11807             break;
11808           case DW_SECT_LOCLISTS_V5:
11809             sections.loclists_offset = offset;
11810             sections.loclists_size = size;
11811             break;
11812           case DW_SECT_MACRO_V5:
11813             sections.macro_offset = offset;
11814             sections.macro_size = size;
11815             break;
11816           case DW_SECT_RNGLISTS_V5:
11817             sections.rnglists_offset = offset;
11818             sections.rnglists_size = size;
11819             break;
11820           case DW_SECT_STR_OFFSETS_V5:
11821             sections.str_offsets_offset = offset;
11822             sections.str_offsets_size = size;
11823             break;
11824           case DW_SECT_RESERVED_V5:
11825           default:
11826             break;
11827         }
11828     }
11829
11830   /* It's easier for the rest of the code if we fake a struct dwo_file and
11831      have dwo_unit "live" in that.  At least for now.
11832
11833      The DWP file can be made up of a random collection of CUs and TUs.
11834      However, for each CU + set of TUs that came from the same original DWO
11835      file, we can combine them back into a virtual DWO file to save space
11836      (fewer struct dwo_file objects to allocate).  Remember that for really
11837      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11838
11839   std::string virtual_dwo_name =
11840     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld-%ld-%ld",
11841                  (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11842                  (long) (sections.line_size ? sections.line_offset : 0),
11843                  (long) (sections.loclists_size ? sections.loclists_offset : 0),
11844                  (long) (sections.str_offsets_size
11845                             ? sections.str_offsets_offset : 0),
11846                  (long) (sections.macro_size ? sections.macro_offset : 0),
11847                  (long) (sections.rnglists_size ? sections.rnglists_offset: 0));
11848   /* Can we use an existing virtual DWO file?  */
11849   dwo_file_slot = lookup_dwo_file_slot (per_objfile,
11850                                         virtual_dwo_name.c_str (),
11851                                         comp_dir);
11852   /* Create one if necessary.  */
11853   if (*dwo_file_slot == NULL)
11854     {
11855       dwarf_read_debug_printf ("Creating virtual DWO: %s",
11856                                virtual_dwo_name.c_str ());
11857
11858       dwo_file = new struct dwo_file;
11859       dwo_file->dwo_name = per_objfile->objfile->intern (virtual_dwo_name);
11860       dwo_file->comp_dir = comp_dir;
11861       dwo_file->sections.abbrev =
11862         create_dwp_v2_or_v5_section (per_objfile,
11863                                      &dwp_file->sections.abbrev,
11864                                      sections.abbrev_offset,
11865                                      sections.abbrev_size);
11866       dwo_file->sections.line =
11867         create_dwp_v2_or_v5_section (per_objfile,
11868                                      &dwp_file->sections.line,
11869                                      sections.line_offset, sections.line_size);
11870       dwo_file->sections.macro =
11871         create_dwp_v2_or_v5_section (per_objfile,
11872                                      &dwp_file->sections.macro,
11873                                      sections.macro_offset,
11874                                      sections.macro_size);
11875       dwo_file->sections.loclists =
11876         create_dwp_v2_or_v5_section (per_objfile,
11877                                      &dwp_file->sections.loclists,
11878                                      sections.loclists_offset,
11879                                      sections.loclists_size);
11880       dwo_file->sections.rnglists =
11881         create_dwp_v2_or_v5_section (per_objfile,
11882                                      &dwp_file->sections.rnglists,
11883                                      sections.rnglists_offset,
11884                                      sections.rnglists_size);
11885       dwo_file->sections.str_offsets =
11886         create_dwp_v2_or_v5_section (per_objfile,
11887                                      &dwp_file->sections.str_offsets,
11888                                      sections.str_offsets_offset,
11889                                      sections.str_offsets_size);
11890       /* The "str" section is global to the entire DWP file.  */
11891       dwo_file->sections.str = dwp_file->sections.str;
11892       /* The info or types section is assigned below to dwo_unit,
11893          there's no need to record it in dwo_file.
11894          Also, we can't simply record type sections in dwo_file because
11895          we record a pointer into the vector in dwo_unit.  As we collect more
11896          types we'll grow the vector and eventually have to reallocate space
11897          for it, invalidating all copies of pointers into the previous
11898          contents.  */
11899       *dwo_file_slot = dwo_file;
11900     }
11901   else
11902     {
11903       dwarf_read_debug_printf ("Using existing virtual DWO: %s",
11904                                virtual_dwo_name.c_str ());
11905
11906       dwo_file = (struct dwo_file *) *dwo_file_slot;
11907     }
11908
11909   dwo_unit = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwo_unit);
11910   dwo_unit->dwo_file = dwo_file;
11911   dwo_unit->signature = signature;
11912   dwo_unit->section
11913     = XOBNEW (&per_objfile->per_bfd->obstack, struct dwarf2_section_info);
11914   *dwo_unit->section = create_dwp_v2_or_v5_section (per_objfile,
11915                                               &dwp_file->sections.info,
11916                                               sections.info_or_types_offset,
11917                                               sections.info_or_types_size);
11918   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11919
11920   return dwo_unit;
11921 }
11922
11923 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
11924    Returns NULL if the signature isn't found.  */
11925
11926 static struct dwo_unit *
11927 lookup_dwo_unit_in_dwp (dwarf2_per_objfile *per_objfile,
11928                         struct dwp_file *dwp_file, const char *comp_dir,
11929                         ULONGEST signature, int is_debug_types)
11930 {
11931   const struct dwp_hash_table *dwp_htab =
11932     is_debug_types ? dwp_file->tus : dwp_file->cus;
11933   bfd *dbfd = dwp_file->dbfd.get ();
11934   uint32_t mask = dwp_htab->nr_slots - 1;
11935   uint32_t hash = signature & mask;
11936   uint32_t hash2 = ((signature >> 32) & mask) | 1;
11937   unsigned int i;
11938   void **slot;
11939   struct dwo_unit find_dwo_cu;
11940
11941   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
11942   find_dwo_cu.signature = signature;
11943   slot = htab_find_slot (is_debug_types
11944                          ? dwp_file->loaded_tus.get ()
11945                          : dwp_file->loaded_cus.get (),
11946                          &find_dwo_cu, INSERT);
11947
11948   if (*slot != NULL)
11949     return (struct dwo_unit *) *slot;
11950
11951   /* Use a for loop so that we don't loop forever on bad debug info.  */
11952   for (i = 0; i < dwp_htab->nr_slots; ++i)
11953     {
11954       ULONGEST signature_in_table;
11955
11956       signature_in_table =
11957         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
11958       if (signature_in_table == signature)
11959         {
11960           uint32_t unit_index =
11961             read_4_bytes (dbfd,
11962                           dwp_htab->unit_table + hash * sizeof (uint32_t));
11963
11964           if (dwp_file->version == 1)
11965             {
11966               *slot = create_dwo_unit_in_dwp_v1 (per_objfile, dwp_file,
11967                                                  unit_index, comp_dir,
11968                                                  signature, is_debug_types);
11969             }
11970           else if (dwp_file->version == 2)
11971             {
11972               *slot = create_dwo_unit_in_dwp_v2 (per_objfile, dwp_file,
11973                                                  unit_index, comp_dir,
11974                                                  signature, is_debug_types);
11975             }
11976           else /* version == 5  */
11977             {
11978               *slot = create_dwo_unit_in_dwp_v5 (per_objfile, dwp_file,
11979                                                  unit_index, comp_dir,
11980                                                  signature, is_debug_types);
11981             }
11982           return (struct dwo_unit *) *slot;
11983         }
11984       if (signature_in_table == 0)
11985         return NULL;
11986       hash = (hash + hash2) & mask;
11987     }
11988
11989   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
11990            " [in module %s]"),
11991          dwp_file->name);
11992 }
11993
11994 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
11995    Open the file specified by FILE_NAME and hand it off to BFD for
11996    preliminary analysis.  Return a newly initialized bfd *, which
11997    includes a canonicalized copy of FILE_NAME.
11998    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
11999    SEARCH_CWD is true if the current directory is to be searched.
12000    It will be searched before debug-file-directory.
12001    If successful, the file is added to the bfd include table of the
12002    objfile's bfd (see gdb_bfd_record_inclusion).
12003    If unable to find/open the file, return NULL.
12004    NOTE: This function is derived from symfile_bfd_open.  */
12005
12006 static gdb_bfd_ref_ptr
12007 try_open_dwop_file (dwarf2_per_objfile *per_objfile,
12008                     const char *file_name, int is_dwp, int search_cwd)
12009 {
12010   int desc;
12011   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12012      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12013      to debug_file_directory.  */
12014   const char *search_path;
12015   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12016
12017   gdb::unique_xmalloc_ptr<char> search_path_holder;
12018   if (search_cwd)
12019     {
12020       if (*debug_file_directory != '\0')
12021         {
12022           search_path_holder.reset (concat (".", dirname_separator_string,
12023                                             debug_file_directory,
12024                                             (char *) NULL));
12025           search_path = search_path_holder.get ();
12026         }
12027       else
12028         search_path = ".";
12029     }
12030   else
12031     search_path = debug_file_directory;
12032
12033   /* Add the path for the executable binary to the list of search paths.  */
12034   std::string objfile_dir = ldirname (objfile_name (per_objfile->objfile));
12035   search_path_holder.reset (concat (objfile_dir.c_str (),
12036                                     dirname_separator_string,
12037                                     search_path, nullptr));
12038   search_path = search_path_holder.get ();
12039
12040   openp_flags flags = OPF_RETURN_REALPATH;
12041   if (is_dwp)
12042     flags |= OPF_SEARCH_IN_PATH;
12043
12044   gdb::unique_xmalloc_ptr<char> absolute_name;
12045   desc = openp (search_path, flags, file_name,
12046                 O_RDONLY | O_BINARY, &absolute_name);
12047   if (desc < 0)
12048     return NULL;
12049
12050   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12051                                          gnutarget, desc));
12052   if (sym_bfd == NULL)
12053     return NULL;
12054   bfd_set_cacheable (sym_bfd.get (), 1);
12055
12056   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12057     return NULL;
12058
12059   /* Success.  Record the bfd as having been included by the objfile's bfd.
12060      This is important because things like demangled_names_hash lives in the
12061      objfile's per_bfd space and may have references to things like symbol
12062      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12063   gdb_bfd_record_inclusion (per_objfile->objfile->obfd, sym_bfd.get ());
12064
12065   return sym_bfd;
12066 }
12067
12068 /* Try to open DWO file FILE_NAME.
12069    COMP_DIR is the DW_AT_comp_dir attribute.
12070    The result is the bfd handle of the file.
12071    If there is a problem finding or opening the file, return NULL.
12072    Upon success, the canonicalized path of the file is stored in the bfd,
12073    same as symfile_bfd_open.  */
12074
12075 static gdb_bfd_ref_ptr
12076 open_dwo_file (dwarf2_per_objfile *per_objfile,
12077                const char *file_name, const char *comp_dir)
12078 {
12079   if (IS_ABSOLUTE_PATH (file_name))
12080     return try_open_dwop_file (per_objfile, file_name,
12081                                0 /*is_dwp*/, 0 /*search_cwd*/);
12082
12083   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12084
12085   if (comp_dir != NULL)
12086     {
12087       gdb::unique_xmalloc_ptr<char> path_to_try
12088         (concat (comp_dir, SLASH_STRING, file_name, (char *) NULL));
12089
12090       /* NOTE: If comp_dir is a relative path, this will also try the
12091          search path, which seems useful.  */
12092       gdb_bfd_ref_ptr abfd (try_open_dwop_file (per_objfile, path_to_try.get (),
12093                                                 0 /*is_dwp*/,
12094                                                 1 /*search_cwd*/));
12095       if (abfd != NULL)
12096         return abfd;
12097     }
12098
12099   /* That didn't work, try debug-file-directory, which, despite its name,
12100      is a list of paths.  */
12101
12102   if (*debug_file_directory == '\0')
12103     return NULL;
12104
12105   return try_open_dwop_file (per_objfile, file_name,
12106                              0 /*is_dwp*/, 1 /*search_cwd*/);
12107 }
12108
12109 /* This function is mapped across the sections and remembers the offset and
12110    size of each of the DWO debugging sections we are interested in.  */
12111
12112 static void
12113 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp,
12114                             dwo_sections *dwo_sections)
12115 {
12116   const struct dwop_section_names *names = &dwop_section_names;
12117
12118   if (names->abbrev_dwo.matches (sectp->name))
12119     {
12120       dwo_sections->abbrev.s.section = sectp;
12121       dwo_sections->abbrev.size = bfd_section_size (sectp);
12122     }
12123   else if (names->info_dwo.matches (sectp->name))
12124     {
12125       dwo_sections->info.s.section = sectp;
12126       dwo_sections->info.size = bfd_section_size (sectp);
12127     }
12128   else if (names->line_dwo.matches (sectp->name))
12129     {
12130       dwo_sections->line.s.section = sectp;
12131       dwo_sections->line.size = bfd_section_size (sectp);
12132     }
12133   else if (names->loc_dwo.matches (sectp->name))
12134     {
12135       dwo_sections->loc.s.section = sectp;
12136       dwo_sections->loc.size = bfd_section_size (sectp);
12137     }
12138   else if (names->loclists_dwo.matches (sectp->name))
12139     {
12140       dwo_sections->loclists.s.section = sectp;
12141       dwo_sections->loclists.size = bfd_section_size (sectp);
12142     }
12143   else if (names->macinfo_dwo.matches (sectp->name))
12144     {
12145       dwo_sections->macinfo.s.section = sectp;
12146       dwo_sections->macinfo.size = bfd_section_size (sectp);
12147     }
12148   else if (names->macro_dwo.matches (sectp->name))
12149     {
12150       dwo_sections->macro.s.section = sectp;
12151       dwo_sections->macro.size = bfd_section_size (sectp);
12152     }
12153   else if (names->rnglists_dwo.matches (sectp->name))
12154     {
12155       dwo_sections->rnglists.s.section = sectp;
12156       dwo_sections->rnglists.size = bfd_section_size (sectp);
12157     }
12158   else if (names->str_dwo.matches (sectp->name))
12159     {
12160       dwo_sections->str.s.section = sectp;
12161       dwo_sections->str.size = bfd_section_size (sectp);
12162     }
12163   else if (names->str_offsets_dwo.matches (sectp->name))
12164     {
12165       dwo_sections->str_offsets.s.section = sectp;
12166       dwo_sections->str_offsets.size = bfd_section_size (sectp);
12167     }
12168   else if (names->types_dwo.matches (sectp->name))
12169     {
12170       struct dwarf2_section_info type_section;
12171
12172       memset (&type_section, 0, sizeof (type_section));
12173       type_section.s.section = sectp;
12174       type_section.size = bfd_section_size (sectp);
12175       dwo_sections->types.push_back (type_section);
12176     }
12177 }
12178
12179 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12180    by PER_CU.  This is for the non-DWP case.
12181    The result is NULL if DWO_NAME can't be found.  */
12182
12183 static struct dwo_file *
12184 open_and_init_dwo_file (dwarf2_cu *cu, const char *dwo_name,
12185                         const char *comp_dir)
12186 {
12187   dwarf2_per_objfile *per_objfile = cu->per_objfile;
12188
12189   gdb_bfd_ref_ptr dbfd = open_dwo_file (per_objfile, dwo_name, comp_dir);
12190   if (dbfd == NULL)
12191     {
12192       dwarf_read_debug_printf ("DWO file not found: %s", dwo_name);
12193
12194       return NULL;
12195     }
12196
12197   dwo_file_up dwo_file (new struct dwo_file);
12198   dwo_file->dwo_name = dwo_name;
12199   dwo_file->comp_dir = comp_dir;
12200   dwo_file->dbfd = std::move (dbfd);
12201
12202   for (asection *sec : gdb_bfd_sections (dwo_file->dbfd))
12203     dwarf2_locate_dwo_sections (dwo_file->dbfd.get (), sec,
12204                                 &dwo_file->sections);
12205
12206   create_cus_hash_table (per_objfile, cu, *dwo_file, dwo_file->sections.info,
12207                          dwo_file->cus);
12208
12209   if (cu->per_cu->dwarf_version < 5)
12210     {
12211       create_debug_types_hash_table (per_objfile, dwo_file.get (),
12212                                      dwo_file->sections.types, dwo_file->tus);
12213     }
12214   else
12215     {
12216       create_debug_type_hash_table (per_objfile, dwo_file.get (),
12217                                     &dwo_file->sections.info, dwo_file->tus,
12218                                     rcuh_kind::COMPILE);
12219     }
12220
12221   dwarf_read_debug_printf ("DWO file found: %s", dwo_name);
12222
12223   return dwo_file.release ();
12224 }
12225
12226 /* This function is mapped across the sections and remembers the offset and
12227    size of each of the DWP debugging sections common to version 1 and 2 that
12228    we are interested in.  */
12229
12230 static void
12231 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12232                                    dwp_file *dwp_file)
12233 {
12234   const struct dwop_section_names *names = &dwop_section_names;
12235   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12236
12237   /* Record the ELF section number for later lookup: this is what the
12238      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12239   gdb_assert (elf_section_nr < dwp_file->num_sections);
12240   dwp_file->elf_sections[elf_section_nr] = sectp;
12241
12242   /* Look for specific sections that we need.  */
12243   if (names->str_dwo.matches (sectp->name))
12244     {
12245       dwp_file->sections.str.s.section = sectp;
12246       dwp_file->sections.str.size = bfd_section_size (sectp);
12247     }
12248   else if (names->cu_index.matches (sectp->name))
12249     {
12250       dwp_file->sections.cu_index.s.section = sectp;
12251       dwp_file->sections.cu_index.size = bfd_section_size (sectp);
12252     }
12253   else if (names->tu_index.matches (sectp->name))
12254     {
12255       dwp_file->sections.tu_index.s.section = sectp;
12256       dwp_file->sections.tu_index.size = bfd_section_size (sectp);
12257     }
12258 }
12259
12260 /* This function is mapped across the sections and remembers the offset and
12261    size of each of the DWP version 2 debugging sections that we are interested
12262    in.  This is split into a separate function because we don't know if we
12263    have version 1 or 2 or 5 until we parse the cu_index/tu_index sections.  */
12264
12265 static void
12266 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12267 {
12268   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12269   const struct dwop_section_names *names = &dwop_section_names;
12270   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12271
12272   /* Record the ELF section number for later lookup: this is what the
12273      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12274   gdb_assert (elf_section_nr < dwp_file->num_sections);
12275   dwp_file->elf_sections[elf_section_nr] = sectp;
12276
12277   /* Look for specific sections that we need.  */
12278   if (names->abbrev_dwo.matches (sectp->name))
12279     {
12280       dwp_file->sections.abbrev.s.section = sectp;
12281       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
12282     }
12283   else if (names->info_dwo.matches (sectp->name))
12284     {
12285       dwp_file->sections.info.s.section = sectp;
12286       dwp_file->sections.info.size = bfd_section_size (sectp);
12287     }
12288   else if (names->line_dwo.matches (sectp->name))
12289     {
12290       dwp_file->sections.line.s.section = sectp;
12291       dwp_file->sections.line.size = bfd_section_size (sectp);
12292     }
12293   else if (names->loc_dwo.matches (sectp->name))
12294     {
12295       dwp_file->sections.loc.s.section = sectp;
12296       dwp_file->sections.loc.size = bfd_section_size (sectp);
12297     }
12298   else if (names->macinfo_dwo.matches (sectp->name))
12299     {
12300       dwp_file->sections.macinfo.s.section = sectp;
12301       dwp_file->sections.macinfo.size = bfd_section_size (sectp);
12302     }
12303   else if (names->macro_dwo.matches (sectp->name))
12304     {
12305       dwp_file->sections.macro.s.section = sectp;
12306       dwp_file->sections.macro.size = bfd_section_size (sectp);
12307     }
12308   else if (names->str_offsets_dwo.matches (sectp->name))
12309     {
12310       dwp_file->sections.str_offsets.s.section = sectp;
12311       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
12312     }
12313   else if (names->types_dwo.matches (sectp->name))
12314     {
12315       dwp_file->sections.types.s.section = sectp;
12316       dwp_file->sections.types.size = bfd_section_size (sectp);
12317     }
12318 }
12319
12320 /* This function is mapped across the sections and remembers the offset and
12321    size of each of the DWP version 5 debugging sections that we are interested
12322    in.  This is split into a separate function because we don't know if we
12323    have version 1 or 2 or 5 until we parse the cu_index/tu_index sections.  */
12324
12325 static void
12326 dwarf2_locate_v5_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12327 {
12328   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12329   const struct dwop_section_names *names = &dwop_section_names;
12330   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12331
12332   /* Record the ELF section number for later lookup: this is what the
12333      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12334   gdb_assert (elf_section_nr < dwp_file->num_sections);
12335   dwp_file->elf_sections[elf_section_nr] = sectp;
12336
12337   /* Look for specific sections that we need.  */
12338   if (names->abbrev_dwo.matches (sectp->name))
12339     {
12340       dwp_file->sections.abbrev.s.section = sectp;
12341       dwp_file->sections.abbrev.size = bfd_section_size (sectp);
12342     }
12343   else if (names->info_dwo.matches (sectp->name))
12344     {
12345       dwp_file->sections.info.s.section = sectp;
12346       dwp_file->sections.info.size = bfd_section_size (sectp);
12347     }
12348   else if (names->line_dwo.matches (sectp->name))
12349    {
12350      dwp_file->sections.line.s.section = sectp;
12351      dwp_file->sections.line.size = bfd_section_size (sectp);
12352     }
12353   else if (names->loclists_dwo.matches (sectp->name))
12354     {
12355       dwp_file->sections.loclists.s.section = sectp;
12356       dwp_file->sections.loclists.size = bfd_section_size (sectp);
12357     }
12358   else if (names->macro_dwo.matches (sectp->name))
12359     {
12360       dwp_file->sections.macro.s.section = sectp;
12361       dwp_file->sections.macro.size = bfd_section_size (sectp);
12362     }
12363   else if (names->rnglists_dwo.matches (sectp->name))
12364     {
12365       dwp_file->sections.rnglists.s.section = sectp;
12366       dwp_file->sections.rnglists.size = bfd_section_size (sectp);
12367     }
12368   else if (names->str_offsets_dwo.matches (sectp->name))
12369     {
12370       dwp_file->sections.str_offsets.s.section = sectp;
12371       dwp_file->sections.str_offsets.size = bfd_section_size (sectp);
12372     }
12373 }
12374
12375 /* Hash function for dwp_file loaded CUs/TUs.  */
12376
12377 static hashval_t
12378 hash_dwp_loaded_cutus (const void *item)
12379 {
12380   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12381
12382   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
12383   return dwo_unit->signature;
12384 }
12385
12386 /* Equality function for dwp_file loaded CUs/TUs.  */
12387
12388 static int
12389 eq_dwp_loaded_cutus (const void *a, const void *b)
12390 {
12391   const struct dwo_unit *dua = (const struct dwo_unit *) a;
12392   const struct dwo_unit *dub = (const struct dwo_unit *) b;
12393
12394   return dua->signature == dub->signature;
12395 }
12396
12397 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
12398
12399 static htab_up
12400 allocate_dwp_loaded_cutus_table ()
12401 {
12402   return htab_up (htab_create_alloc (3,
12403                                      hash_dwp_loaded_cutus,
12404                                      eq_dwp_loaded_cutus,
12405                                      NULL, xcalloc, xfree));
12406 }
12407
12408 /* Try to open DWP file FILE_NAME.
12409    The result is the bfd handle of the file.
12410    If there is a problem finding or opening the file, return NULL.
12411    Upon success, the canonicalized path of the file is stored in the bfd,
12412    same as symfile_bfd_open.  */
12413
12414 static gdb_bfd_ref_ptr
12415 open_dwp_file (dwarf2_per_objfile *per_objfile, const char *file_name)
12416 {
12417   gdb_bfd_ref_ptr abfd (try_open_dwop_file (per_objfile, file_name,
12418                                             1 /*is_dwp*/,
12419                                             1 /*search_cwd*/));
12420   if (abfd != NULL)
12421     return abfd;
12422
12423   /* Work around upstream bug 15652.
12424      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
12425      [Whether that's a "bug" is debatable, but it is getting in our way.]
12426      We have no real idea where the dwp file is, because gdb's realpath-ing
12427      of the executable's path may have discarded the needed info.
12428      [IWBN if the dwp file name was recorded in the executable, akin to
12429      .gnu_debuglink, but that doesn't exist yet.]
12430      Strip the directory from FILE_NAME and search again.  */
12431   if (*debug_file_directory != '\0')
12432     {
12433       /* Don't implicitly search the current directory here.
12434          If the user wants to search "." to handle this case,
12435          it must be added to debug-file-directory.  */
12436       return try_open_dwop_file (per_objfile, lbasename (file_name),
12437                                  1 /*is_dwp*/,
12438                                  0 /*search_cwd*/);
12439     }
12440
12441   return NULL;
12442 }
12443
12444 /* Initialize the use of the DWP file for the current objfile.
12445    By convention the name of the DWP file is ${objfile}.dwp.
12446    The result is NULL if it can't be found.  */
12447
12448 static std::unique_ptr<struct dwp_file>
12449 open_and_init_dwp_file (dwarf2_per_objfile *per_objfile)
12450 {
12451   struct objfile *objfile = per_objfile->objfile;
12452
12453   /* Try to find first .dwp for the binary file before any symbolic links
12454      resolving.  */
12455
12456   /* If the objfile is a debug file, find the name of the real binary
12457      file and get the name of dwp file from there.  */
12458   std::string dwp_name;
12459   if (objfile->separate_debug_objfile_backlink != NULL)
12460     {
12461       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
12462       const char *backlink_basename = lbasename (backlink->original_name);
12463
12464       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
12465     }
12466   else
12467     dwp_name = objfile->original_name;
12468
12469   dwp_name += ".dwp";
12470
12471   gdb_bfd_ref_ptr dbfd (open_dwp_file (per_objfile, dwp_name.c_str ()));
12472   if (dbfd == NULL
12473       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
12474     {
12475       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
12476       dwp_name = objfile_name (objfile);
12477       dwp_name += ".dwp";
12478       dbfd = open_dwp_file (per_objfile, dwp_name.c_str ());
12479     }
12480
12481   if (dbfd == NULL)
12482     {
12483       dwarf_read_debug_printf ("DWP file not found: %s", dwp_name.c_str ());
12484
12485       return std::unique_ptr<dwp_file> ();
12486     }
12487
12488   const char *name = bfd_get_filename (dbfd.get ());
12489   std::unique_ptr<struct dwp_file> dwp_file
12490     (new struct dwp_file (name, std::move (dbfd)));
12491
12492   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
12493   dwp_file->elf_sections =
12494     OBSTACK_CALLOC (&per_objfile->per_bfd->obstack,
12495                     dwp_file->num_sections, asection *);
12496
12497   for (asection *sec : gdb_bfd_sections (dwp_file->dbfd))
12498     dwarf2_locate_common_dwp_sections (dwp_file->dbfd.get (), sec,
12499                                        dwp_file.get ());
12500
12501   dwp_file->cus = create_dwp_hash_table (per_objfile, dwp_file.get (), 0);
12502
12503   dwp_file->tus = create_dwp_hash_table (per_objfile, dwp_file.get (), 1);
12504
12505   /* The DWP file version is stored in the hash table.  Oh well.  */
12506   if (dwp_file->cus && dwp_file->tus
12507       && dwp_file->cus->version != dwp_file->tus->version)
12508     {
12509       /* Technically speaking, we should try to limp along, but this is
12510          pretty bizarre.  We use pulongest here because that's the established
12511          portability solution (e.g, we cannot use %u for uint32_t).  */
12512       error (_("Dwarf Error: DWP file CU version %s doesn't match"
12513                " TU version %s [in DWP file %s]"),
12514              pulongest (dwp_file->cus->version),
12515              pulongest (dwp_file->tus->version), dwp_name.c_str ());
12516     }
12517
12518   if (dwp_file->cus)
12519     dwp_file->version = dwp_file->cus->version;
12520   else if (dwp_file->tus)
12521     dwp_file->version = dwp_file->tus->version;
12522   else
12523     dwp_file->version = 2;
12524
12525   for (asection *sec : gdb_bfd_sections (dwp_file->dbfd))
12526     {
12527       if (dwp_file->version == 2)
12528         dwarf2_locate_v2_dwp_sections (dwp_file->dbfd.get (), sec,
12529                                        dwp_file.get ());
12530       else
12531         dwarf2_locate_v5_dwp_sections (dwp_file->dbfd.get (), sec,
12532                                        dwp_file.get ());
12533     }
12534
12535   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table ();
12536   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table ();
12537
12538   dwarf_read_debug_printf ("DWP file found: %s", dwp_file->name);
12539   dwarf_read_debug_printf ("    %s CUs, %s TUs",
12540                            pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
12541                            pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
12542
12543   return dwp_file;
12544 }
12545
12546 /* Wrapper around open_and_init_dwp_file, only open it once.  */
12547
12548 static struct dwp_file *
12549 get_dwp_file (dwarf2_per_objfile *per_objfile)
12550 {
12551   if (!per_objfile->per_bfd->dwp_checked)
12552     {
12553       per_objfile->per_bfd->dwp_file = open_and_init_dwp_file (per_objfile);
12554       per_objfile->per_bfd->dwp_checked = 1;
12555     }
12556   return per_objfile->per_bfd->dwp_file.get ();
12557 }
12558
12559 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
12560    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
12561    or in the DWP file for the objfile, referenced by THIS_UNIT.
12562    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
12563    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
12564
12565    This is called, for example, when wanting to read a variable with a
12566    complex location.  Therefore we don't want to do file i/o for every call.
12567    Therefore we don't want to look for a DWO file on every call.
12568    Therefore we first see if we've already seen SIGNATURE in a DWP file,
12569    then we check if we've already seen DWO_NAME, and only THEN do we check
12570    for a DWO file.
12571
12572    The result is a pointer to the dwo_unit object or NULL if we didn't find it
12573    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
12574
12575 static struct dwo_unit *
12576 lookup_dwo_cutu (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
12577                  ULONGEST signature, int is_debug_types)
12578 {
12579   dwarf2_per_objfile *per_objfile = cu->per_objfile;
12580   struct objfile *objfile = per_objfile->objfile;
12581   const char *kind = is_debug_types ? "TU" : "CU";
12582   void **dwo_file_slot;
12583   struct dwo_file *dwo_file;
12584   struct dwp_file *dwp_file;
12585
12586   /* First see if there's a DWP file.
12587      If we have a DWP file but didn't find the DWO inside it, don't
12588      look for the original DWO file.  It makes gdb behave differently
12589      depending on whether one is debugging in the build tree.  */
12590
12591   dwp_file = get_dwp_file (per_objfile);
12592   if (dwp_file != NULL)
12593     {
12594       const struct dwp_hash_table *dwp_htab =
12595         is_debug_types ? dwp_file->tus : dwp_file->cus;
12596
12597       if (dwp_htab != NULL)
12598         {
12599           struct dwo_unit *dwo_cutu =
12600             lookup_dwo_unit_in_dwp (per_objfile, dwp_file, comp_dir, signature,
12601                                     is_debug_types);
12602
12603           if (dwo_cutu != NULL)
12604             {
12605               dwarf_read_debug_printf ("Virtual DWO %s %s found: @%s",
12606                                        kind, hex_string (signature),
12607                                        host_address_to_string (dwo_cutu));
12608
12609               return dwo_cutu;
12610             }
12611         }
12612     }
12613   else
12614     {
12615       /* No DWP file, look for the DWO file.  */
12616
12617       dwo_file_slot = lookup_dwo_file_slot (per_objfile, dwo_name, comp_dir);
12618       if (*dwo_file_slot == NULL)
12619         {
12620           /* Read in the file and build a table of the CUs/TUs it contains.  */
12621           *dwo_file_slot = open_and_init_dwo_file (cu, dwo_name, comp_dir);
12622         }
12623       /* NOTE: This will be NULL if unable to open the file.  */
12624       dwo_file = (struct dwo_file *) *dwo_file_slot;
12625
12626       if (dwo_file != NULL)
12627         {
12628           struct dwo_unit *dwo_cutu = NULL;
12629
12630           if (is_debug_types && dwo_file->tus)
12631             {
12632               struct dwo_unit find_dwo_cutu;
12633
12634               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12635               find_dwo_cutu.signature = signature;
12636               dwo_cutu
12637                 = (struct dwo_unit *) htab_find (dwo_file->tus.get (),
12638                                                  &find_dwo_cutu);
12639             }
12640           else if (!is_debug_types && dwo_file->cus)
12641             {
12642               struct dwo_unit find_dwo_cutu;
12643
12644               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12645               find_dwo_cutu.signature = signature;
12646               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus.get (),
12647                                                        &find_dwo_cutu);
12648             }
12649
12650           if (dwo_cutu != NULL)
12651             {
12652               dwarf_read_debug_printf ("DWO %s %s(%s) found: @%s",
12653                                        kind, dwo_name, hex_string (signature),
12654                                        host_address_to_string (dwo_cutu));
12655
12656               return dwo_cutu;
12657             }
12658         }
12659     }
12660
12661   /* We didn't find it.  This could mean a dwo_id mismatch, or
12662      someone deleted the DWO/DWP file, or the search path isn't set up
12663      correctly to find the file.  */
12664
12665   dwarf_read_debug_printf ("DWO %s %s(%s) not found",
12666                            kind, dwo_name, hex_string (signature));
12667
12668   /* This is a warning and not a complaint because it can be caused by
12669      pilot error (e.g., user accidentally deleting the DWO).  */
12670   {
12671     /* Print the name of the DWP file if we looked there, helps the user
12672        better diagnose the problem.  */
12673     std::string dwp_text;
12674
12675     if (dwp_file != NULL)
12676       dwp_text = string_printf (" [in DWP file %s]",
12677                                 lbasename (dwp_file->name));
12678
12679     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
12680                " [in module %s]"),
12681              kind, dwo_name, hex_string (signature), dwp_text.c_str (), kind,
12682              sect_offset_str (cu->per_cu->sect_off), objfile_name (objfile));
12683   }
12684   return NULL;
12685 }
12686
12687 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
12688    See lookup_dwo_cutu_unit for details.  */
12689
12690 static struct dwo_unit *
12691 lookup_dwo_comp_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir,
12692                       ULONGEST signature)
12693 {
12694   gdb_assert (!cu->per_cu->is_debug_types);
12695
12696   return lookup_dwo_cutu (cu, dwo_name, comp_dir, signature, 0);
12697 }
12698
12699 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
12700    See lookup_dwo_cutu_unit for details.  */
12701
12702 static struct dwo_unit *
12703 lookup_dwo_type_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir)
12704 {
12705   gdb_assert (cu->per_cu->is_debug_types);
12706
12707   signatured_type *sig_type = (signatured_type *) cu->per_cu;
12708
12709   return lookup_dwo_cutu (cu, dwo_name, comp_dir, sig_type->signature, 1);
12710 }
12711
12712 /* Traversal function for queue_and_load_all_dwo_tus.  */
12713
12714 static int
12715 queue_and_load_dwo_tu (void **slot, void *info)
12716 {
12717   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
12718   dwarf2_cu *cu = (dwarf2_cu *) info;
12719   ULONGEST signature = dwo_unit->signature;
12720   signatured_type *sig_type = lookup_dwo_signatured_type (cu, signature);
12721
12722   if (sig_type != NULL)
12723     {
12724       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
12725          a real dependency of PER_CU on SIG_TYPE.  That is detected later
12726          while processing PER_CU.  */
12727       if (maybe_queue_comp_unit (NULL, sig_type, cu->per_objfile,
12728                                  cu->per_cu->lang))
12729         load_full_type_unit (sig_type, cu->per_objfile);
12730       cu->per_cu->imported_symtabs_push (sig_type);
12731     }
12732
12733   return 1;
12734 }
12735
12736 /* Queue all TUs contained in the DWO of CU to be read in.
12737    The DWO may have the only definition of the type, though it may not be
12738    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
12739    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
12740
12741 static void
12742 queue_and_load_all_dwo_tus (dwarf2_cu *cu)
12743 {
12744   struct dwo_unit *dwo_unit;
12745   struct dwo_file *dwo_file;
12746
12747   gdb_assert (cu != nullptr);
12748   gdb_assert (!cu->per_cu->is_debug_types);
12749   gdb_assert (get_dwp_file (cu->per_objfile) == nullptr);
12750
12751   dwo_unit = cu->dwo_unit;
12752   gdb_assert (dwo_unit != NULL);
12753
12754   dwo_file = dwo_unit->dwo_file;
12755   if (dwo_file->tus != NULL)
12756     htab_traverse_noresize (dwo_file->tus.get (), queue_and_load_dwo_tu, cu);
12757 }
12758
12759 /* Read in various DIEs.  */
12760
12761 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
12762    Inherit only the children of the DW_AT_abstract_origin DIE not being
12763    already referenced by DW_AT_abstract_origin from the children of the
12764    current DIE.  */
12765
12766 static void
12767 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
12768 {
12769   struct die_info *child_die;
12770   sect_offset *offsetp;
12771   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
12772   struct die_info *origin_die;
12773   /* Iterator of the ORIGIN_DIE children.  */
12774   struct die_info *origin_child_die;
12775   struct attribute *attr;
12776   struct dwarf2_cu *origin_cu;
12777   struct pending **origin_previous_list_in_scope;
12778
12779   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12780   if (!attr)
12781     return;
12782
12783   /* Note that following die references may follow to a die in a
12784      different cu.  */
12785
12786   origin_cu = cu;
12787   origin_die = follow_die_ref (die, attr, &origin_cu);
12788
12789   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
12790      symbols in.  */
12791   origin_previous_list_in_scope = origin_cu->list_in_scope;
12792   origin_cu->list_in_scope = cu->list_in_scope;
12793
12794   if (die->tag != origin_die->tag
12795       && !(die->tag == DW_TAG_inlined_subroutine
12796            && origin_die->tag == DW_TAG_subprogram))
12797     complaint (_("DIE %s and its abstract origin %s have different tags"),
12798                sect_offset_str (die->sect_off),
12799                sect_offset_str (origin_die->sect_off));
12800
12801   /* Find if the concrete and abstract trees are structurally the
12802      same.  This is a shallow traversal and it is not bullet-proof;
12803      the compiler can trick the debugger into believing that the trees
12804      are isomorphic, whereas they actually are not.  However, the
12805      likelyhood of this happening is pretty low, and a full-fledged
12806      check would be an overkill.  */
12807   bool are_isomorphic = true;
12808   die_info *concrete_child = die->child;
12809   die_info *abstract_child = origin_die->child;
12810   while (concrete_child != nullptr || abstract_child != nullptr)
12811     {
12812       if (concrete_child == nullptr
12813           || abstract_child == nullptr
12814           || concrete_child->tag != abstract_child->tag)
12815         {
12816           are_isomorphic = false;
12817           break;
12818         }
12819
12820       concrete_child = concrete_child->sibling;
12821       abstract_child = abstract_child->sibling;
12822     }
12823
12824   /* Walk the origin's children in parallel to the concrete children.
12825      This helps match an origin child in case the debug info misses
12826      DW_AT_abstract_origin attributes.  Keep in mind that the abstract
12827      origin tree may not have the same tree structure as the concrete
12828      DIE, though.  */
12829   die_info *corresponding_abstract_child
12830     = are_isomorphic ? origin_die->child : nullptr;
12831
12832   std::vector<sect_offset> offsets;
12833
12834   for (child_die = die->child;
12835        child_die && child_die->tag;
12836        child_die = child_die->sibling)
12837     {
12838       struct die_info *child_origin_die;
12839       struct dwarf2_cu *child_origin_cu;
12840
12841       /* We are trying to process concrete instance entries:
12842          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
12843          it's not relevant to our analysis here. i.e. detecting DIEs that are
12844          present in the abstract instance but not referenced in the concrete
12845          one.  */
12846       if (child_die->tag == DW_TAG_call_site
12847           || child_die->tag == DW_TAG_GNU_call_site)
12848         {
12849           if (are_isomorphic)
12850             corresponding_abstract_child
12851               = corresponding_abstract_child->sibling;
12852           continue;
12853         }
12854
12855       /* For each CHILD_DIE, find the corresponding child of
12856          ORIGIN_DIE.  If there is more than one layer of
12857          DW_AT_abstract_origin, follow them all; there shouldn't be,
12858          but GCC versions at least through 4.4 generate this (GCC PR
12859          40573).  */
12860       child_origin_die = child_die;
12861       child_origin_cu = cu;
12862       while (1)
12863         {
12864           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
12865                               child_origin_cu);
12866           if (attr == NULL)
12867             break;
12868           child_origin_die = follow_die_ref (child_origin_die, attr,
12869                                              &child_origin_cu);
12870         }
12871
12872       /* If missing DW_AT_abstract_origin, try the corresponding child
12873          of the origin.  Clang emits such lexical scopes.  */
12874       if (child_origin_die == child_die
12875           && dwarf2_attr (child_die, DW_AT_abstract_origin, cu) == nullptr
12876           && are_isomorphic
12877           && child_die->tag == DW_TAG_lexical_block)
12878         child_origin_die = corresponding_abstract_child;
12879
12880       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
12881          counterpart may exist.  */
12882       if (child_origin_die != child_die)
12883         {
12884           if (child_die->tag != child_origin_die->tag
12885               && !(child_die->tag == DW_TAG_inlined_subroutine
12886                    && child_origin_die->tag == DW_TAG_subprogram))
12887             complaint (_("Child DIE %s and its abstract origin %s have "
12888                          "different tags"),
12889                        sect_offset_str (child_die->sect_off),
12890                        sect_offset_str (child_origin_die->sect_off));
12891           if (child_origin_die->parent != origin_die)
12892             complaint (_("Child DIE %s and its abstract origin %s have "
12893                          "different parents"),
12894                        sect_offset_str (child_die->sect_off),
12895                        sect_offset_str (child_origin_die->sect_off));
12896           else
12897             offsets.push_back (child_origin_die->sect_off);
12898         }
12899
12900       if (are_isomorphic)
12901         corresponding_abstract_child = corresponding_abstract_child->sibling;
12902     }
12903   std::sort (offsets.begin (), offsets.end ());
12904   sect_offset *offsets_end = offsets.data () + offsets.size ();
12905   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
12906     if (offsetp[-1] == *offsetp)
12907       complaint (_("Multiple children of DIE %s refer "
12908                    "to DIE %s as their abstract origin"),
12909                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
12910
12911   offsetp = offsets.data ();
12912   origin_child_die = origin_die->child;
12913   while (origin_child_die && origin_child_die->tag)
12914     {
12915       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
12916       while (offsetp < offsets_end
12917              && *offsetp < origin_child_die->sect_off)
12918         offsetp++;
12919       if (offsetp >= offsets_end
12920           || *offsetp > origin_child_die->sect_off)
12921         {
12922           /* Found that ORIGIN_CHILD_DIE is really not referenced.
12923              Check whether we're already processing ORIGIN_CHILD_DIE.
12924              This can happen with mutually referenced abstract_origins.
12925              PR 16581.  */
12926           if (!origin_child_die->in_process)
12927             process_die (origin_child_die, origin_cu);
12928         }
12929       origin_child_die = origin_child_die->sibling;
12930     }
12931   origin_cu->list_in_scope = origin_previous_list_in_scope;
12932
12933   if (cu != origin_cu)
12934     compute_delayed_physnames (origin_cu);
12935 }
12936
12937 static void
12938 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
12939 {
12940   struct objfile *objfile = cu->per_objfile->objfile;
12941   struct gdbarch *gdbarch = objfile->arch ();
12942   struct context_stack *newobj;
12943   CORE_ADDR lowpc;
12944   CORE_ADDR highpc;
12945   struct die_info *child_die;
12946   struct attribute *attr, *call_line, *call_file;
12947   const char *name;
12948   CORE_ADDR baseaddr;
12949   struct block *block;
12950   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
12951   std::vector<struct symbol *> template_args;
12952   struct template_symbol *templ_func = NULL;
12953
12954   if (inlined_func)
12955     {
12956       /* If we do not have call site information, we can't show the
12957          caller of this inlined function.  That's too confusing, so
12958          only use the scope for local variables.  */
12959       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
12960       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
12961       if (call_line == NULL || call_file == NULL)
12962         {
12963           read_lexical_block_scope (die, cu);
12964           return;
12965         }
12966     }
12967
12968   baseaddr = objfile->text_section_offset ();
12969
12970   name = dwarf2_name (die, cu);
12971
12972   /* Ignore functions with missing or empty names.  These are actually
12973      illegal according to the DWARF standard.  */
12974   if (name == NULL)
12975     {
12976       complaint (_("missing name for subprogram DIE at %s"),
12977                  sect_offset_str (die->sect_off));
12978       return;
12979     }
12980
12981   /* Ignore functions with missing or invalid low and high pc attributes.  */
12982   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
12983       <= PC_BOUNDS_INVALID)
12984     {
12985       attr = dwarf2_attr (die, DW_AT_external, cu);
12986       if (attr == nullptr || !attr->as_boolean ())
12987         complaint (_("cannot get low and high bounds "
12988                      "for subprogram DIE at %s"),
12989                    sect_offset_str (die->sect_off));
12990       return;
12991     }
12992
12993   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12994   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12995
12996   /* If we have any template arguments, then we must allocate a
12997      different sort of symbol.  */
12998   for (child_die = die->child; child_die; child_die = child_die->sibling)
12999     {
13000       if (child_die->tag == DW_TAG_template_type_param
13001           || child_die->tag == DW_TAG_template_value_param)
13002         {
13003           templ_func = new (&objfile->objfile_obstack) template_symbol;
13004           templ_func->subclass = SYMBOL_TEMPLATE;
13005           break;
13006         }
13007     }
13008
13009   gdb_assert (cu->get_builder () != nullptr);
13010   newobj = cu->get_builder ()->push_context (0, lowpc);
13011   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13012                              (struct symbol *) templ_func);
13013
13014   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
13015     set_objfile_main_name (objfile, newobj->name->linkage_name (),
13016                            cu->per_cu->lang);
13017
13018   /* If there is a location expression for DW_AT_frame_base, record
13019      it.  */
13020   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13021   if (attr != nullptr)
13022     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13023
13024   /* If there is a location for the static link, record it.  */
13025   newobj->static_link = NULL;
13026   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13027   if (attr != nullptr)
13028     {
13029       newobj->static_link
13030         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13031       attr_to_dynamic_prop (attr, die, cu, newobj->static_link,
13032                             cu->addr_type ());
13033     }
13034
13035   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13036
13037   if (die->child != NULL)
13038     {
13039       child_die = die->child;
13040       while (child_die && child_die->tag)
13041         {
13042           if (child_die->tag == DW_TAG_template_type_param
13043               || child_die->tag == DW_TAG_template_value_param)
13044             {
13045               struct symbol *arg = new_symbol (child_die, NULL, cu);
13046
13047               if (arg != NULL)
13048                 template_args.push_back (arg);
13049             }
13050           else
13051             process_die (child_die, cu);
13052           child_die = child_die->sibling;
13053         }
13054     }
13055
13056   inherit_abstract_dies (die, cu);
13057
13058   /* If we have a DW_AT_specification, we might need to import using
13059      directives from the context of the specification DIE.  See the
13060      comment in determine_prefix.  */
13061   if (cu->per_cu->lang == language_cplus
13062       && dwarf2_attr (die, DW_AT_specification, cu))
13063     {
13064       struct dwarf2_cu *spec_cu = cu;
13065       struct die_info *spec_die = die_specification (die, &spec_cu);
13066
13067       while (spec_die)
13068         {
13069           child_die = spec_die->child;
13070           while (child_die && child_die->tag)
13071             {
13072               if (child_die->tag == DW_TAG_imported_module)
13073                 process_die (child_die, spec_cu);
13074               child_die = child_die->sibling;
13075             }
13076
13077           /* In some cases, GCC generates specification DIEs that
13078              themselves contain DW_AT_specification attributes.  */
13079           spec_die = die_specification (spec_die, &spec_cu);
13080         }
13081     }
13082
13083   struct context_stack cstk = cu->get_builder ()->pop_context ();
13084   /* Make a block for the local symbols within.  */
13085   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13086                                      cstk.static_link, lowpc, highpc);
13087
13088   /* For C++, set the block's scope.  */
13089   if ((cu->per_cu->lang == language_cplus
13090        || cu->per_cu->lang == language_fortran
13091        || cu->per_cu->lang == language_d
13092        || cu->per_cu->lang == language_rust)
13093       && cu->processing_has_namespace_info)
13094     block_set_scope (block, determine_prefix (die, cu),
13095                      &objfile->objfile_obstack);
13096
13097   /* If we have address ranges, record them.  */
13098   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13099
13100   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13101
13102   /* Attach template arguments to function.  */
13103   if (!template_args.empty ())
13104     {
13105       gdb_assert (templ_func != NULL);
13106
13107       templ_func->n_template_arguments = template_args.size ();
13108       templ_func->template_arguments
13109         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13110                      templ_func->n_template_arguments);
13111       memcpy (templ_func->template_arguments,
13112               template_args.data (),
13113               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13114
13115       /* Make sure that the symtab is set on the new symbols.  Even
13116          though they don't appear in this symtab directly, other parts
13117          of gdb assume that symbols do, and this is reasonably
13118          true.  */
13119       for (symbol *sym : template_args)
13120         symbol_set_symtab (sym, symbol_symtab (templ_func));
13121     }
13122
13123   /* In C++, we can have functions nested inside functions (e.g., when
13124      a function declares a class that has methods).  This means that
13125      when we finish processing a function scope, we may need to go
13126      back to building a containing block's symbol lists.  */
13127   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13128   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13129
13130   /* If we've finished processing a top-level function, subsequent
13131      symbols go in the file symbol list.  */
13132   if (cu->get_builder ()->outermost_context_p ())
13133     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13134 }
13135
13136 /* Process all the DIES contained within a lexical block scope.  Start
13137    a new scope, process the dies, and then close the scope.  */
13138
13139 static void
13140 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13141 {
13142   struct objfile *objfile = cu->per_objfile->objfile;
13143   struct gdbarch *gdbarch = objfile->arch ();
13144   CORE_ADDR lowpc, highpc;
13145   struct die_info *child_die;
13146   CORE_ADDR baseaddr;
13147
13148   baseaddr = objfile->text_section_offset ();
13149
13150   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13151   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13152      as multiple lexical blocks?  Handling children in a sane way would
13153      be nasty.  Might be easier to properly extend generic blocks to
13154      describe ranges.  */
13155   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13156     {
13157     case PC_BOUNDS_NOT_PRESENT:
13158       /* DW_TAG_lexical_block has no attributes, process its children as if
13159          there was no wrapping by that DW_TAG_lexical_block.
13160          GCC does no longer produces such DWARF since GCC r224161.  */
13161       for (child_die = die->child;
13162            child_die != NULL && child_die->tag;
13163            child_die = child_die->sibling)
13164         {
13165           /* We might already be processing this DIE.  This can happen
13166              in an unusual circumstance -- where a subroutine A
13167              appears lexically in another subroutine B, but A actually
13168              inlines B.  The recursion is broken here, rather than in
13169              inherit_abstract_dies, because it seems better to simply
13170              drop concrete children here.  */
13171           if (!child_die->in_process)
13172             process_die (child_die, cu);
13173         }
13174       return;
13175     case PC_BOUNDS_INVALID:
13176       return;
13177     }
13178   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13179   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13180
13181   cu->get_builder ()->push_context (0, lowpc);
13182   if (die->child != NULL)
13183     {
13184       child_die = die->child;
13185       while (child_die && child_die->tag)
13186         {
13187           process_die (child_die, cu);
13188           child_die = child_die->sibling;
13189         }
13190     }
13191   inherit_abstract_dies (die, cu);
13192   struct context_stack cstk = cu->get_builder ()->pop_context ();
13193
13194   if (*cu->get_builder ()->get_local_symbols () != NULL
13195       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13196     {
13197       struct block *block
13198         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13199                                      cstk.start_addr, highpc);
13200
13201       /* Note that recording ranges after traversing children, as we
13202          do here, means that recording a parent's ranges entails
13203          walking across all its children's ranges as they appear in
13204          the address map, which is quadratic behavior.
13205
13206          It would be nicer to record the parent's ranges before
13207          traversing its children, simply overriding whatever you find
13208          there.  But since we don't even decide whether to create a
13209          block until after we've traversed its children, that's hard
13210          to do.  */
13211       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13212     }
13213   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13214   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13215 }
13216
13217 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13218
13219 static void
13220 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13221 {
13222   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13223   struct objfile *objfile = per_objfile->objfile;
13224   struct gdbarch *gdbarch = objfile->arch ();
13225   CORE_ADDR pc, baseaddr;
13226   struct attribute *attr;
13227   struct call_site *call_site, call_site_local;
13228   void **slot;
13229   int nparams;
13230   struct die_info *child_die;
13231
13232   baseaddr = objfile->text_section_offset ();
13233
13234   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13235   if (attr == NULL)
13236     {
13237       /* This was a pre-DWARF-5 GNU extension alias
13238          for DW_AT_call_return_pc.  */
13239       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13240     }
13241   if (!attr)
13242     {
13243       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13244                    "DIE %s [in module %s]"),
13245                  sect_offset_str (die->sect_off), objfile_name (objfile));
13246       return;
13247     }
13248   pc = attr->as_address () + baseaddr;
13249   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13250
13251   if (cu->call_site_htab == NULL)
13252     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13253                                                NULL, &objfile->objfile_obstack,
13254                                                hashtab_obstack_allocate, NULL);
13255   call_site_local.pc = pc;
13256   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13257   if (*slot != NULL)
13258     {
13259       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13260                    "DIE %s [in module %s]"),
13261                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13262                  objfile_name (objfile));
13263       return;
13264     }
13265
13266   /* Count parameters at the caller.  */
13267
13268   nparams = 0;
13269   for (child_die = die->child; child_die && child_die->tag;
13270        child_die = child_die->sibling)
13271     {
13272       if (child_die->tag != DW_TAG_call_site_parameter
13273           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13274         {
13275           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13276                        "DW_TAG_call_site child DIE %s [in module %s]"),
13277                      child_die->tag, sect_offset_str (child_die->sect_off),
13278                      objfile_name (objfile));
13279           continue;
13280         }
13281
13282       nparams++;
13283     }
13284
13285   call_site
13286     = ((struct call_site *)
13287        obstack_alloc (&objfile->objfile_obstack,
13288                       sizeof (*call_site)
13289                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13290   *slot = call_site;
13291   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13292   call_site->pc = pc;
13293
13294   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13295       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13296     {
13297       struct die_info *func_die;
13298
13299       /* Skip also over DW_TAG_inlined_subroutine.  */
13300       for (func_die = die->parent;
13301            func_die && func_die->tag != DW_TAG_subprogram
13302            && func_die->tag != DW_TAG_subroutine_type;
13303            func_die = func_die->parent);
13304
13305       /* DW_AT_call_all_calls is a superset
13306          of DW_AT_call_all_tail_calls.  */
13307       if (func_die
13308           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13309           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13310           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13311           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13312         {
13313           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13314              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13315              both the initial caller containing the real return address PC and
13316              the final callee containing the current PC of a chain of tail
13317              calls do not need to have the tail call list complete.  But any
13318              function candidate for a virtual tail call frame searched via
13319              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13320              determined unambiguously.  */
13321         }
13322       else
13323         {
13324           struct type *func_type = NULL;
13325
13326           if (func_die)
13327             func_type = get_die_type (func_die, cu);
13328           if (func_type != NULL)
13329             {
13330               gdb_assert (func_type->code () == TYPE_CODE_FUNC);
13331
13332               /* Enlist this call site to the function.  */
13333               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13334               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13335             }
13336           else
13337             complaint (_("Cannot find function owning DW_TAG_call_site "
13338                          "DIE %s [in module %s]"),
13339                        sect_offset_str (die->sect_off), objfile_name (objfile));
13340         }
13341     }
13342
13343   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13344   if (attr == NULL)
13345     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13346   if (attr == NULL)
13347     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13348   if (attr == NULL)
13349     {
13350       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13351       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13352     }
13353   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13354   if (!attr || (attr->form_is_block () && attr->as_block ()->size == 0))
13355     /* Keep NULL DWARF_BLOCK.  */;
13356   else if (attr->form_is_block ())
13357     {
13358       struct dwarf2_locexpr_baton *dlbaton;
13359       struct dwarf_block *block = attr->as_block ();
13360
13361       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13362       dlbaton->data = block->data;
13363       dlbaton->size = block->size;
13364       dlbaton->per_objfile = per_objfile;
13365       dlbaton->per_cu = cu->per_cu;
13366
13367       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13368     }
13369   else if (attr->form_is_ref ())
13370     {
13371       struct dwarf2_cu *target_cu = cu;
13372       struct die_info *target_die;
13373
13374       target_die = follow_die_ref (die, attr, &target_cu);
13375       gdb_assert (target_cu->per_objfile->objfile == objfile);
13376       if (die_is_declaration (target_die, target_cu))
13377         {
13378           const char *target_physname;
13379
13380           /* Prefer the mangled name; otherwise compute the demangled one.  */
13381           target_physname = dw2_linkage_name (target_die, target_cu);
13382           if (target_physname == NULL)
13383             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13384           if (target_physname == NULL)
13385             complaint (_("DW_AT_call_target target DIE has invalid "
13386                          "physname, for referencing DIE %s [in module %s]"),
13387                        sect_offset_str (die->sect_off), objfile_name (objfile));
13388           else
13389             SET_FIELD_PHYSNAME (call_site->target, target_physname);
13390         }
13391       else
13392         {
13393           CORE_ADDR lowpc;
13394
13395           /* DW_AT_entry_pc should be preferred.  */
13396           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13397               <= PC_BOUNDS_INVALID)
13398             complaint (_("DW_AT_call_target target DIE has invalid "
13399                          "low pc, for referencing DIE %s [in module %s]"),
13400                        sect_offset_str (die->sect_off), objfile_name (objfile));
13401           else
13402             {
13403               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13404               SET_FIELD_PHYSADDR (call_site->target, lowpc);
13405             }
13406         }
13407     }
13408   else
13409     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
13410                  "block nor reference, for DIE %s [in module %s]"),
13411                sect_offset_str (die->sect_off), objfile_name (objfile));
13412
13413   call_site->per_cu = cu->per_cu;
13414   call_site->per_objfile = per_objfile;
13415
13416   for (child_die = die->child;
13417        child_die && child_die->tag;
13418        child_die = child_die->sibling)
13419     {
13420       struct call_site_parameter *parameter;
13421       struct attribute *loc, *origin;
13422
13423       if (child_die->tag != DW_TAG_call_site_parameter
13424           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13425         {
13426           /* Already printed the complaint above.  */
13427           continue;
13428         }
13429
13430       gdb_assert (call_site->parameter_count < nparams);
13431       parameter = &call_site->parameter[call_site->parameter_count];
13432
13433       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
13434          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
13435          register is contained in DW_AT_call_value.  */
13436
13437       loc = dwarf2_attr (child_die, DW_AT_location, cu);
13438       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
13439       if (origin == NULL)
13440         {
13441           /* This was a pre-DWARF-5 GNU extension alias
13442              for DW_AT_call_parameter.  */
13443           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
13444         }
13445       if (loc == NULL && origin != NULL && origin->form_is_ref ())
13446         {
13447           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
13448
13449           sect_offset sect_off = origin->get_ref_die_offset ();
13450           if (!cu->header.offset_in_cu_p (sect_off))
13451             {
13452               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
13453                  binding can be done only inside one CU.  Such referenced DIE
13454                  therefore cannot be even moved to DW_TAG_partial_unit.  */
13455               complaint (_("DW_AT_call_parameter offset is not in CU for "
13456                            "DW_TAG_call_site child DIE %s [in module %s]"),
13457                          sect_offset_str (child_die->sect_off),
13458                          objfile_name (objfile));
13459               continue;
13460             }
13461           parameter->u.param_cu_off
13462             = (cu_offset) (sect_off - cu->header.sect_off);
13463         }
13464       else if (loc == NULL || origin != NULL || !loc->form_is_block ())
13465         {
13466           complaint (_("No DW_FORM_block* DW_AT_location for "
13467                        "DW_TAG_call_site child DIE %s [in module %s]"),
13468                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
13469           continue;
13470         }
13471       else
13472         {
13473           struct dwarf_block *block = loc->as_block ();
13474
13475           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
13476             (block->data, &block->data[block->size]);
13477           if (parameter->u.dwarf_reg != -1)
13478             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
13479           else if (dwarf_block_to_sp_offset (gdbarch, block->data,
13480                                     &block->data[block->size],
13481                                              &parameter->u.fb_offset))
13482             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
13483           else
13484             {
13485               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
13486                            "for DW_FORM_block* DW_AT_location is supported for "
13487                            "DW_TAG_call_site child DIE %s "
13488                            "[in module %s]"),
13489                          sect_offset_str (child_die->sect_off),
13490                          objfile_name (objfile));
13491               continue;
13492             }
13493         }
13494
13495       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
13496       if (attr == NULL)
13497         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
13498       if (attr == NULL || !attr->form_is_block ())
13499         {
13500           complaint (_("No DW_FORM_block* DW_AT_call_value for "
13501                        "DW_TAG_call_site child DIE %s [in module %s]"),
13502                      sect_offset_str (child_die->sect_off),
13503                      objfile_name (objfile));
13504           continue;
13505         }
13506
13507       struct dwarf_block *block = attr->as_block ();
13508       parameter->value = block->data;
13509       parameter->value_size = block->size;
13510
13511       /* Parameters are not pre-cleared by memset above.  */
13512       parameter->data_value = NULL;
13513       parameter->data_value_size = 0;
13514       call_site->parameter_count++;
13515
13516       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
13517       if (attr == NULL)
13518         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
13519       if (attr != nullptr)
13520         {
13521           if (!attr->form_is_block ())
13522             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
13523                          "DW_TAG_call_site child DIE %s [in module %s]"),
13524                        sect_offset_str (child_die->sect_off),
13525                        objfile_name (objfile));
13526           else
13527             {
13528               block = attr->as_block ();
13529               parameter->data_value = block->data;
13530               parameter->data_value_size = block->size;
13531             }
13532         }
13533     }
13534 }
13535
13536 /* Helper function for read_variable.  If DIE represents a virtual
13537    table, then return the type of the concrete object that is
13538    associated with the virtual table.  Otherwise, return NULL.  */
13539
13540 static struct type *
13541 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13542 {
13543   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
13544   if (attr == NULL)
13545     return NULL;
13546
13547   /* Find the type DIE.  */
13548   struct die_info *type_die = NULL;
13549   struct dwarf2_cu *type_cu = cu;
13550
13551   if (attr->form_is_ref ())
13552     type_die = follow_die_ref (die, attr, &type_cu);
13553   if (type_die == NULL)
13554     return NULL;
13555
13556   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
13557     return NULL;
13558   return die_containing_type (type_die, type_cu);
13559 }
13560
13561 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
13562
13563 static void
13564 read_variable (struct die_info *die, struct dwarf2_cu *cu)
13565 {
13566   struct rust_vtable_symbol *storage = NULL;
13567
13568   if (cu->per_cu->lang == language_rust)
13569     {
13570       struct type *containing_type = rust_containing_type (die, cu);
13571
13572       if (containing_type != NULL)
13573         {
13574           struct objfile *objfile = cu->per_objfile->objfile;
13575
13576           storage = new (&objfile->objfile_obstack) rust_vtable_symbol;
13577           storage->concrete_type = containing_type;
13578           storage->subclass = SYMBOL_RUST_VTABLE;
13579         }
13580     }
13581
13582   struct symbol *res = new_symbol (die, NULL, cu, storage);
13583   struct attribute *abstract_origin
13584     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13585   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
13586   if (res == NULL && loc && abstract_origin)
13587     {
13588       /* We have a variable without a name, but with a location and an abstract
13589          origin.  This may be a concrete instance of an abstract variable
13590          referenced from an DW_OP_GNU_variable_value, so save it to find it back
13591          later.  */
13592       struct dwarf2_cu *origin_cu = cu;
13593       struct die_info *origin_die
13594         = follow_die_ref (die, abstract_origin, &origin_cu);
13595       dwarf2_per_objfile *per_objfile = cu->per_objfile;
13596       per_objfile->per_bfd->abstract_to_concrete
13597         [origin_die->sect_off].push_back (die->sect_off);
13598     }
13599 }
13600
13601 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
13602    reading .debug_rnglists.
13603    Callback's type should be:
13604     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13605    Return true if the attributes are present and valid, otherwise,
13606    return false.  */
13607
13608 template <typename Callback>
13609 static bool
13610 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
13611                          dwarf_tag tag, Callback &&callback)
13612 {
13613   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13614   struct objfile *objfile = per_objfile->objfile;
13615   bfd *obfd = objfile->obfd;
13616   /* Base address selection entry.  */
13617   gdb::optional<CORE_ADDR> base;
13618   const gdb_byte *buffer;
13619   CORE_ADDR baseaddr;
13620   bool overflow = false;
13621   ULONGEST addr_index;
13622   struct dwarf2_section_info *rnglists_section;
13623
13624   base = cu->base_address;
13625   rnglists_section = cu_debug_rnglists_section (cu, tag);
13626   rnglists_section->read (objfile);
13627
13628   if (offset >= rnglists_section->size)
13629     {
13630       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
13631                  offset);
13632       return false;
13633     }
13634   buffer = rnglists_section->buffer + offset;
13635
13636   baseaddr = objfile->text_section_offset ();
13637
13638   while (1)
13639     {
13640       /* Initialize it due to a false compiler warning.  */
13641       CORE_ADDR range_beginning = 0, range_end = 0;
13642       const gdb_byte *buf_end = (rnglists_section->buffer
13643                                  + rnglists_section->size);
13644       unsigned int bytes_read;
13645
13646       if (buffer == buf_end)
13647         {
13648           overflow = true;
13649           break;
13650         }
13651       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
13652       switch (rlet)
13653         {
13654         case DW_RLE_end_of_list:
13655           break;
13656         case DW_RLE_base_address:
13657           if (buffer + cu->header.addr_size > buf_end)
13658             {
13659               overflow = true;
13660               break;
13661             }
13662           base = cu->header.read_address (obfd, buffer, &bytes_read);
13663           buffer += bytes_read;
13664           break;
13665         case DW_RLE_base_addressx:
13666           addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13667           buffer += bytes_read;
13668           base = read_addr_index (cu, addr_index);
13669           break;
13670         case DW_RLE_start_length:
13671           if (buffer + cu->header.addr_size > buf_end)
13672             {
13673               overflow = true;
13674               break;
13675             }
13676           range_beginning = cu->header.read_address (obfd, buffer,
13677                                                      &bytes_read);
13678           buffer += bytes_read;
13679           range_end = (range_beginning
13680                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13681           buffer += bytes_read;
13682           if (buffer > buf_end)
13683             {
13684               overflow = true;
13685               break;
13686             }
13687           break;
13688         case DW_RLE_startx_length:
13689           addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13690           buffer += bytes_read;
13691           range_beginning = read_addr_index (cu, addr_index);
13692           if (buffer > buf_end)
13693             {
13694               overflow = true;
13695               break;
13696             }
13697           range_end = (range_beginning
13698                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13699           buffer += bytes_read;
13700           break;
13701         case DW_RLE_offset_pair:
13702           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13703           buffer += bytes_read;
13704           if (buffer > buf_end)
13705             {
13706               overflow = true;
13707               break;
13708             }
13709           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13710           buffer += bytes_read;
13711           if (buffer > buf_end)
13712             {
13713               overflow = true;
13714               break;
13715             }
13716           break;
13717         case DW_RLE_start_end:
13718           if (buffer + 2 * cu->header.addr_size > buf_end)
13719             {
13720               overflow = true;
13721               break;
13722             }
13723           range_beginning = cu->header.read_address (obfd, buffer,
13724                                                      &bytes_read);
13725           buffer += bytes_read;
13726           range_end = cu->header.read_address (obfd, buffer, &bytes_read);
13727           buffer += bytes_read;
13728           break;
13729         case DW_RLE_startx_endx:
13730           addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13731           buffer += bytes_read;
13732           range_beginning = read_addr_index (cu, addr_index);
13733           if (buffer > buf_end)
13734             {
13735               overflow = true;
13736               break;
13737             }
13738           addr_index = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13739           buffer += bytes_read;
13740           range_end = read_addr_index (cu, addr_index);
13741           break;
13742         default:
13743           complaint (_("Invalid .debug_rnglists data (no base address)"));
13744           return false;
13745         }
13746       if (rlet == DW_RLE_end_of_list || overflow)
13747         break;
13748       if (rlet == DW_RLE_base_address)
13749         continue;
13750
13751       if (range_beginning > range_end)
13752         {
13753           /* Inverted range entries are invalid.  */
13754           complaint (_("Invalid .debug_rnglists data (inverted range)"));
13755           return false;
13756         }
13757
13758       /* Empty range entries have no effect.  */
13759       if (range_beginning == range_end)
13760         continue;
13761
13762       /* Only DW_RLE_offset_pair needs the base address added.  */
13763       if (rlet == DW_RLE_offset_pair)
13764         {
13765           if (!base.has_value ())
13766             {
13767               /* We have no valid base address for the DW_RLE_offset_pair.  */
13768               complaint (_("Invalid .debug_rnglists data (no base address for "
13769                            "DW_RLE_offset_pair)"));
13770               return false;
13771             }
13772
13773           range_beginning += *base;
13774           range_end += *base;
13775         }
13776
13777       /* A not-uncommon case of bad debug info.
13778          Don't pollute the addrmap with bad data.  */
13779       if (range_beginning + baseaddr == 0
13780           && !per_objfile->per_bfd->has_section_at_zero)
13781         {
13782           complaint (_(".debug_rnglists entry has start address of zero"
13783                        " [in module %s]"), objfile_name (objfile));
13784           continue;
13785         }
13786
13787       callback (range_beginning, range_end);
13788     }
13789
13790   if (overflow)
13791     {
13792       complaint (_("Offset %d is not terminated "
13793                    "for DW_AT_ranges attribute"),
13794                  offset);
13795       return false;
13796     }
13797
13798   return true;
13799 }
13800
13801 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
13802    Callback's type should be:
13803     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13804    Return 1 if the attributes are present and valid, otherwise, return 0.  */
13805
13806 template <typename Callback>
13807 static int
13808 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu, dwarf_tag tag,
13809                        Callback &&callback)
13810 {
13811   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13812   struct objfile *objfile = per_objfile->objfile;
13813   struct comp_unit_head *cu_header = &cu->header;
13814   bfd *obfd = objfile->obfd;
13815   unsigned int addr_size = cu_header->addr_size;
13816   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13817   /* Base address selection entry.  */
13818   gdb::optional<CORE_ADDR> base;
13819   unsigned int dummy;
13820   const gdb_byte *buffer;
13821   CORE_ADDR baseaddr;
13822
13823   if (cu_header->version >= 5)
13824     return dwarf2_rnglists_process (offset, cu, tag, callback);
13825
13826   base = cu->base_address;
13827
13828   per_objfile->per_bfd->ranges.read (objfile);
13829   if (offset >= per_objfile->per_bfd->ranges.size)
13830     {
13831       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
13832                  offset);
13833       return 0;
13834     }
13835   buffer = per_objfile->per_bfd->ranges.buffer + offset;
13836
13837   baseaddr = objfile->text_section_offset ();
13838
13839   while (1)
13840     {
13841       CORE_ADDR range_beginning, range_end;
13842
13843       range_beginning = cu->header.read_address (obfd, buffer, &dummy);
13844       buffer += addr_size;
13845       range_end = cu->header.read_address (obfd, buffer, &dummy);
13846       buffer += addr_size;
13847       offset += 2 * addr_size;
13848
13849       /* An end of list marker is a pair of zero addresses.  */
13850       if (range_beginning == 0 && range_end == 0)
13851         /* Found the end of list entry.  */
13852         break;
13853
13854       /* Each base address selection entry is a pair of 2 values.
13855          The first is the largest possible address, the second is
13856          the base address.  Check for a base address here.  */
13857       if ((range_beginning & mask) == mask)
13858         {
13859           /* If we found the largest possible address, then we already
13860              have the base address in range_end.  */
13861           base = range_end;
13862           continue;
13863         }
13864
13865       if (!base.has_value ())
13866         {
13867           /* We have no valid base address for the ranges
13868              data.  */
13869           complaint (_("Invalid .debug_ranges data (no base address)"));
13870           return 0;
13871         }
13872
13873       if (range_beginning > range_end)
13874         {
13875           /* Inverted range entries are invalid.  */
13876           complaint (_("Invalid .debug_ranges data (inverted range)"));
13877           return 0;
13878         }
13879
13880       /* Empty range entries have no effect.  */
13881       if (range_beginning == range_end)
13882         continue;
13883
13884       range_beginning += *base;
13885       range_end += *base;
13886
13887       /* A not-uncommon case of bad debug info.
13888          Don't pollute the addrmap with bad data.  */
13889       if (range_beginning + baseaddr == 0
13890           && !per_objfile->per_bfd->has_section_at_zero)
13891         {
13892           complaint (_(".debug_ranges entry has start address of zero"
13893                        " [in module %s]"), objfile_name (objfile));
13894           continue;
13895         }
13896
13897       callback (range_beginning, range_end);
13898     }
13899
13900   return 1;
13901 }
13902
13903 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
13904    Return 1 if the attributes are present and valid, otherwise, return 0.
13905    If RANGES_PST is not NULL we should set up the `psymtabs_addrmap'.  */
13906
13907 static int
13908 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
13909                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
13910                     dwarf2_psymtab *ranges_pst, dwarf_tag tag)
13911 {
13912   struct objfile *objfile = cu->per_objfile->objfile;
13913   dwarf2_per_bfd *per_bfd = cu->per_objfile->per_bfd;
13914   struct gdbarch *gdbarch = objfile->arch ();
13915   const CORE_ADDR baseaddr = objfile->text_section_offset ();
13916   int low_set = 0;
13917   CORE_ADDR low = 0;
13918   CORE_ADDR high = 0;
13919   int retval;
13920
13921   retval = dwarf2_ranges_process (offset, cu, tag,
13922     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
13923     {
13924       if (ranges_pst != NULL)
13925         {
13926           CORE_ADDR lowpc;
13927           CORE_ADDR highpc;
13928
13929           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
13930                                                range_beginning + baseaddr)
13931                    - baseaddr);
13932           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
13933                                                 range_end + baseaddr)
13934                     - baseaddr);
13935           addrmap_set_empty (per_bfd->partial_symtabs->psymtabs_addrmap,
13936                              lowpc, highpc - 1, ranges_pst);
13937         }
13938
13939       /* FIXME: This is recording everything as a low-high
13940          segment of consecutive addresses.  We should have a
13941          data structure for discontiguous block ranges
13942          instead.  */
13943       if (! low_set)
13944         {
13945           low = range_beginning;
13946           high = range_end;
13947           low_set = 1;
13948         }
13949       else
13950         {
13951           if (range_beginning < low)
13952             low = range_beginning;
13953           if (range_end > high)
13954             high = range_end;
13955         }
13956     });
13957   if (!retval)
13958     return 0;
13959
13960   if (! low_set)
13961     /* If the first entry is an end-of-list marker, the range
13962        describes an empty scope, i.e. no instructions.  */
13963     return 0;
13964
13965   if (low_return)
13966     *low_return = low;
13967   if (high_return)
13968     *high_return = high;
13969   return 1;
13970 }
13971
13972 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
13973    definition for the return value.  *LOWPC and *HIGHPC are set iff
13974    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
13975
13976 static enum pc_bounds_kind
13977 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
13978                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
13979                       dwarf2_psymtab *pst)
13980 {
13981   dwarf2_per_objfile *per_objfile = cu->per_objfile;
13982   struct attribute *attr;
13983   struct attribute *attr_high;
13984   CORE_ADDR low = 0;
13985   CORE_ADDR high = 0;
13986   enum pc_bounds_kind ret;
13987
13988   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13989   if (attr_high)
13990     {
13991       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13992       if (attr != nullptr)
13993         {
13994           low = attr->as_address ();
13995           high = attr_high->as_address ();
13996           if (cu->header.version >= 4 && attr_high->form_is_constant ())
13997             high += low;
13998         }
13999       else
14000         /* Found high w/o low attribute.  */
14001         return PC_BOUNDS_INVALID;
14002
14003       /* Found consecutive range of addresses.  */
14004       ret = PC_BOUNDS_HIGH_LOW;
14005     }
14006   else
14007     {
14008       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14009       if (attr != nullptr && attr->form_is_unsigned ())
14010         {
14011           /* Offset in the .debug_ranges or .debug_rnglist section (depending
14012              on DWARF version).  */
14013           ULONGEST ranges_offset = attr->as_unsigned ();
14014
14015           /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
14016              this value.  */
14017           if (die->tag != DW_TAG_compile_unit)
14018             ranges_offset += cu->gnu_ranges_base;
14019
14020           /* Value of the DW_AT_ranges attribute is the offset in the
14021              .debug_ranges section.  */
14022           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst,
14023                                    die->tag))
14024             return PC_BOUNDS_INVALID;
14025           /* Found discontinuous range of addresses.  */
14026           ret = PC_BOUNDS_RANGES;
14027         }
14028       else
14029         return PC_BOUNDS_NOT_PRESENT;
14030     }
14031
14032   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14033   if (high <= low)
14034     return PC_BOUNDS_INVALID;
14035
14036   /* When using the GNU linker, .gnu.linkonce. sections are used to
14037      eliminate duplicate copies of functions and vtables and such.
14038      The linker will arbitrarily choose one and discard the others.
14039      The AT_*_pc values for such functions refer to local labels in
14040      these sections.  If the section from that file was discarded, the
14041      labels are not in the output, so the relocs get a value of 0.
14042      If this is a discarded function, mark the pc bounds as invalid,
14043      so that GDB will ignore it.  */
14044   if (low == 0 && !per_objfile->per_bfd->has_section_at_zero)
14045     return PC_BOUNDS_INVALID;
14046
14047   *lowpc = low;
14048   if (highpc)
14049     *highpc = high;
14050   return ret;
14051 }
14052
14053 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14054    its low and high PC addresses.  Do nothing if these addresses could not
14055    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14056    and HIGHPC to the high address if greater than HIGHPC.  */
14057
14058 static void
14059 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14060                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14061                                  struct dwarf2_cu *cu)
14062 {
14063   CORE_ADDR low, high;
14064   struct die_info *child = die->child;
14065
14066   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14067     {
14068       *lowpc = std::min (*lowpc, low);
14069       *highpc = std::max (*highpc, high);
14070     }
14071
14072   /* If the language does not allow nested subprograms (either inside
14073      subprograms or lexical blocks), we're done.  */
14074   if (cu->per_cu->lang != language_ada)
14075     return;
14076
14077   /* Check all the children of the given DIE.  If it contains nested
14078      subprograms, then check their pc bounds.  Likewise, we need to
14079      check lexical blocks as well, as they may also contain subprogram
14080      definitions.  */
14081   while (child && child->tag)
14082     {
14083       if (child->tag == DW_TAG_subprogram
14084           || child->tag == DW_TAG_lexical_block)
14085         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14086       child = child->sibling;
14087     }
14088 }
14089
14090 /* Get the low and high pc's represented by the scope DIE, and store
14091    them in *LOWPC and *HIGHPC.  If the correct values can't be
14092    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14093
14094 static void
14095 get_scope_pc_bounds (struct die_info *die,
14096                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14097                      struct dwarf2_cu *cu)
14098 {
14099   CORE_ADDR best_low = (CORE_ADDR) -1;
14100   CORE_ADDR best_high = (CORE_ADDR) 0;
14101   CORE_ADDR current_low, current_high;
14102
14103   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14104       >= PC_BOUNDS_RANGES)
14105     {
14106       best_low = current_low;
14107       best_high = current_high;
14108     }
14109   else
14110     {
14111       struct die_info *child = die->child;
14112
14113       while (child && child->tag)
14114         {
14115           switch (child->tag) {
14116           case DW_TAG_subprogram:
14117             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14118             break;
14119           case DW_TAG_namespace:
14120           case DW_TAG_module:
14121             /* FIXME: carlton/2004-01-16: Should we do this for
14122                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14123                that current GCC's always emit the DIEs corresponding
14124                to definitions of methods of classes as children of a
14125                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14126                the DIEs giving the declarations, which could be
14127                anywhere).  But I don't see any reason why the
14128                standards says that they have to be there.  */
14129             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14130
14131             if (current_low != ((CORE_ADDR) -1))
14132               {
14133                 best_low = std::min (best_low, current_low);
14134                 best_high = std::max (best_high, current_high);
14135               }
14136             break;
14137           default:
14138             /* Ignore.  */
14139             break;
14140           }
14141
14142           child = child->sibling;
14143         }
14144     }
14145
14146   *lowpc = best_low;
14147   *highpc = best_high;
14148 }
14149
14150 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14151    in DIE.  */
14152
14153 static void
14154 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14155                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14156 {
14157   struct objfile *objfile = cu->per_objfile->objfile;
14158   struct gdbarch *gdbarch = objfile->arch ();
14159   struct attribute *attr;
14160   struct attribute *attr_high;
14161
14162   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14163   if (attr_high)
14164     {
14165       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14166       if (attr != nullptr)
14167         {
14168           CORE_ADDR low = attr->as_address ();
14169           CORE_ADDR high = attr_high->as_address ();
14170
14171           if (cu->header.version >= 4 && attr_high->form_is_constant ())
14172             high += low;
14173
14174           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14175           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14176           cu->get_builder ()->record_block_range (block, low, high - 1);
14177         }
14178     }
14179
14180   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14181   if (attr != nullptr && attr->form_is_unsigned ())
14182     {
14183       /* Offset in the .debug_ranges or .debug_rnglist section (depending
14184          on DWARF version).  */
14185       ULONGEST ranges_offset = attr->as_unsigned ();
14186
14187       /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
14188          this value.  */
14189       if (die->tag != DW_TAG_compile_unit)
14190         ranges_offset += cu->gnu_ranges_base;
14191
14192       std::vector<blockrange> blockvec;
14193       dwarf2_ranges_process (ranges_offset, cu, die->tag,
14194         [&] (CORE_ADDR start, CORE_ADDR end)
14195         {
14196           start += baseaddr;
14197           end += baseaddr;
14198           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14199           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14200           cu->get_builder ()->record_block_range (block, start, end - 1);
14201           blockvec.emplace_back (start, end);
14202         });
14203
14204       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14205     }
14206 }
14207
14208 /* Check whether the producer field indicates either of GCC < 4.6, or the
14209    Intel C/C++ compiler, and cache the result in CU.  */
14210
14211 static void
14212 check_producer (struct dwarf2_cu *cu)
14213 {
14214   int major, minor;
14215
14216   if (cu->producer == NULL)
14217     {
14218       /* For unknown compilers expect their behavior is DWARF version
14219          compliant.
14220
14221          GCC started to support .debug_types sections by -gdwarf-4 since
14222          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14223          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14224          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14225          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14226     }
14227   else if (producer_is_gcc (cu->producer, &major, &minor))
14228     {
14229       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14230       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14231     }
14232   else if (producer_is_icc (cu->producer, &major, &minor))
14233     {
14234       cu->producer_is_icc = true;
14235       cu->producer_is_icc_lt_14 = major < 14;
14236     }
14237   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14238     cu->producer_is_codewarrior = true;
14239   else
14240     {
14241       /* For other non-GCC compilers, expect their behavior is DWARF version
14242          compliant.  */
14243     }
14244
14245   cu->checked_producer = true;
14246 }
14247
14248 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14249    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14250    during 4.6.0 experimental.  */
14251
14252 static bool
14253 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14254 {
14255   if (!cu->checked_producer)
14256     check_producer (cu);
14257
14258   return cu->producer_is_gxx_lt_4_6;
14259 }
14260
14261
14262 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14263    with incorrect is_stmt attributes.  */
14264
14265 static bool
14266 producer_is_codewarrior (struct dwarf2_cu *cu)
14267 {
14268   if (!cu->checked_producer)
14269     check_producer (cu);
14270
14271   return cu->producer_is_codewarrior;
14272 }
14273
14274 /* Return the accessibility of DIE, as given by DW_AT_accessibility.
14275    If that attribute is not available, return the appropriate
14276    default.  */
14277
14278 static enum dwarf_access_attribute
14279 dwarf2_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14280 {
14281   attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14282   if (attr != nullptr)
14283     {
14284       LONGEST value = attr->constant_value (-1);
14285       if (value == DW_ACCESS_public
14286           || value == DW_ACCESS_protected
14287           || value == DW_ACCESS_private)
14288         return (dwarf_access_attribute) value;
14289       complaint (_("Unhandled DW_AT_accessibility value (%s)"),
14290                  plongest (value));
14291     }
14292
14293   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14294     {
14295       /* The default DWARF 2 accessibility for members is public, the default
14296          accessibility for inheritance is private.  */
14297
14298       if (die->tag != DW_TAG_inheritance)
14299         return DW_ACCESS_public;
14300       else
14301         return DW_ACCESS_private;
14302     }
14303   else
14304     {
14305       /* DWARF 3+ defines the default accessibility a different way.  The same
14306          rules apply now for DW_TAG_inheritance as for the members and it only
14307          depends on the container kind.  */
14308
14309       if (die->parent->tag == DW_TAG_class_type)
14310         return DW_ACCESS_private;
14311       else
14312         return DW_ACCESS_public;
14313     }
14314 }
14315
14316 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14317    offset.  If the attribute was not found return 0, otherwise return
14318    1.  If it was found but could not properly be handled, set *OFFSET
14319    to 0.  */
14320
14321 static int
14322 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14323                              LONGEST *offset)
14324 {
14325   struct attribute *attr;
14326
14327   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14328   if (attr != NULL)
14329     {
14330       *offset = 0;
14331
14332       /* Note that we do not check for a section offset first here.
14333          This is because DW_AT_data_member_location is new in DWARF 4,
14334          so if we see it, we can assume that a constant form is really
14335          a constant and not a section offset.  */
14336       if (attr->form_is_constant ())
14337         *offset = attr->constant_value (0);
14338       else if (attr->form_is_section_offset ())
14339         dwarf2_complex_location_expr_complaint ();
14340       else if (attr->form_is_block ())
14341         *offset = decode_locdesc (attr->as_block (), cu);
14342       else
14343         dwarf2_complex_location_expr_complaint ();
14344
14345       return 1;
14346     }
14347
14348   return 0;
14349 }
14350
14351 /* Look for DW_AT_data_member_location and store the results in FIELD.  */
14352
14353 static void
14354 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14355                              struct field *field)
14356 {
14357   struct attribute *attr;
14358
14359   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14360   if (attr != NULL)
14361     {
14362       if (attr->form_is_constant ())
14363         {
14364           LONGEST offset = attr->constant_value (0);
14365           SET_FIELD_BITPOS (*field, offset * bits_per_byte);
14366         }
14367       else if (attr->form_is_section_offset ())
14368         dwarf2_complex_location_expr_complaint ();
14369       else if (attr->form_is_block ())
14370         {
14371           bool handled;
14372           CORE_ADDR offset = decode_locdesc (attr->as_block (), cu, &handled);
14373           if (handled)
14374             SET_FIELD_BITPOS (*field, offset * bits_per_byte);
14375           else
14376             {
14377               dwarf2_per_objfile *per_objfile = cu->per_objfile;
14378               struct objfile *objfile = per_objfile->objfile;
14379               struct dwarf2_locexpr_baton *dlbaton
14380                 = XOBNEW (&objfile->objfile_obstack,
14381                           struct dwarf2_locexpr_baton);
14382               dlbaton->data = attr->as_block ()->data;
14383               dlbaton->size = attr->as_block ()->size;
14384               /* When using this baton, we want to compute the address
14385                  of the field, not the value.  This is why
14386                  is_reference is set to false here.  */
14387               dlbaton->is_reference = false;
14388               dlbaton->per_objfile = per_objfile;
14389               dlbaton->per_cu = cu->per_cu;
14390
14391               SET_FIELD_DWARF_BLOCK (*field, dlbaton);
14392             }
14393         }
14394       else
14395         dwarf2_complex_location_expr_complaint ();
14396     }
14397 }
14398
14399 /* Add an aggregate field to the field list.  */
14400
14401 static void
14402 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14403                   struct dwarf2_cu *cu)
14404 {
14405   struct objfile *objfile = cu->per_objfile->objfile;
14406   struct gdbarch *gdbarch = objfile->arch ();
14407   struct nextfield *new_field;
14408   struct attribute *attr;
14409   struct field *fp;
14410   const char *fieldname = "";
14411
14412   if (die->tag == DW_TAG_inheritance)
14413     {
14414       fip->baseclasses.emplace_back ();
14415       new_field = &fip->baseclasses.back ();
14416     }
14417   else
14418     {
14419       fip->fields.emplace_back ();
14420       new_field = &fip->fields.back ();
14421     }
14422
14423   new_field->offset = die->sect_off;
14424
14425   new_field->accessibility = dwarf2_access_attribute (die, cu);
14426   if (new_field->accessibility != DW_ACCESS_public)
14427     fip->non_public_fields = true;
14428
14429   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14430   if (attr != nullptr)
14431     new_field->virtuality = attr->as_virtuality ();
14432   else
14433     new_field->virtuality = DW_VIRTUALITY_none;
14434
14435   fp = &new_field->field;
14436
14437   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14438     {
14439       /* Data member other than a C++ static data member.  */
14440
14441       /* Get type of field.  */
14442       fp->set_type (die_type (die, cu));
14443
14444       SET_FIELD_BITPOS (*fp, 0);
14445
14446       /* Get bit size of field (zero if none).  */
14447       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14448       if (attr != nullptr)
14449         {
14450           FIELD_BITSIZE (*fp) = attr->constant_value (0);
14451         }
14452       else
14453         {
14454           FIELD_BITSIZE (*fp) = 0;
14455         }
14456
14457       /* Get bit offset of field.  */
14458       handle_data_member_location (die, cu, fp);
14459       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14460       if (attr != nullptr && attr->form_is_constant ())
14461         {
14462           if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
14463             {
14464               /* For big endian bits, the DW_AT_bit_offset gives the
14465                  additional bit offset from the MSB of the containing
14466                  anonymous object to the MSB of the field.  We don't
14467                  have to do anything special since we don't need to
14468                  know the size of the anonymous object.  */
14469               SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14470                                       + attr->constant_value (0)));
14471             }
14472           else
14473             {
14474               /* For little endian bits, compute the bit offset to the
14475                  MSB of the anonymous object, subtract off the number of
14476                  bits from the MSB of the field to the MSB of the
14477                  object, and then subtract off the number of bits of
14478                  the field itself.  The result is the bit offset of
14479                  the LSB of the field.  */
14480               int anonymous_size;
14481               int bit_offset = attr->constant_value (0);
14482
14483               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14484               if (attr != nullptr && attr->form_is_constant ())
14485                 {
14486                   /* The size of the anonymous object containing
14487                      the bit field is explicit, so use the
14488                      indicated size (in bytes).  */
14489                   anonymous_size = attr->constant_value (0);
14490                 }
14491               else
14492                 {
14493                   /* The size of the anonymous object containing
14494                      the bit field must be inferred from the type
14495                      attribute of the data member containing the
14496                      bit field.  */
14497                   anonymous_size = TYPE_LENGTH (fp->type ());
14498                 }
14499               SET_FIELD_BITPOS (*fp,
14500                                 (FIELD_BITPOS (*fp)
14501                                  + anonymous_size * bits_per_byte
14502                                  - bit_offset - FIELD_BITSIZE (*fp)));
14503             }
14504         }
14505       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14506       if (attr != NULL)
14507         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14508                                 + attr->constant_value (0)));
14509
14510       /* Get name of field.  */
14511       fieldname = dwarf2_name (die, cu);
14512       if (fieldname == NULL)
14513         fieldname = "";
14514
14515       /* The name is already allocated along with this objfile, so we don't
14516          need to duplicate it for the type.  */
14517       fp->name = fieldname;
14518
14519       /* Change accessibility for artificial fields (e.g. virtual table
14520          pointer or virtual base class pointer) to private.  */
14521       if (dwarf2_attr (die, DW_AT_artificial, cu))
14522         {
14523           FIELD_ARTIFICIAL (*fp) = 1;
14524           new_field->accessibility = DW_ACCESS_private;
14525           fip->non_public_fields = true;
14526         }
14527     }
14528   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
14529     {
14530       /* C++ static member.  */
14531
14532       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
14533          is a declaration, but all versions of G++ as of this writing
14534          (so through at least 3.2.1) incorrectly generate
14535          DW_TAG_variable tags.  */
14536
14537       const char *physname;
14538
14539       /* Get name of field.  */
14540       fieldname = dwarf2_name (die, cu);
14541       if (fieldname == NULL)
14542         return;
14543
14544       attr = dwarf2_attr (die, DW_AT_const_value, cu);
14545       if (attr
14546           /* Only create a symbol if this is an external value.
14547              new_symbol checks this and puts the value in the global symbol
14548              table, which we want.  If it is not external, new_symbol
14549              will try to put the value in cu->list_in_scope which is wrong.  */
14550           && dwarf2_flag_true_p (die, DW_AT_external, cu))
14551         {
14552           /* A static const member, not much different than an enum as far as
14553              we're concerned, except that we can support more types.  */
14554           new_symbol (die, NULL, cu);
14555         }
14556
14557       /* Get physical name.  */
14558       physname = dwarf2_physname (fieldname, die, cu);
14559
14560       /* The name is already allocated along with this objfile, so we don't
14561          need to duplicate it for the type.  */
14562       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
14563       fp->set_type (die_type (die, cu));
14564       FIELD_NAME (*fp) = fieldname;
14565     }
14566   else if (die->tag == DW_TAG_inheritance)
14567     {
14568       /* C++ base class field.  */
14569       handle_data_member_location (die, cu, fp);
14570       FIELD_BITSIZE (*fp) = 0;
14571       fp->set_type (die_type (die, cu));
14572       FIELD_NAME (*fp) = fp->type ()->name ();
14573     }
14574   else
14575     gdb_assert_not_reached ("missing case in dwarf2_add_field");
14576 }
14577
14578 /* Can the type given by DIE define another type?  */
14579
14580 static bool
14581 type_can_define_types (const struct die_info *die)
14582 {
14583   switch (die->tag)
14584     {
14585     case DW_TAG_typedef:
14586     case DW_TAG_class_type:
14587     case DW_TAG_structure_type:
14588     case DW_TAG_union_type:
14589     case DW_TAG_enumeration_type:
14590       return true;
14591
14592     default:
14593       return false;
14594     }
14595 }
14596
14597 /* Add a type definition defined in the scope of the FIP's class.  */
14598
14599 static void
14600 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
14601                       struct dwarf2_cu *cu)
14602 {
14603   struct decl_field fp;
14604   memset (&fp, 0, sizeof (fp));
14605
14606   gdb_assert (type_can_define_types (die));
14607
14608   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
14609   fp.name = dwarf2_name (die, cu);
14610   fp.type = read_type_die (die, cu);
14611
14612   /* Save accessibility.  */
14613   dwarf_access_attribute accessibility = dwarf2_access_attribute (die, cu);
14614   switch (accessibility)
14615     {
14616     case DW_ACCESS_public:
14617       /* The assumed value if neither private nor protected.  */
14618       break;
14619     case DW_ACCESS_private:
14620       fp.is_private = 1;
14621       break;
14622     case DW_ACCESS_protected:
14623       fp.is_protected = 1;
14624       break;
14625     }
14626
14627   if (die->tag == DW_TAG_typedef)
14628     fip->typedef_field_list.push_back (fp);
14629   else
14630     fip->nested_types_list.push_back (fp);
14631 }
14632
14633 /* A convenience typedef that's used when finding the discriminant
14634    field for a variant part.  */
14635 typedef std::unordered_map<sect_offset, int, gdb::hash_enum<sect_offset>>
14636   offset_map_type;
14637
14638 /* Compute the discriminant range for a given variant.  OBSTACK is
14639    where the results will be stored.  VARIANT is the variant to
14640    process.  IS_UNSIGNED indicates whether the discriminant is signed
14641    or unsigned.  */
14642
14643 static const gdb::array_view<discriminant_range>
14644 convert_variant_range (struct obstack *obstack, const variant_field &variant,
14645                        bool is_unsigned)
14646 {
14647   std::vector<discriminant_range> ranges;
14648
14649   if (variant.default_branch)
14650     return {};
14651
14652   if (variant.discr_list_data == nullptr)
14653     {
14654       discriminant_range r
14655         = {variant.discriminant_value, variant.discriminant_value};
14656       ranges.push_back (r);
14657     }
14658   else
14659     {
14660       gdb::array_view<const gdb_byte> data (variant.discr_list_data->data,
14661                                             variant.discr_list_data->size);
14662       while (!data.empty ())
14663         {
14664           if (data[0] != DW_DSC_range && data[0] != DW_DSC_label)
14665             {
14666               complaint (_("invalid discriminant marker: %d"), data[0]);
14667               break;
14668             }
14669           bool is_range = data[0] == DW_DSC_range;
14670           data = data.slice (1);
14671
14672           ULONGEST low, high;
14673           unsigned int bytes_read;
14674
14675           if (data.empty ())
14676             {
14677               complaint (_("DW_AT_discr_list missing low value"));
14678               break;
14679             }
14680           if (is_unsigned)
14681             low = read_unsigned_leb128 (nullptr, data.data (), &bytes_read);
14682           else
14683             low = (ULONGEST) read_signed_leb128 (nullptr, data.data (),
14684                                                  &bytes_read);
14685           data = data.slice (bytes_read);
14686
14687           if (is_range)
14688             {
14689               if (data.empty ())
14690                 {
14691                   complaint (_("DW_AT_discr_list missing high value"));
14692                   break;
14693                 }
14694               if (is_unsigned)
14695                 high = read_unsigned_leb128 (nullptr, data.data (),
14696                                              &bytes_read);
14697               else
14698                 high = (LONGEST) read_signed_leb128 (nullptr, data.data (),
14699                                                      &bytes_read);
14700               data = data.slice (bytes_read);
14701             }
14702           else
14703             high = low;
14704
14705           ranges.push_back ({ low, high });
14706         }
14707     }
14708
14709   discriminant_range *result = XOBNEWVEC (obstack, discriminant_range,
14710                                           ranges.size ());
14711   std::copy (ranges.begin (), ranges.end (), result);
14712   return gdb::array_view<discriminant_range> (result, ranges.size ());
14713 }
14714
14715 static const gdb::array_view<variant_part> create_variant_parts
14716   (struct obstack *obstack,
14717    const offset_map_type &offset_map,
14718    struct field_info *fi,
14719    const std::vector<variant_part_builder> &variant_parts);
14720
14721 /* Fill in a "struct variant" for a given variant field.  RESULT is
14722    the variant to fill in.  OBSTACK is where any needed allocations
14723    will be done.  OFFSET_MAP holds the mapping from section offsets to
14724    fields for the type.  FI describes the fields of the type we're
14725    processing.  FIELD is the variant field we're converting.  */
14726
14727 static void
14728 create_one_variant (variant &result, struct obstack *obstack,
14729                     const offset_map_type &offset_map,
14730                     struct field_info *fi, const variant_field &field)
14731 {
14732   result.discriminants = convert_variant_range (obstack, field, false);
14733   result.first_field = field.first_field + fi->baseclasses.size ();
14734   result.last_field = field.last_field + fi->baseclasses.size ();
14735   result.parts = create_variant_parts (obstack, offset_map, fi,
14736                                        field.variant_parts);
14737 }
14738
14739 /* Fill in a "struct variant_part" for a given variant part.  RESULT
14740    is the variant part to fill in.  OBSTACK is where any needed
14741    allocations will be done.  OFFSET_MAP holds the mapping from
14742    section offsets to fields for the type.  FI describes the fields of
14743    the type we're processing.  BUILDER is the variant part to be
14744    converted.  */
14745
14746 static void
14747 create_one_variant_part (variant_part &result,
14748                          struct obstack *obstack,
14749                          const offset_map_type &offset_map,
14750                          struct field_info *fi,
14751                          const variant_part_builder &builder)
14752 {
14753   auto iter = offset_map.find (builder.discriminant_offset);
14754   if (iter == offset_map.end ())
14755     {
14756       result.discriminant_index = -1;
14757       /* Doesn't matter.  */
14758       result.is_unsigned = false;
14759     }
14760   else
14761     {
14762       result.discriminant_index = iter->second;
14763       result.is_unsigned
14764         = fi->fields[result.discriminant_index].field.type ()->is_unsigned ();
14765     }
14766
14767   size_t n = builder.variants.size ();
14768   variant *output = new (obstack) variant[n];
14769   for (size_t i = 0; i < n; ++i)
14770     create_one_variant (output[i], obstack, offset_map, fi,
14771                         builder.variants[i]);
14772
14773   result.variants = gdb::array_view<variant> (output, n);
14774 }
14775
14776 /* Create a vector of variant parts that can be attached to a type.
14777    OBSTACK is where any needed allocations will be done.  OFFSET_MAP
14778    holds the mapping from section offsets to fields for the type.  FI
14779    describes the fields of the type we're processing.  VARIANT_PARTS
14780    is the vector to convert.  */
14781
14782 static const gdb::array_view<variant_part>
14783 create_variant_parts (struct obstack *obstack,
14784                       const offset_map_type &offset_map,
14785                       struct field_info *fi,
14786                       const std::vector<variant_part_builder> &variant_parts)
14787 {
14788   if (variant_parts.empty ())
14789     return {};
14790
14791   size_t n = variant_parts.size ();
14792   variant_part *result = new (obstack) variant_part[n];
14793   for (size_t i = 0; i < n; ++i)
14794     create_one_variant_part (result[i], obstack, offset_map, fi,
14795                              variant_parts[i]);
14796
14797   return gdb::array_view<variant_part> (result, n);
14798 }
14799
14800 /* Compute the variant part vector for FIP, attaching it to TYPE when
14801    done.  */
14802
14803 static void
14804 add_variant_property (struct field_info *fip, struct type *type,
14805                       struct dwarf2_cu *cu)
14806 {
14807   /* Map section offsets of fields to their field index.  Note the
14808      field index here does not take the number of baseclasses into
14809      account.  */
14810   offset_map_type offset_map;
14811   for (int i = 0; i < fip->fields.size (); ++i)
14812     offset_map[fip->fields[i].offset] = i;
14813
14814   struct objfile *objfile = cu->per_objfile->objfile;
14815   gdb::array_view<variant_part> parts
14816     = create_variant_parts (&objfile->objfile_obstack, offset_map, fip,
14817                             fip->variant_parts);
14818
14819   struct dynamic_prop prop;
14820   prop.set_variant_parts ((gdb::array_view<variant_part> *)
14821                           obstack_copy (&objfile->objfile_obstack, &parts,
14822                                         sizeof (parts)));
14823
14824   type->add_dyn_prop (DYN_PROP_VARIANT_PARTS, prop);
14825 }
14826
14827 /* Create the vector of fields, and attach it to the type.  */
14828
14829 static void
14830 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
14831                               struct dwarf2_cu *cu)
14832 {
14833   int nfields = fip->nfields ();
14834
14835   /* Record the field count, allocate space for the array of fields,
14836      and create blank accessibility bitfields if necessary.  */
14837   type->set_num_fields (nfields);
14838   type->set_fields
14839     ((struct field *) TYPE_ZALLOC (type, sizeof (struct field) * nfields));
14840
14841   if (fip->non_public_fields && cu->per_cu->lang != language_ada)
14842     {
14843       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14844
14845       TYPE_FIELD_PRIVATE_BITS (type) =
14846         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14847       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
14848
14849       TYPE_FIELD_PROTECTED_BITS (type) =
14850         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14851       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
14852
14853       TYPE_FIELD_IGNORE_BITS (type) =
14854         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14855       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
14856     }
14857
14858   /* If the type has baseclasses, allocate and clear a bit vector for
14859      TYPE_FIELD_VIRTUAL_BITS.  */
14860   if (!fip->baseclasses.empty () && cu->per_cu->lang != language_ada)
14861     {
14862       int num_bytes = B_BYTES (fip->baseclasses.size ());
14863       unsigned char *pointer;
14864
14865       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14866       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
14867       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
14868       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
14869       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
14870     }
14871
14872   if (!fip->variant_parts.empty ())
14873     add_variant_property (fip, type, cu);
14874
14875   /* Copy the saved-up fields into the field vector.  */
14876   for (int i = 0; i < nfields; ++i)
14877     {
14878       struct nextfield &field
14879         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
14880            : fip->fields[i - fip->baseclasses.size ()]);
14881
14882       type->field (i) = field.field;
14883       switch (field.accessibility)
14884         {
14885         case DW_ACCESS_private:
14886           if (cu->per_cu->lang != language_ada)
14887             SET_TYPE_FIELD_PRIVATE (type, i);
14888           break;
14889
14890         case DW_ACCESS_protected:
14891           if (cu->per_cu->lang != language_ada)
14892             SET_TYPE_FIELD_PROTECTED (type, i);
14893           break;
14894
14895         case DW_ACCESS_public:
14896           break;
14897
14898         default:
14899           /* Unknown accessibility.  Complain and treat it as public.  */
14900           {
14901             complaint (_("unsupported accessibility %d"),
14902                        field.accessibility);
14903           }
14904           break;
14905         }
14906       if (i < fip->baseclasses.size ())
14907         {
14908           switch (field.virtuality)
14909             {
14910             case DW_VIRTUALITY_virtual:
14911             case DW_VIRTUALITY_pure_virtual:
14912               if (cu->per_cu->lang == language_ada)
14913                 error (_("unexpected virtuality in component of Ada type"));
14914               SET_TYPE_FIELD_VIRTUAL (type, i);
14915               break;
14916             }
14917         }
14918     }
14919 }
14920
14921 /* Return true if this member function is a constructor, false
14922    otherwise.  */
14923
14924 static int
14925 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
14926 {
14927   const char *fieldname;
14928   const char *type_name;
14929   int len;
14930
14931   if (die->parent == NULL)
14932     return 0;
14933
14934   if (die->parent->tag != DW_TAG_structure_type
14935       && die->parent->tag != DW_TAG_union_type
14936       && die->parent->tag != DW_TAG_class_type)
14937     return 0;
14938
14939   fieldname = dwarf2_name (die, cu);
14940   type_name = dwarf2_name (die->parent, cu);
14941   if (fieldname == NULL || type_name == NULL)
14942     return 0;
14943
14944   len = strlen (fieldname);
14945   return (strncmp (fieldname, type_name, len) == 0
14946           && (type_name[len] == '\0' || type_name[len] == '<'));
14947 }
14948
14949 /* Add a member function to the proper fieldlist.  */
14950
14951 static void
14952 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
14953                       struct type *type, struct dwarf2_cu *cu)
14954 {
14955   struct objfile *objfile = cu->per_objfile->objfile;
14956   struct attribute *attr;
14957   int i;
14958   struct fnfieldlist *flp = nullptr;
14959   struct fn_field *fnp;
14960   const char *fieldname;
14961   struct type *this_type;
14962
14963   if (cu->per_cu->lang == language_ada)
14964     error (_("unexpected member function in Ada type"));
14965
14966   /* Get name of member function.  */
14967   fieldname = dwarf2_name (die, cu);
14968   if (fieldname == NULL)
14969     return;
14970
14971   /* Look up member function name in fieldlist.  */
14972   for (i = 0; i < fip->fnfieldlists.size (); i++)
14973     {
14974       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
14975         {
14976           flp = &fip->fnfieldlists[i];
14977           break;
14978         }
14979     }
14980
14981   /* Create a new fnfieldlist if necessary.  */
14982   if (flp == nullptr)
14983     {
14984       fip->fnfieldlists.emplace_back ();
14985       flp = &fip->fnfieldlists.back ();
14986       flp->name = fieldname;
14987       i = fip->fnfieldlists.size () - 1;
14988     }
14989
14990   /* Create a new member function field and add it to the vector of
14991      fnfieldlists.  */
14992   flp->fnfields.emplace_back ();
14993   fnp = &flp->fnfields.back ();
14994
14995   /* Delay processing of the physname until later.  */
14996   if (cu->per_cu->lang == language_cplus)
14997     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
14998                         die, cu);
14999   else
15000     {
15001       const char *physname = dwarf2_physname (fieldname, die, cu);
15002       fnp->physname = physname ? physname : "";
15003     }
15004
15005   fnp->type = alloc_type (objfile);
15006   this_type = read_type_die (die, cu);
15007   if (this_type && this_type->code () == TYPE_CODE_FUNC)
15008     {
15009       int nparams = this_type->num_fields ();
15010
15011       /* TYPE is the domain of this method, and THIS_TYPE is the type
15012            of the method itself (TYPE_CODE_METHOD).  */
15013       smash_to_method_type (fnp->type, type,
15014                             TYPE_TARGET_TYPE (this_type),
15015                             this_type->fields (),
15016                             this_type->num_fields (),
15017                             this_type->has_varargs ());
15018
15019       /* Handle static member functions.
15020          Dwarf2 has no clean way to discern C++ static and non-static
15021          member functions.  G++ helps GDB by marking the first
15022          parameter for non-static member functions (which is the this
15023          pointer) as artificial.  We obtain this information from
15024          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15025       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15026         fnp->voffset = VOFFSET_STATIC;
15027     }
15028   else
15029     complaint (_("member function type missing for '%s'"),
15030                dwarf2_full_name (fieldname, die, cu));
15031
15032   /* Get fcontext from DW_AT_containing_type if present.  */
15033   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15034     fnp->fcontext = die_containing_type (die, cu);
15035
15036   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15037      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15038
15039   /* Get accessibility.  */
15040   dwarf_access_attribute accessibility = dwarf2_access_attribute (die, cu);
15041   switch (accessibility)
15042     {
15043     case DW_ACCESS_private:
15044       fnp->is_private = 1;
15045       break;
15046     case DW_ACCESS_protected:
15047       fnp->is_protected = 1;
15048       break;
15049     }
15050
15051   /* Check for artificial methods.  */
15052   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15053   if (attr && attr->as_boolean ())
15054     fnp->is_artificial = 1;
15055
15056   /* Check for defaulted methods.  */
15057   attr = dwarf2_attr (die, DW_AT_defaulted, cu);
15058   if (attr != nullptr)
15059     fnp->defaulted = attr->defaulted ();
15060
15061   /* Check for deleted methods.  */
15062   attr = dwarf2_attr (die, DW_AT_deleted, cu);
15063   if (attr != nullptr && attr->as_boolean ())
15064     fnp->is_deleted = 1;
15065
15066   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15067
15068   /* Get index in virtual function table if it is a virtual member
15069      function.  For older versions of GCC, this is an offset in the
15070      appropriate virtual table, as specified by DW_AT_containing_type.
15071      For everyone else, it is an expression to be evaluated relative
15072      to the object address.  */
15073
15074   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15075   if (attr != nullptr)
15076     {
15077       if (attr->form_is_block () && attr->as_block ()->size > 0)
15078         {
15079           struct dwarf_block *block = attr->as_block ();
15080
15081           if (block->data[0] == DW_OP_constu)
15082             {
15083               /* Old-style GCC.  */
15084               fnp->voffset = decode_locdesc (block, cu) + 2;
15085             }
15086           else if (block->data[0] == DW_OP_deref
15087                    || (block->size > 1
15088                        && block->data[0] == DW_OP_deref_size
15089                        && block->data[1] == cu->header.addr_size))
15090             {
15091               fnp->voffset = decode_locdesc (block, cu);
15092               if ((fnp->voffset % cu->header.addr_size) != 0)
15093                 dwarf2_complex_location_expr_complaint ();
15094               else
15095                 fnp->voffset /= cu->header.addr_size;
15096               fnp->voffset += 2;
15097             }
15098           else
15099             dwarf2_complex_location_expr_complaint ();
15100
15101           if (!fnp->fcontext)
15102             {
15103               /* If there is no `this' field and no DW_AT_containing_type,
15104                  we cannot actually find a base class context for the
15105                  vtable!  */
15106               if (this_type->num_fields () == 0
15107                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15108                 {
15109                   complaint (_("cannot determine context for virtual member "
15110                                "function \"%s\" (offset %s)"),
15111                              fieldname, sect_offset_str (die->sect_off));
15112                 }
15113               else
15114                 {
15115                   fnp->fcontext
15116                     = TYPE_TARGET_TYPE (this_type->field (0).type ());
15117                 }
15118             }
15119         }
15120       else if (attr->form_is_section_offset ())
15121         {
15122           dwarf2_complex_location_expr_complaint ();
15123         }
15124       else
15125         {
15126           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15127                                                  fieldname);
15128         }
15129     }
15130   else
15131     {
15132       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15133       if (attr != nullptr && attr->as_virtuality () != DW_VIRTUALITY_none)
15134         {
15135           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15136           complaint (_("Member function \"%s\" (offset %s) is virtual "
15137                        "but the vtable offset is not specified"),
15138                      fieldname, sect_offset_str (die->sect_off));
15139           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15140           TYPE_CPLUS_DYNAMIC (type) = 1;
15141         }
15142     }
15143 }
15144
15145 /* Create the vector of member function fields, and attach it to the type.  */
15146
15147 static void
15148 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15149                                  struct dwarf2_cu *cu)
15150 {
15151   if (cu->per_cu->lang == language_ada)
15152     error (_("unexpected member functions in Ada type"));
15153
15154   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15155   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15156     TYPE_ALLOC (type,
15157                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15158
15159   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15160     {
15161       struct fnfieldlist &nf = fip->fnfieldlists[i];
15162       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15163
15164       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15165       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15166       fn_flp->fn_fields = (struct fn_field *)
15167         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15168
15169       for (int k = 0; k < nf.fnfields.size (); ++k)
15170         fn_flp->fn_fields[k] = nf.fnfields[k];
15171     }
15172
15173   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15174 }
15175
15176 /* Returns non-zero if NAME is the name of a vtable member in CU's
15177    language, zero otherwise.  */
15178 static int
15179 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15180 {
15181   static const char vptr[] = "_vptr";
15182
15183   /* Look for the C++ form of the vtable.  */
15184   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15185     return 1;
15186
15187   return 0;
15188 }
15189
15190 /* GCC outputs unnamed structures that are really pointers to member
15191    functions, with the ABI-specified layout.  If TYPE describes
15192    such a structure, smash it into a member function type.
15193
15194    GCC shouldn't do this; it should just output pointer to member DIEs.
15195    This is GCC PR debug/28767.  */
15196
15197 static void
15198 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15199 {
15200   struct type *pfn_type, *self_type, *new_type;
15201
15202   /* Check for a structure with no name and two children.  */
15203   if (type->code () != TYPE_CODE_STRUCT || type->num_fields () != 2)
15204     return;
15205
15206   /* Check for __pfn and __delta members.  */
15207   if (TYPE_FIELD_NAME (type, 0) == NULL
15208       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15209       || TYPE_FIELD_NAME (type, 1) == NULL
15210       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15211     return;
15212
15213   /* Find the type of the method.  */
15214   pfn_type = type->field (0).type ();
15215   if (pfn_type == NULL
15216       || pfn_type->code () != TYPE_CODE_PTR
15217       || TYPE_TARGET_TYPE (pfn_type)->code () != TYPE_CODE_FUNC)
15218     return;
15219
15220   /* Look for the "this" argument.  */
15221   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15222   if (pfn_type->num_fields () == 0
15223       /* || pfn_type->field (0).type () == NULL */
15224       || pfn_type->field (0).type ()->code () != TYPE_CODE_PTR)
15225     return;
15226
15227   self_type = TYPE_TARGET_TYPE (pfn_type->field (0).type ());
15228   new_type = alloc_type (objfile);
15229   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15230                         pfn_type->fields (), pfn_type->num_fields (),
15231                         pfn_type->has_varargs ());
15232   smash_to_methodptr_type (type, new_type);
15233 }
15234
15235 /* Helper for quirk_ada_thick_pointer.  If TYPE is an array type that
15236    requires rewriting, then copy it and return the updated copy.
15237    Otherwise return nullptr.  */
15238
15239 static struct type *
15240 rewrite_array_type (struct type *type)
15241 {
15242   if (type->code () != TYPE_CODE_ARRAY)
15243     return nullptr;
15244
15245   struct type *index_type = type->index_type ();
15246   range_bounds *current_bounds = index_type->bounds ();
15247
15248   /* Handle multi-dimensional arrays.  */
15249   struct type *new_target = rewrite_array_type (TYPE_TARGET_TYPE (type));
15250   if (new_target == nullptr)
15251     {
15252       /* Maybe we don't need to rewrite this array.  */
15253       if (current_bounds->low.kind () == PROP_CONST
15254           && current_bounds->high.kind () == PROP_CONST)
15255         return nullptr;
15256     }
15257
15258   /* Either the target type was rewritten, or the bounds have to be
15259      updated.  Either way we want to copy the type and update
15260      everything.  */
15261   struct type *copy = copy_type (type);
15262   int nfields = copy->num_fields ();
15263   field *new_fields
15264     = ((struct field *) TYPE_ZALLOC (copy,
15265                                      nfields * sizeof (struct field)));
15266   memcpy (new_fields, copy->fields (), nfields * sizeof (struct field));
15267   copy->set_fields (new_fields);
15268   if (new_target != nullptr)
15269     TYPE_TARGET_TYPE (copy) = new_target;
15270
15271   struct type *index_copy = copy_type (index_type);
15272   range_bounds *bounds
15273     = (struct range_bounds *) TYPE_ZALLOC (index_copy,
15274                                            sizeof (range_bounds));
15275   *bounds = *current_bounds;
15276   bounds->low.set_const_val (1);
15277   bounds->high.set_const_val (0);
15278   index_copy->set_bounds (bounds);
15279   copy->set_index_type (index_copy);
15280
15281   return copy;
15282 }
15283
15284 /* While some versions of GCC will generate complicated DWARF for an
15285    array (see quirk_ada_thick_pointer), more recent versions were
15286    modified to emit an explicit thick pointer structure.  However, in
15287    this case, the array still has DWARF expressions for its ranges,
15288    and these must be ignored.  */
15289
15290 static void
15291 quirk_ada_thick_pointer_struct (struct die_info *die, struct dwarf2_cu *cu,
15292                                 struct type *type)
15293 {
15294   gdb_assert (cu->per_cu->lang == language_ada);
15295
15296   /* Check for a structure with two children.  */
15297   if (type->code () != TYPE_CODE_STRUCT || type->num_fields () != 2)
15298     return;
15299
15300   /* Check for P_ARRAY and P_BOUNDS members.  */
15301   if (TYPE_FIELD_NAME (type, 0) == NULL
15302       || strcmp (TYPE_FIELD_NAME (type, 0), "P_ARRAY") != 0
15303       || TYPE_FIELD_NAME (type, 1) == NULL
15304       || strcmp (TYPE_FIELD_NAME (type, 1), "P_BOUNDS") != 0)
15305     return;
15306
15307   /* Make sure we're looking at a pointer to an array.  */
15308   if (type->field (0).type ()->code () != TYPE_CODE_PTR)
15309     return;
15310
15311   /* The Ada code already knows how to handle these types, so all that
15312      we need to do is turn the bounds into static bounds.  However, we
15313      don't want to rewrite existing array or index types in-place,
15314      because those may be referenced in other contexts where this
15315      rewriting is undesirable.  */
15316   struct type *new_ary_type
15317     = rewrite_array_type (TYPE_TARGET_TYPE (type->field (0).type ()));
15318   if (new_ary_type != nullptr)
15319     type->field (0).set_type (lookup_pointer_type (new_ary_type));
15320 }
15321
15322 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15323    appropriate error checking and issuing complaints if there is a
15324    problem.  */
15325
15326 static ULONGEST
15327 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15328 {
15329   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15330
15331   if (attr == nullptr)
15332     return 0;
15333
15334   if (!attr->form_is_constant ())
15335     {
15336       complaint (_("DW_AT_alignment must have constant form"
15337                    " - DIE at %s [in module %s]"),
15338                  sect_offset_str (die->sect_off),
15339                  objfile_name (cu->per_objfile->objfile));
15340       return 0;
15341     }
15342
15343   LONGEST val = attr->constant_value (0);
15344   if (val < 0)
15345     {
15346       complaint (_("DW_AT_alignment value must not be negative"
15347                    " - DIE at %s [in module %s]"),
15348                  sect_offset_str (die->sect_off),
15349                  objfile_name (cu->per_objfile->objfile));
15350       return 0;
15351     }
15352   ULONGEST align = val;
15353
15354   if (align == 0)
15355     {
15356       complaint (_("DW_AT_alignment value must not be zero"
15357                    " - DIE at %s [in module %s]"),
15358                  sect_offset_str (die->sect_off),
15359                  objfile_name (cu->per_objfile->objfile));
15360       return 0;
15361     }
15362   if ((align & (align - 1)) != 0)
15363     {
15364       complaint (_("DW_AT_alignment value must be a power of 2"
15365                    " - DIE at %s [in module %s]"),
15366                  sect_offset_str (die->sect_off),
15367                  objfile_name (cu->per_objfile->objfile));
15368       return 0;
15369     }
15370
15371   return align;
15372 }
15373
15374 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15375    the alignment for TYPE.  */
15376
15377 static void
15378 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15379                      struct type *type)
15380 {
15381   if (!set_type_align (type, get_alignment (cu, die)))
15382     complaint (_("DW_AT_alignment value too large"
15383                  " - DIE at %s [in module %s]"),
15384                sect_offset_str (die->sect_off),
15385                objfile_name (cu->per_objfile->objfile));
15386 }
15387
15388 /* Check if the given VALUE is a valid enum dwarf_calling_convention
15389    constant for a type, according to DWARF5 spec, Table 5.5.  */
15390
15391 static bool
15392 is_valid_DW_AT_calling_convention_for_type (ULONGEST value)
15393 {
15394   switch (value)
15395     {
15396     case DW_CC_normal:
15397     case DW_CC_pass_by_reference:
15398     case DW_CC_pass_by_value:
15399       return true;
15400
15401     default:
15402       complaint (_("unrecognized DW_AT_calling_convention value "
15403                    "(%s) for a type"), pulongest (value));
15404       return false;
15405     }
15406 }
15407
15408 /* Check if the given VALUE is a valid enum dwarf_calling_convention
15409    constant for a subroutine, according to DWARF5 spec, Table 3.3, and
15410    also according to GNU-specific values (see include/dwarf2.h).  */
15411
15412 static bool
15413 is_valid_DW_AT_calling_convention_for_subroutine (ULONGEST value)
15414 {
15415   switch (value)
15416     {
15417     case DW_CC_normal:
15418     case DW_CC_program:
15419     case DW_CC_nocall:
15420       return true;
15421
15422     case DW_CC_GNU_renesas_sh:
15423     case DW_CC_GNU_borland_fastcall_i386:
15424     case DW_CC_GDB_IBM_OpenCL:
15425       return true;
15426
15427     default:
15428       complaint (_("unrecognized DW_AT_calling_convention value "
15429                    "(%s) for a subroutine"), pulongest (value));
15430       return false;
15431     }
15432 }
15433
15434 /* Called when we find the DIE that starts a structure or union scope
15435    (definition) to create a type for the structure or union.  Fill in
15436    the type's name and general properties; the members will not be
15437    processed until process_structure_scope.  A symbol table entry for
15438    the type will also not be done until process_structure_scope (assuming
15439    the type has a name).
15440
15441    NOTE: we need to call these functions regardless of whether or not the
15442    DIE has a DW_AT_name attribute, since it might be an anonymous
15443    structure or union.  This gets the type entered into our set of
15444    user defined types.  */
15445
15446 static struct type *
15447 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15448 {
15449   struct objfile *objfile = cu->per_objfile->objfile;
15450   struct type *type;
15451   struct attribute *attr;
15452   const char *name;
15453
15454   /* If the definition of this type lives in .debug_types, read that type.
15455      Don't follow DW_AT_specification though, that will take us back up
15456      the chain and we want to go down.  */
15457   attr = die->attr (DW_AT_signature);
15458   if (attr != nullptr)
15459     {
15460       type = get_DW_AT_signature_type (die, attr, cu);
15461
15462       /* The type's CU may not be the same as CU.
15463          Ensure TYPE is recorded with CU in die_type_hash.  */
15464       return set_die_type (die, type, cu);
15465     }
15466
15467   type = alloc_type (objfile);
15468   INIT_CPLUS_SPECIFIC (type);
15469
15470   name = dwarf2_name (die, cu);
15471   if (name != NULL)
15472     {
15473       if (cu->per_cu->lang == language_cplus
15474           || cu->per_cu->lang == language_d
15475           || cu->per_cu->lang == language_rust)
15476         {
15477           const char *full_name = dwarf2_full_name (name, die, cu);
15478
15479           /* dwarf2_full_name might have already finished building the DIE's
15480              type.  If so, there is no need to continue.  */
15481           if (get_die_type (die, cu) != NULL)
15482             return get_die_type (die, cu);
15483
15484           type->set_name (full_name);
15485         }
15486       else
15487         {
15488           /* The name is already allocated along with this objfile, so
15489              we don't need to duplicate it for the type.  */
15490           type->set_name (name);
15491         }
15492     }
15493
15494   if (die->tag == DW_TAG_structure_type)
15495     {
15496       type->set_code (TYPE_CODE_STRUCT);
15497     }
15498   else if (die->tag == DW_TAG_union_type)
15499     {
15500       type->set_code (TYPE_CODE_UNION);
15501     }
15502   else
15503     {
15504       type->set_code (TYPE_CODE_STRUCT);
15505     }
15506
15507   if (cu->per_cu->lang == language_cplus && die->tag == DW_TAG_class_type)
15508     type->set_is_declared_class (true);
15509
15510   /* Store the calling convention in the type if it's available in
15511      the die.  Otherwise the calling convention remains set to
15512      the default value DW_CC_normal.  */
15513   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15514   if (attr != nullptr
15515       && is_valid_DW_AT_calling_convention_for_type (attr->constant_value (0)))
15516     {
15517       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15518       TYPE_CPLUS_CALLING_CONVENTION (type)
15519         = (enum dwarf_calling_convention) (attr->constant_value (0));
15520     }
15521
15522   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15523   if (attr != nullptr)
15524     {
15525       if (attr->form_is_constant ())
15526         TYPE_LENGTH (type) = attr->constant_value (0);
15527       else
15528         {
15529           struct dynamic_prop prop;
15530           if (attr_to_dynamic_prop (attr, die, cu, &prop, cu->addr_type ()))
15531             type->add_dyn_prop (DYN_PROP_BYTE_SIZE, prop);
15532           TYPE_LENGTH (type) = 0;
15533         }
15534     }
15535   else
15536     {
15537       TYPE_LENGTH (type) = 0;
15538     }
15539
15540   maybe_set_alignment (cu, die, type);
15541
15542   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15543     {
15544       /* ICC<14 does not output the required DW_AT_declaration on
15545          incomplete types, but gives them a size of zero.  */
15546       type->set_is_stub (true);
15547     }
15548   else
15549     type->set_stub_is_supported (true);
15550
15551   if (die_is_declaration (die, cu))
15552     type->set_is_stub (true);
15553   else if (attr == NULL && die->child == NULL
15554            && producer_is_realview (cu->producer))
15555     /* RealView does not output the required DW_AT_declaration
15556        on incomplete types.  */
15557     type->set_is_stub (true);
15558
15559   /* We need to add the type field to the die immediately so we don't
15560      infinitely recurse when dealing with pointers to the structure
15561      type within the structure itself.  */
15562   set_die_type (die, type, cu);
15563
15564   /* set_die_type should be already done.  */
15565   set_descriptive_type (type, die, cu);
15566
15567   return type;
15568 }
15569
15570 static void handle_struct_member_die
15571   (struct die_info *child_die,
15572    struct type *type,
15573    struct field_info *fi,
15574    std::vector<struct symbol *> *template_args,
15575    struct dwarf2_cu *cu);
15576
15577 /* A helper for handle_struct_member_die that handles
15578    DW_TAG_variant_part.  */
15579
15580 static void
15581 handle_variant_part (struct die_info *die, struct type *type,
15582                      struct field_info *fi,
15583                      std::vector<struct symbol *> *template_args,
15584                      struct dwarf2_cu *cu)
15585 {
15586   variant_part_builder *new_part;
15587   if (fi->current_variant_part == nullptr)
15588     {
15589       fi->variant_parts.emplace_back ();
15590       new_part = &fi->variant_parts.back ();
15591     }
15592   else if (!fi->current_variant_part->processing_variant)
15593     {
15594       complaint (_("nested DW_TAG_variant_part seen "
15595                    "- DIE at %s [in module %s]"),
15596                  sect_offset_str (die->sect_off),
15597                  objfile_name (cu->per_objfile->objfile));
15598       return;
15599     }
15600   else
15601     {
15602       variant_field &current = fi->current_variant_part->variants.back ();
15603       current.variant_parts.emplace_back ();
15604       new_part = &current.variant_parts.back ();
15605     }
15606
15607   /* When we recurse, we want callees to add to this new variant
15608      part.  */
15609   scoped_restore save_current_variant_part
15610     = make_scoped_restore (&fi->current_variant_part, new_part);
15611
15612   struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15613   if (discr == NULL)
15614     {
15615       /* It's a univariant form, an extension we support.  */
15616     }
15617   else if (discr->form_is_ref ())
15618     {
15619       struct dwarf2_cu *target_cu = cu;
15620       struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15621
15622       new_part->discriminant_offset = target_die->sect_off;
15623     }
15624   else
15625     {
15626       complaint (_("DW_AT_discr does not have DIE reference form"
15627                    " - DIE at %s [in module %s]"),
15628                  sect_offset_str (die->sect_off),
15629                  objfile_name (cu->per_objfile->objfile));
15630     }
15631
15632   for (die_info *child_die = die->child;
15633        child_die != NULL;
15634        child_die = child_die->sibling)
15635     handle_struct_member_die (child_die, type, fi, template_args, cu);
15636 }
15637
15638 /* A helper for handle_struct_member_die that handles
15639    DW_TAG_variant.  */
15640
15641 static void
15642 handle_variant (struct die_info *die, struct type *type,
15643                 struct field_info *fi,
15644                 std::vector<struct symbol *> *template_args,
15645                 struct dwarf2_cu *cu)
15646 {
15647   if (fi->current_variant_part == nullptr)
15648     {
15649       complaint (_("saw DW_TAG_variant outside DW_TAG_variant_part "
15650                    "- DIE at %s [in module %s]"),
15651                  sect_offset_str (die->sect_off),
15652                  objfile_name (cu->per_objfile->objfile));
15653       return;
15654     }
15655   if (fi->current_variant_part->processing_variant)
15656     {
15657       complaint (_("nested DW_TAG_variant seen "
15658                    "- DIE at %s [in module %s]"),
15659                  sect_offset_str (die->sect_off),
15660                  objfile_name (cu->per_objfile->objfile));
15661       return;
15662     }
15663
15664   scoped_restore save_processing_variant
15665     = make_scoped_restore (&fi->current_variant_part->processing_variant,
15666                            true);
15667
15668   fi->current_variant_part->variants.emplace_back ();
15669   variant_field &variant = fi->current_variant_part->variants.back ();
15670   variant.first_field = fi->fields.size ();
15671
15672   /* In a variant we want to get the discriminant and also add a
15673      field for our sole member child.  */
15674   struct attribute *discr = dwarf2_attr (die, DW_AT_discr_value, cu);
15675   if (discr == nullptr || !discr->form_is_constant ())
15676     {
15677       discr = dwarf2_attr (die, DW_AT_discr_list, cu);
15678       if (discr == nullptr || discr->as_block ()->size == 0)
15679         variant.default_branch = true;
15680       else
15681         variant.discr_list_data = discr->as_block ();
15682     }
15683   else
15684     variant.discriminant_value = discr->constant_value (0);
15685
15686   for (die_info *variant_child = die->child;
15687        variant_child != NULL;
15688        variant_child = variant_child->sibling)
15689     handle_struct_member_die (variant_child, type, fi, template_args, cu);
15690
15691   variant.last_field = fi->fields.size ();
15692 }
15693
15694 /* A helper for process_structure_scope that handles a single member
15695    DIE.  */
15696
15697 static void
15698 handle_struct_member_die (struct die_info *child_die, struct type *type,
15699                           struct field_info *fi,
15700                           std::vector<struct symbol *> *template_args,
15701                           struct dwarf2_cu *cu)
15702 {
15703   if (child_die->tag == DW_TAG_member
15704       || child_die->tag == DW_TAG_variable)
15705     {
15706       /* NOTE: carlton/2002-11-05: A C++ static data member
15707          should be a DW_TAG_member that is a declaration, but
15708          all versions of G++ as of this writing (so through at
15709          least 3.2.1) incorrectly generate DW_TAG_variable
15710          tags for them instead.  */
15711       dwarf2_add_field (fi, child_die, cu);
15712     }
15713   else if (child_die->tag == DW_TAG_subprogram)
15714     {
15715       /* Rust doesn't have member functions in the C++ sense.
15716          However, it does emit ordinary functions as children
15717          of a struct DIE.  */
15718       if (cu->per_cu->lang == language_rust)
15719         read_func_scope (child_die, cu);
15720       else
15721         {
15722           /* C++ member function.  */
15723           dwarf2_add_member_fn (fi, child_die, type, cu);
15724         }
15725     }
15726   else if (child_die->tag == DW_TAG_inheritance)
15727     {
15728       /* C++ base class field.  */
15729       dwarf2_add_field (fi, child_die, cu);
15730     }
15731   else if (type_can_define_types (child_die))
15732     dwarf2_add_type_defn (fi, child_die, cu);
15733   else if (child_die->tag == DW_TAG_template_type_param
15734            || child_die->tag == DW_TAG_template_value_param)
15735     {
15736       struct symbol *arg = new_symbol (child_die, NULL, cu);
15737
15738       if (arg != NULL)
15739         template_args->push_back (arg);
15740     }
15741   else if (child_die->tag == DW_TAG_variant_part)
15742     handle_variant_part (child_die, type, fi, template_args, cu);
15743   else if (child_die->tag == DW_TAG_variant)
15744     handle_variant (child_die, type, fi, template_args, cu);
15745 }
15746
15747 /* Finish creating a structure or union type, including filling in
15748    its members and creating a symbol for it.  */
15749
15750 static void
15751 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15752 {
15753   struct objfile *objfile = cu->per_objfile->objfile;
15754   struct die_info *child_die;
15755   struct type *type;
15756
15757   type = get_die_type (die, cu);
15758   if (type == NULL)
15759     type = read_structure_type (die, cu);
15760
15761   bool has_template_parameters = false;
15762   if (die->child != NULL && ! die_is_declaration (die, cu))
15763     {
15764       struct field_info fi;
15765       std::vector<struct symbol *> template_args;
15766
15767       child_die = die->child;
15768
15769       while (child_die && child_die->tag)
15770         {
15771           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15772           child_die = child_die->sibling;
15773         }
15774
15775       /* Attach template arguments to type.  */
15776       if (!template_args.empty ())
15777         {
15778           has_template_parameters = true;
15779           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15780           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15781           TYPE_TEMPLATE_ARGUMENTS (type)
15782             = XOBNEWVEC (&objfile->objfile_obstack,
15783                          struct symbol *,
15784                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15785           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15786                   template_args.data (),
15787                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15788                    * sizeof (struct symbol *)));
15789         }
15790
15791       /* Attach fields and member functions to the type.  */
15792       if (fi.nfields () > 0)
15793         dwarf2_attach_fields_to_type (&fi, type, cu);
15794       if (!fi.fnfieldlists.empty ())
15795         {
15796           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15797
15798           /* Get the type which refers to the base class (possibly this
15799              class itself) which contains the vtable pointer for the current
15800              class from the DW_AT_containing_type attribute.  This use of
15801              DW_AT_containing_type is a GNU extension.  */
15802
15803           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15804             {
15805               struct type *t = die_containing_type (die, cu);
15806
15807               set_type_vptr_basetype (type, t);
15808               if (type == t)
15809                 {
15810                   int i;
15811
15812                   /* Our own class provides vtbl ptr.  */
15813                   for (i = t->num_fields () - 1;
15814                        i >= TYPE_N_BASECLASSES (t);
15815                        --i)
15816                     {
15817                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15818
15819                       if (is_vtable_name (fieldname, cu))
15820                         {
15821                           set_type_vptr_fieldno (type, i);
15822                           break;
15823                         }
15824                     }
15825
15826                   /* Complain if virtual function table field not found.  */
15827                   if (i < TYPE_N_BASECLASSES (t))
15828                     complaint (_("virtual function table pointer "
15829                                  "not found when defining class '%s'"),
15830                                type->name () ? type->name () : "");
15831                 }
15832               else
15833                 {
15834                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15835                 }
15836             }
15837           else if (cu->producer
15838                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15839             {
15840               /* The IBM XLC compiler does not provide direct indication
15841                  of the containing type, but the vtable pointer is
15842                  always named __vfp.  */
15843
15844               int i;
15845
15846               for (i = type->num_fields () - 1;
15847                    i >= TYPE_N_BASECLASSES (type);
15848                    --i)
15849                 {
15850                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15851                     {
15852                       set_type_vptr_fieldno (type, i);
15853                       set_type_vptr_basetype (type, type);
15854                       break;
15855                     }
15856                 }
15857             }
15858         }
15859
15860       /* Copy fi.typedef_field_list linked list elements content into the
15861          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15862       if (!fi.typedef_field_list.empty ())
15863         {
15864           int count = fi.typedef_field_list.size ();
15865
15866           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15867           TYPE_TYPEDEF_FIELD_ARRAY (type)
15868             = ((struct decl_field *)
15869                TYPE_ALLOC (type,
15870                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
15871           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
15872
15873           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
15874             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
15875         }
15876
15877       /* Copy fi.nested_types_list linked list elements content into the
15878          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15879       if (!fi.nested_types_list.empty ()
15880           && cu->per_cu->lang != language_ada)
15881         {
15882           int count = fi.nested_types_list.size ();
15883
15884           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15885           TYPE_NESTED_TYPES_ARRAY (type)
15886             = ((struct decl_field *)
15887                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
15888           TYPE_NESTED_TYPES_COUNT (type) = count;
15889
15890           for (int i = 0; i < fi.nested_types_list.size (); ++i)
15891             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
15892         }
15893     }
15894
15895   quirk_gcc_member_function_pointer (type, objfile);
15896   if (cu->per_cu->lang == language_rust && die->tag == DW_TAG_union_type)
15897     cu->rust_unions.push_back (type);
15898   else if (cu->per_cu->lang == language_ada)
15899     quirk_ada_thick_pointer_struct (die, cu, type);
15900
15901   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
15902      snapshots) has been known to create a die giving a declaration
15903      for a class that has, as a child, a die giving a definition for a
15904      nested class.  So we have to process our children even if the
15905      current die is a declaration.  Normally, of course, a declaration
15906      won't have any children at all.  */
15907
15908   child_die = die->child;
15909
15910   while (child_die != NULL && child_die->tag)
15911     {
15912       if (child_die->tag == DW_TAG_member
15913           || child_die->tag == DW_TAG_variable
15914           || child_die->tag == DW_TAG_inheritance
15915           || child_die->tag == DW_TAG_template_value_param
15916           || child_die->tag == DW_TAG_template_type_param)
15917         {
15918           /* Do nothing.  */
15919         }
15920       else
15921         process_die (child_die, cu);
15922
15923       child_die = child_die->sibling;
15924     }
15925
15926   /* Do not consider external references.  According to the DWARF standard,
15927      these DIEs are identified by the fact that they have no byte_size
15928      attribute, and a declaration attribute.  */
15929   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
15930       || !die_is_declaration (die, cu)
15931       || dwarf2_attr (die, DW_AT_signature, cu) != NULL)
15932     {
15933       struct symbol *sym = new_symbol (die, type, cu);
15934
15935       if (has_template_parameters)
15936         {
15937           struct symtab *symtab;
15938           if (sym != nullptr)
15939             symtab = symbol_symtab (sym);
15940           else if (cu->line_header != nullptr)
15941             {
15942               /* Any related symtab will do.  */
15943               symtab
15944                 = cu->line_header->file_names ()[0].symtab;
15945             }
15946           else
15947             {
15948               symtab = nullptr;
15949               complaint (_("could not find suitable "
15950                            "symtab for template parameter"
15951                            " - DIE at %s [in module %s]"),
15952                          sect_offset_str (die->sect_off),
15953                          objfile_name (objfile));
15954             }
15955
15956           if (symtab != nullptr)
15957             {
15958               /* Make sure that the symtab is set on the new symbols.
15959                  Even though they don't appear in this symtab directly,
15960                  other parts of gdb assume that symbols do, and this is
15961                  reasonably true.  */
15962               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
15963                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
15964             }
15965         }
15966     }
15967 }
15968
15969 /* Assuming DIE is an enumeration type, and TYPE is its associated
15970    type, update TYPE using some information only available in DIE's
15971    children.  In particular, the fields are computed.  */
15972
15973 static void
15974 update_enumeration_type_from_children (struct die_info *die,
15975                                        struct type *type,
15976                                        struct dwarf2_cu *cu)
15977 {
15978   struct die_info *child_die;
15979   int unsigned_enum = 1;
15980   int flag_enum = 1;
15981
15982   auto_obstack obstack;
15983   std::vector<struct field> fields;
15984
15985   for (child_die = die->child;
15986        child_die != NULL && child_die->tag;
15987        child_die = child_die->sibling)
15988     {
15989       struct attribute *attr;
15990       LONGEST value;
15991       const gdb_byte *bytes;
15992       struct dwarf2_locexpr_baton *baton;
15993       const char *name;
15994
15995       if (child_die->tag != DW_TAG_enumerator)
15996         continue;
15997
15998       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
15999       if (attr == NULL)
16000         continue;
16001
16002       name = dwarf2_name (child_die, cu);
16003       if (name == NULL)
16004         name = "<anonymous enumerator>";
16005
16006       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16007                                &value, &bytes, &baton);
16008       if (value < 0)
16009         {
16010           unsigned_enum = 0;
16011           flag_enum = 0;
16012         }
16013       else
16014         {
16015           if (count_one_bits_ll (value) >= 2)
16016             flag_enum = 0;
16017         }
16018
16019       fields.emplace_back ();
16020       struct field &field = fields.back ();
16021       FIELD_NAME (field) = dwarf2_physname (name, child_die, cu);
16022       SET_FIELD_ENUMVAL (field, value);
16023     }
16024
16025   if (!fields.empty ())
16026     {
16027       type->set_num_fields (fields.size ());
16028       type->set_fields
16029         ((struct field *)
16030          TYPE_ALLOC (type, sizeof (struct field) * fields.size ()));
16031       memcpy (type->fields (), fields.data (),
16032               sizeof (struct field) * fields.size ());
16033     }
16034
16035   if (unsigned_enum)
16036     type->set_is_unsigned (true);
16037
16038   if (flag_enum)
16039     type->set_is_flag_enum (true);
16040 }
16041
16042 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16043    complete the type's fields yet, or create any symbols.  */
16044
16045 static struct type *
16046 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16047 {
16048   struct objfile *objfile = cu->per_objfile->objfile;
16049   struct type *type;
16050   struct attribute *attr;
16051   const char *name;
16052
16053   /* If the definition of this type lives in .debug_types, read that type.
16054      Don't follow DW_AT_specification though, that will take us back up
16055      the chain and we want to go down.  */
16056   attr = die->attr (DW_AT_signature);
16057   if (attr != nullptr)
16058     {
16059       type = get_DW_AT_signature_type (die, attr, cu);
16060
16061       /* The type's CU may not be the same as CU.
16062          Ensure TYPE is recorded with CU in die_type_hash.  */
16063       return set_die_type (die, type, cu);
16064     }
16065
16066   type = alloc_type (objfile);
16067
16068   type->set_code (TYPE_CODE_ENUM);
16069   name = dwarf2_full_name (NULL, die, cu);
16070   if (name != NULL)
16071     type->set_name (name);
16072
16073   attr = dwarf2_attr (die, DW_AT_type, cu);
16074   if (attr != NULL)
16075     {
16076       struct type *underlying_type = die_type (die, cu);
16077
16078       TYPE_TARGET_TYPE (type) = underlying_type;
16079     }
16080
16081   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16082   if (attr != nullptr)
16083     {
16084       TYPE_LENGTH (type) = attr->constant_value (0);
16085     }
16086   else
16087     {
16088       TYPE_LENGTH (type) = 0;
16089     }
16090
16091   maybe_set_alignment (cu, die, type);
16092
16093   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16094      declared as private in the package spec, and then defined only
16095      inside the package body.  Such types are known as Taft Amendment
16096      Types.  When another package uses such a type, an incomplete DIE
16097      may be generated by the compiler.  */
16098   if (die_is_declaration (die, cu))
16099     type->set_is_stub (true);
16100
16101   /* If this type has an underlying type that is not a stub, then we
16102      may use its attributes.  We always use the "unsigned" attribute
16103      in this situation, because ordinarily we guess whether the type
16104      is unsigned -- but the guess can be wrong and the underlying type
16105      can tell us the reality.  However, we defer to a local size
16106      attribute if one exists, because this lets the compiler override
16107      the underlying type if needed.  */
16108   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_TARGET_TYPE (type)->is_stub ())
16109     {
16110       struct type *underlying_type = TYPE_TARGET_TYPE (type);
16111       underlying_type = check_typedef (underlying_type);
16112
16113       type->set_is_unsigned (underlying_type->is_unsigned ());
16114
16115       if (TYPE_LENGTH (type) == 0)
16116         TYPE_LENGTH (type) = TYPE_LENGTH (underlying_type);
16117
16118       if (TYPE_RAW_ALIGN (type) == 0
16119           && TYPE_RAW_ALIGN (underlying_type) != 0)
16120         set_type_align (type, TYPE_RAW_ALIGN (underlying_type));
16121     }
16122
16123   type->set_is_declared_class (dwarf2_flag_true_p (die, DW_AT_enum_class, cu));
16124
16125   set_die_type (die, type, cu);
16126
16127   /* Finish the creation of this type by using the enum's children.
16128      Note that, as usual, this must come after set_die_type to avoid
16129      infinite recursion when trying to compute the names of the
16130      enumerators.  */
16131   update_enumeration_type_from_children (die, type, cu);
16132
16133   return type;
16134 }
16135
16136 /* Given a pointer to a die which begins an enumeration, process all
16137    the dies that define the members of the enumeration, and create the
16138    symbol for the enumeration type.
16139
16140    NOTE: We reverse the order of the element list.  */
16141
16142 static void
16143 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16144 {
16145   struct type *this_type;
16146
16147   this_type = get_die_type (die, cu);
16148   if (this_type == NULL)
16149     this_type = read_enumeration_type (die, cu);
16150
16151   if (die->child != NULL)
16152     {
16153       struct die_info *child_die;
16154       const char *name;
16155
16156       child_die = die->child;
16157       while (child_die && child_die->tag)
16158         {
16159           if (child_die->tag != DW_TAG_enumerator)
16160             {
16161               process_die (child_die, cu);
16162             }
16163           else
16164             {
16165               name = dwarf2_name (child_die, cu);
16166               if (name)
16167                 new_symbol (child_die, this_type, cu);
16168             }
16169
16170           child_die = child_die->sibling;
16171         }
16172     }
16173
16174   /* If we are reading an enum from a .debug_types unit, and the enum
16175      is a declaration, and the enum is not the signatured type in the
16176      unit, then we do not want to add a symbol for it.  Adding a
16177      symbol would in some cases obscure the true definition of the
16178      enum, giving users an incomplete type when the definition is
16179      actually available.  Note that we do not want to do this for all
16180      enums which are just declarations, because C++0x allows forward
16181      enum declarations.  */
16182   if (cu->per_cu->is_debug_types
16183       && die_is_declaration (die, cu))
16184     {
16185       struct signatured_type *sig_type;
16186
16187       sig_type = (struct signatured_type *) cu->per_cu;
16188       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16189       if (sig_type->type_offset_in_section != die->sect_off)
16190         return;
16191     }
16192
16193   new_symbol (die, this_type, cu);
16194 }
16195
16196 /* Helper function for quirk_ada_thick_pointer that examines a bounds
16197    expression for an index type and finds the corresponding field
16198    offset in the hidden "P_BOUNDS" structure.  Returns true on success
16199    and updates *FIELD, false if it fails to recognize an
16200    expression.  */
16201
16202 static bool
16203 recognize_bound_expression (struct die_info *die, enum dwarf_attribute name,
16204                             int *bounds_offset, struct field *field,
16205                             struct dwarf2_cu *cu)
16206 {
16207   struct attribute *attr = dwarf2_attr (die, name, cu);
16208   if (attr == nullptr || !attr->form_is_block ())
16209     return false;
16210
16211   const struct dwarf_block *block = attr->as_block ();
16212   const gdb_byte *start = block->data;
16213   const gdb_byte *end = block->data + block->size;
16214
16215   /* The expression to recognize generally looks like:
16216
16217      (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16218      DW_OP_plus_uconst: 4; DW_OP_deref_size: 4)
16219
16220      However, the second "plus_uconst" may be missing:
16221
16222      (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16223      DW_OP_deref_size: 4)
16224
16225      This happens when the field is at the start of the structure.
16226
16227      Also, the final deref may not be sized:
16228
16229      (DW_OP_push_object_address; DW_OP_plus_uconst: 4; DW_OP_deref;
16230      DW_OP_deref)
16231
16232      This happens when the size of the index type happens to be the
16233      same as the architecture's word size.  This can occur with or
16234      without the second plus_uconst.  */
16235
16236   if (end - start < 2)
16237     return false;
16238   if (*start++ != DW_OP_push_object_address)
16239     return false;
16240   if (*start++ != DW_OP_plus_uconst)
16241     return false;
16242
16243   uint64_t this_bound_off;
16244   start = gdb_read_uleb128 (start, end, &this_bound_off);
16245   if (start == nullptr || (int) this_bound_off != this_bound_off)
16246     return false;
16247   /* Update *BOUNDS_OFFSET if needed, or alternatively verify that it
16248      is consistent among all bounds.  */
16249   if (*bounds_offset == -1)
16250     *bounds_offset = this_bound_off;
16251   else if (*bounds_offset != this_bound_off)
16252     return false;
16253
16254   if (start == end || *start++ != DW_OP_deref)
16255     return false;
16256
16257   int offset = 0;
16258   if (start ==end)
16259     return false;
16260   else if (*start == DW_OP_deref_size || *start == DW_OP_deref)
16261     {
16262       /* This means an offset of 0.  */
16263     }
16264   else if (*start++ != DW_OP_plus_uconst)
16265     return false;
16266   else
16267     {
16268       /* The size is the parameter to DW_OP_plus_uconst.  */
16269       uint64_t val;
16270       start = gdb_read_uleb128 (start, end, &val);
16271       if (start == nullptr)
16272         return false;
16273       if ((int) val != val)
16274         return false;
16275       offset = val;
16276     }
16277
16278   if (start == end)
16279     return false;
16280
16281   uint64_t size;
16282   if (*start == DW_OP_deref_size)
16283     {
16284       start = gdb_read_uleb128 (start + 1, end, &size);
16285       if (start == nullptr)
16286         return false;
16287     }
16288   else if (*start == DW_OP_deref)
16289     {
16290       size = cu->header.addr_size;
16291       ++start;
16292     }
16293   else
16294     return false;
16295
16296   SET_FIELD_BITPOS (*field, 8 * offset);
16297   if (size != TYPE_LENGTH (field->type ()))
16298     FIELD_BITSIZE (*field) = 8 * size;
16299
16300   return true;
16301 }
16302
16303 /* With -fgnat-encodings=minimal, gcc will emit some unusual DWARF for
16304    some kinds of Ada arrays:
16305
16306    <1><11db>: Abbrev Number: 7 (DW_TAG_array_type)
16307       <11dc>   DW_AT_name        : (indirect string, offset: 0x1bb8): string
16308       <11e0>   DW_AT_data_location: 2 byte block: 97 6
16309           (DW_OP_push_object_address; DW_OP_deref)
16310       <11e3>   DW_AT_type        : <0x1173>
16311       <11e7>   DW_AT_sibling     : <0x1201>
16312    <2><11eb>: Abbrev Number: 8 (DW_TAG_subrange_type)
16313       <11ec>   DW_AT_type        : <0x1206>
16314       <11f0>   DW_AT_lower_bound : 6 byte block: 97 23 8 6 94 4
16315           (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16316            DW_OP_deref_size: 4)
16317       <11f7>   DW_AT_upper_bound : 8 byte block: 97 23 8 6 23 4 94 4
16318           (DW_OP_push_object_address; DW_OP_plus_uconst: 8; DW_OP_deref;
16319            DW_OP_plus_uconst: 4; DW_OP_deref_size: 4)
16320
16321    This actually represents a "thick pointer", which is a structure
16322    with two elements: one that is a pointer to the array data, and one
16323    that is a pointer to another structure; this second structure holds
16324    the array bounds.
16325
16326    This returns a new type on success, or nullptr if this didn't
16327    recognize the type.  */
16328
16329 static struct type *
16330 quirk_ada_thick_pointer (struct die_info *die, struct dwarf2_cu *cu,
16331                          struct type *type)
16332 {
16333   struct attribute *attr = dwarf2_attr (die, DW_AT_data_location, cu);
16334   /* So far we've only seen this with block form.  */
16335   if (attr == nullptr || !attr->form_is_block ())
16336     return nullptr;
16337
16338   /* Note that this will fail if the structure layout is changed by
16339      the compiler.  However, we have no good way to recognize some
16340      other layout, because we don't know what expression the compiler
16341      might choose to emit should this happen.  */
16342   struct dwarf_block *blk = attr->as_block ();
16343   if (blk->size != 2
16344       || blk->data[0] != DW_OP_push_object_address
16345       || blk->data[1] != DW_OP_deref)
16346     return nullptr;
16347
16348   int bounds_offset = -1;
16349   int max_align = -1;
16350   std::vector<struct field> range_fields;
16351   for (struct die_info *child_die = die->child;
16352        child_die;
16353        child_die = child_die->sibling)
16354     {
16355       if (child_die->tag == DW_TAG_subrange_type)
16356         {
16357           struct type *underlying = read_subrange_index_type (child_die, cu);
16358
16359           int this_align = type_align (underlying);
16360           if (this_align > max_align)
16361             max_align = this_align;
16362
16363           range_fields.emplace_back ();
16364           range_fields.emplace_back ();
16365
16366           struct field &lower = range_fields[range_fields.size () - 2];
16367           struct field &upper = range_fields[range_fields.size () - 1];
16368
16369           lower.set_type (underlying);
16370           FIELD_ARTIFICIAL (lower) = 1;
16371
16372           upper.set_type (underlying);
16373           FIELD_ARTIFICIAL (upper) = 1;
16374
16375           if (!recognize_bound_expression (child_die, DW_AT_lower_bound,
16376                                            &bounds_offset, &lower, cu)
16377               || !recognize_bound_expression (child_die, DW_AT_upper_bound,
16378                                               &bounds_offset, &upper, cu))
16379             return nullptr;
16380         }
16381     }
16382
16383   /* This shouldn't really happen, but double-check that we found
16384      where the bounds are stored.  */
16385   if (bounds_offset == -1)
16386     return nullptr;
16387
16388   struct objfile *objfile = cu->per_objfile->objfile;
16389   for (int i = 0; i < range_fields.size (); i += 2)
16390     {
16391       char name[20];
16392
16393       /* Set the name of each field in the bounds.  */
16394       xsnprintf (name, sizeof (name), "LB%d", i / 2);
16395       FIELD_NAME (range_fields[i]) = objfile->intern (name);
16396       xsnprintf (name, sizeof (name), "UB%d", i / 2);
16397       FIELD_NAME (range_fields[i + 1]) = objfile->intern (name);
16398     }
16399
16400   struct type *bounds = alloc_type (objfile);
16401   bounds->set_code (TYPE_CODE_STRUCT);
16402
16403   bounds->set_num_fields (range_fields.size ());
16404   bounds->set_fields
16405     ((struct field *) TYPE_ALLOC (bounds, (bounds->num_fields ()
16406                                            * sizeof (struct field))));
16407   memcpy (bounds->fields (), range_fields.data (),
16408           bounds->num_fields () * sizeof (struct field));
16409
16410   int last_fieldno = range_fields.size () - 1;
16411   int bounds_size = (TYPE_FIELD_BITPOS (bounds, last_fieldno) / 8
16412                      + TYPE_LENGTH (bounds->field (last_fieldno).type ()));
16413   TYPE_LENGTH (bounds) = align_up (bounds_size, max_align);
16414
16415   /* Rewrite the existing array type in place.  Specifically, we
16416      remove any dynamic properties we might have read, and we replace
16417      the index types.  */
16418   struct type *iter = type;
16419   for (int i = 0; i < range_fields.size (); i += 2)
16420     {
16421       gdb_assert (iter->code () == TYPE_CODE_ARRAY);
16422       iter->main_type->dyn_prop_list = nullptr;
16423       iter->set_index_type
16424         (create_static_range_type (NULL, bounds->field (i).type (), 1, 0));
16425       iter = TYPE_TARGET_TYPE (iter);
16426     }
16427
16428   struct type *result = alloc_type (objfile);
16429   result->set_code (TYPE_CODE_STRUCT);
16430
16431   result->set_num_fields (2);
16432   result->set_fields
16433     ((struct field *) TYPE_ZALLOC (result, (result->num_fields ()
16434                                             * sizeof (struct field))));
16435
16436   /* The names are chosen to coincide with what the compiler does with
16437      -fgnat-encodings=all, which the Ada code in gdb already
16438      understands.  */
16439   TYPE_FIELD_NAME (result, 0) = "P_ARRAY";
16440   result->field (0).set_type (lookup_pointer_type (type));
16441
16442   TYPE_FIELD_NAME (result, 1) = "P_BOUNDS";
16443   result->field (1).set_type (lookup_pointer_type (bounds));
16444   SET_FIELD_BITPOS (result->field (1), 8 * bounds_offset);
16445
16446   result->set_name (type->name ());
16447   TYPE_LENGTH (result) = (TYPE_LENGTH (result->field (0).type ())
16448                           + TYPE_LENGTH (result->field (1).type ()));
16449
16450   return result;
16451 }
16452
16453 /* Extract all information from a DW_TAG_array_type DIE and put it in
16454    the DIE's type field.  For now, this only handles one dimensional
16455    arrays.  */
16456
16457 static struct type *
16458 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16459 {
16460   struct objfile *objfile = cu->per_objfile->objfile;
16461   struct die_info *child_die;
16462   struct type *type;
16463   struct type *element_type, *range_type, *index_type;
16464   struct attribute *attr;
16465   const char *name;
16466   struct dynamic_prop *byte_stride_prop = NULL;
16467   unsigned int bit_stride = 0;
16468
16469   element_type = die_type (die, cu);
16470
16471   /* The die_type call above may have already set the type for this DIE.  */
16472   type = get_die_type (die, cu);
16473   if (type)
16474     return type;
16475
16476   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16477   if (attr != NULL)
16478     {
16479       int stride_ok;
16480       struct type *prop_type = cu->addr_sized_int_type (false);
16481
16482       byte_stride_prop
16483         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16484       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop,
16485                                         prop_type);
16486       if (!stride_ok)
16487         {
16488           complaint (_("unable to read array DW_AT_byte_stride "
16489                        " - DIE at %s [in module %s]"),
16490                      sect_offset_str (die->sect_off),
16491                      objfile_name (cu->per_objfile->objfile));
16492           /* Ignore this attribute.  We will likely not be able to print
16493              arrays of this type correctly, but there is little we can do
16494              to help if we cannot read the attribute's value.  */
16495           byte_stride_prop = NULL;
16496         }
16497     }
16498
16499   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16500   if (attr != NULL)
16501     bit_stride = attr->constant_value (0);
16502
16503   /* Irix 6.2 native cc creates array types without children for
16504      arrays with unspecified length.  */
16505   if (die->child == NULL)
16506     {
16507       index_type = objfile_type (objfile)->builtin_int;
16508       range_type = create_static_range_type (NULL, index_type, 0, -1);
16509       type = create_array_type_with_stride (NULL, element_type, range_type,
16510                                             byte_stride_prop, bit_stride);
16511       return set_die_type (die, type, cu);
16512     }
16513
16514   std::vector<struct type *> range_types;
16515   child_die = die->child;
16516   while (child_die && child_die->tag)
16517     {
16518       if (child_die->tag == DW_TAG_subrange_type)
16519         {
16520           struct type *child_type = read_type_die (child_die, cu);
16521
16522           if (child_type != NULL)
16523             {
16524               /* The range type was succesfully read.  Save it for the
16525                  array type creation.  */
16526               range_types.push_back (child_type);
16527             }
16528         }
16529       child_die = child_die->sibling;
16530     }
16531
16532   if (range_types.empty ())
16533     {
16534       complaint (_("unable to find array range - DIE at %s [in module %s]"),
16535                  sect_offset_str (die->sect_off),
16536                  objfile_name (cu->per_objfile->objfile));
16537       return NULL;
16538     }
16539
16540   /* Dwarf2 dimensions are output from left to right, create the
16541      necessary array types in backwards order.  */
16542
16543   type = element_type;
16544
16545   if (read_array_order (die, cu) == DW_ORD_col_major)
16546     {
16547       int i = 0;
16548
16549       while (i < range_types.size ())
16550         {
16551           type = create_array_type_with_stride (NULL, type, range_types[i++],
16552                                                 byte_stride_prop, bit_stride);
16553           bit_stride = 0;
16554           byte_stride_prop = nullptr;
16555         }
16556     }
16557   else
16558     {
16559       size_t ndim = range_types.size ();
16560       while (ndim-- > 0)
16561         {
16562           type = create_array_type_with_stride (NULL, type, range_types[ndim],
16563                                                 byte_stride_prop, bit_stride);
16564           bit_stride = 0;
16565           byte_stride_prop = nullptr;
16566         }
16567     }
16568
16569   gdb_assert (type != element_type);
16570
16571   /* Understand Dwarf2 support for vector types (like they occur on
16572      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16573      array type.  This is not part of the Dwarf2/3 standard yet, but a
16574      custom vendor extension.  The main difference between a regular
16575      array and the vector variant is that vectors are passed by value
16576      to functions.  */
16577   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16578   if (attr != nullptr)
16579     make_vector_type (type);
16580
16581   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16582      implementation may choose to implement triple vectors using this
16583      attribute.  */
16584   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16585   if (attr != nullptr && attr->form_is_unsigned ())
16586     {
16587       if (attr->as_unsigned () >= TYPE_LENGTH (type))
16588         TYPE_LENGTH (type) = attr->as_unsigned ();
16589       else
16590         complaint (_("DW_AT_byte_size for array type smaller "
16591                      "than the total size of elements"));
16592     }
16593
16594   name = dwarf2_name (die, cu);
16595   if (name)
16596     type->set_name (name);
16597
16598   maybe_set_alignment (cu, die, type);
16599
16600   struct type *replacement_type = nullptr;
16601   if (cu->per_cu->lang == language_ada)
16602     {
16603       replacement_type = quirk_ada_thick_pointer (die, cu, type);
16604       if (replacement_type != nullptr)
16605         type = replacement_type;
16606     }
16607
16608   /* Install the type in the die.  */
16609   set_die_type (die, type, cu, replacement_type != nullptr);
16610
16611   /* set_die_type should be already done.  */
16612   set_descriptive_type (type, die, cu);
16613
16614   return type;
16615 }
16616
16617 static enum dwarf_array_dim_ordering
16618 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16619 {
16620   struct attribute *attr;
16621
16622   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16623
16624   if (attr != nullptr)
16625     {
16626       LONGEST val = attr->constant_value (-1);
16627       if (val == DW_ORD_row_major || val == DW_ORD_col_major)
16628         return (enum dwarf_array_dim_ordering) val;
16629     }
16630
16631   /* GNU F77 is a special case, as at 08/2004 array type info is the
16632      opposite order to the dwarf2 specification, but data is still
16633      laid out as per normal fortran.
16634
16635      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16636      version checking.  */
16637
16638   if (cu->per_cu->lang == language_fortran
16639       && cu->producer && strstr (cu->producer, "GNU F77"))
16640     {
16641       return DW_ORD_row_major;
16642     }
16643
16644   switch (cu->language_defn->array_ordering ())
16645     {
16646     case array_column_major:
16647       return DW_ORD_col_major;
16648     case array_row_major:
16649     default:
16650       return DW_ORD_row_major;
16651     };
16652 }
16653
16654 /* Extract all information from a DW_TAG_set_type DIE and put it in
16655    the DIE's type field.  */
16656
16657 static struct type *
16658 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16659 {
16660   struct type *domain_type, *set_type;
16661   struct attribute *attr;
16662
16663   domain_type = die_type (die, cu);
16664
16665   /* The die_type call above may have already set the type for this DIE.  */
16666   set_type = get_die_type (die, cu);
16667   if (set_type)
16668     return set_type;
16669
16670   set_type = create_set_type (NULL, domain_type);
16671
16672   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16673   if (attr != nullptr && attr->form_is_unsigned ())
16674     TYPE_LENGTH (set_type) = attr->as_unsigned ();
16675
16676   maybe_set_alignment (cu, die, set_type);
16677
16678   return set_die_type (die, set_type, cu);
16679 }
16680
16681 /* A helper for read_common_block that creates a locexpr baton.
16682    SYM is the symbol which we are marking as computed.
16683    COMMON_DIE is the DIE for the common block.
16684    COMMON_LOC is the location expression attribute for the common
16685    block itself.
16686    MEMBER_LOC is the location expression attribute for the particular
16687    member of the common block that we are processing.
16688    CU is the CU from which the above come.  */
16689
16690 static void
16691 mark_common_block_symbol_computed (struct symbol *sym,
16692                                    struct die_info *common_die,
16693                                    struct attribute *common_loc,
16694                                    struct attribute *member_loc,
16695                                    struct dwarf2_cu *cu)
16696 {
16697   dwarf2_per_objfile *per_objfile = cu->per_objfile;
16698   struct objfile *objfile = per_objfile->objfile;
16699   struct dwarf2_locexpr_baton *baton;
16700   gdb_byte *ptr;
16701   unsigned int cu_off;
16702   enum bfd_endian byte_order = gdbarch_byte_order (objfile->arch ());
16703   LONGEST offset = 0;
16704
16705   gdb_assert (common_loc && member_loc);
16706   gdb_assert (common_loc->form_is_block ());
16707   gdb_assert (member_loc->form_is_block ()
16708               || member_loc->form_is_constant ());
16709
16710   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16711   baton->per_objfile = per_objfile;
16712   baton->per_cu = cu->per_cu;
16713   gdb_assert (baton->per_cu);
16714
16715   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16716
16717   if (member_loc->form_is_constant ())
16718     {
16719       offset = member_loc->constant_value (0);
16720       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16721     }
16722   else
16723     baton->size += member_loc->as_block ()->size;
16724
16725   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16726   baton->data = ptr;
16727
16728   *ptr++ = DW_OP_call4;
16729   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16730   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16731   ptr += 4;
16732
16733   if (member_loc->form_is_constant ())
16734     {
16735       *ptr++ = DW_OP_addr;
16736       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16737       ptr += cu->header.addr_size;
16738     }
16739   else
16740     {
16741       /* We have to copy the data here, because DW_OP_call4 will only
16742          use a DW_AT_location attribute.  */
16743       struct dwarf_block *block = member_loc->as_block ();
16744       memcpy (ptr, block->data, block->size);
16745       ptr += block->size;
16746     }
16747
16748   *ptr++ = DW_OP_plus;
16749   gdb_assert (ptr - baton->data == baton->size);
16750
16751   SYMBOL_LOCATION_BATON (sym) = baton;
16752   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16753 }
16754
16755 /* Create appropriate locally-scoped variables for all the
16756    DW_TAG_common_block entries.  Also create a struct common_block
16757    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16758    is used to separate the common blocks name namespace from regular
16759    variable names.  */
16760
16761 static void
16762 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16763 {
16764   struct attribute *attr;
16765
16766   attr = dwarf2_attr (die, DW_AT_location, cu);
16767   if (attr != nullptr)
16768     {
16769       /* Support the .debug_loc offsets.  */
16770       if (attr->form_is_block ())
16771         {
16772           /* Ok.  */
16773         }
16774       else if (attr->form_is_section_offset ())
16775         {
16776           dwarf2_complex_location_expr_complaint ();
16777           attr = NULL;
16778         }
16779       else
16780         {
16781           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16782                                                  "common block member");
16783           attr = NULL;
16784         }
16785     }
16786
16787   if (die->child != NULL)
16788     {
16789       struct objfile *objfile = cu->per_objfile->objfile;
16790       struct die_info *child_die;
16791       size_t n_entries = 0, size;
16792       struct common_block *common_block;
16793       struct symbol *sym;
16794
16795       for (child_die = die->child;
16796            child_die && child_die->tag;
16797            child_die = child_die->sibling)
16798         ++n_entries;
16799
16800       size = (sizeof (struct common_block)
16801               + (n_entries - 1) * sizeof (struct symbol *));
16802       common_block
16803         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16804                                                  size);
16805       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16806       common_block->n_entries = 0;
16807
16808       for (child_die = die->child;
16809            child_die && child_die->tag;
16810            child_die = child_die->sibling)
16811         {
16812           /* Create the symbol in the DW_TAG_common_block block in the current
16813              symbol scope.  */
16814           sym = new_symbol (child_die, NULL, cu);
16815           if (sym != NULL)
16816             {
16817               struct attribute *member_loc;
16818
16819               common_block->contents[common_block->n_entries++] = sym;
16820
16821               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16822                                         cu);
16823               if (member_loc)
16824                 {
16825                   /* GDB has handled this for a long time, but it is
16826                      not specified by DWARF.  It seems to have been
16827                      emitted by gfortran at least as recently as:
16828                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16829                   complaint (_("Variable in common block has "
16830                                "DW_AT_data_member_location "
16831                                "- DIE at %s [in module %s]"),
16832                                sect_offset_str (child_die->sect_off),
16833                              objfile_name (objfile));
16834
16835                   if (member_loc->form_is_section_offset ())
16836                     dwarf2_complex_location_expr_complaint ();
16837                   else if (member_loc->form_is_constant ()
16838                            || member_loc->form_is_block ())
16839                     {
16840                       if (attr != nullptr)
16841                         mark_common_block_symbol_computed (sym, die, attr,
16842                                                            member_loc, cu);
16843                     }
16844                   else
16845                     dwarf2_complex_location_expr_complaint ();
16846                 }
16847             }
16848         }
16849
16850       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16851       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16852     }
16853 }
16854
16855 /* Create a type for a C++ namespace.  */
16856
16857 static struct type *
16858 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16859 {
16860   struct objfile *objfile = cu->per_objfile->objfile;
16861   const char *previous_prefix, *name;
16862   int is_anonymous;
16863   struct type *type;
16864
16865   /* For extensions, reuse the type of the original namespace.  */
16866   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16867     {
16868       struct die_info *ext_die;
16869       struct dwarf2_cu *ext_cu = cu;
16870
16871       ext_die = dwarf2_extension (die, &ext_cu);
16872       type = read_type_die (ext_die, ext_cu);
16873
16874       /* EXT_CU may not be the same as CU.
16875          Ensure TYPE is recorded with CU in die_type_hash.  */
16876       return set_die_type (die, type, cu);
16877     }
16878
16879   name = namespace_name (die, &is_anonymous, cu);
16880
16881   /* Now build the name of the current namespace.  */
16882
16883   previous_prefix = determine_prefix (die, cu);
16884   if (previous_prefix[0] != '\0')
16885     name = typename_concat (&objfile->objfile_obstack,
16886                             previous_prefix, name, 0, cu);
16887
16888   /* Create the type.  */
16889   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16890
16891   return set_die_type (die, type, cu);
16892 }
16893
16894 /* Read a namespace scope.  */
16895
16896 static void
16897 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16898 {
16899   struct objfile *objfile = cu->per_objfile->objfile;
16900   int is_anonymous;
16901
16902   /* Add a symbol associated to this if we haven't seen the namespace
16903      before.  Also, add a using directive if it's an anonymous
16904      namespace.  */
16905
16906   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16907     {
16908       struct type *type;
16909
16910       type = read_type_die (die, cu);
16911       new_symbol (die, type, cu);
16912
16913       namespace_name (die, &is_anonymous, cu);
16914       if (is_anonymous)
16915         {
16916           const char *previous_prefix = determine_prefix (die, cu);
16917
16918           std::vector<const char *> excludes;
16919           add_using_directive (using_directives (cu),
16920                                previous_prefix, type->name (), NULL,
16921                                NULL, excludes, 0, &objfile->objfile_obstack);
16922         }
16923     }
16924
16925   if (die->child != NULL)
16926     {
16927       struct die_info *child_die = die->child;
16928
16929       while (child_die && child_die->tag)
16930         {
16931           process_die (child_die, cu);
16932           child_die = child_die->sibling;
16933         }
16934     }
16935 }
16936
16937 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16938    imported module.  Still we need that type as local Fortran "use ... only"
16939    declaration imports depend on the created type in determine_prefix.  */
16940
16941 static struct type *
16942 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16943 {
16944   struct objfile *objfile = cu->per_objfile->objfile;
16945   const char *module_name;
16946   struct type *type;
16947
16948   module_name = dwarf2_name (die, cu);
16949   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16950
16951   return set_die_type (die, type, cu);
16952 }
16953
16954 /* Read a Fortran module.  */
16955
16956 static void
16957 read_module (struct die_info *die, struct dwarf2_cu *cu)
16958 {
16959   struct die_info *child_die = die->child;
16960   struct type *type;
16961
16962   type = read_type_die (die, cu);
16963   new_symbol (die, type, cu);
16964
16965   while (child_die && child_die->tag)
16966     {
16967       process_die (child_die, cu);
16968       child_die = child_die->sibling;
16969     }
16970 }
16971
16972 /* Return the name of the namespace represented by DIE.  Set
16973    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16974    namespace.  */
16975
16976 static const char *
16977 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16978 {
16979   struct die_info *current_die;
16980   const char *name = NULL;
16981
16982   /* Loop through the extensions until we find a name.  */
16983
16984   for (current_die = die;
16985        current_die != NULL;
16986        current_die = dwarf2_extension (die, &cu))
16987     {
16988       /* We don't use dwarf2_name here so that we can detect the absence
16989          of a name -> anonymous namespace.  */
16990       name = dwarf2_string_attr (die, DW_AT_name, cu);
16991
16992       if (name != NULL)
16993         break;
16994     }
16995
16996   /* Is it an anonymous namespace?  */
16997
16998   *is_anonymous = (name == NULL);
16999   if (*is_anonymous)
17000     name = CP_ANONYMOUS_NAMESPACE_STR;
17001
17002   return name;
17003 }
17004
17005 /* Extract all information from a DW_TAG_pointer_type DIE and add to
17006    the user defined type vector.  */
17007
17008 static struct type *
17009 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
17010 {
17011   struct gdbarch *gdbarch = cu->per_objfile->objfile->arch ();
17012   struct comp_unit_head *cu_header = &cu->header;
17013   struct type *type;
17014   struct attribute *attr_byte_size;
17015   struct attribute *attr_address_class;
17016   int byte_size, addr_class;
17017   struct type *target_type;
17018
17019   target_type = die_type (die, cu);
17020
17021   /* The die_type call above may have already set the type for this DIE.  */
17022   type = get_die_type (die, cu);
17023   if (type)
17024     return type;
17025
17026   type = lookup_pointer_type (target_type);
17027
17028   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17029   if (attr_byte_size)
17030     byte_size = attr_byte_size->constant_value (cu_header->addr_size);
17031   else
17032     byte_size = cu_header->addr_size;
17033
17034   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17035   if (attr_address_class)
17036     addr_class = attr_address_class->constant_value (DW_ADDR_none);
17037   else
17038     addr_class = DW_ADDR_none;
17039
17040   ULONGEST alignment = get_alignment (cu, die);
17041
17042   /* If the pointer size, alignment, or address class is different
17043      than the default, create a type variant marked as such and set
17044      the length accordingly.  */
17045   if (TYPE_LENGTH (type) != byte_size
17046       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
17047           && alignment != TYPE_RAW_ALIGN (type))
17048       || addr_class != DW_ADDR_none)
17049     {
17050       if (gdbarch_address_class_type_flags_p (gdbarch))
17051         {
17052           type_instance_flags type_flags
17053             = gdbarch_address_class_type_flags (gdbarch, byte_size,
17054                                                 addr_class);
17055           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17056                       == 0);
17057           type = make_type_with_address_space (type, type_flags);
17058         }
17059       else if (TYPE_LENGTH (type) != byte_size)
17060         {
17061           complaint (_("invalid pointer size %d"), byte_size);
17062         }
17063       else if (TYPE_RAW_ALIGN (type) != alignment)
17064         {
17065           complaint (_("Invalid DW_AT_alignment"
17066                        " - DIE at %s [in module %s]"),
17067                      sect_offset_str (die->sect_off),
17068                      objfile_name (cu->per_objfile->objfile));
17069         }
17070       else
17071         {
17072           /* Should we also complain about unhandled address classes?  */
17073         }
17074     }
17075
17076   TYPE_LENGTH (type) = byte_size;
17077   set_type_align (type, alignment);
17078   return set_die_type (die, type, cu);
17079 }
17080
17081 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17082    the user defined type vector.  */
17083
17084 static struct type *
17085 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17086 {
17087   struct type *type;
17088   struct type *to_type;
17089   struct type *domain;
17090
17091   to_type = die_type (die, cu);
17092   domain = die_containing_type (die, cu);
17093
17094   /* The calls above may have already set the type for this DIE.  */
17095   type = get_die_type (die, cu);
17096   if (type)
17097     return type;
17098
17099   if (check_typedef (to_type)->code () == TYPE_CODE_METHOD)
17100     type = lookup_methodptr_type (to_type);
17101   else if (check_typedef (to_type)->code () == TYPE_CODE_FUNC)
17102     {
17103       struct type *new_type = alloc_type (cu->per_objfile->objfile);
17104
17105       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17106                             to_type->fields (), to_type->num_fields (),
17107                             to_type->has_varargs ());
17108       type = lookup_methodptr_type (new_type);
17109     }
17110   else
17111     type = lookup_memberptr_type (to_type, domain);
17112
17113   return set_die_type (die, type, cu);
17114 }
17115
17116 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17117    the user defined type vector.  */
17118
17119 static struct type *
17120 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17121                           enum type_code refcode)
17122 {
17123   struct comp_unit_head *cu_header = &cu->header;
17124   struct type *type, *target_type;
17125   struct attribute *attr;
17126
17127   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17128
17129   target_type = die_type (die, cu);
17130
17131   /* The die_type call above may have already set the type for this DIE.  */
17132   type = get_die_type (die, cu);
17133   if (type)
17134     return type;
17135
17136   type = lookup_reference_type (target_type, refcode);
17137   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17138   if (attr != nullptr)
17139     {
17140       TYPE_LENGTH (type) = attr->constant_value (cu_header->addr_size);
17141     }
17142   else
17143     {
17144       TYPE_LENGTH (type) = cu_header->addr_size;
17145     }
17146   maybe_set_alignment (cu, die, type);
17147   return set_die_type (die, type, cu);
17148 }
17149
17150 /* Add the given cv-qualifiers to the element type of the array.  GCC
17151    outputs DWARF type qualifiers that apply to an array, not the
17152    element type.  But GDB relies on the array element type to carry
17153    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17154    specification.  */
17155
17156 static struct type *
17157 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17158                    struct type *base_type, int cnst, int voltl)
17159 {
17160   struct type *el_type, *inner_array;
17161
17162   base_type = copy_type (base_type);
17163   inner_array = base_type;
17164
17165   while (TYPE_TARGET_TYPE (inner_array)->code () == TYPE_CODE_ARRAY)
17166     {
17167       TYPE_TARGET_TYPE (inner_array) =
17168         copy_type (TYPE_TARGET_TYPE (inner_array));
17169       inner_array = TYPE_TARGET_TYPE (inner_array);
17170     }
17171
17172   el_type = TYPE_TARGET_TYPE (inner_array);
17173   cnst |= TYPE_CONST (el_type);
17174   voltl |= TYPE_VOLATILE (el_type);
17175   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17176
17177   return set_die_type (die, base_type, cu);
17178 }
17179
17180 static struct type *
17181 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17182 {
17183   struct type *base_type, *cv_type;
17184
17185   base_type = die_type (die, cu);
17186
17187   /* The die_type call above may have already set the type for this DIE.  */
17188   cv_type = get_die_type (die, cu);
17189   if (cv_type)
17190     return cv_type;
17191
17192   /* In case the const qualifier is applied to an array type, the element type
17193      is so qualified, not the array type (section 6.7.3 of C99).  */
17194   if (base_type->code () == TYPE_CODE_ARRAY)
17195     return add_array_cv_type (die, cu, base_type, 1, 0);
17196
17197   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17198   return set_die_type (die, cv_type, cu);
17199 }
17200
17201 static struct type *
17202 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17203 {
17204   struct type *base_type, *cv_type;
17205
17206   base_type = die_type (die, cu);
17207
17208   /* The die_type call above may have already set the type for this DIE.  */
17209   cv_type = get_die_type (die, cu);
17210   if (cv_type)
17211     return cv_type;
17212
17213   /* In case the volatile qualifier is applied to an array type, the
17214      element type is so qualified, not the array type (section 6.7.3
17215      of C99).  */
17216   if (base_type->code () == TYPE_CODE_ARRAY)
17217     return add_array_cv_type (die, cu, base_type, 0, 1);
17218
17219   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17220   return set_die_type (die, cv_type, cu);
17221 }
17222
17223 /* Handle DW_TAG_restrict_type.  */
17224
17225 static struct type *
17226 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17227 {
17228   struct type *base_type, *cv_type;
17229
17230   base_type = die_type (die, cu);
17231
17232   /* The die_type call above may have already set the type for this DIE.  */
17233   cv_type = get_die_type (die, cu);
17234   if (cv_type)
17235     return cv_type;
17236
17237   cv_type = make_restrict_type (base_type);
17238   return set_die_type (die, cv_type, cu);
17239 }
17240
17241 /* Handle DW_TAG_atomic_type.  */
17242
17243 static struct type *
17244 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17245 {
17246   struct type *base_type, *cv_type;
17247
17248   base_type = die_type (die, cu);
17249
17250   /* The die_type call above may have already set the type for this DIE.  */
17251   cv_type = get_die_type (die, cu);
17252   if (cv_type)
17253     return cv_type;
17254
17255   cv_type = make_atomic_type (base_type);
17256   return set_die_type (die, cv_type, cu);
17257 }
17258
17259 /* Extract all information from a DW_TAG_string_type DIE and add to
17260    the user defined type vector.  It isn't really a user defined type,
17261    but it behaves like one, with other DIE's using an AT_user_def_type
17262    attribute to reference it.  */
17263
17264 static struct type *
17265 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17266 {
17267   struct objfile *objfile = cu->per_objfile->objfile;
17268   struct gdbarch *gdbarch = objfile->arch ();
17269   struct type *type, *range_type, *index_type, *char_type;
17270   struct attribute *attr;
17271   struct dynamic_prop prop;
17272   bool length_is_constant = true;
17273   LONGEST length;
17274
17275   /* There are a couple of places where bit sizes might be made use of
17276      when parsing a DW_TAG_string_type, however, no producer that we know
17277      of make use of these.  Handling bit sizes that are a multiple of the
17278      byte size is easy enough, but what about other bit sizes?  Lets deal
17279      with that problem when we have to.  Warn about these attributes being
17280      unsupported, then parse the type and ignore them like we always
17281      have.  */
17282   if (dwarf2_attr (die, DW_AT_bit_size, cu) != nullptr
17283       || dwarf2_attr (die, DW_AT_string_length_bit_size, cu) != nullptr)
17284     {
17285       static bool warning_printed = false;
17286       if (!warning_printed)
17287         {
17288           warning (_("DW_AT_bit_size and DW_AT_string_length_bit_size not "
17289                      "currently supported on DW_TAG_string_type."));
17290           warning_printed = true;
17291         }
17292     }
17293
17294   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17295   if (attr != nullptr && !attr->form_is_constant ())
17296     {
17297       /* The string length describes the location at which the length of
17298          the string can be found.  The size of the length field can be
17299          specified with one of the attributes below.  */
17300       struct type *prop_type;
17301       struct attribute *len
17302         = dwarf2_attr (die, DW_AT_string_length_byte_size, cu);
17303       if (len == nullptr)
17304         len = dwarf2_attr (die, DW_AT_byte_size, cu);
17305       if (len != nullptr && len->form_is_constant ())
17306         {
17307           /* Pass 0 as the default as we know this attribute is constant
17308              and the default value will not be returned.  */
17309           LONGEST sz = len->constant_value (0);
17310           prop_type = cu->per_objfile->int_type (sz, true);
17311         }
17312       else
17313         {
17314           /* If the size is not specified then we assume it is the size of
17315              an address on this target.  */
17316           prop_type = cu->addr_sized_int_type (true);
17317         }
17318
17319       /* Convert the attribute into a dynamic property.  */
17320       if (!attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
17321         length = 1;
17322       else
17323         length_is_constant = false;
17324     }
17325   else if (attr != nullptr)
17326     {
17327       /* This DW_AT_string_length just contains the length with no
17328          indirection.  There's no need to create a dynamic property in this
17329          case.  Pass 0 for the default value as we know it will not be
17330          returned in this case.  */
17331       length = attr->constant_value (0);
17332     }
17333   else if ((attr = dwarf2_attr (die, DW_AT_byte_size, cu)) != nullptr)
17334     {
17335       /* We don't currently support non-constant byte sizes for strings.  */
17336       length = attr->constant_value (1);
17337     }
17338   else
17339     {
17340       /* Use 1 as a fallback length if we have nothing else.  */
17341       length = 1;
17342     }
17343
17344   index_type = objfile_type (objfile)->builtin_int;
17345   if (length_is_constant)
17346     range_type = create_static_range_type (NULL, index_type, 1, length);
17347   else
17348     {
17349       struct dynamic_prop low_bound;
17350
17351       low_bound.set_const_val (1);
17352       range_type = create_range_type (NULL, index_type, &low_bound, &prop, 0);
17353     }
17354   char_type = language_string_char_type (cu->language_defn, gdbarch);
17355   type = create_string_type (NULL, char_type, range_type);
17356
17357   return set_die_type (die, type, cu);
17358 }
17359
17360 /* Assuming that DIE corresponds to a function, returns nonzero
17361    if the function is prototyped.  */
17362
17363 static int
17364 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17365 {
17366   struct attribute *attr;
17367
17368   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17369   if (attr && attr->as_boolean ())
17370     return 1;
17371
17372   /* The DWARF standard implies that the DW_AT_prototyped attribute
17373      is only meaningful for C, but the concept also extends to other
17374      languages that allow unprototyped functions (Eg: Objective C).
17375      For all other languages, assume that functions are always
17376      prototyped.  */
17377   if (cu->per_cu->lang != language_c
17378       && cu->per_cu->lang != language_objc
17379       && cu->per_cu->lang != language_opencl)
17380     return 1;
17381
17382   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17383      prototyped and unprototyped functions; default to prototyped,
17384      since that is more common in modern code (and RealView warns
17385      about unprototyped functions).  */
17386   if (producer_is_realview (cu->producer))
17387     return 1;
17388
17389   return 0;
17390 }
17391
17392 /* Handle DIES due to C code like:
17393
17394    struct foo
17395    {
17396    int (*funcp)(int a, long l);
17397    int b;
17398    };
17399
17400    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17401
17402 static struct type *
17403 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17404 {
17405   struct objfile *objfile = cu->per_objfile->objfile;
17406   struct type *type;            /* Type that this function returns.  */
17407   struct type *ftype;           /* Function that returns above type.  */
17408   struct attribute *attr;
17409
17410   type = die_type (die, cu);
17411
17412   /* The die_type call above may have already set the type for this DIE.  */
17413   ftype = get_die_type (die, cu);
17414   if (ftype)
17415     return ftype;
17416
17417   ftype = lookup_function_type (type);
17418
17419   if (prototyped_function_p (die, cu))
17420     ftype->set_is_prototyped (true);
17421
17422   /* Store the calling convention in the type if it's available in
17423      the subroutine die.  Otherwise set the calling convention to
17424      the default value DW_CC_normal.  */
17425   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17426   if (attr != nullptr
17427       && is_valid_DW_AT_calling_convention_for_subroutine (attr->constant_value (0)))
17428     TYPE_CALLING_CONVENTION (ftype)
17429       = (enum dwarf_calling_convention) attr->constant_value (0);
17430   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17431     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17432   else
17433     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17434
17435   /* Record whether the function returns normally to its caller or not
17436      if the DWARF producer set that information.  */
17437   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17438   if (attr && attr->as_boolean ())
17439     TYPE_NO_RETURN (ftype) = 1;
17440
17441   /* We need to add the subroutine type to the die immediately so
17442      we don't infinitely recurse when dealing with parameters
17443      declared as the same subroutine type.  */
17444   set_die_type (die, ftype, cu);
17445
17446   if (die->child != NULL)
17447     {
17448       struct type *void_type = objfile_type (objfile)->builtin_void;
17449       struct die_info *child_die;
17450       int nparams, iparams;
17451
17452       /* Count the number of parameters.
17453          FIXME: GDB currently ignores vararg functions, but knows about
17454          vararg member functions.  */
17455       nparams = 0;
17456       child_die = die->child;
17457       while (child_die && child_die->tag)
17458         {
17459           if (child_die->tag == DW_TAG_formal_parameter)
17460             nparams++;
17461           else if (child_die->tag == DW_TAG_unspecified_parameters)
17462             ftype->set_has_varargs (true);
17463
17464           child_die = child_die->sibling;
17465         }
17466
17467       /* Allocate storage for parameters and fill them in.  */
17468       ftype->set_num_fields (nparams);
17469       ftype->set_fields
17470         ((struct field *) TYPE_ZALLOC (ftype, nparams * sizeof (struct field)));
17471
17472       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17473          even if we error out during the parameters reading below.  */
17474       for (iparams = 0; iparams < nparams; iparams++)
17475         ftype->field (iparams).set_type (void_type);
17476
17477       iparams = 0;
17478       child_die = die->child;
17479       while (child_die && child_die->tag)
17480         {
17481           if (child_die->tag == DW_TAG_formal_parameter)
17482             {
17483               struct type *arg_type;
17484
17485               /* DWARF version 2 has no clean way to discern C++
17486                  static and non-static member functions.  G++ helps
17487                  GDB by marking the first parameter for non-static
17488                  member functions (which is the this pointer) as
17489                  artificial.  We pass this information to
17490                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17491
17492                  DWARF version 3 added DW_AT_object_pointer, which GCC
17493                  4.5 does not yet generate.  */
17494               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17495               if (attr != nullptr)
17496                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = attr->as_boolean ();
17497               else
17498                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17499               arg_type = die_type (child_die, cu);
17500
17501               /* RealView does not mark THIS as const, which the testsuite
17502                  expects.  GCC marks THIS as const in method definitions,
17503                  but not in the class specifications (GCC PR 43053).  */
17504               if (cu->per_cu->lang == language_cplus
17505                   && !TYPE_CONST (arg_type)
17506                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17507                 {
17508                   int is_this = 0;
17509                   struct dwarf2_cu *arg_cu = cu;
17510                   const char *name = dwarf2_name (child_die, cu);
17511
17512                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17513                   if (attr != nullptr)
17514                     {
17515                       /* If the compiler emits this, use it.  */
17516                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17517                         is_this = 1;
17518                     }
17519                   else if (name && strcmp (name, "this") == 0)
17520                     /* Function definitions will have the argument names.  */
17521                     is_this = 1;
17522                   else if (name == NULL && iparams == 0)
17523                     /* Declarations may not have the names, so like
17524                        elsewhere in GDB, assume an artificial first
17525                        argument is "this".  */
17526                     is_this = 1;
17527
17528                   if (is_this)
17529                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17530                                              arg_type, 0);
17531                 }
17532
17533               ftype->field (iparams).set_type (arg_type);
17534               iparams++;
17535             }
17536           child_die = child_die->sibling;
17537         }
17538     }
17539
17540   return ftype;
17541 }
17542
17543 static struct type *
17544 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17545 {
17546   struct objfile *objfile = cu->per_objfile->objfile;
17547   const char *name = NULL;
17548   struct type *this_type, *target_type;
17549
17550   name = dwarf2_full_name (NULL, die, cu);
17551   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17552   this_type->set_target_is_stub (true);
17553   set_die_type (die, this_type, cu);
17554   target_type = die_type (die, cu);
17555   if (target_type != this_type)
17556     TYPE_TARGET_TYPE (this_type) = target_type;
17557   else
17558     {
17559       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17560          spec and cause infinite loops in GDB.  */
17561       complaint (_("Self-referential DW_TAG_typedef "
17562                    "- DIE at %s [in module %s]"),
17563                  sect_offset_str (die->sect_off), objfile_name (objfile));
17564       TYPE_TARGET_TYPE (this_type) = NULL;
17565     }
17566   if (name == NULL)
17567     {
17568       /* Gcc-7 and before supports -feliminate-dwarf2-dups, which generates
17569          anonymous typedefs, which is, strictly speaking, invalid DWARF.
17570          Handle these by just returning the target type, rather than
17571          constructing an anonymous typedef type and trying to handle this
17572          elsewhere.  */
17573       set_die_type (die, target_type, cu);
17574       return target_type;
17575     }
17576   return this_type;
17577 }
17578
17579 /* Helper for get_dwarf2_rational_constant that computes the value of
17580    a given gmp_mpz given an attribute.  */
17581
17582 static void
17583 get_mpz (struct dwarf2_cu *cu, gdb_mpz *value, struct attribute *attr)
17584 {
17585   /* GCC will sometimes emit a 16-byte constant value as a DWARF
17586      location expression that pushes an implicit value.  */
17587   if (attr->form == DW_FORM_exprloc)
17588     {
17589       dwarf_block *blk = attr->as_block ();
17590       if (blk->size > 0 && blk->data[0] == DW_OP_implicit_value)
17591         {
17592           uint64_t len;
17593           const gdb_byte *ptr = safe_read_uleb128 (blk->data + 1,
17594                                                    blk->data + blk->size,
17595                                                    &len);
17596           if (ptr - blk->data + len <= blk->size)
17597             {
17598               mpz_import (value->val, len,
17599                           bfd_big_endian (cu->per_objfile->objfile->obfd) ? 1 : -1,
17600                           1, 0, 0, ptr);
17601               return;
17602             }
17603         }
17604
17605       /* On failure set it to 1.  */
17606       *value = gdb_mpz (1);
17607     }
17608   else if (attr->form_is_block ())
17609     {
17610       dwarf_block *blk = attr->as_block ();
17611       mpz_import (value->val, blk->size,
17612                   bfd_big_endian (cu->per_objfile->objfile->obfd) ? 1 : -1,
17613                   1, 0, 0, blk->data);
17614     }
17615   else
17616     *value = gdb_mpz (attr->constant_value (1));
17617 }
17618
17619 /* Assuming DIE is a rational DW_TAG_constant, read the DIE's
17620    numerator and denominator into NUMERATOR and DENOMINATOR (resp).
17621
17622    If the numerator and/or numerator attribute is missing,
17623    a complaint is filed, and NUMERATOR and DENOMINATOR are left
17624    untouched.  */
17625
17626 static void
17627 get_dwarf2_rational_constant (struct die_info *die, struct dwarf2_cu *cu,
17628                               gdb_mpz *numerator, gdb_mpz *denominator)
17629 {
17630   struct attribute *num_attr, *denom_attr;
17631
17632   num_attr = dwarf2_attr (die, DW_AT_GNU_numerator, cu);
17633   if (num_attr == nullptr)
17634     complaint (_("DW_AT_GNU_numerator missing in %s DIE at %s"),
17635                dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
17636
17637   denom_attr = dwarf2_attr (die, DW_AT_GNU_denominator, cu);
17638   if (denom_attr == nullptr)
17639     complaint (_("DW_AT_GNU_denominator missing in %s DIE at %s"),
17640                dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
17641
17642   if (num_attr == nullptr || denom_attr == nullptr)
17643     return;
17644
17645   get_mpz (cu, numerator, num_attr);
17646   get_mpz (cu, denominator, denom_attr);
17647 }
17648
17649 /* Same as get_dwarf2_rational_constant, but extracting an unsigned
17650    rational constant, rather than a signed one.
17651
17652    If the rational constant has a negative value, a complaint
17653    is filed, and NUMERATOR and DENOMINATOR are left untouched.  */
17654
17655 static void
17656 get_dwarf2_unsigned_rational_constant (struct die_info *die,
17657                                        struct dwarf2_cu *cu,
17658                                        gdb_mpz *numerator,
17659                                        gdb_mpz *denominator)
17660 {
17661   gdb_mpz num (1);
17662   gdb_mpz denom (1);
17663
17664   get_dwarf2_rational_constant (die, cu, &num, &denom);
17665   if (mpz_sgn (num.val) == -1 && mpz_sgn (denom.val) == -1)
17666     {
17667       mpz_neg (num.val, num.val);
17668       mpz_neg (denom.val, denom.val);
17669     }
17670   else if (mpz_sgn (num.val) == -1)
17671     {
17672       complaint (_("unexpected negative value for DW_AT_GNU_numerator"
17673                    " in DIE at %s"),
17674                  sect_offset_str (die->sect_off));
17675       return;
17676     }
17677   else if (mpz_sgn (denom.val) == -1)
17678     {
17679       complaint (_("unexpected negative value for DW_AT_GNU_denominator"
17680                    " in DIE at %s"),
17681                  sect_offset_str (die->sect_off));
17682       return;
17683     }
17684
17685   *numerator = std::move (num);
17686   *denominator = std::move (denom);
17687 }
17688
17689 /* Assuming that ENCODING is a string whose contents starting at the
17690    K'th character is "_nn" where "nn" is a decimal number, scan that
17691    number and set RESULT to the value. K is updated to point to the
17692    character immediately following the number.
17693
17694    If the string does not conform to the format described above, false
17695    is returned, and K may or may not be changed.  */
17696
17697 static bool
17698 ada_get_gnat_encoded_number (const char *encoding, int &k, gdb_mpz *result)
17699 {
17700   /* The next character should be an underscore ('_') followed
17701      by a digit.  */
17702   if (encoding[k] != '_' || !isdigit (encoding[k + 1]))
17703     return false;
17704
17705   /* Skip the underscore.  */
17706   k++;
17707   int start = k;
17708
17709   /* Determine the number of digits for our number.  */
17710   while (isdigit (encoding[k]))
17711     k++;
17712   if (k == start)
17713     return false;
17714
17715   std::string copy (&encoding[start], k - start);
17716   if (mpz_set_str (result->val, copy.c_str (), 10) == -1)
17717     return false;
17718
17719   return true;
17720 }
17721
17722 /* Scan two numbers from ENCODING at OFFSET, assuming the string is of
17723    the form _NN_DD, where NN and DD are decimal numbers.  Set NUM and
17724    DENOM, update OFFSET, and return true on success.  Return false on
17725    failure.  */
17726
17727 static bool
17728 ada_get_gnat_encoded_ratio (const char *encoding, int &offset,
17729                             gdb_mpz *num, gdb_mpz *denom)
17730 {
17731   if (!ada_get_gnat_encoded_number (encoding, offset, num))
17732     return false;
17733   return ada_get_gnat_encoded_number (encoding, offset, denom);
17734 }
17735
17736 /* Assuming DIE corresponds to a fixed point type, finish the creation
17737    of the corresponding TYPE by setting its type-specific data.  CU is
17738    the DIE's CU.  SUFFIX is the "XF" type name suffix coming from GNAT
17739    encodings.  It is nullptr if the GNAT encoding should be
17740    ignored.  */
17741
17742 static void
17743 finish_fixed_point_type (struct type *type, const char *suffix,
17744                          struct die_info *die, struct dwarf2_cu *cu)
17745 {
17746   gdb_assert (type->code () == TYPE_CODE_FIXED_POINT
17747               && TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_FIXED_POINT);
17748
17749   /* If GNAT encodings are preferred, don't examine the
17750      attributes.  */
17751   struct attribute *attr = nullptr;
17752   if (suffix == nullptr)
17753     {
17754       attr = dwarf2_attr (die, DW_AT_binary_scale, cu);
17755       if (attr == nullptr)
17756         attr = dwarf2_attr (die, DW_AT_decimal_scale, cu);
17757       if (attr == nullptr)
17758         attr = dwarf2_attr (die, DW_AT_small, cu);
17759     }
17760
17761   /* Numerator and denominator of our fixed-point type's scaling factor.
17762      The default is a scaling factor of 1, which we use as a fallback
17763      when we are not able to decode it (problem with the debugging info,
17764      unsupported forms, bug in GDB, etc...).  Using that as the default
17765      allows us to at least print the unscaled value, which might still
17766      be useful to a user.  */
17767   gdb_mpz scale_num (1);
17768   gdb_mpz scale_denom (1);
17769
17770   if (attr == nullptr)
17771     {
17772       int offset = 0;
17773       if (suffix != nullptr
17774           && ada_get_gnat_encoded_ratio (suffix, offset, &scale_num,
17775                                          &scale_denom)
17776           /* The number might be encoded as _nn_dd_nn_dd, where the
17777              second ratio is the 'small value.  In this situation, we
17778              want the second value.  */
17779           && (suffix[offset] != '_'
17780               || ada_get_gnat_encoded_ratio (suffix, offset, &scale_num,
17781                                              &scale_denom)))
17782         {
17783           /* Found it.  */
17784         }
17785       else
17786         {
17787           /* Scaling factor not found.  Assume a scaling factor of 1,
17788              and hope for the best.  At least the user will be able to
17789              see the encoded value.  */
17790           scale_num = 1;
17791           scale_denom = 1;
17792           complaint (_("no scale found for fixed-point type (DIE at %s)"),
17793                      sect_offset_str (die->sect_off));
17794         }
17795     }
17796   else if (attr->name == DW_AT_binary_scale)
17797     {
17798       LONGEST scale_exp = attr->constant_value (0);
17799       gdb_mpz *num_or_denom = scale_exp > 0 ? &scale_num : &scale_denom;
17800
17801       mpz_mul_2exp (num_or_denom->val, num_or_denom->val, std::abs (scale_exp));
17802     }
17803   else if (attr->name == DW_AT_decimal_scale)
17804     {
17805       LONGEST scale_exp = attr->constant_value (0);
17806       gdb_mpz *num_or_denom = scale_exp > 0 ? &scale_num : &scale_denom;
17807
17808       mpz_ui_pow_ui (num_or_denom->val, 10, std::abs (scale_exp));
17809     }
17810   else if (attr->name == DW_AT_small)
17811     {
17812       struct die_info *scale_die;
17813       struct dwarf2_cu *scale_cu = cu;
17814
17815       scale_die = follow_die_ref (die, attr, &scale_cu);
17816       if (scale_die->tag == DW_TAG_constant)
17817         get_dwarf2_unsigned_rational_constant (scale_die, scale_cu,
17818                                                &scale_num, &scale_denom);
17819       else
17820         complaint (_("%s DIE not supported as target of DW_AT_small attribute"
17821                      " (DIE at %s)"),
17822                    dwarf_tag_name (die->tag), sect_offset_str (die->sect_off));
17823     }
17824   else
17825     {
17826       complaint (_("unsupported scale attribute %s for fixed-point type"
17827                    " (DIE at %s)"),
17828                  dwarf_attr_name (attr->name),
17829                  sect_offset_str (die->sect_off));
17830     }
17831
17832   gdb_mpq &scaling_factor = type->fixed_point_info ().scaling_factor;
17833   mpz_set (mpq_numref (scaling_factor.val), scale_num.val);
17834   mpz_set (mpq_denref (scaling_factor.val), scale_denom.val);
17835   mpq_canonicalize (scaling_factor.val);
17836 }
17837
17838 /* The gnat-encoding suffix for fixed point.  */
17839
17840 #define GNAT_FIXED_POINT_SUFFIX "___XF_"
17841
17842 /* If NAME encodes an Ada fixed-point type, return a pointer to the
17843    "XF" suffix of the name.  The text after this is what encodes the
17844    'small and 'delta information.  Otherwise, return nullptr.  */
17845
17846 static const char *
17847 gnat_encoded_fixed_point_type_info (const char *name)
17848 {
17849   return strstr (name, GNAT_FIXED_POINT_SUFFIX);
17850 }
17851
17852 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17853    (which may be different from NAME) to the architecture back-end to allow
17854    it to guess the correct format if necessary.  */
17855
17856 static struct type *
17857 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17858                         const char *name_hint, enum bfd_endian byte_order)
17859 {
17860   struct gdbarch *gdbarch = objfile->arch ();
17861   const struct floatformat **format;
17862   struct type *type;
17863
17864   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17865   if (format)
17866     type = init_float_type (objfile, bits, name, format, byte_order);
17867   else
17868     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17869
17870   return type;
17871 }
17872
17873 /* Allocate an integer type of size BITS and name NAME.  */
17874
17875 static struct type *
17876 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17877                           int bits, int unsigned_p, const char *name)
17878 {
17879   struct type *type;
17880
17881   /* Versions of Intel's C Compiler generate an integer type called "void"
17882      instead of using DW_TAG_unspecified_type.  This has been seen on
17883      at least versions 14, 17, and 18.  */
17884   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17885       && strcmp (name, "void") == 0)
17886     type = objfile_type (objfile)->builtin_void;
17887   else
17888     type = init_integer_type (objfile, bits, unsigned_p, name);
17889
17890   return type;
17891 }
17892
17893 /* Return true if DIE has a DW_AT_small attribute whose value is
17894    a constant rational, where both the numerator and denominator
17895    are equal to zero.
17896
17897    CU is the DIE's Compilation Unit.  */
17898
17899 static bool
17900 has_zero_over_zero_small_attribute (struct die_info *die,
17901                                     struct dwarf2_cu *cu)
17902 {
17903   struct attribute *attr = dwarf2_attr (die, DW_AT_small, cu);
17904   if (attr == nullptr)
17905     return false;
17906
17907   struct dwarf2_cu *scale_cu = cu;
17908   struct die_info *scale_die
17909     = follow_die_ref (die, attr, &scale_cu);
17910
17911   if (scale_die->tag != DW_TAG_constant)
17912     return false;
17913
17914   gdb_mpz num (1), denom (1);
17915   get_dwarf2_rational_constant (scale_die, cu, &num, &denom);
17916   return mpz_sgn (num.val) == 0 && mpz_sgn (denom.val) == 0;
17917 }
17918
17919 /* Initialise and return a floating point type of size BITS suitable for
17920    use as a component of a complex number.  The NAME_HINT is passed through
17921    when initialising the floating point type and is the name of the complex
17922    type.
17923
17924    As DWARF doesn't currently provide an explicit name for the components
17925    of a complex number, but it can be helpful to have these components
17926    named, we try to select a suitable name based on the size of the
17927    component.  */
17928 static struct type *
17929 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
17930                                  struct objfile *objfile,
17931                                  int bits, const char *name_hint,
17932                                  enum bfd_endian byte_order)
17933 {
17934   gdbarch *gdbarch = objfile->arch ();
17935   struct type *tt = nullptr;
17936
17937   /* Try to find a suitable floating point builtin type of size BITS.
17938      We're going to use the name of this type as the name for the complex
17939      target type that we are about to create.  */
17940   switch (cu->per_cu->lang)
17941     {
17942     case language_fortran:
17943       switch (bits)
17944         {
17945         case 32:
17946           tt = builtin_f_type (gdbarch)->builtin_real;
17947           break;
17948         case 64:
17949           tt = builtin_f_type (gdbarch)->builtin_real_s8;
17950           break;
17951         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17952         case 128:
17953           tt = builtin_f_type (gdbarch)->builtin_real_s16;
17954           break;
17955         }
17956       break;
17957     default:
17958       switch (bits)
17959         {
17960         case 32:
17961           tt = builtin_type (gdbarch)->builtin_float;
17962           break;
17963         case 64:
17964           tt = builtin_type (gdbarch)->builtin_double;
17965           break;
17966         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17967         case 128:
17968           tt = builtin_type (gdbarch)->builtin_long_double;
17969           break;
17970         }
17971       break;
17972     }
17973
17974   /* If the type we found doesn't match the size we were looking for, then
17975      pretend we didn't find a type at all, the complex target type we
17976      create will then be nameless.  */
17977   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
17978     tt = nullptr;
17979
17980   const char *name = (tt == nullptr) ? nullptr : tt->name ();
17981   return dwarf2_init_float_type (objfile, bits, name, name_hint, byte_order);
17982 }
17983
17984 /* Find a representation of a given base type and install
17985    it in the TYPE field of the die.  */
17986
17987 static struct type *
17988 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17989 {
17990   struct objfile *objfile = cu->per_objfile->objfile;
17991   struct type *type;
17992   struct attribute *attr;
17993   int encoding = 0, bits = 0;
17994   const char *name;
17995   gdbarch *arch;
17996
17997   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17998   if (attr != nullptr && attr->form_is_constant ())
17999     encoding = attr->constant_value (0);
18000   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
18001   if (attr != nullptr)
18002     bits = attr->constant_value (0) * TARGET_CHAR_BIT;
18003   name = dwarf2_name (die, cu);
18004   if (!name)
18005     complaint (_("DW_AT_name missing from DW_TAG_base_type"));
18006
18007   arch = objfile->arch ();
18008   enum bfd_endian byte_order = gdbarch_byte_order (arch);
18009
18010   attr = dwarf2_attr (die, DW_AT_endianity, cu);
18011   if (attr != nullptr && attr->form_is_constant ())
18012     {
18013       int endianity = attr->constant_value (0);
18014
18015       switch (endianity)
18016         {
18017         case DW_END_big:
18018           byte_order = BFD_ENDIAN_BIG;
18019           break;
18020         case DW_END_little:
18021           byte_order = BFD_ENDIAN_LITTLE;
18022           break;
18023         default:
18024           complaint (_("DW_AT_endianity has unrecognized value %d"), endianity);
18025           break;
18026         }
18027     }
18028
18029   if ((encoding == DW_ATE_signed_fixed || encoding == DW_ATE_unsigned_fixed)
18030       && cu->per_cu->lang == language_ada
18031       && has_zero_over_zero_small_attribute (die, cu))
18032     {
18033       /* brobecker/2018-02-24: This is a fixed point type for which
18034          the scaling factor is represented as fraction whose value
18035          does not make sense (zero divided by zero), so we should
18036          normally never see these.  However, there is a small category
18037          of fixed point types for which GNAT is unable to provide
18038          the scaling factor via the standard DWARF mechanisms, and
18039          for which the info is provided via the GNAT encodings instead.
18040          This is likely what this DIE is about.  */
18041       encoding = (encoding == DW_ATE_signed_fixed
18042                   ? DW_ATE_signed
18043                   : DW_ATE_unsigned);
18044     }
18045
18046   /* With GNAT encodings, fixed-point information will be encoded in
18047      the type name.  Note that this can also occur with the above
18048      zero-over-zero case, which is why this is a separate "if" rather
18049      than an "else if".  */
18050   const char *gnat_encoding_suffix = nullptr;
18051   if ((encoding == DW_ATE_signed || encoding == DW_ATE_unsigned)
18052       && cu->per_cu->lang == language_ada
18053       && name != nullptr)
18054     {
18055       gnat_encoding_suffix = gnat_encoded_fixed_point_type_info (name);
18056       if (gnat_encoding_suffix != nullptr)
18057         {
18058           gdb_assert (startswith (gnat_encoding_suffix,
18059                                   GNAT_FIXED_POINT_SUFFIX));
18060           name = obstack_strndup (&cu->per_objfile->objfile->objfile_obstack,
18061                                   name, gnat_encoding_suffix - name);
18062           /* Use -1 here so that SUFFIX points at the "_" after the
18063              "XF".  */
18064           gnat_encoding_suffix += strlen (GNAT_FIXED_POINT_SUFFIX) - 1;
18065
18066           encoding = (encoding == DW_ATE_signed
18067                       ? DW_ATE_signed_fixed
18068                       : DW_ATE_unsigned_fixed);
18069         }
18070     }
18071
18072   switch (encoding)
18073     {
18074       case DW_ATE_address:
18075         /* Turn DW_ATE_address into a void * pointer.  */
18076         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
18077         type = init_pointer_type (objfile, bits, name, type);
18078         break;
18079       case DW_ATE_boolean:
18080         type = init_boolean_type (objfile, bits, 1, name);
18081         break;
18082       case DW_ATE_complex_float:
18083         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name,
18084                                                 byte_order);
18085         if (type->code () == TYPE_CODE_ERROR)
18086           {
18087             if (name == nullptr)
18088               {
18089                 struct obstack *obstack
18090                   = &cu->per_objfile->objfile->objfile_obstack;
18091                 name = obconcat (obstack, "_Complex ", type->name (),
18092                                  nullptr);
18093               }
18094             type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
18095           }
18096         else
18097           type = init_complex_type (name, type);
18098         break;
18099       case DW_ATE_decimal_float:
18100         type = init_decfloat_type (objfile, bits, name);
18101         break;
18102       case DW_ATE_float:
18103         type = dwarf2_init_float_type (objfile, bits, name, name, byte_order);
18104         break;
18105       case DW_ATE_signed:
18106         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
18107         break;
18108       case DW_ATE_unsigned:
18109         if (cu->per_cu->lang == language_fortran
18110             && name
18111             && startswith (name, "character("))
18112           type = init_character_type (objfile, bits, 1, name);
18113         else
18114           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18115         break;
18116       case DW_ATE_signed_char:
18117         if (cu->per_cu->lang == language_ada
18118             || cu->per_cu->lang == language_m2
18119             || cu->per_cu->lang == language_pascal
18120             || cu->per_cu->lang == language_fortran)
18121           type = init_character_type (objfile, bits, 0, name);
18122         else
18123           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
18124         break;
18125       case DW_ATE_unsigned_char:
18126         if (cu->per_cu->lang == language_ada
18127             || cu->per_cu->lang == language_m2
18128             || cu->per_cu->lang == language_pascal
18129             || cu->per_cu->lang == language_fortran
18130             || cu->per_cu->lang == language_rust)
18131           type = init_character_type (objfile, bits, 1, name);
18132         else
18133           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18134         break;
18135       case DW_ATE_UTF:
18136         {
18137           if (bits == 16)
18138             type = builtin_type (arch)->builtin_char16;
18139           else if (bits == 32)
18140             type = builtin_type (arch)->builtin_char32;
18141           else
18142             {
18143               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
18144                          bits);
18145               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
18146             }
18147           return set_die_type (die, type, cu);
18148         }
18149         break;
18150       case DW_ATE_signed_fixed:
18151         type = init_fixed_point_type (objfile, bits, 0, name);
18152         finish_fixed_point_type (type, gnat_encoding_suffix, die, cu);
18153         break;
18154       case DW_ATE_unsigned_fixed:
18155         type = init_fixed_point_type (objfile, bits, 1, name);
18156         finish_fixed_point_type (type, gnat_encoding_suffix, die, cu);
18157         break;
18158
18159       default:
18160         complaint (_("unsupported DW_AT_encoding: '%s'"),
18161                    dwarf_type_encoding_name (encoding));
18162         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
18163         break;
18164     }
18165
18166   if (name && strcmp (name, "char") == 0)
18167     type->set_has_no_signedness (true);
18168
18169   maybe_set_alignment (cu, die, type);
18170
18171   type->set_endianity_is_not_default (gdbarch_byte_order (arch) != byte_order);
18172
18173   if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_INT)
18174     {
18175       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
18176       if (attr != nullptr && attr->as_unsigned () <= 8 * TYPE_LENGTH (type))
18177         {
18178           unsigned real_bit_size = attr->as_unsigned ();
18179           attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
18180           /* Only use the attributes if they make sense together.  */
18181           if (attr == nullptr
18182               || (attr->as_unsigned () + real_bit_size
18183                   <= 8 * TYPE_LENGTH (type)))
18184             {
18185               TYPE_MAIN_TYPE (type)->type_specific.int_stuff.bit_size
18186                 = real_bit_size;
18187               if (attr != nullptr)
18188                 TYPE_MAIN_TYPE (type)->type_specific.int_stuff.bit_offset
18189                   = attr->as_unsigned ();
18190             }
18191         }
18192     }
18193
18194   return set_die_type (die, type, cu);
18195 }
18196
18197 /* A helper function that returns the name of DIE, if it refers to a
18198    variable declaration.  */
18199
18200 static const char *
18201 var_decl_name (struct die_info *die, struct dwarf2_cu *cu)
18202 {
18203   if (die->tag != DW_TAG_variable)
18204     return nullptr;
18205
18206   attribute *attr = dwarf2_attr (die, DW_AT_declaration, cu);
18207   if (attr == nullptr || !attr->as_boolean ())
18208     return nullptr;
18209
18210   attr = dwarf2_attr (die, DW_AT_name, cu);
18211   if (attr == nullptr)
18212     return nullptr;
18213   return attr->as_string ();
18214 }
18215
18216 /* Parse dwarf attribute if it's a block, reference or constant and put the
18217    resulting value of the attribute into struct bound_prop.
18218    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
18219
18220 static int
18221 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
18222                       struct dwarf2_cu *cu, struct dynamic_prop *prop,
18223                       struct type *default_type)
18224 {
18225   struct dwarf2_property_baton *baton;
18226   dwarf2_per_objfile *per_objfile = cu->per_objfile;
18227   struct objfile *objfile = per_objfile->objfile;
18228   struct obstack *obstack = &objfile->objfile_obstack;
18229
18230   gdb_assert (default_type != NULL);
18231
18232   if (attr == NULL || prop == NULL)
18233     return 0;
18234
18235   if (attr->form_is_block ())
18236     {
18237       baton = XOBNEW (obstack, struct dwarf2_property_baton);
18238       baton->property_type = default_type;
18239       baton->locexpr.per_cu = cu->per_cu;
18240       baton->locexpr.per_objfile = per_objfile;
18241
18242       struct dwarf_block *block = attr->as_block ();
18243       baton->locexpr.size = block->size;
18244       baton->locexpr.data = block->data;
18245       switch (attr->name)
18246         {
18247         case DW_AT_string_length:
18248           baton->locexpr.is_reference = true;
18249           break;
18250         default:
18251           baton->locexpr.is_reference = false;
18252           break;
18253         }
18254
18255       prop->set_locexpr (baton);
18256       gdb_assert (prop->baton () != NULL);
18257     }
18258   else if (attr->form_is_ref ())
18259     {
18260       struct dwarf2_cu *target_cu = cu;
18261       struct die_info *target_die;
18262       struct attribute *target_attr;
18263
18264       target_die = follow_die_ref (die, attr, &target_cu);
18265       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
18266       if (target_attr == NULL)
18267         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
18268                                    target_cu);
18269       if (target_attr == NULL)
18270         {
18271           const char *name = var_decl_name (target_die, target_cu);
18272           if (name != nullptr)
18273             {
18274               prop->set_variable_name (name);
18275               return 1;
18276             }
18277           return 0;
18278         }
18279
18280       switch (target_attr->name)
18281         {
18282           case DW_AT_location:
18283             if (target_attr->form_is_section_offset ())
18284               {
18285                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
18286                 baton->property_type = die_type (target_die, target_cu);
18287                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
18288                 prop->set_loclist (baton);
18289                 gdb_assert (prop->baton () != NULL);
18290               }
18291             else if (target_attr->form_is_block ())
18292               {
18293                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
18294                 baton->property_type = die_type (target_die, target_cu);
18295                 baton->locexpr.per_cu = cu->per_cu;
18296                 baton->locexpr.per_objfile = per_objfile;
18297                 struct dwarf_block *block = target_attr->as_block ();
18298                 baton->locexpr.size = block->size;
18299                 baton->locexpr.data = block->data;
18300                 baton->locexpr.is_reference = true;
18301                 prop->set_locexpr (baton);
18302                 gdb_assert (prop->baton () != NULL);
18303               }
18304             else
18305               {
18306                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18307                                                        "dynamic property");
18308                 return 0;
18309               }
18310             break;
18311           case DW_AT_data_member_location:
18312             {
18313               LONGEST offset;
18314
18315               if (!handle_data_member_location (target_die, target_cu,
18316                                                 &offset))
18317                 return 0;
18318
18319               baton = XOBNEW (obstack, struct dwarf2_property_baton);
18320               baton->property_type = read_type_die (target_die->parent,
18321                                                       target_cu);
18322               baton->offset_info.offset = offset;
18323               baton->offset_info.type = die_type (target_die, target_cu);
18324               prop->set_addr_offset (baton);
18325               break;
18326             }
18327         }
18328     }
18329   else if (attr->form_is_constant ())
18330     prop->set_const_val (attr->constant_value (0));
18331   else
18332     {
18333       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
18334                                              dwarf2_name (die, cu));
18335       return 0;
18336     }
18337
18338   return 1;
18339 }
18340
18341 /* See read.h.  */
18342
18343 struct type *
18344 dwarf2_per_objfile::int_type (int size_in_bytes, bool unsigned_p) const
18345 {
18346   struct type *int_type;
18347
18348   /* Helper macro to examine the various builtin types.  */
18349 #define TRY_TYPE(F)                                                     \
18350   int_type = (unsigned_p                                                \
18351               ? objfile_type (objfile)->builtin_unsigned_ ## F          \
18352               : objfile_type (objfile)->builtin_ ## F);                 \
18353   if (int_type != NULL && TYPE_LENGTH (int_type) == size_in_bytes)      \
18354     return int_type
18355
18356   TRY_TYPE (char);
18357   TRY_TYPE (short);
18358   TRY_TYPE (int);
18359   TRY_TYPE (long);
18360   TRY_TYPE (long_long);
18361
18362 #undef TRY_TYPE
18363
18364   gdb_assert_not_reached ("unable to find suitable integer type");
18365 }
18366
18367 /* Read the DW_AT_type attribute for a sub-range.  If this attribute is not
18368    present (which is valid) then compute the default type based on the
18369    compilation units address size.  */
18370
18371 static struct type *
18372 read_subrange_index_type (struct die_info *die, struct dwarf2_cu *cu)
18373 {
18374   struct type *index_type = die_type (die, cu);
18375
18376   /* Dwarf-2 specifications explicitly allows to create subrange types
18377      without specifying a base type.
18378      In that case, the base type must be set to the type of
18379      the lower bound, upper bound or count, in that order, if any of these
18380      three attributes references an object that has a type.
18381      If no base type is found, the Dwarf-2 specifications say that
18382      a signed integer type of size equal to the size of an address should
18383      be used.
18384      For the following C code: `extern char gdb_int [];'
18385      GCC produces an empty range DIE.
18386      FIXME: muller/2010-05-28: Possible references to object for low bound,
18387      high bound or count are not yet handled by this code.  */
18388   if (index_type->code () == TYPE_CODE_VOID)
18389     index_type = cu->addr_sized_int_type (false);
18390
18391   return index_type;
18392 }
18393
18394 /* Read the given DW_AT_subrange DIE.  */
18395
18396 static struct type *
18397 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
18398 {
18399   struct type *base_type, *orig_base_type;
18400   struct type *range_type;
18401   struct attribute *attr;
18402   struct dynamic_prop low, high;
18403   int low_default_is_valid;
18404   int high_bound_is_count = 0;
18405   const char *name;
18406   ULONGEST negative_mask;
18407
18408   orig_base_type = read_subrange_index_type (die, cu);
18409
18410   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
18411      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
18412      creating the range type, but we use the result of check_typedef
18413      when examining properties of the type.  */
18414   base_type = check_typedef (orig_base_type);
18415
18416   /* The die_type call above may have already set the type for this DIE.  */
18417   range_type = get_die_type (die, cu);
18418   if (range_type)
18419     return range_type;
18420
18421   high.set_const_val (0);
18422
18423   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
18424      omitting DW_AT_lower_bound.  */
18425   switch (cu->per_cu->lang)
18426     {
18427     case language_c:
18428     case language_cplus:
18429       low.set_const_val (0);
18430       low_default_is_valid = 1;
18431       break;
18432     case language_fortran:
18433       low.set_const_val (1);
18434       low_default_is_valid = 1;
18435       break;
18436     case language_d:
18437     case language_objc:
18438     case language_rust:
18439       low.set_const_val (0);
18440       low_default_is_valid = (cu->header.version >= 4);
18441       break;
18442     case language_ada:
18443     case language_m2:
18444     case language_pascal:
18445       low.set_const_val (1);
18446       low_default_is_valid = (cu->header.version >= 4);
18447       break;
18448     default:
18449       low.set_const_val (0);
18450       low_default_is_valid = 0;
18451       break;
18452     }
18453
18454   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
18455   if (attr != nullptr)
18456     attr_to_dynamic_prop (attr, die, cu, &low, base_type);
18457   else if (!low_default_is_valid)
18458     complaint (_("Missing DW_AT_lower_bound "
18459                                       "- DIE at %s [in module %s]"),
18460                sect_offset_str (die->sect_off),
18461                objfile_name (cu->per_objfile->objfile));
18462
18463   struct attribute *attr_ub, *attr_count;
18464   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
18465   if (!attr_to_dynamic_prop (attr, die, cu, &high, base_type))
18466     {
18467       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
18468       if (attr_to_dynamic_prop (attr, die, cu, &high, base_type))
18469         {
18470           /* If bounds are constant do the final calculation here.  */
18471           if (low.kind () == PROP_CONST && high.kind () == PROP_CONST)
18472             high.set_const_val (low.const_val () + high.const_val () - 1);
18473           else
18474             high_bound_is_count = 1;
18475         }
18476       else
18477         {
18478           if (attr_ub != NULL)
18479             complaint (_("Unresolved DW_AT_upper_bound "
18480                          "- DIE at %s [in module %s]"),
18481                        sect_offset_str (die->sect_off),
18482                        objfile_name (cu->per_objfile->objfile));
18483           if (attr_count != NULL)
18484             complaint (_("Unresolved DW_AT_count "
18485                          "- DIE at %s [in module %s]"),
18486                        sect_offset_str (die->sect_off),
18487                        objfile_name (cu->per_objfile->objfile));
18488         }
18489     }
18490
18491   LONGEST bias = 0;
18492   struct attribute *bias_attr = dwarf2_attr (die, DW_AT_GNU_bias, cu);
18493   if (bias_attr != nullptr && bias_attr->form_is_constant ())
18494     bias = bias_attr->constant_value (0);
18495
18496   /* Normally, the DWARF producers are expected to use a signed
18497      constant form (Eg. DW_FORM_sdata) to express negative bounds.
18498      But this is unfortunately not always the case, as witnessed
18499      with GCC, for instance, where the ambiguous DW_FORM_dataN form
18500      is used instead.  To work around that ambiguity, we treat
18501      the bounds as signed, and thus sign-extend their values, when
18502      the base type is signed.  */
18503   negative_mask =
18504     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
18505   if (low.kind () == PROP_CONST
18506       && !base_type->is_unsigned () && (low.const_val () & negative_mask))
18507     low.set_const_val (low.const_val () | negative_mask);
18508   if (high.kind () == PROP_CONST
18509       && !base_type->is_unsigned () && (high.const_val () & negative_mask))
18510     high.set_const_val (high.const_val () | negative_mask);
18511
18512   /* Check for bit and byte strides.  */
18513   struct dynamic_prop byte_stride_prop;
18514   attribute *attr_byte_stride = dwarf2_attr (die, DW_AT_byte_stride, cu);
18515   if (attr_byte_stride != nullptr)
18516     {
18517       struct type *prop_type = cu->addr_sized_int_type (false);
18518       attr_to_dynamic_prop (attr_byte_stride, die, cu, &byte_stride_prop,
18519                             prop_type);
18520     }
18521
18522   struct dynamic_prop bit_stride_prop;
18523   attribute *attr_bit_stride = dwarf2_attr (die, DW_AT_bit_stride, cu);
18524   if (attr_bit_stride != nullptr)
18525     {
18526       /* It only makes sense to have either a bit or byte stride.  */
18527       if (attr_byte_stride != nullptr)
18528         {
18529           complaint (_("Found DW_AT_bit_stride and DW_AT_byte_stride "
18530                        "- DIE at %s [in module %s]"),
18531                      sect_offset_str (die->sect_off),
18532                      objfile_name (cu->per_objfile->objfile));
18533           attr_bit_stride = nullptr;
18534         }
18535       else
18536         {
18537           struct type *prop_type = cu->addr_sized_int_type (false);
18538           attr_to_dynamic_prop (attr_bit_stride, die, cu, &bit_stride_prop,
18539                                 prop_type);
18540         }
18541     }
18542
18543   if (attr_byte_stride != nullptr
18544       || attr_bit_stride != nullptr)
18545     {
18546       bool byte_stride_p = (attr_byte_stride != nullptr);
18547       struct dynamic_prop *stride
18548         = byte_stride_p ? &byte_stride_prop : &bit_stride_prop;
18549
18550       range_type
18551         = create_range_type_with_stride (NULL, orig_base_type, &low,
18552                                          &high, bias, stride, byte_stride_p);
18553     }
18554   else
18555     range_type = create_range_type (NULL, orig_base_type, &low, &high, bias);
18556
18557   if (high_bound_is_count)
18558     range_type->bounds ()->flag_upper_bound_is_count = 1;
18559
18560   /* Ada expects an empty array on no boundary attributes.  */
18561   if (attr == NULL && cu->per_cu->lang != language_ada)
18562     range_type->bounds ()->high.set_undefined ();
18563
18564   name = dwarf2_name (die, cu);
18565   if (name)
18566     range_type->set_name (name);
18567
18568   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
18569   if (attr != nullptr)
18570     TYPE_LENGTH (range_type) = attr->constant_value (0);
18571
18572   maybe_set_alignment (cu, die, range_type);
18573
18574   set_die_type (die, range_type, cu);
18575
18576   /* set_die_type should be already done.  */
18577   set_descriptive_type (range_type, die, cu);
18578
18579   return range_type;
18580 }
18581
18582 static struct type *
18583 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
18584 {
18585   struct type *type;
18586
18587   type = init_type (cu->per_objfile->objfile, TYPE_CODE_VOID, 0, NULL);
18588   type->set_name (dwarf2_name (die, cu));
18589
18590   /* In Ada, an unspecified type is typically used when the description
18591      of the type is deferred to a different unit.  When encountering
18592      such a type, we treat it as a stub, and try to resolve it later on,
18593      when needed.  */
18594   if (cu->per_cu->lang == language_ada)
18595     type->set_is_stub (true);
18596
18597   return set_die_type (die, type, cu);
18598 }
18599
18600 /* Read a single die and all its descendents.  Set the die's sibling
18601    field to NULL; set other fields in the die correctly, and set all
18602    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
18603    location of the info_ptr after reading all of those dies.  PARENT
18604    is the parent of the die in question.  */
18605
18606 static struct die_info *
18607 read_die_and_children (const struct die_reader_specs *reader,
18608                        const gdb_byte *info_ptr,
18609                        const gdb_byte **new_info_ptr,
18610                        struct die_info *parent)
18611 {
18612   struct die_info *die;
18613   const gdb_byte *cur_ptr;
18614
18615   cur_ptr = read_full_die_1 (reader, &die, info_ptr, 0);
18616   if (die == NULL)
18617     {
18618       *new_info_ptr = cur_ptr;
18619       return NULL;
18620     }
18621   store_in_ref_table (die, reader->cu);
18622
18623   if (die->has_children)
18624     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
18625   else
18626     {
18627       die->child = NULL;
18628       *new_info_ptr = cur_ptr;
18629     }
18630
18631   die->sibling = NULL;
18632   die->parent = parent;
18633   return die;
18634 }
18635
18636 /* Read a die, all of its descendents, and all of its siblings; set
18637    all of the fields of all of the dies correctly.  Arguments are as
18638    in read_die_and_children.  */
18639
18640 static struct die_info *
18641 read_die_and_siblings_1 (const struct die_reader_specs *reader,
18642                          const gdb_byte *info_ptr,
18643                          const gdb_byte **new_info_ptr,
18644                          struct die_info *parent)
18645 {
18646   struct die_info *first_die, *last_sibling;
18647   const gdb_byte *cur_ptr;
18648
18649   cur_ptr = info_ptr;
18650   first_die = last_sibling = NULL;
18651
18652   while (1)
18653     {
18654       struct die_info *die
18655         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
18656
18657       if (die == NULL)
18658         {
18659           *new_info_ptr = cur_ptr;
18660           return first_die;
18661         }
18662
18663       if (!first_die)
18664         first_die = die;
18665       else
18666         last_sibling->sibling = die;
18667
18668       last_sibling = die;
18669     }
18670 }
18671
18672 /* Read a die, all of its descendents, and all of its siblings; set
18673    all of the fields of all of the dies correctly.  Arguments are as
18674    in read_die_and_children.
18675    This the main entry point for reading a DIE and all its children.  */
18676
18677 static struct die_info *
18678 read_die_and_siblings (const struct die_reader_specs *reader,
18679                        const gdb_byte *info_ptr,
18680                        const gdb_byte **new_info_ptr,
18681                        struct die_info *parent)
18682 {
18683   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18684                                                   new_info_ptr, parent);
18685
18686   if (dwarf_die_debug)
18687     {
18688       fprintf_unfiltered (gdb_stdlog,
18689                           "Read die from %s@0x%x of %s:\n",
18690                           reader->die_section->get_name (),
18691                           (unsigned) (info_ptr - reader->die_section->buffer),
18692                           bfd_get_filename (reader->abfd));
18693       dump_die (die, dwarf_die_debug);
18694     }
18695
18696   return die;
18697 }
18698
18699 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18700    attributes.
18701    The caller is responsible for filling in the extra attributes
18702    and updating (*DIEP)->num_attrs.
18703    Set DIEP to point to a newly allocated die with its information,
18704    except for its child, sibling, and parent fields.  */
18705
18706 static const gdb_byte *
18707 read_full_die_1 (const struct die_reader_specs *reader,
18708                  struct die_info **diep, const gdb_byte *info_ptr,
18709                  int num_extra_attrs)
18710 {
18711   unsigned int abbrev_number, bytes_read, i;
18712   const struct abbrev_info *abbrev;
18713   struct die_info *die;
18714   struct dwarf2_cu *cu = reader->cu;
18715   bfd *abfd = reader->abfd;
18716
18717   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18718   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18719   info_ptr += bytes_read;
18720   if (!abbrev_number)
18721     {
18722       *diep = NULL;
18723       return info_ptr;
18724     }
18725
18726   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18727   if (!abbrev)
18728     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18729            abbrev_number,
18730            bfd_get_filename (abfd));
18731
18732   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18733   die->sect_off = sect_off;
18734   die->tag = abbrev->tag;
18735   die->abbrev = abbrev_number;
18736   die->has_children = abbrev->has_children;
18737
18738   /* Make the result usable.
18739      The caller needs to update num_attrs after adding the extra
18740      attributes.  */
18741   die->num_attrs = abbrev->num_attrs;
18742
18743   bool any_need_reprocess = false;
18744   for (i = 0; i < abbrev->num_attrs; ++i)
18745     {
18746       info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18747                                  info_ptr);
18748       if (die->attrs[i].requires_reprocessing_p ())
18749         any_need_reprocess = true;
18750     }
18751
18752   struct attribute *attr = die->attr (DW_AT_str_offsets_base);
18753   if (attr != nullptr && attr->form_is_unsigned ())
18754     cu->str_offsets_base = attr->as_unsigned ();
18755
18756   attr = die->attr (DW_AT_loclists_base);
18757   if (attr != nullptr)
18758     cu->loclist_base = attr->as_unsigned ();
18759
18760   auto maybe_addr_base = die->addr_base ();
18761   if (maybe_addr_base.has_value ())
18762     cu->addr_base = *maybe_addr_base;
18763
18764   attr = die->attr (DW_AT_rnglists_base);
18765   if (attr != nullptr)
18766     cu->rnglists_base = attr->as_unsigned ();
18767
18768   if (any_need_reprocess)
18769     {
18770       for (i = 0; i < abbrev->num_attrs; ++i)
18771         {
18772           if (die->attrs[i].requires_reprocessing_p ())
18773             read_attribute_reprocess (reader, &die->attrs[i], die->tag);
18774         }
18775     }
18776   *diep = die;
18777   return info_ptr;
18778 }
18779
18780 /* Read a die and all its attributes.
18781    Set DIEP to point to a newly allocated die with its information,
18782    except for its child, sibling, and parent fields.  */
18783
18784 static const gdb_byte *
18785 read_full_die (const struct die_reader_specs *reader,
18786                struct die_info **diep, const gdb_byte *info_ptr)
18787 {
18788   const gdb_byte *result;
18789
18790   result = read_full_die_1 (reader, diep, info_ptr, 0);
18791
18792   if (dwarf_die_debug)
18793     {
18794       fprintf_unfiltered (gdb_stdlog,
18795                           "Read die from %s@0x%x of %s:\n",
18796                           reader->die_section->get_name (),
18797                           (unsigned) (info_ptr - reader->die_section->buffer),
18798                           bfd_get_filename (reader->abfd));
18799       dump_die (*diep, dwarf_die_debug);
18800     }
18801
18802   return result;
18803 }
18804 \f
18805
18806 /* Returns nonzero if TAG represents a type that we might generate a partial
18807    symbol for.  */
18808
18809 static int
18810 is_type_tag_for_partial (int tag, enum language lang)
18811 {
18812   switch (tag)
18813     {
18814 #if 0
18815     /* Some types that would be reasonable to generate partial symbols for,
18816        that we don't at present.  Note that normally this does not
18817        matter, mainly because C compilers don't give names to these
18818        types, but instead emit DW_TAG_typedef.  */
18819     case DW_TAG_file_type:
18820     case DW_TAG_ptr_to_member_type:
18821     case DW_TAG_set_type:
18822     case DW_TAG_string_type:
18823     case DW_TAG_subroutine_type:
18824 #endif
18825
18826       /* GNAT may emit an array with a name, but no typedef, so we
18827          need to make a symbol in this case.  */
18828     case DW_TAG_array_type:
18829       return lang == language_ada;
18830
18831     case DW_TAG_base_type:
18832     case DW_TAG_class_type:
18833     case DW_TAG_interface_type:
18834     case DW_TAG_enumeration_type:
18835     case DW_TAG_structure_type:
18836     case DW_TAG_subrange_type:
18837     case DW_TAG_typedef:
18838     case DW_TAG_union_type:
18839       return 1;
18840     default:
18841       return 0;
18842     }
18843 }
18844
18845 /* Load all DIEs that are interesting for partial symbols into memory.  */
18846
18847 static struct partial_die_info *
18848 load_partial_dies (const struct die_reader_specs *reader,
18849                    const gdb_byte *info_ptr, int building_psymtab)
18850 {
18851   struct dwarf2_cu *cu = reader->cu;
18852   struct objfile *objfile = cu->per_objfile->objfile;
18853   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18854   unsigned int bytes_read;
18855   unsigned int load_all = 0;
18856   int nesting_level = 1;
18857
18858   parent_die = NULL;
18859   last_die = NULL;
18860
18861   gdb_assert (cu->per_cu != NULL);
18862   if (cu->load_all_dies)
18863     load_all = 1;
18864
18865   cu->partial_dies
18866     = htab_create_alloc_ex (cu->header.length / 12,
18867                             partial_die_hash,
18868                             partial_die_eq,
18869                             NULL,
18870                             &cu->comp_unit_obstack,
18871                             hashtab_obstack_allocate,
18872                             dummy_obstack_deallocate);
18873
18874   while (1)
18875     {
18876       const abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr,
18877                                                    &bytes_read);
18878
18879       /* A NULL abbrev means the end of a series of children.  */
18880       if (abbrev == NULL)
18881         {
18882           if (--nesting_level == 0)
18883             return first_die;
18884
18885           info_ptr += bytes_read;
18886           last_die = parent_die;
18887           parent_die = parent_die->die_parent;
18888           continue;
18889         }
18890
18891       /* Check for template arguments.  We never save these; if
18892          they're seen, we just mark the parent, and go on our way.  */
18893       if (parent_die != NULL
18894           && cu->per_cu->lang == language_cplus
18895           && (abbrev->tag == DW_TAG_template_type_param
18896               || abbrev->tag == DW_TAG_template_value_param))
18897         {
18898           parent_die->has_template_arguments = 1;
18899
18900           if (!load_all)
18901             {
18902               /* We don't need a partial DIE for the template argument.  */
18903               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18904               continue;
18905             }
18906         }
18907
18908       /* We only recurse into c++ subprograms looking for template arguments.
18909          Skip their other children.  */
18910       if (!load_all
18911           && cu->per_cu->lang == language_cplus
18912           && parent_die != NULL
18913           && parent_die->tag == DW_TAG_subprogram
18914           && abbrev->tag != DW_TAG_inlined_subroutine)
18915         {
18916           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18917           continue;
18918         }
18919
18920       /* Check whether this DIE is interesting enough to save.  Normally
18921          we would not be interested in members here, but there may be
18922          later variables referencing them via DW_AT_specification (for
18923          static members).  */
18924       if (!load_all
18925           && !is_type_tag_for_partial (abbrev->tag, cu->per_cu->lang)
18926           && abbrev->tag != DW_TAG_constant
18927           && abbrev->tag != DW_TAG_enumerator
18928           && abbrev->tag != DW_TAG_subprogram
18929           && abbrev->tag != DW_TAG_inlined_subroutine
18930           && abbrev->tag != DW_TAG_lexical_block
18931           && abbrev->tag != DW_TAG_variable
18932           && abbrev->tag != DW_TAG_namespace
18933           && abbrev->tag != DW_TAG_module
18934           && abbrev->tag != DW_TAG_member
18935           && abbrev->tag != DW_TAG_imported_unit
18936           && abbrev->tag != DW_TAG_imported_declaration)
18937         {
18938           /* Otherwise we skip to the next sibling, if any.  */
18939           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18940           continue;
18941         }
18942
18943       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18944                                    abbrev);
18945
18946       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18947
18948       /* This two-pass algorithm for processing partial symbols has a
18949          high cost in cache pressure.  Thus, handle some simple cases
18950          here which cover the majority of C partial symbols.  DIEs
18951          which neither have specification tags in them, nor could have
18952          specification tags elsewhere pointing at them, can simply be
18953          processed and discarded.
18954
18955          This segment is also optional; scan_partial_symbols and
18956          add_partial_symbol will handle these DIEs if we chain
18957          them in normally.  When compilers which do not emit large
18958          quantities of duplicate debug information are more common,
18959          this code can probably be removed.  */
18960
18961       /* Any complete simple types at the top level (pretty much all
18962          of them, for a language without namespaces), can be processed
18963          directly.  */
18964       if (parent_die == NULL
18965           && pdi.has_specification == 0
18966           && pdi.is_declaration == 0
18967           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18968               || pdi.tag == DW_TAG_base_type
18969               || pdi.tag == DW_TAG_array_type
18970               || pdi.tag == DW_TAG_subrange_type))
18971         {
18972           if (building_psymtab && pdi.raw_name != NULL)
18973             add_partial_symbol (&pdi, cu);
18974
18975           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18976           continue;
18977         }
18978
18979       /* The exception for DW_TAG_typedef with has_children above is
18980          a workaround of GCC PR debug/47510.  In the case of this complaint
18981          type_name_or_error will error on such types later.
18982
18983          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18984          it could not find the child DIEs referenced later, this is checked
18985          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18986
18987       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18988         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18989                      "- DIE at %s [in module %s]"),
18990                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18991
18992       /* If we're at the second level, and we're an enumerator, and
18993          our parent has no specification (meaning possibly lives in a
18994          namespace elsewhere), then we can add the partial symbol now
18995          instead of queueing it.  */
18996       if (pdi.tag == DW_TAG_enumerator
18997           && parent_die != NULL
18998           && parent_die->die_parent == NULL
18999           && parent_die->tag == DW_TAG_enumeration_type
19000           && parent_die->has_specification == 0)
19001         {
19002           if (pdi.raw_name == NULL)
19003             complaint (_("malformed enumerator DIE ignored"));
19004           else if (building_psymtab)
19005             add_partial_symbol (&pdi, cu);
19006
19007           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
19008           continue;
19009         }
19010
19011       struct partial_die_info *part_die
19012         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
19013
19014       /* We'll save this DIE so link it in.  */
19015       part_die->die_parent = parent_die;
19016       part_die->die_sibling = NULL;
19017       part_die->die_child = NULL;
19018
19019       if (last_die && last_die == parent_die)
19020         last_die->die_child = part_die;
19021       else if (last_die)
19022         last_die->die_sibling = part_die;
19023
19024       last_die = part_die;
19025
19026       if (first_die == NULL)
19027         first_die = part_die;
19028
19029       /* Maybe add the DIE to the hash table.  Not all DIEs that we
19030          find interesting need to be in the hash table, because we
19031          also have the parent/sibling/child chains; only those that we
19032          might refer to by offset later during partial symbol reading.
19033
19034          For now this means things that might have be the target of a
19035          DW_AT_specification, DW_AT_abstract_origin, or
19036          DW_AT_extension.  DW_AT_extension will refer only to
19037          namespaces; DW_AT_abstract_origin refers to functions (and
19038          many things under the function DIE, but we do not recurse
19039          into function DIEs during partial symbol reading) and
19040          possibly variables as well; DW_AT_specification refers to
19041          declarations.  Declarations ought to have the DW_AT_declaration
19042          flag.  It happens that GCC forgets to put it in sometimes, but
19043          only for functions, not for types.
19044
19045          Adding more things than necessary to the hash table is harmless
19046          except for the performance cost.  Adding too few will result in
19047          wasted time in find_partial_die, when we reread the compilation
19048          unit with load_all_dies set.  */
19049
19050       if (load_all
19051           || abbrev->tag == DW_TAG_constant
19052           || abbrev->tag == DW_TAG_subprogram
19053           || abbrev->tag == DW_TAG_variable
19054           || abbrev->tag == DW_TAG_namespace
19055           || part_die->is_declaration)
19056         {
19057           void **slot;
19058
19059           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
19060                                            to_underlying (part_die->sect_off),
19061                                            INSERT);
19062           *slot = part_die;
19063         }
19064
19065       /* For some DIEs we want to follow their children (if any).  For C
19066          we have no reason to follow the children of structures; for other
19067          languages we have to, so that we can get at method physnames
19068          to infer fully qualified class names, for DW_AT_specification,
19069          and for C++ template arguments.  For C++, we also look one level
19070          inside functions to find template arguments (if the name of the
19071          function does not already contain the template arguments).
19072
19073          For Ada and Fortran, we need to scan the children of subprograms
19074          and lexical blocks as well because these languages allow the
19075          definition of nested entities that could be interesting for the
19076          debugger, such as nested subprograms for instance.  */
19077       if (last_die->has_children
19078           && (load_all
19079               || last_die->tag == DW_TAG_namespace
19080               || last_die->tag == DW_TAG_module
19081               || last_die->tag == DW_TAG_enumeration_type
19082               || (cu->per_cu->lang == language_cplus
19083                   && last_die->tag == DW_TAG_subprogram
19084                   && (last_die->raw_name == NULL
19085                       || strchr (last_die->raw_name, '<') == NULL))
19086               || (cu->per_cu->lang != language_c
19087                   && (last_die->tag == DW_TAG_class_type
19088                       || last_die->tag == DW_TAG_interface_type
19089                       || last_die->tag == DW_TAG_structure_type
19090                       || last_die->tag == DW_TAG_union_type))
19091               || ((cu->per_cu->lang == language_ada
19092                    || cu->per_cu->lang == language_fortran)
19093                   && (last_die->tag == DW_TAG_subprogram
19094                       || last_die->tag == DW_TAG_lexical_block))))
19095         {
19096           nesting_level++;
19097           parent_die = last_die;
19098           continue;
19099         }
19100
19101       /* Otherwise we skip to the next sibling, if any.  */
19102       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
19103
19104       /* Back to the top, do it again.  */
19105     }
19106 }
19107
19108 partial_die_info::partial_die_info (sect_offset sect_off_,
19109                                     const struct abbrev_info *abbrev)
19110   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
19111 {
19112 }
19113
19114 /* See class definition.  */
19115
19116 const char *
19117 partial_die_info::name (dwarf2_cu *cu)
19118 {
19119   if (!canonical_name && raw_name != nullptr)
19120     {
19121       struct objfile *objfile = cu->per_objfile->objfile;
19122       raw_name = dwarf2_canonicalize_name (raw_name, cu, objfile);
19123       canonical_name = 1;
19124     }
19125
19126   return raw_name;
19127 }
19128
19129 /* Read a minimal amount of information into the minimal die structure.
19130    INFO_PTR should point just after the initial uleb128 of a DIE.  */
19131
19132 const gdb_byte *
19133 partial_die_info::read (const struct die_reader_specs *reader,
19134                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
19135 {
19136   struct dwarf2_cu *cu = reader->cu;
19137   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19138   unsigned int i;
19139   int has_low_pc_attr = 0;
19140   int has_high_pc_attr = 0;
19141   int high_pc_relative = 0;
19142
19143   for (i = 0; i < abbrev.num_attrs; ++i)
19144     {
19145       attribute attr;
19146       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
19147       /* String and address offsets that need to do the reprocessing have
19148          already been read at this point, so there is no need to wait until
19149          the loop terminates to do the reprocessing.  */
19150       if (attr.requires_reprocessing_p ())
19151         read_attribute_reprocess (reader, &attr, tag);
19152       /* Store the data if it is of an attribute we want to keep in a
19153          partial symbol table.  */
19154       switch (attr.name)
19155         {
19156         case DW_AT_name:
19157           switch (tag)
19158             {
19159             case DW_TAG_compile_unit:
19160             case DW_TAG_partial_unit:
19161             case DW_TAG_type_unit:
19162               /* Compilation units have a DW_AT_name that is a filename, not
19163                  a source language identifier.  */
19164             case DW_TAG_enumeration_type:
19165             case DW_TAG_enumerator:
19166               /* These tags always have simple identifiers already; no need
19167                  to canonicalize them.  */
19168               canonical_name = 1;
19169               raw_name = attr.as_string ();
19170               break;
19171             default:
19172               canonical_name = 0;
19173               raw_name = attr.as_string ();
19174               break;
19175             }
19176           break;
19177         case DW_AT_linkage_name:
19178         case DW_AT_MIPS_linkage_name:
19179           /* Note that both forms of linkage name might appear.  We
19180              assume they will be the same, and we only store the last
19181              one we see.  */
19182           linkage_name = attr.as_string ();
19183           break;
19184         case DW_AT_low_pc:
19185           has_low_pc_attr = 1;
19186           lowpc = attr.as_address ();
19187           break;
19188         case DW_AT_high_pc:
19189           has_high_pc_attr = 1;
19190           highpc = attr.as_address ();
19191           if (cu->header.version >= 4 && attr.form_is_constant ())
19192                 high_pc_relative = 1;
19193           break;
19194         case DW_AT_location:
19195           /* Support the .debug_loc offsets.  */
19196           if (attr.form_is_block ())
19197             {
19198               d.locdesc = attr.as_block ();
19199             }
19200           else if (attr.form_is_section_offset ())
19201             {
19202               dwarf2_complex_location_expr_complaint ();
19203             }
19204           else
19205             {
19206               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
19207                                                      "partial symbol information");
19208             }
19209           break;
19210         case DW_AT_external:
19211           is_external = attr.as_boolean ();
19212           break;
19213         case DW_AT_declaration:
19214           is_declaration = attr.as_boolean ();
19215           break;
19216         case DW_AT_type:
19217           has_type = 1;
19218           break;
19219         case DW_AT_abstract_origin:
19220         case DW_AT_specification:
19221         case DW_AT_extension:
19222           has_specification = 1;
19223           spec_offset = attr.get_ref_die_offset ();
19224           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19225                                    || cu->per_cu->is_dwz);
19226           break;
19227         case DW_AT_sibling:
19228           /* Ignore absolute siblings, they might point outside of
19229              the current compile unit.  */
19230           if (attr.form == DW_FORM_ref_addr)
19231             complaint (_("ignoring absolute DW_AT_sibling"));
19232           else
19233             {
19234               const gdb_byte *buffer = reader->buffer;
19235               sect_offset off = attr.get_ref_die_offset ();
19236               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
19237
19238               if (sibling_ptr < info_ptr)
19239                 complaint (_("DW_AT_sibling points backwards"));
19240               else if (sibling_ptr > reader->buffer_end)
19241                 reader->die_section->overflow_complaint ();
19242               else
19243                 sibling = sibling_ptr;
19244             }
19245           break;
19246         case DW_AT_byte_size:
19247           has_byte_size = 1;
19248           break;
19249         case DW_AT_const_value:
19250           has_const_value = 1;
19251           break;
19252         case DW_AT_calling_convention:
19253           /* DWARF doesn't provide a way to identify a program's source-level
19254              entry point.  DW_AT_calling_convention attributes are only meant
19255              to describe functions' calling conventions.
19256
19257              However, because it's a necessary piece of information in
19258              Fortran, and before DWARF 4 DW_CC_program was the only
19259              piece of debugging information whose definition refers to
19260              a 'main program' at all, several compilers marked Fortran
19261              main programs with DW_CC_program --- even when those
19262              functions use the standard calling conventions.
19263
19264              Although DWARF now specifies a way to provide this
19265              information, we support this practice for backward
19266              compatibility.  */
19267           if (attr.constant_value (0) == DW_CC_program
19268               && cu->per_cu->lang == language_fortran)
19269             main_subprogram = 1;
19270           break;
19271         case DW_AT_inline:
19272           {
19273             LONGEST value = attr.constant_value (-1);
19274             if (value == DW_INL_inlined
19275                 || value == DW_INL_declared_inlined)
19276               may_be_inlined = 1;
19277           }
19278           break;
19279
19280         case DW_AT_import:
19281           if (tag == DW_TAG_imported_unit)
19282             {
19283               d.sect_off = attr.get_ref_die_offset ();
19284               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19285                                   || cu->per_cu->is_dwz);
19286             }
19287           break;
19288
19289         case DW_AT_main_subprogram:
19290           main_subprogram = attr.as_boolean ();
19291           break;
19292
19293         case DW_AT_ranges:
19294           {
19295             /* Offset in the .debug_ranges or .debug_rnglist section (depending
19296                on DWARF version).  */
19297             ULONGEST ranges_offset = attr.as_unsigned ();
19298
19299             /* See dwarf2_cu::gnu_ranges_base's doc for why we might want to add
19300                this value.  */
19301             if (tag != DW_TAG_compile_unit)
19302               ranges_offset += cu->gnu_ranges_base;
19303
19304             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
19305                                     nullptr, tag))
19306               has_pc_info = 1;
19307           }
19308           break;
19309
19310         default:
19311           break;
19312         }
19313     }
19314
19315   /* For Ada, if both the name and the linkage name appear, we prefer
19316      the latter.  This lets "catch exception" work better, regardless
19317      of the order in which the name and linkage name were emitted.
19318      Really, though, this is just a workaround for the fact that gdb
19319      doesn't store both the name and the linkage name.  */
19320   if (cu->per_cu->lang == language_ada && linkage_name != nullptr)
19321     raw_name = linkage_name;
19322
19323   if (high_pc_relative)
19324     highpc += lowpc;
19325
19326   if (has_low_pc_attr && has_high_pc_attr)
19327     {
19328       /* When using the GNU linker, .gnu.linkonce. sections are used to
19329          eliminate duplicate copies of functions and vtables and such.
19330          The linker will arbitrarily choose one and discard the others.
19331          The AT_*_pc values for such functions refer to local labels in
19332          these sections.  If the section from that file was discarded, the
19333          labels are not in the output, so the relocs get a value of 0.
19334          If this is a discarded function, mark the pc bounds as invalid,
19335          so that GDB will ignore it.  */
19336       if (lowpc == 0 && !per_objfile->per_bfd->has_section_at_zero)
19337         {
19338           struct objfile *objfile = per_objfile->objfile;
19339           struct gdbarch *gdbarch = objfile->arch ();
19340
19341           complaint (_("DW_AT_low_pc %s is zero "
19342                        "for DIE at %s [in module %s]"),
19343                      paddress (gdbarch, lowpc),
19344                      sect_offset_str (sect_off),
19345                      objfile_name (objfile));
19346         }
19347       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
19348       else if (lowpc >= highpc)
19349         {
19350           struct objfile *objfile = per_objfile->objfile;
19351           struct gdbarch *gdbarch = objfile->arch ();
19352
19353           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
19354                        "for DIE at %s [in module %s]"),
19355                      paddress (gdbarch, lowpc),
19356                      paddress (gdbarch, highpc),
19357                      sect_offset_str (sect_off),
19358                      objfile_name (objfile));
19359         }
19360       else
19361         has_pc_info = 1;
19362     }
19363
19364   return info_ptr;
19365 }
19366
19367 /* Find a cached partial DIE at OFFSET in CU.  */
19368
19369 struct partial_die_info *
19370 dwarf2_cu::find_partial_die (sect_offset sect_off)
19371 {
19372   struct partial_die_info *lookup_die = NULL;
19373   struct partial_die_info part_die (sect_off);
19374
19375   lookup_die = ((struct partial_die_info *)
19376                 htab_find_with_hash (partial_dies, &part_die,
19377                                      to_underlying (sect_off)));
19378
19379   return lookup_die;
19380 }
19381
19382 /* Find a partial DIE at OFFSET, which may or may not be in CU,
19383    except in the case of .debug_types DIEs which do not reference
19384    outside their CU (they do however referencing other types via
19385    DW_FORM_ref_sig8).  */
19386
19387 static const struct cu_partial_die_info
19388 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
19389 {
19390   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19391   struct objfile *objfile = per_objfile->objfile;
19392   struct partial_die_info *pd = NULL;
19393
19394   if (offset_in_dwz == cu->per_cu->is_dwz
19395       && cu->header.offset_in_cu_p (sect_off))
19396     {
19397       pd = cu->find_partial_die (sect_off);
19398       if (pd != NULL)
19399         return { cu, pd };
19400       /* We missed recording what we needed.
19401          Load all dies and try again.  */
19402     }
19403   else
19404     {
19405       /* TUs don't reference other CUs/TUs (except via type signatures).  */
19406       if (cu->per_cu->is_debug_types)
19407         {
19408           error (_("Dwarf Error: Type Unit at offset %s contains"
19409                    " external reference to offset %s [in module %s].\n"),
19410                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
19411                  bfd_get_filename (objfile->obfd));
19412         }
19413       dwarf2_per_cu_data *per_cu
19414         = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
19415                                             per_objfile);
19416
19417       cu = per_objfile->get_cu (per_cu);
19418       if (cu == NULL || cu->partial_dies == NULL)
19419         load_partial_comp_unit (per_cu, per_objfile, nullptr);
19420
19421       cu = per_objfile->get_cu (per_cu);
19422
19423       cu->last_used = 0;
19424       pd = cu->find_partial_die (sect_off);
19425     }
19426
19427   /* If we didn't find it, and not all dies have been loaded,
19428      load them all and try again.  */
19429
19430   if (pd == NULL && cu->load_all_dies == 0)
19431     {
19432       cu->load_all_dies = 1;
19433
19434       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
19435          THIS_CU->cu may already be in use.  So we can't just free it and
19436          replace its DIEs with the ones we read in.  Instead, we leave those
19437          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
19438          and clobber THIS_CU->cu->partial_dies with the hash table for the new
19439          set.  */
19440       load_partial_comp_unit (cu->per_cu, per_objfile, cu);
19441
19442       pd = cu->find_partial_die (sect_off);
19443     }
19444
19445   if (pd == NULL)
19446     error (_("Dwarf Error: Cannot find DIE at %s [from module %s]\n"),
19447                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
19448   return { cu, pd };
19449 }
19450
19451 /* See if we can figure out if the class lives in a namespace.  We do
19452    this by looking for a member function; its demangled name will
19453    contain namespace info, if there is any.  */
19454
19455 static void
19456 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
19457                                   struct dwarf2_cu *cu)
19458 {
19459   /* NOTE: carlton/2003-10-07: Getting the info this way changes
19460      what template types look like, because the demangler
19461      frequently doesn't give the same name as the debug info.  We
19462      could fix this by only using the demangled name to get the
19463      prefix (but see comment in read_structure_type).  */
19464
19465   struct partial_die_info *real_pdi;
19466   struct partial_die_info *child_pdi;
19467
19468   /* If this DIE (this DIE's specification, if any) has a parent, then
19469      we should not do this.  We'll prepend the parent's fully qualified
19470      name when we create the partial symbol.  */
19471
19472   real_pdi = struct_pdi;
19473   while (real_pdi->has_specification)
19474     {
19475       auto res = find_partial_die (real_pdi->spec_offset,
19476                                    real_pdi->spec_is_dwz, cu);
19477       real_pdi = res.pdi;
19478       cu = res.cu;
19479     }
19480
19481   if (real_pdi->die_parent != NULL)
19482     return;
19483
19484   for (child_pdi = struct_pdi->die_child;
19485        child_pdi != NULL;
19486        child_pdi = child_pdi->die_sibling)
19487     {
19488       if (child_pdi->tag == DW_TAG_subprogram
19489           && child_pdi->linkage_name != NULL)
19490         {
19491           gdb::unique_xmalloc_ptr<char> actual_class_name
19492             (cu->language_defn->class_name_from_physname
19493              (child_pdi->linkage_name));
19494           if (actual_class_name != NULL)
19495             {
19496               struct objfile *objfile = cu->per_objfile->objfile;
19497               struct_pdi->raw_name = objfile->intern (actual_class_name.get ());
19498               struct_pdi->canonical_name = 1;
19499             }
19500           break;
19501         }
19502     }
19503 }
19504
19505 /* Return true if a DIE with TAG may have the DW_AT_const_value
19506    attribute.  */
19507
19508 static bool
19509 can_have_DW_AT_const_value_p (enum dwarf_tag tag)
19510 {
19511   switch (tag)
19512     {
19513     case DW_TAG_constant:
19514     case DW_TAG_enumerator:
19515     case DW_TAG_formal_parameter:
19516     case DW_TAG_template_value_param:
19517     case DW_TAG_variable:
19518       return true;
19519     }
19520
19521   return false;
19522 }
19523
19524 void
19525 partial_die_info::fixup (struct dwarf2_cu *cu)
19526 {
19527   /* Once we've fixed up a die, there's no point in doing so again.
19528      This also avoids a memory leak if we were to call
19529      guess_partial_die_structure_name multiple times.  */
19530   if (fixup_called)
19531     return;
19532
19533   /* If we found a reference attribute and the DIE has no name, try
19534      to find a name in the referred to DIE.  */
19535
19536   if (raw_name == NULL && has_specification)
19537     {
19538       struct partial_die_info *spec_die;
19539
19540       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
19541       spec_die = res.pdi;
19542       cu = res.cu;
19543
19544       spec_die->fixup (cu);
19545
19546       if (spec_die->raw_name)
19547         {
19548           raw_name = spec_die->raw_name;
19549           canonical_name = spec_die->canonical_name;
19550
19551           /* Copy DW_AT_external attribute if it is set.  */
19552           if (spec_die->is_external)
19553             is_external = spec_die->is_external;
19554         }
19555     }
19556
19557   if (!has_const_value && has_specification
19558       && can_have_DW_AT_const_value_p (tag))
19559     {
19560       struct partial_die_info *spec_die;
19561
19562       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
19563       spec_die = res.pdi;
19564       cu = res.cu;
19565
19566       spec_die->fixup (cu);
19567
19568       if (spec_die->has_const_value)
19569         {
19570           /* Copy DW_AT_const_value attribute if it is set.  */
19571           has_const_value = spec_die->has_const_value;
19572         }
19573     }
19574
19575   /* Set default names for some unnamed DIEs.  */
19576
19577   if (raw_name == NULL && tag == DW_TAG_namespace)
19578     {
19579       raw_name = CP_ANONYMOUS_NAMESPACE_STR;
19580       canonical_name = 1;
19581     }
19582
19583   /* If there is no parent die to provide a namespace, and there are
19584      children, see if we can determine the namespace from their linkage
19585      name.  */
19586   if (cu->per_cu->lang == language_cplus
19587       && !cu->per_objfile->per_bfd->types.empty ()
19588       && die_parent == NULL
19589       && has_children
19590       && (tag == DW_TAG_class_type
19591           || tag == DW_TAG_structure_type
19592           || tag == DW_TAG_union_type))
19593     guess_partial_die_structure_name (this, cu);
19594
19595   /* GCC might emit a nameless struct or union that has a linkage
19596      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19597   if (raw_name == NULL
19598       && (tag == DW_TAG_class_type
19599           || tag == DW_TAG_interface_type
19600           || tag == DW_TAG_structure_type
19601           || tag == DW_TAG_union_type)
19602       && linkage_name != NULL)
19603     {
19604       gdb::unique_xmalloc_ptr<char> demangled
19605         (gdb_demangle (linkage_name, DMGL_TYPES));
19606       if (demangled != nullptr)
19607         {
19608           const char *base;
19609
19610           /* Strip any leading namespaces/classes, keep only the base name.
19611              DW_AT_name for named DIEs does not contain the prefixes.  */
19612           base = strrchr (demangled.get (), ':');
19613           if (base && base > demangled.get () && base[-1] == ':')
19614             base++;
19615           else
19616             base = demangled.get ();
19617
19618           struct objfile *objfile = cu->per_objfile->objfile;
19619           raw_name = objfile->intern (base);
19620           canonical_name = 1;
19621         }
19622     }
19623
19624   fixup_called = 1;
19625 }
19626
19627 /* Read the .debug_loclists or .debug_rnglists header (they are the same format)
19628    contents from the given SECTION in the HEADER.
19629
19630    HEADER_OFFSET is the offset of the header in the section.  */
19631 static void
19632 read_loclists_rnglists_header (struct loclists_rnglists_header *header,
19633                                struct dwarf2_section_info *section,
19634                                sect_offset header_offset)
19635 {
19636   unsigned int bytes_read;
19637   bfd *abfd = section->get_bfd_owner ();
19638   const gdb_byte *info_ptr = section->buffer + to_underlying (header_offset);
19639
19640   header->length = read_initial_length (abfd, info_ptr, &bytes_read);
19641   info_ptr += bytes_read;
19642
19643   header->version = read_2_bytes (abfd, info_ptr);
19644   info_ptr += 2;
19645
19646   header->addr_size = read_1_byte (abfd, info_ptr);
19647   info_ptr += 1;
19648
19649   header->segment_collector_size = read_1_byte (abfd, info_ptr);
19650   info_ptr += 1;
19651
19652   header->offset_entry_count = read_4_bytes (abfd, info_ptr);
19653 }
19654
19655 /* Return the DW_AT_loclists_base value for the CU.  */
19656 static ULONGEST
19657 lookup_loclist_base (struct dwarf2_cu *cu)
19658 {
19659   /* For the .dwo unit, the loclist_base points to the first offset following
19660      the header. The header consists of the following entities-
19661      1. Unit Length (4 bytes for 32 bit DWARF format, and 12 bytes for the 64
19662          bit format)
19663      2. version (2 bytes)
19664      3. address size (1 byte)
19665      4. segment selector size (1 byte)
19666      5. offset entry count (4 bytes)
19667      These sizes are derived as per the DWARFv5 standard.  */
19668   if (cu->dwo_unit != nullptr)
19669     {
19670       if (cu->header.initial_length_size == 4)
19671          return LOCLIST_HEADER_SIZE32;
19672       return LOCLIST_HEADER_SIZE64;
19673     }
19674   return cu->loclist_base;
19675 }
19676
19677 /* Given a DW_FORM_loclistx value LOCLIST_INDEX, fetch the offset from the
19678    array of offsets in the .debug_loclists section.  */
19679
19680 static sect_offset
19681 read_loclist_index (struct dwarf2_cu *cu, ULONGEST loclist_index)
19682 {
19683   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19684   struct objfile *objfile = per_objfile->objfile;
19685   bfd *abfd = objfile->obfd;
19686   ULONGEST loclist_header_size =
19687     (cu->header.initial_length_size == 4 ? LOCLIST_HEADER_SIZE32
19688      : LOCLIST_HEADER_SIZE64);
19689   ULONGEST loclist_base = lookup_loclist_base (cu);
19690
19691   /* Offset in .debug_loclists of the offset for LOCLIST_INDEX.  */
19692   ULONGEST start_offset =
19693     loclist_base + loclist_index * cu->header.offset_size;
19694
19695   /* Get loclists section.  */
19696   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19697
19698   /* Read the loclists section content.  */
19699   section->read (objfile);
19700   if (section->buffer == NULL)
19701     error (_("DW_FORM_loclistx used without .debug_loclists "
19702              "section [in module %s]"), objfile_name (objfile));
19703
19704   /* DW_AT_loclists_base points after the .debug_loclists contribution header,
19705      so if loclist_base is smaller than the header size, we have a problem.  */
19706   if (loclist_base < loclist_header_size)
19707     error (_("DW_AT_loclists_base is smaller than header size [in module %s]"),
19708            objfile_name (objfile));
19709
19710   /* Read the header of the loclists contribution.  */
19711   struct loclists_rnglists_header header;
19712   read_loclists_rnglists_header (&header, section,
19713                                  (sect_offset) (loclist_base - loclist_header_size));
19714
19715   /* Verify the loclist index is valid.  */
19716   if (loclist_index >= header.offset_entry_count)
19717     error (_("DW_FORM_loclistx pointing outside of "
19718              ".debug_loclists offset array [in module %s]"),
19719            objfile_name (objfile));
19720
19721   /* Validate that reading won't go beyond the end of the section.  */
19722   if (start_offset + cu->header.offset_size > section->size)
19723     error (_("Reading DW_FORM_loclistx index beyond end of"
19724              ".debug_loclists section [in module %s]"),
19725            objfile_name (objfile));
19726
19727   const gdb_byte *info_ptr = section->buffer + start_offset;
19728
19729   if (cu->header.offset_size == 4)
19730     return (sect_offset) (bfd_get_32 (abfd, info_ptr) + loclist_base);
19731   else
19732     return (sect_offset) (bfd_get_64 (abfd, info_ptr) + loclist_base);
19733 }
19734
19735 /* Given a DW_FORM_rnglistx value RNGLIST_INDEX, fetch the offset from the
19736    array of offsets in the .debug_rnglists section.  */
19737
19738 static sect_offset
19739 read_rnglist_index (struct dwarf2_cu *cu, ULONGEST rnglist_index,
19740                     dwarf_tag tag)
19741 {
19742   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->per_objfile;
19743   struct objfile *objfile = dwarf2_per_objfile->objfile;
19744   bfd *abfd = objfile->obfd;
19745   ULONGEST rnglist_header_size =
19746     (cu->header.initial_length_size == 4 ? RNGLIST_HEADER_SIZE32
19747      : RNGLIST_HEADER_SIZE64);
19748
19749   /* When reading a DW_FORM_rnglistx from a DWO, we read from the DWO's
19750      .debug_rnglists.dwo section.  The rnglists base given in the skeleton
19751      doesn't apply.  */
19752   ULONGEST rnglist_base =
19753       (cu->dwo_unit != nullptr) ? rnglist_header_size : cu->rnglists_base;
19754
19755   /* Offset in .debug_rnglists of the offset for RNGLIST_INDEX.  */
19756   ULONGEST start_offset =
19757     rnglist_base + rnglist_index * cu->header.offset_size;
19758
19759   /* Get rnglists section.  */
19760   struct dwarf2_section_info *section = cu_debug_rnglists_section (cu, tag);
19761
19762   /* Read the rnglists section content.  */
19763   section->read (objfile);
19764   if (section->buffer == nullptr)
19765     error (_("DW_FORM_rnglistx used without .debug_rnglists section "
19766              "[in module %s]"),
19767            objfile_name (objfile));
19768
19769   /* DW_AT_rnglists_base points after the .debug_rnglists contribution header,
19770      so if rnglist_base is smaller than the header size, we have a problem.  */
19771   if (rnglist_base < rnglist_header_size)
19772     error (_("DW_AT_rnglists_base is smaller than header size [in module %s]"),
19773            objfile_name (objfile));
19774
19775   /* Read the header of the rnglists contribution.  */
19776   struct loclists_rnglists_header header;
19777   read_loclists_rnglists_header (&header, section,
19778                                  (sect_offset) (rnglist_base - rnglist_header_size));
19779
19780   /* Verify the rnglist index is valid.  */
19781   if (rnglist_index >= header.offset_entry_count)
19782     error (_("DW_FORM_rnglistx index pointing outside of "
19783              ".debug_rnglists offset array [in module %s]"),
19784            objfile_name (objfile));
19785
19786   /* Validate that reading won't go beyond the end of the section.  */
19787   if (start_offset + cu->header.offset_size > section->size)
19788     error (_("Reading DW_FORM_rnglistx index beyond end of"
19789              ".debug_rnglists section [in module %s]"),
19790            objfile_name (objfile));
19791
19792   const gdb_byte *info_ptr = section->buffer + start_offset;
19793
19794   if (cu->header.offset_size == 4)
19795     return (sect_offset) (read_4_bytes (abfd, info_ptr) + rnglist_base);
19796   else
19797     return (sect_offset) (read_8_bytes (abfd, info_ptr) + rnglist_base);
19798 }
19799
19800 /* Process the attributes that had to be skipped in the first round. These
19801    attributes are the ones that need str_offsets_base or addr_base attributes.
19802    They could not have been processed in the first round, because at the time
19803    the values of str_offsets_base or addr_base may not have been known.  */
19804 static void
19805 read_attribute_reprocess (const struct die_reader_specs *reader,
19806                           struct attribute *attr, dwarf_tag tag)
19807 {
19808   struct dwarf2_cu *cu = reader->cu;
19809   switch (attr->form)
19810     {
19811       case DW_FORM_addrx:
19812       case DW_FORM_GNU_addr_index:
19813         attr->set_address (read_addr_index (cu,
19814                                             attr->as_unsigned_reprocess ()));
19815         break;
19816       case DW_FORM_loclistx:
19817         {
19818           sect_offset loclists_sect_off
19819             = read_loclist_index (cu, attr->as_unsigned_reprocess ());
19820
19821           attr->set_unsigned (to_underlying (loclists_sect_off));
19822         }
19823         break;
19824       case DW_FORM_rnglistx:
19825         {
19826           sect_offset rnglists_sect_off
19827             = read_rnglist_index (cu, attr->as_unsigned_reprocess (), tag);
19828
19829           attr->set_unsigned (to_underlying (rnglists_sect_off));
19830         }
19831         break;
19832       case DW_FORM_strx:
19833       case DW_FORM_strx1:
19834       case DW_FORM_strx2:
19835       case DW_FORM_strx3:
19836       case DW_FORM_strx4:
19837       case DW_FORM_GNU_str_index:
19838         {
19839           unsigned int str_index = attr->as_unsigned_reprocess ();
19840           gdb_assert (!attr->canonical_string_p ());
19841           if (reader->dwo_file != NULL)
19842             attr->set_string_noncanonical (read_dwo_str_index (reader,
19843                                                                str_index));
19844           else
19845             attr->set_string_noncanonical (read_stub_str_index (cu,
19846                                                                 str_index));
19847           break;
19848         }
19849       default:
19850         gdb_assert_not_reached (_("Unexpected DWARF form."));
19851     }
19852 }
19853
19854 /* Read an attribute value described by an attribute form.  */
19855
19856 static const gdb_byte *
19857 read_attribute_value (const struct die_reader_specs *reader,
19858                       struct attribute *attr, unsigned form,
19859                       LONGEST implicit_const, const gdb_byte *info_ptr)
19860 {
19861   struct dwarf2_cu *cu = reader->cu;
19862   dwarf2_per_objfile *per_objfile = cu->per_objfile;
19863   struct objfile *objfile = per_objfile->objfile;
19864   bfd *abfd = reader->abfd;
19865   struct comp_unit_head *cu_header = &cu->header;
19866   unsigned int bytes_read;
19867   struct dwarf_block *blk;
19868
19869   attr->form = (enum dwarf_form) form;
19870   switch (form)
19871     {
19872     case DW_FORM_ref_addr:
19873       if (cu_header->version == 2)
19874         attr->set_unsigned (cu_header->read_address (abfd, info_ptr,
19875                                                      &bytes_read));
19876       else
19877         attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
19878                                                     &bytes_read));
19879       info_ptr += bytes_read;
19880       break;
19881     case DW_FORM_GNU_ref_alt:
19882       attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
19883                                                   &bytes_read));
19884       info_ptr += bytes_read;
19885       break;
19886     case DW_FORM_addr:
19887       {
19888         struct gdbarch *gdbarch = objfile->arch ();
19889         CORE_ADDR addr = cu_header->read_address (abfd, info_ptr, &bytes_read);
19890         addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr);
19891         attr->set_address (addr);
19892         info_ptr += bytes_read;
19893       }
19894       break;
19895     case DW_FORM_block2:
19896       blk = dwarf_alloc_block (cu);
19897       blk->size = read_2_bytes (abfd, info_ptr);
19898       info_ptr += 2;
19899       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19900       info_ptr += blk->size;
19901       attr->set_block (blk);
19902       break;
19903     case DW_FORM_block4:
19904       blk = dwarf_alloc_block (cu);
19905       blk->size = read_4_bytes (abfd, info_ptr);
19906       info_ptr += 4;
19907       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19908       info_ptr += blk->size;
19909       attr->set_block (blk);
19910       break;
19911     case DW_FORM_data2:
19912       attr->set_unsigned (read_2_bytes (abfd, info_ptr));
19913       info_ptr += 2;
19914       break;
19915     case DW_FORM_data4:
19916       attr->set_unsigned (read_4_bytes (abfd, info_ptr));
19917       info_ptr += 4;
19918       break;
19919     case DW_FORM_data8:
19920       attr->set_unsigned (read_8_bytes (abfd, info_ptr));
19921       info_ptr += 8;
19922       break;
19923     case DW_FORM_data16:
19924       blk = dwarf_alloc_block (cu);
19925       blk->size = 16;
19926       blk->data = read_n_bytes (abfd, info_ptr, 16);
19927       info_ptr += 16;
19928       attr->set_block (blk);
19929       break;
19930     case DW_FORM_sec_offset:
19931       attr->set_unsigned (cu_header->read_offset (abfd, info_ptr,
19932                                                   &bytes_read));
19933       info_ptr += bytes_read;
19934       break;
19935     case DW_FORM_loclistx:
19936       {
19937         attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
19938                                                             &bytes_read));
19939         info_ptr += bytes_read;
19940       }
19941       break;
19942     case DW_FORM_string:
19943       attr->set_string_noncanonical (read_direct_string (abfd, info_ptr,
19944                                                          &bytes_read));
19945       info_ptr += bytes_read;
19946       break;
19947     case DW_FORM_strp:
19948       if (!cu->per_cu->is_dwz)
19949         {
19950           attr->set_string_noncanonical
19951             (read_indirect_string (per_objfile,
19952                                    abfd, info_ptr, cu_header,
19953                                    &bytes_read));
19954           info_ptr += bytes_read;
19955           break;
19956         }
19957       /* FALLTHROUGH */
19958     case DW_FORM_line_strp:
19959       if (!cu->per_cu->is_dwz)
19960         {
19961           attr->set_string_noncanonical
19962             (per_objfile->read_line_string (info_ptr, cu_header,
19963                                             &bytes_read));
19964           info_ptr += bytes_read;
19965           break;
19966         }
19967       /* FALLTHROUGH */
19968     case DW_FORM_GNU_strp_alt:
19969       {
19970         dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd, true);
19971         LONGEST str_offset = cu_header->read_offset (abfd, info_ptr,
19972                                                      &bytes_read);
19973
19974         attr->set_string_noncanonical
19975           (dwz->read_string (objfile, str_offset));
19976         info_ptr += bytes_read;
19977       }
19978       break;
19979     case DW_FORM_exprloc:
19980     case DW_FORM_block:
19981       blk = dwarf_alloc_block (cu);
19982       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19983       info_ptr += bytes_read;
19984       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19985       info_ptr += blk->size;
19986       attr->set_block (blk);
19987       break;
19988     case DW_FORM_block1:
19989       blk = dwarf_alloc_block (cu);
19990       blk->size = read_1_byte (abfd, info_ptr);
19991       info_ptr += 1;
19992       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19993       info_ptr += blk->size;
19994       attr->set_block (blk);
19995       break;
19996     case DW_FORM_data1:
19997     case DW_FORM_flag:
19998       attr->set_unsigned (read_1_byte (abfd, info_ptr));
19999       info_ptr += 1;
20000       break;
20001     case DW_FORM_flag_present:
20002       attr->set_unsigned (1);
20003       break;
20004     case DW_FORM_sdata:
20005       attr->set_signed (read_signed_leb128 (abfd, info_ptr, &bytes_read));
20006       info_ptr += bytes_read;
20007       break;
20008     case DW_FORM_rnglistx:
20009       {
20010         attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
20011                                                             &bytes_read));
20012         info_ptr += bytes_read;
20013       }
20014       break;
20015     case DW_FORM_udata:
20016       attr->set_unsigned (read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
20017       info_ptr += bytes_read;
20018       break;
20019     case DW_FORM_ref1:
20020       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20021                            + read_1_byte (abfd, info_ptr)));
20022       info_ptr += 1;
20023       break;
20024     case DW_FORM_ref2:
20025       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20026                            + read_2_bytes (abfd, info_ptr)));
20027       info_ptr += 2;
20028       break;
20029     case DW_FORM_ref4:
20030       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20031                            + read_4_bytes (abfd, info_ptr)));
20032       info_ptr += 4;
20033       break;
20034     case DW_FORM_ref8:
20035       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20036                            + read_8_bytes (abfd, info_ptr)));
20037       info_ptr += 8;
20038       break;
20039     case DW_FORM_ref_sig8:
20040       attr->set_signature (read_8_bytes (abfd, info_ptr));
20041       info_ptr += 8;
20042       break;
20043     case DW_FORM_ref_udata:
20044       attr->set_unsigned ((to_underlying (cu_header->sect_off)
20045                            + read_unsigned_leb128 (abfd, info_ptr,
20046                                                    &bytes_read)));
20047       info_ptr += bytes_read;
20048       break;
20049     case DW_FORM_indirect:
20050       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
20051       info_ptr += bytes_read;
20052       if (form == DW_FORM_implicit_const)
20053         {
20054           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
20055           info_ptr += bytes_read;
20056         }
20057       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
20058                                        info_ptr);
20059       break;
20060     case DW_FORM_implicit_const:
20061       attr->set_signed (implicit_const);
20062       break;
20063     case DW_FORM_addrx:
20064     case DW_FORM_GNU_addr_index:
20065       attr->set_unsigned_reprocess (read_unsigned_leb128 (abfd, info_ptr,
20066                                                           &bytes_read));
20067       info_ptr += bytes_read;
20068       break;
20069     case DW_FORM_strx:
20070     case DW_FORM_strx1:
20071     case DW_FORM_strx2:
20072     case DW_FORM_strx3:
20073     case DW_FORM_strx4:
20074     case DW_FORM_GNU_str_index:
20075       {
20076         ULONGEST str_index;
20077         if (form == DW_FORM_strx1)
20078           {
20079             str_index = read_1_byte (abfd, info_ptr);
20080             info_ptr += 1;
20081           }
20082         else if (form == DW_FORM_strx2)
20083           {
20084             str_index = read_2_bytes (abfd, info_ptr);
20085             info_ptr += 2;
20086           }
20087         else if (form == DW_FORM_strx3)
20088           {
20089             str_index = read_3_bytes (abfd, info_ptr);
20090             info_ptr += 3;
20091           }
20092         else if (form == DW_FORM_strx4)
20093           {
20094             str_index = read_4_bytes (abfd, info_ptr);
20095             info_ptr += 4;
20096           }
20097         else
20098           {
20099             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
20100             info_ptr += bytes_read;
20101           }
20102         attr->set_unsigned_reprocess (str_index);
20103       }
20104       break;
20105     default:
20106       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
20107              dwarf_form_name (form),
20108              bfd_get_filename (abfd));
20109     }
20110
20111   /* Super hack.  */
20112   if (cu->per_cu->is_dwz && attr->form_is_ref ())
20113     attr->form = DW_FORM_GNU_ref_alt;
20114
20115   /* We have seen instances where the compiler tried to emit a byte
20116      size attribute of -1 which ended up being encoded as an unsigned
20117      0xffffffff.  Although 0xffffffff is technically a valid size value,
20118      an object of this size seems pretty unlikely so we can relatively
20119      safely treat these cases as if the size attribute was invalid and
20120      treat them as zero by default.  */
20121   if (attr->name == DW_AT_byte_size
20122       && form == DW_FORM_data4
20123       && attr->as_unsigned () >= 0xffffffff)
20124     {
20125       complaint
20126         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
20127          hex_string (attr->as_unsigned ()));
20128       attr->set_unsigned (0);
20129     }
20130
20131   return info_ptr;
20132 }
20133
20134 /* Read an attribute described by an abbreviated attribute.  */
20135
20136 static const gdb_byte *
20137 read_attribute (const struct die_reader_specs *reader,
20138                 struct attribute *attr, const struct attr_abbrev *abbrev,
20139                 const gdb_byte *info_ptr)
20140 {
20141   attr->name = abbrev->name;
20142   attr->string_is_canonical = 0;
20143   attr->requires_reprocessing = 0;
20144   return read_attribute_value (reader, attr, abbrev->form,
20145                                abbrev->implicit_const, info_ptr);
20146 }
20147
20148 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
20149
20150 static const char *
20151 read_indirect_string_at_offset (dwarf2_per_objfile *per_objfile,
20152                                 LONGEST str_offset)
20153 {
20154   return per_objfile->per_bfd->str.read_string (per_objfile->objfile,
20155                                                 str_offset, "DW_FORM_strp");
20156 }
20157
20158 /* Return pointer to string at .debug_str offset as read from BUF.
20159    BUF is assumed to be in a compilation unit described by CU_HEADER.
20160    Return *BYTES_READ_PTR count of bytes read from BUF.  */
20161
20162 static const char *
20163 read_indirect_string (dwarf2_per_objfile *per_objfile, bfd *abfd,
20164                       const gdb_byte *buf,
20165                       const struct comp_unit_head *cu_header,
20166                       unsigned int *bytes_read_ptr)
20167 {
20168   LONGEST str_offset = cu_header->read_offset (abfd, buf, bytes_read_ptr);
20169
20170   return read_indirect_string_at_offset (per_objfile, str_offset);
20171 }
20172
20173 /* See read.h.  */
20174
20175 const char *
20176 dwarf2_per_objfile::read_line_string (const gdb_byte *buf,
20177                                       const struct comp_unit_head *cu_header,
20178                                       unsigned int *bytes_read_ptr)
20179 {
20180   bfd *abfd = objfile->obfd;
20181   LONGEST str_offset = cu_header->read_offset (abfd, buf, bytes_read_ptr);
20182
20183   return per_bfd->line_str.read_string (objfile, str_offset, "DW_FORM_line_strp");
20184 }
20185
20186 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
20187    ADDR_BASE is the DW_AT_addr_base (DW_AT_GNU_addr_base) attribute or zero.
20188    ADDR_SIZE is the size of addresses from the CU header.  */
20189
20190 static CORE_ADDR
20191 read_addr_index_1 (dwarf2_per_objfile *per_objfile, unsigned int addr_index,
20192                    gdb::optional<ULONGEST> addr_base, int addr_size)
20193 {
20194   struct objfile *objfile = per_objfile->objfile;
20195   bfd *abfd = objfile->obfd;
20196   const gdb_byte *info_ptr;
20197   ULONGEST addr_base_or_zero = addr_base.has_value () ? *addr_base : 0;
20198
20199   per_objfile->per_bfd->addr.read (objfile);
20200   if (per_objfile->per_bfd->addr.buffer == NULL)
20201     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
20202            objfile_name (objfile));
20203   if (addr_base_or_zero + addr_index * addr_size
20204       >= per_objfile->per_bfd->addr.size)
20205     error (_("DW_FORM_addr_index pointing outside of "
20206              ".debug_addr section [in module %s]"),
20207            objfile_name (objfile));
20208   info_ptr = (per_objfile->per_bfd->addr.buffer + addr_base_or_zero
20209               + addr_index * addr_size);
20210   if (addr_size == 4)
20211     return bfd_get_32 (abfd, info_ptr);
20212   else
20213     return bfd_get_64 (abfd, info_ptr);
20214 }
20215
20216 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
20217
20218 static CORE_ADDR
20219 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
20220 {
20221   return read_addr_index_1 (cu->per_objfile, addr_index,
20222                             cu->addr_base, cu->header.addr_size);
20223 }
20224
20225 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
20226
20227 static CORE_ADDR
20228 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
20229                              unsigned int *bytes_read)
20230 {
20231   bfd *abfd = cu->per_objfile->objfile->obfd;
20232   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
20233
20234   return read_addr_index (cu, addr_index);
20235 }
20236
20237 /* See read.h.  */
20238
20239 CORE_ADDR
20240 dwarf2_read_addr_index (dwarf2_per_cu_data *per_cu,
20241                         dwarf2_per_objfile *per_objfile,
20242                         unsigned int addr_index)
20243 {
20244   struct dwarf2_cu *cu = per_objfile->get_cu (per_cu);
20245   gdb::optional<ULONGEST> addr_base;
20246   int addr_size;
20247
20248   /* We need addr_base and addr_size.
20249      If we don't have PER_CU->cu, we have to get it.
20250      Nasty, but the alternative is storing the needed info in PER_CU,
20251      which at this point doesn't seem justified: it's not clear how frequently
20252      it would get used and it would increase the size of every PER_CU.
20253      Entry points like dwarf2_per_cu_addr_size do a similar thing
20254      so we're not in uncharted territory here.
20255      Alas we need to be a bit more complicated as addr_base is contained
20256      in the DIE.
20257
20258      We don't need to read the entire CU(/TU).
20259      We just need the header and top level die.
20260
20261      IWBN to use the aging mechanism to let us lazily later discard the CU.
20262      For now we skip this optimization.  */
20263
20264   if (cu != NULL)
20265     {
20266       addr_base = cu->addr_base;
20267       addr_size = cu->header.addr_size;
20268     }
20269   else
20270     {
20271       cutu_reader reader (per_cu, per_objfile, nullptr, nullptr, false);
20272       addr_base = reader.cu->addr_base;
20273       addr_size = reader.cu->header.addr_size;
20274     }
20275
20276   return read_addr_index_1 (per_objfile, addr_index, addr_base, addr_size);
20277 }
20278
20279 /* Given a DW_FORM_GNU_str_index value STR_INDEX, fetch the string.
20280    STR_SECTION, STR_OFFSETS_SECTION can be from a Fission stub or a
20281    DWO file.  */
20282
20283 static const char *
20284 read_str_index (struct dwarf2_cu *cu,
20285                 struct dwarf2_section_info *str_section,
20286                 struct dwarf2_section_info *str_offsets_section,
20287                 ULONGEST str_offsets_base, ULONGEST str_index)
20288 {
20289   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20290   struct objfile *objfile = per_objfile->objfile;
20291   const char *objf_name = objfile_name (objfile);
20292   bfd *abfd = objfile->obfd;
20293   const gdb_byte *info_ptr;
20294   ULONGEST str_offset;
20295   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
20296
20297   str_section->read (objfile);
20298   str_offsets_section->read (objfile);
20299   if (str_section->buffer == NULL)
20300     error (_("%s used without %s section"
20301              " in CU at offset %s [in module %s]"),
20302            form_name, str_section->get_name (),
20303            sect_offset_str (cu->header.sect_off), objf_name);
20304   if (str_offsets_section->buffer == NULL)
20305     error (_("%s used without %s section"
20306              " in CU at offset %s [in module %s]"),
20307            form_name, str_section->get_name (),
20308            sect_offset_str (cu->header.sect_off), objf_name);
20309   info_ptr = (str_offsets_section->buffer
20310               + str_offsets_base
20311               + str_index * cu->header.offset_size);
20312   if (cu->header.offset_size == 4)
20313     str_offset = bfd_get_32 (abfd, info_ptr);
20314   else
20315     str_offset = bfd_get_64 (abfd, info_ptr);
20316   if (str_offset >= str_section->size)
20317     error (_("Offset from %s pointing outside of"
20318              " .debug_str.dwo section in CU at offset %s [in module %s]"),
20319            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20320   return (const char *) (str_section->buffer + str_offset);
20321 }
20322
20323 /* Given a DW_FORM_GNU_str_index from a DWO file, fetch the string.  */
20324
20325 static const char *
20326 read_dwo_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
20327 {
20328   ULONGEST str_offsets_base = reader->cu->header.version >= 5
20329                               ? reader->cu->header.addr_size : 0;
20330   return read_str_index (reader->cu,
20331                          &reader->dwo_file->sections.str,
20332                          &reader->dwo_file->sections.str_offsets,
20333                          str_offsets_base, str_index);
20334 }
20335
20336 /* Given a DW_FORM_GNU_str_index from a Fission stub, fetch the string.  */
20337
20338 static const char *
20339 read_stub_str_index (struct dwarf2_cu *cu, ULONGEST str_index)
20340 {
20341   struct objfile *objfile = cu->per_objfile->objfile;
20342   const char *objf_name = objfile_name (objfile);
20343   static const char form_name[] = "DW_FORM_GNU_str_index";
20344   static const char str_offsets_attr_name[] = "DW_AT_str_offsets";
20345
20346   if (!cu->str_offsets_base.has_value ())
20347     error (_("%s used in Fission stub without %s"
20348              " in CU at offset 0x%lx [in module %s]"),
20349            form_name, str_offsets_attr_name,
20350            (long) cu->header.offset_size, objf_name);
20351
20352   return read_str_index (cu,
20353                          &cu->per_objfile->per_bfd->str,
20354                          &cu->per_objfile->per_bfd->str_offsets,
20355                          *cu->str_offsets_base, str_index);
20356 }
20357
20358 /* Return the length of an LEB128 number in BUF.  */
20359
20360 static int
20361 leb128_size (const gdb_byte *buf)
20362 {
20363   const gdb_byte *begin = buf;
20364   gdb_byte byte;
20365
20366   while (1)
20367     {
20368       byte = *buf++;
20369       if ((byte & 128) == 0)
20370         return buf - begin;
20371     }
20372 }
20373
20374 static enum language
20375 dwarf_lang_to_enum_language (unsigned int lang)
20376 {
20377   enum language language;
20378
20379   switch (lang)
20380     {
20381     case DW_LANG_C89:
20382     case DW_LANG_C99:
20383     case DW_LANG_C11:
20384     case DW_LANG_C:
20385     case DW_LANG_UPC:
20386       language = language_c;
20387       break;
20388     case DW_LANG_Java:
20389     case DW_LANG_C_plus_plus:
20390     case DW_LANG_C_plus_plus_11:
20391     case DW_LANG_C_plus_plus_14:
20392       language = language_cplus;
20393       break;
20394     case DW_LANG_D:
20395       language = language_d;
20396       break;
20397     case DW_LANG_Fortran77:
20398     case DW_LANG_Fortran90:
20399     case DW_LANG_Fortran95:
20400     case DW_LANG_Fortran03:
20401     case DW_LANG_Fortran08:
20402       language = language_fortran;
20403       break;
20404     case DW_LANG_Go:
20405       language = language_go;
20406       break;
20407     case DW_LANG_Mips_Assembler:
20408       language = language_asm;
20409       break;
20410     case DW_LANG_Ada83:
20411     case DW_LANG_Ada95:
20412       language = language_ada;
20413       break;
20414     case DW_LANG_Modula2:
20415       language = language_m2;
20416       break;
20417     case DW_LANG_Pascal83:
20418       language = language_pascal;
20419       break;
20420     case DW_LANG_ObjC:
20421       language = language_objc;
20422       break;
20423     case DW_LANG_Rust:
20424     case DW_LANG_Rust_old:
20425       language = language_rust;
20426       break;
20427     case DW_LANG_OpenCL:
20428       language = language_opencl;
20429       break;
20430     case DW_LANG_Cobol74:
20431     case DW_LANG_Cobol85:
20432     default:
20433       language = language_minimal;
20434       break;
20435     }
20436
20437   return language;
20438 }
20439
20440 /* Return the named attribute or NULL if not there.  */
20441
20442 static struct attribute *
20443 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20444 {
20445   for (;;)
20446     {
20447       unsigned int i;
20448       struct attribute *spec = NULL;
20449
20450       for (i = 0; i < die->num_attrs; ++i)
20451         {
20452           if (die->attrs[i].name == name)
20453             return &die->attrs[i];
20454           if (die->attrs[i].name == DW_AT_specification
20455               || die->attrs[i].name == DW_AT_abstract_origin)
20456             spec = &die->attrs[i];
20457         }
20458
20459       if (!spec)
20460         break;
20461
20462       die = follow_die_ref (die, spec, &cu);
20463     }
20464
20465   return NULL;
20466 }
20467
20468 /* Return the string associated with a string-typed attribute, or NULL if it
20469    is either not found or is of an incorrect type.  */
20470
20471 static const char *
20472 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20473 {
20474   struct attribute *attr;
20475   const char *str = NULL;
20476
20477   attr = dwarf2_attr (die, name, cu);
20478
20479   if (attr != NULL)
20480     {
20481       str = attr->as_string ();
20482       if (str == nullptr)
20483         complaint (_("string type expected for attribute %s for "
20484                      "DIE at %s in module %s"),
20485                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
20486                    objfile_name (cu->per_objfile->objfile));
20487     }
20488
20489   return str;
20490 }
20491
20492 /* Return the dwo name or NULL if not present. If present, it is in either
20493    DW_AT_GNU_dwo_name or DW_AT_dwo_name attribute.  */
20494 static const char *
20495 dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu)
20496 {
20497   const char *dwo_name = dwarf2_string_attr (die, DW_AT_GNU_dwo_name, cu);
20498   if (dwo_name == nullptr)
20499     dwo_name = dwarf2_string_attr (die, DW_AT_dwo_name, cu);
20500   return dwo_name;
20501 }
20502
20503 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20504    and holds a non-zero value.  This function should only be used for
20505    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20506
20507 static int
20508 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20509 {
20510   struct attribute *attr = dwarf2_attr (die, name, cu);
20511
20512   return attr != nullptr && attr->as_boolean ();
20513 }
20514
20515 static int
20516 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20517 {
20518   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20519      which value is non-zero.  However, we have to be careful with
20520      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20521      (via dwarf2_flag_true_p) follows this attribute.  So we may
20522      end up accidently finding a declaration attribute that belongs
20523      to a different DIE referenced by the specification attribute,
20524      even though the given DIE does not have a declaration attribute.  */
20525   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20526           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20527 }
20528
20529 /* Return the die giving the specification for DIE, if there is
20530    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20531    containing the return value on output.  If there is no
20532    specification, but there is an abstract origin, that is
20533    returned.  */
20534
20535 static struct die_info *
20536 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20537 {
20538   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20539                                              *spec_cu);
20540
20541   if (spec_attr == NULL)
20542     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20543
20544   if (spec_attr == NULL)
20545     return NULL;
20546   else
20547     return follow_die_ref (die, spec_attr, spec_cu);
20548 }
20549
20550 /* A convenience function to find the proper .debug_line section for a CU.  */
20551
20552 static struct dwarf2_section_info *
20553 get_debug_line_section (struct dwarf2_cu *cu)
20554 {
20555   struct dwarf2_section_info *section;
20556   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20557
20558   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20559      DWO file.  */
20560   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20561     section = &cu->dwo_unit->dwo_file->sections.line;
20562   else if (cu->per_cu->is_dwz)
20563     {
20564       dwz_file *dwz = dwarf2_get_dwz_file (per_objfile->per_bfd, true);
20565
20566       section = &dwz->line;
20567     }
20568   else
20569     section = &per_objfile->per_bfd->line;
20570
20571   return section;
20572 }
20573
20574 /* Read the statement program header starting at OFFSET in
20575    .debug_line, or .debug_line.dwo.  Return a pointer
20576    to a struct line_header, allocated using xmalloc.
20577    Returns NULL if there is a problem reading the header, e.g., if it
20578    has a version we don't understand.
20579
20580    NOTE: the strings in the include directory and file name tables of
20581    the returned object point into the dwarf line section buffer,
20582    and must not be freed.  */
20583
20584 static line_header_up
20585 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20586 {
20587   struct dwarf2_section_info *section;
20588   dwarf2_per_objfile *per_objfile = cu->per_objfile;
20589
20590   section = get_debug_line_section (cu);
20591   section->read (per_objfile->objfile);
20592   if (section->buffer == NULL)
20593     {
20594       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20595         complaint (_("missing .debug_line.dwo section"));
20596       else
20597         complaint (_("missing .debug_line section"));
20598       return 0;
20599     }
20600
20601   return dwarf_decode_line_header (sect_off, cu->per_cu->is_dwz,
20602                                    per_objfile, section, &cu->header);
20603 }
20604
20605 /* Subroutine of dwarf_decode_lines to simplify it.
20606    Return the file name for the given file_entry.
20607    CU_INFO describes the CU's DW_AT_name and DW_AT_comp_dir.
20608    If space for the result is malloc'd, *NAME_HOLDER will be set.
20609    Returns NULL if FILE_INDEX should be ignored, i.e., it is
20610    equivalent to CU_INFO.  */
20611
20612 static const char *
20613 compute_include_file_name (const struct line_header *lh, const file_entry &fe,
20614                            const file_and_directory &cu_info,
20615                            gdb::unique_xmalloc_ptr<char> *name_holder)
20616 {
20617   const char *include_name = fe.name;
20618   const char *include_name_to_compare = include_name;
20619
20620   const char *dir_name = fe.include_dir (lh);
20621
20622   gdb::unique_xmalloc_ptr<char> hold_compare;
20623   if (!IS_ABSOLUTE_PATH (include_name)
20624       && (dir_name != NULL || cu_info.comp_dir != NULL))
20625     {
20626       /* Avoid creating a duplicate name for CU_INFO.
20627          We do this by comparing INCLUDE_NAME and CU_INFO.
20628          Before we do the comparison, however, we need to account
20629          for DIR_NAME and COMP_DIR.
20630          First prepend dir_name (if non-NULL).  If we still don't
20631          have an absolute path prepend comp_dir (if non-NULL).
20632          However, the directory we record in the include-file's
20633          psymtab does not contain COMP_DIR (to match the
20634          corresponding symtab(s)).
20635
20636          Example:
20637
20638          bash$ cd /tmp
20639          bash$ gcc -g ./hello.c
20640          include_name = "hello.c"
20641          dir_name = "."
20642          DW_AT_comp_dir = comp_dir = "/tmp"
20643          DW_AT_name = "./hello.c"
20644
20645       */
20646
20647       if (dir_name != NULL)
20648         {
20649           name_holder->reset (concat (dir_name, SLASH_STRING,
20650                                       include_name, (char *) NULL));
20651           include_name = name_holder->get ();
20652           include_name_to_compare = include_name;
20653         }
20654       if (!IS_ABSOLUTE_PATH (include_name) && cu_info.comp_dir != nullptr)
20655         {
20656           hold_compare.reset (concat (cu_info.comp_dir, SLASH_STRING,
20657                                       include_name, (char *) NULL));
20658           include_name_to_compare = hold_compare.get ();
20659         }
20660     }
20661
20662   gdb::unique_xmalloc_ptr<char> copied_name;
20663   const char *cu_filename = cu_info.name;
20664   if (!IS_ABSOLUTE_PATH (cu_filename) && cu_info.comp_dir != nullptr)
20665     {
20666       copied_name.reset (concat (cu_info.comp_dir, SLASH_STRING,
20667                                  cu_filename, (char *) NULL));
20668       cu_filename = copied_name.get ();
20669     }
20670
20671   if (FILENAME_CMP (include_name_to_compare, cu_filename) == 0)
20672     return nullptr;
20673   return include_name;
20674 }
20675
20676 /* State machine to track the state of the line number program.  */
20677
20678 class lnp_state_machine
20679 {
20680 public:
20681   /* Initialize a machine state for the start of a line number
20682      program.  */
20683   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20684                      bool record_lines_p);
20685
20686   file_entry *current_file ()
20687   {
20688     /* lh->file_names is 0-based, but the file name numbers in the
20689        statement program are 1-based.  */
20690     return m_line_header->file_name_at (m_file);
20691   }
20692
20693   /* Record the line in the state machine.  END_SEQUENCE is true if
20694      we're processing the end of a sequence.  */
20695   void record_line (bool end_sequence);
20696
20697   /* Check ADDRESS is -1, or zero and less than UNRELOCATED_LOWPC, and if true
20698      nop-out rest of the lines in this sequence.  */
20699   void check_line_address (struct dwarf2_cu *cu,
20700                            const gdb_byte *line_ptr,
20701                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20702
20703   void handle_set_discriminator (unsigned int discriminator)
20704   {
20705     m_discriminator = discriminator;
20706     m_line_has_non_zero_discriminator |= discriminator != 0;
20707   }
20708
20709   /* Handle DW_LNE_set_address.  */
20710   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20711   {
20712     m_op_index = 0;
20713     address += baseaddr;
20714     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20715   }
20716
20717   /* Handle DW_LNS_advance_pc.  */
20718   void handle_advance_pc (CORE_ADDR adjust);
20719
20720   /* Handle a special opcode.  */
20721   void handle_special_opcode (unsigned char op_code);
20722
20723   /* Handle DW_LNS_advance_line.  */
20724   void handle_advance_line (int line_delta)
20725   {
20726     advance_line (line_delta);
20727   }
20728
20729   /* Handle DW_LNS_set_file.  */
20730   void handle_set_file (file_name_index file);
20731
20732   /* Handle DW_LNS_negate_stmt.  */
20733   void handle_negate_stmt ()
20734   {
20735     m_is_stmt = !m_is_stmt;
20736   }
20737
20738   /* Handle DW_LNS_const_add_pc.  */
20739   void handle_const_add_pc ();
20740
20741   /* Handle DW_LNS_fixed_advance_pc.  */
20742   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20743   {
20744     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20745     m_op_index = 0;
20746   }
20747
20748   /* Handle DW_LNS_copy.  */
20749   void handle_copy ()
20750   {
20751     record_line (false);
20752     m_discriminator = 0;
20753   }
20754
20755   /* Handle DW_LNE_end_sequence.  */
20756   void handle_end_sequence ()
20757   {
20758     m_currently_recording_lines = true;
20759   }
20760
20761 private:
20762   /* Advance the line by LINE_DELTA.  */
20763   void advance_line (int line_delta)
20764   {
20765     m_line += line_delta;
20766
20767     if (line_delta != 0)
20768       m_line_has_non_zero_discriminator = m_discriminator != 0;
20769   }
20770
20771   struct dwarf2_cu *m_cu;
20772
20773   gdbarch *m_gdbarch;
20774
20775   /* True if we're recording lines.
20776      Otherwise we're building partial symtabs and are just interested in
20777      finding include files mentioned by the line number program.  */
20778   bool m_record_lines_p;
20779
20780   /* The line number header.  */
20781   line_header *m_line_header;
20782
20783   /* These are part of the standard DWARF line number state machine,
20784      and initialized according to the DWARF spec.  */
20785
20786   unsigned char m_op_index = 0;
20787   /* The line table index of the current file.  */
20788   file_name_index m_file = 1;
20789   unsigned int m_line = 1;
20790
20791   /* These are initialized in the constructor.  */
20792
20793   CORE_ADDR m_address;
20794   bool m_is_stmt;
20795   unsigned int m_discriminator;
20796
20797   /* Additional bits of state we need to track.  */
20798
20799   /* The last file that we called dwarf2_start_subfile for.
20800      This is only used for TLLs.  */
20801   unsigned int m_last_file = 0;
20802   /* The last file a line number was recorded for.  */
20803   struct subfile *m_last_subfile = NULL;
20804
20805   /* The address of the last line entry.  */
20806   CORE_ADDR m_last_address;
20807
20808   /* Set to true when a previous line at the same address (using
20809      m_last_address) had m_is_stmt true.  This is reset to false when a
20810      line entry at a new address (m_address different to m_last_address) is
20811      processed.  */
20812   bool m_stmt_at_address = false;
20813
20814   /* When true, record the lines we decode.  */
20815   bool m_currently_recording_lines = false;
20816
20817   /* The last line number that was recorded, used to coalesce
20818      consecutive entries for the same line.  This can happen, for
20819      example, when discriminators are present.  PR 17276.  */
20820   unsigned int m_last_line = 0;
20821   bool m_line_has_non_zero_discriminator = false;
20822 };
20823
20824 void
20825 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20826 {
20827   CORE_ADDR addr_adj = (((m_op_index + adjust)
20828                          / m_line_header->maximum_ops_per_instruction)
20829                         * m_line_header->minimum_instruction_length);
20830   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20831   m_op_index = ((m_op_index + adjust)
20832                 % m_line_header->maximum_ops_per_instruction);
20833 }
20834
20835 void
20836 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20837 {
20838   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20839   unsigned char adj_opcode_d = adj_opcode / m_line_header->line_range;
20840   unsigned char adj_opcode_r = adj_opcode % m_line_header->line_range;
20841   CORE_ADDR addr_adj = (((m_op_index + adj_opcode_d)
20842                          / m_line_header->maximum_ops_per_instruction)
20843                         * m_line_header->minimum_instruction_length);
20844   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20845   m_op_index = ((m_op_index + adj_opcode_d)
20846                 % m_line_header->maximum_ops_per_instruction);
20847
20848   int line_delta = m_line_header->line_base + adj_opcode_r;
20849   advance_line (line_delta);
20850   record_line (false);
20851   m_discriminator = 0;
20852 }
20853
20854 void
20855 lnp_state_machine::handle_set_file (file_name_index file)
20856 {
20857   m_file = file;
20858
20859   const file_entry *fe = current_file ();
20860   if (fe == NULL)
20861     dwarf2_debug_line_missing_file_complaint ();
20862   else if (m_record_lines_p)
20863     {
20864       const char *dir = fe->include_dir (m_line_header);
20865
20866       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20867       m_line_has_non_zero_discriminator = m_discriminator != 0;
20868       dwarf2_start_subfile (m_cu, fe->name, dir);
20869     }
20870 }
20871
20872 void
20873 lnp_state_machine::handle_const_add_pc ()
20874 {
20875   CORE_ADDR adjust
20876     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20877
20878   CORE_ADDR addr_adj
20879     = (((m_op_index + adjust)
20880         / m_line_header->maximum_ops_per_instruction)
20881        * m_line_header->minimum_instruction_length);
20882
20883   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20884   m_op_index = ((m_op_index + adjust)
20885                 % m_line_header->maximum_ops_per_instruction);
20886 }
20887
20888 /* Return non-zero if we should add LINE to the line number table.
20889    LINE is the line to add, LAST_LINE is the last line that was added,
20890    LAST_SUBFILE is the subfile for LAST_LINE.
20891    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20892    had a non-zero discriminator.
20893
20894    We have to be careful in the presence of discriminators.
20895    E.g., for this line:
20896
20897      for (i = 0; i < 100000; i++);
20898
20899    clang can emit four line number entries for that one line,
20900    each with a different discriminator.
20901    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20902
20903    However, we want gdb to coalesce all four entries into one.
20904    Otherwise the user could stepi into the middle of the line and
20905    gdb would get confused about whether the pc really was in the
20906    middle of the line.
20907
20908    Things are further complicated by the fact that two consecutive
20909    line number entries for the same line is a heuristic used by gcc
20910    to denote the end of the prologue.  So we can't just discard duplicate
20911    entries, we have to be selective about it.  The heuristic we use is
20912    that we only collapse consecutive entries for the same line if at least
20913    one of those entries has a non-zero discriminator.  PR 17276.
20914
20915    Note: Addresses in the line number state machine can never go backwards
20916    within one sequence, thus this coalescing is ok.  */
20917
20918 static int
20919 dwarf_record_line_p (struct dwarf2_cu *cu,
20920                      unsigned int line, unsigned int last_line,
20921                      int line_has_non_zero_discriminator,
20922                      struct subfile *last_subfile)
20923 {
20924   if (cu->get_builder ()->get_current_subfile () != last_subfile)
20925     return 1;
20926   if (line != last_line)
20927     return 1;
20928   /* Same line for the same file that we've seen already.
20929      As a last check, for pr 17276, only record the line if the line
20930      has never had a non-zero discriminator.  */
20931   if (!line_has_non_zero_discriminator)
20932     return 1;
20933   return 0;
20934 }
20935
20936 /* Use the CU's builder to record line number LINE beginning at
20937    address ADDRESS in the line table of subfile SUBFILE.  */
20938
20939 static void
20940 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20941                      unsigned int line, CORE_ADDR address, bool is_stmt,
20942                      struct dwarf2_cu *cu)
20943 {
20944   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20945
20946   if (dwarf_line_debug)
20947     {
20948       fprintf_unfiltered (gdb_stdlog,
20949                           "Recording line %u, file %s, address %s\n",
20950                           line, lbasename (subfile->name),
20951                           paddress (gdbarch, address));
20952     }
20953
20954   if (cu != nullptr)
20955     cu->get_builder ()->record_line (subfile, line, addr, is_stmt);
20956 }
20957
20958 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20959    Mark the end of a set of line number records.
20960    The arguments are the same as for dwarf_record_line_1.
20961    If SUBFILE is NULL the request is ignored.  */
20962
20963 static void
20964 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20965                    CORE_ADDR address, struct dwarf2_cu *cu)
20966 {
20967   if (subfile == NULL)
20968     return;
20969
20970   if (dwarf_line_debug)
20971     {
20972       fprintf_unfiltered (gdb_stdlog,
20973                           "Finishing current line, file %s, address %s\n",
20974                           lbasename (subfile->name),
20975                           paddress (gdbarch, address));
20976     }
20977
20978   dwarf_record_line_1 (gdbarch, subfile, 0, address, true, cu);
20979 }
20980
20981 void
20982 lnp_state_machine::record_line (bool end_sequence)
20983 {
20984   if (dwarf_line_debug)
20985     {
20986       fprintf_unfiltered (gdb_stdlog,
20987                           "Processing actual line %u: file %u,"
20988                           " address %s, is_stmt %u, discrim %u%s\n",
20989                           m_line, m_file,
20990                           paddress (m_gdbarch, m_address),
20991                           m_is_stmt, m_discriminator,
20992                           (end_sequence ? "\t(end sequence)" : ""));
20993     }
20994
20995   file_entry *fe = current_file ();
20996
20997   if (fe == NULL)
20998     dwarf2_debug_line_missing_file_complaint ();
20999   /* For now we ignore lines not starting on an instruction boundary.
21000      But not when processing end_sequence for compatibility with the
21001      previous version of the code.  */
21002   else if (m_op_index == 0 || end_sequence)
21003     {
21004       fe->included_p = true;
21005       if (m_record_lines_p)
21006         {
21007           /* When we switch files we insert an end maker in the first file,
21008              switch to the second file and add a new line entry.  The
21009              problem is that the end marker inserted in the first file will
21010              discard any previous line entries at the same address.  If the
21011              line entries in the first file are marked as is-stmt, while
21012              the new line in the second file is non-stmt, then this means
21013              the end marker will discard is-stmt lines so we can have a
21014              non-stmt line.  This means that there are less addresses at
21015              which the user can insert a breakpoint.
21016
21017              To improve this we track the last address in m_last_address,
21018              and whether we have seen an is-stmt at this address.  Then
21019              when switching files, if we have seen a stmt at the current
21020              address, and we are switching to create a non-stmt line, then
21021              discard the new line.  */
21022           bool file_changed
21023             = m_last_subfile != m_cu->get_builder ()->get_current_subfile ();
21024           bool ignore_this_line
21025            = ((file_changed && !end_sequence && m_last_address == m_address
21026                && !m_is_stmt && m_stmt_at_address)
21027               || (!end_sequence && m_line == 0));
21028
21029           if ((file_changed && !ignore_this_line) || end_sequence)
21030             {
21031               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
21032                                  m_currently_recording_lines ? m_cu : nullptr);
21033             }
21034
21035           if (!end_sequence && !ignore_this_line)
21036             {
21037               bool is_stmt = producer_is_codewarrior (m_cu) || m_is_stmt;
21038
21039               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
21040                                        m_line_has_non_zero_discriminator,
21041                                        m_last_subfile))
21042                 {
21043                   buildsym_compunit *builder = m_cu->get_builder ();
21044                   dwarf_record_line_1 (m_gdbarch,
21045                                        builder->get_current_subfile (),
21046                                        m_line, m_address, is_stmt,
21047                                        m_currently_recording_lines ? m_cu : nullptr);
21048                 }
21049               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
21050               m_last_line = m_line;
21051             }
21052         }
21053     }
21054
21055   /* Track whether we have seen any m_is_stmt true at m_address in case we
21056      have multiple line table entries all at m_address.  */
21057   if (m_last_address != m_address)
21058     {
21059       m_stmt_at_address = false;
21060       m_last_address = m_address;
21061     }
21062   m_stmt_at_address |= m_is_stmt;
21063 }
21064
21065 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
21066                                       line_header *lh, bool record_lines_p)
21067 {
21068   m_cu = cu;
21069   m_gdbarch = arch;
21070   m_record_lines_p = record_lines_p;
21071   m_line_header = lh;
21072
21073   m_currently_recording_lines = true;
21074
21075   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
21076      was a line entry for it so that the backend has a chance to adjust it
21077      and also record it in case it needs it.  This is currently used by MIPS
21078      code, cf. `mips_adjust_dwarf2_line'.  */
21079   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
21080   m_is_stmt = lh->default_is_stmt;
21081   m_discriminator = 0;
21082
21083   m_last_address = m_address;
21084   m_stmt_at_address = false;
21085 }
21086
21087 void
21088 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
21089                                        const gdb_byte *line_ptr,
21090                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
21091 {
21092   /* Linkers resolve a symbolic relocation referencing a GC'd function to 0 or
21093      -1.  If ADDRESS is 0, ignoring the opcode will err if the text section is
21094      located at 0x0.  In this case, additionally check that if
21095      ADDRESS < UNRELOCATED_LOWPC.  */
21096
21097   if ((address == 0 && address < unrelocated_lowpc)
21098       || address == (CORE_ADDR) -1)
21099     {
21100       /* This line table is for a function which has been
21101          GCd by the linker.  Ignore it.  PR gdb/12528 */
21102
21103       struct objfile *objfile = cu->per_objfile->objfile;
21104       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
21105
21106       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
21107                  line_offset, objfile_name (objfile));
21108       m_currently_recording_lines = false;
21109       /* Note: m_currently_recording_lines is left as false until we see
21110          DW_LNE_end_sequence.  */
21111     }
21112 }
21113
21114 /* Subroutine of dwarf_decode_lines to simplify it.
21115    Process the line number information in LH.
21116    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21117    program in order to set included_p for every referenced header.  */
21118
21119 static void
21120 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21121                       const int decode_for_pst_p, CORE_ADDR lowpc)
21122 {
21123   const gdb_byte *line_ptr, *extended_end;
21124   const gdb_byte *line_end;
21125   unsigned int bytes_read, extended_len;
21126   unsigned char op_code, extended_op;
21127   CORE_ADDR baseaddr;
21128   struct objfile *objfile = cu->per_objfile->objfile;
21129   bfd *abfd = objfile->obfd;
21130   struct gdbarch *gdbarch = objfile->arch ();
21131   /* True if we're recording line info (as opposed to building partial
21132      symtabs and just interested in finding include files mentioned by
21133      the line number program).  */
21134   bool record_lines_p = !decode_for_pst_p;
21135
21136   baseaddr = objfile->text_section_offset ();
21137
21138   line_ptr = lh->statement_program_start;
21139   line_end = lh->statement_program_end;
21140
21141   /* Read the statement sequences until there's nothing left.  */
21142   while (line_ptr < line_end)
21143     {
21144       /* The DWARF line number program state machine.  Reset the state
21145          machine at the start of each sequence.  */
21146       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
21147       bool end_sequence = false;
21148
21149       if (record_lines_p)
21150         {
21151           /* Start a subfile for the current file of the state
21152              machine.  */
21153           const file_entry *fe = state_machine.current_file ();
21154
21155           if (fe != NULL)
21156             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
21157         }
21158
21159       /* Decode the table.  */
21160       while (line_ptr < line_end && !end_sequence)
21161         {
21162           op_code = read_1_byte (abfd, line_ptr);
21163           line_ptr += 1;
21164
21165           if (op_code >= lh->opcode_base)
21166             {
21167               /* Special opcode.  */
21168               state_machine.handle_special_opcode (op_code);
21169             }
21170           else switch (op_code)
21171             {
21172             case DW_LNS_extended_op:
21173               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21174                                                    &bytes_read);
21175               line_ptr += bytes_read;
21176               extended_end = line_ptr + extended_len;
21177               extended_op = read_1_byte (abfd, line_ptr);
21178               line_ptr += 1;
21179               if (DW_LNE_lo_user <= extended_op
21180                   && extended_op <= DW_LNE_hi_user)
21181                 {
21182                   /* Vendor extension, ignore.  */
21183                   line_ptr = extended_end;
21184                   break;
21185                 }
21186               switch (extended_op)
21187                 {
21188                 case DW_LNE_end_sequence:
21189                   state_machine.handle_end_sequence ();
21190                   end_sequence = true;
21191                   break;
21192                 case DW_LNE_set_address:
21193                   {
21194                     CORE_ADDR address
21195                       = cu->header.read_address (abfd, line_ptr, &bytes_read);
21196                     line_ptr += bytes_read;
21197
21198                     state_machine.check_line_address (cu, line_ptr,
21199                                                       lowpc - baseaddr, address);
21200                     state_machine.handle_set_address (baseaddr, address);
21201                   }
21202                   break;
21203                 case DW_LNE_define_file:
21204                   {
21205                     const char *cur_file;
21206                     unsigned int mod_time, length;
21207                     dir_index dindex;
21208
21209                     cur_file = read_direct_string (abfd, line_ptr,
21210                                                    &bytes_read);
21211                     line_ptr += bytes_read;
21212                     dindex = (dir_index)
21213                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21214                     line_ptr += bytes_read;
21215                     mod_time =
21216                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21217                     line_ptr += bytes_read;
21218                     length =
21219                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21220                     line_ptr += bytes_read;
21221                     lh->add_file_name (cur_file, dindex, mod_time, length);
21222                   }
21223                   break;
21224                 case DW_LNE_set_discriminator:
21225                   {
21226                     /* The discriminator is not interesting to the
21227                        debugger; just ignore it.  We still need to
21228                        check its value though:
21229                        if there are consecutive entries for the same
21230                        (non-prologue) line we want to coalesce them.
21231                        PR 17276.  */
21232                     unsigned int discr
21233                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21234                     line_ptr += bytes_read;
21235
21236                     state_machine.handle_set_discriminator (discr);
21237                   }
21238                   break;
21239                 default:
21240                   complaint (_("mangled .debug_line section"));
21241                   return;
21242                 }
21243               /* Make sure that we parsed the extended op correctly.  If e.g.
21244                  we expected a different address size than the producer used,
21245                  we may have read the wrong number of bytes.  */
21246               if (line_ptr != extended_end)
21247                 {
21248                   complaint (_("mangled .debug_line section"));
21249                   return;
21250                 }
21251               break;
21252             case DW_LNS_copy:
21253               state_machine.handle_copy ();
21254               break;
21255             case DW_LNS_advance_pc:
21256               {
21257                 CORE_ADDR adjust
21258                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21259                 line_ptr += bytes_read;
21260
21261                 state_machine.handle_advance_pc (adjust);
21262               }
21263               break;
21264             case DW_LNS_advance_line:
21265               {
21266                 int line_delta
21267                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21268                 line_ptr += bytes_read;
21269
21270                 state_machine.handle_advance_line (line_delta);
21271               }
21272               break;
21273             case DW_LNS_set_file:
21274               {
21275                 file_name_index file
21276                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21277                                                             &bytes_read);
21278                 line_ptr += bytes_read;
21279
21280                 state_machine.handle_set_file (file);
21281               }
21282               break;
21283             case DW_LNS_set_column:
21284               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21285               line_ptr += bytes_read;
21286               break;
21287             case DW_LNS_negate_stmt:
21288               state_machine.handle_negate_stmt ();
21289               break;
21290             case DW_LNS_set_basic_block:
21291               break;
21292             /* Add to the address register of the state machine the
21293                address increment value corresponding to special opcode
21294                255.  I.e., this value is scaled by the minimum
21295                instruction length since special opcode 255 would have
21296                scaled the increment.  */
21297             case DW_LNS_const_add_pc:
21298               state_machine.handle_const_add_pc ();
21299               break;
21300             case DW_LNS_fixed_advance_pc:
21301               {
21302                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21303                 line_ptr += 2;
21304
21305                 state_machine.handle_fixed_advance_pc (addr_adj);
21306               }
21307               break;
21308             default:
21309               {
21310                 /* Unknown standard opcode, ignore it.  */
21311                 int i;
21312
21313                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21314                   {
21315                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21316                     line_ptr += bytes_read;
21317                   }
21318               }
21319             }
21320         }
21321
21322       if (!end_sequence)
21323         dwarf2_debug_line_missing_end_sequence_complaint ();
21324
21325       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21326          in which case we still finish recording the last line).  */
21327       state_machine.record_line (true);
21328     }
21329 }
21330
21331 /* Decode the Line Number Program (LNP) for the given line_header
21332    structure and CU.  The actual information extracted and the type
21333    of structures created from the LNP depends on the value of PST.
21334
21335    1. If PST is NULL, then this procedure uses the data from the program
21336       to create all necessary symbol tables, and their linetables.
21337
21338    2. If PST is not NULL, this procedure reads the program to determine
21339       the list of files included by the unit represented by PST, and
21340       builds all the associated partial symbol tables.
21341
21342    FND holds the CU file name and directory, if known.
21343    It is used for relative paths in the line table.
21344
21345    NOTE: It is important that psymtabs have the same file name (via
21346    strcmp) as the corresponding symtab.  Since the directory is not
21347    used in the name of the symtab we don't use it in the name of the
21348    psymtabs we create.  E.g. expand_line_sal requires this when
21349    finding psymtabs to expand.  A good testcase for this is
21350    mb-inline.exp.
21351
21352    LOWPC is the lowest address in CU (or 0 if not known).
21353
21354    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21355    for its PC<->lines mapping information.  Otherwise only the filename
21356    table is read in.  */
21357
21358 static void
21359 dwarf_decode_lines (struct line_header *lh, const file_and_directory &fnd,
21360                     struct dwarf2_cu *cu, dwarf2_psymtab *pst,
21361                     CORE_ADDR lowpc, int decode_mapping)
21362 {
21363   struct objfile *objfile = cu->per_objfile->objfile;
21364   const int decode_for_pst_p = (pst != NULL);
21365
21366   if (decode_mapping)
21367     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21368
21369   if (decode_for_pst_p)
21370     {
21371       /* Now that we're done scanning the Line Header Program, we can
21372          create the psymtab of each included file.  */
21373       for (auto &file_entry : lh->file_names ())
21374         if (file_entry.included_p)
21375           {
21376             gdb::unique_xmalloc_ptr<char> name_holder;
21377             const char *include_name =
21378               compute_include_file_name (lh, file_entry, fnd, &name_holder);
21379             if (include_name != NULL)
21380               dwarf2_create_include_psymtab
21381                 (cu->per_objfile->per_bfd, include_name, pst,
21382                  cu->per_objfile->per_bfd->partial_symtabs.get (),
21383                  objfile->per_bfd);
21384           }
21385     }
21386   else
21387     {
21388       /* Make sure a symtab is created for every file, even files
21389          which contain only variables (i.e. no code with associated
21390          line numbers).  */
21391       buildsym_compunit *builder = cu->get_builder ();
21392       struct compunit_symtab *cust = builder->get_compunit_symtab ();
21393
21394       for (auto &fe : lh->file_names ())
21395         {
21396           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21397           if (builder->get_current_subfile ()->symtab == NULL)
21398             {
21399               builder->get_current_subfile ()->symtab
21400                 = allocate_symtab (cust,
21401                                    builder->get_current_subfile ()->name);
21402             }
21403           fe.symtab = builder->get_current_subfile ()->symtab;
21404         }
21405     }
21406 }
21407
21408 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21409    DIRNAME the name of the source directory which contains FILENAME
21410    or NULL if not known.
21411    This routine tries to keep line numbers from identical absolute and
21412    relative file names in a common subfile.
21413
21414    Using the `list' example from the GDB testsuite, which resides in
21415    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21416    of /srcdir/list0.c yields the following debugging information for list0.c:
21417
21418    DW_AT_name:          /srcdir/list0.c
21419    DW_AT_comp_dir:      /compdir
21420    files.files[0].name: list0.h
21421    files.files[0].dir:  /srcdir
21422    files.files[1].name: list0.c
21423    files.files[1].dir:  /srcdir
21424
21425    The line number information for list0.c has to end up in a single
21426    subfile, so that `break /srcdir/list0.c:1' works as expected.
21427    start_subfile will ensure that this happens provided that we pass the
21428    concatenation of files.files[1].dir and files.files[1].name as the
21429    subfile's name.  */
21430
21431 static void
21432 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21433                       const char *dirname)
21434 {
21435   gdb::unique_xmalloc_ptr<char> copy;
21436
21437   /* In order not to lose the line information directory,
21438      we concatenate it to the filename when it makes sense.
21439      Note that the Dwarf3 standard says (speaking of filenames in line
21440      information): ``The directory index is ignored for file names
21441      that represent full path names''.  Thus ignoring dirname in the
21442      `else' branch below isn't an issue.  */
21443
21444   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21445     {
21446       copy.reset (concat (dirname, SLASH_STRING, filename, (char *) NULL));
21447       filename = copy.get ();
21448     }
21449
21450   cu->get_builder ()->start_subfile (filename);
21451 }
21452
21453 static void
21454 var_decode_location (struct attribute *attr, struct symbol *sym,
21455                      struct dwarf2_cu *cu)
21456 {
21457   struct objfile *objfile = cu->per_objfile->objfile;
21458   struct comp_unit_head *cu_header = &cu->header;
21459
21460   /* NOTE drow/2003-01-30: There used to be a comment and some special
21461      code here to turn a symbol with DW_AT_external and a
21462      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21463      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21464      with some versions of binutils) where shared libraries could have
21465      relocations against symbols in their debug information - the
21466      minimal symbol would have the right address, but the debug info
21467      would not.  It's no longer necessary, because we will explicitly
21468      apply relocations when we read in the debug information now.  */
21469
21470   /* A DW_AT_location attribute with no contents indicates that a
21471      variable has been optimized away.  */
21472   if (attr->form_is_block () && attr->as_block ()->size == 0)
21473     {
21474       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21475       return;
21476     }
21477
21478   /* Handle one degenerate form of location expression specially, to
21479      preserve GDB's previous behavior when section offsets are
21480      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
21481      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
21482
21483   if (attr->form_is_block ())
21484     {
21485       struct dwarf_block *block = attr->as_block ();
21486
21487       if ((block->data[0] == DW_OP_addr
21488            && block->size == 1 + cu_header->addr_size)
21489           || ((block->data[0] == DW_OP_GNU_addr_index
21490                || block->data[0] == DW_OP_addrx)
21491               && (block->size
21492                   == 1 + leb128_size (&block->data[1]))))
21493         {
21494           unsigned int dummy;
21495
21496           if (block->data[0] == DW_OP_addr)
21497             SET_SYMBOL_VALUE_ADDRESS
21498               (sym, cu->header.read_address (objfile->obfd,
21499                                              block->data + 1,
21500                                              &dummy));
21501           else
21502             SET_SYMBOL_VALUE_ADDRESS
21503               (sym, read_addr_index_from_leb128 (cu, block->data + 1,
21504                                                  &dummy));
21505           SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21506           fixup_symbol_section (sym, objfile);
21507           SET_SYMBOL_VALUE_ADDRESS
21508             (sym,
21509              SYMBOL_VALUE_ADDRESS (sym)
21510              + objfile->section_offsets[sym->section_index ()]);
21511           return;
21512         }
21513     }
21514
21515   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21516      expression evaluator, and use LOC_COMPUTED only when necessary
21517      (i.e. when the value of a register or memory location is
21518      referenced, or a thread-local block, etc.).  Then again, it might
21519      not be worthwhile.  I'm assuming that it isn't unless performance
21520      or memory numbers show me otherwise.  */
21521
21522   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21523
21524   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21525     cu->has_loclist = true;
21526 }
21527
21528 /* Given a pointer to a DWARF information entry, figure out if we need
21529    to make a symbol table entry for it, and if so, create a new entry
21530    and return a pointer to it.
21531    If TYPE is NULL, determine symbol type from the die, otherwise
21532    used the passed type.
21533    If SPACE is not NULL, use it to hold the new symbol.  If it is
21534    NULL, allocate a new symbol on the objfile's obstack.  */
21535
21536 static struct symbol *
21537 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21538             struct symbol *space)
21539 {
21540   dwarf2_per_objfile *per_objfile = cu->per_objfile;
21541   struct objfile *objfile = per_objfile->objfile;
21542   struct gdbarch *gdbarch = objfile->arch ();
21543   struct symbol *sym = NULL;
21544   const char *name;
21545   struct attribute *attr = NULL;
21546   struct attribute *attr2 = NULL;
21547   CORE_ADDR baseaddr;
21548   struct pending **list_to_add = NULL;
21549
21550   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21551
21552   baseaddr = objfile->text_section_offset ();
21553
21554   name = dwarf2_name (die, cu);
21555   if (name)
21556     {
21557       int suppress_add = 0;
21558
21559       if (space)
21560         sym = space;
21561       else
21562         sym = new (&objfile->objfile_obstack) symbol;
21563       OBJSTAT (objfile, n_syms++);
21564
21565       /* Cache this symbol's name and the name's demangled form (if any).  */
21566       sym->set_language (cu->per_cu->lang, &objfile->objfile_obstack);
21567       /* Fortran does not have mangling standard and the mangling does differ
21568          between gfortran, iFort etc.  */
21569       const char *physname
21570         = (cu->per_cu->lang == language_fortran
21571            ? dwarf2_full_name (name, die, cu)
21572            : dwarf2_physname (name, die, cu));
21573       const char *linkagename = dw2_linkage_name (die, cu);
21574
21575       if (linkagename == nullptr || cu->per_cu->lang == language_ada)
21576         sym->set_linkage_name (physname);
21577       else
21578         {
21579           sym->set_demangled_name (physname, &objfile->objfile_obstack);
21580           sym->set_linkage_name (linkagename);
21581         }
21582
21583       /* Default assumptions.
21584          Use the passed type or decode it from the die.  */
21585       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21586       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21587       if (type != NULL)
21588         SYMBOL_TYPE (sym) = type;
21589       else
21590         SYMBOL_TYPE (sym) = die_type (die, cu);
21591       attr = dwarf2_attr (die,
21592                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21593                           cu);
21594       if (attr != nullptr)
21595         SYMBOL_LINE (sym) = attr->constant_value (0);
21596
21597       attr = dwarf2_attr (die,
21598                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21599                           cu);
21600       if (attr != nullptr && attr->is_nonnegative ())
21601         {
21602           file_name_index file_index
21603             = (file_name_index) attr->as_nonnegative ();
21604           struct file_entry *fe;
21605
21606           if (cu->line_header != NULL)
21607             fe = cu->line_header->file_name_at (file_index);
21608           else
21609             fe = NULL;
21610
21611           if (fe == NULL)
21612             complaint (_("file index out of range"));
21613           else
21614             symbol_set_symtab (sym, fe->symtab);
21615         }
21616
21617       switch (die->tag)
21618         {
21619         case DW_TAG_label:
21620           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21621           if (attr != nullptr)
21622             {
21623               CORE_ADDR addr;
21624
21625               addr = attr->as_address ();
21626               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21627               SET_SYMBOL_VALUE_ADDRESS (sym, addr);
21628               SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21629             }
21630           else
21631             SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21632           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21633           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21634           add_symbol_to_list (sym, cu->list_in_scope);
21635           break;
21636         case DW_TAG_subprogram:
21637           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21638              finish_block.  */
21639           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21640           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21641           if ((attr2 != nullptr && attr2->as_boolean ())
21642               || cu->per_cu->lang == language_ada
21643               || cu->per_cu->lang == language_fortran)
21644             {
21645               /* Subprograms marked external are stored as a global symbol.
21646                  Ada and Fortran subprograms, whether marked external or
21647                  not, are always stored as a global symbol, because we want
21648                  to be able to access them globally.  For instance, we want
21649                  to be able to break on a nested subprogram without having
21650                  to specify the context.  */
21651               list_to_add = cu->get_builder ()->get_global_symbols ();
21652             }
21653           else
21654             {
21655               list_to_add = cu->list_in_scope;
21656             }
21657           break;
21658         case DW_TAG_inlined_subroutine:
21659           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21660              finish_block.  */
21661           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21662           SYMBOL_INLINED (sym) = 1;
21663           list_to_add = cu->list_in_scope;
21664           break;
21665         case DW_TAG_template_value_param:
21666           suppress_add = 1;
21667           /* Fall through.  */
21668         case DW_TAG_constant:
21669         case DW_TAG_variable:
21670         case DW_TAG_member:
21671           /* Compilation with minimal debug info may result in
21672              variables with missing type entries.  Change the
21673              misleading `void' type to something sensible.  */
21674           if (SYMBOL_TYPE (sym)->code () == TYPE_CODE_VOID)
21675             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21676
21677           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21678           /* In the case of DW_TAG_member, we should only be called for
21679              static const members.  */
21680           if (die->tag == DW_TAG_member)
21681             {
21682               /* dwarf2_add_field uses die_is_declaration,
21683                  so we do the same.  */
21684               gdb_assert (die_is_declaration (die, cu));
21685               gdb_assert (attr);
21686             }
21687           if (attr != nullptr)
21688             {
21689               dwarf2_const_value (attr, sym, cu);
21690               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21691               if (!suppress_add)
21692                 {
21693                   if (attr2 != nullptr && attr2->as_boolean ())
21694                     list_to_add = cu->get_builder ()->get_global_symbols ();
21695                   else
21696                     list_to_add = cu->list_in_scope;
21697                 }
21698               break;
21699             }
21700           attr = dwarf2_attr (die, DW_AT_location, cu);
21701           if (attr != nullptr)
21702             {
21703               var_decode_location (attr, sym, cu);
21704               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21705
21706               /* Fortran explicitly imports any global symbols to the local
21707                  scope by DW_TAG_common_block.  */
21708               if (cu->per_cu->lang == language_fortran && die->parent
21709                   && die->parent->tag == DW_TAG_common_block)
21710                 attr2 = NULL;
21711
21712               if (SYMBOL_CLASS (sym) == LOC_STATIC
21713                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21714                   && !per_objfile->per_bfd->has_section_at_zero)
21715                 {
21716                   /* When a static variable is eliminated by the linker,
21717                      the corresponding debug information is not stripped
21718                      out, but the variable address is set to null;
21719                      do not add such variables into symbol table.  */
21720                 }
21721               else if (attr2 != nullptr && attr2->as_boolean ())
21722                 {
21723                   if (SYMBOL_CLASS (sym) == LOC_STATIC
21724                       && (objfile->flags & OBJF_MAINLINE) == 0
21725                       && per_objfile->per_bfd->can_copy)
21726                     {
21727                       /* A global static variable might be subject to
21728                          copy relocation.  We first check for a local
21729                          minsym, though, because maybe the symbol was
21730                          marked hidden, in which case this would not
21731                          apply.  */
21732                       bound_minimal_symbol found
21733                         = (lookup_minimal_symbol_linkage
21734                            (sym->linkage_name (), objfile));
21735                       if (found.minsym != nullptr)
21736                         sym->maybe_copied = 1;
21737                     }
21738
21739                   /* A variable with DW_AT_external is never static,
21740                      but it may be block-scoped.  */
21741                   list_to_add
21742                     = ((cu->list_in_scope
21743                         == cu->get_builder ()->get_file_symbols ())
21744                        ? cu->get_builder ()->get_global_symbols ()
21745                        : cu->list_in_scope);
21746                 }
21747               else
21748                 list_to_add = cu->list_in_scope;
21749             }
21750           else
21751             {
21752               /* We do not know the address of this symbol.
21753                  If it is an external symbol and we have type information
21754                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21755                  The address of the variable will then be determined from
21756                  the minimal symbol table whenever the variable is
21757                  referenced.  */
21758               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21759
21760               /* Fortran explicitly imports any global symbols to the local
21761                  scope by DW_TAG_common_block.  */
21762               if (cu->per_cu->lang == language_fortran && die->parent
21763                   && die->parent->tag == DW_TAG_common_block)
21764                 {
21765                   /* SYMBOL_CLASS doesn't matter here because
21766                      read_common_block is going to reset it.  */
21767                   if (!suppress_add)
21768                     list_to_add = cu->list_in_scope;
21769                 }
21770               else if (attr2 != nullptr && attr2->as_boolean ()
21771                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21772                 {
21773                   /* A variable with DW_AT_external is never static, but it
21774                      may be block-scoped.  */
21775                   list_to_add
21776                     = ((cu->list_in_scope
21777                         == cu->get_builder ()->get_file_symbols ())
21778                        ? cu->get_builder ()->get_global_symbols ()
21779                        : cu->list_in_scope);
21780
21781                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21782                 }
21783               else if (!die_is_declaration (die, cu))
21784                 {
21785                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21786                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21787                   if (!suppress_add)
21788                     list_to_add = cu->list_in_scope;
21789                 }
21790             }
21791           break;
21792         case DW_TAG_formal_parameter:
21793           {
21794             /* If we are inside a function, mark this as an argument.  If
21795                not, we might be looking at an argument to an inlined function
21796                when we do not have enough information to show inlined frames;
21797                pretend it's a local variable in that case so that the user can
21798                still see it.  */
21799             struct context_stack *curr
21800               = cu->get_builder ()->get_current_context_stack ();
21801             if (curr != nullptr && curr->name != nullptr)
21802               SYMBOL_IS_ARGUMENT (sym) = 1;
21803             attr = dwarf2_attr (die, DW_AT_location, cu);
21804             if (attr != nullptr)
21805               {
21806                 var_decode_location (attr, sym, cu);
21807               }
21808             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21809             if (attr != nullptr)
21810               {
21811                 dwarf2_const_value (attr, sym, cu);
21812               }
21813
21814             list_to_add = cu->list_in_scope;
21815           }
21816           break;
21817         case DW_TAG_unspecified_parameters:
21818           /* From varargs functions; gdb doesn't seem to have any
21819              interest in this information, so just ignore it for now.
21820              (FIXME?) */
21821           break;
21822         case DW_TAG_template_type_param:
21823           suppress_add = 1;
21824           /* Fall through.  */
21825         case DW_TAG_class_type:
21826         case DW_TAG_interface_type:
21827         case DW_TAG_structure_type:
21828         case DW_TAG_union_type:
21829         case DW_TAG_set_type:
21830         case DW_TAG_enumeration_type:
21831           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21832           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21833
21834           {
21835             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21836                really ever be static objects: otherwise, if you try
21837                to, say, break of a class's method and you're in a file
21838                which doesn't mention that class, it won't work unless
21839                the check for all static symbols in lookup_symbol_aux
21840                saves you.  See the OtherFileClass tests in
21841                gdb.c++/namespace.exp.  */
21842
21843             if (!suppress_add)
21844               {
21845                 buildsym_compunit *builder = cu->get_builder ();
21846                 list_to_add
21847                   = (cu->list_in_scope == builder->get_file_symbols ()
21848                      && cu->per_cu->lang == language_cplus
21849                      ? builder->get_global_symbols ()
21850                      : cu->list_in_scope);
21851
21852                 /* The semantics of C++ state that "struct foo {
21853                    ... }" also defines a typedef for "foo".  */
21854                 if (cu->per_cu->lang == language_cplus
21855                     || cu->per_cu->lang == language_ada
21856                     || cu->per_cu->lang == language_d
21857                     || cu->per_cu->lang == language_rust)
21858                   {
21859                     /* The symbol's name is already allocated along
21860                        with this objfile, so we don't need to
21861                        duplicate it for the type.  */
21862                     if (SYMBOL_TYPE (sym)->name () == 0)
21863                       SYMBOL_TYPE (sym)->set_name (sym->search_name ());
21864                   }
21865               }
21866           }
21867           break;
21868         case DW_TAG_typedef:
21869           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21870           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21871           list_to_add = cu->list_in_scope;
21872           break;
21873         case DW_TAG_array_type:
21874         case DW_TAG_base_type:
21875         case DW_TAG_subrange_type:
21876           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21877           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21878           list_to_add = cu->list_in_scope;
21879           break;
21880         case DW_TAG_enumerator:
21881           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21882           if (attr != nullptr)
21883             {
21884               dwarf2_const_value (attr, sym, cu);
21885             }
21886           {
21887             /* NOTE: carlton/2003-11-10: See comment above in the
21888                DW_TAG_class_type, etc. block.  */
21889
21890             list_to_add
21891               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
21892                  && cu->per_cu->lang == language_cplus
21893                  ? cu->get_builder ()->get_global_symbols ()
21894                  : cu->list_in_scope);
21895           }
21896           break;
21897         case DW_TAG_imported_declaration:
21898         case DW_TAG_namespace:
21899           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21900           list_to_add = cu->get_builder ()->get_global_symbols ();
21901           break;
21902         case DW_TAG_module:
21903           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21904           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21905           list_to_add = cu->get_builder ()->get_global_symbols ();
21906           break;
21907         case DW_TAG_common_block:
21908           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21909           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21910           add_symbol_to_list (sym, cu->list_in_scope);
21911           break;
21912         default:
21913           /* Not a tag we recognize.  Hopefully we aren't processing
21914              trash data, but since we must specifically ignore things
21915              we don't recognize, there is nothing else we should do at
21916              this point.  */
21917           complaint (_("unsupported tag: '%s'"),
21918                      dwarf_tag_name (die->tag));
21919           break;
21920         }
21921
21922       if (suppress_add)
21923         {
21924           sym->hash_next = objfile->template_symbols;
21925           objfile->template_symbols = sym;
21926           list_to_add = NULL;
21927         }
21928
21929       if (list_to_add != NULL)
21930         add_symbol_to_list (sym, list_to_add);
21931
21932       /* For the benefit of old versions of GCC, check for anonymous
21933          namespaces based on the demangled name.  */
21934       if (!cu->processing_has_namespace_info
21935           && cu->per_cu->lang == language_cplus)
21936         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
21937     }
21938   return (sym);
21939 }
21940
21941 /* Given an attr with a DW_FORM_dataN value in host byte order,
21942    zero-extend it as appropriate for the symbol's type.  The DWARF
21943    standard (v4) is not entirely clear about the meaning of using
21944    DW_FORM_dataN for a constant with a signed type, where the type is
21945    wider than the data.  The conclusion of a discussion on the DWARF
21946    list was that this is unspecified.  We choose to always zero-extend
21947    because that is the interpretation long in use by GCC.  */
21948
21949 static gdb_byte *
21950 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21951                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21952 {
21953   struct objfile *objfile = cu->per_objfile->objfile;
21954   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21955                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21956   LONGEST l = attr->constant_value (0);
21957
21958   if (bits < sizeof (*value) * 8)
21959     {
21960       l &= ((LONGEST) 1 << bits) - 1;
21961       *value = l;
21962     }
21963   else if (bits == sizeof (*value) * 8)
21964     *value = l;
21965   else
21966     {
21967       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21968       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21969       return bytes;
21970     }
21971
21972   return NULL;
21973 }
21974
21975 /* Read a constant value from an attribute.  Either set *VALUE, or if
21976    the value does not fit in *VALUE, set *BYTES - either already
21977    allocated on the objfile obstack, or newly allocated on OBSTACK,
21978    or, set *BATON, if we translated the constant to a location
21979    expression.  */
21980
21981 static void
21982 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21983                          const char *name, struct obstack *obstack,
21984                          struct dwarf2_cu *cu,
21985                          LONGEST *value, const gdb_byte **bytes,
21986                          struct dwarf2_locexpr_baton **baton)
21987 {
21988   dwarf2_per_objfile *per_objfile = cu->per_objfile;
21989   struct objfile *objfile = per_objfile->objfile;
21990   struct comp_unit_head *cu_header = &cu->header;
21991   struct dwarf_block *blk;
21992   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21993                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21994
21995   *value = 0;
21996   *bytes = NULL;
21997   *baton = NULL;
21998
21999   switch (attr->form)
22000     {
22001     case DW_FORM_addr:
22002     case DW_FORM_addrx:
22003     case DW_FORM_GNU_addr_index:
22004       {
22005         gdb_byte *data;
22006
22007         if (TYPE_LENGTH (type) != cu_header->addr_size)
22008           dwarf2_const_value_length_mismatch_complaint (name,
22009                                                         cu_header->addr_size,
22010                                                         TYPE_LENGTH (type));
22011         /* Symbols of this form are reasonably rare, so we just
22012            piggyback on the existing location code rather than writing
22013            a new implementation of symbol_computed_ops.  */
22014         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
22015         (*baton)->per_objfile = per_objfile;
22016         (*baton)->per_cu = cu->per_cu;
22017         gdb_assert ((*baton)->per_cu);
22018
22019         (*baton)->size = 2 + cu_header->addr_size;
22020         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
22021         (*baton)->data = data;
22022
22023         data[0] = DW_OP_addr;
22024         store_unsigned_integer (&data[1], cu_header->addr_size,
22025                                 byte_order, attr->as_address ());
22026         data[cu_header->addr_size + 1] = DW_OP_stack_value;
22027       }
22028       break;
22029     case DW_FORM_string:
22030     case DW_FORM_strp:
22031     case DW_FORM_strx:
22032     case DW_FORM_GNU_str_index:
22033     case DW_FORM_GNU_strp_alt:
22034       /* The string is already allocated on the objfile obstack, point
22035          directly to it.  */
22036       *bytes = (const gdb_byte *) attr->as_string ();
22037       break;
22038     case DW_FORM_block1:
22039     case DW_FORM_block2:
22040     case DW_FORM_block4:
22041     case DW_FORM_block:
22042     case DW_FORM_exprloc:
22043     case DW_FORM_data16:
22044       blk = attr->as_block ();
22045       if (TYPE_LENGTH (type) != blk->size)
22046         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
22047                                                       TYPE_LENGTH (type));
22048       *bytes = blk->data;
22049       break;
22050
22051       /* The DW_AT_const_value attributes are supposed to carry the
22052          symbol's value "represented as it would be on the target
22053          architecture."  By the time we get here, it's already been
22054          converted to host endianness, so we just need to sign- or
22055          zero-extend it as appropriate.  */
22056     case DW_FORM_data1:
22057       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
22058       break;
22059     case DW_FORM_data2:
22060       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
22061       break;
22062     case DW_FORM_data4:
22063       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
22064       break;
22065     case DW_FORM_data8:
22066       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
22067       break;
22068
22069     case DW_FORM_sdata:
22070     case DW_FORM_implicit_const:
22071       *value = attr->as_signed ();
22072       break;
22073
22074     case DW_FORM_udata:
22075       *value = attr->as_unsigned ();
22076       break;
22077
22078     default:
22079       complaint (_("unsupported const value attribute form: '%s'"),
22080                  dwarf_form_name (attr->form));
22081       *value = 0;
22082       break;
22083     }
22084 }
22085
22086
22087 /* Copy constant value from an attribute to a symbol.  */
22088
22089 static void
22090 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
22091                     struct dwarf2_cu *cu)
22092 {
22093   struct objfile *objfile = cu->per_objfile->objfile;
22094   LONGEST value;
22095   const gdb_byte *bytes;
22096   struct dwarf2_locexpr_baton *baton;
22097
22098   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
22099                            sym->print_name (),
22100                            &objfile->objfile_obstack, cu,
22101                            &value, &bytes, &baton);
22102
22103   if (baton != NULL)
22104     {
22105       SYMBOL_LOCATION_BATON (sym) = baton;
22106       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22107     }
22108   else if (bytes != NULL)
22109      {
22110       SYMBOL_VALUE_BYTES (sym) = bytes;
22111       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22112     }
22113   else
22114     {
22115       SYMBOL_VALUE (sym) = value;
22116       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22117     }
22118 }
22119
22120 /* Return the type of the die in question using its DW_AT_type attribute.  */
22121
22122 static struct type *
22123 die_type (struct die_info *die, struct dwarf2_cu *cu)
22124 {
22125   struct attribute *type_attr;
22126
22127   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22128   if (!type_attr)
22129     {
22130       struct objfile *objfile = cu->per_objfile->objfile;
22131       /* A missing DW_AT_type represents a void type.  */
22132       return objfile_type (objfile)->builtin_void;
22133     }
22134
22135   return lookup_die_type (die, type_attr, cu);
22136 }
22137
22138 /* True iff CU's producer generates GNAT Ada auxiliary information
22139    that allows to find parallel types through that information instead
22140    of having to do expensive parallel lookups by type name.  */
22141
22142 static int
22143 need_gnat_info (struct dwarf2_cu *cu)
22144 {
22145   /* Assume that the Ada compiler was GNAT, which always produces
22146      the auxiliary information.  */
22147   return (cu->per_cu->lang == language_ada);
22148 }
22149
22150 /* Return the auxiliary type of the die in question using its
22151    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22152    attribute is not present.  */
22153
22154 static struct type *
22155 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22156 {
22157   struct attribute *type_attr;
22158
22159   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22160   if (!type_attr)
22161     return NULL;
22162
22163   return lookup_die_type (die, type_attr, cu);
22164 }
22165
22166 /* If DIE has a descriptive_type attribute, then set the TYPE's
22167    descriptive type accordingly.  */
22168
22169 static void
22170 set_descriptive_type (struct type *type, struct die_info *die,
22171                       struct dwarf2_cu *cu)
22172 {
22173   struct type *descriptive_type = die_descriptive_type (die, cu);
22174
22175   if (descriptive_type)
22176     {
22177       ALLOCATE_GNAT_AUX_TYPE (type);
22178       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22179     }
22180 }
22181
22182 /* Return the containing type of the die in question using its
22183    DW_AT_containing_type attribute.  */
22184
22185 static struct type *
22186 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22187 {
22188   struct attribute *type_attr;
22189   struct objfile *objfile = cu->per_objfile->objfile;
22190
22191   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22192   if (!type_attr)
22193     error (_("Dwarf Error: Problem turning containing type into gdb type "
22194              "[in module %s]"), objfile_name (objfile));
22195
22196   return lookup_die_type (die, type_attr, cu);
22197 }
22198
22199 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22200
22201 static struct type *
22202 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22203 {
22204   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22205   struct objfile *objfile = per_objfile->objfile;
22206   char *saved;
22207
22208   std::string message
22209     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
22210                      objfile_name (objfile),
22211                      sect_offset_str (cu->header.sect_off),
22212                      sect_offset_str (die->sect_off));
22213   saved = obstack_strdup (&objfile->objfile_obstack, message);
22214
22215   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22216 }
22217
22218 /* Look up the type of DIE in CU using its type attribute ATTR.
22219    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22220    DW_AT_containing_type.
22221    If there is no type substitute an error marker.  */
22222
22223 static struct type *
22224 lookup_die_type (struct die_info *die, const struct attribute *attr,
22225                  struct dwarf2_cu *cu)
22226 {
22227   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22228   struct objfile *objfile = per_objfile->objfile;
22229   struct type *this_type;
22230
22231   gdb_assert (attr->name == DW_AT_type
22232               || attr->name == DW_AT_GNAT_descriptive_type
22233               || attr->name == DW_AT_containing_type);
22234
22235   /* First see if we have it cached.  */
22236
22237   if (attr->form == DW_FORM_GNU_ref_alt)
22238     {
22239       struct dwarf2_per_cu_data *per_cu;
22240       sect_offset sect_off = attr->get_ref_die_offset ();
22241
22242       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, per_objfile);
22243       this_type = get_die_type_at_offset (sect_off, per_cu, per_objfile);
22244     }
22245   else if (attr->form_is_ref ())
22246     {
22247       sect_offset sect_off = attr->get_ref_die_offset ();
22248
22249       this_type = get_die_type_at_offset (sect_off, cu->per_cu, per_objfile);
22250     }
22251   else if (attr->form == DW_FORM_ref_sig8)
22252     {
22253       ULONGEST signature = attr->as_signature ();
22254
22255       return get_signatured_type (die, signature, cu);
22256     }
22257   else
22258     {
22259       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
22260                    " at %s [in module %s]"),
22261                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22262                  objfile_name (objfile));
22263       return build_error_marker_type (cu, die);
22264     }
22265
22266   /* If not cached we need to read it in.  */
22267
22268   if (this_type == NULL)
22269     {
22270       struct die_info *type_die = NULL;
22271       struct dwarf2_cu *type_cu = cu;
22272
22273       if (attr->form_is_ref ())
22274         type_die = follow_die_ref (die, attr, &type_cu);
22275       if (type_die == NULL)
22276         return build_error_marker_type (cu, die);
22277       /* If we find the type now, it's probably because the type came
22278          from an inter-CU reference and the type's CU got expanded before
22279          ours.  */
22280       this_type = read_type_die (type_die, type_cu);
22281     }
22282
22283   /* If we still don't have a type use an error marker.  */
22284
22285   if (this_type == NULL)
22286     return build_error_marker_type (cu, die);
22287
22288   return this_type;
22289 }
22290
22291 /* Return the type in DIE, CU.
22292    Returns NULL for invalid types.
22293
22294    This first does a lookup in die_type_hash,
22295    and only reads the die in if necessary.
22296
22297    NOTE: This can be called when reading in partial or full symbols.  */
22298
22299 static struct type *
22300 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22301 {
22302   struct type *this_type;
22303
22304   this_type = get_die_type (die, cu);
22305   if (this_type)
22306     return this_type;
22307
22308   return read_type_die_1 (die, cu);
22309 }
22310
22311 /* Read the type in DIE, CU.
22312    Returns NULL for invalid types.  */
22313
22314 static struct type *
22315 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22316 {
22317   struct type *this_type = NULL;
22318
22319   switch (die->tag)
22320     {
22321     case DW_TAG_class_type:
22322     case DW_TAG_interface_type:
22323     case DW_TAG_structure_type:
22324     case DW_TAG_union_type:
22325       this_type = read_structure_type (die, cu);
22326       break;
22327     case DW_TAG_enumeration_type:
22328       this_type = read_enumeration_type (die, cu);
22329       break;
22330     case DW_TAG_subprogram:
22331     case DW_TAG_subroutine_type:
22332     case DW_TAG_inlined_subroutine:
22333       this_type = read_subroutine_type (die, cu);
22334       break;
22335     case DW_TAG_array_type:
22336       this_type = read_array_type (die, cu);
22337       break;
22338     case DW_TAG_set_type:
22339       this_type = read_set_type (die, cu);
22340       break;
22341     case DW_TAG_pointer_type:
22342       this_type = read_tag_pointer_type (die, cu);
22343       break;
22344     case DW_TAG_ptr_to_member_type:
22345       this_type = read_tag_ptr_to_member_type (die, cu);
22346       break;
22347     case DW_TAG_reference_type:
22348       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22349       break;
22350     case DW_TAG_rvalue_reference_type:
22351       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22352       break;
22353     case DW_TAG_const_type:
22354       this_type = read_tag_const_type (die, cu);
22355       break;
22356     case DW_TAG_volatile_type:
22357       this_type = read_tag_volatile_type (die, cu);
22358       break;
22359     case DW_TAG_restrict_type:
22360       this_type = read_tag_restrict_type (die, cu);
22361       break;
22362     case DW_TAG_string_type:
22363       this_type = read_tag_string_type (die, cu);
22364       break;
22365     case DW_TAG_typedef:
22366       this_type = read_typedef (die, cu);
22367       break;
22368     case DW_TAG_subrange_type:
22369       this_type = read_subrange_type (die, cu);
22370       break;
22371     case DW_TAG_base_type:
22372       this_type = read_base_type (die, cu);
22373       break;
22374     case DW_TAG_unspecified_type:
22375       this_type = read_unspecified_type (die, cu);
22376       break;
22377     case DW_TAG_namespace:
22378       this_type = read_namespace_type (die, cu);
22379       break;
22380     case DW_TAG_module:
22381       this_type = read_module_type (die, cu);
22382       break;
22383     case DW_TAG_atomic_type:
22384       this_type = read_tag_atomic_type (die, cu);
22385       break;
22386     default:
22387       complaint (_("unexpected tag in read_type_die: '%s'"),
22388                  dwarf_tag_name (die->tag));
22389       break;
22390     }
22391
22392   return this_type;
22393 }
22394
22395 /* See if we can figure out if the class lives in a namespace.  We do
22396    this by looking for a member function; its demangled name will
22397    contain namespace info, if there is any.
22398    Return the computed name or NULL.
22399    Space for the result is allocated on the objfile's obstack.
22400    This is the full-die version of guess_partial_die_structure_name.
22401    In this case we know DIE has no useful parent.  */
22402
22403 static const char *
22404 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22405 {
22406   struct die_info *spec_die;
22407   struct dwarf2_cu *spec_cu;
22408   struct die_info *child;
22409   struct objfile *objfile = cu->per_objfile->objfile;
22410
22411   spec_cu = cu;
22412   spec_die = die_specification (die, &spec_cu);
22413   if (spec_die != NULL)
22414     {
22415       die = spec_die;
22416       cu = spec_cu;
22417     }
22418
22419   for (child = die->child;
22420        child != NULL;
22421        child = child->sibling)
22422     {
22423       if (child->tag == DW_TAG_subprogram)
22424         {
22425           const char *linkage_name = dw2_linkage_name (child, cu);
22426
22427           if (linkage_name != NULL)
22428             {
22429               gdb::unique_xmalloc_ptr<char> actual_name
22430                 (cu->language_defn->class_name_from_physname (linkage_name));
22431               const char *name = NULL;
22432
22433               if (actual_name != NULL)
22434                 {
22435                   const char *die_name = dwarf2_name (die, cu);
22436
22437                   if (die_name != NULL
22438                       && strcmp (die_name, actual_name.get ()) != 0)
22439                     {
22440                       /* Strip off the class name from the full name.
22441                          We want the prefix.  */
22442                       int die_name_len = strlen (die_name);
22443                       int actual_name_len = strlen (actual_name.get ());
22444                       const char *ptr = actual_name.get ();
22445
22446                       /* Test for '::' as a sanity check.  */
22447                       if (actual_name_len > die_name_len + 2
22448                           && ptr[actual_name_len - die_name_len - 1] == ':')
22449                         name = obstack_strndup (
22450                           &objfile->per_bfd->storage_obstack,
22451                           ptr, actual_name_len - die_name_len - 2);
22452                     }
22453                 }
22454               return name;
22455             }
22456         }
22457     }
22458
22459   return NULL;
22460 }
22461
22462 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22463    prefix part in such case.  See
22464    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22465
22466 static const char *
22467 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22468 {
22469   struct attribute *attr;
22470   const char *base;
22471
22472   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22473       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22474     return NULL;
22475
22476   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22477     return NULL;
22478
22479   attr = dw2_linkage_name_attr (die, cu);
22480   const char *attr_name = attr->as_string ();
22481   if (attr == NULL || attr_name == NULL)
22482     return NULL;
22483
22484   /* dwarf2_name had to be already called.  */
22485   gdb_assert (attr->canonical_string_p ());
22486
22487   /* Strip the base name, keep any leading namespaces/classes.  */
22488   base = strrchr (attr_name, ':');
22489   if (base == NULL || base == attr_name || base[-1] != ':')
22490     return "";
22491
22492   struct objfile *objfile = cu->per_objfile->objfile;
22493   return obstack_strndup (&objfile->per_bfd->storage_obstack,
22494                           attr_name,
22495                           &base[-1] - attr_name);
22496 }
22497
22498 /* Return the name of the namespace/class that DIE is defined within,
22499    or "" if we can't tell.  The caller should not xfree the result.
22500
22501    For example, if we're within the method foo() in the following
22502    code:
22503
22504    namespace N {
22505      class C {
22506        void foo () {
22507        }
22508      };
22509    }
22510
22511    then determine_prefix on foo's die will return "N::C".  */
22512
22513 static const char *
22514 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22515 {
22516   dwarf2_per_objfile *per_objfile = cu->per_objfile;
22517   struct die_info *parent, *spec_die;
22518   struct dwarf2_cu *spec_cu;
22519   struct type *parent_type;
22520   const char *retval;
22521
22522   if (cu->per_cu->lang != language_cplus
22523       && cu->per_cu->lang != language_fortran
22524       && cu->per_cu->lang != language_d
22525       && cu->per_cu->lang != language_rust)
22526     return "";
22527
22528   retval = anonymous_struct_prefix (die, cu);
22529   if (retval)
22530     return retval;
22531
22532   /* We have to be careful in the presence of DW_AT_specification.
22533      For example, with GCC 3.4, given the code
22534
22535      namespace N {
22536        void foo() {
22537          // Definition of N::foo.
22538        }
22539      }
22540
22541      then we'll have a tree of DIEs like this:
22542
22543      1: DW_TAG_compile_unit
22544        2: DW_TAG_namespace        // N
22545          3: DW_TAG_subprogram     // declaration of N::foo
22546        4: DW_TAG_subprogram       // definition of N::foo
22547             DW_AT_specification   // refers to die #3
22548
22549      Thus, when processing die #4, we have to pretend that we're in
22550      the context of its DW_AT_specification, namely the contex of die
22551      #3.  */
22552   spec_cu = cu;
22553   spec_die = die_specification (die, &spec_cu);
22554   if (spec_die == NULL)
22555     parent = die->parent;
22556   else
22557     {
22558       parent = spec_die->parent;
22559       cu = spec_cu;
22560     }
22561
22562   if (parent == NULL)
22563     return "";
22564   else if (parent->building_fullname)
22565     {
22566       const char *name;
22567       const char *parent_name;
22568
22569       /* It has been seen on RealView 2.2 built binaries,
22570          DW_TAG_template_type_param types actually _defined_ as
22571          children of the parent class:
22572
22573          enum E {};
22574          template class <class Enum> Class{};
22575          Class<enum E> class_e;
22576
22577          1: DW_TAG_class_type (Class)
22578            2: DW_TAG_enumeration_type (E)
22579              3: DW_TAG_enumerator (enum1:0)
22580              3: DW_TAG_enumerator (enum2:1)
22581              ...
22582            2: DW_TAG_template_type_param
22583               DW_AT_type  DW_FORM_ref_udata (E)
22584
22585          Besides being broken debug info, it can put GDB into an
22586          infinite loop.  Consider:
22587
22588          When we're building the full name for Class<E>, we'll start
22589          at Class, and go look over its template type parameters,
22590          finding E.  We'll then try to build the full name of E, and
22591          reach here.  We're now trying to build the full name of E,
22592          and look over the parent DIE for containing scope.  In the
22593          broken case, if we followed the parent DIE of E, we'd again
22594          find Class, and once again go look at its template type
22595          arguments, etc., etc.  Simply don't consider such parent die
22596          as source-level parent of this die (it can't be, the language
22597          doesn't allow it), and break the loop here.  */
22598       name = dwarf2_name (die, cu);
22599       parent_name = dwarf2_name (parent, cu);
22600       complaint (_("template param type '%s' defined within parent '%s'"),
22601                  name ? name : "<unknown>",
22602                  parent_name ? parent_name : "<unknown>");
22603       return "";
22604     }
22605   else
22606     switch (parent->tag)
22607       {
22608       case DW_TAG_namespace:
22609         parent_type = read_type_die (parent, cu);
22610         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22611            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22612            Work around this problem here.  */
22613         if (cu->per_cu->lang == language_cplus
22614             && strcmp (parent_type->name (), "::") == 0)
22615           return "";
22616         /* We give a name to even anonymous namespaces.  */
22617         return parent_type->name ();
22618       case DW_TAG_class_type:
22619       case DW_TAG_interface_type:
22620       case DW_TAG_structure_type:
22621       case DW_TAG_union_type:
22622       case DW_TAG_module:
22623         parent_type = read_type_die (parent, cu);
22624         if (parent_type->name () != NULL)
22625           return parent_type->name ();
22626         else
22627           /* An anonymous structure is only allowed non-static data
22628              members; no typedefs, no member functions, et cetera.
22629              So it does not need a prefix.  */
22630           return "";
22631       case DW_TAG_compile_unit:
22632       case DW_TAG_partial_unit:
22633         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22634         if (cu->per_cu->lang == language_cplus
22635             && !per_objfile->per_bfd->types.empty ()
22636             && die->child != NULL
22637             && (die->tag == DW_TAG_class_type
22638                 || die->tag == DW_TAG_structure_type
22639                 || die->tag == DW_TAG_union_type))
22640           {
22641             const char *name = guess_full_die_structure_name (die, cu);
22642             if (name != NULL)
22643               return name;
22644           }
22645         return "";
22646       case DW_TAG_subprogram:
22647         /* Nested subroutines in Fortran get a prefix with the name
22648            of the parent's subroutine.  */
22649         if (cu->per_cu->lang == language_fortran)
22650           {
22651             if ((die->tag ==  DW_TAG_subprogram)
22652                 && (dwarf2_name (parent, cu) != NULL))
22653               return dwarf2_name (parent, cu);
22654           }
22655         return "";
22656       case DW_TAG_enumeration_type:
22657         parent_type = read_type_die (parent, cu);
22658         if (parent_type->is_declared_class ())
22659           {
22660             if (parent_type->name () != NULL)
22661               return parent_type->name ();
22662             return "";
22663           }
22664         /* Fall through.  */
22665       default:
22666         return determine_prefix (parent, cu);
22667       }
22668 }
22669
22670 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22671    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22672    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22673    an obconcat, otherwise allocate storage for the result.  The CU argument is
22674    used to determine the language and hence, the appropriate separator.  */
22675
22676 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22677
22678 static char *
22679 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22680                  int physname, struct dwarf2_cu *cu)
22681 {
22682   const char *lead = "";
22683   const char *sep;
22684
22685   if (suffix == NULL || suffix[0] == '\0'
22686       || prefix == NULL || prefix[0] == '\0')
22687     sep = "";
22688   else if (cu->per_cu->lang == language_d)
22689     {
22690       /* For D, the 'main' function could be defined in any module, but it
22691          should never be prefixed.  */
22692       if (strcmp (suffix, "D main") == 0)
22693         {
22694           prefix = "";
22695           sep = "";
22696         }
22697       else
22698         sep = ".";
22699     }
22700   else if (cu->per_cu->lang == language_fortran && physname)
22701     {
22702       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22703          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22704
22705       lead = "__";
22706       sep = "_MOD_";
22707     }
22708   else
22709     sep = "::";
22710
22711   if (prefix == NULL)
22712     prefix = "";
22713   if (suffix == NULL)
22714     suffix = "";
22715
22716   if (obs == NULL)
22717     {
22718       char *retval
22719         = ((char *)
22720            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22721
22722       strcpy (retval, lead);
22723       strcat (retval, prefix);
22724       strcat (retval, sep);
22725       strcat (retval, suffix);
22726       return retval;
22727     }
22728   else
22729     {
22730       /* We have an obstack.  */
22731       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22732     }
22733 }
22734
22735 /* Get name of a die, return NULL if not found.  */
22736
22737 static const char *
22738 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22739                           struct objfile *objfile)
22740 {
22741   if (name && cu->per_cu->lang == language_cplus)
22742     {
22743       gdb::unique_xmalloc_ptr<char> canon_name
22744         = cp_canonicalize_string (name);
22745
22746       if (canon_name != nullptr)
22747         name = objfile->intern (canon_name.get ());
22748     }
22749
22750   return name;
22751 }
22752
22753 /* Get name of a die, return NULL if not found.
22754    Anonymous namespaces are converted to their magic string.  */
22755
22756 static const char *
22757 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22758 {
22759   struct attribute *attr;
22760   struct objfile *objfile = cu->per_objfile->objfile;
22761
22762   attr = dwarf2_attr (die, DW_AT_name, cu);
22763   const char *attr_name = attr == nullptr ? nullptr : attr->as_string ();
22764   if (attr_name == nullptr
22765       && die->tag != DW_TAG_namespace
22766       && die->tag != DW_TAG_class_type
22767       && die->tag != DW_TAG_interface_type
22768       && die->tag != DW_TAG_structure_type
22769       && die->tag != DW_TAG_union_type)
22770     return NULL;
22771
22772   switch (die->tag)
22773     {
22774     case DW_TAG_compile_unit:
22775     case DW_TAG_partial_unit:
22776       /* Compilation units have a DW_AT_name that is a filename, not
22777          a source language identifier.  */
22778     case DW_TAG_enumeration_type:
22779     case DW_TAG_enumerator:
22780       /* These tags always have simple identifiers already; no need
22781          to canonicalize them.  */
22782       return attr_name;
22783
22784     case DW_TAG_namespace:
22785       if (attr_name != nullptr)
22786         return attr_name;
22787       return CP_ANONYMOUS_NAMESPACE_STR;
22788
22789     case DW_TAG_class_type:
22790     case DW_TAG_interface_type:
22791     case DW_TAG_structure_type:
22792     case DW_TAG_union_type:
22793       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22794          structures or unions.  These were of the form "._%d" in GCC 4.1,
22795          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22796          and GCC 4.4.  We work around this problem by ignoring these.  */
22797       if (attr_name != nullptr
22798           && (startswith (attr_name, "._")
22799               || startswith (attr_name, "<anonymous")))
22800         return NULL;
22801
22802       /* GCC might emit a nameless typedef that has a linkage name.  See
22803          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22804       if (!attr || attr_name == NULL)
22805         {
22806           attr = dw2_linkage_name_attr (die, cu);
22807           attr_name = attr == nullptr ? nullptr : attr->as_string ();
22808           if (attr == NULL || attr_name == NULL)
22809             return NULL;
22810
22811           /* Avoid demangling attr_name the second time on a second
22812              call for the same DIE.  */
22813           if (!attr->canonical_string_p ())
22814             {
22815               gdb::unique_xmalloc_ptr<char> demangled
22816                 (gdb_demangle (attr_name, DMGL_TYPES));
22817               if (demangled == nullptr)
22818                 return nullptr;
22819
22820               attr->set_string_canonical (objfile->intern (demangled.get ()));
22821               attr_name = attr->as_string ();
22822             }
22823
22824           /* Strip any leading namespaces/classes, keep only the
22825              base name.  DW_AT_name for named DIEs does not
22826              contain the prefixes.  */
22827           const char *base = strrchr (attr_name, ':');
22828           if (base && base > attr_name && base[-1] == ':')
22829             return &base[1];
22830           else
22831             return attr_name;
22832         }
22833       break;
22834
22835     default:
22836       break;
22837     }
22838
22839   if (!attr->canonical_string_p ())
22840     attr->set_string_canonical (dwarf2_canonicalize_name (attr_name, cu,
22841                                                           objfile));
22842   return attr->as_string ();
22843 }
22844
22845 /* Return the die that this die in an extension of, or NULL if there
22846    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22847    containing the return value on output.  */
22848
22849 static struct die_info *
22850 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22851 {
22852   struct attribute *attr;
22853
22854   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22855   if (attr == NULL)
22856     return NULL;
22857
22858   return follow_die_ref (die, attr, ext_cu);
22859 }
22860
22861 static void
22862 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22863 {
22864   unsigned int i;
22865
22866   print_spaces (indent, f);
22867   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22868                       dwarf_tag_name (die->tag), die->abbrev,
22869                       sect_offset_str (die->sect_off));
22870
22871   if (die->parent != NULL)
22872     {
22873       print_spaces (indent, f);
22874       fprintf_unfiltered (f, "  parent at offset: %s\n",
22875                           sect_offset_str (die->parent->sect_off));
22876     }
22877
22878   print_spaces (indent, f);
22879   fprintf_unfiltered (f, "  has children: %s\n",
22880            dwarf_bool_name (die->child != NULL));
22881
22882   print_spaces (indent, f);
22883   fprintf_unfiltered (f, "  attributes:\n");
22884
22885   for (i = 0; i < die->num_attrs; ++i)
22886     {
22887       print_spaces (indent, f);
22888       fprintf_unfiltered (f, "    %s (%s) ",
22889                dwarf_attr_name (die->attrs[i].name),
22890                dwarf_form_name (die->attrs[i].form));
22891
22892       switch (die->attrs[i].form)
22893         {
22894         case DW_FORM_addr:
22895         case DW_FORM_addrx:
22896         case DW_FORM_GNU_addr_index:
22897           fprintf_unfiltered (f, "address: ");
22898           fputs_filtered (hex_string (die->attrs[i].as_address ()), f);
22899           break;
22900         case DW_FORM_block2:
22901         case DW_FORM_block4:
22902         case DW_FORM_block:
22903         case DW_FORM_block1:
22904           fprintf_unfiltered (f, "block: size %s",
22905                               pulongest (die->attrs[i].as_block ()->size));
22906           break;
22907         case DW_FORM_exprloc:
22908           fprintf_unfiltered (f, "expression: size %s",
22909                               pulongest (die->attrs[i].as_block ()->size));
22910           break;
22911         case DW_FORM_data16:
22912           fprintf_unfiltered (f, "constant of 16 bytes");
22913           break;
22914         case DW_FORM_ref_addr:
22915           fprintf_unfiltered (f, "ref address: ");
22916           fputs_filtered (hex_string (die->attrs[i].as_unsigned ()), f);
22917           break;
22918         case DW_FORM_GNU_ref_alt:
22919           fprintf_unfiltered (f, "alt ref address: ");
22920           fputs_filtered (hex_string (die->attrs[i].as_unsigned ()), f);
22921           break;
22922         case DW_FORM_ref1:
22923         case DW_FORM_ref2:
22924         case DW_FORM_ref4:
22925         case DW_FORM_ref8:
22926         case DW_FORM_ref_udata:
22927           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22928                               (long) (die->attrs[i].as_unsigned ()));
22929           break;
22930         case DW_FORM_data1:
22931         case DW_FORM_data2:
22932         case DW_FORM_data4:
22933         case DW_FORM_data8:
22934         case DW_FORM_udata:
22935           fprintf_unfiltered (f, "constant: %s",
22936                               pulongest (die->attrs[i].as_unsigned ()));
22937           break;
22938         case DW_FORM_sec_offset:
22939           fprintf_unfiltered (f, "section offset: %s",
22940                               pulongest (die->attrs[i].as_unsigned ()));
22941           break;
22942         case DW_FORM_ref_sig8:
22943           fprintf_unfiltered (f, "signature: %s",
22944                               hex_string (die->attrs[i].as_signature ()));
22945           break;
22946         case DW_FORM_string:
22947         case DW_FORM_strp:
22948         case DW_FORM_line_strp:
22949         case DW_FORM_strx:
22950         case DW_FORM_GNU_str_index:
22951         case DW_FORM_GNU_strp_alt:
22952           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22953                               die->attrs[i].as_string ()
22954                               ? die->attrs[i].as_string () : "",
22955                               die->attrs[i].canonical_string_p () ? "is" : "not");
22956           break;
22957         case DW_FORM_flag:
22958           if (die->attrs[i].as_boolean ())
22959             fprintf_unfiltered (f, "flag: TRUE");
22960           else
22961             fprintf_unfiltered (f, "flag: FALSE");
22962           break;
22963         case DW_FORM_flag_present:
22964           fprintf_unfiltered (f, "flag: TRUE");
22965           break;
22966         case DW_FORM_indirect:
22967           /* The reader will have reduced the indirect form to
22968              the "base form" so this form should not occur.  */
22969           fprintf_unfiltered (f,
22970                               "unexpected attribute form: DW_FORM_indirect");
22971           break;
22972         case DW_FORM_sdata:
22973         case DW_FORM_implicit_const:
22974           fprintf_unfiltered (f, "constant: %s",
22975                               plongest (die->attrs[i].as_signed ()));
22976           break;
22977         default:
22978           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22979                    die->attrs[i].form);
22980           break;
22981         }
22982       fprintf_unfiltered (f, "\n");
22983     }
22984 }
22985
22986 static void
22987 dump_die_for_error (struct die_info *die)
22988 {
22989   dump_die_shallow (gdb_stderr, 0, die);
22990 }
22991
22992 static void
22993 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22994 {
22995   int indent = level * 4;
22996
22997   gdb_assert (die != NULL);
22998
22999   if (level >= max_level)
23000     return;
23001
23002   dump_die_shallow (f, indent, die);
23003
23004   if (die->child != NULL)
23005     {
23006       print_spaces (indent, f);
23007       fprintf_unfiltered (f, "  Children:");
23008       if (level + 1 < max_level)
23009         {
23010           fprintf_unfiltered (f, "\n");
23011           dump_die_1 (f, level + 1, max_level, die->child);
23012         }
23013       else
23014         {
23015           fprintf_unfiltered (f,
23016                               " [not printed, max nesting level reached]\n");
23017         }
23018     }
23019
23020   if (die->sibling != NULL && level > 0)
23021     {
23022       dump_die_1 (f, level, max_level, die->sibling);
23023     }
23024 }
23025
23026 /* This is called from the pdie macro in gdbinit.in.
23027    It's not static so gcc will keep a copy callable from gdb.  */
23028
23029 void
23030 dump_die (struct die_info *die, int max_level)
23031 {
23032   dump_die_1 (gdb_stdlog, 0, max_level, die);
23033 }
23034
23035 static void
23036 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23037 {
23038   void **slot;
23039
23040   slot = htab_find_slot_with_hash (cu->die_hash, die,
23041                                    to_underlying (die->sect_off),
23042                                    INSERT);
23043
23044   *slot = die;
23045 }
23046
23047 /* Follow reference or signature attribute ATTR of SRC_DIE.
23048    On entry *REF_CU is the CU of SRC_DIE.
23049    On exit *REF_CU is the CU of the result.  */
23050
23051 static struct die_info *
23052 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23053                        struct dwarf2_cu **ref_cu)
23054 {
23055   struct die_info *die;
23056
23057   if (attr->form_is_ref ())
23058     die = follow_die_ref (src_die, attr, ref_cu);
23059   else if (attr->form == DW_FORM_ref_sig8)
23060     die = follow_die_sig (src_die, attr, ref_cu);
23061   else
23062     {
23063       dump_die_for_error (src_die);
23064       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23065              objfile_name ((*ref_cu)->per_objfile->objfile));
23066     }
23067
23068   return die;
23069 }
23070
23071 /* Follow reference OFFSET.
23072    On entry *REF_CU is the CU of the source die referencing OFFSET.
23073    On exit *REF_CU is the CU of the result.
23074    Returns NULL if OFFSET is invalid.  */
23075
23076 static struct die_info *
23077 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23078                    struct dwarf2_cu **ref_cu)
23079 {
23080   struct die_info temp_die;
23081   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23082   dwarf2_per_objfile *per_objfile = cu->per_objfile;
23083
23084   gdb_assert (cu->per_cu != NULL);
23085
23086   target_cu = cu;
23087
23088   dwarf_read_debug_printf_v ("source CU offset: %s, target offset: %s, "
23089                              "source CU contains target offset: %d",
23090                              sect_offset_str (cu->per_cu->sect_off),
23091                              sect_offset_str (sect_off),
23092                              cu->header.offset_in_cu_p (sect_off));
23093
23094   if (cu->per_cu->is_debug_types)
23095     {
23096       /* .debug_types CUs cannot reference anything outside their CU.
23097          If they need to, they have to reference a signatured type via
23098          DW_FORM_ref_sig8.  */
23099       if (!cu->header.offset_in_cu_p (sect_off))
23100         return NULL;
23101     }
23102   else if (offset_in_dwz != cu->per_cu->is_dwz
23103            || !cu->header.offset_in_cu_p (sect_off))
23104     {
23105       struct dwarf2_per_cu_data *per_cu;
23106
23107       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23108                                                  per_objfile);
23109
23110       dwarf_read_debug_printf_v ("target CU offset: %s, "
23111                                  "target CU DIEs loaded: %d",
23112                                  sect_offset_str (per_cu->sect_off),
23113                                  per_objfile->get_cu (per_cu) != nullptr);
23114
23115       /* If necessary, add it to the queue and load its DIEs.
23116
23117          Even if maybe_queue_comp_unit doesn't require us to load the CU's DIEs,
23118          it doesn't mean they are currently loaded.  Since we require them
23119          to be loaded, we must check for ourselves.  */
23120       if (maybe_queue_comp_unit (cu, per_cu, per_objfile, cu->per_cu->lang)
23121           || per_objfile->get_cu (per_cu) == nullptr)
23122         load_full_comp_unit (per_cu, per_objfile, per_objfile->get_cu (per_cu),
23123                              false, cu->per_cu->lang);
23124
23125       target_cu = per_objfile->get_cu (per_cu);
23126       gdb_assert (target_cu != nullptr);
23127     }
23128   else if (cu->dies == NULL)
23129     {
23130       /* We're loading full DIEs during partial symbol reading.  */
23131       gdb_assert (per_objfile->per_bfd->reading_partial_symbols);
23132       load_full_comp_unit (cu->per_cu, per_objfile, cu, false,
23133                            language_minimal);
23134     }
23135
23136   *ref_cu = target_cu;
23137   temp_die.sect_off = sect_off;
23138
23139   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23140                                                   &temp_die,
23141                                                   to_underlying (sect_off));
23142 }
23143
23144 /* Follow reference attribute ATTR of SRC_DIE.
23145    On entry *REF_CU is the CU of SRC_DIE.
23146    On exit *REF_CU is the CU of the result.  */
23147
23148 static struct die_info *
23149 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23150                 struct dwarf2_cu **ref_cu)
23151 {
23152   sect_offset sect_off = attr->get_ref_die_offset ();
23153   struct dwarf2_cu *cu = *ref_cu;
23154   struct die_info *die;
23155
23156   die = follow_die_offset (sect_off,
23157                            (attr->form == DW_FORM_GNU_ref_alt
23158                             || cu->per_cu->is_dwz),
23159                            ref_cu);
23160   if (!die)
23161     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23162            "at %s [in module %s]"),
23163            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23164            objfile_name (cu->per_objfile->objfile));
23165
23166   return die;
23167 }
23168
23169 /* See read.h.  */
23170
23171 struct dwarf2_locexpr_baton
23172 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23173                                dwarf2_per_cu_data *per_cu,
23174                                dwarf2_per_objfile *per_objfile,
23175                                gdb::function_view<CORE_ADDR ()> get_frame_pc,
23176                                bool resolve_abstract_p)
23177 {
23178   struct die_info *die;
23179   struct attribute *attr;
23180   struct dwarf2_locexpr_baton retval;
23181   struct objfile *objfile = per_objfile->objfile;
23182
23183   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
23184   if (cu == nullptr)
23185     cu = load_cu (per_cu, per_objfile, false);
23186
23187   if (cu == nullptr)
23188     {
23189       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23190          Instead just throw an error, not much else we can do.  */
23191       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23192              sect_offset_str (sect_off), objfile_name (objfile));
23193     }
23194
23195   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23196   if (!die)
23197     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23198            sect_offset_str (sect_off), objfile_name (objfile));
23199
23200   attr = dwarf2_attr (die, DW_AT_location, cu);
23201   if (!attr && resolve_abstract_p
23202       && (per_objfile->per_bfd->abstract_to_concrete.find (die->sect_off)
23203           != per_objfile->per_bfd->abstract_to_concrete.end ()))
23204     {
23205       CORE_ADDR pc = get_frame_pc ();
23206       CORE_ADDR baseaddr = objfile->text_section_offset ();
23207       struct gdbarch *gdbarch = objfile->arch ();
23208
23209       for (const auto &cand_off
23210              : per_objfile->per_bfd->abstract_to_concrete[die->sect_off])
23211         {
23212           struct dwarf2_cu *cand_cu = cu;
23213           struct die_info *cand
23214             = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
23215           if (!cand
23216               || !cand->parent
23217               || cand->parent->tag != DW_TAG_subprogram)
23218             continue;
23219
23220           CORE_ADDR pc_low, pc_high;
23221           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
23222           if (pc_low == ((CORE_ADDR) -1))
23223             continue;
23224           pc_low = gdbarch_adjust_dwarf2_addr (gdbarch, pc_low + baseaddr);
23225           pc_high = gdbarch_adjust_dwarf2_addr (gdbarch, pc_high + baseaddr);
23226           if (!(pc_low <= pc && pc < pc_high))
23227             continue;
23228
23229           die = cand;
23230           attr = dwarf2_attr (die, DW_AT_location, cu);
23231           break;
23232         }
23233     }
23234
23235   if (!attr)
23236     {
23237       /* DWARF: "If there is no such attribute, then there is no effect.".
23238          DATA is ignored if SIZE is 0.  */
23239
23240       retval.data = NULL;
23241       retval.size = 0;
23242     }
23243   else if (attr->form_is_section_offset ())
23244     {
23245       struct dwarf2_loclist_baton loclist_baton;
23246       CORE_ADDR pc = get_frame_pc ();
23247       size_t size;
23248
23249       fill_in_loclist_baton (cu, &loclist_baton, attr);
23250
23251       retval.data = dwarf2_find_location_expression (&loclist_baton,
23252                                                      &size, pc);
23253       retval.size = size;
23254     }
23255   else
23256     {
23257       if (!attr->form_is_block ())
23258         error (_("Dwarf Error: DIE at %s referenced in module %s "
23259                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23260                sect_offset_str (sect_off), objfile_name (objfile));
23261
23262       struct dwarf_block *block = attr->as_block ();
23263       retval.data = block->data;
23264       retval.size = block->size;
23265     }
23266   retval.per_objfile = per_objfile;
23267   retval.per_cu = cu->per_cu;
23268
23269   per_objfile->age_comp_units ();
23270
23271   return retval;
23272 }
23273
23274 /* See read.h.  */
23275
23276 struct dwarf2_locexpr_baton
23277 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23278                              dwarf2_per_cu_data *per_cu,
23279                              dwarf2_per_objfile *per_objfile,
23280                              gdb::function_view<CORE_ADDR ()> get_frame_pc)
23281 {
23282   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23283
23284   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, per_objfile,
23285                                         get_frame_pc);
23286 }
23287
23288 /* Write a constant of a given type as target-ordered bytes into
23289    OBSTACK.  */
23290
23291 static const gdb_byte *
23292 write_constant_as_bytes (struct obstack *obstack,
23293                          enum bfd_endian byte_order,
23294                          struct type *type,
23295                          ULONGEST value,
23296                          LONGEST *len)
23297 {
23298   gdb_byte *result;
23299
23300   *len = TYPE_LENGTH (type);
23301   result = (gdb_byte *) obstack_alloc (obstack, *len);
23302   store_unsigned_integer (result, *len, byte_order, value);
23303
23304   return result;
23305 }
23306
23307 /* See read.h.  */
23308
23309 const gdb_byte *
23310 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23311                              dwarf2_per_cu_data *per_cu,
23312                              dwarf2_per_objfile *per_objfile,
23313                              obstack *obstack,
23314                              LONGEST *len)
23315 {
23316   struct die_info *die;
23317   struct attribute *attr;
23318   const gdb_byte *result = NULL;
23319   struct type *type;
23320   LONGEST value;
23321   enum bfd_endian byte_order;
23322   struct objfile *objfile = per_objfile->objfile;
23323
23324   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
23325   if (cu == nullptr)
23326     cu = load_cu (per_cu, per_objfile, false);
23327
23328   if (cu == nullptr)
23329     {
23330       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23331          Instead just throw an error, not much else we can do.  */
23332       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23333              sect_offset_str (sect_off), objfile_name (objfile));
23334     }
23335
23336   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23337   if (!die)
23338     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23339            sect_offset_str (sect_off), objfile_name (objfile));
23340
23341   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23342   if (attr == NULL)
23343     return NULL;
23344
23345   byte_order = (bfd_big_endian (objfile->obfd)
23346                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23347
23348   switch (attr->form)
23349     {
23350     case DW_FORM_addr:
23351     case DW_FORM_addrx:
23352     case DW_FORM_GNU_addr_index:
23353       {
23354         gdb_byte *tem;
23355
23356         *len = cu->header.addr_size;
23357         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23358         store_unsigned_integer (tem, *len, byte_order, attr->as_address ());
23359         result = tem;
23360       }
23361       break;
23362     case DW_FORM_string:
23363     case DW_FORM_strp:
23364     case DW_FORM_strx:
23365     case DW_FORM_GNU_str_index:
23366     case DW_FORM_GNU_strp_alt:
23367       /* The string is already allocated on the objfile obstack, point
23368          directly to it.  */
23369       {
23370         const char *attr_name = attr->as_string ();
23371         result = (const gdb_byte *) attr_name;
23372         *len = strlen (attr_name);
23373       }
23374       break;
23375     case DW_FORM_block1:
23376     case DW_FORM_block2:
23377     case DW_FORM_block4:
23378     case DW_FORM_block:
23379     case DW_FORM_exprloc:
23380     case DW_FORM_data16:
23381       {
23382         struct dwarf_block *block = attr->as_block ();
23383         result = block->data;
23384         *len = block->size;
23385       }
23386       break;
23387
23388       /* The DW_AT_const_value attributes are supposed to carry the
23389          symbol's value "represented as it would be on the target
23390          architecture."  By the time we get here, it's already been
23391          converted to host endianness, so we just need to sign- or
23392          zero-extend it as appropriate.  */
23393     case DW_FORM_data1:
23394       type = die_type (die, cu);
23395       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23396       if (result == NULL)
23397         result = write_constant_as_bytes (obstack, byte_order,
23398                                           type, value, len);
23399       break;
23400     case DW_FORM_data2:
23401       type = die_type (die, cu);
23402       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23403       if (result == NULL)
23404         result = write_constant_as_bytes (obstack, byte_order,
23405                                           type, value, len);
23406       break;
23407     case DW_FORM_data4:
23408       type = die_type (die, cu);
23409       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23410       if (result == NULL)
23411         result = write_constant_as_bytes (obstack, byte_order,
23412                                           type, value, len);
23413       break;
23414     case DW_FORM_data8:
23415       type = die_type (die, cu);
23416       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23417       if (result == NULL)
23418         result = write_constant_as_bytes (obstack, byte_order,
23419                                           type, value, len);
23420       break;
23421
23422     case DW_FORM_sdata:
23423     case DW_FORM_implicit_const:
23424       type = die_type (die, cu);
23425       result = write_constant_as_bytes (obstack, byte_order,
23426                                         type, attr->as_signed (), len);
23427       break;
23428
23429     case DW_FORM_udata:
23430       type = die_type (die, cu);
23431       result = write_constant_as_bytes (obstack, byte_order,
23432                                         type, attr->as_unsigned (), len);
23433       break;
23434
23435     default:
23436       complaint (_("unsupported const value attribute form: '%s'"),
23437                  dwarf_form_name (attr->form));
23438       break;
23439     }
23440
23441   return result;
23442 }
23443
23444 /* See read.h.  */
23445
23446 struct type *
23447 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23448                                 dwarf2_per_cu_data *per_cu,
23449                                 dwarf2_per_objfile *per_objfile,
23450                                 const char **var_name)
23451 {
23452   struct die_info *die;
23453
23454   dwarf2_cu *cu = per_objfile->get_cu (per_cu);
23455   if (cu == nullptr)
23456     cu = load_cu (per_cu, per_objfile, false);
23457
23458   if (cu == nullptr)
23459     return nullptr;
23460
23461   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23462   if (!die)
23463     return NULL;
23464
23465   if (var_name != nullptr)
23466     *var_name = var_decl_name (die, cu);
23467   return die_type (die, cu);
23468 }
23469
23470 /* See read.h.  */
23471
23472 struct type *
23473 dwarf2_get_die_type (cu_offset die_offset,
23474                      dwarf2_per_cu_data *per_cu,
23475                      dwarf2_per_objfile *per_objfile)
23476 {
23477   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23478   return get_die_type_at_offset (die_offset_sect, per_cu, per_objfile);
23479 }
23480
23481 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23482    On entry *REF_CU is the CU of SRC_DIE.
23483    On exit *REF_CU is the CU of the result.
23484    Returns NULL if the referenced DIE isn't found.  */
23485
23486 static struct die_info *
23487 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23488                   struct dwarf2_cu **ref_cu)
23489 {
23490   struct die_info temp_die;
23491   struct dwarf2_cu *sig_cu;
23492   struct die_info *die;
23493   dwarf2_per_objfile *per_objfile = (*ref_cu)->per_objfile;
23494
23495
23496   /* While it might be nice to assert sig_type->type == NULL here,
23497      we can get here for DW_AT_imported_declaration where we need
23498      the DIE not the type.  */
23499
23500   /* If necessary, add it to the queue and load its DIEs.
23501
23502      Even if maybe_queue_comp_unit doesn't require us to load the CU's DIEs,
23503      it doesn't mean they are currently loaded.  Since we require them
23504      to be loaded, we must check for ourselves.  */
23505   if (maybe_queue_comp_unit (*ref_cu, sig_type, per_objfile,
23506                              language_minimal)
23507       || per_objfile->get_cu (sig_type) == nullptr)
23508     read_signatured_type (sig_type, per_objfile);
23509
23510   sig_cu = per_objfile->get_cu (sig_type);
23511   gdb_assert (sig_cu != NULL);
23512   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23513   temp_die.sect_off = sig_type->type_offset_in_section;
23514   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23515                                                  to_underlying (temp_die.sect_off));
23516   if (die)
23517     {
23518       /* For .gdb_index version 7 keep track of included TUs.
23519          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23520       if (per_objfile->per_bfd->index_table != NULL
23521           && per_objfile->per_bfd->index_table->version <= 7)
23522         {
23523           (*ref_cu)->per_cu->imported_symtabs_push (sig_cu->per_cu);
23524         }
23525
23526       *ref_cu = sig_cu;
23527       return die;
23528     }
23529
23530   return NULL;
23531 }
23532
23533 /* Follow signatured type referenced by ATTR in SRC_DIE.
23534    On entry *REF_CU is the CU of SRC_DIE.
23535    On exit *REF_CU is the CU of the result.
23536    The result is the DIE of the type.
23537    If the referenced type cannot be found an error is thrown.  */
23538
23539 static struct die_info *
23540 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23541                 struct dwarf2_cu **ref_cu)
23542 {
23543   ULONGEST signature = attr->as_signature ();
23544   struct signatured_type *sig_type;
23545   struct die_info *die;
23546
23547   gdb_assert (attr->form == DW_FORM_ref_sig8);
23548
23549   sig_type = lookup_signatured_type (*ref_cu, signature);
23550   /* sig_type will be NULL if the signatured type is missing from
23551      the debug info.  */
23552   if (sig_type == NULL)
23553     {
23554       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23555                " from DIE at %s [in module %s]"),
23556              hex_string (signature), sect_offset_str (src_die->sect_off),
23557              objfile_name ((*ref_cu)->per_objfile->objfile));
23558     }
23559
23560   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23561   if (die == NULL)
23562     {
23563       dump_die_for_error (src_die);
23564       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23565                " from DIE at %s [in module %s]"),
23566              hex_string (signature), sect_offset_str (src_die->sect_off),
23567              objfile_name ((*ref_cu)->per_objfile->objfile));
23568     }
23569
23570   return die;
23571 }
23572
23573 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23574    reading in and processing the type unit if necessary.  */
23575
23576 static struct type *
23577 get_signatured_type (struct die_info *die, ULONGEST signature,
23578                      struct dwarf2_cu *cu)
23579 {
23580   dwarf2_per_objfile *per_objfile = cu->per_objfile;
23581   struct signatured_type *sig_type;
23582   struct dwarf2_cu *type_cu;
23583   struct die_info *type_die;
23584   struct type *type;
23585
23586   sig_type = lookup_signatured_type (cu, signature);
23587   /* sig_type will be NULL if the signatured type is missing from
23588      the debug info.  */
23589   if (sig_type == NULL)
23590     {
23591       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23592                    " from DIE at %s [in module %s]"),
23593                  hex_string (signature), sect_offset_str (die->sect_off),
23594                  objfile_name (per_objfile->objfile));
23595       return build_error_marker_type (cu, die);
23596     }
23597
23598   /* If we already know the type we're done.  */
23599   type = per_objfile->get_type_for_signatured_type (sig_type);
23600   if (type != nullptr)
23601     return type;
23602
23603   type_cu = cu;
23604   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23605   if (type_die != NULL)
23606     {
23607       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23608          is created.  This is important, for example, because for c++ classes
23609          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23610       type = read_type_die (type_die, type_cu);
23611       if (type == NULL)
23612         {
23613           complaint (_("Dwarf Error: Cannot build signatured type %s"
23614                        " referenced from DIE at %s [in module %s]"),
23615                      hex_string (signature), sect_offset_str (die->sect_off),
23616                      objfile_name (per_objfile->objfile));
23617           type = build_error_marker_type (cu, die);
23618         }
23619     }
23620   else
23621     {
23622       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23623                    " from DIE at %s [in module %s]"),
23624                  hex_string (signature), sect_offset_str (die->sect_off),
23625                  objfile_name (per_objfile->objfile));
23626       type = build_error_marker_type (cu, die);
23627     }
23628
23629   per_objfile->set_type_for_signatured_type (sig_type, type);
23630
23631   return type;
23632 }
23633
23634 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23635    reading in and processing the type unit if necessary.  */
23636
23637 static struct type *
23638 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23639                           struct dwarf2_cu *cu) /* ARI: editCase function */
23640 {
23641   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23642   if (attr->form_is_ref ())
23643     {
23644       struct dwarf2_cu *type_cu = cu;
23645       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23646
23647       return read_type_die (type_die, type_cu);
23648     }
23649   else if (attr->form == DW_FORM_ref_sig8)
23650     {
23651       return get_signatured_type (die, attr->as_signature (), cu);
23652     }
23653   else
23654     {
23655       dwarf2_per_objfile *per_objfile = cu->per_objfile;
23656
23657       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23658                    " at %s [in module %s]"),
23659                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23660                  objfile_name (per_objfile->objfile));
23661       return build_error_marker_type (cu, die);
23662     }
23663 }
23664
23665 /* Load the DIEs associated with type unit PER_CU into memory.  */
23666
23667 static void
23668 load_full_type_unit (dwarf2_per_cu_data *per_cu,
23669                      dwarf2_per_objfile *per_objfile)
23670 {
23671   struct signatured_type *sig_type;
23672
23673   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23674   gdb_assert (! per_cu->type_unit_group_p ());
23675
23676   /* We have the per_cu, but we need the signatured_type.
23677      Fortunately this is an easy translation.  */
23678   gdb_assert (per_cu->is_debug_types);
23679   sig_type = (struct signatured_type *) per_cu;
23680
23681   gdb_assert (per_objfile->get_cu (per_cu) == nullptr);
23682
23683   read_signatured_type (sig_type, per_objfile);
23684
23685   gdb_assert (per_objfile->get_cu (per_cu) != nullptr);
23686 }
23687
23688 /* Read in a signatured type and build its CU and DIEs.
23689    If the type is a stub for the real type in a DWO file,
23690    read in the real type from the DWO file as well.  */
23691
23692 static void
23693 read_signatured_type (signatured_type *sig_type,
23694                       dwarf2_per_objfile *per_objfile)
23695 {
23696   gdb_assert (sig_type->is_debug_types);
23697   gdb_assert (per_objfile->get_cu (sig_type) == nullptr);
23698
23699   cutu_reader reader (sig_type, per_objfile, nullptr, nullptr, false);
23700
23701   if (!reader.dummy_p)
23702     {
23703       struct dwarf2_cu *cu = reader.cu;
23704       const gdb_byte *info_ptr = reader.info_ptr;
23705
23706       gdb_assert (cu->die_hash == NULL);
23707       cu->die_hash =
23708         htab_create_alloc_ex (cu->header.length / 12,
23709                               die_hash,
23710                               die_eq,
23711                               NULL,
23712                               &cu->comp_unit_obstack,
23713                               hashtab_obstack_allocate,
23714                               dummy_obstack_deallocate);
23715
23716       if (reader.comp_unit_die->has_children)
23717         reader.comp_unit_die->child
23718           = read_die_and_siblings (&reader, info_ptr, &info_ptr,
23719                                    reader.comp_unit_die);
23720       cu->dies = reader.comp_unit_die;
23721       /* comp_unit_die is not stored in die_hash, no need.  */
23722
23723       /* We try not to read any attributes in this function, because
23724          not all CUs needed for references have been loaded yet, and
23725          symbol table processing isn't initialized.  But we have to
23726          set the CU language, or we won't be able to build types
23727          correctly.  Similarly, if we do not read the producer, we can
23728          not apply producer-specific interpretation.  */
23729       prepare_one_comp_unit (cu, cu->dies, language_minimal);
23730
23731       reader.keep ();
23732     }
23733
23734   sig_type->tu_read = 1;
23735 }
23736
23737 /* Decode simple location descriptions.
23738    Given a pointer to a dwarf block that defines a location, compute
23739    the location and return the value.  If COMPUTED is non-null, it is
23740    set to true to indicate that decoding was successful, and false
23741    otherwise.  If COMPUTED is null, then this function may emit a
23742    complaint.  */
23743
23744 static CORE_ADDR
23745 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu, bool *computed)
23746 {
23747   struct objfile *objfile = cu->per_objfile->objfile;
23748   size_t i;
23749   size_t size = blk->size;
23750   const gdb_byte *data = blk->data;
23751   CORE_ADDR stack[64];
23752   int stacki;
23753   unsigned int bytes_read, unsnd;
23754   gdb_byte op;
23755
23756   if (computed != nullptr)
23757     *computed = false;
23758
23759   i = 0;
23760   stacki = 0;
23761   stack[stacki] = 0;
23762   stack[++stacki] = 0;
23763
23764   while (i < size)
23765     {
23766       op = data[i++];
23767       switch (op)
23768         {
23769         case DW_OP_lit0:
23770         case DW_OP_lit1:
23771         case DW_OP_lit2:
23772         case DW_OP_lit3:
23773         case DW_OP_lit4:
23774         case DW_OP_lit5:
23775         case DW_OP_lit6:
23776         case DW_OP_lit7:
23777         case DW_OP_lit8:
23778         case DW_OP_lit9:
23779         case DW_OP_lit10:
23780         case DW_OP_lit11:
23781         case DW_OP_lit12:
23782         case DW_OP_lit13:
23783         case DW_OP_lit14:
23784         case DW_OP_lit15:
23785         case DW_OP_lit16:
23786         case DW_OP_lit17:
23787         case DW_OP_lit18:
23788         case DW_OP_lit19:
23789         case DW_OP_lit20:
23790         case DW_OP_lit21:
23791         case DW_OP_lit22:
23792         case DW_OP_lit23:
23793         case DW_OP_lit24:
23794         case DW_OP_lit25:
23795         case DW_OP_lit26:
23796         case DW_OP_lit27:
23797         case DW_OP_lit28:
23798         case DW_OP_lit29:
23799         case DW_OP_lit30:
23800         case DW_OP_lit31:
23801           stack[++stacki] = op - DW_OP_lit0;
23802           break;
23803
23804         case DW_OP_reg0:
23805         case DW_OP_reg1:
23806         case DW_OP_reg2:
23807         case DW_OP_reg3:
23808         case DW_OP_reg4:
23809         case DW_OP_reg5:
23810         case DW_OP_reg6:
23811         case DW_OP_reg7:
23812         case DW_OP_reg8:
23813         case DW_OP_reg9:
23814         case DW_OP_reg10:
23815         case DW_OP_reg11:
23816         case DW_OP_reg12:
23817         case DW_OP_reg13:
23818         case DW_OP_reg14:
23819         case DW_OP_reg15:
23820         case DW_OP_reg16:
23821         case DW_OP_reg17:
23822         case DW_OP_reg18:
23823         case DW_OP_reg19:
23824         case DW_OP_reg20:
23825         case DW_OP_reg21:
23826         case DW_OP_reg22:
23827         case DW_OP_reg23:
23828         case DW_OP_reg24:
23829         case DW_OP_reg25:
23830         case DW_OP_reg26:
23831         case DW_OP_reg27:
23832         case DW_OP_reg28:
23833         case DW_OP_reg29:
23834         case DW_OP_reg30:
23835         case DW_OP_reg31:
23836           stack[++stacki] = op - DW_OP_reg0;
23837           if (i < size)
23838             {
23839               if (computed == nullptr)
23840                 dwarf2_complex_location_expr_complaint ();
23841               else
23842                 return 0;
23843             }
23844           break;
23845
23846         case DW_OP_regx:
23847           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23848           i += bytes_read;
23849           stack[++stacki] = unsnd;
23850           if (i < size)
23851             {
23852               if (computed == nullptr)
23853                 dwarf2_complex_location_expr_complaint ();
23854               else
23855                 return 0;
23856             }
23857           break;
23858
23859         case DW_OP_addr:
23860           stack[++stacki] = cu->header.read_address (objfile->obfd, &data[i],
23861                                                      &bytes_read);
23862           i += bytes_read;
23863           break;
23864
23865         case DW_OP_const1u:
23866           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23867           i += 1;
23868           break;
23869
23870         case DW_OP_const1s:
23871           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23872           i += 1;
23873           break;
23874
23875         case DW_OP_const2u:
23876           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23877           i += 2;
23878           break;
23879
23880         case DW_OP_const2s:
23881           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23882           i += 2;
23883           break;
23884
23885         case DW_OP_const4u:
23886           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23887           i += 4;
23888           break;
23889
23890         case DW_OP_const4s:
23891           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23892           i += 4;
23893           break;
23894
23895         case DW_OP_const8u:
23896           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23897           i += 8;
23898           break;
23899
23900         case DW_OP_constu:
23901           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23902                                                   &bytes_read);
23903           i += bytes_read;
23904           break;
23905
23906         case DW_OP_consts:
23907           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23908           i += bytes_read;
23909           break;
23910
23911         case DW_OP_dup:
23912           stack[stacki + 1] = stack[stacki];
23913           stacki++;
23914           break;
23915
23916         case DW_OP_plus:
23917           stack[stacki - 1] += stack[stacki];
23918           stacki--;
23919           break;
23920
23921         case DW_OP_plus_uconst:
23922           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23923                                                  &bytes_read);
23924           i += bytes_read;
23925           break;
23926
23927         case DW_OP_minus:
23928           stack[stacki - 1] -= stack[stacki];
23929           stacki--;
23930           break;
23931
23932         case DW_OP_deref:
23933           /* If we're not the last op, then we definitely can't encode
23934              this using GDB's address_class enum.  This is valid for partial
23935              global symbols, although the variable's address will be bogus
23936              in the psymtab.  */
23937           if (i < size)
23938             {
23939               if (computed == nullptr)
23940                 dwarf2_complex_location_expr_complaint ();
23941               else
23942                 return 0;
23943             }
23944           break;
23945
23946         case DW_OP_GNU_push_tls_address:
23947         case DW_OP_form_tls_address:
23948           /* The top of the stack has the offset from the beginning
23949              of the thread control block at which the variable is located.  */
23950           /* Nothing should follow this operator, so the top of stack would
23951              be returned.  */
23952           /* This is valid for partial global symbols, but the variable's
23953              address will be bogus in the psymtab.  Make it always at least
23954              non-zero to not look as a variable garbage collected by linker
23955              which have DW_OP_addr 0.  */
23956           if (i < size)
23957             {
23958               if (computed == nullptr)
23959                 dwarf2_complex_location_expr_complaint ();
23960               else
23961                 return 0;
23962             }
23963           stack[stacki]++;
23964           break;
23965
23966         case DW_OP_GNU_uninit:
23967           if (computed != nullptr)
23968             return 0;
23969           break;
23970
23971         case DW_OP_addrx:
23972         case DW_OP_GNU_addr_index:
23973         case DW_OP_GNU_const_index:
23974           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23975                                                          &bytes_read);
23976           i += bytes_read;
23977           break;
23978
23979         default:
23980           if (computed == nullptr)
23981             {
23982               const char *name = get_DW_OP_name (op);
23983
23984               if (name)
23985                 complaint (_("unsupported stack op: '%s'"),
23986                            name);
23987               else
23988                 complaint (_("unsupported stack op: '%02x'"),
23989                            op);
23990             }
23991
23992           return (stack[stacki]);
23993         }
23994
23995       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23996          outside of the allocated space.  Also enforce minimum>0.  */
23997       if (stacki >= ARRAY_SIZE (stack) - 1)
23998         {
23999           if (computed == nullptr)
24000             complaint (_("location description stack overflow"));
24001           return 0;
24002         }
24003
24004       if (stacki <= 0)
24005         {
24006           if (computed == nullptr)
24007             complaint (_("location description stack underflow"));
24008           return 0;
24009         }
24010     }
24011
24012   if (computed != nullptr)
24013     *computed = true;
24014   return (stack[stacki]);
24015 }
24016
24017 /* memory allocation interface */
24018
24019 static struct dwarf_block *
24020 dwarf_alloc_block (struct dwarf2_cu *cu)
24021 {
24022   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24023 }
24024
24025 static struct die_info *
24026 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24027 {
24028   struct die_info *die;
24029   size_t size = sizeof (struct die_info);
24030
24031   if (num_attrs > 1)
24032     size += (num_attrs - 1) * sizeof (struct attribute);
24033
24034   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24035   memset (die, 0, sizeof (struct die_info));
24036   return (die);
24037 }
24038
24039 \f
24040
24041 /* Macro support.  */
24042
24043 /* An overload of dwarf_decode_macros that finds the correct section
24044    and ensures it is read in before calling the other overload.  */
24045
24046 static void
24047 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24048                      int section_is_gnu)
24049 {
24050   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24051   struct objfile *objfile = per_objfile->objfile;
24052   const struct line_header *lh = cu->line_header;
24053   unsigned int offset_size = cu->header.offset_size;
24054   struct dwarf2_section_info *section;
24055   const char *section_name;
24056
24057   if (cu->dwo_unit != nullptr)
24058     {
24059       if (section_is_gnu)
24060         {
24061           section = &cu->dwo_unit->dwo_file->sections.macro;
24062           section_name = ".debug_macro.dwo";
24063         }
24064       else
24065         {
24066           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24067           section_name = ".debug_macinfo.dwo";
24068         }
24069     }
24070   else
24071     {
24072       if (section_is_gnu)
24073         {
24074           section = &per_objfile->per_bfd->macro;
24075           section_name = ".debug_macro";
24076         }
24077       else
24078         {
24079           section = &per_objfile->per_bfd->macinfo;
24080           section_name = ".debug_macinfo";
24081         }
24082     }
24083
24084   section->read (objfile);
24085   if (section->buffer == nullptr)
24086     {
24087       complaint (_("missing %s section"), section_name);
24088       return;
24089     }
24090
24091   buildsym_compunit *builder = cu->get_builder ();
24092
24093   struct dwarf2_section_info *str_offsets_section;
24094   struct dwarf2_section_info *str_section;
24095   ULONGEST str_offsets_base;
24096
24097   if (cu->dwo_unit != nullptr)
24098     {
24099       str_offsets_section = &cu->dwo_unit->dwo_file
24100                                ->sections.str_offsets;
24101       str_section = &cu->dwo_unit->dwo_file->sections.str;
24102       str_offsets_base = cu->header.addr_size;
24103     }
24104   else
24105     {
24106       str_offsets_section = &per_objfile->per_bfd->str_offsets;
24107       str_section = &per_objfile->per_bfd->str;
24108       str_offsets_base = *cu->str_offsets_base;
24109     }
24110
24111   dwarf_decode_macros (per_objfile, builder, section, lh,
24112                        offset_size, offset, str_section, str_offsets_section,
24113                        str_offsets_base, section_is_gnu);
24114 }
24115
24116 /* Return the .debug_loc section to use for CU.
24117    For DWO files use .debug_loc.dwo.  */
24118
24119 static struct dwarf2_section_info *
24120 cu_debug_loc_section (struct dwarf2_cu *cu)
24121 {
24122   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24123
24124   if (cu->dwo_unit)
24125     {
24126       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24127
24128       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24129     }
24130   return (cu->header.version >= 5 ? &per_objfile->per_bfd->loclists
24131                                   : &per_objfile->per_bfd->loc);
24132 }
24133
24134 /* Return the .debug_rnglists section to use for CU.  */
24135 static struct dwarf2_section_info *
24136 cu_debug_rnglists_section (struct dwarf2_cu *cu, dwarf_tag tag)
24137 {
24138   if (cu->header.version < 5)
24139     error (_(".debug_rnglists section cannot be used in DWARF %d"),
24140            cu->header.version);
24141   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->per_objfile;
24142
24143   /* Make sure we read the .debug_rnglists section from the file that
24144      contains the DW_AT_ranges attribute we are reading.  Normally that
24145      would be the .dwo file, if there is one.  However for DW_TAG_compile_unit
24146      or DW_TAG_skeleton unit, we always want to read from objfile/linked
24147      program.  */
24148   if (cu->dwo_unit != nullptr
24149       && tag != DW_TAG_compile_unit
24150       && tag != DW_TAG_skeleton_unit)
24151     {
24152       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24153
24154       if (sections->rnglists.size > 0)
24155         return &sections->rnglists;
24156       else
24157         error (_(".debug_rnglists section is missing from .dwo file."));
24158     }
24159   return &dwarf2_per_objfile->per_bfd->rnglists;
24160 }
24161
24162 /* A helper function that fills in a dwarf2_loclist_baton.  */
24163
24164 static void
24165 fill_in_loclist_baton (struct dwarf2_cu *cu,
24166                        struct dwarf2_loclist_baton *baton,
24167                        const struct attribute *attr)
24168 {
24169   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24170   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24171
24172   section->read (per_objfile->objfile);
24173
24174   baton->per_objfile = per_objfile;
24175   baton->per_cu = cu->per_cu;
24176   gdb_assert (baton->per_cu);
24177   /* We don't know how long the location list is, but make sure we
24178      don't run off the edge of the section.  */
24179   baton->size = section->size - attr->as_unsigned ();
24180   baton->data = section->buffer + attr->as_unsigned ();
24181   if (cu->base_address.has_value ())
24182     baton->base_address = *cu->base_address;
24183   else
24184     baton->base_address = 0;
24185   baton->from_dwo = cu->dwo_unit != NULL;
24186 }
24187
24188 static void
24189 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24190                              struct dwarf2_cu *cu, int is_block)
24191 {
24192   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24193   struct objfile *objfile = per_objfile->objfile;
24194   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24195
24196   if (attr->form_is_section_offset ()
24197       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24198          the section.  If so, fall through to the complaint in the
24199          other branch.  */
24200       && attr->as_unsigned () < section->get_size (objfile))
24201     {
24202       struct dwarf2_loclist_baton *baton;
24203
24204       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24205
24206       fill_in_loclist_baton (cu, baton, attr);
24207
24208       if (!cu->base_address.has_value ())
24209         complaint (_("Location list used without "
24210                      "specifying the CU base address."));
24211
24212       SYMBOL_ACLASS_INDEX (sym) = (is_block
24213                                    ? dwarf2_loclist_block_index
24214                                    : dwarf2_loclist_index);
24215       SYMBOL_LOCATION_BATON (sym) = baton;
24216     }
24217   else
24218     {
24219       struct dwarf2_locexpr_baton *baton;
24220
24221       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24222       baton->per_objfile = per_objfile;
24223       baton->per_cu = cu->per_cu;
24224       gdb_assert (baton->per_cu);
24225
24226       if (attr->form_is_block ())
24227         {
24228           /* Note that we're just copying the block's data pointer
24229              here, not the actual data.  We're still pointing into the
24230              info_buffer for SYM's objfile; right now we never release
24231              that buffer, but when we do clean up properly this may
24232              need to change.  */
24233           struct dwarf_block *block = attr->as_block ();
24234           baton->size = block->size;
24235           baton->data = block->data;
24236         }
24237       else
24238         {
24239           dwarf2_invalid_attrib_class_complaint ("location description",
24240                                                  sym->natural_name ());
24241           baton->size = 0;
24242         }
24243
24244       SYMBOL_ACLASS_INDEX (sym) = (is_block
24245                                    ? dwarf2_locexpr_block_index
24246                                    : dwarf2_locexpr_index);
24247       SYMBOL_LOCATION_BATON (sym) = baton;
24248     }
24249 }
24250
24251 /* See read.h.  */
24252
24253 const comp_unit_head *
24254 dwarf2_per_cu_data::get_header () const
24255 {
24256   if (!m_header_read_in)
24257     {
24258       const gdb_byte *info_ptr
24259         = this->section->buffer + to_underlying (this->sect_off);
24260
24261       memset (&m_header, 0, sizeof (m_header));
24262
24263       read_comp_unit_head (&m_header, info_ptr, this->section,
24264                            rcuh_kind::COMPILE);
24265
24266       m_header_read_in = true;
24267     }
24268
24269   return &m_header;
24270 }
24271
24272 /* See read.h.  */
24273
24274 int
24275 dwarf2_per_cu_data::addr_size () const
24276 {
24277   return this->get_header ()->addr_size;
24278 }
24279
24280 /* See read.h.  */
24281
24282 int
24283 dwarf2_per_cu_data::offset_size () const
24284 {
24285   return this->get_header ()->offset_size;
24286 }
24287
24288 /* See read.h.  */
24289
24290 int
24291 dwarf2_per_cu_data::ref_addr_size () const
24292 {
24293   const comp_unit_head *header = this->get_header ();
24294
24295   if (header->version == 2)
24296     return header->addr_size;
24297   else
24298     return header->offset_size;
24299 }
24300
24301 /* A helper function for dwarf2_find_containing_comp_unit that returns
24302    the index of the result, and that searches a vector.  It will
24303    return a result even if the offset in question does not actually
24304    occur in any CU.  This is separate so that it can be unit
24305    tested.  */
24306
24307 static int
24308 dwarf2_find_containing_comp_unit
24309   (sect_offset sect_off,
24310    unsigned int offset_in_dwz,
24311    const std::vector<dwarf2_per_cu_data_up> &all_comp_units)
24312 {
24313   int low, high;
24314
24315   low = 0;
24316   high = all_comp_units.size () - 1;
24317   while (high > low)
24318     {
24319       struct dwarf2_per_cu_data *mid_cu;
24320       int mid = low + (high - low) / 2;
24321
24322       mid_cu = all_comp_units[mid].get ();
24323       if (mid_cu->is_dwz > offset_in_dwz
24324           || (mid_cu->is_dwz == offset_in_dwz
24325               && mid_cu->sect_off + mid_cu->length > sect_off))
24326         high = mid;
24327       else
24328         low = mid + 1;
24329     }
24330   gdb_assert (low == high);
24331   return low;
24332 }
24333
24334 /* Locate the .debug_info compilation unit from CU's objfile which contains
24335    the DIE at OFFSET.  Raises an error on failure.  */
24336
24337 static struct dwarf2_per_cu_data *
24338 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24339                                   unsigned int offset_in_dwz,
24340                                   dwarf2_per_objfile *per_objfile)
24341 {
24342   int low = dwarf2_find_containing_comp_unit
24343     (sect_off, offset_in_dwz, per_objfile->per_bfd->all_comp_units);
24344   dwarf2_per_cu_data *this_cu
24345     = per_objfile->per_bfd->all_comp_units[low].get ();
24346
24347   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
24348     {
24349       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24350         error (_("Dwarf Error: could not find partial DIE containing "
24351                "offset %s [in module %s]"),
24352                sect_offset_str (sect_off),
24353                bfd_get_filename (per_objfile->objfile->obfd));
24354
24355       gdb_assert (per_objfile->per_bfd->all_comp_units[low-1]->sect_off
24356                   <= sect_off);
24357       return per_objfile->per_bfd->all_comp_units[low - 1].get ();
24358     }
24359   else
24360     {
24361       if (low == per_objfile->per_bfd->all_comp_units.size () - 1
24362           && sect_off >= this_cu->sect_off + this_cu->length)
24363         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24364       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24365       return this_cu;
24366     }
24367 }
24368
24369 #if GDB_SELF_TEST
24370
24371 namespace selftests {
24372 namespace find_containing_comp_unit {
24373
24374 static void
24375 run_test ()
24376 {
24377   dwarf2_per_cu_data_up one (new dwarf2_per_cu_data);
24378   dwarf2_per_cu_data *one_ptr = one.get ();
24379   dwarf2_per_cu_data_up two (new dwarf2_per_cu_data);
24380   dwarf2_per_cu_data *two_ptr = two.get ();
24381   dwarf2_per_cu_data_up three (new dwarf2_per_cu_data);
24382   dwarf2_per_cu_data *three_ptr = three.get ();
24383   dwarf2_per_cu_data_up four (new dwarf2_per_cu_data);
24384   dwarf2_per_cu_data *four_ptr = four.get ();
24385
24386   one->length = 5;
24387   two->sect_off = sect_offset (one->length);
24388   two->length = 7;
24389
24390   three->length = 5;
24391   three->is_dwz = 1;
24392   four->sect_off = sect_offset (three->length);
24393   four->length = 7;
24394   four->is_dwz = 1;
24395
24396   std::vector<dwarf2_per_cu_data_up> units;
24397   units.push_back (std::move (one));
24398   units.push_back (std::move (two));
24399   units.push_back (std::move (three));
24400   units.push_back (std::move (four));
24401
24402   int result;
24403
24404   result = dwarf2_find_containing_comp_unit (sect_offset (0), 0, units);
24405   SELF_CHECK (units[result].get () == one_ptr);
24406   result = dwarf2_find_containing_comp_unit (sect_offset (3), 0, units);
24407   SELF_CHECK (units[result].get () == one_ptr);
24408   result = dwarf2_find_containing_comp_unit (sect_offset (5), 0, units);
24409   SELF_CHECK (units[result].get () == two_ptr);
24410
24411   result = dwarf2_find_containing_comp_unit (sect_offset (0), 1, units);
24412   SELF_CHECK (units[result].get () == three_ptr);
24413   result = dwarf2_find_containing_comp_unit (sect_offset (3), 1, units);
24414   SELF_CHECK (units[result].get () == three_ptr);
24415   result = dwarf2_find_containing_comp_unit (sect_offset (5), 1, units);
24416   SELF_CHECK (units[result].get () == four_ptr);
24417 }
24418
24419 }
24420 }
24421
24422 #endif /* GDB_SELF_TEST */
24423
24424 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24425
24426 static void
24427 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24428                        enum language pretend_language)
24429 {
24430   struct attribute *attr;
24431
24432   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24433
24434   /* Set the language we're debugging.  */
24435   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24436   if (cu->producer != nullptr
24437       && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
24438     {
24439       /* The XLCL doesn't generate DW_LANG_OpenCL because this
24440          attribute is not standardised yet.  As a workaround for the
24441          language detection we fall back to the DW_AT_producer
24442          string.  */
24443       cu->per_cu->lang = language_opencl;
24444     }
24445   else if (cu->producer != nullptr
24446            && strstr (cu->producer, "GNU Go ") != NULL)
24447     {
24448       /* Similar hack for Go.  */
24449       cu->per_cu->lang = language_go;
24450     }
24451   else if (attr != nullptr)
24452     cu->per_cu->lang = dwarf_lang_to_enum_language (attr->constant_value (0));
24453   else
24454     cu->per_cu->lang = pretend_language;
24455   cu->language_defn = language_def (cu->per_cu->lang);
24456 }
24457
24458 /* See read.h.  */
24459
24460 dwarf2_cu *
24461 dwarf2_per_objfile::get_cu (dwarf2_per_cu_data *per_cu)
24462 {
24463   auto it = m_dwarf2_cus.find (per_cu);
24464   if (it == m_dwarf2_cus.end ())
24465     return nullptr;
24466
24467   return it->second;
24468 }
24469
24470 /* See read.h.  */
24471
24472 void
24473 dwarf2_per_objfile::set_cu (dwarf2_per_cu_data *per_cu, dwarf2_cu *cu)
24474 {
24475   gdb_assert (this->get_cu (per_cu) == nullptr);
24476
24477   m_dwarf2_cus[per_cu] = cu;
24478 }
24479
24480 /* See read.h.  */
24481
24482 void
24483 dwarf2_per_objfile::age_comp_units ()
24484 {
24485   dwarf_read_debug_printf_v ("running");
24486
24487   /* This is not expected to be called in the middle of CU expansion.  There is
24488      an invariant that if a CU is in the CUs-to-expand queue, its DIEs are
24489      loaded in memory.  Calling age_comp_units while the queue is in use could
24490      make us free the DIEs for a CU that is in the queue and therefore break
24491      that invariant.  */
24492   gdb_assert (!this->per_bfd->queue.has_value ());
24493
24494   /* Start by clearing all marks.  */
24495   for (auto pair : m_dwarf2_cus)
24496     pair.second->clear_mark ();
24497
24498   /* Traverse all CUs, mark them and their dependencies if used recently
24499      enough.  */
24500   for (auto pair : m_dwarf2_cus)
24501     {
24502       dwarf2_cu *cu = pair.second;
24503
24504       cu->last_used++;
24505       if (cu->last_used <= dwarf_max_cache_age)
24506         cu->mark ();
24507     }
24508
24509   /* Delete all CUs still not marked.  */
24510   for (auto it = m_dwarf2_cus.begin (); it != m_dwarf2_cus.end ();)
24511     {
24512       dwarf2_cu *cu = it->second;
24513
24514       if (!cu->is_marked ())
24515         {
24516           dwarf_read_debug_printf_v ("deleting old CU %s",
24517                                      sect_offset_str (cu->per_cu->sect_off));
24518           delete cu;
24519           it = m_dwarf2_cus.erase (it);
24520         }
24521       else
24522         it++;
24523     }
24524 }
24525
24526 /* See read.h.  */
24527
24528 void
24529 dwarf2_per_objfile::remove_cu (dwarf2_per_cu_data *per_cu)
24530 {
24531   auto it = m_dwarf2_cus.find (per_cu);
24532   if (it == m_dwarf2_cus.end ())
24533     return;
24534
24535   delete it->second;
24536
24537   m_dwarf2_cus.erase (it);
24538 }
24539
24540 dwarf2_per_objfile::~dwarf2_per_objfile ()
24541 {
24542   remove_all_cus ();
24543 }
24544
24545 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
24546    We store these in a hash table separate from the DIEs, and preserve them
24547    when the DIEs are flushed out of cache.
24548
24549    The CU "per_cu" pointer is needed because offset alone is not enough to
24550    uniquely identify the type.  A file may have multiple .debug_types sections,
24551    or the type may come from a DWO file.  Furthermore, while it's more logical
24552    to use per_cu->section+offset, with Fission the section with the data is in
24553    the DWO file but we don't know that section at the point we need it.
24554    We have to use something in dwarf2_per_cu_data (or the pointer to it)
24555    because we can enter the lookup routine, get_die_type_at_offset, from
24556    outside this file, and thus won't necessarily have PER_CU->cu.
24557    Fortunately, PER_CU is stable for the life of the objfile.  */
24558
24559 struct dwarf2_per_cu_offset_and_type
24560 {
24561   const struct dwarf2_per_cu_data *per_cu;
24562   sect_offset sect_off;
24563   struct type *type;
24564 };
24565
24566 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
24567
24568 static hashval_t
24569 per_cu_offset_and_type_hash (const void *item)
24570 {
24571   const struct dwarf2_per_cu_offset_and_type *ofs
24572     = (const struct dwarf2_per_cu_offset_and_type *) item;
24573
24574   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
24575 }
24576
24577 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
24578
24579 static int
24580 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
24581 {
24582   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
24583     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
24584   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
24585     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
24586
24587   return (ofs_lhs->per_cu == ofs_rhs->per_cu
24588           && ofs_lhs->sect_off == ofs_rhs->sect_off);
24589 }
24590
24591 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
24592    table if necessary.  For convenience, return TYPE.
24593
24594    The DIEs reading must have careful ordering to:
24595     * Not cause infinite loops trying to read in DIEs as a prerequisite for
24596       reading current DIE.
24597     * Not trying to dereference contents of still incompletely read in types
24598       while reading in other DIEs.
24599     * Enable referencing still incompletely read in types just by a pointer to
24600       the type without accessing its fields.
24601
24602    Therefore caller should follow these rules:
24603      * Try to fetch any prerequisite types we may need to build this DIE type
24604        before building the type and calling set_die_type.
24605      * After building type call set_die_type for current DIE as soon as
24606        possible before fetching more types to complete the current type.
24607      * Make the type as complete as possible before fetching more types.  */
24608
24609 static struct type *
24610 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
24611               bool skip_data_location)
24612 {
24613   dwarf2_per_objfile *per_objfile = cu->per_objfile;
24614   struct dwarf2_per_cu_offset_and_type **slot, ofs;
24615   struct objfile *objfile = per_objfile->objfile;
24616   struct attribute *attr;
24617   struct dynamic_prop prop;
24618
24619   /* For Ada types, make sure that the gnat-specific data is always
24620      initialized (if not already set).  There are a few types where
24621      we should not be doing so, because the type-specific area is
24622      already used to hold some other piece of info (eg: TYPE_CODE_FLT
24623      where the type-specific area is used to store the floatformat).
24624      But this is not a problem, because the gnat-specific information
24625      is actually not needed for these types.  */
24626   if (need_gnat_info (cu)
24627       && type->code () != TYPE_CODE_FUNC
24628       && type->code () != TYPE_CODE_FLT
24629       && type->code () != TYPE_CODE_METHODPTR
24630       && type->code () != TYPE_CODE_MEMBERPTR
24631       && type->code () != TYPE_CODE_METHOD
24632       && type->code () != TYPE_CODE_FIXED_POINT
24633       && !HAVE_GNAT_AUX_INFO (type))
24634     INIT_GNAT_SPECIFIC (type);
24635
24636   /* Read DW_AT_allocated and set in type.  */
24637   attr = dwarf2_attr (die, DW_AT_allocated, cu);
24638   if (attr != NULL)
24639     {
24640       struct type *prop_type = cu->addr_sized_int_type (false);
24641       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
24642         type->add_dyn_prop (DYN_PROP_ALLOCATED, prop);
24643     }
24644
24645   /* Read DW_AT_associated and set in type.  */
24646   attr = dwarf2_attr (die, DW_AT_associated, cu);
24647   if (attr != NULL)
24648     {
24649       struct type *prop_type = cu->addr_sized_int_type (false);
24650       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
24651         type->add_dyn_prop (DYN_PROP_ASSOCIATED, prop);
24652     }
24653
24654   /* Read DW_AT_data_location and set in type.  */
24655   if (!skip_data_location)
24656     {
24657       attr = dwarf2_attr (die, DW_AT_data_location, cu);
24658       if (attr_to_dynamic_prop (attr, die, cu, &prop, cu->addr_type ()))
24659         type->add_dyn_prop (DYN_PROP_DATA_LOCATION, prop);
24660     }
24661
24662   if (per_objfile->die_type_hash == NULL)
24663     per_objfile->die_type_hash
24664       = htab_up (htab_create_alloc (127,
24665                                     per_cu_offset_and_type_hash,
24666                                     per_cu_offset_and_type_eq,
24667                                     NULL, xcalloc, xfree));
24668
24669   ofs.per_cu = cu->per_cu;
24670   ofs.sect_off = die->sect_off;
24671   ofs.type = type;
24672   slot = (struct dwarf2_per_cu_offset_and_type **)
24673     htab_find_slot (per_objfile->die_type_hash.get (), &ofs, INSERT);
24674   if (*slot)
24675     complaint (_("A problem internal to GDB: DIE %s has type already set"),
24676                sect_offset_str (die->sect_off));
24677   *slot = XOBNEW (&objfile->objfile_obstack,
24678                   struct dwarf2_per_cu_offset_and_type);
24679   **slot = ofs;
24680   return type;
24681 }
24682
24683 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
24684    or return NULL if the die does not have a saved type.  */
24685
24686 static struct type *
24687 get_die_type_at_offset (sect_offset sect_off,
24688                         dwarf2_per_cu_data *per_cu,
24689                         dwarf2_per_objfile *per_objfile)
24690 {
24691   struct dwarf2_per_cu_offset_and_type *slot, ofs;
24692
24693   if (per_objfile->die_type_hash == NULL)
24694     return NULL;
24695
24696   ofs.per_cu = per_cu;
24697   ofs.sect_off = sect_off;
24698   slot = ((struct dwarf2_per_cu_offset_and_type *)
24699           htab_find (per_objfile->die_type_hash.get (), &ofs));
24700   if (slot)
24701     return slot->type;
24702   else
24703     return NULL;
24704 }
24705
24706 /* Look up the type for DIE in CU in die_type_hash,
24707    or return NULL if DIE does not have a saved type.  */
24708
24709 static struct type *
24710 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
24711 {
24712   return get_die_type_at_offset (die->sect_off, cu->per_cu, cu->per_objfile);
24713 }
24714
24715 /* Trivial hash function for partial_die_info: the hash value of a DIE
24716    is its offset in .debug_info for this objfile.  */
24717
24718 static hashval_t
24719 partial_die_hash (const void *item)
24720 {
24721   const struct partial_die_info *part_die
24722     = (const struct partial_die_info *) item;
24723
24724   return to_underlying (part_die->sect_off);
24725 }
24726
24727 /* Trivial comparison function for partial_die_info structures: two DIEs
24728    are equal if they have the same offset.  */
24729
24730 static int
24731 partial_die_eq (const void *item_lhs, const void *item_rhs)
24732 {
24733   const struct partial_die_info *part_die_lhs
24734     = (const struct partial_die_info *) item_lhs;
24735   const struct partial_die_info *part_die_rhs
24736     = (const struct partial_die_info *) item_rhs;
24737
24738   return part_die_lhs->sect_off == part_die_rhs->sect_off;
24739 }
24740
24741 struct cmd_list_element *set_dwarf_cmdlist;
24742 struct cmd_list_element *show_dwarf_cmdlist;
24743
24744 static void
24745 show_check_physname (struct ui_file *file, int from_tty,
24746                      struct cmd_list_element *c, const char *value)
24747 {
24748   fprintf_filtered (file,
24749                     _("Whether to check \"physname\" is %s.\n"),
24750                     value);
24751 }
24752
24753 void _initialize_dwarf2_read ();
24754 void
24755 _initialize_dwarf2_read ()
24756 {
24757   add_basic_prefix_cmd ("dwarf", class_maintenance, _("\
24758 Set DWARF specific variables.\n\
24759 Configure DWARF variables such as the cache size."),
24760                         &set_dwarf_cmdlist,
24761                         0/*allow-unknown*/, &maintenance_set_cmdlist);
24762
24763   add_show_prefix_cmd ("dwarf", class_maintenance, _("\
24764 Show DWARF specific variables.\n\
24765 Show DWARF variables such as the cache size."),
24766                        &show_dwarf_cmdlist,
24767                        0/*allow-unknown*/, &maintenance_show_cmdlist);
24768
24769   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24770                             &dwarf_max_cache_age, _("\
24771 Set the upper bound on the age of cached DWARF compilation units."), _("\
24772 Show the upper bound on the age of cached DWARF compilation units."), _("\
24773 A higher limit means that cached compilation units will be stored\n\
24774 in memory longer, and more total memory will be used.  Zero disables\n\
24775 caching, which can slow down startup."),
24776                             NULL,
24777                             show_dwarf_max_cache_age,
24778                             &set_dwarf_cmdlist,
24779                             &show_dwarf_cmdlist);
24780
24781   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24782 Set debugging of the DWARF reader."), _("\
24783 Show debugging of the DWARF reader."), _("\
24784 When enabled (non-zero), debugging messages are printed during DWARF\n\
24785 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24786 information.  A value greater than 1 provides more verbose information."),
24787                             NULL,
24788                             NULL,
24789                             &setdebuglist, &showdebuglist);
24790
24791   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24792 Set debugging of the DWARF DIE reader."), _("\
24793 Show debugging of the DWARF DIE reader."), _("\
24794 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24795 The value is the maximum depth to print."),
24796                              NULL,
24797                              NULL,
24798                              &setdebuglist, &showdebuglist);
24799
24800   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24801 Set debugging of the dwarf line reader."), _("\
24802 Show debugging of the dwarf line reader."), _("\
24803 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24804 A value of 1 (one) provides basic information.\n\
24805 A value greater than 1 provides more verbose information."),
24806                              NULL,
24807                              NULL,
24808                              &setdebuglist, &showdebuglist);
24809
24810   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24811 Set cross-checking of \"physname\" code against demangler."), _("\
24812 Show cross-checking of \"physname\" code against demangler."), _("\
24813 When enabled, GDB's internal \"physname\" code is checked against\n\
24814 the demangler."),
24815                            NULL, show_check_physname,
24816                            &setdebuglist, &showdebuglist);
24817
24818   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24819                            no_class, &use_deprecated_index_sections, _("\
24820 Set whether to use deprecated gdb_index sections."), _("\
24821 Show whether to use deprecated gdb_index sections."), _("\
24822 When enabled, deprecated .gdb_index sections are used anyway.\n\
24823 Normally they are ignored either because of a missing feature or\n\
24824 performance issue.\n\
24825 Warning: This option must be enabled before gdb reads the file."),
24826                            NULL,
24827                            NULL,
24828                            &setlist, &showlist);
24829
24830   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24831                                                         &dwarf2_locexpr_funcs);
24832   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24833                                                         &dwarf2_loclist_funcs);
24834
24835   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24836                                         &dwarf2_block_frame_base_locexpr_funcs);
24837   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24838                                         &dwarf2_block_frame_base_loclist_funcs);
24839
24840 #if GDB_SELF_TEST
24841   selftests::register_test ("dw2_expand_symtabs_matching",
24842                             selftests::dw2_expand_symtabs_matching::run_test);
24843   selftests::register_test ("dwarf2_find_containing_comp_unit",
24844                             selftests::find_containing_comp_unit::run_test);
24845 #endif
24846 }
This page took 1.414371 seconds and 4 git commands to generate.