Move read_partial_die to partial_die_info::read
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89
90 /* When == 1, print basic high level tracing messages.
91    When > 1, be more verbose.
92    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
93 static unsigned int dwarf_read_debug = 0;
94
95 /* When non-zero, dump DIEs after they are read in.  */
96 static unsigned int dwarf_die_debug = 0;
97
98 /* When non-zero, dump line number entries as they are read in.  */
99 static unsigned int dwarf_line_debug = 0;
100
101 /* When non-zero, cross-check physname against demangler.  */
102 static int check_physname = 0;
103
104 /* When non-zero, do not reject deprecated .gdb_index sections.  */
105 static int use_deprecated_index_sections = 0;
106
107 static const struct objfile_data *dwarf2_objfile_data_key;
108
109 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
110
111 static int dwarf2_locexpr_index;
112 static int dwarf2_loclist_index;
113 static int dwarf2_locexpr_block_index;
114 static int dwarf2_loclist_block_index;
115
116 /* A descriptor for dwarf sections.
117
118    S.ASECTION, SIZE are typically initialized when the objfile is first
119    scanned.  BUFFER, READIN are filled in later when the section is read.
120    If the section contained compressed data then SIZE is updated to record
121    the uncompressed size of the section.
122
123    DWP file format V2 introduces a wrinkle that is easiest to handle by
124    creating the concept of virtual sections contained within a real section.
125    In DWP V2 the sections of the input DWO files are concatenated together
126    into one section, but section offsets are kept relative to the original
127    input section.
128    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
129    the real section this "virtual" section is contained in, and BUFFER,SIZE
130    describe the virtual section.  */
131
132 struct dwarf2_section_info
133 {
134   union
135   {
136     /* If this is a real section, the bfd section.  */
137     asection *section;
138     /* If this is a virtual section, pointer to the containing ("real")
139        section.  */
140     struct dwarf2_section_info *containing_section;
141   } s;
142   /* Pointer to section data, only valid if readin.  */
143   const gdb_byte *buffer;
144   /* The size of the section, real or virtual.  */
145   bfd_size_type size;
146   /* If this is a virtual section, the offset in the real section.
147      Only valid if is_virtual.  */
148   bfd_size_type virtual_offset;
149   /* True if we have tried to read this section.  */
150   char readin;
151   /* True if this is a virtual section, False otherwise.
152      This specifies which of s.section and s.containing_section to use.  */
153   char is_virtual;
154 };
155
156 typedef struct dwarf2_section_info dwarf2_section_info_def;
157 DEF_VEC_O (dwarf2_section_info_def);
158
159 /* All offsets in the index are of this type.  It must be
160    architecture-independent.  */
161 typedef uint32_t offset_type;
162
163 DEF_VEC_I (offset_type);
164
165 /* Ensure only legit values are used.  */
166 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
167   do { \
168     gdb_assert ((unsigned int) (value) <= 1); \
169     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
170   } while (0)
171
172 /* Ensure only legit values are used.  */
173 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
174   do { \
175     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
176                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
177     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
178   } while (0)
179
180 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
181 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
182   do { \
183     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
184     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
185   } while (0)
186
187 #if WORDS_BIGENDIAN
188
189 /* Convert VALUE between big- and little-endian.  */
190
191 static offset_type
192 byte_swap (offset_type value)
193 {
194   offset_type result;
195
196   result = (value & 0xff) << 24;
197   result |= (value & 0xff00) << 8;
198   result |= (value & 0xff0000) >> 8;
199   result |= (value & 0xff000000) >> 24;
200   return result;
201 }
202
203 #define MAYBE_SWAP(V)  byte_swap (V)
204
205 #else
206 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
207 #endif /* WORDS_BIGENDIAN */
208
209 /* An index into a (C++) symbol name component in a symbol name as
210    recorded in the mapped_index's symbol table.  For each C++ symbol
211    in the symbol table, we record one entry for the start of each
212    component in the symbol in a table of name components, and then
213    sort the table, in order to be able to binary search symbol names,
214    ignoring leading namespaces, both completion and regular look up.
215    For example, for symbol "A::B::C", we'll have an entry that points
216    to "A::B::C", another that points to "B::C", and another for "C".
217    Note that function symbols in GDB index have no parameter
218    information, just the function/method names.  You can convert a
219    name_component to a "const char *" using the
220    'mapped_index::symbol_name_at(offset_type)' method.  */
221
222 struct name_component
223 {
224   /* Offset in the symbol name where the component starts.  Stored as
225      a (32-bit) offset instead of a pointer to save memory and improve
226      locality on 64-bit architectures.  */
227   offset_type name_offset;
228
229   /* The symbol's index in the symbol and constant pool tables of a
230      mapped_index.  */
231   offset_type idx;
232 };
233
234 /* Base class containing bits shared by both .gdb_index and
235    .debug_name indexes.  */
236
237 struct mapped_index_base
238 {
239   /* The name_component table (a sorted vector).  See name_component's
240      description above.  */
241   std::vector<name_component> name_components;
242
243   /* How NAME_COMPONENTS is sorted.  */
244   enum case_sensitivity name_components_casing;
245
246   /* Return the number of names in the symbol table.  */
247   virtual size_t symbol_name_count () const = 0;
248
249   /* Get the name of the symbol at IDX in the symbol table.  */
250   virtual const char *symbol_name_at (offset_type idx) const = 0;
251
252   /* Return whether the name at IDX in the symbol table should be
253      ignored.  */
254   virtual bool symbol_name_slot_invalid (offset_type idx) const
255   {
256     return false;
257   }
258
259   /* Build the symbol name component sorted vector, if we haven't
260      yet.  */
261   void build_name_components ();
262
263   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
264      possible matches for LN_NO_PARAMS in the name component
265      vector.  */
266   std::pair<std::vector<name_component>::const_iterator,
267             std::vector<name_component>::const_iterator>
268     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
269
270   /* Prevent deleting/destroying via a base class pointer.  */
271 protected:
272   ~mapped_index_base() = default;
273 };
274
275 /* A description of the mapped index.  The file format is described in
276    a comment by the code that writes the index.  */
277 struct mapped_index final : public mapped_index_base
278 {
279   /* A slot/bucket in the symbol table hash.  */
280   struct symbol_table_slot
281   {
282     const offset_type name;
283     const offset_type vec;
284   };
285
286   /* Index data format version.  */
287   int version;
288
289   /* The total length of the buffer.  */
290   off_t total_size;
291
292   /* The address table data.  */
293   gdb::array_view<const gdb_byte> address_table;
294
295   /* The symbol table, implemented as a hash table.  */
296   gdb::array_view<symbol_table_slot> symbol_table;
297
298   /* A pointer to the constant pool.  */
299   const char *constant_pool;
300
301   bool symbol_name_slot_invalid (offset_type idx) const override
302   {
303     const auto &bucket = this->symbol_table[idx];
304     return bucket.name == 0 && bucket.vec;
305   }
306
307   /* Convenience method to get at the name of the symbol at IDX in the
308      symbol table.  */
309   const char *symbol_name_at (offset_type idx) const override
310   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
311
312   size_t symbol_name_count () const override
313   { return this->symbol_table.size (); }
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   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
321   : dwarf2_per_objfile (dwarf2_per_objfile_)
322   {}
323
324   struct dwarf2_per_objfile *dwarf2_per_objfile;
325   bfd_endian dwarf5_byte_order;
326   bool dwarf5_is_dwarf64;
327   bool augmentation_is_gdb;
328   uint8_t offset_size;
329   uint32_t cu_count = 0;
330   uint32_t tu_count, bucket_count, name_count;
331   const gdb_byte *cu_table_reordered, *tu_table_reordered;
332   const uint32_t *bucket_table_reordered, *hash_table_reordered;
333   const gdb_byte *name_table_string_offs_reordered;
334   const gdb_byte *name_table_entry_offs_reordered;
335   const gdb_byte *entry_pool;
336
337   struct index_val
338   {
339     ULONGEST dwarf_tag;
340     struct attr
341     {
342       /* Attribute name DW_IDX_*.  */
343       ULONGEST dw_idx;
344
345       /* Attribute form DW_FORM_*.  */
346       ULONGEST form;
347
348       /* Value if FORM is DW_FORM_implicit_const.  */
349       LONGEST implicit_const;
350     };
351     std::vector<attr> attr_vec;
352   };
353
354   std::unordered_map<ULONGEST, index_val> abbrev_map;
355
356   const char *namei_to_name (uint32_t namei) const;
357
358   /* Implementation of the mapped_index_base virtual interface, for
359      the name_components cache.  */
360
361   const char *symbol_name_at (offset_type idx) const override
362   { return namei_to_name (idx); }
363
364   size_t symbol_name_count () const override
365   { return this->name_count; }
366 };
367
368 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
369 DEF_VEC_P (dwarf2_per_cu_ptr);
370
371 struct tu_stats
372 {
373   int nr_uniq_abbrev_tables;
374   int nr_symtabs;
375   int nr_symtab_sharers;
376   int nr_stmt_less_type_units;
377   int nr_all_type_units_reallocs;
378 };
379
380 /* Collection of data recorded per objfile.
381    This hangs off of dwarf2_objfile_data_key.  */
382
383 struct dwarf2_per_objfile : public allocate_on_obstack
384 {
385   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
386      dwarf2 section names, or is NULL if the standard ELF names are
387      used.  */
388   dwarf2_per_objfile (struct objfile *objfile,
389                       const dwarf2_debug_sections *names);
390
391   ~dwarf2_per_objfile ();
392
393   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
394
395   /* Free all cached compilation units.  */
396   void free_cached_comp_units ();
397 private:
398   /* This function is mapped across the sections and remembers the
399      offset and size of each of the debugging sections we are
400      interested in.  */
401   void locate_sections (bfd *abfd, asection *sectp,
402                         const dwarf2_debug_sections &names);
403
404 public:
405   dwarf2_section_info info {};
406   dwarf2_section_info abbrev {};
407   dwarf2_section_info line {};
408   dwarf2_section_info loc {};
409   dwarf2_section_info loclists {};
410   dwarf2_section_info macinfo {};
411   dwarf2_section_info macro {};
412   dwarf2_section_info str {};
413   dwarf2_section_info line_str {};
414   dwarf2_section_info ranges {};
415   dwarf2_section_info rnglists {};
416   dwarf2_section_info addr {};
417   dwarf2_section_info frame {};
418   dwarf2_section_info eh_frame {};
419   dwarf2_section_info gdb_index {};
420   dwarf2_section_info debug_names {};
421   dwarf2_section_info debug_aranges {};
422
423   VEC (dwarf2_section_info_def) *types = NULL;
424
425   /* Back link.  */
426   struct objfile *objfile = NULL;
427
428   /* Table of all the compilation units.  This is used to locate
429      the target compilation unit of a particular reference.  */
430   struct dwarf2_per_cu_data **all_comp_units = NULL;
431
432   /* The number of compilation units in ALL_COMP_UNITS.  */
433   int n_comp_units = 0;
434
435   /* The number of .debug_types-related CUs.  */
436   int n_type_units = 0;
437
438   /* The number of elements allocated in all_type_units.
439      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
440   int n_allocated_type_units = 0;
441
442   /* The .debug_types-related CUs (TUs).
443      This is stored in malloc space because we may realloc it.  */
444   struct signatured_type **all_type_units = NULL;
445
446   /* Table of struct type_unit_group objects.
447      The hash key is the DW_AT_stmt_list value.  */
448   htab_t type_unit_groups {};
449
450   /* A table mapping .debug_types signatures to its signatured_type entry.
451      This is NULL if the .debug_types section hasn't been read in yet.  */
452   htab_t signatured_types {};
453
454   /* Type unit statistics, to see how well the scaling improvements
455      are doing.  */
456   struct tu_stats tu_stats {};
457
458   /* A chain of compilation units that are currently read in, so that
459      they can be freed later.  */
460   dwarf2_per_cu_data *read_in_chain = NULL;
461
462   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
463      This is NULL if the table hasn't been allocated yet.  */
464   htab_t dwo_files {};
465
466   /* True if we've checked for whether there is a DWP file.  */
467   bool dwp_checked = false;
468
469   /* The DWP file if there is one, or NULL.  */
470   struct dwp_file *dwp_file = NULL;
471
472   /* The shared '.dwz' file, if one exists.  This is used when the
473      original data was compressed using 'dwz -m'.  */
474   struct dwz_file *dwz_file = NULL;
475
476   /* A flag indicating whether this objfile has a section loaded at a
477      VMA of 0.  */
478   bool has_section_at_zero = false;
479
480   /* True if we are using the mapped index,
481      or we are faking it for OBJF_READNOW's sake.  */
482   bool using_index = false;
483
484   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
485   mapped_index *index_table = NULL;
486
487   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
488   std::unique_ptr<mapped_debug_names> debug_names_table;
489
490   /* When using index_table, this keeps track of all quick_file_names entries.
491      TUs typically share line table entries with a CU, so we maintain a
492      separate table of all line table entries to support the sharing.
493      Note that while there can be way more TUs than CUs, we've already
494      sorted all the TUs into "type unit groups", grouped by their
495      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
496      CU and its associated TU group if there is one.  */
497   htab_t quick_file_names_table {};
498
499   /* Set during partial symbol reading, to prevent queueing of full
500      symbols.  */
501   bool reading_partial_symbols = false;
502
503   /* Table mapping type DIEs to their struct type *.
504      This is NULL if not allocated yet.
505      The mapping is done via (CU/TU + DIE offset) -> type.  */
506   htab_t die_type_hash {};
507
508   /* The CUs we recently read.  */
509   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
510
511   /* Table containing line_header indexed by offset and offset_in_dwz.  */
512   htab_t line_header_hash {};
513
514   /* Table containing all filenames.  This is an optional because the
515      table is lazily constructed on first access.  */
516   gdb::optional<filename_seen_cache> filenames_cache;
517 };
518
519 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
520
521 struct dwarf2_per_objfile *
522 get_dwarf2_per_objfile (struct objfile *objfile)
523 {
524   return ((struct dwarf2_per_objfile *)
525           objfile_data (objfile, dwarf2_objfile_data_key));
526 }
527
528 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
529
530 void
531 set_dwarf2_per_objfile (struct objfile *objfile,
532                         struct dwarf2_per_objfile *dwarf2_per_objfile)
533 {
534   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
535   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
536 }
537
538 /* Default names of the debugging sections.  */
539
540 /* Note that if the debugging section has been compressed, it might
541    have a name like .zdebug_info.  */
542
543 static const struct dwarf2_debug_sections dwarf2_elf_names =
544 {
545   { ".debug_info", ".zdebug_info" },
546   { ".debug_abbrev", ".zdebug_abbrev" },
547   { ".debug_line", ".zdebug_line" },
548   { ".debug_loc", ".zdebug_loc" },
549   { ".debug_loclists", ".zdebug_loclists" },
550   { ".debug_macinfo", ".zdebug_macinfo" },
551   { ".debug_macro", ".zdebug_macro" },
552   { ".debug_str", ".zdebug_str" },
553   { ".debug_line_str", ".zdebug_line_str" },
554   { ".debug_ranges", ".zdebug_ranges" },
555   { ".debug_rnglists", ".zdebug_rnglists" },
556   { ".debug_types", ".zdebug_types" },
557   { ".debug_addr", ".zdebug_addr" },
558   { ".debug_frame", ".zdebug_frame" },
559   { ".eh_frame", NULL },
560   { ".gdb_index", ".zgdb_index" },
561   { ".debug_names", ".zdebug_names" },
562   { ".debug_aranges", ".zdebug_aranges" },
563   23
564 };
565
566 /* List of DWO/DWP sections.  */
567
568 static const struct dwop_section_names
569 {
570   struct dwarf2_section_names abbrev_dwo;
571   struct dwarf2_section_names info_dwo;
572   struct dwarf2_section_names line_dwo;
573   struct dwarf2_section_names loc_dwo;
574   struct dwarf2_section_names loclists_dwo;
575   struct dwarf2_section_names macinfo_dwo;
576   struct dwarf2_section_names macro_dwo;
577   struct dwarf2_section_names str_dwo;
578   struct dwarf2_section_names str_offsets_dwo;
579   struct dwarf2_section_names types_dwo;
580   struct dwarf2_section_names cu_index;
581   struct dwarf2_section_names tu_index;
582 }
583 dwop_section_names =
584 {
585   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
586   { ".debug_info.dwo", ".zdebug_info.dwo" },
587   { ".debug_line.dwo", ".zdebug_line.dwo" },
588   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
589   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
590   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
591   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
592   { ".debug_str.dwo", ".zdebug_str.dwo" },
593   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
594   { ".debug_types.dwo", ".zdebug_types.dwo" },
595   { ".debug_cu_index", ".zdebug_cu_index" },
596   { ".debug_tu_index", ".zdebug_tu_index" },
597 };
598
599 /* local data types */
600
601 /* The data in a compilation unit header, after target2host
602    translation, looks like this.  */
603 struct comp_unit_head
604 {
605   unsigned int length;
606   short version;
607   unsigned char addr_size;
608   unsigned char signed_addr_p;
609   sect_offset abbrev_sect_off;
610
611   /* Size of file offsets; either 4 or 8.  */
612   unsigned int offset_size;
613
614   /* Size of the length field; either 4 or 12.  */
615   unsigned int initial_length_size;
616
617   enum dwarf_unit_type unit_type;
618
619   /* Offset to the first byte of this compilation unit header in the
620      .debug_info section, for resolving relative reference dies.  */
621   sect_offset sect_off;
622
623   /* Offset to first die in this cu from the start of the cu.
624      This will be the first byte following the compilation unit header.  */
625   cu_offset first_die_cu_offset;
626
627   /* 64-bit signature of this type unit - it is valid only for
628      UNIT_TYPE DW_UT_type.  */
629   ULONGEST signature;
630
631   /* For types, offset in the type's DIE of the type defined by this TU.  */
632   cu_offset type_cu_offset_in_tu;
633 };
634
635 /* Type used for delaying computation of method physnames.
636    See comments for compute_delayed_physnames.  */
637 struct delayed_method_info
638 {
639   /* The type to which the method is attached, i.e., its parent class.  */
640   struct type *type;
641
642   /* The index of the method in the type's function fieldlists.  */
643   int fnfield_index;
644
645   /* The index of the method in the fieldlist.  */
646   int index;
647
648   /* The name of the DIE.  */
649   const char *name;
650
651   /*  The DIE associated with this method.  */
652   struct die_info *die;
653 };
654
655 /* Internal state when decoding a particular compilation unit.  */
656 struct dwarf2_cu
657 {
658   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
659   ~dwarf2_cu ();
660
661   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
662
663   /* The header of the compilation unit.  */
664   struct comp_unit_head header {};
665
666   /* Base address of this compilation unit.  */
667   CORE_ADDR base_address = 0;
668
669   /* Non-zero if base_address has been set.  */
670   int base_known = 0;
671
672   /* The language we are debugging.  */
673   enum language language = language_unknown;
674   const struct language_defn *language_defn = nullptr;
675
676   const char *producer = nullptr;
677
678   /* The generic symbol table building routines have separate lists for
679      file scope symbols and all all other scopes (local scopes).  So
680      we need to select the right one to pass to add_symbol_to_list().
681      We do it by keeping a pointer to the correct list in list_in_scope.
682
683      FIXME: The original dwarf code just treated the file scope as the
684      first local scope, and all other local scopes as nested local
685      scopes, and worked fine.  Check to see if we really need to
686      distinguish these in buildsym.c.  */
687   struct pending **list_in_scope = nullptr;
688
689   /* Hash table holding all the loaded partial DIEs
690      with partial_die->offset.SECT_OFF as hash.  */
691   htab_t partial_dies = nullptr;
692
693   /* Storage for things with the same lifetime as this read-in compilation
694      unit, including partial DIEs.  */
695   auto_obstack comp_unit_obstack;
696
697   /* When multiple dwarf2_cu structures are living in memory, this field
698      chains them all together, so that they can be released efficiently.
699      We will probably also want a generation counter so that most-recently-used
700      compilation units are cached...  */
701   struct dwarf2_per_cu_data *read_in_chain = nullptr;
702
703   /* Backlink to our per_cu entry.  */
704   struct dwarf2_per_cu_data *per_cu;
705
706   /* How many compilation units ago was this CU last referenced?  */
707   int last_used = 0;
708
709   /* A hash table of DIE cu_offset for following references with
710      die_info->offset.sect_off as hash.  */
711   htab_t die_hash = nullptr;
712
713   /* Full DIEs if read in.  */
714   struct die_info *dies = nullptr;
715
716   /* A set of pointers to dwarf2_per_cu_data objects for compilation
717      units referenced by this one.  Only set during full symbol processing;
718      partial symbol tables do not have dependencies.  */
719   htab_t dependencies = nullptr;
720
721   /* Header data from the line table, during full symbol processing.  */
722   struct line_header *line_header = nullptr;
723   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
724      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
725      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
726      to the line header as long as this DIE is being processed.  See
727      process_die_scope.  */
728   die_info *line_header_die_owner = nullptr;
729
730   /* A list of methods which need to have physnames computed
731      after all type information has been read.  */
732   std::vector<delayed_method_info> method_list;
733
734   /* To be copied to symtab->call_site_htab.  */
735   htab_t call_site_htab = nullptr;
736
737   /* Non-NULL if this CU came from a DWO file.
738      There is an invariant here that is important to remember:
739      Except for attributes copied from the top level DIE in the "main"
740      (or "stub") file in preparation for reading the DWO file
741      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
742      Either there isn't a DWO file (in which case this is NULL and the point
743      is moot), or there is and either we're not going to read it (in which
744      case this is NULL) or there is and we are reading it (in which case this
745      is non-NULL).  */
746   struct dwo_unit *dwo_unit = nullptr;
747
748   /* The DW_AT_addr_base attribute if present, zero otherwise
749      (zero is a valid value though).
750      Note this value comes from the Fission stub CU/TU's DIE.  */
751   ULONGEST addr_base = 0;
752
753   /* The DW_AT_ranges_base attribute if present, zero otherwise
754      (zero is a valid value though).
755      Note this value comes from the Fission stub CU/TU's DIE.
756      Also note that the value is zero in the non-DWO case so this value can
757      be used without needing to know whether DWO files are in use or not.
758      N.B. This does not apply to DW_AT_ranges appearing in
759      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
760      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
761      DW_AT_ranges_base *would* have to be applied, and we'd have to care
762      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
763   ULONGEST ranges_base = 0;
764
765   /* Mark used when releasing cached dies.  */
766   unsigned int mark : 1;
767
768   /* This CU references .debug_loc.  See the symtab->locations_valid field.
769      This test is imperfect as there may exist optimized debug code not using
770      any location list and still facing inlining issues if handled as
771      unoptimized code.  For a future better test see GCC PR other/32998.  */
772   unsigned int has_loclist : 1;
773
774   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
775      if all the producer_is_* fields are valid.  This information is cached
776      because profiling CU expansion showed excessive time spent in
777      producer_is_gxx_lt_4_6.  */
778   unsigned int checked_producer : 1;
779   unsigned int producer_is_gxx_lt_4_6 : 1;
780   unsigned int producer_is_gcc_lt_4_3 : 1;
781   unsigned int producer_is_icc_lt_14 : 1;
782
783   /* When set, the file that we're processing is known to have
784      debugging info for C++ namespaces.  GCC 3.3.x did not produce
785      this information, but later versions do.  */
786
787   unsigned int processing_has_namespace_info : 1;
788
789   struct partial_die_info *find_partial_die (sect_offset sect_off);
790 };
791
792 /* Persistent data held for a compilation unit, even when not
793    processing it.  We put a pointer to this structure in the
794    read_symtab_private field of the psymtab.  */
795
796 struct dwarf2_per_cu_data
797 {
798   /* The start offset and length of this compilation unit.
799      NOTE: Unlike comp_unit_head.length, this length includes
800      initial_length_size.
801      If the DIE refers to a DWO file, this is always of the original die,
802      not the DWO file.  */
803   sect_offset sect_off;
804   unsigned int length;
805
806   /* DWARF standard version this data has been read from (such as 4 or 5).  */
807   short dwarf_version;
808
809   /* Flag indicating this compilation unit will be read in before
810      any of the current compilation units are processed.  */
811   unsigned int queued : 1;
812
813   /* This flag will be set when reading partial DIEs if we need to load
814      absolutely all DIEs for this compilation unit, instead of just the ones
815      we think are interesting.  It gets set if we look for a DIE in the
816      hash table and don't find it.  */
817   unsigned int load_all_dies : 1;
818
819   /* Non-zero if this CU is from .debug_types.
820      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
821      this is non-zero.  */
822   unsigned int is_debug_types : 1;
823
824   /* Non-zero if this CU is from the .dwz file.  */
825   unsigned int is_dwz : 1;
826
827   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
828      This flag is only valid if is_debug_types is true.
829      We can't read a CU directly from a DWO file: There are required
830      attributes in the stub.  */
831   unsigned int reading_dwo_directly : 1;
832
833   /* Non-zero if the TU has been read.
834      This is used to assist the "Stay in DWO Optimization" for Fission:
835      When reading a DWO, it's faster to read TUs from the DWO instead of
836      fetching them from random other DWOs (due to comdat folding).
837      If the TU has already been read, the optimization is unnecessary
838      (and unwise - we don't want to change where gdb thinks the TU lives
839      "midflight").
840      This flag is only valid if is_debug_types is true.  */
841   unsigned int tu_read : 1;
842
843   /* The section this CU/TU lives in.
844      If the DIE refers to a DWO file, this is always the original die,
845      not the DWO file.  */
846   struct dwarf2_section_info *section;
847
848   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
849      of the CU cache it gets reset to NULL again.  This is left as NULL for
850      dummy CUs (a CU header, but nothing else).  */
851   struct dwarf2_cu *cu;
852
853   /* The corresponding dwarf2_per_objfile.  */
854   struct dwarf2_per_objfile *dwarf2_per_objfile;
855
856   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
857      is active.  Otherwise, the 'psymtab' field is active.  */
858   union
859   {
860     /* The partial symbol table associated with this compilation unit,
861        or NULL for unread partial units.  */
862     struct partial_symtab *psymtab;
863
864     /* Data needed by the "quick" functions.  */
865     struct dwarf2_per_cu_quick_data *quick;
866   } v;
867
868   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
869      while reading psymtabs, used to compute the psymtab dependencies,
870      and then cleared.  Then it is filled in again while reading full
871      symbols, and only deleted when the objfile is destroyed.
872
873      This is also used to work around a difference between the way gold
874      generates .gdb_index version <=7 and the way gdb does.  Arguably this
875      is a gold bug.  For symbols coming from TUs, gold records in the index
876      the CU that includes the TU instead of the TU itself.  This breaks
877      dw2_lookup_symbol: It assumes that if the index says symbol X lives
878      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
879      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
880      we need to look in TU Z to find X.  Fortunately, this is akin to
881      DW_TAG_imported_unit, so we just use the same mechanism: For
882      .gdb_index version <=7 this also records the TUs that the CU referred
883      to.  Concurrently with this change gdb was modified to emit version 8
884      indices so we only pay a price for gold generated indices.
885      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
886   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
887 };
888
889 /* Entry in the signatured_types hash table.  */
890
891 struct signatured_type
892 {
893   /* The "per_cu" object of this type.
894      This struct is used iff per_cu.is_debug_types.
895      N.B.: This is the first member so that it's easy to convert pointers
896      between them.  */
897   struct dwarf2_per_cu_data per_cu;
898
899   /* The type's signature.  */
900   ULONGEST signature;
901
902   /* Offset in the TU of the type's DIE, as read from the TU header.
903      If this TU is a DWO stub and the definition lives in a DWO file
904      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
905   cu_offset type_offset_in_tu;
906
907   /* Offset in the section of the type's DIE.
908      If the definition lives in a DWO file, this is the offset in the
909      .debug_types.dwo section.
910      The value is zero until the actual value is known.
911      Zero is otherwise not a valid section offset.  */
912   sect_offset type_offset_in_section;
913
914   /* Type units are grouped by their DW_AT_stmt_list entry so that they
915      can share them.  This points to the containing symtab.  */
916   struct type_unit_group *type_unit_group;
917
918   /* The type.
919      The first time we encounter this type we fully read it in and install it
920      in the symbol tables.  Subsequent times we only need the type.  */
921   struct type *type;
922
923   /* Containing DWO unit.
924      This field is valid iff per_cu.reading_dwo_directly.  */
925   struct dwo_unit *dwo_unit;
926 };
927
928 typedef struct signatured_type *sig_type_ptr;
929 DEF_VEC_P (sig_type_ptr);
930
931 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
932    This includes type_unit_group and quick_file_names.  */
933
934 struct stmt_list_hash
935 {
936   /* The DWO unit this table is from or NULL if there is none.  */
937   struct dwo_unit *dwo_unit;
938
939   /* Offset in .debug_line or .debug_line.dwo.  */
940   sect_offset line_sect_off;
941 };
942
943 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
944    an object of this type.  */
945
946 struct type_unit_group
947 {
948   /* dwarf2read.c's main "handle" on a TU symtab.
949      To simplify things we create an artificial CU that "includes" all the
950      type units using this stmt_list so that the rest of the code still has
951      a "per_cu" handle on the symtab.
952      This PER_CU is recognized by having no section.  */
953 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
954   struct dwarf2_per_cu_data per_cu;
955
956   /* The TUs that share this DW_AT_stmt_list entry.
957      This is added to while parsing type units to build partial symtabs,
958      and is deleted afterwards and not used again.  */
959   VEC (sig_type_ptr) *tus;
960
961   /* The compunit symtab.
962      Type units in a group needn't all be defined in the same source file,
963      so we create an essentially anonymous symtab as the compunit symtab.  */
964   struct compunit_symtab *compunit_symtab;
965
966   /* The data used to construct the hash key.  */
967   struct stmt_list_hash hash;
968
969   /* The number of symtabs from the line header.
970      The value here must match line_header.num_file_names.  */
971   unsigned int num_symtabs;
972
973   /* The symbol tables for this TU (obtained from the files listed in
974      DW_AT_stmt_list).
975      WARNING: The order of entries here must match the order of entries
976      in the line header.  After the first TU using this type_unit_group, the
977      line header for the subsequent TUs is recreated from this.  This is done
978      because we need to use the same symtabs for each TU using the same
979      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
980      there's no guarantee the line header doesn't have duplicate entries.  */
981   struct symtab **symtabs;
982 };
983
984 /* These sections are what may appear in a (real or virtual) DWO file.  */
985
986 struct dwo_sections
987 {
988   struct dwarf2_section_info abbrev;
989   struct dwarf2_section_info line;
990   struct dwarf2_section_info loc;
991   struct dwarf2_section_info loclists;
992   struct dwarf2_section_info macinfo;
993   struct dwarf2_section_info macro;
994   struct dwarf2_section_info str;
995   struct dwarf2_section_info str_offsets;
996   /* In the case of a virtual DWO file, these two are unused.  */
997   struct dwarf2_section_info info;
998   VEC (dwarf2_section_info_def) *types;
999 };
1000
1001 /* CUs/TUs in DWP/DWO files.  */
1002
1003 struct dwo_unit
1004 {
1005   /* Backlink to the containing struct dwo_file.  */
1006   struct dwo_file *dwo_file;
1007
1008   /* The "id" that distinguishes this CU/TU.
1009      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1010      Since signatures came first, we stick with it for consistency.  */
1011   ULONGEST signature;
1012
1013   /* The section this CU/TU lives in, in the DWO file.  */
1014   struct dwarf2_section_info *section;
1015
1016   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1017   sect_offset sect_off;
1018   unsigned int length;
1019
1020   /* For types, offset in the type's DIE of the type defined by this TU.  */
1021   cu_offset type_offset_in_tu;
1022 };
1023
1024 /* include/dwarf2.h defines the DWP section codes.
1025    It defines a max value but it doesn't define a min value, which we
1026    use for error checking, so provide one.  */
1027
1028 enum dwp_v2_section_ids
1029 {
1030   DW_SECT_MIN = 1
1031 };
1032
1033 /* Data for one DWO file.
1034
1035    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1036    appears in a DWP file).  DWP files don't really have DWO files per se -
1037    comdat folding of types "loses" the DWO file they came from, and from
1038    a high level view DWP files appear to contain a mass of random types.
1039    However, to maintain consistency with the non-DWP case we pretend DWP
1040    files contain virtual DWO files, and we assign each TU with one virtual
1041    DWO file (generally based on the line and abbrev section offsets -
1042    a heuristic that seems to work in practice).  */
1043
1044 struct dwo_file
1045 {
1046   /* The DW_AT_GNU_dwo_name attribute.
1047      For virtual DWO files the name is constructed from the section offsets
1048      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1049      from related CU+TUs.  */
1050   const char *dwo_name;
1051
1052   /* The DW_AT_comp_dir attribute.  */
1053   const char *comp_dir;
1054
1055   /* The bfd, when the file is open.  Otherwise this is NULL.
1056      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1057   bfd *dbfd;
1058
1059   /* The sections that make up this DWO file.
1060      Remember that for virtual DWO files in DWP V2, these are virtual
1061      sections (for lack of a better name).  */
1062   struct dwo_sections sections;
1063
1064   /* The CUs in the file.
1065      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1066      an extension to handle LLVM's Link Time Optimization output (where
1067      multiple source files may be compiled into a single object/dwo pair). */
1068   htab_t cus;
1069
1070   /* Table of TUs in the file.
1071      Each element is a struct dwo_unit.  */
1072   htab_t tus;
1073 };
1074
1075 /* These sections are what may appear in a DWP file.  */
1076
1077 struct dwp_sections
1078 {
1079   /* These are used by both DWP version 1 and 2.  */
1080   struct dwarf2_section_info str;
1081   struct dwarf2_section_info cu_index;
1082   struct dwarf2_section_info tu_index;
1083
1084   /* These are only used by DWP version 2 files.
1085      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1086      sections are referenced by section number, and are not recorded here.
1087      In DWP version 2 there is at most one copy of all these sections, each
1088      section being (effectively) comprised of the concatenation of all of the
1089      individual sections that exist in the version 1 format.
1090      To keep the code simple we treat each of these concatenated pieces as a
1091      section itself (a virtual section?).  */
1092   struct dwarf2_section_info abbrev;
1093   struct dwarf2_section_info info;
1094   struct dwarf2_section_info line;
1095   struct dwarf2_section_info loc;
1096   struct dwarf2_section_info macinfo;
1097   struct dwarf2_section_info macro;
1098   struct dwarf2_section_info str_offsets;
1099   struct dwarf2_section_info types;
1100 };
1101
1102 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1103    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1104
1105 struct virtual_v1_dwo_sections
1106 {
1107   struct dwarf2_section_info abbrev;
1108   struct dwarf2_section_info line;
1109   struct dwarf2_section_info loc;
1110   struct dwarf2_section_info macinfo;
1111   struct dwarf2_section_info macro;
1112   struct dwarf2_section_info str_offsets;
1113   /* Each DWP hash table entry records one CU or one TU.
1114      That is recorded here, and copied to dwo_unit.section.  */
1115   struct dwarf2_section_info info_or_types;
1116 };
1117
1118 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1119    In version 2, the sections of the DWO files are concatenated together
1120    and stored in one section of that name.  Thus each ELF section contains
1121    several "virtual" sections.  */
1122
1123 struct virtual_v2_dwo_sections
1124 {
1125   bfd_size_type abbrev_offset;
1126   bfd_size_type abbrev_size;
1127
1128   bfd_size_type line_offset;
1129   bfd_size_type line_size;
1130
1131   bfd_size_type loc_offset;
1132   bfd_size_type loc_size;
1133
1134   bfd_size_type macinfo_offset;
1135   bfd_size_type macinfo_size;
1136
1137   bfd_size_type macro_offset;
1138   bfd_size_type macro_size;
1139
1140   bfd_size_type str_offsets_offset;
1141   bfd_size_type str_offsets_size;
1142
1143   /* Each DWP hash table entry records one CU or one TU.
1144      That is recorded here, and copied to dwo_unit.section.  */
1145   bfd_size_type info_or_types_offset;
1146   bfd_size_type info_or_types_size;
1147 };
1148
1149 /* Contents of DWP hash tables.  */
1150
1151 struct dwp_hash_table
1152 {
1153   uint32_t version, nr_columns;
1154   uint32_t nr_units, nr_slots;
1155   const gdb_byte *hash_table, *unit_table;
1156   union
1157   {
1158     struct
1159     {
1160       const gdb_byte *indices;
1161     } v1;
1162     struct
1163     {
1164       /* This is indexed by column number and gives the id of the section
1165          in that column.  */
1166 #define MAX_NR_V2_DWO_SECTIONS \
1167   (1 /* .debug_info or .debug_types */ \
1168    + 1 /* .debug_abbrev */ \
1169    + 1 /* .debug_line */ \
1170    + 1 /* .debug_loc */ \
1171    + 1 /* .debug_str_offsets */ \
1172    + 1 /* .debug_macro or .debug_macinfo */)
1173       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1174       const gdb_byte *offsets;
1175       const gdb_byte *sizes;
1176     } v2;
1177   } section_pool;
1178 };
1179
1180 /* Data for one DWP file.  */
1181
1182 struct dwp_file
1183 {
1184   /* Name of the file.  */
1185   const char *name;
1186
1187   /* File format version.  */
1188   int version;
1189
1190   /* The bfd.  */
1191   bfd *dbfd;
1192
1193   /* Section info for this file.  */
1194   struct dwp_sections sections;
1195
1196   /* Table of CUs in the file.  */
1197   const struct dwp_hash_table *cus;
1198
1199   /* Table of TUs in the file.  */
1200   const struct dwp_hash_table *tus;
1201
1202   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1203   htab_t loaded_cus;
1204   htab_t loaded_tus;
1205
1206   /* Table to map ELF section numbers to their sections.
1207      This is only needed for the DWP V1 file format.  */
1208   unsigned int num_sections;
1209   asection **elf_sections;
1210 };
1211
1212 /* This represents a '.dwz' file.  */
1213
1214 struct dwz_file
1215 {
1216   /* A dwz file can only contain a few sections.  */
1217   struct dwarf2_section_info abbrev;
1218   struct dwarf2_section_info info;
1219   struct dwarf2_section_info str;
1220   struct dwarf2_section_info line;
1221   struct dwarf2_section_info macro;
1222   struct dwarf2_section_info gdb_index;
1223   struct dwarf2_section_info debug_names;
1224
1225   /* The dwz's BFD.  */
1226   bfd *dwz_bfd;
1227 };
1228
1229 /* Struct used to pass misc. parameters to read_die_and_children, et
1230    al.  which are used for both .debug_info and .debug_types dies.
1231    All parameters here are unchanging for the life of the call.  This
1232    struct exists to abstract away the constant parameters of die reading.  */
1233
1234 struct die_reader_specs
1235 {
1236   /* The bfd of die_section.  */
1237   bfd* abfd;
1238
1239   /* The CU of the DIE we are parsing.  */
1240   struct dwarf2_cu *cu;
1241
1242   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1243   struct dwo_file *dwo_file;
1244
1245   /* The section the die comes from.
1246      This is either .debug_info or .debug_types, or the .dwo variants.  */
1247   struct dwarf2_section_info *die_section;
1248
1249   /* die_section->buffer.  */
1250   const gdb_byte *buffer;
1251
1252   /* The end of the buffer.  */
1253   const gdb_byte *buffer_end;
1254
1255   /* The value of the DW_AT_comp_dir attribute.  */
1256   const char *comp_dir;
1257
1258   /* The abbreviation table to use when reading the DIEs.  */
1259   struct abbrev_table *abbrev_table;
1260 };
1261
1262 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1263 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1264                                       const gdb_byte *info_ptr,
1265                                       struct die_info *comp_unit_die,
1266                                       int has_children,
1267                                       void *data);
1268
1269 /* A 1-based directory index.  This is a strong typedef to prevent
1270    accidentally using a directory index as a 0-based index into an
1271    array/vector.  */
1272 enum class dir_index : unsigned int {};
1273
1274 /* Likewise, a 1-based file name index.  */
1275 enum class file_name_index : unsigned int {};
1276
1277 struct file_entry
1278 {
1279   file_entry () = default;
1280
1281   file_entry (const char *name_, dir_index d_index_,
1282               unsigned int mod_time_, unsigned int length_)
1283     : name (name_),
1284       d_index (d_index_),
1285       mod_time (mod_time_),
1286       length (length_)
1287   {}
1288
1289   /* Return the include directory at D_INDEX stored in LH.  Returns
1290      NULL if D_INDEX is out of bounds.  */
1291   const char *include_dir (const line_header *lh) const;
1292
1293   /* The file name.  Note this is an observing pointer.  The memory is
1294      owned by debug_line_buffer.  */
1295   const char *name {};
1296
1297   /* The directory index (1-based).  */
1298   dir_index d_index {};
1299
1300   unsigned int mod_time {};
1301
1302   unsigned int length {};
1303
1304   /* True if referenced by the Line Number Program.  */
1305   bool included_p {};
1306
1307   /* The associated symbol table, if any.  */
1308   struct symtab *symtab {};
1309 };
1310
1311 /* The line number information for a compilation unit (found in the
1312    .debug_line section) begins with a "statement program header",
1313    which contains the following information.  */
1314 struct line_header
1315 {
1316   line_header ()
1317     : offset_in_dwz {}
1318   {}
1319
1320   /* Add an entry to the include directory table.  */
1321   void add_include_dir (const char *include_dir);
1322
1323   /* Add an entry to the file name table.  */
1324   void add_file_name (const char *name, dir_index d_index,
1325                       unsigned int mod_time, unsigned int length);
1326
1327   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1328      is out of bounds.  */
1329   const char *include_dir_at (dir_index index) const
1330   {
1331     /* Convert directory index number (1-based) to vector index
1332        (0-based).  */
1333     size_t vec_index = to_underlying (index) - 1;
1334
1335     if (vec_index >= include_dirs.size ())
1336       return NULL;
1337     return include_dirs[vec_index];
1338   }
1339
1340   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1341      is out of bounds.  */
1342   file_entry *file_name_at (file_name_index index)
1343   {
1344     /* Convert file name index number (1-based) to vector index
1345        (0-based).  */
1346     size_t vec_index = to_underlying (index) - 1;
1347
1348     if (vec_index >= file_names.size ())
1349       return NULL;
1350     return &file_names[vec_index];
1351   }
1352
1353   /* Const version of the above.  */
1354   const file_entry *file_name_at (unsigned int index) const
1355   {
1356     if (index >= file_names.size ())
1357       return NULL;
1358     return &file_names[index];
1359   }
1360
1361   /* Offset of line number information in .debug_line section.  */
1362   sect_offset sect_off {};
1363
1364   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1365   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1366
1367   unsigned int total_length {};
1368   unsigned short version {};
1369   unsigned int header_length {};
1370   unsigned char minimum_instruction_length {};
1371   unsigned char maximum_ops_per_instruction {};
1372   unsigned char default_is_stmt {};
1373   int line_base {};
1374   unsigned char line_range {};
1375   unsigned char opcode_base {};
1376
1377   /* standard_opcode_lengths[i] is the number of operands for the
1378      standard opcode whose value is i.  This means that
1379      standard_opcode_lengths[0] is unused, and the last meaningful
1380      element is standard_opcode_lengths[opcode_base - 1].  */
1381   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1382
1383   /* The include_directories table.  Note these are observing
1384      pointers.  The memory is owned by debug_line_buffer.  */
1385   std::vector<const char *> include_dirs;
1386
1387   /* The file_names table.  */
1388   std::vector<file_entry> file_names;
1389
1390   /* The start and end of the statement program following this
1391      header.  These point into dwarf2_per_objfile->line_buffer.  */
1392   const gdb_byte *statement_program_start {}, *statement_program_end {};
1393 };
1394
1395 typedef std::unique_ptr<line_header> line_header_up;
1396
1397 const char *
1398 file_entry::include_dir (const line_header *lh) const
1399 {
1400   return lh->include_dir_at (d_index);
1401 }
1402
1403 /* When we construct a partial symbol table entry we only
1404    need this much information.  */
1405 struct partial_die_info : public allocate_on_obstack
1406   {
1407     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1408
1409     /* Disable assign but still keep copy ctor, which is needed
1410        load_partial_dies.   */
1411     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1412
1413     /* Adjust the partial die before generating a symbol for it.  This
1414        function may set the is_external flag or change the DIE's
1415        name.  */
1416     void fixup (struct dwarf2_cu *cu);
1417
1418     /* Read a minimal amount of information into the minimal die
1419        structure.  */
1420     const gdb_byte *read (const struct die_reader_specs *reader,
1421                           const struct abbrev_info &abbrev,
1422                           const gdb_byte *info_ptr);
1423
1424     /* Offset of this DIE.  */
1425     const sect_offset sect_off;
1426
1427     /* DWARF-2 tag for this DIE.  */
1428     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1429
1430     /* Assorted flags describing the data found in this DIE.  */
1431     const unsigned int has_children : 1;
1432
1433     unsigned int is_external : 1;
1434     unsigned int is_declaration : 1;
1435     unsigned int has_type : 1;
1436     unsigned int has_specification : 1;
1437     unsigned int has_pc_info : 1;
1438     unsigned int may_be_inlined : 1;
1439
1440     /* This DIE has been marked DW_AT_main_subprogram.  */
1441     unsigned int main_subprogram : 1;
1442
1443     /* Flag set if the SCOPE field of this structure has been
1444        computed.  */
1445     unsigned int scope_set : 1;
1446
1447     /* Flag set if the DIE has a byte_size attribute.  */
1448     unsigned int has_byte_size : 1;
1449
1450     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1451     unsigned int has_const_value : 1;
1452
1453     /* Flag set if any of the DIE's children are template arguments.  */
1454     unsigned int has_template_arguments : 1;
1455
1456     /* Flag set if fixup has been called on this die.  */
1457     unsigned int fixup_called : 1;
1458
1459     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1460     unsigned int is_dwz : 1;
1461
1462     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1463     unsigned int spec_is_dwz : 1;
1464
1465     /* The name of this DIE.  Normally the value of DW_AT_name, but
1466        sometimes a default name for unnamed DIEs.  */
1467     const char *name = nullptr;
1468
1469     /* The linkage name, if present.  */
1470     const char *linkage_name = nullptr;
1471
1472     /* The scope to prepend to our children.  This is generally
1473        allocated on the comp_unit_obstack, so will disappear
1474        when this compilation unit leaves the cache.  */
1475     const char *scope = nullptr;
1476
1477     /* Some data associated with the partial DIE.  The tag determines
1478        which field is live.  */
1479     union
1480     {
1481       /* The location description associated with this DIE, if any.  */
1482       struct dwarf_block *locdesc;
1483       /* The offset of an import, for DW_TAG_imported_unit.  */
1484       sect_offset sect_off;
1485     } d {};
1486
1487     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1488     CORE_ADDR lowpc = 0;
1489     CORE_ADDR highpc = 0;
1490
1491     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1492        DW_AT_sibling, if any.  */
1493     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1494        could return DW_AT_sibling values to its caller load_partial_dies.  */
1495     const gdb_byte *sibling = nullptr;
1496
1497     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1498        DW_AT_specification (or DW_AT_abstract_origin or
1499        DW_AT_extension).  */
1500     sect_offset spec_offset {};
1501
1502     /* Pointers to this DIE's parent, first child, and next sibling,
1503        if any.  */
1504     struct partial_die_info *die_parent = nullptr;
1505     struct partial_die_info *die_child = nullptr;
1506     struct partial_die_info *die_sibling = nullptr;
1507
1508     friend struct partial_die_info *
1509     dwarf2_cu::find_partial_die (sect_offset sect_off);
1510
1511   private:
1512     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1513     partial_die_info (sect_offset sect_off)
1514       : partial_die_info (sect_off, DW_TAG_padding, 0)
1515     {
1516     }
1517
1518     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1519                       int has_children_)
1520       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1521     {
1522       is_external = 0;
1523       is_declaration = 0;
1524       has_type = 0;
1525       has_specification = 0;
1526       has_pc_info = 0;
1527       may_be_inlined = 0;
1528       main_subprogram = 0;
1529       scope_set = 0;
1530       has_byte_size = 0;
1531       has_const_value = 0;
1532       has_template_arguments = 0;
1533       fixup_called = 0;
1534       is_dwz = 0;
1535       spec_is_dwz = 0;
1536     }
1537   };
1538
1539 /* This data structure holds the information of an abbrev.  */
1540 struct abbrev_info
1541   {
1542     unsigned int number;        /* number identifying abbrev */
1543     enum dwarf_tag tag;         /* dwarf tag */
1544     unsigned short has_children;                /* boolean */
1545     unsigned short num_attrs;   /* number of attributes */
1546     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1547     struct abbrev_info *next;   /* next in chain */
1548   };
1549
1550 struct attr_abbrev
1551   {
1552     ENUM_BITFIELD(dwarf_attribute) name : 16;
1553     ENUM_BITFIELD(dwarf_form) form : 16;
1554
1555     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1556     LONGEST implicit_const;
1557   };
1558
1559 /* Size of abbrev_table.abbrev_hash_table.  */
1560 #define ABBREV_HASH_SIZE 121
1561
1562 /* Top level data structure to contain an abbreviation table.  */
1563
1564 struct abbrev_table
1565 {
1566   explicit abbrev_table (sect_offset off)
1567     : sect_off (off)
1568   {
1569     m_abbrevs =
1570       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1571     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1572   }
1573
1574   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1575
1576   /* Allocate space for a struct abbrev_info object in
1577      ABBREV_TABLE.  */
1578   struct abbrev_info *alloc_abbrev ();
1579
1580   /* Add an abbreviation to the table.  */
1581   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1582
1583   /* Look up an abbrev in the table.
1584      Returns NULL if the abbrev is not found.  */
1585
1586   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1587
1588
1589   /* Where the abbrev table came from.
1590      This is used as a sanity check when the table is used.  */
1591   const sect_offset sect_off;
1592
1593   /* Storage for the abbrev table.  */
1594   auto_obstack abbrev_obstack;
1595
1596 private:
1597
1598   /* Hash table of abbrevs.
1599      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1600      It could be statically allocated, but the previous code didn't so we
1601      don't either.  */
1602   struct abbrev_info **m_abbrevs;
1603 };
1604
1605 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1606
1607 /* Attributes have a name and a value.  */
1608 struct attribute
1609   {
1610     ENUM_BITFIELD(dwarf_attribute) name : 16;
1611     ENUM_BITFIELD(dwarf_form) form : 15;
1612
1613     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1614        field should be in u.str (existing only for DW_STRING) but it is kept
1615        here for better struct attribute alignment.  */
1616     unsigned int string_is_canonical : 1;
1617
1618     union
1619       {
1620         const char *str;
1621         struct dwarf_block *blk;
1622         ULONGEST unsnd;
1623         LONGEST snd;
1624         CORE_ADDR addr;
1625         ULONGEST signature;
1626       }
1627     u;
1628   };
1629
1630 /* This data structure holds a complete die structure.  */
1631 struct die_info
1632   {
1633     /* DWARF-2 tag for this DIE.  */
1634     ENUM_BITFIELD(dwarf_tag) tag : 16;
1635
1636     /* Number of attributes */
1637     unsigned char num_attrs;
1638
1639     /* True if we're presently building the full type name for the
1640        type derived from this DIE.  */
1641     unsigned char building_fullname : 1;
1642
1643     /* True if this die is in process.  PR 16581.  */
1644     unsigned char in_process : 1;
1645
1646     /* Abbrev number */
1647     unsigned int abbrev;
1648
1649     /* Offset in .debug_info or .debug_types section.  */
1650     sect_offset sect_off;
1651
1652     /* The dies in a compilation unit form an n-ary tree.  PARENT
1653        points to this die's parent; CHILD points to the first child of
1654        this node; and all the children of a given node are chained
1655        together via their SIBLING fields.  */
1656     struct die_info *child;     /* Its first child, if any.  */
1657     struct die_info *sibling;   /* Its next sibling, if any.  */
1658     struct die_info *parent;    /* Its parent, if any.  */
1659
1660     /* An array of attributes, with NUM_ATTRS elements.  There may be
1661        zero, but it's not common and zero-sized arrays are not
1662        sufficiently portable C.  */
1663     struct attribute attrs[1];
1664   };
1665
1666 /* Get at parts of an attribute structure.  */
1667
1668 #define DW_STRING(attr)    ((attr)->u.str)
1669 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1670 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1671 #define DW_BLOCK(attr)     ((attr)->u.blk)
1672 #define DW_SND(attr)       ((attr)->u.snd)
1673 #define DW_ADDR(attr)      ((attr)->u.addr)
1674 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1675
1676 /* Blocks are a bunch of untyped bytes.  */
1677 struct dwarf_block
1678   {
1679     size_t size;
1680
1681     /* Valid only if SIZE is not zero.  */
1682     const gdb_byte *data;
1683   };
1684
1685 #ifndef ATTR_ALLOC_CHUNK
1686 #define ATTR_ALLOC_CHUNK 4
1687 #endif
1688
1689 /* Allocate fields for structs, unions and enums in this size.  */
1690 #ifndef DW_FIELD_ALLOC_CHUNK
1691 #define DW_FIELD_ALLOC_CHUNK 4
1692 #endif
1693
1694 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1695    but this would require a corresponding change in unpack_field_as_long
1696    and friends.  */
1697 static int bits_per_byte = 8;
1698
1699 struct nextfield
1700 {
1701   struct nextfield *next;
1702   int accessibility;
1703   int virtuality;
1704   struct field field;
1705 };
1706
1707 struct nextfnfield
1708 {
1709   struct nextfnfield *next;
1710   struct fn_field fnfield;
1711 };
1712
1713 struct fnfieldlist
1714 {
1715   const char *name;
1716   int length;
1717   struct nextfnfield *head;
1718 };
1719
1720 struct decl_field_list
1721 {
1722   struct decl_field field;
1723   struct decl_field_list *next;
1724 };
1725
1726 /* The routines that read and process dies for a C struct or C++ class
1727    pass lists of data member fields and lists of member function fields
1728    in an instance of a field_info structure, as defined below.  */
1729 struct field_info
1730   {
1731     /* List of data member and baseclasses fields.  */
1732     struct nextfield *fields, *baseclasses;
1733
1734     /* Number of fields (including baseclasses).  */
1735     int nfields;
1736
1737     /* Number of baseclasses.  */
1738     int nbaseclasses;
1739
1740     /* Set if the accesibility of one of the fields is not public.  */
1741     int non_public_fields;
1742
1743     /* Member function fieldlist array, contains name of possibly overloaded
1744        member function, number of overloaded member functions and a pointer
1745        to the head of the member function field chain.  */
1746     struct fnfieldlist *fnfieldlists;
1747
1748     /* Number of entries in the fnfieldlists array.  */
1749     int nfnfields;
1750
1751     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1752        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1753     struct decl_field_list *typedef_field_list;
1754     unsigned typedef_field_list_count;
1755
1756     /* Nested types defined by this class and the number of elements in this
1757        list.  */
1758     struct decl_field_list *nested_types_list;
1759     unsigned nested_types_list_count;
1760   };
1761
1762 /* One item on the queue of compilation units to read in full symbols
1763    for.  */
1764 struct dwarf2_queue_item
1765 {
1766   struct dwarf2_per_cu_data *per_cu;
1767   enum language pretend_language;
1768   struct dwarf2_queue_item *next;
1769 };
1770
1771 /* The current queue.  */
1772 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1773
1774 /* Loaded secondary compilation units are kept in memory until they
1775    have not been referenced for the processing of this many
1776    compilation units.  Set this to zero to disable caching.  Cache
1777    sizes of up to at least twenty will improve startup time for
1778    typical inter-CU-reference binaries, at an obvious memory cost.  */
1779 static int dwarf_max_cache_age = 5;
1780 static void
1781 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1782                           struct cmd_list_element *c, const char *value)
1783 {
1784   fprintf_filtered (file, _("The upper bound on the age of cached "
1785                             "DWARF compilation units is %s.\n"),
1786                     value);
1787 }
1788 \f
1789 /* local function prototypes */
1790
1791 static const char *get_section_name (const struct dwarf2_section_info *);
1792
1793 static const char *get_section_file_name (const struct dwarf2_section_info *);
1794
1795 static void dwarf2_find_base_address (struct die_info *die,
1796                                       struct dwarf2_cu *cu);
1797
1798 static struct partial_symtab *create_partial_symtab
1799   (struct dwarf2_per_cu_data *per_cu, const char *name);
1800
1801 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1802                                         const gdb_byte *info_ptr,
1803                                         struct die_info *type_unit_die,
1804                                         int has_children, void *data);
1805
1806 static void dwarf2_build_psymtabs_hard
1807   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1808
1809 static void scan_partial_symbols (struct partial_die_info *,
1810                                   CORE_ADDR *, CORE_ADDR *,
1811                                   int, struct dwarf2_cu *);
1812
1813 static void add_partial_symbol (struct partial_die_info *,
1814                                 struct dwarf2_cu *);
1815
1816 static void add_partial_namespace (struct partial_die_info *pdi,
1817                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1818                                    int set_addrmap, struct dwarf2_cu *cu);
1819
1820 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1821                                 CORE_ADDR *highpc, int set_addrmap,
1822                                 struct dwarf2_cu *cu);
1823
1824 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1825                                      struct dwarf2_cu *cu);
1826
1827 static void add_partial_subprogram (struct partial_die_info *pdi,
1828                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1829                                     int need_pc, struct dwarf2_cu *cu);
1830
1831 static void dwarf2_read_symtab (struct partial_symtab *,
1832                                 struct objfile *);
1833
1834 static void psymtab_to_symtab_1 (struct partial_symtab *);
1835
1836 static abbrev_table_up abbrev_table_read_table
1837   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1838    sect_offset);
1839
1840 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1841
1842 static struct partial_die_info *load_partial_dies
1843   (const struct die_reader_specs *, const gdb_byte *, int);
1844
1845 static struct partial_die_info *find_partial_die (sect_offset, int,
1846                                                   struct dwarf2_cu *);
1847
1848 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1849                                        struct attribute *, struct attr_abbrev *,
1850                                        const gdb_byte *);
1851
1852 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1853
1854 static int read_1_signed_byte (bfd *, const gdb_byte *);
1855
1856 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1857
1858 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1859
1860 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1861
1862 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1863                                unsigned int *);
1864
1865 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1866
1867 static LONGEST read_checked_initial_length_and_offset
1868   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1869    unsigned int *, unsigned int *);
1870
1871 static LONGEST read_offset (bfd *, const gdb_byte *,
1872                             const struct comp_unit_head *,
1873                             unsigned int *);
1874
1875 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1876
1877 static sect_offset read_abbrev_offset
1878   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1879    struct dwarf2_section_info *, sect_offset);
1880
1881 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1882
1883 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1884
1885 static const char *read_indirect_string
1886   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1887    const struct comp_unit_head *, unsigned int *);
1888
1889 static const char *read_indirect_line_string
1890   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1891    const struct comp_unit_head *, unsigned int *);
1892
1893 static const char *read_indirect_string_at_offset
1894   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1895    LONGEST str_offset);
1896
1897 static const char *read_indirect_string_from_dwz
1898   (struct objfile *objfile, struct dwz_file *, LONGEST);
1899
1900 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1901
1902 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1903                                               const gdb_byte *,
1904                                               unsigned int *);
1905
1906 static const char *read_str_index (const struct die_reader_specs *reader,
1907                                    ULONGEST str_index);
1908
1909 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1910
1911 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1912                                       struct dwarf2_cu *);
1913
1914 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1915                                                 unsigned int);
1916
1917 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1918                                        struct dwarf2_cu *cu);
1919
1920 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1921                                struct dwarf2_cu *cu);
1922
1923 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1924
1925 static struct die_info *die_specification (struct die_info *die,
1926                                            struct dwarf2_cu **);
1927
1928 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1929                                                 struct dwarf2_cu *cu);
1930
1931 static void dwarf_decode_lines (struct line_header *, const char *,
1932                                 struct dwarf2_cu *, struct partial_symtab *,
1933                                 CORE_ADDR, int decode_mapping);
1934
1935 static void dwarf2_start_subfile (const char *, const char *);
1936
1937 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1938                                                     const char *, const char *,
1939                                                     CORE_ADDR);
1940
1941 static struct symbol *new_symbol (struct die_info *, struct type *,
1942                                   struct dwarf2_cu *, struct symbol * = NULL);
1943
1944 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1945                                 struct dwarf2_cu *);
1946
1947 static void dwarf2_const_value_attr (const struct attribute *attr,
1948                                      struct type *type,
1949                                      const char *name,
1950                                      struct obstack *obstack,
1951                                      struct dwarf2_cu *cu, LONGEST *value,
1952                                      const gdb_byte **bytes,
1953                                      struct dwarf2_locexpr_baton **baton);
1954
1955 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1956
1957 static int need_gnat_info (struct dwarf2_cu *);
1958
1959 static struct type *die_descriptive_type (struct die_info *,
1960                                           struct dwarf2_cu *);
1961
1962 static void set_descriptive_type (struct type *, struct die_info *,
1963                                   struct dwarf2_cu *);
1964
1965 static struct type *die_containing_type (struct die_info *,
1966                                          struct dwarf2_cu *);
1967
1968 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1969                                      struct dwarf2_cu *);
1970
1971 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1972
1973 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1974
1975 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1976
1977 static char *typename_concat (struct obstack *obs, const char *prefix,
1978                               const char *suffix, int physname,
1979                               struct dwarf2_cu *cu);
1980
1981 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1982
1983 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1984
1985 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1986
1987 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1988
1989 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1990
1991 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1992
1993 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1994                                struct dwarf2_cu *, struct partial_symtab *);
1995
1996 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1997    values.  Keep the items ordered with increasing constraints compliance.  */
1998 enum pc_bounds_kind
1999 {
2000   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
2001   PC_BOUNDS_NOT_PRESENT,
2002
2003   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
2004      were present but they do not form a valid range of PC addresses.  */
2005   PC_BOUNDS_INVALID,
2006
2007   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
2008   PC_BOUNDS_RANGES,
2009
2010   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
2011   PC_BOUNDS_HIGH_LOW,
2012 };
2013
2014 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
2015                                                  CORE_ADDR *, CORE_ADDR *,
2016                                                  struct dwarf2_cu *,
2017                                                  struct partial_symtab *);
2018
2019 static void get_scope_pc_bounds (struct die_info *,
2020                                  CORE_ADDR *, CORE_ADDR *,
2021                                  struct dwarf2_cu *);
2022
2023 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
2024                                         CORE_ADDR, struct dwarf2_cu *);
2025
2026 static void dwarf2_add_field (struct field_info *, struct die_info *,
2027                               struct dwarf2_cu *);
2028
2029 static void dwarf2_attach_fields_to_type (struct field_info *,
2030                                           struct type *, struct dwarf2_cu *);
2031
2032 static void dwarf2_add_member_fn (struct field_info *,
2033                                   struct die_info *, struct type *,
2034                                   struct dwarf2_cu *);
2035
2036 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
2037                                              struct type *,
2038                                              struct dwarf2_cu *);
2039
2040 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
2041
2042 static void read_common_block (struct die_info *, struct dwarf2_cu *);
2043
2044 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2045
2046 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2047
2048 static struct using_direct **using_directives (enum language);
2049
2050 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2051
2052 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2053
2054 static struct type *read_module_type (struct die_info *die,
2055                                       struct dwarf2_cu *cu);
2056
2057 static const char *namespace_name (struct die_info *die,
2058                                    int *is_anonymous, struct dwarf2_cu *);
2059
2060 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2061
2062 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2063
2064 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2065                                                        struct dwarf2_cu *);
2066
2067 static struct die_info *read_die_and_siblings_1
2068   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2069    struct die_info *);
2070
2071 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2072                                                const gdb_byte *info_ptr,
2073                                                const gdb_byte **new_info_ptr,
2074                                                struct die_info *parent);
2075
2076 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2077                                         struct die_info **, const gdb_byte *,
2078                                         int *, int);
2079
2080 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2081                                       struct die_info **, const gdb_byte *,
2082                                       int *);
2083
2084 static void process_die (struct die_info *, struct dwarf2_cu *);
2085
2086 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2087                                              struct obstack *);
2088
2089 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2090
2091 static const char *dwarf2_full_name (const char *name,
2092                                      struct die_info *die,
2093                                      struct dwarf2_cu *cu);
2094
2095 static const char *dwarf2_physname (const char *name, struct die_info *die,
2096                                     struct dwarf2_cu *cu);
2097
2098 static struct die_info *dwarf2_extension (struct die_info *die,
2099                                           struct dwarf2_cu **);
2100
2101 static const char *dwarf_tag_name (unsigned int);
2102
2103 static const char *dwarf_attr_name (unsigned int);
2104
2105 static const char *dwarf_form_name (unsigned int);
2106
2107 static const char *dwarf_bool_name (unsigned int);
2108
2109 static const char *dwarf_type_encoding_name (unsigned int);
2110
2111 static struct die_info *sibling_die (struct die_info *);
2112
2113 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2114
2115 static void dump_die_for_error (struct die_info *);
2116
2117 static void dump_die_1 (struct ui_file *, int level, int max_level,
2118                         struct die_info *);
2119
2120 /*static*/ void dump_die (struct die_info *, int max_level);
2121
2122 static void store_in_ref_table (struct die_info *,
2123                                 struct dwarf2_cu *);
2124
2125 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2126
2127 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2128
2129 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2130                                                const struct attribute *,
2131                                                struct dwarf2_cu **);
2132
2133 static struct die_info *follow_die_ref (struct die_info *,
2134                                         const struct attribute *,
2135                                         struct dwarf2_cu **);
2136
2137 static struct die_info *follow_die_sig (struct die_info *,
2138                                         const struct attribute *,
2139                                         struct dwarf2_cu **);
2140
2141 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2142                                          struct dwarf2_cu *);
2143
2144 static struct type *get_DW_AT_signature_type (struct die_info *,
2145                                               const struct attribute *,
2146                                               struct dwarf2_cu *);
2147
2148 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2149
2150 static void read_signatured_type (struct signatured_type *);
2151
2152 static int attr_to_dynamic_prop (const struct attribute *attr,
2153                                  struct die_info *die, struct dwarf2_cu *cu,
2154                                  struct dynamic_prop *prop);
2155
2156 /* memory allocation interface */
2157
2158 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2159
2160 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2161
2162 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2163
2164 static int attr_form_is_block (const struct attribute *);
2165
2166 static int attr_form_is_section_offset (const struct attribute *);
2167
2168 static int attr_form_is_constant (const struct attribute *);
2169
2170 static int attr_form_is_ref (const struct attribute *);
2171
2172 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2173                                    struct dwarf2_loclist_baton *baton,
2174                                    const struct attribute *attr);
2175
2176 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2177                                          struct symbol *sym,
2178                                          struct dwarf2_cu *cu,
2179                                          int is_block);
2180
2181 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2182                                      const gdb_byte *info_ptr,
2183                                      struct abbrev_info *abbrev);
2184
2185 static hashval_t partial_die_hash (const void *item);
2186
2187 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2188
2189 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2190   (sect_offset sect_off, unsigned int offset_in_dwz,
2191    struct dwarf2_per_objfile *dwarf2_per_objfile);
2192
2193 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2194                                    struct die_info *comp_unit_die,
2195                                    enum language pretend_language);
2196
2197 static void free_cached_comp_units (void *);
2198
2199 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2200
2201 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2202
2203 static struct type *set_die_type (struct die_info *, struct type *,
2204                                   struct dwarf2_cu *);
2205
2206 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2207
2208 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2209
2210 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2211                                  enum language);
2212
2213 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2214                                     enum language);
2215
2216 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2217                                     enum language);
2218
2219 static void dwarf2_add_dependence (struct dwarf2_cu *,
2220                                    struct dwarf2_per_cu_data *);
2221
2222 static void dwarf2_mark (struct dwarf2_cu *);
2223
2224 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2225
2226 static struct type *get_die_type_at_offset (sect_offset,
2227                                             struct dwarf2_per_cu_data *);
2228
2229 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2230
2231 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2232                              enum language pretend_language);
2233
2234 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2235
2236 /* Class, the destructor of which frees all allocated queue entries.  This
2237    will only have work to do if an error was thrown while processing the
2238    dwarf.  If no error was thrown then the queue entries should have all
2239    been processed, and freed, as we went along.  */
2240
2241 class dwarf2_queue_guard
2242 {
2243 public:
2244   dwarf2_queue_guard () = default;
2245
2246   /* Free any entries remaining on the queue.  There should only be
2247      entries left if we hit an error while processing the dwarf.  */
2248   ~dwarf2_queue_guard ()
2249   {
2250     struct dwarf2_queue_item *item, *last;
2251
2252     item = dwarf2_queue;
2253     while (item)
2254       {
2255         /* Anything still marked queued is likely to be in an
2256            inconsistent state, so discard it.  */
2257         if (item->per_cu->queued)
2258           {
2259             if (item->per_cu->cu != NULL)
2260               free_one_cached_comp_unit (item->per_cu);
2261             item->per_cu->queued = 0;
2262           }
2263
2264         last = item;
2265         item = item->next;
2266         xfree (last);
2267       }
2268
2269     dwarf2_queue = dwarf2_queue_tail = NULL;
2270   }
2271 };
2272
2273 /* The return type of find_file_and_directory.  Note, the enclosed
2274    string pointers are only valid while this object is valid.  */
2275
2276 struct file_and_directory
2277 {
2278   /* The filename.  This is never NULL.  */
2279   const char *name;
2280
2281   /* The compilation directory.  NULL if not known.  If we needed to
2282      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2283      points directly to the DW_AT_comp_dir string attribute owned by
2284      the obstack that owns the DIE.  */
2285   const char *comp_dir;
2286
2287   /* If we needed to build a new string for comp_dir, this is what
2288      owns the storage.  */
2289   std::string comp_dir_storage;
2290 };
2291
2292 static file_and_directory find_file_and_directory (struct die_info *die,
2293                                                    struct dwarf2_cu *cu);
2294
2295 static char *file_full_name (int file, struct line_header *lh,
2296                              const char *comp_dir);
2297
2298 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2299 enum class rcuh_kind { COMPILE, TYPE };
2300
2301 static const gdb_byte *read_and_check_comp_unit_head
2302   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2303    struct comp_unit_head *header,
2304    struct dwarf2_section_info *section,
2305    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2306    rcuh_kind section_kind);
2307
2308 static void init_cutu_and_read_dies
2309   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2310    int use_existing_cu, int keep,
2311    die_reader_func_ftype *die_reader_func, void *data);
2312
2313 static void init_cutu_and_read_dies_simple
2314   (struct dwarf2_per_cu_data *this_cu,
2315    die_reader_func_ftype *die_reader_func, void *data);
2316
2317 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2318
2319 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2320
2321 static struct dwo_unit *lookup_dwo_unit_in_dwp
2322   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2323    struct dwp_file *dwp_file, const char *comp_dir,
2324    ULONGEST signature, int is_debug_types);
2325
2326 static struct dwp_file *get_dwp_file
2327   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2328
2329 static struct dwo_unit *lookup_dwo_comp_unit
2330   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2331
2332 static struct dwo_unit *lookup_dwo_type_unit
2333   (struct signatured_type *, const char *, const char *);
2334
2335 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2336
2337 static void free_dwo_file_cleanup (void *);
2338
2339 struct free_dwo_file_cleanup_data
2340 {
2341   struct dwo_file *dwo_file;
2342   struct dwarf2_per_objfile *dwarf2_per_objfile;
2343 };
2344
2345 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2346
2347 static void check_producer (struct dwarf2_cu *cu);
2348
2349 static void free_line_header_voidp (void *arg);
2350 \f
2351 /* Various complaints about symbol reading that don't abort the process.  */
2352
2353 static void
2354 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2355 {
2356   complaint (&symfile_complaints,
2357              _("statement list doesn't fit in .debug_line section"));
2358 }
2359
2360 static void
2361 dwarf2_debug_line_missing_file_complaint (void)
2362 {
2363   complaint (&symfile_complaints,
2364              _(".debug_line section has line data without a file"));
2365 }
2366
2367 static void
2368 dwarf2_debug_line_missing_end_sequence_complaint (void)
2369 {
2370   complaint (&symfile_complaints,
2371              _(".debug_line section has line "
2372                "program sequence without an end"));
2373 }
2374
2375 static void
2376 dwarf2_complex_location_expr_complaint (void)
2377 {
2378   complaint (&symfile_complaints, _("location expression too complex"));
2379 }
2380
2381 static void
2382 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2383                                               int arg3)
2384 {
2385   complaint (&symfile_complaints,
2386              _("const value length mismatch for '%s', got %d, expected %d"),
2387              arg1, arg2, arg3);
2388 }
2389
2390 static void
2391 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2392 {
2393   complaint (&symfile_complaints,
2394              _("debug info runs off end of %s section"
2395                " [in module %s]"),
2396              get_section_name (section),
2397              get_section_file_name (section));
2398 }
2399
2400 static void
2401 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2402 {
2403   complaint (&symfile_complaints,
2404              _("macro debug info contains a "
2405                "malformed macro definition:\n`%s'"),
2406              arg1);
2407 }
2408
2409 static void
2410 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2411 {
2412   complaint (&symfile_complaints,
2413              _("invalid attribute class or form for '%s' in '%s'"),
2414              arg1, arg2);
2415 }
2416
2417 /* Hash function for line_header_hash.  */
2418
2419 static hashval_t
2420 line_header_hash (const struct line_header *ofs)
2421 {
2422   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2423 }
2424
2425 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2426
2427 static hashval_t
2428 line_header_hash_voidp (const void *item)
2429 {
2430   const struct line_header *ofs = (const struct line_header *) item;
2431
2432   return line_header_hash (ofs);
2433 }
2434
2435 /* Equality function for line_header_hash.  */
2436
2437 static int
2438 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2439 {
2440   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2441   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2442
2443   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2444           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2445 }
2446
2447 \f
2448
2449 /* Read the given attribute value as an address, taking the attribute's
2450    form into account.  */
2451
2452 static CORE_ADDR
2453 attr_value_as_address (struct attribute *attr)
2454 {
2455   CORE_ADDR addr;
2456
2457   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2458     {
2459       /* Aside from a few clearly defined exceptions, attributes that
2460          contain an address must always be in DW_FORM_addr form.
2461          Unfortunately, some compilers happen to be violating this
2462          requirement by encoding addresses using other forms, such
2463          as DW_FORM_data4 for example.  For those broken compilers,
2464          we try to do our best, without any guarantee of success,
2465          to interpret the address correctly.  It would also be nice
2466          to generate a complaint, but that would require us to maintain
2467          a list of legitimate cases where a non-address form is allowed,
2468          as well as update callers to pass in at least the CU's DWARF
2469          version.  This is more overhead than what we're willing to
2470          expand for a pretty rare case.  */
2471       addr = DW_UNSND (attr);
2472     }
2473   else
2474     addr = DW_ADDR (attr);
2475
2476   return addr;
2477 }
2478
2479 /* The suffix for an index file.  */
2480 #define INDEX4_SUFFIX ".gdb-index"
2481 #define INDEX5_SUFFIX ".debug_names"
2482 #define DEBUG_STR_SUFFIX ".debug_str"
2483
2484 /* See declaration.  */
2485
2486 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2487                                         const dwarf2_debug_sections *names)
2488   : objfile (objfile_)
2489 {
2490   if (names == NULL)
2491     names = &dwarf2_elf_names;
2492
2493   bfd *obfd = objfile->obfd;
2494
2495   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2496     locate_sections (obfd, sec, *names);
2497 }
2498
2499 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2500
2501 dwarf2_per_objfile::~dwarf2_per_objfile ()
2502 {
2503   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2504   free_cached_comp_units ();
2505
2506   if (quick_file_names_table)
2507     htab_delete (quick_file_names_table);
2508
2509   if (line_header_hash)
2510     htab_delete (line_header_hash);
2511
2512   for (int ix = 0; ix < n_comp_units; ++ix)
2513    VEC_free (dwarf2_per_cu_ptr, all_comp_units[ix]->imported_symtabs);
2514
2515   for (int ix = 0; ix < n_type_units; ++ix)
2516     VEC_free (dwarf2_per_cu_ptr,
2517               all_type_units[ix]->per_cu.imported_symtabs);
2518   xfree (all_type_units);
2519
2520   VEC_free (dwarf2_section_info_def, types);
2521
2522   if (dwo_files != NULL)
2523     free_dwo_files (dwo_files, objfile);
2524   if (dwp_file != NULL)
2525     gdb_bfd_unref (dwp_file->dbfd);
2526
2527   if (dwz_file != NULL && dwz_file->dwz_bfd)
2528     gdb_bfd_unref (dwz_file->dwz_bfd);
2529
2530   if (index_table != NULL)
2531     index_table->~mapped_index ();
2532
2533   /* Everything else should be on the objfile obstack.  */
2534 }
2535
2536 /* See declaration.  */
2537
2538 void
2539 dwarf2_per_objfile::free_cached_comp_units ()
2540 {
2541   dwarf2_per_cu_data *per_cu = read_in_chain;
2542   dwarf2_per_cu_data **last_chain = &read_in_chain;
2543   while (per_cu != NULL)
2544     {
2545       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2546
2547       delete per_cu->cu;
2548       *last_chain = next_cu;
2549       per_cu = next_cu;
2550     }
2551 }
2552
2553 /* Try to locate the sections we need for DWARF 2 debugging
2554    information and return true if we have enough to do something.
2555    NAMES points to the dwarf2 section names, or is NULL if the standard
2556    ELF names are used.  */
2557
2558 int
2559 dwarf2_has_info (struct objfile *objfile,
2560                  const struct dwarf2_debug_sections *names)
2561 {
2562   if (objfile->flags & OBJF_READNEVER)
2563     return 0;
2564
2565   struct dwarf2_per_objfile *dwarf2_per_objfile
2566     = get_dwarf2_per_objfile (objfile);
2567
2568   if (dwarf2_per_objfile == NULL)
2569     {
2570       /* Initialize per-objfile state.  */
2571       dwarf2_per_objfile
2572         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2573                                                                      names);
2574       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2575     }
2576   return (!dwarf2_per_objfile->info.is_virtual
2577           && dwarf2_per_objfile->info.s.section != NULL
2578           && !dwarf2_per_objfile->abbrev.is_virtual
2579           && dwarf2_per_objfile->abbrev.s.section != NULL);
2580 }
2581
2582 /* Return the containing section of virtual section SECTION.  */
2583
2584 static struct dwarf2_section_info *
2585 get_containing_section (const struct dwarf2_section_info *section)
2586 {
2587   gdb_assert (section->is_virtual);
2588   return section->s.containing_section;
2589 }
2590
2591 /* Return the bfd owner of SECTION.  */
2592
2593 static struct bfd *
2594 get_section_bfd_owner (const struct dwarf2_section_info *section)
2595 {
2596   if (section->is_virtual)
2597     {
2598       section = get_containing_section (section);
2599       gdb_assert (!section->is_virtual);
2600     }
2601   return section->s.section->owner;
2602 }
2603
2604 /* Return the bfd section of SECTION.
2605    Returns NULL if the section is not present.  */
2606
2607 static asection *
2608 get_section_bfd_section (const struct dwarf2_section_info *section)
2609 {
2610   if (section->is_virtual)
2611     {
2612       section = get_containing_section (section);
2613       gdb_assert (!section->is_virtual);
2614     }
2615   return section->s.section;
2616 }
2617
2618 /* Return the name of SECTION.  */
2619
2620 static const char *
2621 get_section_name (const struct dwarf2_section_info *section)
2622 {
2623   asection *sectp = get_section_bfd_section (section);
2624
2625   gdb_assert (sectp != NULL);
2626   return bfd_section_name (get_section_bfd_owner (section), sectp);
2627 }
2628
2629 /* Return the name of the file SECTION is in.  */
2630
2631 static const char *
2632 get_section_file_name (const struct dwarf2_section_info *section)
2633 {
2634   bfd *abfd = get_section_bfd_owner (section);
2635
2636   return bfd_get_filename (abfd);
2637 }
2638
2639 /* Return the id of SECTION.
2640    Returns 0 if SECTION doesn't exist.  */
2641
2642 static int
2643 get_section_id (const struct dwarf2_section_info *section)
2644 {
2645   asection *sectp = get_section_bfd_section (section);
2646
2647   if (sectp == NULL)
2648     return 0;
2649   return sectp->id;
2650 }
2651
2652 /* Return the flags of SECTION.
2653    SECTION (or containing section if this is a virtual section) must exist.  */
2654
2655 static int
2656 get_section_flags (const struct dwarf2_section_info *section)
2657 {
2658   asection *sectp = get_section_bfd_section (section);
2659
2660   gdb_assert (sectp != NULL);
2661   return bfd_get_section_flags (sectp->owner, sectp);
2662 }
2663
2664 /* When loading sections, we look either for uncompressed section or for
2665    compressed section names.  */
2666
2667 static int
2668 section_is_p (const char *section_name,
2669               const struct dwarf2_section_names *names)
2670 {
2671   if (names->normal != NULL
2672       && strcmp (section_name, names->normal) == 0)
2673     return 1;
2674   if (names->compressed != NULL
2675       && strcmp (section_name, names->compressed) == 0)
2676     return 1;
2677   return 0;
2678 }
2679
2680 /* See declaration.  */
2681
2682 void
2683 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2684                                      const dwarf2_debug_sections &names)
2685 {
2686   flagword aflag = bfd_get_section_flags (abfd, sectp);
2687
2688   if ((aflag & SEC_HAS_CONTENTS) == 0)
2689     {
2690     }
2691   else if (section_is_p (sectp->name, &names.info))
2692     {
2693       this->info.s.section = sectp;
2694       this->info.size = bfd_get_section_size (sectp);
2695     }
2696   else if (section_is_p (sectp->name, &names.abbrev))
2697     {
2698       this->abbrev.s.section = sectp;
2699       this->abbrev.size = bfd_get_section_size (sectp);
2700     }
2701   else if (section_is_p (sectp->name, &names.line))
2702     {
2703       this->line.s.section = sectp;
2704       this->line.size = bfd_get_section_size (sectp);
2705     }
2706   else if (section_is_p (sectp->name, &names.loc))
2707     {
2708       this->loc.s.section = sectp;
2709       this->loc.size = bfd_get_section_size (sectp);
2710     }
2711   else if (section_is_p (sectp->name, &names.loclists))
2712     {
2713       this->loclists.s.section = sectp;
2714       this->loclists.size = bfd_get_section_size (sectp);
2715     }
2716   else if (section_is_p (sectp->name, &names.macinfo))
2717     {
2718       this->macinfo.s.section = sectp;
2719       this->macinfo.size = bfd_get_section_size (sectp);
2720     }
2721   else if (section_is_p (sectp->name, &names.macro))
2722     {
2723       this->macro.s.section = sectp;
2724       this->macro.size = bfd_get_section_size (sectp);
2725     }
2726   else if (section_is_p (sectp->name, &names.str))
2727     {
2728       this->str.s.section = sectp;
2729       this->str.size = bfd_get_section_size (sectp);
2730     }
2731   else if (section_is_p (sectp->name, &names.line_str))
2732     {
2733       this->line_str.s.section = sectp;
2734       this->line_str.size = bfd_get_section_size (sectp);
2735     }
2736   else if (section_is_p (sectp->name, &names.addr))
2737     {
2738       this->addr.s.section = sectp;
2739       this->addr.size = bfd_get_section_size (sectp);
2740     }
2741   else if (section_is_p (sectp->name, &names.frame))
2742     {
2743       this->frame.s.section = sectp;
2744       this->frame.size = bfd_get_section_size (sectp);
2745     }
2746   else if (section_is_p (sectp->name, &names.eh_frame))
2747     {
2748       this->eh_frame.s.section = sectp;
2749       this->eh_frame.size = bfd_get_section_size (sectp);
2750     }
2751   else if (section_is_p (sectp->name, &names.ranges))
2752     {
2753       this->ranges.s.section = sectp;
2754       this->ranges.size = bfd_get_section_size (sectp);
2755     }
2756   else if (section_is_p (sectp->name, &names.rnglists))
2757     {
2758       this->rnglists.s.section = sectp;
2759       this->rnglists.size = bfd_get_section_size (sectp);
2760     }
2761   else if (section_is_p (sectp->name, &names.types))
2762     {
2763       struct dwarf2_section_info type_section;
2764
2765       memset (&type_section, 0, sizeof (type_section));
2766       type_section.s.section = sectp;
2767       type_section.size = bfd_get_section_size (sectp);
2768
2769       VEC_safe_push (dwarf2_section_info_def, this->types,
2770                      &type_section);
2771     }
2772   else if (section_is_p (sectp->name, &names.gdb_index))
2773     {
2774       this->gdb_index.s.section = sectp;
2775       this->gdb_index.size = bfd_get_section_size (sectp);
2776     }
2777   else if (section_is_p (sectp->name, &names.debug_names))
2778     {
2779       this->debug_names.s.section = sectp;
2780       this->debug_names.size = bfd_get_section_size (sectp);
2781     }
2782   else if (section_is_p (sectp->name, &names.debug_aranges))
2783     {
2784       this->debug_aranges.s.section = sectp;
2785       this->debug_aranges.size = bfd_get_section_size (sectp);
2786     }
2787
2788   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2789       && bfd_section_vma (abfd, sectp) == 0)
2790     this->has_section_at_zero = true;
2791 }
2792
2793 /* A helper function that decides whether a section is empty,
2794    or not present.  */
2795
2796 static int
2797 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2798 {
2799   if (section->is_virtual)
2800     return section->size == 0;
2801   return section->s.section == NULL || section->size == 0;
2802 }
2803
2804 /* Read the contents of the section INFO.
2805    OBJFILE is the main object file, but not necessarily the file where
2806    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2807    of the DWO file.
2808    If the section is compressed, uncompress it before returning.  */
2809
2810 static void
2811 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2812 {
2813   asection *sectp;
2814   bfd *abfd;
2815   gdb_byte *buf, *retbuf;
2816
2817   if (info->readin)
2818     return;
2819   info->buffer = NULL;
2820   info->readin = 1;
2821
2822   if (dwarf2_section_empty_p (info))
2823     return;
2824
2825   sectp = get_section_bfd_section (info);
2826
2827   /* If this is a virtual section we need to read in the real one first.  */
2828   if (info->is_virtual)
2829     {
2830       struct dwarf2_section_info *containing_section =
2831         get_containing_section (info);
2832
2833       gdb_assert (sectp != NULL);
2834       if ((sectp->flags & SEC_RELOC) != 0)
2835         {
2836           error (_("Dwarf Error: DWP format V2 with relocations is not"
2837                    " supported in section %s [in module %s]"),
2838                  get_section_name (info), get_section_file_name (info));
2839         }
2840       dwarf2_read_section (objfile, containing_section);
2841       /* Other code should have already caught virtual sections that don't
2842          fit.  */
2843       gdb_assert (info->virtual_offset + info->size
2844                   <= containing_section->size);
2845       /* If the real section is empty or there was a problem reading the
2846          section we shouldn't get here.  */
2847       gdb_assert (containing_section->buffer != NULL);
2848       info->buffer = containing_section->buffer + info->virtual_offset;
2849       return;
2850     }
2851
2852   /* If the section has relocations, we must read it ourselves.
2853      Otherwise we attach it to the BFD.  */
2854   if ((sectp->flags & SEC_RELOC) == 0)
2855     {
2856       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2857       return;
2858     }
2859
2860   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2861   info->buffer = buf;
2862
2863   /* When debugging .o files, we may need to apply relocations; see
2864      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2865      We never compress sections in .o files, so we only need to
2866      try this when the section is not compressed.  */
2867   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2868   if (retbuf != NULL)
2869     {
2870       info->buffer = retbuf;
2871       return;
2872     }
2873
2874   abfd = get_section_bfd_owner (info);
2875   gdb_assert (abfd != NULL);
2876
2877   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2878       || bfd_bread (buf, info->size, abfd) != info->size)
2879     {
2880       error (_("Dwarf Error: Can't read DWARF data"
2881                " in section %s [in module %s]"),
2882              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2883     }
2884 }
2885
2886 /* A helper function that returns the size of a section in a safe way.
2887    If you are positive that the section has been read before using the
2888    size, then it is safe to refer to the dwarf2_section_info object's
2889    "size" field directly.  In other cases, you must call this
2890    function, because for compressed sections the size field is not set
2891    correctly until the section has been read.  */
2892
2893 static bfd_size_type
2894 dwarf2_section_size (struct objfile *objfile,
2895                      struct dwarf2_section_info *info)
2896 {
2897   if (!info->readin)
2898     dwarf2_read_section (objfile, info);
2899   return info->size;
2900 }
2901
2902 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2903    SECTION_NAME.  */
2904
2905 void
2906 dwarf2_get_section_info (struct objfile *objfile,
2907                          enum dwarf2_section_enum sect,
2908                          asection **sectp, const gdb_byte **bufp,
2909                          bfd_size_type *sizep)
2910 {
2911   struct dwarf2_per_objfile *data
2912     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2913                                                   dwarf2_objfile_data_key);
2914   struct dwarf2_section_info *info;
2915
2916   /* We may see an objfile without any DWARF, in which case we just
2917      return nothing.  */
2918   if (data == NULL)
2919     {
2920       *sectp = NULL;
2921       *bufp = NULL;
2922       *sizep = 0;
2923       return;
2924     }
2925   switch (sect)
2926     {
2927     case DWARF2_DEBUG_FRAME:
2928       info = &data->frame;
2929       break;
2930     case DWARF2_EH_FRAME:
2931       info = &data->eh_frame;
2932       break;
2933     default:
2934       gdb_assert_not_reached ("unexpected section");
2935     }
2936
2937   dwarf2_read_section (objfile, info);
2938
2939   *sectp = get_section_bfd_section (info);
2940   *bufp = info->buffer;
2941   *sizep = info->size;
2942 }
2943
2944 /* A helper function to find the sections for a .dwz file.  */
2945
2946 static void
2947 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2948 {
2949   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2950
2951   /* Note that we only support the standard ELF names, because .dwz
2952      is ELF-only (at the time of writing).  */
2953   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2954     {
2955       dwz_file->abbrev.s.section = sectp;
2956       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2957     }
2958   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2959     {
2960       dwz_file->info.s.section = sectp;
2961       dwz_file->info.size = bfd_get_section_size (sectp);
2962     }
2963   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2964     {
2965       dwz_file->str.s.section = sectp;
2966       dwz_file->str.size = bfd_get_section_size (sectp);
2967     }
2968   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2969     {
2970       dwz_file->line.s.section = sectp;
2971       dwz_file->line.size = bfd_get_section_size (sectp);
2972     }
2973   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2974     {
2975       dwz_file->macro.s.section = sectp;
2976       dwz_file->macro.size = bfd_get_section_size (sectp);
2977     }
2978   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2979     {
2980       dwz_file->gdb_index.s.section = sectp;
2981       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2982     }
2983   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2984     {
2985       dwz_file->debug_names.s.section = sectp;
2986       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2987     }
2988 }
2989
2990 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2991    there is no .gnu_debugaltlink section in the file.  Error if there
2992    is such a section but the file cannot be found.  */
2993
2994 static struct dwz_file *
2995 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2996 {
2997   const char *filename;
2998   struct dwz_file *result;
2999   bfd_size_type buildid_len_arg;
3000   size_t buildid_len;
3001   bfd_byte *buildid;
3002
3003   if (dwarf2_per_objfile->dwz_file != NULL)
3004     return dwarf2_per_objfile->dwz_file;
3005
3006   bfd_set_error (bfd_error_no_error);
3007   gdb::unique_xmalloc_ptr<char> data
3008     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
3009                                   &buildid_len_arg, &buildid));
3010   if (data == NULL)
3011     {
3012       if (bfd_get_error () == bfd_error_no_error)
3013         return NULL;
3014       error (_("could not read '.gnu_debugaltlink' section: %s"),
3015              bfd_errmsg (bfd_get_error ()));
3016     }
3017
3018   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
3019
3020   buildid_len = (size_t) buildid_len_arg;
3021
3022   filename = data.get ();
3023
3024   std::string abs_storage;
3025   if (!IS_ABSOLUTE_PATH (filename))
3026     {
3027       gdb::unique_xmalloc_ptr<char> abs
3028         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
3029
3030       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
3031       filename = abs_storage.c_str ();
3032     }
3033
3034   /* First try the file name given in the section.  If that doesn't
3035      work, try to use the build-id instead.  */
3036   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
3037   if (dwz_bfd != NULL)
3038     {
3039       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
3040         dwz_bfd.release ();
3041     }
3042
3043   if (dwz_bfd == NULL)
3044     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
3045
3046   if (dwz_bfd == NULL)
3047     error (_("could not find '.gnu_debugaltlink' file for %s"),
3048            objfile_name (dwarf2_per_objfile->objfile));
3049
3050   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
3051                            struct dwz_file);
3052   result->dwz_bfd = dwz_bfd.release ();
3053
3054   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
3055
3056   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
3057   dwarf2_per_objfile->dwz_file = result;
3058   return result;
3059 }
3060 \f
3061 /* DWARF quick_symbols_functions support.  */
3062
3063 /* TUs can share .debug_line entries, and there can be a lot more TUs than
3064    unique line tables, so we maintain a separate table of all .debug_line
3065    derived entries to support the sharing.
3066    All the quick functions need is the list of file names.  We discard the
3067    line_header when we're done and don't need to record it here.  */
3068 struct quick_file_names
3069 {
3070   /* The data used to construct the hash key.  */
3071   struct stmt_list_hash hash;
3072
3073   /* The number of entries in file_names, real_names.  */
3074   unsigned int num_file_names;
3075
3076   /* The file names from the line table, after being run through
3077      file_full_name.  */
3078   const char **file_names;
3079
3080   /* The file names from the line table after being run through
3081      gdb_realpath.  These are computed lazily.  */
3082   const char **real_names;
3083 };
3084
3085 /* When using the index (and thus not using psymtabs), each CU has an
3086    object of this type.  This is used to hold information needed by
3087    the various "quick" methods.  */
3088 struct dwarf2_per_cu_quick_data
3089 {
3090   /* The file table.  This can be NULL if there was no file table
3091      or it's currently not read in.
3092      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
3093   struct quick_file_names *file_names;
3094
3095   /* The corresponding symbol table.  This is NULL if symbols for this
3096      CU have not yet been read.  */
3097   struct compunit_symtab *compunit_symtab;
3098
3099   /* A temporary mark bit used when iterating over all CUs in
3100      expand_symtabs_matching.  */
3101   unsigned int mark : 1;
3102
3103   /* True if we've tried to read the file table and found there isn't one.
3104      There will be no point in trying to read it again next time.  */
3105   unsigned int no_file_data : 1;
3106 };
3107
3108 /* Utility hash function for a stmt_list_hash.  */
3109
3110 static hashval_t
3111 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3112 {
3113   hashval_t v = 0;
3114
3115   if (stmt_list_hash->dwo_unit != NULL)
3116     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3117   v += to_underlying (stmt_list_hash->line_sect_off);
3118   return v;
3119 }
3120
3121 /* Utility equality function for a stmt_list_hash.  */
3122
3123 static int
3124 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3125                     const struct stmt_list_hash *rhs)
3126 {
3127   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3128     return 0;
3129   if (lhs->dwo_unit != NULL
3130       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3131     return 0;
3132
3133   return lhs->line_sect_off == rhs->line_sect_off;
3134 }
3135
3136 /* Hash function for a quick_file_names.  */
3137
3138 static hashval_t
3139 hash_file_name_entry (const void *e)
3140 {
3141   const struct quick_file_names *file_data
3142     = (const struct quick_file_names *) e;
3143
3144   return hash_stmt_list_entry (&file_data->hash);
3145 }
3146
3147 /* Equality function for a quick_file_names.  */
3148
3149 static int
3150 eq_file_name_entry (const void *a, const void *b)
3151 {
3152   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3153   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3154
3155   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3156 }
3157
3158 /* Delete function for a quick_file_names.  */
3159
3160 static void
3161 delete_file_name_entry (void *e)
3162 {
3163   struct quick_file_names *file_data = (struct quick_file_names *) e;
3164   int i;
3165
3166   for (i = 0; i < file_data->num_file_names; ++i)
3167     {
3168       xfree ((void*) file_data->file_names[i]);
3169       if (file_data->real_names)
3170         xfree ((void*) file_data->real_names[i]);
3171     }
3172
3173   /* The space for the struct itself lives on objfile_obstack,
3174      so we don't free it here.  */
3175 }
3176
3177 /* Create a quick_file_names hash table.  */
3178
3179 static htab_t
3180 create_quick_file_names_table (unsigned int nr_initial_entries)
3181 {
3182   return htab_create_alloc (nr_initial_entries,
3183                             hash_file_name_entry, eq_file_name_entry,
3184                             delete_file_name_entry, xcalloc, xfree);
3185 }
3186
3187 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3188    have to be created afterwards.  You should call age_cached_comp_units after
3189    processing PER_CU->CU.  dw2_setup must have been already called.  */
3190
3191 static void
3192 load_cu (struct dwarf2_per_cu_data *per_cu)
3193 {
3194   if (per_cu->is_debug_types)
3195     load_full_type_unit (per_cu);
3196   else
3197     load_full_comp_unit (per_cu, language_minimal);
3198
3199   if (per_cu->cu == NULL)
3200     return;  /* Dummy CU.  */
3201
3202   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3203 }
3204
3205 /* Read in the symbols for PER_CU.  */
3206
3207 static void
3208 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3209 {
3210   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3211
3212   /* Skip type_unit_groups, reading the type units they contain
3213      is handled elsewhere.  */
3214   if (IS_TYPE_UNIT_GROUP (per_cu))
3215     return;
3216
3217   /* The destructor of dwarf2_queue_guard frees any entries left on
3218      the queue.  After this point we're guaranteed to leave this function
3219      with the dwarf queue empty.  */
3220   dwarf2_queue_guard q_guard;
3221
3222   if (dwarf2_per_objfile->using_index
3223       ? per_cu->v.quick->compunit_symtab == NULL
3224       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3225     {
3226       queue_comp_unit (per_cu, language_minimal);
3227       load_cu (per_cu);
3228
3229       /* If we just loaded a CU from a DWO, and we're working with an index
3230          that may badly handle TUs, load all the TUs in that DWO as well.
3231          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3232       if (!per_cu->is_debug_types
3233           && per_cu->cu != NULL
3234           && per_cu->cu->dwo_unit != NULL
3235           && dwarf2_per_objfile->index_table != NULL
3236           && dwarf2_per_objfile->index_table->version <= 7
3237           /* DWP files aren't supported yet.  */
3238           && get_dwp_file (dwarf2_per_objfile) == NULL)
3239         queue_and_load_all_dwo_tus (per_cu);
3240     }
3241
3242   process_queue (dwarf2_per_objfile);
3243
3244   /* Age the cache, releasing compilation units that have not
3245      been used recently.  */
3246   age_cached_comp_units (dwarf2_per_objfile);
3247 }
3248
3249 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3250    the objfile from which this CU came.  Returns the resulting symbol
3251    table.  */
3252
3253 static struct compunit_symtab *
3254 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3255 {
3256   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3257
3258   gdb_assert (dwarf2_per_objfile->using_index);
3259   if (!per_cu->v.quick->compunit_symtab)
3260     {
3261       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3262                                               dwarf2_per_objfile);
3263       scoped_restore decrementer = increment_reading_symtab ();
3264       dw2_do_instantiate_symtab (per_cu);
3265       process_cu_includes (dwarf2_per_objfile);
3266       do_cleanups (back_to);
3267     }
3268
3269   return per_cu->v.quick->compunit_symtab;
3270 }
3271
3272 /* Return the CU/TU given its index.
3273
3274    This is intended for loops like:
3275
3276    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3277                     + dwarf2_per_objfile->n_type_units); ++i)
3278      {
3279        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3280
3281        ...;
3282      }
3283 */
3284
3285 static struct dwarf2_per_cu_data *
3286 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3287               int index)
3288 {
3289   if (index >= dwarf2_per_objfile->n_comp_units)
3290     {
3291       index -= dwarf2_per_objfile->n_comp_units;
3292       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3293       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3294     }
3295
3296   return dwarf2_per_objfile->all_comp_units[index];
3297 }
3298
3299 /* Return the CU given its index.
3300    This differs from dw2_get_cutu in that it's for when you know INDEX
3301    refers to a CU.  */
3302
3303 static struct dwarf2_per_cu_data *
3304 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3305 {
3306   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3307
3308   return dwarf2_per_objfile->all_comp_units[index];
3309 }
3310
3311 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3312    objfile_obstack, and constructed with the specified field
3313    values.  */
3314
3315 static dwarf2_per_cu_data *
3316 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3317                           struct dwarf2_section_info *section,
3318                           int is_dwz,
3319                           sect_offset sect_off, ULONGEST length)
3320 {
3321   struct objfile *objfile = dwarf2_per_objfile->objfile;
3322   dwarf2_per_cu_data *the_cu
3323     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3324                      struct dwarf2_per_cu_data);
3325   the_cu->sect_off = sect_off;
3326   the_cu->length = length;
3327   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3328   the_cu->section = section;
3329   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3330                                    struct dwarf2_per_cu_quick_data);
3331   the_cu->is_dwz = is_dwz;
3332   return the_cu;
3333 }
3334
3335 /* A helper for create_cus_from_index that handles a given list of
3336    CUs.  */
3337
3338 static void
3339 create_cus_from_index_list (struct objfile *objfile,
3340                             const gdb_byte *cu_list, offset_type n_elements,
3341                             struct dwarf2_section_info *section,
3342                             int is_dwz,
3343                             int base_offset)
3344 {
3345   offset_type i;
3346   struct dwarf2_per_objfile *dwarf2_per_objfile
3347     = get_dwarf2_per_objfile (objfile);
3348
3349   for (i = 0; i < n_elements; i += 2)
3350     {
3351       gdb_static_assert (sizeof (ULONGEST) >= 8);
3352
3353       sect_offset sect_off
3354         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3355       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3356       cu_list += 2 * 8;
3357
3358       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3359         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3360                                      sect_off, length);
3361     }
3362 }
3363
3364 /* Read the CU list from the mapped index, and use it to create all
3365    the CU objects for this objfile.  */
3366
3367 static void
3368 create_cus_from_index (struct objfile *objfile,
3369                        const gdb_byte *cu_list, offset_type cu_list_elements,
3370                        const gdb_byte *dwz_list, offset_type dwz_elements)
3371 {
3372   struct dwz_file *dwz;
3373   struct dwarf2_per_objfile *dwarf2_per_objfile
3374     = get_dwarf2_per_objfile (objfile);
3375
3376   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3377   dwarf2_per_objfile->all_comp_units =
3378     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3379                dwarf2_per_objfile->n_comp_units);
3380
3381   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3382                               &dwarf2_per_objfile->info, 0, 0);
3383
3384   if (dwz_elements == 0)
3385     return;
3386
3387   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3388   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3389                               cu_list_elements / 2);
3390 }
3391
3392 /* Create the signatured type hash table from the index.  */
3393
3394 static void
3395 create_signatured_type_table_from_index (struct objfile *objfile,
3396                                          struct dwarf2_section_info *section,
3397                                          const gdb_byte *bytes,
3398                                          offset_type elements)
3399 {
3400   offset_type i;
3401   htab_t sig_types_hash;
3402   struct dwarf2_per_objfile *dwarf2_per_objfile
3403     = get_dwarf2_per_objfile (objfile);
3404
3405   dwarf2_per_objfile->n_type_units
3406     = dwarf2_per_objfile->n_allocated_type_units
3407     = elements / 3;
3408   dwarf2_per_objfile->all_type_units =
3409     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3410
3411   sig_types_hash = allocate_signatured_type_table (objfile);
3412
3413   for (i = 0; i < elements; i += 3)
3414     {
3415       struct signatured_type *sig_type;
3416       ULONGEST signature;
3417       void **slot;
3418       cu_offset type_offset_in_tu;
3419
3420       gdb_static_assert (sizeof (ULONGEST) >= 8);
3421       sect_offset sect_off
3422         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3423       type_offset_in_tu
3424         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3425                                                 BFD_ENDIAN_LITTLE);
3426       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3427       bytes += 3 * 8;
3428
3429       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3430                                  struct signatured_type);
3431       sig_type->signature = signature;
3432       sig_type->type_offset_in_tu = type_offset_in_tu;
3433       sig_type->per_cu.is_debug_types = 1;
3434       sig_type->per_cu.section = section;
3435       sig_type->per_cu.sect_off = sect_off;
3436       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3437       sig_type->per_cu.v.quick
3438         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3439                           struct dwarf2_per_cu_quick_data);
3440
3441       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3442       *slot = sig_type;
3443
3444       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3445     }
3446
3447   dwarf2_per_objfile->signatured_types = sig_types_hash;
3448 }
3449
3450 /* Create the signatured type hash table from .debug_names.  */
3451
3452 static void
3453 create_signatured_type_table_from_debug_names
3454   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3455    const mapped_debug_names &map,
3456    struct dwarf2_section_info *section,
3457    struct dwarf2_section_info *abbrev_section)
3458 {
3459   struct objfile *objfile = dwarf2_per_objfile->objfile;
3460
3461   dwarf2_read_section (objfile, section);
3462   dwarf2_read_section (objfile, abbrev_section);
3463
3464   dwarf2_per_objfile->n_type_units
3465     = dwarf2_per_objfile->n_allocated_type_units
3466     = map.tu_count;
3467   dwarf2_per_objfile->all_type_units
3468     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3469
3470   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3471
3472   for (uint32_t i = 0; i < map.tu_count; ++i)
3473     {
3474       struct signatured_type *sig_type;
3475       ULONGEST signature;
3476       void **slot;
3477       cu_offset type_offset_in_tu;
3478
3479       sect_offset sect_off
3480         = (sect_offset) (extract_unsigned_integer
3481                          (map.tu_table_reordered + i * map.offset_size,
3482                           map.offset_size,
3483                           map.dwarf5_byte_order));
3484
3485       comp_unit_head cu_header;
3486       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3487                                      abbrev_section,
3488                                      section->buffer + to_underlying (sect_off),
3489                                      rcuh_kind::TYPE);
3490
3491       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3492                                  struct signatured_type);
3493       sig_type->signature = cu_header.signature;
3494       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3495       sig_type->per_cu.is_debug_types = 1;
3496       sig_type->per_cu.section = section;
3497       sig_type->per_cu.sect_off = sect_off;
3498       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3499       sig_type->per_cu.v.quick
3500         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3501                           struct dwarf2_per_cu_quick_data);
3502
3503       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3504       *slot = sig_type;
3505
3506       dwarf2_per_objfile->all_type_units[i] = sig_type;
3507     }
3508
3509   dwarf2_per_objfile->signatured_types = sig_types_hash;
3510 }
3511
3512 /* Read the address map data from the mapped index, and use it to
3513    populate the objfile's psymtabs_addrmap.  */
3514
3515 static void
3516 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3517                            struct mapped_index *index)
3518 {
3519   struct objfile *objfile = dwarf2_per_objfile->objfile;
3520   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3521   const gdb_byte *iter, *end;
3522   struct addrmap *mutable_map;
3523   CORE_ADDR baseaddr;
3524
3525   auto_obstack temp_obstack;
3526
3527   mutable_map = addrmap_create_mutable (&temp_obstack);
3528
3529   iter = index->address_table.data ();
3530   end = iter + index->address_table.size ();
3531
3532   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3533
3534   while (iter < end)
3535     {
3536       ULONGEST hi, lo, cu_index;
3537       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3538       iter += 8;
3539       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3540       iter += 8;
3541       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3542       iter += 4;
3543
3544       if (lo > hi)
3545         {
3546           complaint (&symfile_complaints,
3547                      _(".gdb_index address table has invalid range (%s - %s)"),
3548                      hex_string (lo), hex_string (hi));
3549           continue;
3550         }
3551
3552       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3553         {
3554           complaint (&symfile_complaints,
3555                      _(".gdb_index address table has invalid CU number %u"),
3556                      (unsigned) cu_index);
3557           continue;
3558         }
3559
3560       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3561       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3562       addrmap_set_empty (mutable_map, lo, hi - 1,
3563                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3564     }
3565
3566   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3567                                                     &objfile->objfile_obstack);
3568 }
3569
3570 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3571    populate the objfile's psymtabs_addrmap.  */
3572
3573 static void
3574 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3575                              struct dwarf2_section_info *section)
3576 {
3577   struct objfile *objfile = dwarf2_per_objfile->objfile;
3578   bfd *abfd = objfile->obfd;
3579   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3580   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3581                                        SECT_OFF_TEXT (objfile));
3582
3583   auto_obstack temp_obstack;
3584   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3585
3586   std::unordered_map<sect_offset,
3587                      dwarf2_per_cu_data *,
3588                      gdb::hash_enum<sect_offset>>
3589     debug_info_offset_to_per_cu;
3590   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3591     {
3592       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3593       const auto insertpair
3594         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3595       if (!insertpair.second)
3596         {
3597           warning (_("Section .debug_aranges in %s has duplicate "
3598                      "debug_info_offset %s, ignoring .debug_aranges."),
3599                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3600           return;
3601         }
3602     }
3603
3604   dwarf2_read_section (objfile, section);
3605
3606   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3607
3608   const gdb_byte *addr = section->buffer;
3609
3610   while (addr < section->buffer + section->size)
3611     {
3612       const gdb_byte *const entry_addr = addr;
3613       unsigned int bytes_read;
3614
3615       const LONGEST entry_length = read_initial_length (abfd, addr,
3616                                                         &bytes_read);
3617       addr += bytes_read;
3618
3619       const gdb_byte *const entry_end = addr + entry_length;
3620       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3621       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3622       if (addr + entry_length > section->buffer + section->size)
3623         {
3624           warning (_("Section .debug_aranges in %s entry at offset %zu "
3625                      "length %s exceeds section length %s, "
3626                      "ignoring .debug_aranges."),
3627                    objfile_name (objfile), entry_addr - section->buffer,
3628                    plongest (bytes_read + entry_length),
3629                    pulongest (section->size));
3630           return;
3631         }
3632
3633       /* The version number.  */
3634       const uint16_t version = read_2_bytes (abfd, addr);
3635       addr += 2;
3636       if (version != 2)
3637         {
3638           warning (_("Section .debug_aranges in %s entry at offset %zu "
3639                      "has unsupported version %d, ignoring .debug_aranges."),
3640                    objfile_name (objfile), entry_addr - section->buffer,
3641                    version);
3642           return;
3643         }
3644
3645       const uint64_t debug_info_offset
3646         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3647       addr += offset_size;
3648       const auto per_cu_it
3649         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3650       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3651         {
3652           warning (_("Section .debug_aranges in %s entry at offset %zu "
3653                      "debug_info_offset %s does not exists, "
3654                      "ignoring .debug_aranges."),
3655                    objfile_name (objfile), entry_addr - section->buffer,
3656                    pulongest (debug_info_offset));
3657           return;
3658         }
3659       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3660
3661       const uint8_t address_size = *addr++;
3662       if (address_size < 1 || address_size > 8)
3663         {
3664           warning (_("Section .debug_aranges in %s entry at offset %zu "
3665                      "address_size %u is invalid, ignoring .debug_aranges."),
3666                    objfile_name (objfile), entry_addr - section->buffer,
3667                    address_size);
3668           return;
3669         }
3670
3671       const uint8_t segment_selector_size = *addr++;
3672       if (segment_selector_size != 0)
3673         {
3674           warning (_("Section .debug_aranges in %s entry at offset %zu "
3675                      "segment_selector_size %u is not supported, "
3676                      "ignoring .debug_aranges."),
3677                    objfile_name (objfile), entry_addr - section->buffer,
3678                    segment_selector_size);
3679           return;
3680         }
3681
3682       /* Must pad to an alignment boundary that is twice the address
3683          size.  It is undocumented by the DWARF standard but GCC does
3684          use it.  */
3685       for (size_t padding = ((-(addr - section->buffer))
3686                              & (2 * address_size - 1));
3687            padding > 0; padding--)
3688         if (*addr++ != 0)
3689           {
3690             warning (_("Section .debug_aranges in %s entry at offset %zu "
3691                        "padding is not zero, ignoring .debug_aranges."),
3692                      objfile_name (objfile), entry_addr - section->buffer);
3693             return;
3694           }
3695
3696       for (;;)
3697         {
3698           if (addr + 2 * address_size > entry_end)
3699             {
3700               warning (_("Section .debug_aranges in %s entry at offset %zu "
3701                          "address list is not properly terminated, "
3702                          "ignoring .debug_aranges."),
3703                        objfile_name (objfile), entry_addr - section->buffer);
3704               return;
3705             }
3706           ULONGEST start = extract_unsigned_integer (addr, address_size,
3707                                                      dwarf5_byte_order);
3708           addr += address_size;
3709           ULONGEST length = extract_unsigned_integer (addr, address_size,
3710                                                       dwarf5_byte_order);
3711           addr += address_size;
3712           if (start == 0 && length == 0)
3713             break;
3714           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3715             {
3716               /* Symbol was eliminated due to a COMDAT group.  */
3717               continue;
3718             }
3719           ULONGEST end = start + length;
3720           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3721           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3722           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3723         }
3724     }
3725
3726   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3727                                                     &objfile->objfile_obstack);
3728 }
3729
3730 /* The hash function for strings in the mapped index.  This is the same as
3731    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3732    implementation.  This is necessary because the hash function is tied to the
3733    format of the mapped index file.  The hash values do not have to match with
3734    SYMBOL_HASH_NEXT.
3735    
3736    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3737
3738 static hashval_t
3739 mapped_index_string_hash (int index_version, const void *p)
3740 {
3741   const unsigned char *str = (const unsigned char *) p;
3742   hashval_t r = 0;
3743   unsigned char c;
3744
3745   while ((c = *str++) != 0)
3746     {
3747       if (index_version >= 5)
3748         c = tolower (c);
3749       r = r * 67 + c - 113;
3750     }
3751
3752   return r;
3753 }
3754
3755 /* Find a slot in the mapped index INDEX for the object named NAME.
3756    If NAME is found, set *VEC_OUT to point to the CU vector in the
3757    constant pool and return true.  If NAME cannot be found, return
3758    false.  */
3759
3760 static bool
3761 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3762                           offset_type **vec_out)
3763 {
3764   offset_type hash;
3765   offset_type slot, step;
3766   int (*cmp) (const char *, const char *);
3767
3768   gdb::unique_xmalloc_ptr<char> without_params;
3769   if (current_language->la_language == language_cplus
3770       || current_language->la_language == language_fortran
3771       || current_language->la_language == language_d)
3772     {
3773       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3774          not contain any.  */
3775
3776       if (strchr (name, '(') != NULL)
3777         {
3778           without_params = cp_remove_params (name);
3779
3780           if (without_params != NULL)
3781             name = without_params.get ();
3782         }
3783     }
3784
3785   /* Index version 4 did not support case insensitive searches.  But the
3786      indices for case insensitive languages are built in lowercase, therefore
3787      simulate our NAME being searched is also lowercased.  */
3788   hash = mapped_index_string_hash ((index->version == 4
3789                                     && case_sensitivity == case_sensitive_off
3790                                     ? 5 : index->version),
3791                                    name);
3792
3793   slot = hash & (index->symbol_table.size () - 1);
3794   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3795   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3796
3797   for (;;)
3798     {
3799       const char *str;
3800
3801       const auto &bucket = index->symbol_table[slot];
3802       if (bucket.name == 0 && bucket.vec == 0)
3803         return false;
3804
3805       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3806       if (!cmp (name, str))
3807         {
3808           *vec_out = (offset_type *) (index->constant_pool
3809                                       + MAYBE_SWAP (bucket.vec));
3810           return true;
3811         }
3812
3813       slot = (slot + step) & (index->symbol_table.size () - 1);
3814     }
3815 }
3816
3817 /* A helper function that reads the .gdb_index from SECTION and fills
3818    in MAP.  FILENAME is the name of the file containing the section;
3819    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3820    ok to use deprecated sections.
3821
3822    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3823    out parameters that are filled in with information about the CU and
3824    TU lists in the section.
3825
3826    Returns 1 if all went well, 0 otherwise.  */
3827
3828 static int
3829 read_index_from_section (struct objfile *objfile,
3830                          const char *filename,
3831                          int deprecated_ok,
3832                          struct dwarf2_section_info *section,
3833                          struct mapped_index *map,
3834                          const gdb_byte **cu_list,
3835                          offset_type *cu_list_elements,
3836                          const gdb_byte **types_list,
3837                          offset_type *types_list_elements)
3838 {
3839   const gdb_byte *addr;
3840   offset_type version;
3841   offset_type *metadata;
3842   int i;
3843
3844   if (dwarf2_section_empty_p (section))
3845     return 0;
3846
3847   /* Older elfutils strip versions could keep the section in the main
3848      executable while splitting it for the separate debug info file.  */
3849   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3850     return 0;
3851
3852   dwarf2_read_section (objfile, section);
3853
3854   addr = section->buffer;
3855   /* Version check.  */
3856   version = MAYBE_SWAP (*(offset_type *) addr);
3857   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3858      causes the index to behave very poorly for certain requests.  Version 3
3859      contained incomplete addrmap.  So, it seems better to just ignore such
3860      indices.  */
3861   if (version < 4)
3862     {
3863       static int warning_printed = 0;
3864       if (!warning_printed)
3865         {
3866           warning (_("Skipping obsolete .gdb_index section in %s."),
3867                    filename);
3868           warning_printed = 1;
3869         }
3870       return 0;
3871     }
3872   /* Index version 4 uses a different hash function than index version
3873      5 and later.
3874
3875      Versions earlier than 6 did not emit psymbols for inlined
3876      functions.  Using these files will cause GDB not to be able to
3877      set breakpoints on inlined functions by name, so we ignore these
3878      indices unless the user has done
3879      "set use-deprecated-index-sections on".  */
3880   if (version < 6 && !deprecated_ok)
3881     {
3882       static int warning_printed = 0;
3883       if (!warning_printed)
3884         {
3885           warning (_("\
3886 Skipping deprecated .gdb_index section in %s.\n\
3887 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3888 to use the section anyway."),
3889                    filename);
3890           warning_printed = 1;
3891         }
3892       return 0;
3893     }
3894   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3895      of the TU (for symbols coming from TUs),
3896      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3897      Plus gold-generated indices can have duplicate entries for global symbols,
3898      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3899      These are just performance bugs, and we can't distinguish gdb-generated
3900      indices from gold-generated ones, so issue no warning here.  */
3901
3902   /* Indexes with higher version than the one supported by GDB may be no
3903      longer backward compatible.  */
3904   if (version > 8)
3905     return 0;
3906
3907   map->version = version;
3908   map->total_size = section->size;
3909
3910   metadata = (offset_type *) (addr + sizeof (offset_type));
3911
3912   i = 0;
3913   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3914   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3915                        / 8);
3916   ++i;
3917
3918   *types_list = addr + MAYBE_SWAP (metadata[i]);
3919   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3920                            - MAYBE_SWAP (metadata[i]))
3921                           / 8);
3922   ++i;
3923
3924   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3925   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3926   map->address_table
3927     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3928   ++i;
3929
3930   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3931   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3932   map->symbol_table
3933     = gdb::array_view<mapped_index::symbol_table_slot>
3934        ((mapped_index::symbol_table_slot *) symbol_table,
3935         (mapped_index::symbol_table_slot *) symbol_table_end);
3936
3937   ++i;
3938   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3939
3940   return 1;
3941 }
3942
3943 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3944    elements of all the CUs and return 1.  Otherwise, return 0.  */
3945
3946 static int
3947 dwarf2_read_index (struct objfile *objfile)
3948 {
3949   struct mapped_index local_map, *map;
3950   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3951   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3952   struct dwz_file *dwz;
3953   struct dwarf2_per_objfile *dwarf2_per_objfile
3954     = get_dwarf2_per_objfile (objfile);
3955
3956   if (!read_index_from_section (objfile, objfile_name (objfile),
3957                                 use_deprecated_index_sections,
3958                                 &dwarf2_per_objfile->gdb_index, &local_map,
3959                                 &cu_list, &cu_list_elements,
3960                                 &types_list, &types_list_elements))
3961     return 0;
3962
3963   /* Don't use the index if it's empty.  */
3964   if (local_map.symbol_table.empty ())
3965     return 0;
3966
3967   /* If there is a .dwz file, read it so we can get its CU list as
3968      well.  */
3969   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3970   if (dwz != NULL)
3971     {
3972       struct mapped_index dwz_map;
3973       const gdb_byte *dwz_types_ignore;
3974       offset_type dwz_types_elements_ignore;
3975
3976       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3977                                     1,
3978                                     &dwz->gdb_index, &dwz_map,
3979                                     &dwz_list, &dwz_list_elements,
3980                                     &dwz_types_ignore,
3981                                     &dwz_types_elements_ignore))
3982         {
3983           warning (_("could not read '.gdb_index' section from %s; skipping"),
3984                    bfd_get_filename (dwz->dwz_bfd));
3985           return 0;
3986         }
3987     }
3988
3989   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3990                          dwz_list_elements);
3991
3992   if (types_list_elements)
3993     {
3994       struct dwarf2_section_info *section;
3995
3996       /* We can only handle a single .debug_types when we have an
3997          index.  */
3998       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3999         return 0;
4000
4001       section = VEC_index (dwarf2_section_info_def,
4002                            dwarf2_per_objfile->types, 0);
4003
4004       create_signatured_type_table_from_index (objfile, section, types_list,
4005                                                types_list_elements);
4006     }
4007
4008   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
4009
4010   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
4011   map = new (map) mapped_index ();
4012   *map = local_map;
4013
4014   dwarf2_per_objfile->index_table = map;
4015   dwarf2_per_objfile->using_index = 1;
4016   dwarf2_per_objfile->quick_file_names_table =
4017     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4018
4019   return 1;
4020 }
4021
4022 /* die_reader_func for dw2_get_file_names.  */
4023
4024 static void
4025 dw2_get_file_names_reader (const struct die_reader_specs *reader,
4026                            const gdb_byte *info_ptr,
4027                            struct die_info *comp_unit_die,
4028                            int has_children,
4029                            void *data)
4030 {
4031   struct dwarf2_cu *cu = reader->cu;
4032   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
4033   struct dwarf2_per_objfile *dwarf2_per_objfile
4034     = cu->per_cu->dwarf2_per_objfile;
4035   struct objfile *objfile = dwarf2_per_objfile->objfile;
4036   struct dwarf2_per_cu_data *lh_cu;
4037   struct attribute *attr;
4038   int i;
4039   void **slot;
4040   struct quick_file_names *qfn;
4041
4042   gdb_assert (! this_cu->is_debug_types);
4043
4044   /* Our callers never want to match partial units -- instead they
4045      will match the enclosing full CU.  */
4046   if (comp_unit_die->tag == DW_TAG_partial_unit)
4047     {
4048       this_cu->v.quick->no_file_data = 1;
4049       return;
4050     }
4051
4052   lh_cu = this_cu;
4053   slot = NULL;
4054
4055   line_header_up lh;
4056   sect_offset line_offset {};
4057
4058   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4059   if (attr)
4060     {
4061       struct quick_file_names find_entry;
4062
4063       line_offset = (sect_offset) DW_UNSND (attr);
4064
4065       /* We may have already read in this line header (TU line header sharing).
4066          If we have we're done.  */
4067       find_entry.hash.dwo_unit = cu->dwo_unit;
4068       find_entry.hash.line_sect_off = line_offset;
4069       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
4070                              &find_entry, INSERT);
4071       if (*slot != NULL)
4072         {
4073           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
4074           return;
4075         }
4076
4077       lh = dwarf_decode_line_header (line_offset, cu);
4078     }
4079   if (lh == NULL)
4080     {
4081       lh_cu->v.quick->no_file_data = 1;
4082       return;
4083     }
4084
4085   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
4086   qfn->hash.dwo_unit = cu->dwo_unit;
4087   qfn->hash.line_sect_off = line_offset;
4088   gdb_assert (slot != NULL);
4089   *slot = qfn;
4090
4091   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
4092
4093   qfn->num_file_names = lh->file_names.size ();
4094   qfn->file_names =
4095     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
4096   for (i = 0; i < lh->file_names.size (); ++i)
4097     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
4098   qfn->real_names = NULL;
4099
4100   lh_cu->v.quick->file_names = qfn;
4101 }
4102
4103 /* A helper for the "quick" functions which attempts to read the line
4104    table for THIS_CU.  */
4105
4106 static struct quick_file_names *
4107 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4108 {
4109   /* This should never be called for TUs.  */
4110   gdb_assert (! this_cu->is_debug_types);
4111   /* Nor type unit groups.  */
4112   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4113
4114   if (this_cu->v.quick->file_names != NULL)
4115     return this_cu->v.quick->file_names;
4116   /* If we know there is no line data, no point in looking again.  */
4117   if (this_cu->v.quick->no_file_data)
4118     return NULL;
4119
4120   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4121
4122   if (this_cu->v.quick->no_file_data)
4123     return NULL;
4124   return this_cu->v.quick->file_names;
4125 }
4126
4127 /* A helper for the "quick" functions which computes and caches the
4128    real path for a given file name from the line table.  */
4129
4130 static const char *
4131 dw2_get_real_path (struct objfile *objfile,
4132                    struct quick_file_names *qfn, int index)
4133 {
4134   if (qfn->real_names == NULL)
4135     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4136                                       qfn->num_file_names, const char *);
4137
4138   if (qfn->real_names[index] == NULL)
4139     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4140
4141   return qfn->real_names[index];
4142 }
4143
4144 static struct symtab *
4145 dw2_find_last_source_symtab (struct objfile *objfile)
4146 {
4147   struct dwarf2_per_objfile *dwarf2_per_objfile
4148     = get_dwarf2_per_objfile (objfile);
4149   int index = dwarf2_per_objfile->n_comp_units - 1;
4150   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4151   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4152
4153   if (cust == NULL)
4154     return NULL;
4155
4156   return compunit_primary_filetab (cust);
4157 }
4158
4159 /* Traversal function for dw2_forget_cached_source_info.  */
4160
4161 static int
4162 dw2_free_cached_file_names (void **slot, void *info)
4163 {
4164   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4165
4166   if (file_data->real_names)
4167     {
4168       int i;
4169
4170       for (i = 0; i < file_data->num_file_names; ++i)
4171         {
4172           xfree ((void*) file_data->real_names[i]);
4173           file_data->real_names[i] = NULL;
4174         }
4175     }
4176
4177   return 1;
4178 }
4179
4180 static void
4181 dw2_forget_cached_source_info (struct objfile *objfile)
4182 {
4183   struct dwarf2_per_objfile *dwarf2_per_objfile
4184     = get_dwarf2_per_objfile (objfile);
4185
4186   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4187                           dw2_free_cached_file_names, NULL);
4188 }
4189
4190 /* Helper function for dw2_map_symtabs_matching_filename that expands
4191    the symtabs and calls the iterator.  */
4192
4193 static int
4194 dw2_map_expand_apply (struct objfile *objfile,
4195                       struct dwarf2_per_cu_data *per_cu,
4196                       const char *name, const char *real_path,
4197                       gdb::function_view<bool (symtab *)> callback)
4198 {
4199   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4200
4201   /* Don't visit already-expanded CUs.  */
4202   if (per_cu->v.quick->compunit_symtab)
4203     return 0;
4204
4205   /* This may expand more than one symtab, and we want to iterate over
4206      all of them.  */
4207   dw2_instantiate_symtab (per_cu);
4208
4209   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4210                                     last_made, callback);
4211 }
4212
4213 /* Implementation of the map_symtabs_matching_filename method.  */
4214
4215 static bool
4216 dw2_map_symtabs_matching_filename
4217   (struct objfile *objfile, const char *name, const char *real_path,
4218    gdb::function_view<bool (symtab *)> callback)
4219 {
4220   int i;
4221   const char *name_basename = lbasename (name);
4222   struct dwarf2_per_objfile *dwarf2_per_objfile
4223     = get_dwarf2_per_objfile (objfile);
4224
4225   /* The rule is CUs specify all the files, including those used by
4226      any TU, so there's no need to scan TUs here.  */
4227
4228   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4229     {
4230       int j;
4231       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4232       struct quick_file_names *file_data;
4233
4234       /* We only need to look at symtabs not already expanded.  */
4235       if (per_cu->v.quick->compunit_symtab)
4236         continue;
4237
4238       file_data = dw2_get_file_names (per_cu);
4239       if (file_data == NULL)
4240         continue;
4241
4242       for (j = 0; j < file_data->num_file_names; ++j)
4243         {
4244           const char *this_name = file_data->file_names[j];
4245           const char *this_real_name;
4246
4247           if (compare_filenames_for_search (this_name, name))
4248             {
4249               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4250                                         callback))
4251                 return true;
4252               continue;
4253             }
4254
4255           /* Before we invoke realpath, which can get expensive when many
4256              files are involved, do a quick comparison of the basenames.  */
4257           if (! basenames_may_differ
4258               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4259             continue;
4260
4261           this_real_name = dw2_get_real_path (objfile, file_data, j);
4262           if (compare_filenames_for_search (this_real_name, name))
4263             {
4264               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4265                                         callback))
4266                 return true;
4267               continue;
4268             }
4269
4270           if (real_path != NULL)
4271             {
4272               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4273               gdb_assert (IS_ABSOLUTE_PATH (name));
4274               if (this_real_name != NULL
4275                   && FILENAME_CMP (real_path, this_real_name) == 0)
4276                 {
4277                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4278                                             callback))
4279                     return true;
4280                   continue;
4281                 }
4282             }
4283         }
4284     }
4285
4286   return false;
4287 }
4288
4289 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4290
4291 struct dw2_symtab_iterator
4292 {
4293   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4294   struct dwarf2_per_objfile *dwarf2_per_objfile;
4295   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4296   int want_specific_block;
4297   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4298      Unused if !WANT_SPECIFIC_BLOCK.  */
4299   int block_index;
4300   /* The kind of symbol we're looking for.  */
4301   domain_enum domain;
4302   /* The list of CUs from the index entry of the symbol,
4303      or NULL if not found.  */
4304   offset_type *vec;
4305   /* The next element in VEC to look at.  */
4306   int next;
4307   /* The number of elements in VEC, or zero if there is no match.  */
4308   int length;
4309   /* Have we seen a global version of the symbol?
4310      If so we can ignore all further global instances.
4311      This is to work around gold/15646, inefficient gold-generated
4312      indices.  */
4313   int global_seen;
4314 };
4315
4316 /* Initialize the index symtab iterator ITER.
4317    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4318    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4319
4320 static void
4321 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4322                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4323                       int want_specific_block,
4324                       int block_index,
4325                       domain_enum domain,
4326                       const char *name)
4327 {
4328   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4329   iter->want_specific_block = want_specific_block;
4330   iter->block_index = block_index;
4331   iter->domain = domain;
4332   iter->next = 0;
4333   iter->global_seen = 0;
4334
4335   mapped_index *index = dwarf2_per_objfile->index_table;
4336
4337   /* index is NULL if OBJF_READNOW.  */
4338   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4339     iter->length = MAYBE_SWAP (*iter->vec);
4340   else
4341     {
4342       iter->vec = NULL;
4343       iter->length = 0;
4344     }
4345 }
4346
4347 /* Return the next matching CU or NULL if there are no more.  */
4348
4349 static struct dwarf2_per_cu_data *
4350 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4351 {
4352   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4353
4354   for ( ; iter->next < iter->length; ++iter->next)
4355     {
4356       offset_type cu_index_and_attrs =
4357         MAYBE_SWAP (iter->vec[iter->next + 1]);
4358       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4359       struct dwarf2_per_cu_data *per_cu;
4360       int want_static = iter->block_index != GLOBAL_BLOCK;
4361       /* This value is only valid for index versions >= 7.  */
4362       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4363       gdb_index_symbol_kind symbol_kind =
4364         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4365       /* Only check the symbol attributes if they're present.
4366          Indices prior to version 7 don't record them,
4367          and indices >= 7 may elide them for certain symbols
4368          (gold does this).  */
4369       int attrs_valid =
4370         (dwarf2_per_objfile->index_table->version >= 7
4371          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4372
4373       /* Don't crash on bad data.  */
4374       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4375                        + dwarf2_per_objfile->n_type_units))
4376         {
4377           complaint (&symfile_complaints,
4378                      _(".gdb_index entry has bad CU index"
4379                        " [in module %s]"),
4380                      objfile_name (dwarf2_per_objfile->objfile));
4381           continue;
4382         }
4383
4384       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4385
4386       /* Skip if already read in.  */
4387       if (per_cu->v.quick->compunit_symtab)
4388         continue;
4389
4390       /* Check static vs global.  */
4391       if (attrs_valid)
4392         {
4393           if (iter->want_specific_block
4394               && want_static != is_static)
4395             continue;
4396           /* Work around gold/15646.  */
4397           if (!is_static && iter->global_seen)
4398             continue;
4399           if (!is_static)
4400             iter->global_seen = 1;
4401         }
4402
4403       /* Only check the symbol's kind if it has one.  */
4404       if (attrs_valid)
4405         {
4406           switch (iter->domain)
4407             {
4408             case VAR_DOMAIN:
4409               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4410                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4411                   /* Some types are also in VAR_DOMAIN.  */
4412                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4413                 continue;
4414               break;
4415             case STRUCT_DOMAIN:
4416               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4417                 continue;
4418               break;
4419             case LABEL_DOMAIN:
4420               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4421                 continue;
4422               break;
4423             default:
4424               break;
4425             }
4426         }
4427
4428       ++iter->next;
4429       return per_cu;
4430     }
4431
4432   return NULL;
4433 }
4434
4435 static struct compunit_symtab *
4436 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4437                    const char *name, domain_enum domain)
4438 {
4439   struct compunit_symtab *stab_best = NULL;
4440   struct dwarf2_per_objfile *dwarf2_per_objfile
4441     = get_dwarf2_per_objfile (objfile);
4442
4443   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4444
4445   struct dw2_symtab_iterator iter;
4446   struct dwarf2_per_cu_data *per_cu;
4447
4448   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4449
4450   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4451     {
4452       struct symbol *sym, *with_opaque = NULL;
4453       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4454       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4455       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4456
4457       sym = block_find_symbol (block, name, domain,
4458                                block_find_non_opaque_type_preferred,
4459                                &with_opaque);
4460
4461       /* Some caution must be observed with overloaded functions
4462          and methods, since the index will not contain any overload
4463          information (but NAME might contain it).  */
4464
4465       if (sym != NULL
4466           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4467         return stab;
4468       if (with_opaque != NULL
4469           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4470         stab_best = stab;
4471
4472       /* Keep looking through other CUs.  */
4473     }
4474
4475   return stab_best;
4476 }
4477
4478 static void
4479 dw2_print_stats (struct objfile *objfile)
4480 {
4481   struct dwarf2_per_objfile *dwarf2_per_objfile
4482     = get_dwarf2_per_objfile (objfile);
4483   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4484   int count = 0;
4485
4486   for (int i = 0; i < total; ++i)
4487     {
4488       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4489
4490       if (!per_cu->v.quick->compunit_symtab)
4491         ++count;
4492     }
4493   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4494   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4495 }
4496
4497 /* This dumps minimal information about the index.
4498    It is called via "mt print objfiles".
4499    One use is to verify .gdb_index has been loaded by the
4500    gdb.dwarf2/gdb-index.exp testcase.  */
4501
4502 static void
4503 dw2_dump (struct objfile *objfile)
4504 {
4505   struct dwarf2_per_objfile *dwarf2_per_objfile
4506     = get_dwarf2_per_objfile (objfile);
4507
4508   gdb_assert (dwarf2_per_objfile->using_index);
4509   printf_filtered (".gdb_index:");
4510   if (dwarf2_per_objfile->index_table != NULL)
4511     {
4512       printf_filtered (" version %d\n",
4513                        dwarf2_per_objfile->index_table->version);
4514     }
4515   else
4516     printf_filtered (" faked for \"readnow\"\n");
4517   printf_filtered ("\n");
4518 }
4519
4520 static void
4521 dw2_relocate (struct objfile *objfile,
4522               const struct section_offsets *new_offsets,
4523               const struct section_offsets *delta)
4524 {
4525   /* There's nothing to relocate here.  */
4526 }
4527
4528 static void
4529 dw2_expand_symtabs_for_function (struct objfile *objfile,
4530                                  const char *func_name)
4531 {
4532   struct dwarf2_per_objfile *dwarf2_per_objfile
4533     = get_dwarf2_per_objfile (objfile);
4534
4535   struct dw2_symtab_iterator iter;
4536   struct dwarf2_per_cu_data *per_cu;
4537
4538   /* Note: It doesn't matter what we pass for block_index here.  */
4539   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4540                         func_name);
4541
4542   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4543     dw2_instantiate_symtab (per_cu);
4544
4545 }
4546
4547 static void
4548 dw2_expand_all_symtabs (struct objfile *objfile)
4549 {
4550   struct dwarf2_per_objfile *dwarf2_per_objfile
4551     = get_dwarf2_per_objfile (objfile);
4552   int total_units = (dwarf2_per_objfile->n_comp_units
4553                      + dwarf2_per_objfile->n_type_units);
4554
4555   for (int i = 0; i < total_units; ++i)
4556     {
4557       struct dwarf2_per_cu_data *per_cu
4558         = dw2_get_cutu (dwarf2_per_objfile, i);
4559
4560       dw2_instantiate_symtab (per_cu);
4561     }
4562 }
4563
4564 static void
4565 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4566                                   const char *fullname)
4567 {
4568   struct dwarf2_per_objfile *dwarf2_per_objfile
4569     = get_dwarf2_per_objfile (objfile);
4570
4571   /* We don't need to consider type units here.
4572      This is only called for examining code, e.g. expand_line_sal.
4573      There can be an order of magnitude (or more) more type units
4574      than comp units, and we avoid them if we can.  */
4575
4576   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4577     {
4578       int j;
4579       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4580       struct quick_file_names *file_data;
4581
4582       /* We only need to look at symtabs not already expanded.  */
4583       if (per_cu->v.quick->compunit_symtab)
4584         continue;
4585
4586       file_data = dw2_get_file_names (per_cu);
4587       if (file_data == NULL)
4588         continue;
4589
4590       for (j = 0; j < file_data->num_file_names; ++j)
4591         {
4592           const char *this_fullname = file_data->file_names[j];
4593
4594           if (filename_cmp (this_fullname, fullname) == 0)
4595             {
4596               dw2_instantiate_symtab (per_cu);
4597               break;
4598             }
4599         }
4600     }
4601 }
4602
4603 static void
4604 dw2_map_matching_symbols (struct objfile *objfile,
4605                           const char * name, domain_enum domain,
4606                           int global,
4607                           int (*callback) (struct block *,
4608                                            struct symbol *, void *),
4609                           void *data, symbol_name_match_type match,
4610                           symbol_compare_ftype *ordered_compare)
4611 {
4612   /* Currently unimplemented; used for Ada.  The function can be called if the
4613      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4614      does not look for non-Ada symbols this function should just return.  */
4615 }
4616
4617 /* Symbol name matcher for .gdb_index names.
4618
4619    Symbol names in .gdb_index have a few particularities:
4620
4621    - There's no indication of which is the language of each symbol.
4622
4623      Since each language has its own symbol name matching algorithm,
4624      and we don't know which language is the right one, we must match
4625      each symbol against all languages.  This would be a potential
4626      performance problem if it were not mitigated by the
4627      mapped_index::name_components lookup table, which significantly
4628      reduces the number of times we need to call into this matcher,
4629      making it a non-issue.
4630
4631    - Symbol names in the index have no overload (parameter)
4632      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4633      appear as "foo" in the index, for example.
4634
4635      This means that the lookup names passed to the symbol name
4636      matcher functions must have no parameter information either
4637      because (e.g.) symbol search name "foo" does not match
4638      lookup-name "foo(int)" [while swapping search name for lookup
4639      name would match].
4640 */
4641 class gdb_index_symbol_name_matcher
4642 {
4643 public:
4644   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4645   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4646
4647   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4648      Returns true if any matcher matches.  */
4649   bool matches (const char *symbol_name);
4650
4651 private:
4652   /* A reference to the lookup name we're matching against.  */
4653   const lookup_name_info &m_lookup_name;
4654
4655   /* A vector holding all the different symbol name matchers, for all
4656      languages.  */
4657   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4658 };
4659
4660 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4661   (const lookup_name_info &lookup_name)
4662     : m_lookup_name (lookup_name)
4663 {
4664   /* Prepare the vector of comparison functions upfront, to avoid
4665      doing the same work for each symbol.  Care is taken to avoid
4666      matching with the same matcher more than once if/when multiple
4667      languages use the same matcher function.  */
4668   auto &matchers = m_symbol_name_matcher_funcs;
4669   matchers.reserve (nr_languages);
4670
4671   matchers.push_back (default_symbol_name_matcher);
4672
4673   for (int i = 0; i < nr_languages; i++)
4674     {
4675       const language_defn *lang = language_def ((enum language) i);
4676       symbol_name_matcher_ftype *name_matcher
4677         = get_symbol_name_matcher (lang, m_lookup_name);
4678
4679       /* Don't insert the same comparison routine more than once.
4680          Note that we do this linear walk instead of a seemingly
4681          cheaper sorted insert, or use a std::set or something like
4682          that, because relative order of function addresses is not
4683          stable.  This is not a problem in practice because the number
4684          of supported languages is low, and the cost here is tiny
4685          compared to the number of searches we'll do afterwards using
4686          this object.  */
4687       if (name_matcher != default_symbol_name_matcher
4688           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4689               == matchers.end ()))
4690         matchers.push_back (name_matcher);
4691     }
4692 }
4693
4694 bool
4695 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4696 {
4697   for (auto matches_name : m_symbol_name_matcher_funcs)
4698     if (matches_name (symbol_name, m_lookup_name, NULL))
4699       return true;
4700
4701   return false;
4702 }
4703
4704 /* Starting from a search name, return the string that finds the upper
4705    bound of all strings that start with SEARCH_NAME in a sorted name
4706    list.  Returns the empty string to indicate that the upper bound is
4707    the end of the list.  */
4708
4709 static std::string
4710 make_sort_after_prefix_name (const char *search_name)
4711 {
4712   /* When looking to complete "func", we find the upper bound of all
4713      symbols that start with "func" by looking for where we'd insert
4714      the closest string that would follow "func" in lexicographical
4715      order.  Usually, that's "func"-with-last-character-incremented,
4716      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4717      will be UTF-8 multi-byte sequences, but we can't be certain.
4718      Especially mind the 0xff character, which is a valid character in
4719      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4720      rule out compilers allowing it in identifiers.  Note that
4721      conveniently, strcmp/strcasecmp are specified to compare
4722      characters interpreted as unsigned char.  So what we do is treat
4723      the whole string as a base 256 number composed of a sequence of
4724      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4725      to 0, and carries 1 to the following more-significant position.
4726      If the very first character in SEARCH_NAME ends up incremented
4727      and carries/overflows, then the upper bound is the end of the
4728      list.  The string after the empty string is also the empty
4729      string.
4730
4731      Some examples of this operation:
4732
4733        SEARCH_NAME  => "+1" RESULT
4734
4735        "abc"              => "abd"
4736        "ab\xff"           => "ac"
4737        "\xff" "a" "\xff"  => "\xff" "b"
4738        "\xff"             => ""
4739        "\xff\xff"         => ""
4740        ""                 => ""
4741
4742      Then, with these symbols for example:
4743
4744       func
4745       func1
4746       fund
4747
4748      completing "func" looks for symbols between "func" and
4749      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4750      which finds "func" and "func1", but not "fund".
4751
4752      And with:
4753
4754       funcÿ     (Latin1 'ÿ' [0xff])
4755       funcÿ1
4756       fund
4757
4758      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4759      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4760
4761      And with:
4762
4763       ÿÿ        (Latin1 'ÿ' [0xff])
4764       ÿÿ1
4765
4766      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4767      the end of the list.
4768   */
4769   std::string after = search_name;
4770   while (!after.empty () && (unsigned char) after.back () == 0xff)
4771     after.pop_back ();
4772   if (!after.empty ())
4773     after.back () = (unsigned char) after.back () + 1;
4774   return after;
4775 }
4776
4777 /* See declaration.  */
4778
4779 std::pair<std::vector<name_component>::const_iterator,
4780           std::vector<name_component>::const_iterator>
4781 mapped_index_base::find_name_components_bounds
4782   (const lookup_name_info &lookup_name_without_params) const
4783 {
4784   auto *name_cmp
4785     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4786
4787   const char *cplus
4788     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4789
4790   /* Comparison function object for lower_bound that matches against a
4791      given symbol name.  */
4792   auto lookup_compare_lower = [&] (const name_component &elem,
4793                                    const char *name)
4794     {
4795       const char *elem_qualified = this->symbol_name_at (elem.idx);
4796       const char *elem_name = elem_qualified + elem.name_offset;
4797       return name_cmp (elem_name, name) < 0;
4798     };
4799
4800   /* Comparison function object for upper_bound that matches against a
4801      given symbol name.  */
4802   auto lookup_compare_upper = [&] (const char *name,
4803                                    const name_component &elem)
4804     {
4805       const char *elem_qualified = this->symbol_name_at (elem.idx);
4806       const char *elem_name = elem_qualified + elem.name_offset;
4807       return name_cmp (name, elem_name) < 0;
4808     };
4809
4810   auto begin = this->name_components.begin ();
4811   auto end = this->name_components.end ();
4812
4813   /* Find the lower bound.  */
4814   auto lower = [&] ()
4815     {
4816       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4817         return begin;
4818       else
4819         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4820     } ();
4821
4822   /* Find the upper bound.  */
4823   auto upper = [&] ()
4824     {
4825       if (lookup_name_without_params.completion_mode ())
4826         {
4827           /* In completion mode, we want UPPER to point past all
4828              symbols names that have the same prefix.  I.e., with
4829              these symbols, and completing "func":
4830
4831               function        << lower bound
4832               function1
4833               other_function  << upper bound
4834
4835              We find the upper bound by looking for the insertion
4836              point of "func"-with-last-character-incremented,
4837              i.e. "fund".  */
4838           std::string after = make_sort_after_prefix_name (cplus);
4839           if (after.empty ())
4840             return end;
4841           return std::lower_bound (lower, end, after.c_str (),
4842                                    lookup_compare_lower);
4843         }
4844       else
4845         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4846     } ();
4847
4848   return {lower, upper};
4849 }
4850
4851 /* See declaration.  */
4852
4853 void
4854 mapped_index_base::build_name_components ()
4855 {
4856   if (!this->name_components.empty ())
4857     return;
4858
4859   this->name_components_casing = case_sensitivity;
4860   auto *name_cmp
4861     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4862
4863   /* The code below only knows how to break apart components of C++
4864      symbol names (and other languages that use '::' as
4865      namespace/module separator).  If we add support for wild matching
4866      to some language that uses some other operator (E.g., Ada, Go and
4867      D use '.'), then we'll need to try splitting the symbol name
4868      according to that language too.  Note that Ada does support wild
4869      matching, but doesn't currently support .gdb_index.  */
4870   auto count = this->symbol_name_count ();
4871   for (offset_type idx = 0; idx < count; idx++)
4872     {
4873       if (this->symbol_name_slot_invalid (idx))
4874         continue;
4875
4876       const char *name = this->symbol_name_at (idx);
4877
4878       /* Add each name component to the name component table.  */
4879       unsigned int previous_len = 0;
4880       for (unsigned int current_len = cp_find_first_component (name);
4881            name[current_len] != '\0';
4882            current_len += cp_find_first_component (name + current_len))
4883         {
4884           gdb_assert (name[current_len] == ':');
4885           this->name_components.push_back ({previous_len, idx});
4886           /* Skip the '::'.  */
4887           current_len += 2;
4888           previous_len = current_len;
4889         }
4890       this->name_components.push_back ({previous_len, idx});
4891     }
4892
4893   /* Sort name_components elements by name.  */
4894   auto name_comp_compare = [&] (const name_component &left,
4895                                 const name_component &right)
4896     {
4897       const char *left_qualified = this->symbol_name_at (left.idx);
4898       const char *right_qualified = this->symbol_name_at (right.idx);
4899
4900       const char *left_name = left_qualified + left.name_offset;
4901       const char *right_name = right_qualified + right.name_offset;
4902
4903       return name_cmp (left_name, right_name) < 0;
4904     };
4905
4906   std::sort (this->name_components.begin (),
4907              this->name_components.end (),
4908              name_comp_compare);
4909 }
4910
4911 /* Helper for dw2_expand_symtabs_matching that works with a
4912    mapped_index_base instead of the containing objfile.  This is split
4913    to a separate function in order to be able to unit test the
4914    name_components matching using a mock mapped_index_base.  For each
4915    symbol name that matches, calls MATCH_CALLBACK, passing it the
4916    symbol's index in the mapped_index_base symbol table.  */
4917
4918 static void
4919 dw2_expand_symtabs_matching_symbol
4920   (mapped_index_base &index,
4921    const lookup_name_info &lookup_name_in,
4922    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4923    enum search_domain kind,
4924    gdb::function_view<void (offset_type)> match_callback)
4925 {
4926   lookup_name_info lookup_name_without_params
4927     = lookup_name_in.make_ignore_params ();
4928   gdb_index_symbol_name_matcher lookup_name_matcher
4929     (lookup_name_without_params);
4930
4931   /* Build the symbol name component sorted vector, if we haven't
4932      yet.  */
4933   index.build_name_components ();
4934
4935   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4936
4937   /* Now for each symbol name in range, check to see if we have a name
4938      match, and if so, call the MATCH_CALLBACK callback.  */
4939
4940   /* The same symbol may appear more than once in the range though.
4941      E.g., if we're looking for symbols that complete "w", and we have
4942      a symbol named "w1::w2", we'll find the two name components for
4943      that same symbol in the range.  To be sure we only call the
4944      callback once per symbol, we first collect the symbol name
4945      indexes that matched in a temporary vector and ignore
4946      duplicates.  */
4947   std::vector<offset_type> matches;
4948   matches.reserve (std::distance (bounds.first, bounds.second));
4949
4950   for (; bounds.first != bounds.second; ++bounds.first)
4951     {
4952       const char *qualified = index.symbol_name_at (bounds.first->idx);
4953
4954       if (!lookup_name_matcher.matches (qualified)
4955           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4956         continue;
4957
4958       matches.push_back (bounds.first->idx);
4959     }
4960
4961   std::sort (matches.begin (), matches.end ());
4962
4963   /* Finally call the callback, once per match.  */
4964   ULONGEST prev = -1;
4965   for (offset_type idx : matches)
4966     {
4967       if (prev != idx)
4968         {
4969           match_callback (idx);
4970           prev = idx;
4971         }
4972     }
4973
4974   /* Above we use a type wider than idx's for 'prev', since 0 and
4975      (offset_type)-1 are both possible values.  */
4976   static_assert (sizeof (prev) > sizeof (offset_type), "");
4977 }
4978
4979 #if GDB_SELF_TEST
4980
4981 namespace selftests { namespace dw2_expand_symtabs_matching {
4982
4983 /* A mock .gdb_index/.debug_names-like name index table, enough to
4984    exercise dw2_expand_symtabs_matching_symbol, which works with the
4985    mapped_index_base interface.  Builds an index from the symbol list
4986    passed as parameter to the constructor.  */
4987 class mock_mapped_index : public mapped_index_base
4988 {
4989 public:
4990   mock_mapped_index (gdb::array_view<const char *> symbols)
4991     : m_symbol_table (symbols)
4992   {}
4993
4994   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4995
4996   /* Return the number of names in the symbol table.  */
4997   virtual size_t symbol_name_count () const
4998   {
4999     return m_symbol_table.size ();
5000   }
5001
5002   /* Get the name of the symbol at IDX in the symbol table.  */
5003   virtual const char *symbol_name_at (offset_type idx) const
5004   {
5005     return m_symbol_table[idx];
5006   }
5007
5008 private:
5009   gdb::array_view<const char *> m_symbol_table;
5010 };
5011
5012 /* Convenience function that converts a NULL pointer to a "<null>"
5013    string, to pass to print routines.  */
5014
5015 static const char *
5016 string_or_null (const char *str)
5017 {
5018   return str != NULL ? str : "<null>";
5019 }
5020
5021 /* Check if a lookup_name_info built from
5022    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
5023    index.  EXPECTED_LIST is the list of expected matches, in expected
5024    matching order.  If no match expected, then an empty list is
5025    specified.  Returns true on success.  On failure prints a warning
5026    indicating the file:line that failed, and returns false.  */
5027
5028 static bool
5029 check_match (const char *file, int line,
5030              mock_mapped_index &mock_index,
5031              const char *name, symbol_name_match_type match_type,
5032              bool completion_mode,
5033              std::initializer_list<const char *> expected_list)
5034 {
5035   lookup_name_info lookup_name (name, match_type, completion_mode);
5036
5037   bool matched = true;
5038
5039   auto mismatch = [&] (const char *expected_str,
5040                        const char *got)
5041   {
5042     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
5043                "expected=\"%s\", got=\"%s\"\n"),
5044              file, line,
5045              (match_type == symbol_name_match_type::FULL
5046               ? "FULL" : "WILD"),
5047              name, string_or_null (expected_str), string_or_null (got));
5048     matched = false;
5049   };
5050
5051   auto expected_it = expected_list.begin ();
5052   auto expected_end = expected_list.end ();
5053
5054   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
5055                                       NULL, ALL_DOMAIN,
5056                                       [&] (offset_type idx)
5057   {
5058     const char *matched_name = mock_index.symbol_name_at (idx);
5059     const char *expected_str
5060       = expected_it == expected_end ? NULL : *expected_it++;
5061
5062     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
5063       mismatch (expected_str, matched_name);
5064   });
5065
5066   const char *expected_str
5067   = expected_it == expected_end ? NULL : *expected_it++;
5068   if (expected_str != NULL)
5069     mismatch (expected_str, NULL);
5070
5071   return matched;
5072 }
5073
5074 /* The symbols added to the mock mapped_index for testing (in
5075    canonical form).  */
5076 static const char *test_symbols[] = {
5077   "function",
5078   "std::bar",
5079   "std::zfunction",
5080   "std::zfunction2",
5081   "w1::w2",
5082   "ns::foo<char*>",
5083   "ns::foo<int>",
5084   "ns::foo<long>",
5085   "ns2::tmpl<int>::foo2",
5086   "(anonymous namespace)::A::B::C",
5087
5088   /* These are used to check that the increment-last-char in the
5089      matching algorithm for completion doesn't match "t1_fund" when
5090      completing "t1_func".  */
5091   "t1_func",
5092   "t1_func1",
5093   "t1_fund",
5094   "t1_fund1",
5095
5096   /* A UTF-8 name with multi-byte sequences to make sure that
5097      cp-name-parser understands this as a single identifier ("função"
5098      is "function" in PT).  */
5099   u8"u8função",
5100
5101   /* \377 (0xff) is Latin1 'ÿ'.  */
5102   "yfunc\377",
5103
5104   /* \377 (0xff) is Latin1 'ÿ'.  */
5105   "\377",
5106   "\377\377123",
5107
5108   /* A name with all sorts of complications.  Starts with "z" to make
5109      it easier for the completion tests below.  */
5110 #define Z_SYM_NAME \
5111   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5112     "::tuple<(anonymous namespace)::ui*, " \
5113     "std::default_delete<(anonymous namespace)::ui>, void>"
5114
5115   Z_SYM_NAME
5116 };
5117
5118 /* Returns true if the mapped_index_base::find_name_component_bounds
5119    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5120    in completion mode.  */
5121
5122 static bool
5123 check_find_bounds_finds (mapped_index_base &index,
5124                          const char *search_name,
5125                          gdb::array_view<const char *> expected_syms)
5126 {
5127   lookup_name_info lookup_name (search_name,
5128                                 symbol_name_match_type::FULL, true);
5129
5130   auto bounds = index.find_name_components_bounds (lookup_name);
5131
5132   size_t distance = std::distance (bounds.first, bounds.second);
5133   if (distance != expected_syms.size ())
5134     return false;
5135
5136   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5137     {
5138       auto nc_elem = bounds.first + exp_elem;
5139       const char *qualified = index.symbol_name_at (nc_elem->idx);
5140       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5141         return false;
5142     }
5143
5144   return true;
5145 }
5146
5147 /* Test the lower-level mapped_index::find_name_component_bounds
5148    method.  */
5149
5150 static void
5151 test_mapped_index_find_name_component_bounds ()
5152 {
5153   mock_mapped_index mock_index (test_symbols);
5154
5155   mock_index.build_name_components ();
5156
5157   /* Test the lower-level mapped_index::find_name_component_bounds
5158      method in completion mode.  */
5159   {
5160     static const char *expected_syms[] = {
5161       "t1_func",
5162       "t1_func1",
5163     };
5164
5165     SELF_CHECK (check_find_bounds_finds (mock_index,
5166                                          "t1_func", expected_syms));
5167   }
5168
5169   /* Check that the increment-last-char in the name matching algorithm
5170      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5171   {
5172     static const char *expected_syms1[] = {
5173       "\377",
5174       "\377\377123",
5175     };
5176     SELF_CHECK (check_find_bounds_finds (mock_index,
5177                                          "\377", expected_syms1));
5178
5179     static const char *expected_syms2[] = {
5180       "\377\377123",
5181     };
5182     SELF_CHECK (check_find_bounds_finds (mock_index,
5183                                          "\377\377", expected_syms2));
5184   }
5185 }
5186
5187 /* Test dw2_expand_symtabs_matching_symbol.  */
5188
5189 static void
5190 test_dw2_expand_symtabs_matching_symbol ()
5191 {
5192   mock_mapped_index mock_index (test_symbols);
5193
5194   /* We let all tests run until the end even if some fails, for debug
5195      convenience.  */
5196   bool any_mismatch = false;
5197
5198   /* Create the expected symbols list (an initializer_list).  Needed
5199      because lists have commas, and we need to pass them to CHECK,
5200      which is a macro.  */
5201 #define EXPECT(...) { __VA_ARGS__ }
5202
5203   /* Wrapper for check_match that passes down the current
5204      __FILE__/__LINE__.  */
5205 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5206   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5207                                 mock_index,                             \
5208                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5209                                 EXPECTED_LIST)
5210
5211   /* Identity checks.  */
5212   for (const char *sym : test_symbols)
5213     {
5214       /* Should be able to match all existing symbols.  */
5215       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5216                    EXPECT (sym));
5217
5218       /* Should be able to match all existing symbols with
5219          parameters.  */
5220       std::string with_params = std::string (sym) + "(int)";
5221       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5222                    EXPECT (sym));
5223
5224       /* Should be able to match all existing symbols with
5225          parameters and qualifiers.  */
5226       with_params = std::string (sym) + " ( int ) const";
5227       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5228                    EXPECT (sym));
5229
5230       /* This should really find sym, but cp-name-parser.y doesn't
5231          know about lvalue/rvalue qualifiers yet.  */
5232       with_params = std::string (sym) + " ( int ) &&";
5233       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5234                    {});
5235     }
5236
5237   /* Check that the name matching algorithm for completion doesn't get
5238      confused with Latin1 'ÿ' / 0xff.  */
5239   {
5240     static const char str[] = "\377";
5241     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5242                  EXPECT ("\377", "\377\377123"));
5243   }
5244
5245   /* Check that the increment-last-char in the matching algorithm for
5246      completion doesn't match "t1_fund" when completing "t1_func".  */
5247   {
5248     static const char str[] = "t1_func";
5249     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5250                  EXPECT ("t1_func", "t1_func1"));
5251   }
5252
5253   /* Check that completion mode works at each prefix of the expected
5254      symbol name.  */
5255   {
5256     static const char str[] = "function(int)";
5257     size_t len = strlen (str);
5258     std::string lookup;
5259
5260     for (size_t i = 1; i < len; i++)
5261       {
5262         lookup.assign (str, i);
5263         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5264                      EXPECT ("function"));
5265       }
5266   }
5267
5268   /* While "w" is a prefix of both components, the match function
5269      should still only be called once.  */
5270   {
5271     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5272                  EXPECT ("w1::w2"));
5273     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5274                  EXPECT ("w1::w2"));
5275   }
5276
5277   /* Same, with a "complicated" symbol.  */
5278   {
5279     static const char str[] = Z_SYM_NAME;
5280     size_t len = strlen (str);
5281     std::string lookup;
5282
5283     for (size_t i = 1; i < len; i++)
5284       {
5285         lookup.assign (str, i);
5286         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5287                      EXPECT (Z_SYM_NAME));
5288       }
5289   }
5290
5291   /* In FULL mode, an incomplete symbol doesn't match.  */
5292   {
5293     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5294                  {});
5295   }
5296
5297   /* A complete symbol with parameters matches any overload, since the
5298      index has no overload info.  */
5299   {
5300     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5301                  EXPECT ("std::zfunction", "std::zfunction2"));
5302     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5303                  EXPECT ("std::zfunction", "std::zfunction2"));
5304     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5305                  EXPECT ("std::zfunction", "std::zfunction2"));
5306   }
5307
5308   /* Check that whitespace is ignored appropriately.  A symbol with a
5309      template argument list. */
5310   {
5311     static const char expected[] = "ns::foo<int>";
5312     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5313                  EXPECT (expected));
5314     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5315                  EXPECT (expected));
5316   }
5317
5318   /* Check that whitespace is ignored appropriately.  A symbol with a
5319      template argument list that includes a pointer.  */
5320   {
5321     static const char expected[] = "ns::foo<char*>";
5322     /* Try both completion and non-completion modes.  */
5323     static const bool completion_mode[2] = {false, true};
5324     for (size_t i = 0; i < 2; i++)
5325       {
5326         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5327                      completion_mode[i], EXPECT (expected));
5328         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5329                      completion_mode[i], EXPECT (expected));
5330
5331         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5332                      completion_mode[i], EXPECT (expected));
5333         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5334                      completion_mode[i], EXPECT (expected));
5335       }
5336   }
5337
5338   {
5339     /* Check method qualifiers are ignored.  */
5340     static const char expected[] = "ns::foo<char*>";
5341     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5342                  symbol_name_match_type::FULL, true, EXPECT (expected));
5343     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5344                  symbol_name_match_type::FULL, true, EXPECT (expected));
5345     CHECK_MATCH ("foo < char * >  ( int ) const",
5346                  symbol_name_match_type::WILD, true, EXPECT (expected));
5347     CHECK_MATCH ("foo < char * >  ( int ) &&",
5348                  symbol_name_match_type::WILD, true, EXPECT (expected));
5349   }
5350
5351   /* Test lookup names that don't match anything.  */
5352   {
5353     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5354                  {});
5355
5356     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5357                  {});
5358   }
5359
5360   /* Some wild matching tests, exercising "(anonymous namespace)",
5361      which should not be confused with a parameter list.  */
5362   {
5363     static const char *syms[] = {
5364       "A::B::C",
5365       "B::C",
5366       "C",
5367       "A :: B :: C ( int )",
5368       "B :: C ( int )",
5369       "C ( int )",
5370     };
5371
5372     for (const char *s : syms)
5373       {
5374         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5375                      EXPECT ("(anonymous namespace)::A::B::C"));
5376       }
5377   }
5378
5379   {
5380     static const char expected[] = "ns2::tmpl<int>::foo2";
5381     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5382                  EXPECT (expected));
5383     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5384                  EXPECT (expected));
5385   }
5386
5387   SELF_CHECK (!any_mismatch);
5388
5389 #undef EXPECT
5390 #undef CHECK_MATCH
5391 }
5392
5393 static void
5394 run_test ()
5395 {
5396   test_mapped_index_find_name_component_bounds ();
5397   test_dw2_expand_symtabs_matching_symbol ();
5398 }
5399
5400 }} // namespace selftests::dw2_expand_symtabs_matching
5401
5402 #endif /* GDB_SELF_TEST */
5403
5404 /* If FILE_MATCHER is NULL or if PER_CU has
5405    dwarf2_per_cu_quick_data::MARK set (see
5406    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5407    EXPANSION_NOTIFY on it.  */
5408
5409 static void
5410 dw2_expand_symtabs_matching_one
5411   (struct dwarf2_per_cu_data *per_cu,
5412    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5413    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5414 {
5415   if (file_matcher == NULL || per_cu->v.quick->mark)
5416     {
5417       bool symtab_was_null
5418         = (per_cu->v.quick->compunit_symtab == NULL);
5419
5420       dw2_instantiate_symtab (per_cu);
5421
5422       if (expansion_notify != NULL
5423           && symtab_was_null
5424           && per_cu->v.quick->compunit_symtab != NULL)
5425         expansion_notify (per_cu->v.quick->compunit_symtab);
5426     }
5427 }
5428
5429 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5430    matched, to expand corresponding CUs that were marked.  IDX is the
5431    index of the symbol name that matched.  */
5432
5433 static void
5434 dw2_expand_marked_cus
5435   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5436    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5437    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5438    search_domain kind)
5439 {
5440   offset_type *vec, vec_len, vec_idx;
5441   bool global_seen = false;
5442   mapped_index &index = *dwarf2_per_objfile->index_table;
5443
5444   vec = (offset_type *) (index.constant_pool
5445                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5446   vec_len = MAYBE_SWAP (vec[0]);
5447   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5448     {
5449       struct dwarf2_per_cu_data *per_cu;
5450       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5451       /* This value is only valid for index versions >= 7.  */
5452       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5453       gdb_index_symbol_kind symbol_kind =
5454         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5455       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5456       /* Only check the symbol attributes if they're present.
5457          Indices prior to version 7 don't record them,
5458          and indices >= 7 may elide them for certain symbols
5459          (gold does this).  */
5460       int attrs_valid =
5461         (index.version >= 7
5462          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5463
5464       /* Work around gold/15646.  */
5465       if (attrs_valid)
5466         {
5467           if (!is_static && global_seen)
5468             continue;
5469           if (!is_static)
5470             global_seen = true;
5471         }
5472
5473       /* Only check the symbol's kind if it has one.  */
5474       if (attrs_valid)
5475         {
5476           switch (kind)
5477             {
5478             case VARIABLES_DOMAIN:
5479               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5480                 continue;
5481               break;
5482             case FUNCTIONS_DOMAIN:
5483               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5484                 continue;
5485               break;
5486             case TYPES_DOMAIN:
5487               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5488                 continue;
5489               break;
5490             default:
5491               break;
5492             }
5493         }
5494
5495       /* Don't crash on bad data.  */
5496       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5497                        + dwarf2_per_objfile->n_type_units))
5498         {
5499           complaint (&symfile_complaints,
5500                      _(".gdb_index entry has bad CU index"
5501                        " [in module %s]"),
5502                        objfile_name (dwarf2_per_objfile->objfile));
5503           continue;
5504         }
5505
5506       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5507       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5508                                        expansion_notify);
5509     }
5510 }
5511
5512 /* If FILE_MATCHER is non-NULL, set all the
5513    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5514    that match FILE_MATCHER.  */
5515
5516 static void
5517 dw_expand_symtabs_matching_file_matcher
5518   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5519    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5520 {
5521   if (file_matcher == NULL)
5522     return;
5523
5524   objfile *const objfile = dwarf2_per_objfile->objfile;
5525
5526   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5527                                             htab_eq_pointer,
5528                                             NULL, xcalloc, xfree));
5529   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5530                                                 htab_eq_pointer,
5531                                                 NULL, xcalloc, xfree));
5532
5533   /* The rule is CUs specify all the files, including those used by
5534      any TU, so there's no need to scan TUs here.  */
5535
5536   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5537     {
5538       int j;
5539       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5540       struct quick_file_names *file_data;
5541       void **slot;
5542
5543       QUIT;
5544
5545       per_cu->v.quick->mark = 0;
5546
5547       /* We only need to look at symtabs not already expanded.  */
5548       if (per_cu->v.quick->compunit_symtab)
5549         continue;
5550
5551       file_data = dw2_get_file_names (per_cu);
5552       if (file_data == NULL)
5553         continue;
5554
5555       if (htab_find (visited_not_found.get (), file_data) != NULL)
5556         continue;
5557       else if (htab_find (visited_found.get (), file_data) != NULL)
5558         {
5559           per_cu->v.quick->mark = 1;
5560           continue;
5561         }
5562
5563       for (j = 0; j < file_data->num_file_names; ++j)
5564         {
5565           const char *this_real_name;
5566
5567           if (file_matcher (file_data->file_names[j], false))
5568             {
5569               per_cu->v.quick->mark = 1;
5570               break;
5571             }
5572
5573           /* Before we invoke realpath, which can get expensive when many
5574              files are involved, do a quick comparison of the basenames.  */
5575           if (!basenames_may_differ
5576               && !file_matcher (lbasename (file_data->file_names[j]),
5577                                 true))
5578             continue;
5579
5580           this_real_name = dw2_get_real_path (objfile, file_data, j);
5581           if (file_matcher (this_real_name, false))
5582             {
5583               per_cu->v.quick->mark = 1;
5584               break;
5585             }
5586         }
5587
5588       slot = htab_find_slot (per_cu->v.quick->mark
5589                              ? visited_found.get ()
5590                              : visited_not_found.get (),
5591                              file_data, INSERT);
5592       *slot = file_data;
5593     }
5594 }
5595
5596 static void
5597 dw2_expand_symtabs_matching
5598   (struct objfile *objfile,
5599    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5600    const lookup_name_info &lookup_name,
5601    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5602    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5603    enum search_domain kind)
5604 {
5605   struct dwarf2_per_objfile *dwarf2_per_objfile
5606     = get_dwarf2_per_objfile (objfile);
5607
5608   /* index_table is NULL if OBJF_READNOW.  */
5609   if (!dwarf2_per_objfile->index_table)
5610     return;
5611
5612   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5613
5614   mapped_index &index = *dwarf2_per_objfile->index_table;
5615
5616   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5617                                       symbol_matcher,
5618                                       kind, [&] (offset_type idx)
5619     {
5620       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5621                              expansion_notify, kind);
5622     });
5623 }
5624
5625 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5626    symtab.  */
5627
5628 static struct compunit_symtab *
5629 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5630                                           CORE_ADDR pc)
5631 {
5632   int i;
5633
5634   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5635       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5636     return cust;
5637
5638   if (cust->includes == NULL)
5639     return NULL;
5640
5641   for (i = 0; cust->includes[i]; ++i)
5642     {
5643       struct compunit_symtab *s = cust->includes[i];
5644
5645       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5646       if (s != NULL)
5647         return s;
5648     }
5649
5650   return NULL;
5651 }
5652
5653 static struct compunit_symtab *
5654 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5655                                   struct bound_minimal_symbol msymbol,
5656                                   CORE_ADDR pc,
5657                                   struct obj_section *section,
5658                                   int warn_if_readin)
5659 {
5660   struct dwarf2_per_cu_data *data;
5661   struct compunit_symtab *result;
5662
5663   if (!objfile->psymtabs_addrmap)
5664     return NULL;
5665
5666   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5667                                                      pc);
5668   if (!data)
5669     return NULL;
5670
5671   if (warn_if_readin && data->v.quick->compunit_symtab)
5672     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5673              paddress (get_objfile_arch (objfile), pc));
5674
5675   result
5676     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5677                                                 pc);
5678   gdb_assert (result != NULL);
5679   return result;
5680 }
5681
5682 static void
5683 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5684                           void *data, int need_fullname)
5685 {
5686   struct dwarf2_per_objfile *dwarf2_per_objfile
5687     = get_dwarf2_per_objfile (objfile);
5688
5689   if (!dwarf2_per_objfile->filenames_cache)
5690     {
5691       dwarf2_per_objfile->filenames_cache.emplace ();
5692
5693       htab_up visited (htab_create_alloc (10,
5694                                           htab_hash_pointer, htab_eq_pointer,
5695                                           NULL, xcalloc, xfree));
5696
5697       /* The rule is CUs specify all the files, including those used
5698          by any TU, so there's no need to scan TUs here.  We can
5699          ignore file names coming from already-expanded CUs.  */
5700
5701       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5702         {
5703           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5704
5705           if (per_cu->v.quick->compunit_symtab)
5706             {
5707               void **slot = htab_find_slot (visited.get (),
5708                                             per_cu->v.quick->file_names,
5709                                             INSERT);
5710
5711               *slot = per_cu->v.quick->file_names;
5712             }
5713         }
5714
5715       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5716         {
5717           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5718           struct quick_file_names *file_data;
5719           void **slot;
5720
5721           /* We only need to look at symtabs not already expanded.  */
5722           if (per_cu->v.quick->compunit_symtab)
5723             continue;
5724
5725           file_data = dw2_get_file_names (per_cu);
5726           if (file_data == NULL)
5727             continue;
5728
5729           slot = htab_find_slot (visited.get (), file_data, INSERT);
5730           if (*slot)
5731             {
5732               /* Already visited.  */
5733               continue;
5734             }
5735           *slot = file_data;
5736
5737           for (int j = 0; j < file_data->num_file_names; ++j)
5738             {
5739               const char *filename = file_data->file_names[j];
5740               dwarf2_per_objfile->filenames_cache->seen (filename);
5741             }
5742         }
5743     }
5744
5745   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5746     {
5747       gdb::unique_xmalloc_ptr<char> this_real_name;
5748
5749       if (need_fullname)
5750         this_real_name = gdb_realpath (filename);
5751       (*fun) (filename, this_real_name.get (), data);
5752     });
5753 }
5754
5755 static int
5756 dw2_has_symbols (struct objfile *objfile)
5757 {
5758   return 1;
5759 }
5760
5761 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5762 {
5763   dw2_has_symbols,
5764   dw2_find_last_source_symtab,
5765   dw2_forget_cached_source_info,
5766   dw2_map_symtabs_matching_filename,
5767   dw2_lookup_symbol,
5768   dw2_print_stats,
5769   dw2_dump,
5770   dw2_relocate,
5771   dw2_expand_symtabs_for_function,
5772   dw2_expand_all_symtabs,
5773   dw2_expand_symtabs_with_fullname,
5774   dw2_map_matching_symbols,
5775   dw2_expand_symtabs_matching,
5776   dw2_find_pc_sect_compunit_symtab,
5777   NULL,
5778   dw2_map_symbol_filenames
5779 };
5780
5781 /* DWARF-5 debug_names reader.  */
5782
5783 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5784 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5785
5786 /* A helper function that reads the .debug_names section in SECTION
5787    and fills in MAP.  FILENAME is the name of the file containing the
5788    section; it is used for error reporting.
5789
5790    Returns true if all went well, false otherwise.  */
5791
5792 static bool
5793 read_debug_names_from_section (struct objfile *objfile,
5794                                const char *filename,
5795                                struct dwarf2_section_info *section,
5796                                mapped_debug_names &map)
5797 {
5798   if (dwarf2_section_empty_p (section))
5799     return false;
5800
5801   /* Older elfutils strip versions could keep the section in the main
5802      executable while splitting it for the separate debug info file.  */
5803   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5804     return false;
5805
5806   dwarf2_read_section (objfile, section);
5807
5808   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5809
5810   const gdb_byte *addr = section->buffer;
5811
5812   bfd *const abfd = get_section_bfd_owner (section);
5813
5814   unsigned int bytes_read;
5815   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5816   addr += bytes_read;
5817
5818   map.dwarf5_is_dwarf64 = bytes_read != 4;
5819   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5820   if (bytes_read + length != section->size)
5821     {
5822       /* There may be multiple per-CU indices.  */
5823       warning (_("Section .debug_names in %s length %s does not match "
5824                  "section length %s, ignoring .debug_names."),
5825                filename, plongest (bytes_read + length),
5826                pulongest (section->size));
5827       return false;
5828     }
5829
5830   /* The version number.  */
5831   uint16_t version = read_2_bytes (abfd, addr);
5832   addr += 2;
5833   if (version != 5)
5834     {
5835       warning (_("Section .debug_names in %s has unsupported version %d, "
5836                  "ignoring .debug_names."),
5837                filename, version);
5838       return false;
5839     }
5840
5841   /* Padding.  */
5842   uint16_t padding = read_2_bytes (abfd, addr);
5843   addr += 2;
5844   if (padding != 0)
5845     {
5846       warning (_("Section .debug_names in %s has unsupported padding %d, "
5847                  "ignoring .debug_names."),
5848                filename, padding);
5849       return false;
5850     }
5851
5852   /* comp_unit_count - The number of CUs in the CU list.  */
5853   map.cu_count = read_4_bytes (abfd, addr);
5854   addr += 4;
5855
5856   /* local_type_unit_count - The number of TUs in the local TU
5857      list.  */
5858   map.tu_count = read_4_bytes (abfd, addr);
5859   addr += 4;
5860
5861   /* foreign_type_unit_count - The number of TUs in the foreign TU
5862      list.  */
5863   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5864   addr += 4;
5865   if (foreign_tu_count != 0)
5866     {
5867       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5868                  "ignoring .debug_names."),
5869                filename, static_cast<unsigned long> (foreign_tu_count));
5870       return false;
5871     }
5872
5873   /* bucket_count - The number of hash buckets in the hash lookup
5874      table.  */
5875   map.bucket_count = read_4_bytes (abfd, addr);
5876   addr += 4;
5877
5878   /* name_count - The number of unique names in the index.  */
5879   map.name_count = read_4_bytes (abfd, addr);
5880   addr += 4;
5881
5882   /* abbrev_table_size - The size in bytes of the abbreviations
5883      table.  */
5884   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5885   addr += 4;
5886
5887   /* augmentation_string_size - The size in bytes of the augmentation
5888      string.  This value is rounded up to a multiple of 4.  */
5889   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5890   addr += 4;
5891   map.augmentation_is_gdb = ((augmentation_string_size
5892                               == sizeof (dwarf5_augmentation))
5893                              && memcmp (addr, dwarf5_augmentation,
5894                                         sizeof (dwarf5_augmentation)) == 0);
5895   augmentation_string_size += (-augmentation_string_size) & 3;
5896   addr += augmentation_string_size;
5897
5898   /* List of CUs */
5899   map.cu_table_reordered = addr;
5900   addr += map.cu_count * map.offset_size;
5901
5902   /* List of Local TUs */
5903   map.tu_table_reordered = addr;
5904   addr += map.tu_count * map.offset_size;
5905
5906   /* Hash Lookup Table */
5907   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5908   addr += map.bucket_count * 4;
5909   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5910   addr += map.name_count * 4;
5911
5912   /* Name Table */
5913   map.name_table_string_offs_reordered = addr;
5914   addr += map.name_count * map.offset_size;
5915   map.name_table_entry_offs_reordered = addr;
5916   addr += map.name_count * map.offset_size;
5917
5918   const gdb_byte *abbrev_table_start = addr;
5919   for (;;)
5920     {
5921       unsigned int bytes_read;
5922       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5923       addr += bytes_read;
5924       if (index_num == 0)
5925         break;
5926
5927       const auto insertpair
5928         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5929       if (!insertpair.second)
5930         {
5931           warning (_("Section .debug_names in %s has duplicate index %s, "
5932                      "ignoring .debug_names."),
5933                    filename, pulongest (index_num));
5934           return false;
5935         }
5936       mapped_debug_names::index_val &indexval = insertpair.first->second;
5937       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5938       addr += bytes_read;
5939
5940       for (;;)
5941         {
5942           mapped_debug_names::index_val::attr attr;
5943           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5944           addr += bytes_read;
5945           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5946           addr += bytes_read;
5947           if (attr.form == DW_FORM_implicit_const)
5948             {
5949               attr.implicit_const = read_signed_leb128 (abfd, addr,
5950                                                         &bytes_read);
5951               addr += bytes_read;
5952             }
5953           if (attr.dw_idx == 0 && attr.form == 0)
5954             break;
5955           indexval.attr_vec.push_back (std::move (attr));
5956         }
5957     }
5958   if (addr != abbrev_table_start + abbrev_table_size)
5959     {
5960       warning (_("Section .debug_names in %s has abbreviation_table "
5961                  "of size %zu vs. written as %u, ignoring .debug_names."),
5962                filename, addr - abbrev_table_start, abbrev_table_size);
5963       return false;
5964     }
5965   map.entry_pool = addr;
5966
5967   return true;
5968 }
5969
5970 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5971    list.  */
5972
5973 static void
5974 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5975                                   const mapped_debug_names &map,
5976                                   dwarf2_section_info &section,
5977                                   bool is_dwz, int base_offset)
5978 {
5979   sect_offset sect_off_prev;
5980   for (uint32_t i = 0; i <= map.cu_count; ++i)
5981     {
5982       sect_offset sect_off_next;
5983       if (i < map.cu_count)
5984         {
5985           sect_off_next
5986             = (sect_offset) (extract_unsigned_integer
5987                              (map.cu_table_reordered + i * map.offset_size,
5988                               map.offset_size,
5989                               map.dwarf5_byte_order));
5990         }
5991       else
5992         sect_off_next = (sect_offset) section.size;
5993       if (i >= 1)
5994         {
5995           const ULONGEST length = sect_off_next - sect_off_prev;
5996           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5997             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5998                                          sect_off_prev, length);
5999         }
6000       sect_off_prev = sect_off_next;
6001     }
6002 }
6003
6004 /* Read the CU list from the mapped index, and use it to create all
6005    the CU objects for this dwarf2_per_objfile.  */
6006
6007 static void
6008 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
6009                              const mapped_debug_names &map,
6010                              const mapped_debug_names &dwz_map)
6011 {
6012   struct objfile *objfile = dwarf2_per_objfile->objfile;
6013
6014   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
6015   dwarf2_per_objfile->all_comp_units
6016     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
6017                  dwarf2_per_objfile->n_comp_units);
6018
6019   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
6020                                     dwarf2_per_objfile->info,
6021                                     false /* is_dwz */,
6022                                     0 /* base_offset */);
6023
6024   if (dwz_map.cu_count == 0)
6025     return;
6026
6027   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6028   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
6029                                     true /* is_dwz */,
6030                                     map.cu_count /* base_offset */);
6031 }
6032
6033 /* Read .debug_names.  If everything went ok, initialize the "quick"
6034    elements of all the CUs and return true.  Otherwise, return false.  */
6035
6036 static bool
6037 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
6038 {
6039   mapped_debug_names local_map (dwarf2_per_objfile);
6040   mapped_debug_names dwz_map (dwarf2_per_objfile);
6041   struct objfile *objfile = dwarf2_per_objfile->objfile;
6042
6043   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
6044                                       &dwarf2_per_objfile->debug_names,
6045                                       local_map))
6046     return false;
6047
6048   /* Don't use the index if it's empty.  */
6049   if (local_map.name_count == 0)
6050     return false;
6051
6052   /* If there is a .dwz file, read it so we can get its CU list as
6053      well.  */
6054   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6055   if (dwz != NULL)
6056     {
6057       if (!read_debug_names_from_section (objfile,
6058                                           bfd_get_filename (dwz->dwz_bfd),
6059                                           &dwz->debug_names, dwz_map))
6060         {
6061           warning (_("could not read '.debug_names' section from %s; skipping"),
6062                    bfd_get_filename (dwz->dwz_bfd));
6063           return false;
6064         }
6065     }
6066
6067   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
6068
6069   if (local_map.tu_count != 0)
6070     {
6071       /* We can only handle a single .debug_types when we have an
6072          index.  */
6073       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
6074         return false;
6075
6076       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
6077                                                 dwarf2_per_objfile->types, 0);
6078
6079       create_signatured_type_table_from_debug_names
6080         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
6081     }
6082
6083   create_addrmap_from_aranges (dwarf2_per_objfile,
6084                                &dwarf2_per_objfile->debug_aranges);
6085
6086   dwarf2_per_objfile->debug_names_table.reset
6087     (new mapped_debug_names (dwarf2_per_objfile));
6088   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
6089   dwarf2_per_objfile->using_index = 1;
6090   dwarf2_per_objfile->quick_file_names_table =
6091     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6092
6093   return true;
6094 }
6095
6096 /* Symbol name hashing function as specified by DWARF-5.  */
6097
6098 static uint32_t
6099 dwarf5_djb_hash (const char *str_)
6100 {
6101   const unsigned char *str = (const unsigned char *) str_;
6102
6103   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6104      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6105
6106   uint32_t hash = 5381;
6107   while (int c = *str++)
6108     hash = hash * 33 + tolower (c);
6109   return hash;
6110 }
6111
6112 /* Type used to manage iterating over all CUs looking for a symbol for
6113    .debug_names.  */
6114
6115 class dw2_debug_names_iterator
6116 {
6117 public:
6118   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6119      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6120   dw2_debug_names_iterator (const mapped_debug_names &map,
6121                             bool want_specific_block,
6122                             block_enum block_index, domain_enum domain,
6123                             const char *name)
6124     : m_map (map), m_want_specific_block (want_specific_block),
6125       m_block_index (block_index), m_domain (domain),
6126       m_addr (find_vec_in_debug_names (map, name))
6127   {}
6128
6129   dw2_debug_names_iterator (const mapped_debug_names &map,
6130                             search_domain search, uint32_t namei)
6131     : m_map (map),
6132       m_search (search),
6133       m_addr (find_vec_in_debug_names (map, namei))
6134   {}
6135
6136   /* Return the next matching CU or NULL if there are no more.  */
6137   dwarf2_per_cu_data *next ();
6138
6139 private:
6140   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6141                                                   const char *name);
6142   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6143                                                   uint32_t namei);
6144
6145   /* The internalized form of .debug_names.  */
6146   const mapped_debug_names &m_map;
6147
6148   /* If true, only look for symbols that match BLOCK_INDEX.  */
6149   const bool m_want_specific_block = false;
6150
6151   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6152      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6153      value.  */
6154   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6155
6156   /* The kind of symbol we're looking for.  */
6157   const domain_enum m_domain = UNDEF_DOMAIN;
6158   const search_domain m_search = ALL_DOMAIN;
6159
6160   /* The list of CUs from the index entry of the symbol, or NULL if
6161      not found.  */
6162   const gdb_byte *m_addr;
6163 };
6164
6165 const char *
6166 mapped_debug_names::namei_to_name (uint32_t namei) const
6167 {
6168   const ULONGEST namei_string_offs
6169     = extract_unsigned_integer ((name_table_string_offs_reordered
6170                                  + namei * offset_size),
6171                                 offset_size,
6172                                 dwarf5_byte_order);
6173   return read_indirect_string_at_offset
6174     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6175 }
6176
6177 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6178    found, return pointer to its pool data.  If NAME cannot be found,
6179    return NULL.  */
6180
6181 const gdb_byte *
6182 dw2_debug_names_iterator::find_vec_in_debug_names
6183   (const mapped_debug_names &map, const char *name)
6184 {
6185   int (*cmp) (const char *, const char *);
6186
6187   if (current_language->la_language == language_cplus
6188       || current_language->la_language == language_fortran
6189       || current_language->la_language == language_d)
6190     {
6191       /* NAME is already canonical.  Drop any qualifiers as
6192          .debug_names does not contain any.  */
6193
6194       if (strchr (name, '(') != NULL)
6195         {
6196           gdb::unique_xmalloc_ptr<char> without_params
6197             = cp_remove_params (name);
6198
6199           if (without_params != NULL)
6200             {
6201               name = without_params.get();
6202             }
6203         }
6204     }
6205
6206   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6207
6208   const uint32_t full_hash = dwarf5_djb_hash (name);
6209   uint32_t namei
6210     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6211                                 (map.bucket_table_reordered
6212                                  + (full_hash % map.bucket_count)), 4,
6213                                 map.dwarf5_byte_order);
6214   if (namei == 0)
6215     return NULL;
6216   --namei;
6217   if (namei >= map.name_count)
6218     {
6219       complaint (&symfile_complaints,
6220                  _("Wrong .debug_names with name index %u but name_count=%u "
6221                    "[in module %s]"),
6222                  namei, map.name_count,
6223                  objfile_name (map.dwarf2_per_objfile->objfile));
6224       return NULL;
6225     }
6226
6227   for (;;)
6228     {
6229       const uint32_t namei_full_hash
6230         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6231                                     (map.hash_table_reordered + namei), 4,
6232                                     map.dwarf5_byte_order);
6233       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6234         return NULL;
6235
6236       if (full_hash == namei_full_hash)
6237         {
6238           const char *const namei_string = map.namei_to_name (namei);
6239
6240 #if 0 /* An expensive sanity check.  */
6241           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6242             {
6243               complaint (&symfile_complaints,
6244                          _("Wrong .debug_names hash for string at index %u "
6245                            "[in module %s]"),
6246                          namei, objfile_name (dwarf2_per_objfile->objfile));
6247               return NULL;
6248             }
6249 #endif
6250
6251           if (cmp (namei_string, name) == 0)
6252             {
6253               const ULONGEST namei_entry_offs
6254                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6255                                              + namei * map.offset_size),
6256                                             map.offset_size, map.dwarf5_byte_order);
6257               return map.entry_pool + namei_entry_offs;
6258             }
6259         }
6260
6261       ++namei;
6262       if (namei >= map.name_count)
6263         return NULL;
6264     }
6265 }
6266
6267 const gdb_byte *
6268 dw2_debug_names_iterator::find_vec_in_debug_names
6269   (const mapped_debug_names &map, uint32_t namei)
6270 {
6271   if (namei >= map.name_count)
6272     {
6273       complaint (&symfile_complaints,
6274                  _("Wrong .debug_names with name index %u but name_count=%u "
6275                    "[in module %s]"),
6276                  namei, map.name_count,
6277                  objfile_name (map.dwarf2_per_objfile->objfile));
6278       return NULL;
6279     }
6280
6281   const ULONGEST namei_entry_offs
6282     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6283                                  + namei * map.offset_size),
6284                                 map.offset_size, map.dwarf5_byte_order);
6285   return map.entry_pool + namei_entry_offs;
6286 }
6287
6288 /* See dw2_debug_names_iterator.  */
6289
6290 dwarf2_per_cu_data *
6291 dw2_debug_names_iterator::next ()
6292 {
6293   if (m_addr == NULL)
6294     return NULL;
6295
6296   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6297   struct objfile *objfile = dwarf2_per_objfile->objfile;
6298   bfd *const abfd = objfile->obfd;
6299
6300  again:
6301
6302   unsigned int bytes_read;
6303   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6304   m_addr += bytes_read;
6305   if (abbrev == 0)
6306     return NULL;
6307
6308   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6309   if (indexval_it == m_map.abbrev_map.cend ())
6310     {
6311       complaint (&symfile_complaints,
6312                  _("Wrong .debug_names undefined abbrev code %s "
6313                    "[in module %s]"),
6314                  pulongest (abbrev), objfile_name (objfile));
6315       return NULL;
6316     }
6317   const mapped_debug_names::index_val &indexval = indexval_it->second;
6318   bool have_is_static = false;
6319   bool is_static;
6320   dwarf2_per_cu_data *per_cu = NULL;
6321   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6322     {
6323       ULONGEST ull;
6324       switch (attr.form)
6325         {
6326         case DW_FORM_implicit_const:
6327           ull = attr.implicit_const;
6328           break;
6329         case DW_FORM_flag_present:
6330           ull = 1;
6331           break;
6332         case DW_FORM_udata:
6333           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6334           m_addr += bytes_read;
6335           break;
6336         default:
6337           complaint (&symfile_complaints,
6338                      _("Unsupported .debug_names form %s [in module %s]"),
6339                      dwarf_form_name (attr.form),
6340                      objfile_name (objfile));
6341           return NULL;
6342         }
6343       switch (attr.dw_idx)
6344         {
6345         case DW_IDX_compile_unit:
6346           /* Don't crash on bad data.  */
6347           if (ull >= dwarf2_per_objfile->n_comp_units)
6348             {
6349               complaint (&symfile_complaints,
6350                          _(".debug_names entry has bad CU index %s"
6351                            " [in module %s]"),
6352                          pulongest (ull),
6353                          objfile_name (dwarf2_per_objfile->objfile));
6354               continue;
6355             }
6356           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6357           break;
6358         case DW_IDX_type_unit:
6359           /* Don't crash on bad data.  */
6360           if (ull >= dwarf2_per_objfile->n_type_units)
6361             {
6362               complaint (&symfile_complaints,
6363                          _(".debug_names entry has bad TU index %s"
6364                            " [in module %s]"),
6365                          pulongest (ull),
6366                          objfile_name (dwarf2_per_objfile->objfile));
6367               continue;
6368             }
6369           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6370                                  dwarf2_per_objfile->n_comp_units + ull);
6371           break;
6372         case DW_IDX_GNU_internal:
6373           if (!m_map.augmentation_is_gdb)
6374             break;
6375           have_is_static = true;
6376           is_static = true;
6377           break;
6378         case DW_IDX_GNU_external:
6379           if (!m_map.augmentation_is_gdb)
6380             break;
6381           have_is_static = true;
6382           is_static = false;
6383           break;
6384         }
6385     }
6386
6387   /* Skip if already read in.  */
6388   if (per_cu->v.quick->compunit_symtab)
6389     goto again;
6390
6391   /* Check static vs global.  */
6392   if (have_is_static)
6393     {
6394       const bool want_static = m_block_index != GLOBAL_BLOCK;
6395       if (m_want_specific_block && want_static != is_static)
6396         goto again;
6397     }
6398
6399   /* Match dw2_symtab_iter_next, symbol_kind
6400      and debug_names::psymbol_tag.  */
6401   switch (m_domain)
6402     {
6403     case VAR_DOMAIN:
6404       switch (indexval.dwarf_tag)
6405         {
6406         case DW_TAG_variable:
6407         case DW_TAG_subprogram:
6408         /* Some types are also in VAR_DOMAIN.  */
6409         case DW_TAG_typedef:
6410         case DW_TAG_structure_type:
6411           break;
6412         default:
6413           goto again;
6414         }
6415       break;
6416     case STRUCT_DOMAIN:
6417       switch (indexval.dwarf_tag)
6418         {
6419         case DW_TAG_typedef:
6420         case DW_TAG_structure_type:
6421           break;
6422         default:
6423           goto again;
6424         }
6425       break;
6426     case LABEL_DOMAIN:
6427       switch (indexval.dwarf_tag)
6428         {
6429         case 0:
6430         case DW_TAG_variable:
6431           break;
6432         default:
6433           goto again;
6434         }
6435       break;
6436     default:
6437       break;
6438     }
6439
6440   /* Match dw2_expand_symtabs_matching, symbol_kind and
6441      debug_names::psymbol_tag.  */
6442   switch (m_search)
6443     {
6444     case VARIABLES_DOMAIN:
6445       switch (indexval.dwarf_tag)
6446         {
6447         case DW_TAG_variable:
6448           break;
6449         default:
6450           goto again;
6451         }
6452       break;
6453     case FUNCTIONS_DOMAIN:
6454       switch (indexval.dwarf_tag)
6455         {
6456         case DW_TAG_subprogram:
6457           break;
6458         default:
6459           goto again;
6460         }
6461       break;
6462     case TYPES_DOMAIN:
6463       switch (indexval.dwarf_tag)
6464         {
6465         case DW_TAG_typedef:
6466         case DW_TAG_structure_type:
6467           break;
6468         default:
6469           goto again;
6470         }
6471       break;
6472     default:
6473       break;
6474     }
6475
6476   return per_cu;
6477 }
6478
6479 static struct compunit_symtab *
6480 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6481                                const char *name, domain_enum domain)
6482 {
6483   const block_enum block_index = static_cast<block_enum> (block_index_int);
6484   struct dwarf2_per_objfile *dwarf2_per_objfile
6485     = get_dwarf2_per_objfile (objfile);
6486
6487   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6488   if (!mapp)
6489     {
6490       /* index is NULL if OBJF_READNOW.  */
6491       return NULL;
6492     }
6493   const auto &map = *mapp;
6494
6495   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6496                                  block_index, domain, name);
6497
6498   struct compunit_symtab *stab_best = NULL;
6499   struct dwarf2_per_cu_data *per_cu;
6500   while ((per_cu = iter.next ()) != NULL)
6501     {
6502       struct symbol *sym, *with_opaque = NULL;
6503       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6504       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6505       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6506
6507       sym = block_find_symbol (block, name, domain,
6508                                block_find_non_opaque_type_preferred,
6509                                &with_opaque);
6510
6511       /* Some caution must be observed with overloaded functions and
6512          methods, since the index will not contain any overload
6513          information (but NAME might contain it).  */
6514
6515       if (sym != NULL
6516           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6517         return stab;
6518       if (with_opaque != NULL
6519           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6520         stab_best = stab;
6521
6522       /* Keep looking through other CUs.  */
6523     }
6524
6525   return stab_best;
6526 }
6527
6528 /* This dumps minimal information about .debug_names.  It is called
6529    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6530    uses this to verify that .debug_names has been loaded.  */
6531
6532 static void
6533 dw2_debug_names_dump (struct objfile *objfile)
6534 {
6535   struct dwarf2_per_objfile *dwarf2_per_objfile
6536     = get_dwarf2_per_objfile (objfile);
6537
6538   gdb_assert (dwarf2_per_objfile->using_index);
6539   printf_filtered (".debug_names:");
6540   if (dwarf2_per_objfile->debug_names_table)
6541     printf_filtered (" exists\n");
6542   else
6543     printf_filtered (" faked for \"readnow\"\n");
6544   printf_filtered ("\n");
6545 }
6546
6547 static void
6548 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6549                                              const char *func_name)
6550 {
6551   struct dwarf2_per_objfile *dwarf2_per_objfile
6552     = get_dwarf2_per_objfile (objfile);
6553
6554   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6555   if (dwarf2_per_objfile->debug_names_table)
6556     {
6557       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6558
6559       /* Note: It doesn't matter what we pass for block_index here.  */
6560       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6561                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6562
6563       struct dwarf2_per_cu_data *per_cu;
6564       while ((per_cu = iter.next ()) != NULL)
6565         dw2_instantiate_symtab (per_cu);
6566     }
6567 }
6568
6569 static void
6570 dw2_debug_names_expand_symtabs_matching
6571   (struct objfile *objfile,
6572    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6573    const lookup_name_info &lookup_name,
6574    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6575    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6576    enum search_domain kind)
6577 {
6578   struct dwarf2_per_objfile *dwarf2_per_objfile
6579     = get_dwarf2_per_objfile (objfile);
6580
6581   /* debug_names_table is NULL if OBJF_READNOW.  */
6582   if (!dwarf2_per_objfile->debug_names_table)
6583     return;
6584
6585   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6586
6587   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6588
6589   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6590                                       symbol_matcher,
6591                                       kind, [&] (offset_type namei)
6592     {
6593       /* The name was matched, now expand corresponding CUs that were
6594          marked.  */
6595       dw2_debug_names_iterator iter (map, kind, namei);
6596
6597       struct dwarf2_per_cu_data *per_cu;
6598       while ((per_cu = iter.next ()) != NULL)
6599         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6600                                          expansion_notify);
6601     });
6602 }
6603
6604 const struct quick_symbol_functions dwarf2_debug_names_functions =
6605 {
6606   dw2_has_symbols,
6607   dw2_find_last_source_symtab,
6608   dw2_forget_cached_source_info,
6609   dw2_map_symtabs_matching_filename,
6610   dw2_debug_names_lookup_symbol,
6611   dw2_print_stats,
6612   dw2_debug_names_dump,
6613   dw2_relocate,
6614   dw2_debug_names_expand_symtabs_for_function,
6615   dw2_expand_all_symtabs,
6616   dw2_expand_symtabs_with_fullname,
6617   dw2_map_matching_symbols,
6618   dw2_debug_names_expand_symtabs_matching,
6619   dw2_find_pc_sect_compunit_symtab,
6620   NULL,
6621   dw2_map_symbol_filenames
6622 };
6623
6624 /* See symfile.h.  */
6625
6626 bool
6627 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6628 {
6629   struct dwarf2_per_objfile *dwarf2_per_objfile
6630     = get_dwarf2_per_objfile (objfile);
6631
6632   /* If we're about to read full symbols, don't bother with the
6633      indices.  In this case we also don't care if some other debug
6634      format is making psymtabs, because they are all about to be
6635      expanded anyway.  */
6636   if ((objfile->flags & OBJF_READNOW))
6637     {
6638       int i;
6639
6640       dwarf2_per_objfile->using_index = 1;
6641       create_all_comp_units (dwarf2_per_objfile);
6642       create_all_type_units (dwarf2_per_objfile);
6643       dwarf2_per_objfile->quick_file_names_table =
6644         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6645
6646       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6647                        + dwarf2_per_objfile->n_type_units); ++i)
6648         {
6649           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6650
6651           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6652                                             struct dwarf2_per_cu_quick_data);
6653         }
6654
6655       /* Return 1 so that gdb sees the "quick" functions.  However,
6656          these functions will be no-ops because we will have expanded
6657          all symtabs.  */
6658       *index_kind = dw_index_kind::GDB_INDEX;
6659       return true;
6660     }
6661
6662   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6663     {
6664       *index_kind = dw_index_kind::DEBUG_NAMES;
6665       return true;
6666     }
6667
6668   if (dwarf2_read_index (objfile))
6669     {
6670       *index_kind = dw_index_kind::GDB_INDEX;
6671       return true;
6672     }
6673
6674   return false;
6675 }
6676
6677 \f
6678
6679 /* Build a partial symbol table.  */
6680
6681 void
6682 dwarf2_build_psymtabs (struct objfile *objfile)
6683 {
6684   struct dwarf2_per_objfile *dwarf2_per_objfile
6685     = get_dwarf2_per_objfile (objfile);
6686
6687   if (objfile->global_psymbols.capacity () == 0
6688       && objfile->static_psymbols.capacity () == 0)
6689     init_psymbol_list (objfile, 1024);
6690
6691   TRY
6692     {
6693       /* This isn't really ideal: all the data we allocate on the
6694          objfile's obstack is still uselessly kept around.  However,
6695          freeing it seems unsafe.  */
6696       psymtab_discarder psymtabs (objfile);
6697       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6698       psymtabs.keep ();
6699     }
6700   CATCH (except, RETURN_MASK_ERROR)
6701     {
6702       exception_print (gdb_stderr, except);
6703     }
6704   END_CATCH
6705 }
6706
6707 /* Return the total length of the CU described by HEADER.  */
6708
6709 static unsigned int
6710 get_cu_length (const struct comp_unit_head *header)
6711 {
6712   return header->initial_length_size + header->length;
6713 }
6714
6715 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6716
6717 static inline bool
6718 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6719 {
6720   sect_offset bottom = cu_header->sect_off;
6721   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6722
6723   return sect_off >= bottom && sect_off < top;
6724 }
6725
6726 /* Find the base address of the compilation unit for range lists and
6727    location lists.  It will normally be specified by DW_AT_low_pc.
6728    In DWARF-3 draft 4, the base address could be overridden by
6729    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6730    compilation units with discontinuous ranges.  */
6731
6732 static void
6733 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6734 {
6735   struct attribute *attr;
6736
6737   cu->base_known = 0;
6738   cu->base_address = 0;
6739
6740   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6741   if (attr)
6742     {
6743       cu->base_address = attr_value_as_address (attr);
6744       cu->base_known = 1;
6745     }
6746   else
6747     {
6748       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6749       if (attr)
6750         {
6751           cu->base_address = attr_value_as_address (attr);
6752           cu->base_known = 1;
6753         }
6754     }
6755 }
6756
6757 /* Read in the comp unit header information from the debug_info at info_ptr.
6758    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6759    NOTE: This leaves members offset, first_die_offset to be filled in
6760    by the caller.  */
6761
6762 static const gdb_byte *
6763 read_comp_unit_head (struct comp_unit_head *cu_header,
6764                      const gdb_byte *info_ptr,
6765                      struct dwarf2_section_info *section,
6766                      rcuh_kind section_kind)
6767 {
6768   int signed_addr;
6769   unsigned int bytes_read;
6770   const char *filename = get_section_file_name (section);
6771   bfd *abfd = get_section_bfd_owner (section);
6772
6773   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6774   cu_header->initial_length_size = bytes_read;
6775   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6776   info_ptr += bytes_read;
6777   cu_header->version = read_2_bytes (abfd, info_ptr);
6778   info_ptr += 2;
6779   if (cu_header->version < 5)
6780     switch (section_kind)
6781       {
6782       case rcuh_kind::COMPILE:
6783         cu_header->unit_type = DW_UT_compile;
6784         break;
6785       case rcuh_kind::TYPE:
6786         cu_header->unit_type = DW_UT_type;
6787         break;
6788       default:
6789         internal_error (__FILE__, __LINE__,
6790                         _("read_comp_unit_head: invalid section_kind"));
6791       }
6792   else
6793     {
6794       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6795                                                  (read_1_byte (abfd, info_ptr));
6796       info_ptr += 1;
6797       switch (cu_header->unit_type)
6798         {
6799         case DW_UT_compile:
6800           if (section_kind != rcuh_kind::COMPILE)
6801             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6802                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6803                    filename);
6804           break;
6805         case DW_UT_type:
6806           section_kind = rcuh_kind::TYPE;
6807           break;
6808         default:
6809           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6810                  "(is %d, should be %d or %d) [in module %s]"),
6811                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6812         }
6813
6814       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6815       info_ptr += 1;
6816     }
6817   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6818                                                           cu_header,
6819                                                           &bytes_read);
6820   info_ptr += bytes_read;
6821   if (cu_header->version < 5)
6822     {
6823       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6824       info_ptr += 1;
6825     }
6826   signed_addr = bfd_get_sign_extend_vma (abfd);
6827   if (signed_addr < 0)
6828     internal_error (__FILE__, __LINE__,
6829                     _("read_comp_unit_head: dwarf from non elf file"));
6830   cu_header->signed_addr_p = signed_addr;
6831
6832   if (section_kind == rcuh_kind::TYPE)
6833     {
6834       LONGEST type_offset;
6835
6836       cu_header->signature = read_8_bytes (abfd, info_ptr);
6837       info_ptr += 8;
6838
6839       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6840       info_ptr += bytes_read;
6841       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6842       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6843         error (_("Dwarf Error: Too big type_offset in compilation unit "
6844                "header (is %s) [in module %s]"), plongest (type_offset),
6845                filename);
6846     }
6847
6848   return info_ptr;
6849 }
6850
6851 /* Helper function that returns the proper abbrev section for
6852    THIS_CU.  */
6853
6854 static struct dwarf2_section_info *
6855 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6856 {
6857   struct dwarf2_section_info *abbrev;
6858   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6859
6860   if (this_cu->is_dwz)
6861     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6862   else
6863     abbrev = &dwarf2_per_objfile->abbrev;
6864
6865   return abbrev;
6866 }
6867
6868 /* Subroutine of read_and_check_comp_unit_head and
6869    read_and_check_type_unit_head to simplify them.
6870    Perform various error checking on the header.  */
6871
6872 static void
6873 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6874                             struct comp_unit_head *header,
6875                             struct dwarf2_section_info *section,
6876                             struct dwarf2_section_info *abbrev_section)
6877 {
6878   const char *filename = get_section_file_name (section);
6879
6880   if (header->version < 2 || header->version > 5)
6881     error (_("Dwarf Error: wrong version in compilation unit header "
6882            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6883            filename);
6884
6885   if (to_underlying (header->abbrev_sect_off)
6886       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6887     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6888            "(offset %s + 6) [in module %s]"),
6889            sect_offset_str (header->abbrev_sect_off),
6890            sect_offset_str (header->sect_off),
6891            filename);
6892
6893   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6894      avoid potential 32-bit overflow.  */
6895   if (((ULONGEST) header->sect_off + get_cu_length (header))
6896       > section->size)
6897     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6898            "(offset %s + 0) [in module %s]"),
6899            header->length, sect_offset_str (header->sect_off),
6900            filename);
6901 }
6902
6903 /* Read in a CU/TU header and perform some basic error checking.
6904    The contents of the header are stored in HEADER.
6905    The result is a pointer to the start of the first DIE.  */
6906
6907 static const gdb_byte *
6908 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6909                                struct comp_unit_head *header,
6910                                struct dwarf2_section_info *section,
6911                                struct dwarf2_section_info *abbrev_section,
6912                                const gdb_byte *info_ptr,
6913                                rcuh_kind section_kind)
6914 {
6915   const gdb_byte *beg_of_comp_unit = info_ptr;
6916
6917   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6918
6919   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6920
6921   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6922
6923   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6924                               abbrev_section);
6925
6926   return info_ptr;
6927 }
6928
6929 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6930
6931 static sect_offset
6932 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6933                     struct dwarf2_section_info *section,
6934                     sect_offset sect_off)
6935 {
6936   bfd *abfd = get_section_bfd_owner (section);
6937   const gdb_byte *info_ptr;
6938   unsigned int initial_length_size, offset_size;
6939   uint16_t version;
6940
6941   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6942   info_ptr = section->buffer + to_underlying (sect_off);
6943   read_initial_length (abfd, info_ptr, &initial_length_size);
6944   offset_size = initial_length_size == 4 ? 4 : 8;
6945   info_ptr += initial_length_size;
6946
6947   version = read_2_bytes (abfd, info_ptr);
6948   info_ptr += 2;
6949   if (version >= 5)
6950     {
6951       /* Skip unit type and address size.  */
6952       info_ptr += 2;
6953     }
6954
6955   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6956 }
6957
6958 /* Allocate a new partial symtab for file named NAME and mark this new
6959    partial symtab as being an include of PST.  */
6960
6961 static void
6962 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6963                                struct objfile *objfile)
6964 {
6965   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6966
6967   if (!IS_ABSOLUTE_PATH (subpst->filename))
6968     {
6969       /* It shares objfile->objfile_obstack.  */
6970       subpst->dirname = pst->dirname;
6971     }
6972
6973   subpst->textlow = 0;
6974   subpst->texthigh = 0;
6975
6976   subpst->dependencies
6977     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6978   subpst->dependencies[0] = pst;
6979   subpst->number_of_dependencies = 1;
6980
6981   subpst->globals_offset = 0;
6982   subpst->n_global_syms = 0;
6983   subpst->statics_offset = 0;
6984   subpst->n_static_syms = 0;
6985   subpst->compunit_symtab = NULL;
6986   subpst->read_symtab = pst->read_symtab;
6987   subpst->readin = 0;
6988
6989   /* No private part is necessary for include psymtabs.  This property
6990      can be used to differentiate between such include psymtabs and
6991      the regular ones.  */
6992   subpst->read_symtab_private = NULL;
6993 }
6994
6995 /* Read the Line Number Program data and extract the list of files
6996    included by the source file represented by PST.  Build an include
6997    partial symtab for each of these included files.  */
6998
6999 static void
7000 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
7001                                struct die_info *die,
7002                                struct partial_symtab *pst)
7003 {
7004   line_header_up lh;
7005   struct attribute *attr;
7006
7007   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7008   if (attr)
7009     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
7010   if (lh == NULL)
7011     return;  /* No linetable, so no includes.  */
7012
7013   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
7014   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
7015 }
7016
7017 static hashval_t
7018 hash_signatured_type (const void *item)
7019 {
7020   const struct signatured_type *sig_type
7021     = (const struct signatured_type *) item;
7022
7023   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
7024   return sig_type->signature;
7025 }
7026
7027 static int
7028 eq_signatured_type (const void *item_lhs, const void *item_rhs)
7029 {
7030   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
7031   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
7032
7033   return lhs->signature == rhs->signature;
7034 }
7035
7036 /* Allocate a hash table for signatured types.  */
7037
7038 static htab_t
7039 allocate_signatured_type_table (struct objfile *objfile)
7040 {
7041   return htab_create_alloc_ex (41,
7042                                hash_signatured_type,
7043                                eq_signatured_type,
7044                                NULL,
7045                                &objfile->objfile_obstack,
7046                                hashtab_obstack_allocate,
7047                                dummy_obstack_deallocate);
7048 }
7049
7050 /* A helper function to add a signatured type CU to a table.  */
7051
7052 static int
7053 add_signatured_type_cu_to_table (void **slot, void *datum)
7054 {
7055   struct signatured_type *sigt = (struct signatured_type *) *slot;
7056   struct signatured_type ***datap = (struct signatured_type ***) datum;
7057
7058   **datap = sigt;
7059   ++*datap;
7060
7061   return 1;
7062 }
7063
7064 /* A helper for create_debug_types_hash_table.  Read types from SECTION
7065    and fill them into TYPES_HTAB.  It will process only type units,
7066    therefore DW_UT_type.  */
7067
7068 static void
7069 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7070                               struct dwo_file *dwo_file,
7071                               dwarf2_section_info *section, htab_t &types_htab,
7072                               rcuh_kind section_kind)
7073 {
7074   struct objfile *objfile = dwarf2_per_objfile->objfile;
7075   struct dwarf2_section_info *abbrev_section;
7076   bfd *abfd;
7077   const gdb_byte *info_ptr, *end_ptr;
7078
7079   abbrev_section = (dwo_file != NULL
7080                     ? &dwo_file->sections.abbrev
7081                     : &dwarf2_per_objfile->abbrev);
7082
7083   if (dwarf_read_debug)
7084     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
7085                         get_section_name (section),
7086                         get_section_file_name (abbrev_section));
7087
7088   dwarf2_read_section (objfile, section);
7089   info_ptr = section->buffer;
7090
7091   if (info_ptr == NULL)
7092     return;
7093
7094   /* We can't set abfd until now because the section may be empty or
7095      not present, in which case the bfd is unknown.  */
7096   abfd = get_section_bfd_owner (section);
7097
7098   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7099      because we don't need to read any dies: the signature is in the
7100      header.  */
7101
7102   end_ptr = info_ptr + section->size;
7103   while (info_ptr < end_ptr)
7104     {
7105       struct signatured_type *sig_type;
7106       struct dwo_unit *dwo_tu;
7107       void **slot;
7108       const gdb_byte *ptr = info_ptr;
7109       struct comp_unit_head header;
7110       unsigned int length;
7111
7112       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7113
7114       /* Initialize it due to a false compiler warning.  */
7115       header.signature = -1;
7116       header.type_cu_offset_in_tu = (cu_offset) -1;
7117
7118       /* We need to read the type's signature in order to build the hash
7119          table, but we don't need anything else just yet.  */
7120
7121       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7122                                            abbrev_section, ptr, section_kind);
7123
7124       length = get_cu_length (&header);
7125
7126       /* Skip dummy type units.  */
7127       if (ptr >= info_ptr + length
7128           || peek_abbrev_code (abfd, ptr) == 0
7129           || header.unit_type != DW_UT_type)
7130         {
7131           info_ptr += length;
7132           continue;
7133         }
7134
7135       if (types_htab == NULL)
7136         {
7137           if (dwo_file)
7138             types_htab = allocate_dwo_unit_table (objfile);
7139           else
7140             types_htab = allocate_signatured_type_table (objfile);
7141         }
7142
7143       if (dwo_file)
7144         {
7145           sig_type = NULL;
7146           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7147                                    struct dwo_unit);
7148           dwo_tu->dwo_file = dwo_file;
7149           dwo_tu->signature = header.signature;
7150           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7151           dwo_tu->section = section;
7152           dwo_tu->sect_off = sect_off;
7153           dwo_tu->length = length;
7154         }
7155       else
7156         {
7157           /* N.B.: type_offset is not usable if this type uses a DWO file.
7158              The real type_offset is in the DWO file.  */
7159           dwo_tu = NULL;
7160           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7161                                      struct signatured_type);
7162           sig_type->signature = header.signature;
7163           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7164           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7165           sig_type->per_cu.is_debug_types = 1;
7166           sig_type->per_cu.section = section;
7167           sig_type->per_cu.sect_off = sect_off;
7168           sig_type->per_cu.length = length;
7169         }
7170
7171       slot = htab_find_slot (types_htab,
7172                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7173                              INSERT);
7174       gdb_assert (slot != NULL);
7175       if (*slot != NULL)
7176         {
7177           sect_offset dup_sect_off;
7178
7179           if (dwo_file)
7180             {
7181               const struct dwo_unit *dup_tu
7182                 = (const struct dwo_unit *) *slot;
7183
7184               dup_sect_off = dup_tu->sect_off;
7185             }
7186           else
7187             {
7188               const struct signatured_type *dup_tu
7189                 = (const struct signatured_type *) *slot;
7190
7191               dup_sect_off = dup_tu->per_cu.sect_off;
7192             }
7193
7194           complaint (&symfile_complaints,
7195                      _("debug type entry at offset %s is duplicate to"
7196                        " the entry at offset %s, signature %s"),
7197                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
7198                      hex_string (header.signature));
7199         }
7200       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7201
7202       if (dwarf_read_debug > 1)
7203         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
7204                             sect_offset_str (sect_off),
7205                             hex_string (header.signature));
7206
7207       info_ptr += length;
7208     }
7209 }
7210
7211 /* Create the hash table of all entries in the .debug_types
7212    (or .debug_types.dwo) section(s).
7213    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7214    otherwise it is NULL.
7215
7216    The result is a pointer to the hash table or NULL if there are no types.
7217
7218    Note: This function processes DWO files only, not DWP files.  */
7219
7220 static void
7221 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7222                                struct dwo_file *dwo_file,
7223                                VEC (dwarf2_section_info_def) *types,
7224                                htab_t &types_htab)
7225 {
7226   int ix;
7227   struct dwarf2_section_info *section;
7228
7229   if (VEC_empty (dwarf2_section_info_def, types))
7230     return;
7231
7232   for (ix = 0;
7233        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7234        ++ix)
7235     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7236                                   types_htab, rcuh_kind::TYPE);
7237 }
7238
7239 /* Create the hash table of all entries in the .debug_types section,
7240    and initialize all_type_units.
7241    The result is zero if there is an error (e.g. missing .debug_types section),
7242    otherwise non-zero.  */
7243
7244 static int
7245 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7246 {
7247   htab_t types_htab = NULL;
7248   struct signatured_type **iter;
7249
7250   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7251                                 &dwarf2_per_objfile->info, types_htab,
7252                                 rcuh_kind::COMPILE);
7253   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7254                                  dwarf2_per_objfile->types, types_htab);
7255   if (types_htab == NULL)
7256     {
7257       dwarf2_per_objfile->signatured_types = NULL;
7258       return 0;
7259     }
7260
7261   dwarf2_per_objfile->signatured_types = types_htab;
7262
7263   dwarf2_per_objfile->n_type_units
7264     = dwarf2_per_objfile->n_allocated_type_units
7265     = htab_elements (types_htab);
7266   dwarf2_per_objfile->all_type_units =
7267     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7268   iter = &dwarf2_per_objfile->all_type_units[0];
7269   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7270   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7271               == dwarf2_per_objfile->n_type_units);
7272
7273   return 1;
7274 }
7275
7276 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7277    If SLOT is non-NULL, it is the entry to use in the hash table.
7278    Otherwise we find one.  */
7279
7280 static struct signatured_type *
7281 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7282                void **slot)
7283 {
7284   struct objfile *objfile = dwarf2_per_objfile->objfile;
7285   int n_type_units = dwarf2_per_objfile->n_type_units;
7286   struct signatured_type *sig_type;
7287
7288   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7289   ++n_type_units;
7290   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7291     {
7292       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7293         dwarf2_per_objfile->n_allocated_type_units = 1;
7294       dwarf2_per_objfile->n_allocated_type_units *= 2;
7295       dwarf2_per_objfile->all_type_units
7296         = XRESIZEVEC (struct signatured_type *,
7297                       dwarf2_per_objfile->all_type_units,
7298                       dwarf2_per_objfile->n_allocated_type_units);
7299       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7300     }
7301   dwarf2_per_objfile->n_type_units = n_type_units;
7302
7303   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7304                              struct signatured_type);
7305   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7306   sig_type->signature = sig;
7307   sig_type->per_cu.is_debug_types = 1;
7308   if (dwarf2_per_objfile->using_index)
7309     {
7310       sig_type->per_cu.v.quick =
7311         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7312                         struct dwarf2_per_cu_quick_data);
7313     }
7314
7315   if (slot == NULL)
7316     {
7317       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7318                              sig_type, INSERT);
7319     }
7320   gdb_assert (*slot == NULL);
7321   *slot = sig_type;
7322   /* The rest of sig_type must be filled in by the caller.  */
7323   return sig_type;
7324 }
7325
7326 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7327    Fill in SIG_ENTRY with DWO_ENTRY.  */
7328
7329 static void
7330 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7331                                   struct signatured_type *sig_entry,
7332                                   struct dwo_unit *dwo_entry)
7333 {
7334   /* Make sure we're not clobbering something we don't expect to.  */
7335   gdb_assert (! sig_entry->per_cu.queued);
7336   gdb_assert (sig_entry->per_cu.cu == NULL);
7337   if (dwarf2_per_objfile->using_index)
7338     {
7339       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7340       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7341     }
7342   else
7343       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7344   gdb_assert (sig_entry->signature == dwo_entry->signature);
7345   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7346   gdb_assert (sig_entry->type_unit_group == NULL);
7347   gdb_assert (sig_entry->dwo_unit == NULL);
7348
7349   sig_entry->per_cu.section = dwo_entry->section;
7350   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7351   sig_entry->per_cu.length = dwo_entry->length;
7352   sig_entry->per_cu.reading_dwo_directly = 1;
7353   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7354   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7355   sig_entry->dwo_unit = dwo_entry;
7356 }
7357
7358 /* Subroutine of lookup_signatured_type.
7359    If we haven't read the TU yet, create the signatured_type data structure
7360    for a TU to be read in directly from a DWO file, bypassing the stub.
7361    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7362    using .gdb_index, then when reading a CU we want to stay in the DWO file
7363    containing that CU.  Otherwise we could end up reading several other DWO
7364    files (due to comdat folding) to process the transitive closure of all the
7365    mentioned TUs, and that can be slow.  The current DWO file will have every
7366    type signature that it needs.
7367    We only do this for .gdb_index because in the psymtab case we already have
7368    to read all the DWOs to build the type unit groups.  */
7369
7370 static struct signatured_type *
7371 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7372 {
7373   struct dwarf2_per_objfile *dwarf2_per_objfile
7374     = cu->per_cu->dwarf2_per_objfile;
7375   struct objfile *objfile = dwarf2_per_objfile->objfile;
7376   struct dwo_file *dwo_file;
7377   struct dwo_unit find_dwo_entry, *dwo_entry;
7378   struct signatured_type find_sig_entry, *sig_entry;
7379   void **slot;
7380
7381   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7382
7383   /* If TU skeletons have been removed then we may not have read in any
7384      TUs yet.  */
7385   if (dwarf2_per_objfile->signatured_types == NULL)
7386     {
7387       dwarf2_per_objfile->signatured_types
7388         = allocate_signatured_type_table (objfile);
7389     }
7390
7391   /* We only ever need to read in one copy of a signatured type.
7392      Use the global signatured_types array to do our own comdat-folding
7393      of types.  If this is the first time we're reading this TU, and
7394      the TU has an entry in .gdb_index, replace the recorded data from
7395      .gdb_index with this TU.  */
7396
7397   find_sig_entry.signature = sig;
7398   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7399                          &find_sig_entry, INSERT);
7400   sig_entry = (struct signatured_type *) *slot;
7401
7402   /* We can get here with the TU already read, *or* in the process of being
7403      read.  Don't reassign the global entry to point to this DWO if that's
7404      the case.  Also note that if the TU is already being read, it may not
7405      have come from a DWO, the program may be a mix of Fission-compiled
7406      code and non-Fission-compiled code.  */
7407
7408   /* Have we already tried to read this TU?
7409      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7410      needn't exist in the global table yet).  */
7411   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7412     return sig_entry;
7413
7414   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7415      dwo_unit of the TU itself.  */
7416   dwo_file = cu->dwo_unit->dwo_file;
7417
7418   /* Ok, this is the first time we're reading this TU.  */
7419   if (dwo_file->tus == NULL)
7420     return NULL;
7421   find_dwo_entry.signature = sig;
7422   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7423   if (dwo_entry == NULL)
7424     return NULL;
7425
7426   /* If the global table doesn't have an entry for this TU, add one.  */
7427   if (sig_entry == NULL)
7428     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7429
7430   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7431   sig_entry->per_cu.tu_read = 1;
7432   return sig_entry;
7433 }
7434
7435 /* Subroutine of lookup_signatured_type.
7436    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7437    then try the DWP file.  If the TU stub (skeleton) has been removed then
7438    it won't be in .gdb_index.  */
7439
7440 static struct signatured_type *
7441 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7442 {
7443   struct dwarf2_per_objfile *dwarf2_per_objfile
7444     = cu->per_cu->dwarf2_per_objfile;
7445   struct objfile *objfile = dwarf2_per_objfile->objfile;
7446   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7447   struct dwo_unit *dwo_entry;
7448   struct signatured_type find_sig_entry, *sig_entry;
7449   void **slot;
7450
7451   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7452   gdb_assert (dwp_file != NULL);
7453
7454   /* If TU skeletons have been removed then we may not have read in any
7455      TUs yet.  */
7456   if (dwarf2_per_objfile->signatured_types == NULL)
7457     {
7458       dwarf2_per_objfile->signatured_types
7459         = allocate_signatured_type_table (objfile);
7460     }
7461
7462   find_sig_entry.signature = sig;
7463   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7464                          &find_sig_entry, INSERT);
7465   sig_entry = (struct signatured_type *) *slot;
7466
7467   /* Have we already tried to read this TU?
7468      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7469      needn't exist in the global table yet).  */
7470   if (sig_entry != NULL)
7471     return sig_entry;
7472
7473   if (dwp_file->tus == NULL)
7474     return NULL;
7475   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7476                                       sig, 1 /* is_debug_types */);
7477   if (dwo_entry == NULL)
7478     return NULL;
7479
7480   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7481   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7482
7483   return sig_entry;
7484 }
7485
7486 /* Lookup a signature based type for DW_FORM_ref_sig8.
7487    Returns NULL if signature SIG is not present in the table.
7488    It is up to the caller to complain about this.  */
7489
7490 static struct signatured_type *
7491 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7492 {
7493   struct dwarf2_per_objfile *dwarf2_per_objfile
7494     = cu->per_cu->dwarf2_per_objfile;
7495
7496   if (cu->dwo_unit
7497       && dwarf2_per_objfile->using_index)
7498     {
7499       /* We're in a DWO/DWP file, and we're using .gdb_index.
7500          These cases require special processing.  */
7501       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7502         return lookup_dwo_signatured_type (cu, sig);
7503       else
7504         return lookup_dwp_signatured_type (cu, sig);
7505     }
7506   else
7507     {
7508       struct signatured_type find_entry, *entry;
7509
7510       if (dwarf2_per_objfile->signatured_types == NULL)
7511         return NULL;
7512       find_entry.signature = sig;
7513       entry = ((struct signatured_type *)
7514                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7515       return entry;
7516     }
7517 }
7518 \f
7519 /* Low level DIE reading support.  */
7520
7521 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7522
7523 static void
7524 init_cu_die_reader (struct die_reader_specs *reader,
7525                     struct dwarf2_cu *cu,
7526                     struct dwarf2_section_info *section,
7527                     struct dwo_file *dwo_file,
7528                     struct abbrev_table *abbrev_table)
7529 {
7530   gdb_assert (section->readin && section->buffer != NULL);
7531   reader->abfd = get_section_bfd_owner (section);
7532   reader->cu = cu;
7533   reader->dwo_file = dwo_file;
7534   reader->die_section = section;
7535   reader->buffer = section->buffer;
7536   reader->buffer_end = section->buffer + section->size;
7537   reader->comp_dir = NULL;
7538   reader->abbrev_table = abbrev_table;
7539 }
7540
7541 /* Subroutine of init_cutu_and_read_dies to simplify it.
7542    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7543    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7544    already.
7545
7546    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7547    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7548    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7549    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7550    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7551    STUB_COMP_DIR may be non-NULL.
7552    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7553    are filled in with the info of the DIE from the DWO file.
7554    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7555    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7556    kept around for at least as long as *RESULT_READER.
7557
7558    The result is non-zero if a valid (non-dummy) DIE was found.  */
7559
7560 static int
7561 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7562                         struct dwo_unit *dwo_unit,
7563                         struct die_info *stub_comp_unit_die,
7564                         const char *stub_comp_dir,
7565                         struct die_reader_specs *result_reader,
7566                         const gdb_byte **result_info_ptr,
7567                         struct die_info **result_comp_unit_die,
7568                         int *result_has_children,
7569                         abbrev_table_up *result_dwo_abbrev_table)
7570 {
7571   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7572   struct objfile *objfile = dwarf2_per_objfile->objfile;
7573   struct dwarf2_cu *cu = this_cu->cu;
7574   bfd *abfd;
7575   const gdb_byte *begin_info_ptr, *info_ptr;
7576   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7577   int i,num_extra_attrs;
7578   struct dwarf2_section_info *dwo_abbrev_section;
7579   struct attribute *attr;
7580   struct die_info *comp_unit_die;
7581
7582   /* At most one of these may be provided.  */
7583   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7584
7585   /* These attributes aren't processed until later:
7586      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7587      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7588      referenced later.  However, these attributes are found in the stub
7589      which we won't have later.  In order to not impose this complication
7590      on the rest of the code, we read them here and copy them to the
7591      DWO CU/TU die.  */
7592
7593   stmt_list = NULL;
7594   low_pc = NULL;
7595   high_pc = NULL;
7596   ranges = NULL;
7597   comp_dir = NULL;
7598
7599   if (stub_comp_unit_die != NULL)
7600     {
7601       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7602          DWO file.  */
7603       if (! this_cu->is_debug_types)
7604         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7605       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7606       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7607       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7608       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7609
7610       /* There should be a DW_AT_addr_base attribute here (if needed).
7611          We need the value before we can process DW_FORM_GNU_addr_index.  */
7612       cu->addr_base = 0;
7613       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7614       if (attr)
7615         cu->addr_base = DW_UNSND (attr);
7616
7617       /* There should be a DW_AT_ranges_base attribute here (if needed).
7618          We need the value before we can process DW_AT_ranges.  */
7619       cu->ranges_base = 0;
7620       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7621       if (attr)
7622         cu->ranges_base = DW_UNSND (attr);
7623     }
7624   else if (stub_comp_dir != NULL)
7625     {
7626       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7627       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7628       comp_dir->name = DW_AT_comp_dir;
7629       comp_dir->form = DW_FORM_string;
7630       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7631       DW_STRING (comp_dir) = stub_comp_dir;
7632     }
7633
7634   /* Set up for reading the DWO CU/TU.  */
7635   cu->dwo_unit = dwo_unit;
7636   dwarf2_section_info *section = dwo_unit->section;
7637   dwarf2_read_section (objfile, section);
7638   abfd = get_section_bfd_owner (section);
7639   begin_info_ptr = info_ptr = (section->buffer
7640                                + to_underlying (dwo_unit->sect_off));
7641   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7642
7643   if (this_cu->is_debug_types)
7644     {
7645       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7646
7647       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7648                                                 &cu->header, section,
7649                                                 dwo_abbrev_section,
7650                                                 info_ptr, rcuh_kind::TYPE);
7651       /* This is not an assert because it can be caused by bad debug info.  */
7652       if (sig_type->signature != cu->header.signature)
7653         {
7654           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7655                    " TU at offset %s [in module %s]"),
7656                  hex_string (sig_type->signature),
7657                  hex_string (cu->header.signature),
7658                  sect_offset_str (dwo_unit->sect_off),
7659                  bfd_get_filename (abfd));
7660         }
7661       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7662       /* For DWOs coming from DWP files, we don't know the CU length
7663          nor the type's offset in the TU until now.  */
7664       dwo_unit->length = get_cu_length (&cu->header);
7665       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7666
7667       /* Establish the type offset that can be used to lookup the type.
7668          For DWO files, we don't know it until now.  */
7669       sig_type->type_offset_in_section
7670         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7671     }
7672   else
7673     {
7674       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7675                                                 &cu->header, section,
7676                                                 dwo_abbrev_section,
7677                                                 info_ptr, rcuh_kind::COMPILE);
7678       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7679       /* For DWOs coming from DWP files, we don't know the CU length
7680          until now.  */
7681       dwo_unit->length = get_cu_length (&cu->header);
7682     }
7683
7684   *result_dwo_abbrev_table
7685     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7686                                cu->header.abbrev_sect_off);
7687   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7688                       result_dwo_abbrev_table->get ());
7689
7690   /* Read in the die, but leave space to copy over the attributes
7691      from the stub.  This has the benefit of simplifying the rest of
7692      the code - all the work to maintain the illusion of a single
7693      DW_TAG_{compile,type}_unit DIE is done here.  */
7694   num_extra_attrs = ((stmt_list != NULL)
7695                      + (low_pc != NULL)
7696                      + (high_pc != NULL)
7697                      + (ranges != NULL)
7698                      + (comp_dir != NULL));
7699   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7700                               result_has_children, num_extra_attrs);
7701
7702   /* Copy over the attributes from the stub to the DIE we just read in.  */
7703   comp_unit_die = *result_comp_unit_die;
7704   i = comp_unit_die->num_attrs;
7705   if (stmt_list != NULL)
7706     comp_unit_die->attrs[i++] = *stmt_list;
7707   if (low_pc != NULL)
7708     comp_unit_die->attrs[i++] = *low_pc;
7709   if (high_pc != NULL)
7710     comp_unit_die->attrs[i++] = *high_pc;
7711   if (ranges != NULL)
7712     comp_unit_die->attrs[i++] = *ranges;
7713   if (comp_dir != NULL)
7714     comp_unit_die->attrs[i++] = *comp_dir;
7715   comp_unit_die->num_attrs += num_extra_attrs;
7716
7717   if (dwarf_die_debug)
7718     {
7719       fprintf_unfiltered (gdb_stdlog,
7720                           "Read die from %s@0x%x of %s:\n",
7721                           get_section_name (section),
7722                           (unsigned) (begin_info_ptr - section->buffer),
7723                           bfd_get_filename (abfd));
7724       dump_die (comp_unit_die, dwarf_die_debug);
7725     }
7726
7727   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7728      TUs by skipping the stub and going directly to the entry in the DWO file.
7729      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7730      to get it via circuitous means.  Blech.  */
7731   if (comp_dir != NULL)
7732     result_reader->comp_dir = DW_STRING (comp_dir);
7733
7734   /* Skip dummy compilation units.  */
7735   if (info_ptr >= begin_info_ptr + dwo_unit->length
7736       || peek_abbrev_code (abfd, info_ptr) == 0)
7737     return 0;
7738
7739   *result_info_ptr = info_ptr;
7740   return 1;
7741 }
7742
7743 /* Subroutine of init_cutu_and_read_dies to simplify it.
7744    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7745    Returns NULL if the specified DWO unit cannot be found.  */
7746
7747 static struct dwo_unit *
7748 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7749                  struct die_info *comp_unit_die)
7750 {
7751   struct dwarf2_cu *cu = this_cu->cu;
7752   ULONGEST signature;
7753   struct dwo_unit *dwo_unit;
7754   const char *comp_dir, *dwo_name;
7755
7756   gdb_assert (cu != NULL);
7757
7758   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7759   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7760   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7761
7762   if (this_cu->is_debug_types)
7763     {
7764       struct signatured_type *sig_type;
7765
7766       /* Since this_cu is the first member of struct signatured_type,
7767          we can go from a pointer to one to a pointer to the other.  */
7768       sig_type = (struct signatured_type *) this_cu;
7769       signature = sig_type->signature;
7770       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7771     }
7772   else
7773     {
7774       struct attribute *attr;
7775
7776       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7777       if (! attr)
7778         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7779                  " [in module %s]"),
7780                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7781       signature = DW_UNSND (attr);
7782       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7783                                        signature);
7784     }
7785
7786   return dwo_unit;
7787 }
7788
7789 /* Subroutine of init_cutu_and_read_dies to simplify it.
7790    See it for a description of the parameters.
7791    Read a TU directly from a DWO file, bypassing the stub.  */
7792
7793 static void
7794 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7795                            int use_existing_cu, int keep,
7796                            die_reader_func_ftype *die_reader_func,
7797                            void *data)
7798 {
7799   std::unique_ptr<dwarf2_cu> new_cu;
7800   struct signatured_type *sig_type;
7801   struct die_reader_specs reader;
7802   const gdb_byte *info_ptr;
7803   struct die_info *comp_unit_die;
7804   int has_children;
7805   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7806
7807   /* Verify we can do the following downcast, and that we have the
7808      data we need.  */
7809   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7810   sig_type = (struct signatured_type *) this_cu;
7811   gdb_assert (sig_type->dwo_unit != NULL);
7812
7813   if (use_existing_cu && this_cu->cu != NULL)
7814     {
7815       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7816       /* There's no need to do the rereading_dwo_cu handling that
7817          init_cutu_and_read_dies does since we don't read the stub.  */
7818     }
7819   else
7820     {
7821       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7822       gdb_assert (this_cu->cu == NULL);
7823       new_cu.reset (new dwarf2_cu (this_cu));
7824     }
7825
7826   /* A future optimization, if needed, would be to use an existing
7827      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7828      could share abbrev tables.  */
7829
7830   /* The abbreviation table used by READER, this must live at least as long as
7831      READER.  */
7832   abbrev_table_up dwo_abbrev_table;
7833
7834   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7835                               NULL /* stub_comp_unit_die */,
7836                               sig_type->dwo_unit->dwo_file->comp_dir,
7837                               &reader, &info_ptr,
7838                               &comp_unit_die, &has_children,
7839                               &dwo_abbrev_table) == 0)
7840     {
7841       /* Dummy die.  */
7842       return;
7843     }
7844
7845   /* All the "real" work is done here.  */
7846   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7847
7848   /* This duplicates the code in init_cutu_and_read_dies,
7849      but the alternative is making the latter more complex.
7850      This function is only for the special case of using DWO files directly:
7851      no point in overly complicating the general case just to handle this.  */
7852   if (new_cu != NULL && keep)
7853     {
7854       /* Link this CU into read_in_chain.  */
7855       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7856       dwarf2_per_objfile->read_in_chain = this_cu;
7857       /* The chain owns it now.  */
7858       new_cu.release ();
7859     }
7860 }
7861
7862 /* Initialize a CU (or TU) and read its DIEs.
7863    If the CU defers to a DWO file, read the DWO file as well.
7864
7865    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7866    Otherwise the table specified in the comp unit header is read in and used.
7867    This is an optimization for when we already have the abbrev table.
7868
7869    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7870    Otherwise, a new CU is allocated with xmalloc.
7871
7872    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7873    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7874
7875    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7876    linker) then DIE_READER_FUNC will not get called.  */
7877
7878 static void
7879 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7880                          struct abbrev_table *abbrev_table,
7881                          int use_existing_cu, int keep,
7882                          die_reader_func_ftype *die_reader_func,
7883                          void *data)
7884 {
7885   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7886   struct objfile *objfile = dwarf2_per_objfile->objfile;
7887   struct dwarf2_section_info *section = this_cu->section;
7888   bfd *abfd = get_section_bfd_owner (section);
7889   struct dwarf2_cu *cu;
7890   const gdb_byte *begin_info_ptr, *info_ptr;
7891   struct die_reader_specs reader;
7892   struct die_info *comp_unit_die;
7893   int has_children;
7894   struct attribute *attr;
7895   struct signatured_type *sig_type = NULL;
7896   struct dwarf2_section_info *abbrev_section;
7897   /* Non-zero if CU currently points to a DWO file and we need to
7898      reread it.  When this happens we need to reread the skeleton die
7899      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7900   int rereading_dwo_cu = 0;
7901
7902   if (dwarf_die_debug)
7903     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7904                         this_cu->is_debug_types ? "type" : "comp",
7905                         sect_offset_str (this_cu->sect_off));
7906
7907   if (use_existing_cu)
7908     gdb_assert (keep);
7909
7910   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7911      file (instead of going through the stub), short-circuit all of this.  */
7912   if (this_cu->reading_dwo_directly)
7913     {
7914       /* Narrow down the scope of possibilities to have to understand.  */
7915       gdb_assert (this_cu->is_debug_types);
7916       gdb_assert (abbrev_table == NULL);
7917       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7918                                  die_reader_func, data);
7919       return;
7920     }
7921
7922   /* This is cheap if the section is already read in.  */
7923   dwarf2_read_section (objfile, section);
7924
7925   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7926
7927   abbrev_section = get_abbrev_section_for_cu (this_cu);
7928
7929   std::unique_ptr<dwarf2_cu> new_cu;
7930   if (use_existing_cu && this_cu->cu != NULL)
7931     {
7932       cu = this_cu->cu;
7933       /* If this CU is from a DWO file we need to start over, we need to
7934          refetch the attributes from the skeleton CU.
7935          This could be optimized by retrieving those attributes from when we
7936          were here the first time: the previous comp_unit_die was stored in
7937          comp_unit_obstack.  But there's no data yet that we need this
7938          optimization.  */
7939       if (cu->dwo_unit != NULL)
7940         rereading_dwo_cu = 1;
7941     }
7942   else
7943     {
7944       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7945       gdb_assert (this_cu->cu == NULL);
7946       new_cu.reset (new dwarf2_cu (this_cu));
7947       cu = new_cu.get ();
7948     }
7949
7950   /* Get the header.  */
7951   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7952     {
7953       /* We already have the header, there's no need to read it in again.  */
7954       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7955     }
7956   else
7957     {
7958       if (this_cu->is_debug_types)
7959         {
7960           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7961                                                     &cu->header, section,
7962                                                     abbrev_section, info_ptr,
7963                                                     rcuh_kind::TYPE);
7964
7965           /* Since per_cu is the first member of struct signatured_type,
7966              we can go from a pointer to one to a pointer to the other.  */
7967           sig_type = (struct signatured_type *) this_cu;
7968           gdb_assert (sig_type->signature == cu->header.signature);
7969           gdb_assert (sig_type->type_offset_in_tu
7970                       == cu->header.type_cu_offset_in_tu);
7971           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7972
7973           /* LENGTH has not been set yet for type units if we're
7974              using .gdb_index.  */
7975           this_cu->length = get_cu_length (&cu->header);
7976
7977           /* Establish the type offset that can be used to lookup the type.  */
7978           sig_type->type_offset_in_section =
7979             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7980
7981           this_cu->dwarf_version = cu->header.version;
7982         }
7983       else
7984         {
7985           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7986                                                     &cu->header, section,
7987                                                     abbrev_section,
7988                                                     info_ptr,
7989                                                     rcuh_kind::COMPILE);
7990
7991           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7992           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7993           this_cu->dwarf_version = cu->header.version;
7994         }
7995     }
7996
7997   /* Skip dummy compilation units.  */
7998   if (info_ptr >= begin_info_ptr + this_cu->length
7999       || peek_abbrev_code (abfd, info_ptr) == 0)
8000     return;
8001
8002   /* If we don't have them yet, read the abbrevs for this compilation unit.
8003      And if we need to read them now, make sure they're freed when we're
8004      done (own the table through ABBREV_TABLE_HOLDER).  */
8005   abbrev_table_up abbrev_table_holder;
8006   if (abbrev_table != NULL)
8007     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
8008   else
8009     {
8010       abbrev_table_holder
8011         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8012                                    cu->header.abbrev_sect_off);
8013       abbrev_table = abbrev_table_holder.get ();
8014     }
8015
8016   /* Read the top level CU/TU die.  */
8017   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
8018   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8019
8020   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
8021      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
8022      table from the DWO file and pass the ownership over to us.  It will be
8023      referenced from READER, so we must make sure to free it after we're done
8024      with READER.
8025
8026      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
8027      DWO CU, that this test will fail (the attribute will not be present).  */
8028   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
8029   abbrev_table_up dwo_abbrev_table;
8030   if (attr)
8031     {
8032       struct dwo_unit *dwo_unit;
8033       struct die_info *dwo_comp_unit_die;
8034
8035       if (has_children)
8036         {
8037           complaint (&symfile_complaints,
8038                      _("compilation unit with DW_AT_GNU_dwo_name"
8039                        " has children (offset %s) [in module %s]"),
8040                      sect_offset_str (this_cu->sect_off),
8041                      bfd_get_filename (abfd));
8042         }
8043       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
8044       if (dwo_unit != NULL)
8045         {
8046           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
8047                                       comp_unit_die, NULL,
8048                                       &reader, &info_ptr,
8049                                       &dwo_comp_unit_die, &has_children,
8050                                       &dwo_abbrev_table) == 0)
8051             {
8052               /* Dummy die.  */
8053               return;
8054             }
8055           comp_unit_die = dwo_comp_unit_die;
8056         }
8057       else
8058         {
8059           /* Yikes, we couldn't find the rest of the DIE, we only have
8060              the stub.  A complaint has already been logged.  There's
8061              not much more we can do except pass on the stub DIE to
8062              die_reader_func.  We don't want to throw an error on bad
8063              debug info.  */
8064         }
8065     }
8066
8067   /* All of the above is setup for this call.  Yikes.  */
8068   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8069
8070   /* Done, clean up.  */
8071   if (new_cu != NULL && keep)
8072     {
8073       /* Link this CU into read_in_chain.  */
8074       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8075       dwarf2_per_objfile->read_in_chain = this_cu;
8076       /* The chain owns it now.  */
8077       new_cu.release ();
8078     }
8079 }
8080
8081 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8082    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8083    to have already done the lookup to find the DWO file).
8084
8085    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8086    THIS_CU->is_debug_types, but nothing else.
8087
8088    We fill in THIS_CU->length.
8089
8090    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8091    linker) then DIE_READER_FUNC will not get called.
8092
8093    THIS_CU->cu is always freed when done.
8094    This is done in order to not leave THIS_CU->cu in a state where we have
8095    to care whether it refers to the "main" CU or the DWO CU.  */
8096
8097 static void
8098 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8099                                    struct dwo_file *dwo_file,
8100                                    die_reader_func_ftype *die_reader_func,
8101                                    void *data)
8102 {
8103   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8104   struct objfile *objfile = dwarf2_per_objfile->objfile;
8105   struct dwarf2_section_info *section = this_cu->section;
8106   bfd *abfd = get_section_bfd_owner (section);
8107   struct dwarf2_section_info *abbrev_section;
8108   const gdb_byte *begin_info_ptr, *info_ptr;
8109   struct die_reader_specs reader;
8110   struct die_info *comp_unit_die;
8111   int has_children;
8112
8113   if (dwarf_die_debug)
8114     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
8115                         this_cu->is_debug_types ? "type" : "comp",
8116                         sect_offset_str (this_cu->sect_off));
8117
8118   gdb_assert (this_cu->cu == NULL);
8119
8120   abbrev_section = (dwo_file != NULL
8121                     ? &dwo_file->sections.abbrev
8122                     : get_abbrev_section_for_cu (this_cu));
8123
8124   /* This is cheap if the section is already read in.  */
8125   dwarf2_read_section (objfile, section);
8126
8127   struct dwarf2_cu cu (this_cu);
8128
8129   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8130   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8131                                             &cu.header, section,
8132                                             abbrev_section, info_ptr,
8133                                             (this_cu->is_debug_types
8134                                              ? rcuh_kind::TYPE
8135                                              : rcuh_kind::COMPILE));
8136
8137   this_cu->length = get_cu_length (&cu.header);
8138
8139   /* Skip dummy compilation units.  */
8140   if (info_ptr >= begin_info_ptr + this_cu->length
8141       || peek_abbrev_code (abfd, info_ptr) == 0)
8142     return;
8143
8144   abbrev_table_up abbrev_table
8145     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8146                                cu.header.abbrev_sect_off);
8147
8148   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8149   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8150
8151   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8152 }
8153
8154 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8155    does not lookup the specified DWO file.
8156    This cannot be used to read DWO files.
8157
8158    THIS_CU->cu is always freed when done.
8159    This is done in order to not leave THIS_CU->cu in a state where we have
8160    to care whether it refers to the "main" CU or the DWO CU.
8161    We can revisit this if the data shows there's a performance issue.  */
8162
8163 static void
8164 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8165                                 die_reader_func_ftype *die_reader_func,
8166                                 void *data)
8167 {
8168   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8169 }
8170 \f
8171 /* Type Unit Groups.
8172
8173    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8174    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8175    so that all types coming from the same compilation (.o file) are grouped
8176    together.  A future step could be to put the types in the same symtab as
8177    the CU the types ultimately came from.  */
8178
8179 static hashval_t
8180 hash_type_unit_group (const void *item)
8181 {
8182   const struct type_unit_group *tu_group
8183     = (const struct type_unit_group *) item;
8184
8185   return hash_stmt_list_entry (&tu_group->hash);
8186 }
8187
8188 static int
8189 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8190 {
8191   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8192   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8193
8194   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8195 }
8196
8197 /* Allocate a hash table for type unit groups.  */
8198
8199 static htab_t
8200 allocate_type_unit_groups_table (struct objfile *objfile)
8201 {
8202   return htab_create_alloc_ex (3,
8203                                hash_type_unit_group,
8204                                eq_type_unit_group,
8205                                NULL,
8206                                &objfile->objfile_obstack,
8207                                hashtab_obstack_allocate,
8208                                dummy_obstack_deallocate);
8209 }
8210
8211 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8212    partial symtabs.  We combine several TUs per psymtab to not let the size
8213    of any one psymtab grow too big.  */
8214 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8215 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8216
8217 /* Helper routine for get_type_unit_group.
8218    Create the type_unit_group object used to hold one or more TUs.  */
8219
8220 static struct type_unit_group *
8221 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8222 {
8223   struct dwarf2_per_objfile *dwarf2_per_objfile
8224     = cu->per_cu->dwarf2_per_objfile;
8225   struct objfile *objfile = dwarf2_per_objfile->objfile;
8226   struct dwarf2_per_cu_data *per_cu;
8227   struct type_unit_group *tu_group;
8228
8229   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8230                              struct type_unit_group);
8231   per_cu = &tu_group->per_cu;
8232   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8233
8234   if (dwarf2_per_objfile->using_index)
8235     {
8236       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8237                                         struct dwarf2_per_cu_quick_data);
8238     }
8239   else
8240     {
8241       unsigned int line_offset = to_underlying (line_offset_struct);
8242       struct partial_symtab *pst;
8243       char *name;
8244
8245       /* Give the symtab a useful name for debug purposes.  */
8246       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8247         name = xstrprintf ("<type_units_%d>",
8248                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8249       else
8250         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8251
8252       pst = create_partial_symtab (per_cu, name);
8253       pst->anonymous = 1;
8254
8255       xfree (name);
8256     }
8257
8258   tu_group->hash.dwo_unit = cu->dwo_unit;
8259   tu_group->hash.line_sect_off = line_offset_struct;
8260
8261   return tu_group;
8262 }
8263
8264 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8265    STMT_LIST is a DW_AT_stmt_list attribute.  */
8266
8267 static struct type_unit_group *
8268 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8269 {
8270   struct dwarf2_per_objfile *dwarf2_per_objfile
8271     = cu->per_cu->dwarf2_per_objfile;
8272   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8273   struct type_unit_group *tu_group;
8274   void **slot;
8275   unsigned int line_offset;
8276   struct type_unit_group type_unit_group_for_lookup;
8277
8278   if (dwarf2_per_objfile->type_unit_groups == NULL)
8279     {
8280       dwarf2_per_objfile->type_unit_groups =
8281         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8282     }
8283
8284   /* Do we need to create a new group, or can we use an existing one?  */
8285
8286   if (stmt_list)
8287     {
8288       line_offset = DW_UNSND (stmt_list);
8289       ++tu_stats->nr_symtab_sharers;
8290     }
8291   else
8292     {
8293       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8294          We can do various things here like create one group per TU or
8295          spread them over multiple groups to split up the expansion work.
8296          To avoid worst case scenarios (too many groups or too large groups)
8297          we, umm, group them in bunches.  */
8298       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8299                      | (tu_stats->nr_stmt_less_type_units
8300                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8301       ++tu_stats->nr_stmt_less_type_units;
8302     }
8303
8304   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8305   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8306   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8307                          &type_unit_group_for_lookup, INSERT);
8308   if (*slot != NULL)
8309     {
8310       tu_group = (struct type_unit_group *) *slot;
8311       gdb_assert (tu_group != NULL);
8312     }
8313   else
8314     {
8315       sect_offset line_offset_struct = (sect_offset) line_offset;
8316       tu_group = create_type_unit_group (cu, line_offset_struct);
8317       *slot = tu_group;
8318       ++tu_stats->nr_symtabs;
8319     }
8320
8321   return tu_group;
8322 }
8323 \f
8324 /* Partial symbol tables.  */
8325
8326 /* Create a psymtab named NAME and assign it to PER_CU.
8327
8328    The caller must fill in the following details:
8329    dirname, textlow, texthigh.  */
8330
8331 static struct partial_symtab *
8332 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8333 {
8334   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8335   struct partial_symtab *pst;
8336
8337   pst = start_psymtab_common (objfile, name, 0,
8338                               objfile->global_psymbols,
8339                               objfile->static_psymbols);
8340
8341   pst->psymtabs_addrmap_supported = 1;
8342
8343   /* This is the glue that links PST into GDB's symbol API.  */
8344   pst->read_symtab_private = per_cu;
8345   pst->read_symtab = dwarf2_read_symtab;
8346   per_cu->v.psymtab = pst;
8347
8348   return pst;
8349 }
8350
8351 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8352    type.  */
8353
8354 struct process_psymtab_comp_unit_data
8355 {
8356   /* True if we are reading a DW_TAG_partial_unit.  */
8357
8358   int want_partial_unit;
8359
8360   /* The "pretend" language that is used if the CU doesn't declare a
8361      language.  */
8362
8363   enum language pretend_language;
8364 };
8365
8366 /* die_reader_func for process_psymtab_comp_unit.  */
8367
8368 static void
8369 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8370                                   const gdb_byte *info_ptr,
8371                                   struct die_info *comp_unit_die,
8372                                   int has_children,
8373                                   void *data)
8374 {
8375   struct dwarf2_cu *cu = reader->cu;
8376   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8377   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8378   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8379   CORE_ADDR baseaddr;
8380   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8381   struct partial_symtab *pst;
8382   enum pc_bounds_kind cu_bounds_kind;
8383   const char *filename;
8384   struct process_psymtab_comp_unit_data *info
8385     = (struct process_psymtab_comp_unit_data *) data;
8386
8387   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8388     return;
8389
8390   gdb_assert (! per_cu->is_debug_types);
8391
8392   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8393
8394   cu->list_in_scope = &file_symbols;
8395
8396   /* Allocate a new partial symbol table structure.  */
8397   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8398   if (filename == NULL)
8399     filename = "";
8400
8401   pst = create_partial_symtab (per_cu, filename);
8402
8403   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8404   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8405
8406   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8407
8408   dwarf2_find_base_address (comp_unit_die, cu);
8409
8410   /* Possibly set the default values of LOWPC and HIGHPC from
8411      `DW_AT_ranges'.  */
8412   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8413                                          &best_highpc, cu, pst);
8414   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8415     /* Store the contiguous range if it is not empty; it can be empty for
8416        CUs with no code.  */
8417     addrmap_set_empty (objfile->psymtabs_addrmap,
8418                        gdbarch_adjust_dwarf2_addr (gdbarch,
8419                                                    best_lowpc + baseaddr),
8420                        gdbarch_adjust_dwarf2_addr (gdbarch,
8421                                                    best_highpc + baseaddr) - 1,
8422                        pst);
8423
8424   /* Check if comp unit has_children.
8425      If so, read the rest of the partial symbols from this comp unit.
8426      If not, there's no more debug_info for this comp unit.  */
8427   if (has_children)
8428     {
8429       struct partial_die_info *first_die;
8430       CORE_ADDR lowpc, highpc;
8431
8432       lowpc = ((CORE_ADDR) -1);
8433       highpc = ((CORE_ADDR) 0);
8434
8435       first_die = load_partial_dies (reader, info_ptr, 1);
8436
8437       scan_partial_symbols (first_die, &lowpc, &highpc,
8438                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8439
8440       /* If we didn't find a lowpc, set it to highpc to avoid
8441          complaints from `maint check'.  */
8442       if (lowpc == ((CORE_ADDR) -1))
8443         lowpc = highpc;
8444
8445       /* If the compilation unit didn't have an explicit address range,
8446          then use the information extracted from its child dies.  */
8447       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8448         {
8449           best_lowpc = lowpc;
8450           best_highpc = highpc;
8451         }
8452     }
8453   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8454   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8455
8456   end_psymtab_common (objfile, pst);
8457
8458   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8459     {
8460       int i;
8461       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8462       struct dwarf2_per_cu_data *iter;
8463
8464       /* Fill in 'dependencies' here; we fill in 'users' in a
8465          post-pass.  */
8466       pst->number_of_dependencies = len;
8467       pst->dependencies =
8468         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8469       for (i = 0;
8470            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8471                         i, iter);
8472            ++i)
8473         pst->dependencies[i] = iter->v.psymtab;
8474
8475       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8476     }
8477
8478   /* Get the list of files included in the current compilation unit,
8479      and build a psymtab for each of them.  */
8480   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8481
8482   if (dwarf_read_debug)
8483     {
8484       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8485
8486       fprintf_unfiltered (gdb_stdlog,
8487                           "Psymtab for %s unit @%s: %s - %s"
8488                           ", %d global, %d static syms\n",
8489                           per_cu->is_debug_types ? "type" : "comp",
8490                           sect_offset_str (per_cu->sect_off),
8491                           paddress (gdbarch, pst->textlow),
8492                           paddress (gdbarch, pst->texthigh),
8493                           pst->n_global_syms, pst->n_static_syms);
8494     }
8495 }
8496
8497 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8498    Process compilation unit THIS_CU for a psymtab.  */
8499
8500 static void
8501 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8502                            int want_partial_unit,
8503                            enum language pretend_language)
8504 {
8505   /* If this compilation unit was already read in, free the
8506      cached copy in order to read it in again.  This is
8507      necessary because we skipped some symbols when we first
8508      read in the compilation unit (see load_partial_dies).
8509      This problem could be avoided, but the benefit is unclear.  */
8510   if (this_cu->cu != NULL)
8511     free_one_cached_comp_unit (this_cu);
8512
8513   if (this_cu->is_debug_types)
8514     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8515                              NULL);
8516   else
8517     {
8518       process_psymtab_comp_unit_data info;
8519       info.want_partial_unit = want_partial_unit;
8520       info.pretend_language = pretend_language;
8521       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8522                                process_psymtab_comp_unit_reader, &info);
8523     }
8524
8525   /* Age out any secondary CUs.  */
8526   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8527 }
8528
8529 /* Reader function for build_type_psymtabs.  */
8530
8531 static void
8532 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8533                             const gdb_byte *info_ptr,
8534                             struct die_info *type_unit_die,
8535                             int has_children,
8536                             void *data)
8537 {
8538   struct dwarf2_per_objfile *dwarf2_per_objfile
8539     = reader->cu->per_cu->dwarf2_per_objfile;
8540   struct objfile *objfile = dwarf2_per_objfile->objfile;
8541   struct dwarf2_cu *cu = reader->cu;
8542   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8543   struct signatured_type *sig_type;
8544   struct type_unit_group *tu_group;
8545   struct attribute *attr;
8546   struct partial_die_info *first_die;
8547   CORE_ADDR lowpc, highpc;
8548   struct partial_symtab *pst;
8549
8550   gdb_assert (data == NULL);
8551   gdb_assert (per_cu->is_debug_types);
8552   sig_type = (struct signatured_type *) per_cu;
8553
8554   if (! has_children)
8555     return;
8556
8557   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8558   tu_group = get_type_unit_group (cu, attr);
8559
8560   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8561
8562   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8563   cu->list_in_scope = &file_symbols;
8564   pst = create_partial_symtab (per_cu, "");
8565   pst->anonymous = 1;
8566
8567   first_die = load_partial_dies (reader, info_ptr, 1);
8568
8569   lowpc = (CORE_ADDR) -1;
8570   highpc = (CORE_ADDR) 0;
8571   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8572
8573   end_psymtab_common (objfile, pst);
8574 }
8575
8576 /* Struct used to sort TUs by their abbreviation table offset.  */
8577
8578 struct tu_abbrev_offset
8579 {
8580   struct signatured_type *sig_type;
8581   sect_offset abbrev_offset;
8582 };
8583
8584 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8585
8586 static int
8587 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8588 {
8589   const struct tu_abbrev_offset * const *a
8590     = (const struct tu_abbrev_offset * const*) ap;
8591   const struct tu_abbrev_offset * const *b
8592     = (const struct tu_abbrev_offset * const*) bp;
8593   sect_offset aoff = (*a)->abbrev_offset;
8594   sect_offset boff = (*b)->abbrev_offset;
8595
8596   return (aoff > boff) - (aoff < boff);
8597 }
8598
8599 /* Efficiently read all the type units.
8600    This does the bulk of the work for build_type_psymtabs.
8601
8602    The efficiency is because we sort TUs by the abbrev table they use and
8603    only read each abbrev table once.  In one program there are 200K TUs
8604    sharing 8K abbrev tables.
8605
8606    The main purpose of this function is to support building the
8607    dwarf2_per_objfile->type_unit_groups table.
8608    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8609    can collapse the search space by grouping them by stmt_list.
8610    The savings can be significant, in the same program from above the 200K TUs
8611    share 8K stmt_list tables.
8612
8613    FUNC is expected to call get_type_unit_group, which will create the
8614    struct type_unit_group if necessary and add it to
8615    dwarf2_per_objfile->type_unit_groups.  */
8616
8617 static void
8618 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8619 {
8620   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8621   struct cleanup *cleanups;
8622   abbrev_table_up abbrev_table;
8623   sect_offset abbrev_offset;
8624   struct tu_abbrev_offset *sorted_by_abbrev;
8625   int i;
8626
8627   /* It's up to the caller to not call us multiple times.  */
8628   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8629
8630   if (dwarf2_per_objfile->n_type_units == 0)
8631     return;
8632
8633   /* TUs typically share abbrev tables, and there can be way more TUs than
8634      abbrev tables.  Sort by abbrev table to reduce the number of times we
8635      read each abbrev table in.
8636      Alternatives are to punt or to maintain a cache of abbrev tables.
8637      This is simpler and efficient enough for now.
8638
8639      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8640      symtab to use).  Typically TUs with the same abbrev offset have the same
8641      stmt_list value too so in practice this should work well.
8642
8643      The basic algorithm here is:
8644
8645       sort TUs by abbrev table
8646       for each TU with same abbrev table:
8647         read abbrev table if first user
8648         read TU top level DIE
8649           [IWBN if DWO skeletons had DW_AT_stmt_list]
8650         call FUNC  */
8651
8652   if (dwarf_read_debug)
8653     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8654
8655   /* Sort in a separate table to maintain the order of all_type_units
8656      for .gdb_index: TU indices directly index all_type_units.  */
8657   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8658                               dwarf2_per_objfile->n_type_units);
8659   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8660     {
8661       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8662
8663       sorted_by_abbrev[i].sig_type = sig_type;
8664       sorted_by_abbrev[i].abbrev_offset =
8665         read_abbrev_offset (dwarf2_per_objfile,
8666                             sig_type->per_cu.section,
8667                             sig_type->per_cu.sect_off);
8668     }
8669   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8670   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8671          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8672
8673   abbrev_offset = (sect_offset) ~(unsigned) 0;
8674
8675   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8676     {
8677       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8678
8679       /* Switch to the next abbrev table if necessary.  */
8680       if (abbrev_table == NULL
8681           || tu->abbrev_offset != abbrev_offset)
8682         {
8683           abbrev_offset = tu->abbrev_offset;
8684           abbrev_table =
8685             abbrev_table_read_table (dwarf2_per_objfile,
8686                                      &dwarf2_per_objfile->abbrev,
8687                                      abbrev_offset);
8688           ++tu_stats->nr_uniq_abbrev_tables;
8689         }
8690
8691       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8692                                0, 0, build_type_psymtabs_reader, NULL);
8693     }
8694
8695   do_cleanups (cleanups);
8696 }
8697
8698 /* Print collected type unit statistics.  */
8699
8700 static void
8701 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8702 {
8703   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8704
8705   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8706   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8707                       dwarf2_per_objfile->n_type_units);
8708   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8709                       tu_stats->nr_uniq_abbrev_tables);
8710   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8711                       tu_stats->nr_symtabs);
8712   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8713                       tu_stats->nr_symtab_sharers);
8714   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8715                       tu_stats->nr_stmt_less_type_units);
8716   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8717                       tu_stats->nr_all_type_units_reallocs);
8718 }
8719
8720 /* Traversal function for build_type_psymtabs.  */
8721
8722 static int
8723 build_type_psymtab_dependencies (void **slot, void *info)
8724 {
8725   struct dwarf2_per_objfile *dwarf2_per_objfile
8726     = (struct dwarf2_per_objfile *) info;
8727   struct objfile *objfile = dwarf2_per_objfile->objfile;
8728   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8729   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8730   struct partial_symtab *pst = per_cu->v.psymtab;
8731   int len = VEC_length (sig_type_ptr, tu_group->tus);
8732   struct signatured_type *iter;
8733   int i;
8734
8735   gdb_assert (len > 0);
8736   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8737
8738   pst->number_of_dependencies = len;
8739   pst->dependencies =
8740     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8741   for (i = 0;
8742        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8743        ++i)
8744     {
8745       gdb_assert (iter->per_cu.is_debug_types);
8746       pst->dependencies[i] = iter->per_cu.v.psymtab;
8747       iter->type_unit_group = tu_group;
8748     }
8749
8750   VEC_free (sig_type_ptr, tu_group->tus);
8751
8752   return 1;
8753 }
8754
8755 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8756    Build partial symbol tables for the .debug_types comp-units.  */
8757
8758 static void
8759 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8760 {
8761   if (! create_all_type_units (dwarf2_per_objfile))
8762     return;
8763
8764   build_type_psymtabs_1 (dwarf2_per_objfile);
8765 }
8766
8767 /* Traversal function for process_skeletonless_type_unit.
8768    Read a TU in a DWO file and build partial symbols for it.  */
8769
8770 static int
8771 process_skeletonless_type_unit (void **slot, void *info)
8772 {
8773   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8774   struct dwarf2_per_objfile *dwarf2_per_objfile
8775     = (struct dwarf2_per_objfile *) info;
8776   struct signatured_type find_entry, *entry;
8777
8778   /* If this TU doesn't exist in the global table, add it and read it in.  */
8779
8780   if (dwarf2_per_objfile->signatured_types == NULL)
8781     {
8782       dwarf2_per_objfile->signatured_types
8783         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8784     }
8785
8786   find_entry.signature = dwo_unit->signature;
8787   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8788                          INSERT);
8789   /* If we've already seen this type there's nothing to do.  What's happening
8790      is we're doing our own version of comdat-folding here.  */
8791   if (*slot != NULL)
8792     return 1;
8793
8794   /* This does the job that create_all_type_units would have done for
8795      this TU.  */
8796   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8797   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8798   *slot = entry;
8799
8800   /* This does the job that build_type_psymtabs_1 would have done.  */
8801   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8802                            build_type_psymtabs_reader, NULL);
8803
8804   return 1;
8805 }
8806
8807 /* Traversal function for process_skeletonless_type_units.  */
8808
8809 static int
8810 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8811 {
8812   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8813
8814   if (dwo_file->tus != NULL)
8815     {
8816       htab_traverse_noresize (dwo_file->tus,
8817                               process_skeletonless_type_unit, info);
8818     }
8819
8820   return 1;
8821 }
8822
8823 /* Scan all TUs of DWO files, verifying we've processed them.
8824    This is needed in case a TU was emitted without its skeleton.
8825    Note: This can't be done until we know what all the DWO files are.  */
8826
8827 static void
8828 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8829 {
8830   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8831   if (get_dwp_file (dwarf2_per_objfile) == NULL
8832       && dwarf2_per_objfile->dwo_files != NULL)
8833     {
8834       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8835                               process_dwo_file_for_skeletonless_type_units,
8836                               dwarf2_per_objfile);
8837     }
8838 }
8839
8840 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8841
8842 static void
8843 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8844 {
8845   int i;
8846
8847   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8848     {
8849       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8850       struct partial_symtab *pst = per_cu->v.psymtab;
8851       int j;
8852
8853       if (pst == NULL)
8854         continue;
8855
8856       for (j = 0; j < pst->number_of_dependencies; ++j)
8857         {
8858           /* Set the 'user' field only if it is not already set.  */
8859           if (pst->dependencies[j]->user == NULL)
8860             pst->dependencies[j]->user = pst;
8861         }
8862     }
8863 }
8864
8865 /* Build the partial symbol table by doing a quick pass through the
8866    .debug_info and .debug_abbrev sections.  */
8867
8868 static void
8869 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8870 {
8871   struct cleanup *back_to;
8872   int i;
8873   struct objfile *objfile = dwarf2_per_objfile->objfile;
8874
8875   if (dwarf_read_debug)
8876     {
8877       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8878                           objfile_name (objfile));
8879     }
8880
8881   dwarf2_per_objfile->reading_partial_symbols = 1;
8882
8883   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8884
8885   /* Any cached compilation units will be linked by the per-objfile
8886      read_in_chain.  Make sure to free them when we're done.  */
8887   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8888
8889   build_type_psymtabs (dwarf2_per_objfile);
8890
8891   create_all_comp_units (dwarf2_per_objfile);
8892
8893   /* Create a temporary address map on a temporary obstack.  We later
8894      copy this to the final obstack.  */
8895   auto_obstack temp_obstack;
8896
8897   scoped_restore save_psymtabs_addrmap
8898     = make_scoped_restore (&objfile->psymtabs_addrmap,
8899                            addrmap_create_mutable (&temp_obstack));
8900
8901   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8902     {
8903       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8904
8905       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8906     }
8907
8908   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8909   process_skeletonless_type_units (dwarf2_per_objfile);
8910
8911   /* Now that all TUs have been processed we can fill in the dependencies.  */
8912   if (dwarf2_per_objfile->type_unit_groups != NULL)
8913     {
8914       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8915                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8916     }
8917
8918   if (dwarf_read_debug)
8919     print_tu_stats (dwarf2_per_objfile);
8920
8921   set_partial_user (dwarf2_per_objfile);
8922
8923   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8924                                                     &objfile->objfile_obstack);
8925   /* At this point we want to keep the address map.  */
8926   save_psymtabs_addrmap.release ();
8927
8928   do_cleanups (back_to);
8929
8930   if (dwarf_read_debug)
8931     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8932                         objfile_name (objfile));
8933 }
8934
8935 /* die_reader_func for load_partial_comp_unit.  */
8936
8937 static void
8938 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8939                                const gdb_byte *info_ptr,
8940                                struct die_info *comp_unit_die,
8941                                int has_children,
8942                                void *data)
8943 {
8944   struct dwarf2_cu *cu = reader->cu;
8945
8946   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8947
8948   /* Check if comp unit has_children.
8949      If so, read the rest of the partial symbols from this comp unit.
8950      If not, there's no more debug_info for this comp unit.  */
8951   if (has_children)
8952     load_partial_dies (reader, info_ptr, 0);
8953 }
8954
8955 /* Load the partial DIEs for a secondary CU into memory.
8956    This is also used when rereading a primary CU with load_all_dies.  */
8957
8958 static void
8959 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8960 {
8961   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8962                            load_partial_comp_unit_reader, NULL);
8963 }
8964
8965 static void
8966 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8967                               struct dwarf2_section_info *section,
8968                               struct dwarf2_section_info *abbrev_section,
8969                               unsigned int is_dwz,
8970                               int *n_allocated,
8971                               int *n_comp_units,
8972                               struct dwarf2_per_cu_data ***all_comp_units)
8973 {
8974   const gdb_byte *info_ptr;
8975   struct objfile *objfile = dwarf2_per_objfile->objfile;
8976
8977   if (dwarf_read_debug)
8978     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8979                         get_section_name (section),
8980                         get_section_file_name (section));
8981
8982   dwarf2_read_section (objfile, section);
8983
8984   info_ptr = section->buffer;
8985
8986   while (info_ptr < section->buffer + section->size)
8987     {
8988       struct dwarf2_per_cu_data *this_cu;
8989
8990       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8991
8992       comp_unit_head cu_header;
8993       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8994                                      abbrev_section, info_ptr,
8995                                      rcuh_kind::COMPILE);
8996
8997       /* Save the compilation unit for later lookup.  */
8998       if (cu_header.unit_type != DW_UT_type)
8999         {
9000           this_cu = XOBNEW (&objfile->objfile_obstack,
9001                             struct dwarf2_per_cu_data);
9002           memset (this_cu, 0, sizeof (*this_cu));
9003         }
9004       else
9005         {
9006           auto sig_type = XOBNEW (&objfile->objfile_obstack,
9007                                   struct signatured_type);
9008           memset (sig_type, 0, sizeof (*sig_type));
9009           sig_type->signature = cu_header.signature;
9010           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
9011           this_cu = &sig_type->per_cu;
9012         }
9013       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
9014       this_cu->sect_off = sect_off;
9015       this_cu->length = cu_header.length + cu_header.initial_length_size;
9016       this_cu->is_dwz = is_dwz;
9017       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
9018       this_cu->section = section;
9019
9020       if (*n_comp_units == *n_allocated)
9021         {
9022           *n_allocated *= 2;
9023           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
9024                                         *all_comp_units, *n_allocated);
9025         }
9026       (*all_comp_units)[*n_comp_units] = this_cu;
9027       ++*n_comp_units;
9028
9029       info_ptr = info_ptr + this_cu->length;
9030     }
9031 }
9032
9033 /* Create a list of all compilation units in OBJFILE.
9034    This is only done for -readnow and building partial symtabs.  */
9035
9036 static void
9037 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
9038 {
9039   int n_allocated;
9040   int n_comp_units;
9041   struct dwarf2_per_cu_data **all_comp_units;
9042   struct dwz_file *dwz;
9043   struct objfile *objfile = dwarf2_per_objfile->objfile;
9044
9045   n_comp_units = 0;
9046   n_allocated = 10;
9047   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9048
9049   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9050                                 &dwarf2_per_objfile->abbrev, 0,
9051                                 &n_allocated, &n_comp_units, &all_comp_units);
9052
9053   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9054   if (dwz != NULL)
9055     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9056                                   1, &n_allocated, &n_comp_units,
9057                                   &all_comp_units);
9058
9059   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9060                                                   struct dwarf2_per_cu_data *,
9061                                                   n_comp_units);
9062   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9063           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9064   xfree (all_comp_units);
9065   dwarf2_per_objfile->n_comp_units = n_comp_units;
9066 }
9067
9068 /* Process all loaded DIEs for compilation unit CU, starting at
9069    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9070    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9071    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9072    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9073
9074 static void
9075 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9076                       CORE_ADDR *highpc, int set_addrmap,
9077                       struct dwarf2_cu *cu)
9078 {
9079   struct partial_die_info *pdi;
9080
9081   /* Now, march along the PDI's, descending into ones which have
9082      interesting children but skipping the children of the other ones,
9083      until we reach the end of the compilation unit.  */
9084
9085   pdi = first_die;
9086
9087   while (pdi != NULL)
9088     {
9089       pdi->fixup (cu);
9090
9091       /* Anonymous namespaces or modules have no name but have interesting
9092          children, so we need to look at them.  Ditto for anonymous
9093          enums.  */
9094
9095       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9096           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9097           || pdi->tag == DW_TAG_imported_unit
9098           || pdi->tag == DW_TAG_inlined_subroutine)
9099         {
9100           switch (pdi->tag)
9101             {
9102             case DW_TAG_subprogram:
9103             case DW_TAG_inlined_subroutine:
9104               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9105               break;
9106             case DW_TAG_constant:
9107             case DW_TAG_variable:
9108             case DW_TAG_typedef:
9109             case DW_TAG_union_type:
9110               if (!pdi->is_declaration)
9111                 {
9112                   add_partial_symbol (pdi, cu);
9113                 }
9114               break;
9115             case DW_TAG_class_type:
9116             case DW_TAG_interface_type:
9117             case DW_TAG_structure_type:
9118               if (!pdi->is_declaration)
9119                 {
9120                   add_partial_symbol (pdi, cu);
9121                 }
9122               if (cu->language == language_rust && pdi->has_children)
9123                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9124                                       set_addrmap, cu);
9125               break;
9126             case DW_TAG_enumeration_type:
9127               if (!pdi->is_declaration)
9128                 add_partial_enumeration (pdi, cu);
9129               break;
9130             case DW_TAG_base_type:
9131             case DW_TAG_subrange_type:
9132               /* File scope base type definitions are added to the partial
9133                  symbol table.  */
9134               add_partial_symbol (pdi, cu);
9135               break;
9136             case DW_TAG_namespace:
9137               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9138               break;
9139             case DW_TAG_module:
9140               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9141               break;
9142             case DW_TAG_imported_unit:
9143               {
9144                 struct dwarf2_per_cu_data *per_cu;
9145
9146                 /* For now we don't handle imported units in type units.  */
9147                 if (cu->per_cu->is_debug_types)
9148                   {
9149                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9150                              " supported in type units [in module %s]"),
9151                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9152                   }
9153
9154                 per_cu = dwarf2_find_containing_comp_unit
9155                            (pdi->d.sect_off, pdi->is_dwz,
9156                             cu->per_cu->dwarf2_per_objfile);
9157
9158                 /* Go read the partial unit, if needed.  */
9159                 if (per_cu->v.psymtab == NULL)
9160                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9161
9162                 VEC_safe_push (dwarf2_per_cu_ptr,
9163                                cu->per_cu->imported_symtabs, per_cu);
9164               }
9165               break;
9166             case DW_TAG_imported_declaration:
9167               add_partial_symbol (pdi, cu);
9168               break;
9169             default:
9170               break;
9171             }
9172         }
9173
9174       /* If the die has a sibling, skip to the sibling.  */
9175
9176       pdi = pdi->die_sibling;
9177     }
9178 }
9179
9180 /* Functions used to compute the fully scoped name of a partial DIE.
9181
9182    Normally, this is simple.  For C++, the parent DIE's fully scoped
9183    name is concatenated with "::" and the partial DIE's name.
9184    Enumerators are an exception; they use the scope of their parent
9185    enumeration type, i.e. the name of the enumeration type is not
9186    prepended to the enumerator.
9187
9188    There are two complexities.  One is DW_AT_specification; in this
9189    case "parent" means the parent of the target of the specification,
9190    instead of the direct parent of the DIE.  The other is compilers
9191    which do not emit DW_TAG_namespace; in this case we try to guess
9192    the fully qualified name of structure types from their members'
9193    linkage names.  This must be done using the DIE's children rather
9194    than the children of any DW_AT_specification target.  We only need
9195    to do this for structures at the top level, i.e. if the target of
9196    any DW_AT_specification (if any; otherwise the DIE itself) does not
9197    have a parent.  */
9198
9199 /* Compute the scope prefix associated with PDI's parent, in
9200    compilation unit CU.  The result will be allocated on CU's
9201    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9202    field.  NULL is returned if no prefix is necessary.  */
9203 static const char *
9204 partial_die_parent_scope (struct partial_die_info *pdi,
9205                           struct dwarf2_cu *cu)
9206 {
9207   const char *grandparent_scope;
9208   struct partial_die_info *parent, *real_pdi;
9209
9210   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9211      then this means the parent of the specification DIE.  */
9212
9213   real_pdi = pdi;
9214   while (real_pdi->has_specification)
9215     real_pdi = find_partial_die (real_pdi->spec_offset,
9216                                  real_pdi->spec_is_dwz, cu);
9217
9218   parent = real_pdi->die_parent;
9219   if (parent == NULL)
9220     return NULL;
9221
9222   if (parent->scope_set)
9223     return parent->scope;
9224
9225   parent->fixup (cu);
9226
9227   grandparent_scope = partial_die_parent_scope (parent, cu);
9228
9229   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9230      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9231      Work around this problem here.  */
9232   if (cu->language == language_cplus
9233       && parent->tag == DW_TAG_namespace
9234       && strcmp (parent->name, "::") == 0
9235       && grandparent_scope == NULL)
9236     {
9237       parent->scope = NULL;
9238       parent->scope_set = 1;
9239       return NULL;
9240     }
9241
9242   if (pdi->tag == DW_TAG_enumerator)
9243     /* Enumerators should not get the name of the enumeration as a prefix.  */
9244     parent->scope = grandparent_scope;
9245   else if (parent->tag == DW_TAG_namespace
9246       || parent->tag == DW_TAG_module
9247       || parent->tag == DW_TAG_structure_type
9248       || parent->tag == DW_TAG_class_type
9249       || parent->tag == DW_TAG_interface_type
9250       || parent->tag == DW_TAG_union_type
9251       || parent->tag == DW_TAG_enumeration_type)
9252     {
9253       if (grandparent_scope == NULL)
9254         parent->scope = parent->name;
9255       else
9256         parent->scope = typename_concat (&cu->comp_unit_obstack,
9257                                          grandparent_scope,
9258                                          parent->name, 0, cu);
9259     }
9260   else
9261     {
9262       /* FIXME drow/2004-04-01: What should we be doing with
9263          function-local names?  For partial symbols, we should probably be
9264          ignoring them.  */
9265       complaint (&symfile_complaints,
9266                  _("unhandled containing DIE tag %d for DIE at %s"),
9267                  parent->tag, sect_offset_str (pdi->sect_off));
9268       parent->scope = grandparent_scope;
9269     }
9270
9271   parent->scope_set = 1;
9272   return parent->scope;
9273 }
9274
9275 /* Return the fully scoped name associated with PDI, from compilation unit
9276    CU.  The result will be allocated with malloc.  */
9277
9278 static char *
9279 partial_die_full_name (struct partial_die_info *pdi,
9280                        struct dwarf2_cu *cu)
9281 {
9282   const char *parent_scope;
9283
9284   /* If this is a template instantiation, we can not work out the
9285      template arguments from partial DIEs.  So, unfortunately, we have
9286      to go through the full DIEs.  At least any work we do building
9287      types here will be reused if full symbols are loaded later.  */
9288   if (pdi->has_template_arguments)
9289     {
9290       pdi->fixup (cu);
9291
9292       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9293         {
9294           struct die_info *die;
9295           struct attribute attr;
9296           struct dwarf2_cu *ref_cu = cu;
9297
9298           /* DW_FORM_ref_addr is using section offset.  */
9299           attr.name = (enum dwarf_attribute) 0;
9300           attr.form = DW_FORM_ref_addr;
9301           attr.u.unsnd = to_underlying (pdi->sect_off);
9302           die = follow_die_ref (NULL, &attr, &ref_cu);
9303
9304           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9305         }
9306     }
9307
9308   parent_scope = partial_die_parent_scope (pdi, cu);
9309   if (parent_scope == NULL)
9310     return NULL;
9311   else
9312     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9313 }
9314
9315 static void
9316 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9317 {
9318   struct dwarf2_per_objfile *dwarf2_per_objfile
9319     = cu->per_cu->dwarf2_per_objfile;
9320   struct objfile *objfile = dwarf2_per_objfile->objfile;
9321   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9322   CORE_ADDR addr = 0;
9323   const char *actual_name = NULL;
9324   CORE_ADDR baseaddr;
9325   char *built_actual_name;
9326
9327   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9328
9329   built_actual_name = partial_die_full_name (pdi, cu);
9330   if (built_actual_name != NULL)
9331     actual_name = built_actual_name;
9332
9333   if (actual_name == NULL)
9334     actual_name = pdi->name;
9335
9336   switch (pdi->tag)
9337     {
9338     case DW_TAG_inlined_subroutine:
9339     case DW_TAG_subprogram:
9340       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9341       if (pdi->is_external || cu->language == language_ada)
9342         {
9343           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9344              of the global scope.  But in Ada, we want to be able to access
9345              nested procedures globally.  So all Ada subprograms are stored
9346              in the global scope.  */
9347           add_psymbol_to_list (actual_name, strlen (actual_name),
9348                                built_actual_name != NULL,
9349                                VAR_DOMAIN, LOC_BLOCK,
9350                                &objfile->global_psymbols,
9351                                addr, cu->language, objfile);
9352         }
9353       else
9354         {
9355           add_psymbol_to_list (actual_name, strlen (actual_name),
9356                                built_actual_name != NULL,
9357                                VAR_DOMAIN, LOC_BLOCK,
9358                                &objfile->static_psymbols,
9359                                addr, cu->language, objfile);
9360         }
9361
9362       if (pdi->main_subprogram && actual_name != NULL)
9363         set_objfile_main_name (objfile, actual_name, cu->language);
9364       break;
9365     case DW_TAG_constant:
9366       {
9367         std::vector<partial_symbol *> *list;
9368
9369         if (pdi->is_external)
9370           list = &objfile->global_psymbols;
9371         else
9372           list = &objfile->static_psymbols;
9373         add_psymbol_to_list (actual_name, strlen (actual_name),
9374                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9375                              list, 0, cu->language, objfile);
9376       }
9377       break;
9378     case DW_TAG_variable:
9379       if (pdi->d.locdesc)
9380         addr = decode_locdesc (pdi->d.locdesc, cu);
9381
9382       if (pdi->d.locdesc
9383           && addr == 0
9384           && !dwarf2_per_objfile->has_section_at_zero)
9385         {
9386           /* A global or static variable may also have been stripped
9387              out by the linker if unused, in which case its address
9388              will be nullified; do not add such variables into partial
9389              symbol table then.  */
9390         }
9391       else if (pdi->is_external)
9392         {
9393           /* Global Variable.
9394              Don't enter into the minimal symbol tables as there is
9395              a minimal symbol table entry from the ELF symbols already.
9396              Enter into partial symbol table if it has a location
9397              descriptor or a type.
9398              If the location descriptor is missing, new_symbol will create
9399              a LOC_UNRESOLVED symbol, the address of the variable will then
9400              be determined from the minimal symbol table whenever the variable
9401              is referenced.
9402              The address for the partial symbol table entry is not
9403              used by GDB, but it comes in handy for debugging partial symbol
9404              table building.  */
9405
9406           if (pdi->d.locdesc || pdi->has_type)
9407             add_psymbol_to_list (actual_name, strlen (actual_name),
9408                                  built_actual_name != NULL,
9409                                  VAR_DOMAIN, LOC_STATIC,
9410                                  &objfile->global_psymbols,
9411                                  addr + baseaddr,
9412                                  cu->language, objfile);
9413         }
9414       else
9415         {
9416           int has_loc = pdi->d.locdesc != NULL;
9417
9418           /* Static Variable.  Skip symbols whose value we cannot know (those
9419              without location descriptors or constant values).  */
9420           if (!has_loc && !pdi->has_const_value)
9421             {
9422               xfree (built_actual_name);
9423               return;
9424             }
9425
9426           add_psymbol_to_list (actual_name, strlen (actual_name),
9427                                built_actual_name != NULL,
9428                                VAR_DOMAIN, LOC_STATIC,
9429                                &objfile->static_psymbols,
9430                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9431                                cu->language, objfile);
9432         }
9433       break;
9434     case DW_TAG_typedef:
9435     case DW_TAG_base_type:
9436     case DW_TAG_subrange_type:
9437       add_psymbol_to_list (actual_name, strlen (actual_name),
9438                            built_actual_name != NULL,
9439                            VAR_DOMAIN, LOC_TYPEDEF,
9440                            &objfile->static_psymbols,
9441                            0, cu->language, objfile);
9442       break;
9443     case DW_TAG_imported_declaration:
9444     case DW_TAG_namespace:
9445       add_psymbol_to_list (actual_name, strlen (actual_name),
9446                            built_actual_name != NULL,
9447                            VAR_DOMAIN, LOC_TYPEDEF,
9448                            &objfile->global_psymbols,
9449                            0, cu->language, objfile);
9450       break;
9451     case DW_TAG_module:
9452       add_psymbol_to_list (actual_name, strlen (actual_name),
9453                            built_actual_name != NULL,
9454                            MODULE_DOMAIN, LOC_TYPEDEF,
9455                            &objfile->global_psymbols,
9456                            0, cu->language, objfile);
9457       break;
9458     case DW_TAG_class_type:
9459     case DW_TAG_interface_type:
9460     case DW_TAG_structure_type:
9461     case DW_TAG_union_type:
9462     case DW_TAG_enumeration_type:
9463       /* Skip external references.  The DWARF standard says in the section
9464          about "Structure, Union, and Class Type Entries": "An incomplete
9465          structure, union or class type is represented by a structure,
9466          union or class entry that does not have a byte size attribute
9467          and that has a DW_AT_declaration attribute."  */
9468       if (!pdi->has_byte_size && pdi->is_declaration)
9469         {
9470           xfree (built_actual_name);
9471           return;
9472         }
9473
9474       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9475          static vs. global.  */
9476       add_psymbol_to_list (actual_name, strlen (actual_name),
9477                            built_actual_name != NULL,
9478                            STRUCT_DOMAIN, LOC_TYPEDEF,
9479                            cu->language == language_cplus
9480                            ? &objfile->global_psymbols
9481                            : &objfile->static_psymbols,
9482                            0, cu->language, objfile);
9483
9484       break;
9485     case DW_TAG_enumerator:
9486       add_psymbol_to_list (actual_name, strlen (actual_name),
9487                            built_actual_name != NULL,
9488                            VAR_DOMAIN, LOC_CONST,
9489                            cu->language == language_cplus
9490                            ? &objfile->global_psymbols
9491                            : &objfile->static_psymbols,
9492                            0, cu->language, objfile);
9493       break;
9494     default:
9495       break;
9496     }
9497
9498   xfree (built_actual_name);
9499 }
9500
9501 /* Read a partial die corresponding to a namespace; also, add a symbol
9502    corresponding to that namespace to the symbol table.  NAMESPACE is
9503    the name of the enclosing namespace.  */
9504
9505 static void
9506 add_partial_namespace (struct partial_die_info *pdi,
9507                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9508                        int set_addrmap, struct dwarf2_cu *cu)
9509 {
9510   /* Add a symbol for the namespace.  */
9511
9512   add_partial_symbol (pdi, cu);
9513
9514   /* Now scan partial symbols in that namespace.  */
9515
9516   if (pdi->has_children)
9517     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9518 }
9519
9520 /* Read a partial die corresponding to a Fortran module.  */
9521
9522 static void
9523 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9524                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9525 {
9526   /* Add a symbol for the namespace.  */
9527
9528   add_partial_symbol (pdi, cu);
9529
9530   /* Now scan partial symbols in that module.  */
9531
9532   if (pdi->has_children)
9533     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9534 }
9535
9536 /* Read a partial die corresponding to a subprogram or an inlined
9537    subprogram and create a partial symbol for that subprogram.
9538    When the CU language allows it, this routine also defines a partial
9539    symbol for each nested subprogram that this subprogram contains.
9540    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9541    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9542
9543    PDI may also be a lexical block, in which case we simply search
9544    recursively for subprograms defined inside that lexical block.
9545    Again, this is only performed when the CU language allows this
9546    type of definitions.  */
9547
9548 static void
9549 add_partial_subprogram (struct partial_die_info *pdi,
9550                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9551                         int set_addrmap, struct dwarf2_cu *cu)
9552 {
9553   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9554     {
9555       if (pdi->has_pc_info)
9556         {
9557           if (pdi->lowpc < *lowpc)
9558             *lowpc = pdi->lowpc;
9559           if (pdi->highpc > *highpc)
9560             *highpc = pdi->highpc;
9561           if (set_addrmap)
9562             {
9563               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9564               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9565               CORE_ADDR baseaddr;
9566               CORE_ADDR highpc;
9567               CORE_ADDR lowpc;
9568
9569               baseaddr = ANOFFSET (objfile->section_offsets,
9570                                    SECT_OFF_TEXT (objfile));
9571               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9572                                                   pdi->lowpc + baseaddr);
9573               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9574                                                    pdi->highpc + baseaddr);
9575               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9576                                  cu->per_cu->v.psymtab);
9577             }
9578         }
9579
9580       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9581         {
9582           if (!pdi->is_declaration)
9583             /* Ignore subprogram DIEs that do not have a name, they are
9584                illegal.  Do not emit a complaint at this point, we will
9585                do so when we convert this psymtab into a symtab.  */
9586             if (pdi->name)
9587               add_partial_symbol (pdi, cu);
9588         }
9589     }
9590
9591   if (! pdi->has_children)
9592     return;
9593
9594   if (cu->language == language_ada)
9595     {
9596       pdi = pdi->die_child;
9597       while (pdi != NULL)
9598         {
9599           pdi->fixup (cu);
9600           if (pdi->tag == DW_TAG_subprogram
9601               || pdi->tag == DW_TAG_inlined_subroutine
9602               || pdi->tag == DW_TAG_lexical_block)
9603             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9604           pdi = pdi->die_sibling;
9605         }
9606     }
9607 }
9608
9609 /* Read a partial die corresponding to an enumeration type.  */
9610
9611 static void
9612 add_partial_enumeration (struct partial_die_info *enum_pdi,
9613                          struct dwarf2_cu *cu)
9614 {
9615   struct partial_die_info *pdi;
9616
9617   if (enum_pdi->name != NULL)
9618     add_partial_symbol (enum_pdi, cu);
9619
9620   pdi = enum_pdi->die_child;
9621   while (pdi)
9622     {
9623       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9624         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9625       else
9626         add_partial_symbol (pdi, cu);
9627       pdi = pdi->die_sibling;
9628     }
9629 }
9630
9631 /* Return the initial uleb128 in the die at INFO_PTR.  */
9632
9633 static unsigned int
9634 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9635 {
9636   unsigned int bytes_read;
9637
9638   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9639 }
9640
9641 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9642    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9643
9644    Return the corresponding abbrev, or NULL if the number is zero (indicating
9645    an empty DIE).  In either case *BYTES_READ will be set to the length of
9646    the initial number.  */
9647
9648 static struct abbrev_info *
9649 peek_die_abbrev (const die_reader_specs &reader,
9650                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9651 {
9652   dwarf2_cu *cu = reader.cu;
9653   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9654   unsigned int abbrev_number
9655     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9656
9657   if (abbrev_number == 0)
9658     return NULL;
9659
9660   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9661   if (!abbrev)
9662     {
9663       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9664                " at offset %s [in module %s]"),
9665              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9666              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9667     }
9668
9669   return abbrev;
9670 }
9671
9672 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9673    Returns a pointer to the end of a series of DIEs, terminated by an empty
9674    DIE.  Any children of the skipped DIEs will also be skipped.  */
9675
9676 static const gdb_byte *
9677 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9678 {
9679   while (1)
9680     {
9681       unsigned int bytes_read;
9682       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9683
9684       if (abbrev == NULL)
9685         return info_ptr + bytes_read;
9686       else
9687         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9688     }
9689 }
9690
9691 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9692    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9693    abbrev corresponding to that skipped uleb128 should be passed in
9694    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9695    children.  */
9696
9697 static const gdb_byte *
9698 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9699               struct abbrev_info *abbrev)
9700 {
9701   unsigned int bytes_read;
9702   struct attribute attr;
9703   bfd *abfd = reader->abfd;
9704   struct dwarf2_cu *cu = reader->cu;
9705   const gdb_byte *buffer = reader->buffer;
9706   const gdb_byte *buffer_end = reader->buffer_end;
9707   unsigned int form, i;
9708
9709   for (i = 0; i < abbrev->num_attrs; i++)
9710     {
9711       /* The only abbrev we care about is DW_AT_sibling.  */
9712       if (abbrev->attrs[i].name == DW_AT_sibling)
9713         {
9714           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9715           if (attr.form == DW_FORM_ref_addr)
9716             complaint (&symfile_complaints,
9717                        _("ignoring absolute DW_AT_sibling"));
9718           else
9719             {
9720               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9721               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9722
9723               if (sibling_ptr < info_ptr)
9724                 complaint (&symfile_complaints,
9725                            _("DW_AT_sibling points backwards"));
9726               else if (sibling_ptr > reader->buffer_end)
9727                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9728               else
9729                 return sibling_ptr;
9730             }
9731         }
9732
9733       /* If it isn't DW_AT_sibling, skip this attribute.  */
9734       form = abbrev->attrs[i].form;
9735     skip_attribute:
9736       switch (form)
9737         {
9738         case DW_FORM_ref_addr:
9739           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9740              and later it is offset sized.  */
9741           if (cu->header.version == 2)
9742             info_ptr += cu->header.addr_size;
9743           else
9744             info_ptr += cu->header.offset_size;
9745           break;
9746         case DW_FORM_GNU_ref_alt:
9747           info_ptr += cu->header.offset_size;
9748           break;
9749         case DW_FORM_addr:
9750           info_ptr += cu->header.addr_size;
9751           break;
9752         case DW_FORM_data1:
9753         case DW_FORM_ref1:
9754         case DW_FORM_flag:
9755           info_ptr += 1;
9756           break;
9757         case DW_FORM_flag_present:
9758         case DW_FORM_implicit_const:
9759           break;
9760         case DW_FORM_data2:
9761         case DW_FORM_ref2:
9762           info_ptr += 2;
9763           break;
9764         case DW_FORM_data4:
9765         case DW_FORM_ref4:
9766           info_ptr += 4;
9767           break;
9768         case DW_FORM_data8:
9769         case DW_FORM_ref8:
9770         case DW_FORM_ref_sig8:
9771           info_ptr += 8;
9772           break;
9773         case DW_FORM_data16:
9774           info_ptr += 16;
9775           break;
9776         case DW_FORM_string:
9777           read_direct_string (abfd, info_ptr, &bytes_read);
9778           info_ptr += bytes_read;
9779           break;
9780         case DW_FORM_sec_offset:
9781         case DW_FORM_strp:
9782         case DW_FORM_GNU_strp_alt:
9783           info_ptr += cu->header.offset_size;
9784           break;
9785         case DW_FORM_exprloc:
9786         case DW_FORM_block:
9787           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9788           info_ptr += bytes_read;
9789           break;
9790         case DW_FORM_block1:
9791           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9792           break;
9793         case DW_FORM_block2:
9794           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9795           break;
9796         case DW_FORM_block4:
9797           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9798           break;
9799         case DW_FORM_sdata:
9800         case DW_FORM_udata:
9801         case DW_FORM_ref_udata:
9802         case DW_FORM_GNU_addr_index:
9803         case DW_FORM_GNU_str_index:
9804           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9805           break;
9806         case DW_FORM_indirect:
9807           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9808           info_ptr += bytes_read;
9809           /* We need to continue parsing from here, so just go back to
9810              the top.  */
9811           goto skip_attribute;
9812
9813         default:
9814           error (_("Dwarf Error: Cannot handle %s "
9815                    "in DWARF reader [in module %s]"),
9816                  dwarf_form_name (form),
9817                  bfd_get_filename (abfd));
9818         }
9819     }
9820
9821   if (abbrev->has_children)
9822     return skip_children (reader, info_ptr);
9823   else
9824     return info_ptr;
9825 }
9826
9827 /* Locate ORIG_PDI's sibling.
9828    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9829
9830 static const gdb_byte *
9831 locate_pdi_sibling (const struct die_reader_specs *reader,
9832                     struct partial_die_info *orig_pdi,
9833                     const gdb_byte *info_ptr)
9834 {
9835   /* Do we know the sibling already?  */
9836
9837   if (orig_pdi->sibling)
9838     return orig_pdi->sibling;
9839
9840   /* Are there any children to deal with?  */
9841
9842   if (!orig_pdi->has_children)
9843     return info_ptr;
9844
9845   /* Skip the children the long way.  */
9846
9847   return skip_children (reader, info_ptr);
9848 }
9849
9850 /* Expand this partial symbol table into a full symbol table.  SELF is
9851    not NULL.  */
9852
9853 static void
9854 dwarf2_read_symtab (struct partial_symtab *self,
9855                     struct objfile *objfile)
9856 {
9857   struct dwarf2_per_objfile *dwarf2_per_objfile
9858     = get_dwarf2_per_objfile (objfile);
9859
9860   if (self->readin)
9861     {
9862       warning (_("bug: psymtab for %s is already read in."),
9863                self->filename);
9864     }
9865   else
9866     {
9867       if (info_verbose)
9868         {
9869           printf_filtered (_("Reading in symbols for %s..."),
9870                            self->filename);
9871           gdb_flush (gdb_stdout);
9872         }
9873
9874       /* If this psymtab is constructed from a debug-only objfile, the
9875          has_section_at_zero flag will not necessarily be correct.  We
9876          can get the correct value for this flag by looking at the data
9877          associated with the (presumably stripped) associated objfile.  */
9878       if (objfile->separate_debug_objfile_backlink)
9879         {
9880           struct dwarf2_per_objfile *dpo_backlink
9881             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9882
9883           dwarf2_per_objfile->has_section_at_zero
9884             = dpo_backlink->has_section_at_zero;
9885         }
9886
9887       dwarf2_per_objfile->reading_partial_symbols = 0;
9888
9889       psymtab_to_symtab_1 (self);
9890
9891       /* Finish up the debug error message.  */
9892       if (info_verbose)
9893         printf_filtered (_("done.\n"));
9894     }
9895
9896   process_cu_includes (dwarf2_per_objfile);
9897 }
9898 \f
9899 /* Reading in full CUs.  */
9900
9901 /* Add PER_CU to the queue.  */
9902
9903 static void
9904 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9905                  enum language pretend_language)
9906 {
9907   struct dwarf2_queue_item *item;
9908
9909   per_cu->queued = 1;
9910   item = XNEW (struct dwarf2_queue_item);
9911   item->per_cu = per_cu;
9912   item->pretend_language = pretend_language;
9913   item->next = NULL;
9914
9915   if (dwarf2_queue == NULL)
9916     dwarf2_queue = item;
9917   else
9918     dwarf2_queue_tail->next = item;
9919
9920   dwarf2_queue_tail = item;
9921 }
9922
9923 /* If PER_CU is not yet queued, add it to the queue.
9924    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9925    dependency.
9926    The result is non-zero if PER_CU was queued, otherwise the result is zero
9927    meaning either PER_CU is already queued or it is already loaded.
9928
9929    N.B. There is an invariant here that if a CU is queued then it is loaded.
9930    The caller is required to load PER_CU if we return non-zero.  */
9931
9932 static int
9933 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9934                        struct dwarf2_per_cu_data *per_cu,
9935                        enum language pretend_language)
9936 {
9937   /* We may arrive here during partial symbol reading, if we need full
9938      DIEs to process an unusual case (e.g. template arguments).  Do
9939      not queue PER_CU, just tell our caller to load its DIEs.  */
9940   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9941     {
9942       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9943         return 1;
9944       return 0;
9945     }
9946
9947   /* Mark the dependence relation so that we don't flush PER_CU
9948      too early.  */
9949   if (dependent_cu != NULL)
9950     dwarf2_add_dependence (dependent_cu, per_cu);
9951
9952   /* If it's already on the queue, we have nothing to do.  */
9953   if (per_cu->queued)
9954     return 0;
9955
9956   /* If the compilation unit is already loaded, just mark it as
9957      used.  */
9958   if (per_cu->cu != NULL)
9959     {
9960       per_cu->cu->last_used = 0;
9961       return 0;
9962     }
9963
9964   /* Add it to the queue.  */
9965   queue_comp_unit (per_cu, pretend_language);
9966
9967   return 1;
9968 }
9969
9970 /* Process the queue.  */
9971
9972 static void
9973 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9974 {
9975   struct dwarf2_queue_item *item, *next_item;
9976
9977   if (dwarf_read_debug)
9978     {
9979       fprintf_unfiltered (gdb_stdlog,
9980                           "Expanding one or more symtabs of objfile %s ...\n",
9981                           objfile_name (dwarf2_per_objfile->objfile));
9982     }
9983
9984   /* The queue starts out with one item, but following a DIE reference
9985      may load a new CU, adding it to the end of the queue.  */
9986   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9987     {
9988       if ((dwarf2_per_objfile->using_index
9989            ? !item->per_cu->v.quick->compunit_symtab
9990            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9991           /* Skip dummy CUs.  */
9992           && item->per_cu->cu != NULL)
9993         {
9994           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9995           unsigned int debug_print_threshold;
9996           char buf[100];
9997
9998           if (per_cu->is_debug_types)
9999             {
10000               struct signatured_type *sig_type =
10001                 (struct signatured_type *) per_cu;
10002
10003               sprintf (buf, "TU %s at offset %s",
10004                        hex_string (sig_type->signature),
10005                        sect_offset_str (per_cu->sect_off));
10006               /* There can be 100s of TUs.
10007                  Only print them in verbose mode.  */
10008               debug_print_threshold = 2;
10009             }
10010           else
10011             {
10012               sprintf (buf, "CU at offset %s",
10013                        sect_offset_str (per_cu->sect_off));
10014               debug_print_threshold = 1;
10015             }
10016
10017           if (dwarf_read_debug >= debug_print_threshold)
10018             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
10019
10020           if (per_cu->is_debug_types)
10021             process_full_type_unit (per_cu, item->pretend_language);
10022           else
10023             process_full_comp_unit (per_cu, item->pretend_language);
10024
10025           if (dwarf_read_debug >= debug_print_threshold)
10026             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
10027         }
10028
10029       item->per_cu->queued = 0;
10030       next_item = item->next;
10031       xfree (item);
10032     }
10033
10034   dwarf2_queue_tail = NULL;
10035
10036   if (dwarf_read_debug)
10037     {
10038       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
10039                           objfile_name (dwarf2_per_objfile->objfile));
10040     }
10041 }
10042
10043 /* Read in full symbols for PST, and anything it depends on.  */
10044
10045 static void
10046 psymtab_to_symtab_1 (struct partial_symtab *pst)
10047 {
10048   struct dwarf2_per_cu_data *per_cu;
10049   int i;
10050
10051   if (pst->readin)
10052     return;
10053
10054   for (i = 0; i < pst->number_of_dependencies; i++)
10055     if (!pst->dependencies[i]->readin
10056         && pst->dependencies[i]->user == NULL)
10057       {
10058         /* Inform about additional files that need to be read in.  */
10059         if (info_verbose)
10060           {
10061             /* FIXME: i18n: Need to make this a single string.  */
10062             fputs_filtered (" ", gdb_stdout);
10063             wrap_here ("");
10064             fputs_filtered ("and ", gdb_stdout);
10065             wrap_here ("");
10066             printf_filtered ("%s...", pst->dependencies[i]->filename);
10067             wrap_here ("");     /* Flush output.  */
10068             gdb_flush (gdb_stdout);
10069           }
10070         psymtab_to_symtab_1 (pst->dependencies[i]);
10071       }
10072
10073   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10074
10075   if (per_cu == NULL)
10076     {
10077       /* It's an include file, no symbols to read for it.
10078          Everything is in the parent symtab.  */
10079       pst->readin = 1;
10080       return;
10081     }
10082
10083   dw2_do_instantiate_symtab (per_cu);
10084 }
10085
10086 /* Trivial hash function for die_info: the hash value of a DIE
10087    is its offset in .debug_info for this objfile.  */
10088
10089 static hashval_t
10090 die_hash (const void *item)
10091 {
10092   const struct die_info *die = (const struct die_info *) item;
10093
10094   return to_underlying (die->sect_off);
10095 }
10096
10097 /* Trivial comparison function for die_info structures: two DIEs
10098    are equal if they have the same offset.  */
10099
10100 static int
10101 die_eq (const void *item_lhs, const void *item_rhs)
10102 {
10103   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10104   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10105
10106   return die_lhs->sect_off == die_rhs->sect_off;
10107 }
10108
10109 /* die_reader_func for load_full_comp_unit.
10110    This is identical to read_signatured_type_reader,
10111    but is kept separate for now.  */
10112
10113 static void
10114 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10115                             const gdb_byte *info_ptr,
10116                             struct die_info *comp_unit_die,
10117                             int has_children,
10118                             void *data)
10119 {
10120   struct dwarf2_cu *cu = reader->cu;
10121   enum language *language_ptr = (enum language *) data;
10122
10123   gdb_assert (cu->die_hash == NULL);
10124   cu->die_hash =
10125     htab_create_alloc_ex (cu->header.length / 12,
10126                           die_hash,
10127                           die_eq,
10128                           NULL,
10129                           &cu->comp_unit_obstack,
10130                           hashtab_obstack_allocate,
10131                           dummy_obstack_deallocate);
10132
10133   if (has_children)
10134     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10135                                                   &info_ptr, comp_unit_die);
10136   cu->dies = comp_unit_die;
10137   /* comp_unit_die is not stored in die_hash, no need.  */
10138
10139   /* We try not to read any attributes in this function, because not
10140      all CUs needed for references have been loaded yet, and symbol
10141      table processing isn't initialized.  But we have to set the CU language,
10142      or we won't be able to build types correctly.
10143      Similarly, if we do not read the producer, we can not apply
10144      producer-specific interpretation.  */
10145   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10146 }
10147
10148 /* Load the DIEs associated with PER_CU into memory.  */
10149
10150 static void
10151 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10152                      enum language pretend_language)
10153 {
10154   gdb_assert (! this_cu->is_debug_types);
10155
10156   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10157                            load_full_comp_unit_reader, &pretend_language);
10158 }
10159
10160 /* Add a DIE to the delayed physname list.  */
10161
10162 static void
10163 add_to_method_list (struct type *type, int fnfield_index, int index,
10164                     const char *name, struct die_info *die,
10165                     struct dwarf2_cu *cu)
10166 {
10167   struct delayed_method_info mi;
10168   mi.type = type;
10169   mi.fnfield_index = fnfield_index;
10170   mi.index = index;
10171   mi.name = name;
10172   mi.die = die;
10173   cu->method_list.push_back (mi);
10174 }
10175
10176 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10177    "const" / "volatile".  If so, decrements LEN by the length of the
10178    modifier and return true.  Otherwise return false.  */
10179
10180 template<size_t N>
10181 static bool
10182 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10183 {
10184   size_t mod_len = sizeof (mod) - 1;
10185   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10186     {
10187       len -= mod_len;
10188       return true;
10189     }
10190   return false;
10191 }
10192
10193 /* Compute the physnames of any methods on the CU's method list.
10194
10195    The computation of method physnames is delayed in order to avoid the
10196    (bad) condition that one of the method's formal parameters is of an as yet
10197    incomplete type.  */
10198
10199 static void
10200 compute_delayed_physnames (struct dwarf2_cu *cu)
10201 {
10202   /* Only C++ delays computing physnames.  */
10203   if (cu->method_list.empty ())
10204     return;
10205   gdb_assert (cu->language == language_cplus);
10206
10207   for (struct delayed_method_info &mi : cu->method_list)
10208     {
10209       const char *physname;
10210       struct fn_fieldlist *fn_flp
10211         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
10212       physname = dwarf2_physname (mi.name, mi.die, cu);
10213       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
10214         = physname ? physname : "";
10215
10216       /* Since there's no tag to indicate whether a method is a
10217          const/volatile overload, extract that information out of the
10218          demangled name.  */
10219       if (physname != NULL)
10220         {
10221           size_t len = strlen (physname);
10222
10223           while (1)
10224             {
10225               if (physname[len] == ')') /* shortcut */
10226                 break;
10227               else if (check_modifier (physname, len, " const"))
10228                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
10229               else if (check_modifier (physname, len, " volatile"))
10230                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
10231               else
10232                 break;
10233             }
10234         }
10235     }
10236
10237   /* The list is no longer needed.  */
10238   cu->method_list.clear ();
10239 }
10240
10241 /* Go objects should be embedded in a DW_TAG_module DIE,
10242    and it's not clear if/how imported objects will appear.
10243    To keep Go support simple until that's worked out,
10244    go back through what we've read and create something usable.
10245    We could do this while processing each DIE, and feels kinda cleaner,
10246    but that way is more invasive.
10247    This is to, for example, allow the user to type "p var" or "b main"
10248    without having to specify the package name, and allow lookups
10249    of module.object to work in contexts that use the expression
10250    parser.  */
10251
10252 static void
10253 fixup_go_packaging (struct dwarf2_cu *cu)
10254 {
10255   char *package_name = NULL;
10256   struct pending *list;
10257   int i;
10258
10259   for (list = global_symbols; list != NULL; list = list->next)
10260     {
10261       for (i = 0; i < list->nsyms; ++i)
10262         {
10263           struct symbol *sym = list->symbol[i];
10264
10265           if (SYMBOL_LANGUAGE (sym) == language_go
10266               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10267             {
10268               char *this_package_name = go_symbol_package_name (sym);
10269
10270               if (this_package_name == NULL)
10271                 continue;
10272               if (package_name == NULL)
10273                 package_name = this_package_name;
10274               else
10275                 {
10276                   struct objfile *objfile
10277                     = cu->per_cu->dwarf2_per_objfile->objfile;
10278                   if (strcmp (package_name, this_package_name) != 0)
10279                     complaint (&symfile_complaints,
10280                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10281                                (symbol_symtab (sym) != NULL
10282                                 ? symtab_to_filename_for_display
10283                                     (symbol_symtab (sym))
10284                                 : objfile_name (objfile)),
10285                                this_package_name, package_name);
10286                   xfree (this_package_name);
10287                 }
10288             }
10289         }
10290     }
10291
10292   if (package_name != NULL)
10293     {
10294       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10295       const char *saved_package_name
10296         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10297                                         package_name,
10298                                         strlen (package_name));
10299       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10300                                      saved_package_name);
10301       struct symbol *sym;
10302
10303       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10304
10305       sym = allocate_symbol (objfile);
10306       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10307       SYMBOL_SET_NAMES (sym, saved_package_name,
10308                         strlen (saved_package_name), 0, objfile);
10309       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10310          e.g., "main" finds the "main" module and not C's main().  */
10311       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10312       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10313       SYMBOL_TYPE (sym) = type;
10314
10315       add_symbol_to_list (sym, &global_symbols);
10316
10317       xfree (package_name);
10318     }
10319 }
10320
10321 /* Return the symtab for PER_CU.  This works properly regardless of
10322    whether we're using the index or psymtabs.  */
10323
10324 static struct compunit_symtab *
10325 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10326 {
10327   return (per_cu->dwarf2_per_objfile->using_index
10328           ? per_cu->v.quick->compunit_symtab
10329           : per_cu->v.psymtab->compunit_symtab);
10330 }
10331
10332 /* A helper function for computing the list of all symbol tables
10333    included by PER_CU.  */
10334
10335 static void
10336 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10337                                 htab_t all_children, htab_t all_type_symtabs,
10338                                 struct dwarf2_per_cu_data *per_cu,
10339                                 struct compunit_symtab *immediate_parent)
10340 {
10341   void **slot;
10342   int ix;
10343   struct compunit_symtab *cust;
10344   struct dwarf2_per_cu_data *iter;
10345
10346   slot = htab_find_slot (all_children, per_cu, INSERT);
10347   if (*slot != NULL)
10348     {
10349       /* This inclusion and its children have been processed.  */
10350       return;
10351     }
10352
10353   *slot = per_cu;
10354   /* Only add a CU if it has a symbol table.  */
10355   cust = get_compunit_symtab (per_cu);
10356   if (cust != NULL)
10357     {
10358       /* If this is a type unit only add its symbol table if we haven't
10359          seen it yet (type unit per_cu's can share symtabs).  */
10360       if (per_cu->is_debug_types)
10361         {
10362           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10363           if (*slot == NULL)
10364             {
10365               *slot = cust;
10366               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10367               if (cust->user == NULL)
10368                 cust->user = immediate_parent;
10369             }
10370         }
10371       else
10372         {
10373           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10374           if (cust->user == NULL)
10375             cust->user = immediate_parent;
10376         }
10377     }
10378
10379   for (ix = 0;
10380        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10381        ++ix)
10382     {
10383       recursively_compute_inclusions (result, all_children,
10384                                       all_type_symtabs, iter, cust);
10385     }
10386 }
10387
10388 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10389    PER_CU.  */
10390
10391 static void
10392 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10393 {
10394   gdb_assert (! per_cu->is_debug_types);
10395
10396   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10397     {
10398       int ix, len;
10399       struct dwarf2_per_cu_data *per_cu_iter;
10400       struct compunit_symtab *compunit_symtab_iter;
10401       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10402       htab_t all_children, all_type_symtabs;
10403       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10404
10405       /* If we don't have a symtab, we can just skip this case.  */
10406       if (cust == NULL)
10407         return;
10408
10409       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10410                                         NULL, xcalloc, xfree);
10411       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10412                                             NULL, xcalloc, xfree);
10413
10414       for (ix = 0;
10415            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10416                         ix, per_cu_iter);
10417            ++ix)
10418         {
10419           recursively_compute_inclusions (&result_symtabs, all_children,
10420                                           all_type_symtabs, per_cu_iter,
10421                                           cust);
10422         }
10423
10424       /* Now we have a transitive closure of all the included symtabs.  */
10425       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10426       cust->includes
10427         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10428                      struct compunit_symtab *, len + 1);
10429       for (ix = 0;
10430            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10431                         compunit_symtab_iter);
10432            ++ix)
10433         cust->includes[ix] = compunit_symtab_iter;
10434       cust->includes[len] = NULL;
10435
10436       VEC_free (compunit_symtab_ptr, result_symtabs);
10437       htab_delete (all_children);
10438       htab_delete (all_type_symtabs);
10439     }
10440 }
10441
10442 /* Compute the 'includes' field for the symtabs of all the CUs we just
10443    read.  */
10444
10445 static void
10446 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10447 {
10448   int ix;
10449   struct dwarf2_per_cu_data *iter;
10450
10451   for (ix = 0;
10452        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10453                     ix, iter);
10454        ++ix)
10455     {
10456       if (! iter->is_debug_types)
10457         compute_compunit_symtab_includes (iter);
10458     }
10459
10460   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10461 }
10462
10463 /* Generate full symbol information for PER_CU, whose DIEs have
10464    already been loaded into memory.  */
10465
10466 static void
10467 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10468                         enum language pretend_language)
10469 {
10470   struct dwarf2_cu *cu = per_cu->cu;
10471   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10472   struct objfile *objfile = dwarf2_per_objfile->objfile;
10473   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10474   CORE_ADDR lowpc, highpc;
10475   struct compunit_symtab *cust;
10476   CORE_ADDR baseaddr;
10477   struct block *static_block;
10478   CORE_ADDR addr;
10479
10480   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10481
10482   buildsym_init ();
10483   scoped_free_pendings free_pending;
10484
10485   /* Clear the list here in case something was left over.  */
10486   cu->method_list.clear ();
10487
10488   cu->list_in_scope = &file_symbols;
10489
10490   cu->language = pretend_language;
10491   cu->language_defn = language_def (cu->language);
10492
10493   /* Do line number decoding in read_file_scope () */
10494   process_die (cu->dies, cu);
10495
10496   /* For now fudge the Go package.  */
10497   if (cu->language == language_go)
10498     fixup_go_packaging (cu);
10499
10500   /* Now that we have processed all the DIEs in the CU, all the types 
10501      should be complete, and it should now be safe to compute all of the
10502      physnames.  */
10503   compute_delayed_physnames (cu);
10504
10505   /* Some compilers don't define a DW_AT_high_pc attribute for the
10506      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10507      it, by scanning the DIE's below the compilation unit.  */
10508   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10509
10510   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10511   static_block = end_symtab_get_static_block (addr, 0, 1);
10512
10513   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10514      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10515      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10516      addrmap to help ensure it has an accurate map of pc values belonging to
10517      this comp unit.  */
10518   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10519
10520   cust = end_symtab_from_static_block (static_block,
10521                                        SECT_OFF_TEXT (objfile), 0);
10522
10523   if (cust != NULL)
10524     {
10525       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10526
10527       /* Set symtab language to language from DW_AT_language.  If the
10528          compilation is from a C file generated by language preprocessors, do
10529          not set the language if it was already deduced by start_subfile.  */
10530       if (!(cu->language == language_c
10531             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10532         COMPUNIT_FILETABS (cust)->language = cu->language;
10533
10534       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10535          produce DW_AT_location with location lists but it can be possibly
10536          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10537          there were bugs in prologue debug info, fixed later in GCC-4.5
10538          by "unwind info for epilogues" patch (which is not directly related).
10539
10540          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10541          needed, it would be wrong due to missing DW_AT_producer there.
10542
10543          Still one can confuse GDB by using non-standard GCC compilation
10544          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10545          */ 
10546       if (cu->has_loclist && gcc_4_minor >= 5)
10547         cust->locations_valid = 1;
10548
10549       if (gcc_4_minor >= 5)
10550         cust->epilogue_unwind_valid = 1;
10551
10552       cust->call_site_htab = cu->call_site_htab;
10553     }
10554
10555   if (dwarf2_per_objfile->using_index)
10556     per_cu->v.quick->compunit_symtab = cust;
10557   else
10558     {
10559       struct partial_symtab *pst = per_cu->v.psymtab;
10560       pst->compunit_symtab = cust;
10561       pst->readin = 1;
10562     }
10563
10564   /* Push it for inclusion processing later.  */
10565   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10566 }
10567
10568 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10569    already been loaded into memory.  */
10570
10571 static void
10572 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10573                         enum language pretend_language)
10574 {
10575   struct dwarf2_cu *cu = per_cu->cu;
10576   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10577   struct objfile *objfile = dwarf2_per_objfile->objfile;
10578   struct compunit_symtab *cust;
10579   struct signatured_type *sig_type;
10580
10581   gdb_assert (per_cu->is_debug_types);
10582   sig_type = (struct signatured_type *) per_cu;
10583
10584   buildsym_init ();
10585   scoped_free_pendings free_pending;
10586
10587   /* Clear the list here in case something was left over.  */
10588   cu->method_list.clear ();
10589
10590   cu->list_in_scope = &file_symbols;
10591
10592   cu->language = pretend_language;
10593   cu->language_defn = language_def (cu->language);
10594
10595   /* The symbol tables are set up in read_type_unit_scope.  */
10596   process_die (cu->dies, cu);
10597
10598   /* For now fudge the Go package.  */
10599   if (cu->language == language_go)
10600     fixup_go_packaging (cu);
10601
10602   /* Now that we have processed all the DIEs in the CU, all the types 
10603      should be complete, and it should now be safe to compute all of the
10604      physnames.  */
10605   compute_delayed_physnames (cu);
10606
10607   /* TUs share symbol tables.
10608      If this is the first TU to use this symtab, complete the construction
10609      of it with end_expandable_symtab.  Otherwise, complete the addition of
10610      this TU's symbols to the existing symtab.  */
10611   if (sig_type->type_unit_group->compunit_symtab == NULL)
10612     {
10613       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10614       sig_type->type_unit_group->compunit_symtab = cust;
10615
10616       if (cust != NULL)
10617         {
10618           /* Set symtab language to language from DW_AT_language.  If the
10619              compilation is from a C file generated by language preprocessors,
10620              do not set the language if it was already deduced by
10621              start_subfile.  */
10622           if (!(cu->language == language_c
10623                 && COMPUNIT_FILETABS (cust)->language != language_c))
10624             COMPUNIT_FILETABS (cust)->language = cu->language;
10625         }
10626     }
10627   else
10628     {
10629       augment_type_symtab ();
10630       cust = sig_type->type_unit_group->compunit_symtab;
10631     }
10632
10633   if (dwarf2_per_objfile->using_index)
10634     per_cu->v.quick->compunit_symtab = cust;
10635   else
10636     {
10637       struct partial_symtab *pst = per_cu->v.psymtab;
10638       pst->compunit_symtab = cust;
10639       pst->readin = 1;
10640     }
10641 }
10642
10643 /* Process an imported unit DIE.  */
10644
10645 static void
10646 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10647 {
10648   struct attribute *attr;
10649
10650   /* For now we don't handle imported units in type units.  */
10651   if (cu->per_cu->is_debug_types)
10652     {
10653       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10654                " supported in type units [in module %s]"),
10655              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10656     }
10657
10658   attr = dwarf2_attr (die, DW_AT_import, cu);
10659   if (attr != NULL)
10660     {
10661       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10662       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10663       dwarf2_per_cu_data *per_cu
10664         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10665                                             cu->per_cu->dwarf2_per_objfile);
10666
10667       /* If necessary, add it to the queue and load its DIEs.  */
10668       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10669         load_full_comp_unit (per_cu, cu->language);
10670
10671       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10672                      per_cu);
10673     }
10674 }
10675
10676 /* RAII object that represents a process_die scope: i.e.,
10677    starts/finishes processing a DIE.  */
10678 class process_die_scope
10679 {
10680 public:
10681   process_die_scope (die_info *die, dwarf2_cu *cu)
10682     : m_die (die), m_cu (cu)
10683   {
10684     /* We should only be processing DIEs not already in process.  */
10685     gdb_assert (!m_die->in_process);
10686     m_die->in_process = true;
10687   }
10688
10689   ~process_die_scope ()
10690   {
10691     m_die->in_process = false;
10692
10693     /* If we're done processing the DIE for the CU that owns the line
10694        header, we don't need the line header anymore.  */
10695     if (m_cu->line_header_die_owner == m_die)
10696       {
10697         delete m_cu->line_header;
10698         m_cu->line_header = NULL;
10699         m_cu->line_header_die_owner = NULL;
10700       }
10701   }
10702
10703 private:
10704   die_info *m_die;
10705   dwarf2_cu *m_cu;
10706 };
10707
10708 /* Process a die and its children.  */
10709
10710 static void
10711 process_die (struct die_info *die, struct dwarf2_cu *cu)
10712 {
10713   process_die_scope scope (die, cu);
10714
10715   switch (die->tag)
10716     {
10717     case DW_TAG_padding:
10718       break;
10719     case DW_TAG_compile_unit:
10720     case DW_TAG_partial_unit:
10721       read_file_scope (die, cu);
10722       break;
10723     case DW_TAG_type_unit:
10724       read_type_unit_scope (die, cu);
10725       break;
10726     case DW_TAG_subprogram:
10727     case DW_TAG_inlined_subroutine:
10728       read_func_scope (die, cu);
10729       break;
10730     case DW_TAG_lexical_block:
10731     case DW_TAG_try_block:
10732     case DW_TAG_catch_block:
10733       read_lexical_block_scope (die, cu);
10734       break;
10735     case DW_TAG_call_site:
10736     case DW_TAG_GNU_call_site:
10737       read_call_site_scope (die, cu);
10738       break;
10739     case DW_TAG_class_type:
10740     case DW_TAG_interface_type:
10741     case DW_TAG_structure_type:
10742     case DW_TAG_union_type:
10743       process_structure_scope (die, cu);
10744       break;
10745     case DW_TAG_enumeration_type:
10746       process_enumeration_scope (die, cu);
10747       break;
10748
10749     /* These dies have a type, but processing them does not create
10750        a symbol or recurse to process the children.  Therefore we can
10751        read them on-demand through read_type_die.  */
10752     case DW_TAG_subroutine_type:
10753     case DW_TAG_set_type:
10754     case DW_TAG_array_type:
10755     case DW_TAG_pointer_type:
10756     case DW_TAG_ptr_to_member_type:
10757     case DW_TAG_reference_type:
10758     case DW_TAG_rvalue_reference_type:
10759     case DW_TAG_string_type:
10760       break;
10761
10762     case DW_TAG_base_type:
10763     case DW_TAG_subrange_type:
10764     case DW_TAG_typedef:
10765       /* Add a typedef symbol for the type definition, if it has a
10766          DW_AT_name.  */
10767       new_symbol (die, read_type_die (die, cu), cu);
10768       break;
10769     case DW_TAG_common_block:
10770       read_common_block (die, cu);
10771       break;
10772     case DW_TAG_common_inclusion:
10773       break;
10774     case DW_TAG_namespace:
10775       cu->processing_has_namespace_info = 1;
10776       read_namespace (die, cu);
10777       break;
10778     case DW_TAG_module:
10779       cu->processing_has_namespace_info = 1;
10780       read_module (die, cu);
10781       break;
10782     case DW_TAG_imported_declaration:
10783       cu->processing_has_namespace_info = 1;
10784       if (read_namespace_alias (die, cu))
10785         break;
10786       /* The declaration is not a global namespace alias: fall through.  */
10787     case DW_TAG_imported_module:
10788       cu->processing_has_namespace_info = 1;
10789       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10790                                  || cu->language != language_fortran))
10791         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10792                    dwarf_tag_name (die->tag));
10793       read_import_statement (die, cu);
10794       break;
10795
10796     case DW_TAG_imported_unit:
10797       process_imported_unit_die (die, cu);
10798       break;
10799
10800     case DW_TAG_variable:
10801       read_variable (die, cu);
10802       break;
10803
10804     default:
10805       new_symbol (die, NULL, cu);
10806       break;
10807     }
10808 }
10809 \f
10810 /* DWARF name computation.  */
10811
10812 /* A helper function for dwarf2_compute_name which determines whether DIE
10813    needs to have the name of the scope prepended to the name listed in the
10814    die.  */
10815
10816 static int
10817 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10818 {
10819   struct attribute *attr;
10820
10821   switch (die->tag)
10822     {
10823     case DW_TAG_namespace:
10824     case DW_TAG_typedef:
10825     case DW_TAG_class_type:
10826     case DW_TAG_interface_type:
10827     case DW_TAG_structure_type:
10828     case DW_TAG_union_type:
10829     case DW_TAG_enumeration_type:
10830     case DW_TAG_enumerator:
10831     case DW_TAG_subprogram:
10832     case DW_TAG_inlined_subroutine:
10833     case DW_TAG_member:
10834     case DW_TAG_imported_declaration:
10835       return 1;
10836
10837     case DW_TAG_variable:
10838     case DW_TAG_constant:
10839       /* We only need to prefix "globally" visible variables.  These include
10840          any variable marked with DW_AT_external or any variable that
10841          lives in a namespace.  [Variables in anonymous namespaces
10842          require prefixing, but they are not DW_AT_external.]  */
10843
10844       if (dwarf2_attr (die, DW_AT_specification, cu))
10845         {
10846           struct dwarf2_cu *spec_cu = cu;
10847
10848           return die_needs_namespace (die_specification (die, &spec_cu),
10849                                       spec_cu);
10850         }
10851
10852       attr = dwarf2_attr (die, DW_AT_external, cu);
10853       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10854           && die->parent->tag != DW_TAG_module)
10855         return 0;
10856       /* A variable in a lexical block of some kind does not need a
10857          namespace, even though in C++ such variables may be external
10858          and have a mangled name.  */
10859       if (die->parent->tag ==  DW_TAG_lexical_block
10860           || die->parent->tag ==  DW_TAG_try_block
10861           || die->parent->tag ==  DW_TAG_catch_block
10862           || die->parent->tag == DW_TAG_subprogram)
10863         return 0;
10864       return 1;
10865
10866     default:
10867       return 0;
10868     }
10869 }
10870
10871 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10872    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10873    defined for the given DIE.  */
10874
10875 static struct attribute *
10876 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10877 {
10878   struct attribute *attr;
10879
10880   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10881   if (attr == NULL)
10882     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10883
10884   return attr;
10885 }
10886
10887 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10888    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10889    defined for the given DIE.  */
10890
10891 static const char *
10892 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10893 {
10894   const char *linkage_name;
10895
10896   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10897   if (linkage_name == NULL)
10898     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10899
10900   return linkage_name;
10901 }
10902
10903 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10904    compute the physname for the object, which include a method's:
10905    - formal parameters (C++),
10906    - receiver type (Go),
10907
10908    The term "physname" is a bit confusing.
10909    For C++, for example, it is the demangled name.
10910    For Go, for example, it's the mangled name.
10911
10912    For Ada, return the DIE's linkage name rather than the fully qualified
10913    name.  PHYSNAME is ignored..
10914
10915    The result is allocated on the objfile_obstack and canonicalized.  */
10916
10917 static const char *
10918 dwarf2_compute_name (const char *name,
10919                      struct die_info *die, struct dwarf2_cu *cu,
10920                      int physname)
10921 {
10922   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10923
10924   if (name == NULL)
10925     name = dwarf2_name (die, cu);
10926
10927   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10928      but otherwise compute it by typename_concat inside GDB.
10929      FIXME: Actually this is not really true, or at least not always true.
10930      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10931      Fortran names because there is no mangling standard.  So new_symbol
10932      will set the demangled name to the result of dwarf2_full_name, and it is
10933      the demangled name that GDB uses if it exists.  */
10934   if (cu->language == language_ada
10935       || (cu->language == language_fortran && physname))
10936     {
10937       /* For Ada unit, we prefer the linkage name over the name, as
10938          the former contains the exported name, which the user expects
10939          to be able to reference.  Ideally, we want the user to be able
10940          to reference this entity using either natural or linkage name,
10941          but we haven't started looking at this enhancement yet.  */
10942       const char *linkage_name = dw2_linkage_name (die, cu);
10943
10944       if (linkage_name != NULL)
10945         return linkage_name;
10946     }
10947
10948   /* These are the only languages we know how to qualify names in.  */
10949   if (name != NULL
10950       && (cu->language == language_cplus
10951           || cu->language == language_fortran || cu->language == language_d
10952           || cu->language == language_rust))
10953     {
10954       if (die_needs_namespace (die, cu))
10955         {
10956           const char *prefix;
10957           const char *canonical_name = NULL;
10958
10959           string_file buf;
10960
10961           prefix = determine_prefix (die, cu);
10962           if (*prefix != '\0')
10963             {
10964               char *prefixed_name = typename_concat (NULL, prefix, name,
10965                                                      physname, cu);
10966
10967               buf.puts (prefixed_name);
10968               xfree (prefixed_name);
10969             }
10970           else
10971             buf.puts (name);
10972
10973           /* Template parameters may be specified in the DIE's DW_AT_name, or
10974              as children with DW_TAG_template_type_param or
10975              DW_TAG_value_type_param.  If the latter, add them to the name
10976              here.  If the name already has template parameters, then
10977              skip this step; some versions of GCC emit both, and
10978              it is more efficient to use the pre-computed name.
10979
10980              Something to keep in mind about this process: it is very
10981              unlikely, or in some cases downright impossible, to produce
10982              something that will match the mangled name of a function.
10983              If the definition of the function has the same debug info,
10984              we should be able to match up with it anyway.  But fallbacks
10985              using the minimal symbol, for instance to find a method
10986              implemented in a stripped copy of libstdc++, will not work.
10987              If we do not have debug info for the definition, we will have to
10988              match them up some other way.
10989
10990              When we do name matching there is a related problem with function
10991              templates; two instantiated function templates are allowed to
10992              differ only by their return types, which we do not add here.  */
10993
10994           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10995             {
10996               struct attribute *attr;
10997               struct die_info *child;
10998               int first = 1;
10999
11000               die->building_fullname = 1;
11001
11002               for (child = die->child; child != NULL; child = child->sibling)
11003                 {
11004                   struct type *type;
11005                   LONGEST value;
11006                   const gdb_byte *bytes;
11007                   struct dwarf2_locexpr_baton *baton;
11008                   struct value *v;
11009
11010                   if (child->tag != DW_TAG_template_type_param
11011                       && child->tag != DW_TAG_template_value_param)
11012                     continue;
11013
11014                   if (first)
11015                     {
11016                       buf.puts ("<");
11017                       first = 0;
11018                     }
11019                   else
11020                     buf.puts (", ");
11021
11022                   attr = dwarf2_attr (child, DW_AT_type, cu);
11023                   if (attr == NULL)
11024                     {
11025                       complaint (&symfile_complaints,
11026                                  _("template parameter missing DW_AT_type"));
11027                       buf.puts ("UNKNOWN_TYPE");
11028                       continue;
11029                     }
11030                   type = die_type (child, cu);
11031
11032                   if (child->tag == DW_TAG_template_type_param)
11033                     {
11034                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
11035                       continue;
11036                     }
11037
11038                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
11039                   if (attr == NULL)
11040                     {
11041                       complaint (&symfile_complaints,
11042                                  _("template parameter missing "
11043                                    "DW_AT_const_value"));
11044                       buf.puts ("UNKNOWN_VALUE");
11045                       continue;
11046                     }
11047
11048                   dwarf2_const_value_attr (attr, type, name,
11049                                            &cu->comp_unit_obstack, cu,
11050                                            &value, &bytes, &baton);
11051
11052                   if (TYPE_NOSIGN (type))
11053                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11054                        changed, this can use value_print instead.  */
11055                     c_printchar (value, type, &buf);
11056                   else
11057                     {
11058                       struct value_print_options opts;
11059
11060                       if (baton != NULL)
11061                         v = dwarf2_evaluate_loc_desc (type, NULL,
11062                                                       baton->data,
11063                                                       baton->size,
11064                                                       baton->per_cu);
11065                       else if (bytes != NULL)
11066                         {
11067                           v = allocate_value (type);
11068                           memcpy (value_contents_writeable (v), bytes,
11069                                   TYPE_LENGTH (type));
11070                         }
11071                       else
11072                         v = value_from_longest (type, value);
11073
11074                       /* Specify decimal so that we do not depend on
11075                          the radix.  */
11076                       get_formatted_print_options (&opts, 'd');
11077                       opts.raw = 1;
11078                       value_print (v, &buf, &opts);
11079                       release_value (v);
11080                       value_free (v);
11081                     }
11082                 }
11083
11084               die->building_fullname = 0;
11085
11086               if (!first)
11087                 {
11088                   /* Close the argument list, with a space if necessary
11089                      (nested templates).  */
11090                   if (!buf.empty () && buf.string ().back () == '>')
11091                     buf.puts (" >");
11092                   else
11093                     buf.puts (">");
11094                 }
11095             }
11096
11097           /* For C++ methods, append formal parameter type
11098              information, if PHYSNAME.  */
11099
11100           if (physname && die->tag == DW_TAG_subprogram
11101               && cu->language == language_cplus)
11102             {
11103               struct type *type = read_type_die (die, cu);
11104
11105               c_type_print_args (type, &buf, 1, cu->language,
11106                                  &type_print_raw_options);
11107
11108               if (cu->language == language_cplus)
11109                 {
11110                   /* Assume that an artificial first parameter is
11111                      "this", but do not crash if it is not.  RealView
11112                      marks unnamed (and thus unused) parameters as
11113                      artificial; there is no way to differentiate
11114                      the two cases.  */
11115                   if (TYPE_NFIELDS (type) > 0
11116                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11117                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11118                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11119                                                                         0))))
11120                     buf.puts (" const");
11121                 }
11122             }
11123
11124           const std::string &intermediate_name = buf.string ();
11125
11126           if (cu->language == language_cplus)
11127             canonical_name
11128               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11129                                           &objfile->per_bfd->storage_obstack);
11130
11131           /* If we only computed INTERMEDIATE_NAME, or if
11132              INTERMEDIATE_NAME is already canonical, then we need to
11133              copy it to the appropriate obstack.  */
11134           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11135             name = ((const char *)
11136                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11137                                    intermediate_name.c_str (),
11138                                    intermediate_name.length ()));
11139           else
11140             name = canonical_name;
11141         }
11142     }
11143
11144   return name;
11145 }
11146
11147 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11148    If scope qualifiers are appropriate they will be added.  The result
11149    will be allocated on the storage_obstack, or NULL if the DIE does
11150    not have a name.  NAME may either be from a previous call to
11151    dwarf2_name or NULL.
11152
11153    The output string will be canonicalized (if C++).  */
11154
11155 static const char *
11156 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11157 {
11158   return dwarf2_compute_name (name, die, cu, 0);
11159 }
11160
11161 /* Construct a physname for the given DIE in CU.  NAME may either be
11162    from a previous call to dwarf2_name or NULL.  The result will be
11163    allocated on the objfile_objstack or NULL if the DIE does not have a
11164    name.
11165
11166    The output string will be canonicalized (if C++).  */
11167
11168 static const char *
11169 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11170 {
11171   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11172   const char *retval, *mangled = NULL, *canon = NULL;
11173   int need_copy = 1;
11174
11175   /* In this case dwarf2_compute_name is just a shortcut not building anything
11176      on its own.  */
11177   if (!die_needs_namespace (die, cu))
11178     return dwarf2_compute_name (name, die, cu, 1);
11179
11180   mangled = dw2_linkage_name (die, cu);
11181
11182   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11183      See https://github.com/rust-lang/rust/issues/32925.  */
11184   if (cu->language == language_rust && mangled != NULL
11185       && strchr (mangled, '{') != NULL)
11186     mangled = NULL;
11187
11188   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11189      has computed.  */
11190   gdb::unique_xmalloc_ptr<char> demangled;
11191   if (mangled != NULL)
11192     {
11193
11194       if (cu->language == language_go)
11195         {
11196           /* This is a lie, but we already lie to the caller new_symbol.
11197              new_symbol assumes we return the mangled name.
11198              This just undoes that lie until things are cleaned up.  */
11199         }
11200       else
11201         {
11202           /* Use DMGL_RET_DROP for C++ template functions to suppress
11203              their return type.  It is easier for GDB users to search
11204              for such functions as `name(params)' than `long name(params)'.
11205              In such case the minimal symbol names do not match the full
11206              symbol names but for template functions there is never a need
11207              to look up their definition from their declaration so
11208              the only disadvantage remains the minimal symbol variant
11209              `long name(params)' does not have the proper inferior type.  */
11210           demangled.reset (gdb_demangle (mangled,
11211                                          (DMGL_PARAMS | DMGL_ANSI
11212                                           | DMGL_RET_DROP)));
11213         }
11214       if (demangled)
11215         canon = demangled.get ();
11216       else
11217         {
11218           canon = mangled;
11219           need_copy = 0;
11220         }
11221     }
11222
11223   if (canon == NULL || check_physname)
11224     {
11225       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11226
11227       if (canon != NULL && strcmp (physname, canon) != 0)
11228         {
11229           /* It may not mean a bug in GDB.  The compiler could also
11230              compute DW_AT_linkage_name incorrectly.  But in such case
11231              GDB would need to be bug-to-bug compatible.  */
11232
11233           complaint (&symfile_complaints,
11234                      _("Computed physname <%s> does not match demangled <%s> "
11235                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11236                      physname, canon, mangled, sect_offset_str (die->sect_off),
11237                      objfile_name (objfile));
11238
11239           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11240              is available here - over computed PHYSNAME.  It is safer
11241              against both buggy GDB and buggy compilers.  */
11242
11243           retval = canon;
11244         }
11245       else
11246         {
11247           retval = physname;
11248           need_copy = 0;
11249         }
11250     }
11251   else
11252     retval = canon;
11253
11254   if (need_copy)
11255     retval = ((const char *)
11256               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11257                              retval, strlen (retval)));
11258
11259   return retval;
11260 }
11261
11262 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11263    a new symbol for it.
11264
11265    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11266
11267 static int
11268 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11269 {
11270   struct attribute *attr;
11271
11272   /* If the die does not have a name, this is not a namespace
11273      alias.  */
11274   attr = dwarf2_attr (die, DW_AT_name, cu);
11275   if (attr != NULL)
11276     {
11277       int num;
11278       struct die_info *d = die;
11279       struct dwarf2_cu *imported_cu = cu;
11280
11281       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11282          keep inspecting DIEs until we hit the underlying import.  */
11283 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11284       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11285         {
11286           attr = dwarf2_attr (d, DW_AT_import, cu);
11287           if (attr == NULL)
11288             break;
11289
11290           d = follow_die_ref (d, attr, &imported_cu);
11291           if (d->tag != DW_TAG_imported_declaration)
11292             break;
11293         }
11294
11295       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11296         {
11297           complaint (&symfile_complaints,
11298                      _("DIE at %s has too many recursively imported "
11299                        "declarations"), sect_offset_str (d->sect_off));
11300           return 0;
11301         }
11302
11303       if (attr != NULL)
11304         {
11305           struct type *type;
11306           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11307
11308           type = get_die_type_at_offset (sect_off, cu->per_cu);
11309           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11310             {
11311               /* This declaration is a global namespace alias.  Add
11312                  a symbol for it whose type is the aliased namespace.  */
11313               new_symbol (die, type, cu);
11314               return 1;
11315             }
11316         }
11317     }
11318
11319   return 0;
11320 }
11321
11322 /* Return the using directives repository (global or local?) to use in the
11323    current context for LANGUAGE.
11324
11325    For Ada, imported declarations can materialize renamings, which *may* be
11326    global.  However it is impossible (for now?) in DWARF to distinguish
11327    "external" imported declarations and "static" ones.  As all imported
11328    declarations seem to be static in all other languages, make them all CU-wide
11329    global only in Ada.  */
11330
11331 static struct using_direct **
11332 using_directives (enum language language)
11333 {
11334   if (language == language_ada && context_stack_depth == 0)
11335     return &global_using_directives;
11336   else
11337     return &local_using_directives;
11338 }
11339
11340 /* Read the import statement specified by the given die and record it.  */
11341
11342 static void
11343 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11344 {
11345   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11346   struct attribute *import_attr;
11347   struct die_info *imported_die, *child_die;
11348   struct dwarf2_cu *imported_cu;
11349   const char *imported_name;
11350   const char *imported_name_prefix;
11351   const char *canonical_name;
11352   const char *import_alias;
11353   const char *imported_declaration = NULL;
11354   const char *import_prefix;
11355   std::vector<const char *> excludes;
11356
11357   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11358   if (import_attr == NULL)
11359     {
11360       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11361                  dwarf_tag_name (die->tag));
11362       return;
11363     }
11364
11365   imported_cu = cu;
11366   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11367   imported_name = dwarf2_name (imported_die, imported_cu);
11368   if (imported_name == NULL)
11369     {
11370       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11371
11372         The import in the following code:
11373         namespace A
11374           {
11375             typedef int B;
11376           }
11377
11378         int main ()
11379           {
11380             using A::B;
11381             B b;
11382             return b;
11383           }
11384
11385         ...
11386          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11387             <52>   DW_AT_decl_file   : 1
11388             <53>   DW_AT_decl_line   : 6
11389             <54>   DW_AT_import      : <0x75>
11390          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11391             <59>   DW_AT_name        : B
11392             <5b>   DW_AT_decl_file   : 1
11393             <5c>   DW_AT_decl_line   : 2
11394             <5d>   DW_AT_type        : <0x6e>
11395         ...
11396          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11397             <76>   DW_AT_byte_size   : 4
11398             <77>   DW_AT_encoding    : 5        (signed)
11399
11400         imports the wrong die ( 0x75 instead of 0x58 ).
11401         This case will be ignored until the gcc bug is fixed.  */
11402       return;
11403     }
11404
11405   /* Figure out the local name after import.  */
11406   import_alias = dwarf2_name (die, cu);
11407
11408   /* Figure out where the statement is being imported to.  */
11409   import_prefix = determine_prefix (die, cu);
11410
11411   /* Figure out what the scope of the imported die is and prepend it
11412      to the name of the imported die.  */
11413   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11414
11415   if (imported_die->tag != DW_TAG_namespace
11416       && imported_die->tag != DW_TAG_module)
11417     {
11418       imported_declaration = imported_name;
11419       canonical_name = imported_name_prefix;
11420     }
11421   else if (strlen (imported_name_prefix) > 0)
11422     canonical_name = obconcat (&objfile->objfile_obstack,
11423                                imported_name_prefix,
11424                                (cu->language == language_d ? "." : "::"),
11425                                imported_name, (char *) NULL);
11426   else
11427     canonical_name = imported_name;
11428
11429   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11430     for (child_die = die->child; child_die && child_die->tag;
11431          child_die = sibling_die (child_die))
11432       {
11433         /* DWARF-4: A Fortran use statement with a “rename list” may be
11434            represented by an imported module entry with an import attribute
11435            referring to the module and owned entries corresponding to those
11436            entities that are renamed as part of being imported.  */
11437
11438         if (child_die->tag != DW_TAG_imported_declaration)
11439           {
11440             complaint (&symfile_complaints,
11441                        _("child DW_TAG_imported_declaration expected "
11442                          "- DIE at %s [in module %s]"),
11443                        sect_offset_str (child_die->sect_off),
11444                        objfile_name (objfile));
11445             continue;
11446           }
11447
11448         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11449         if (import_attr == NULL)
11450           {
11451             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11452                        dwarf_tag_name (child_die->tag));
11453             continue;
11454           }
11455
11456         imported_cu = cu;
11457         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11458                                               &imported_cu);
11459         imported_name = dwarf2_name (imported_die, imported_cu);
11460         if (imported_name == NULL)
11461           {
11462             complaint (&symfile_complaints,
11463                        _("child DW_TAG_imported_declaration has unknown "
11464                          "imported name - DIE at %s [in module %s]"),
11465                        sect_offset_str (child_die->sect_off),
11466                        objfile_name (objfile));
11467             continue;
11468           }
11469
11470         excludes.push_back (imported_name);
11471
11472         process_die (child_die, cu);
11473       }
11474
11475   add_using_directive (using_directives (cu->language),
11476                        import_prefix,
11477                        canonical_name,
11478                        import_alias,
11479                        imported_declaration,
11480                        excludes,
11481                        0,
11482                        &objfile->objfile_obstack);
11483 }
11484
11485 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11486    types, but gives them a size of zero.  Starting with version 14,
11487    ICC is compatible with GCC.  */
11488
11489 static int
11490 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11491 {
11492   if (!cu->checked_producer)
11493     check_producer (cu);
11494
11495   return cu->producer_is_icc_lt_14;
11496 }
11497
11498 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11499    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11500    this, it was first present in GCC release 4.3.0.  */
11501
11502 static int
11503 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11504 {
11505   if (!cu->checked_producer)
11506     check_producer (cu);
11507
11508   return cu->producer_is_gcc_lt_4_3;
11509 }
11510
11511 static file_and_directory
11512 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11513 {
11514   file_and_directory res;
11515
11516   /* Find the filename.  Do not use dwarf2_name here, since the filename
11517      is not a source language identifier.  */
11518   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11519   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11520
11521   if (res.comp_dir == NULL
11522       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11523       && IS_ABSOLUTE_PATH (res.name))
11524     {
11525       res.comp_dir_storage = ldirname (res.name);
11526       if (!res.comp_dir_storage.empty ())
11527         res.comp_dir = res.comp_dir_storage.c_str ();
11528     }
11529   if (res.comp_dir != NULL)
11530     {
11531       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11532          directory, get rid of it.  */
11533       const char *cp = strchr (res.comp_dir, ':');
11534
11535       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11536         res.comp_dir = cp + 1;
11537     }
11538
11539   if (res.name == NULL)
11540     res.name = "<unknown>";
11541
11542   return res;
11543 }
11544
11545 /* Handle DW_AT_stmt_list for a compilation unit.
11546    DIE is the DW_TAG_compile_unit die for CU.
11547    COMP_DIR is the compilation directory.  LOWPC is passed to
11548    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11549
11550 static void
11551 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11552                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11553 {
11554   struct dwarf2_per_objfile *dwarf2_per_objfile
11555     = cu->per_cu->dwarf2_per_objfile;
11556   struct objfile *objfile = dwarf2_per_objfile->objfile;
11557   struct attribute *attr;
11558   struct line_header line_header_local;
11559   hashval_t line_header_local_hash;
11560   void **slot;
11561   int decode_mapping;
11562
11563   gdb_assert (! cu->per_cu->is_debug_types);
11564
11565   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11566   if (attr == NULL)
11567     return;
11568
11569   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11570
11571   /* The line header hash table is only created if needed (it exists to
11572      prevent redundant reading of the line table for partial_units).
11573      If we're given a partial_unit, we'll need it.  If we're given a
11574      compile_unit, then use the line header hash table if it's already
11575      created, but don't create one just yet.  */
11576
11577   if (dwarf2_per_objfile->line_header_hash == NULL
11578       && die->tag == DW_TAG_partial_unit)
11579     {
11580       dwarf2_per_objfile->line_header_hash
11581         = htab_create_alloc_ex (127, line_header_hash_voidp,
11582                                 line_header_eq_voidp,
11583                                 free_line_header_voidp,
11584                                 &objfile->objfile_obstack,
11585                                 hashtab_obstack_allocate,
11586                                 dummy_obstack_deallocate);
11587     }
11588
11589   line_header_local.sect_off = line_offset;
11590   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11591   line_header_local_hash = line_header_hash (&line_header_local);
11592   if (dwarf2_per_objfile->line_header_hash != NULL)
11593     {
11594       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11595                                        &line_header_local,
11596                                        line_header_local_hash, NO_INSERT);
11597
11598       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11599          is not present in *SLOT (since if there is something in *SLOT then
11600          it will be for a partial_unit).  */
11601       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11602         {
11603           gdb_assert (*slot != NULL);
11604           cu->line_header = (struct line_header *) *slot;
11605           return;
11606         }
11607     }
11608
11609   /* dwarf_decode_line_header does not yet provide sufficient information.
11610      We always have to call also dwarf_decode_lines for it.  */
11611   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11612   if (lh == NULL)
11613     return;
11614
11615   cu->line_header = lh.release ();
11616   cu->line_header_die_owner = die;
11617
11618   if (dwarf2_per_objfile->line_header_hash == NULL)
11619     slot = NULL;
11620   else
11621     {
11622       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11623                                        &line_header_local,
11624                                        line_header_local_hash, INSERT);
11625       gdb_assert (slot != NULL);
11626     }
11627   if (slot != NULL && *slot == NULL)
11628     {
11629       /* This newly decoded line number information unit will be owned
11630          by line_header_hash hash table.  */
11631       *slot = cu->line_header;
11632       cu->line_header_die_owner = NULL;
11633     }
11634   else
11635     {
11636       /* We cannot free any current entry in (*slot) as that struct line_header
11637          may be already used by multiple CUs.  Create only temporary decoded
11638          line_header for this CU - it may happen at most once for each line
11639          number information unit.  And if we're not using line_header_hash
11640          then this is what we want as well.  */
11641       gdb_assert (die->tag != DW_TAG_partial_unit);
11642     }
11643   decode_mapping = (die->tag != DW_TAG_partial_unit);
11644   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11645                       decode_mapping);
11646
11647 }
11648
11649 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11650
11651 static void
11652 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11653 {
11654   struct dwarf2_per_objfile *dwarf2_per_objfile
11655     = cu->per_cu->dwarf2_per_objfile;
11656   struct objfile *objfile = dwarf2_per_objfile->objfile;
11657   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11658   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11659   CORE_ADDR highpc = ((CORE_ADDR) 0);
11660   struct attribute *attr;
11661   struct die_info *child_die;
11662   CORE_ADDR baseaddr;
11663
11664   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11665
11666   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11667
11668   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11669      from finish_block.  */
11670   if (lowpc == ((CORE_ADDR) -1))
11671     lowpc = highpc;
11672   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11673
11674   file_and_directory fnd = find_file_and_directory (die, cu);
11675
11676   prepare_one_comp_unit (cu, die, cu->language);
11677
11678   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11679      standardised yet.  As a workaround for the language detection we fall
11680      back to the DW_AT_producer string.  */
11681   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11682     cu->language = language_opencl;
11683
11684   /* Similar hack for Go.  */
11685   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11686     set_cu_language (DW_LANG_Go, cu);
11687
11688   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11689
11690   /* Decode line number information if present.  We do this before
11691      processing child DIEs, so that the line header table is available
11692      for DW_AT_decl_file.  */
11693   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11694
11695   /* Process all dies in compilation unit.  */
11696   if (die->child != NULL)
11697     {
11698       child_die = die->child;
11699       while (child_die && child_die->tag)
11700         {
11701           process_die (child_die, cu);
11702           child_die = sibling_die (child_die);
11703         }
11704     }
11705
11706   /* Decode macro information, if present.  Dwarf 2 macro information
11707      refers to information in the line number info statement program
11708      header, so we can only read it if we've read the header
11709      successfully.  */
11710   attr = dwarf2_attr (die, DW_AT_macros, cu);
11711   if (attr == NULL)
11712     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11713   if (attr && cu->line_header)
11714     {
11715       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11716         complaint (&symfile_complaints,
11717                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11718
11719       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11720     }
11721   else
11722     {
11723       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11724       if (attr && cu->line_header)
11725         {
11726           unsigned int macro_offset = DW_UNSND (attr);
11727
11728           dwarf_decode_macros (cu, macro_offset, 0);
11729         }
11730     }
11731 }
11732
11733 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11734    Create the set of symtabs used by this TU, or if this TU is sharing
11735    symtabs with another TU and the symtabs have already been created
11736    then restore those symtabs in the line header.
11737    We don't need the pc/line-number mapping for type units.  */
11738
11739 static void
11740 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11741 {
11742   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11743   struct type_unit_group *tu_group;
11744   int first_time;
11745   struct attribute *attr;
11746   unsigned int i;
11747   struct signatured_type *sig_type;
11748
11749   gdb_assert (per_cu->is_debug_types);
11750   sig_type = (struct signatured_type *) per_cu;
11751
11752   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11753
11754   /* If we're using .gdb_index (includes -readnow) then
11755      per_cu->type_unit_group may not have been set up yet.  */
11756   if (sig_type->type_unit_group == NULL)
11757     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11758   tu_group = sig_type->type_unit_group;
11759
11760   /* If we've already processed this stmt_list there's no real need to
11761      do it again, we could fake it and just recreate the part we need
11762      (file name,index -> symtab mapping).  If data shows this optimization
11763      is useful we can do it then.  */
11764   first_time = tu_group->compunit_symtab == NULL;
11765
11766   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11767      debug info.  */
11768   line_header_up lh;
11769   if (attr != NULL)
11770     {
11771       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11772       lh = dwarf_decode_line_header (line_offset, cu);
11773     }
11774   if (lh == NULL)
11775     {
11776       if (first_time)
11777         dwarf2_start_symtab (cu, "", NULL, 0);
11778       else
11779         {
11780           gdb_assert (tu_group->symtabs == NULL);
11781           restart_symtab (tu_group->compunit_symtab, "", 0);
11782         }
11783       return;
11784     }
11785
11786   cu->line_header = lh.release ();
11787   cu->line_header_die_owner = die;
11788
11789   if (first_time)
11790     {
11791       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11792
11793       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11794          still initializing it, and our caller (a few levels up)
11795          process_full_type_unit still needs to know if this is the first
11796          time.  */
11797
11798       tu_group->num_symtabs = cu->line_header->file_names.size ();
11799       tu_group->symtabs = XNEWVEC (struct symtab *,
11800                                    cu->line_header->file_names.size ());
11801
11802       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11803         {
11804           file_entry &fe = cu->line_header->file_names[i];
11805
11806           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11807
11808           if (current_subfile->symtab == NULL)
11809             {
11810               /* NOTE: start_subfile will recognize when it's been
11811                  passed a file it has already seen.  So we can't
11812                  assume there's a simple mapping from
11813                  cu->line_header->file_names to subfiles, plus
11814                  cu->line_header->file_names may contain dups.  */
11815               current_subfile->symtab
11816                 = allocate_symtab (cust, current_subfile->name);
11817             }
11818
11819           fe.symtab = current_subfile->symtab;
11820           tu_group->symtabs[i] = fe.symtab;
11821         }
11822     }
11823   else
11824     {
11825       restart_symtab (tu_group->compunit_symtab, "", 0);
11826
11827       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11828         {
11829           file_entry &fe = cu->line_header->file_names[i];
11830
11831           fe.symtab = tu_group->symtabs[i];
11832         }
11833     }
11834
11835   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11836      so they don't have a "real" (so to speak) symtab anyway.
11837      There is later code that will assign the main symtab to all symbols
11838      that don't have one.  We need to handle the case of a symbol with a
11839      missing symtab (DW_AT_decl_file) anyway.  */
11840 }
11841
11842 /* Process DW_TAG_type_unit.
11843    For TUs we want to skip the first top level sibling if it's not the
11844    actual type being defined by this TU.  In this case the first top
11845    level sibling is there to provide context only.  */
11846
11847 static void
11848 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11849 {
11850   struct die_info *child_die;
11851
11852   prepare_one_comp_unit (cu, die, language_minimal);
11853
11854   /* Initialize (or reinitialize) the machinery for building symtabs.
11855      We do this before processing child DIEs, so that the line header table
11856      is available for DW_AT_decl_file.  */
11857   setup_type_unit_groups (die, cu);
11858
11859   if (die->child != NULL)
11860     {
11861       child_die = die->child;
11862       while (child_die && child_die->tag)
11863         {
11864           process_die (child_die, cu);
11865           child_die = sibling_die (child_die);
11866         }
11867     }
11868 }
11869 \f
11870 /* DWO/DWP files.
11871
11872    http://gcc.gnu.org/wiki/DebugFission
11873    http://gcc.gnu.org/wiki/DebugFissionDWP
11874
11875    To simplify handling of both DWO files ("object" files with the DWARF info)
11876    and DWP files (a file with the DWOs packaged up into one file), we treat
11877    DWP files as having a collection of virtual DWO files.  */
11878
11879 static hashval_t
11880 hash_dwo_file (const void *item)
11881 {
11882   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11883   hashval_t hash;
11884
11885   hash = htab_hash_string (dwo_file->dwo_name);
11886   if (dwo_file->comp_dir != NULL)
11887     hash += htab_hash_string (dwo_file->comp_dir);
11888   return hash;
11889 }
11890
11891 static int
11892 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11893 {
11894   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11895   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11896
11897   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11898     return 0;
11899   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11900     return lhs->comp_dir == rhs->comp_dir;
11901   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11902 }
11903
11904 /* Allocate a hash table for DWO files.  */
11905
11906 static htab_t
11907 allocate_dwo_file_hash_table (struct objfile *objfile)
11908 {
11909   return htab_create_alloc_ex (41,
11910                                hash_dwo_file,
11911                                eq_dwo_file,
11912                                NULL,
11913                                &objfile->objfile_obstack,
11914                                hashtab_obstack_allocate,
11915                                dummy_obstack_deallocate);
11916 }
11917
11918 /* Lookup DWO file DWO_NAME.  */
11919
11920 static void **
11921 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11922                       const char *dwo_name,
11923                       const char *comp_dir)
11924 {
11925   struct dwo_file find_entry;
11926   void **slot;
11927
11928   if (dwarf2_per_objfile->dwo_files == NULL)
11929     dwarf2_per_objfile->dwo_files
11930       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11931
11932   memset (&find_entry, 0, sizeof (find_entry));
11933   find_entry.dwo_name = dwo_name;
11934   find_entry.comp_dir = comp_dir;
11935   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11936
11937   return slot;
11938 }
11939
11940 static hashval_t
11941 hash_dwo_unit (const void *item)
11942 {
11943   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11944
11945   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11946   return dwo_unit->signature;
11947 }
11948
11949 static int
11950 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11951 {
11952   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11953   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11954
11955   /* The signature is assumed to be unique within the DWO file.
11956      So while object file CU dwo_id's always have the value zero,
11957      that's OK, assuming each object file DWO file has only one CU,
11958      and that's the rule for now.  */
11959   return lhs->signature == rhs->signature;
11960 }
11961
11962 /* Allocate a hash table for DWO CUs,TUs.
11963    There is one of these tables for each of CUs,TUs for each DWO file.  */
11964
11965 static htab_t
11966 allocate_dwo_unit_table (struct objfile *objfile)
11967 {
11968   /* Start out with a pretty small number.
11969      Generally DWO files contain only one CU and maybe some TUs.  */
11970   return htab_create_alloc_ex (3,
11971                                hash_dwo_unit,
11972                                eq_dwo_unit,
11973                                NULL,
11974                                &objfile->objfile_obstack,
11975                                hashtab_obstack_allocate,
11976                                dummy_obstack_deallocate);
11977 }
11978
11979 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11980
11981 struct create_dwo_cu_data
11982 {
11983   struct dwo_file *dwo_file;
11984   struct dwo_unit dwo_unit;
11985 };
11986
11987 /* die_reader_func for create_dwo_cu.  */
11988
11989 static void
11990 create_dwo_cu_reader (const struct die_reader_specs *reader,
11991                       const gdb_byte *info_ptr,
11992                       struct die_info *comp_unit_die,
11993                       int has_children,
11994                       void *datap)
11995 {
11996   struct dwarf2_cu *cu = reader->cu;
11997   sect_offset sect_off = cu->per_cu->sect_off;
11998   struct dwarf2_section_info *section = cu->per_cu->section;
11999   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
12000   struct dwo_file *dwo_file = data->dwo_file;
12001   struct dwo_unit *dwo_unit = &data->dwo_unit;
12002   struct attribute *attr;
12003
12004   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
12005   if (attr == NULL)
12006     {
12007       complaint (&symfile_complaints,
12008                  _("Dwarf Error: debug entry at offset %s is missing"
12009                    " its dwo_id [in module %s]"),
12010                  sect_offset_str (sect_off), dwo_file->dwo_name);
12011       return;
12012     }
12013
12014   dwo_unit->dwo_file = dwo_file;
12015   dwo_unit->signature = DW_UNSND (attr);
12016   dwo_unit->section = section;
12017   dwo_unit->sect_off = sect_off;
12018   dwo_unit->length = cu->per_cu->length;
12019
12020   if (dwarf_read_debug)
12021     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
12022                         sect_offset_str (sect_off),
12023                         hex_string (dwo_unit->signature));
12024 }
12025
12026 /* Create the dwo_units for the CUs in a DWO_FILE.
12027    Note: This function processes DWO files only, not DWP files.  */
12028
12029 static void
12030 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12031                        struct dwo_file &dwo_file, dwarf2_section_info &section,
12032                        htab_t &cus_htab)
12033 {
12034   struct objfile *objfile = dwarf2_per_objfile->objfile;
12035   const gdb_byte *info_ptr, *end_ptr;
12036
12037   dwarf2_read_section (objfile, &section);
12038   info_ptr = section.buffer;
12039
12040   if (info_ptr == NULL)
12041     return;
12042
12043   if (dwarf_read_debug)
12044     {
12045       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12046                           get_section_name (&section),
12047                           get_section_file_name (&section));
12048     }
12049
12050   end_ptr = info_ptr + section.size;
12051   while (info_ptr < end_ptr)
12052     {
12053       struct dwarf2_per_cu_data per_cu;
12054       struct create_dwo_cu_data create_dwo_cu_data;
12055       struct dwo_unit *dwo_unit;
12056       void **slot;
12057       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12058
12059       memset (&create_dwo_cu_data.dwo_unit, 0,
12060               sizeof (create_dwo_cu_data.dwo_unit));
12061       memset (&per_cu, 0, sizeof (per_cu));
12062       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12063       per_cu.is_debug_types = 0;
12064       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12065       per_cu.section = &section;
12066       create_dwo_cu_data.dwo_file = &dwo_file;
12067
12068       init_cutu_and_read_dies_no_follow (
12069           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12070       info_ptr += per_cu.length;
12071
12072       // If the unit could not be parsed, skip it.
12073       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12074         continue;
12075
12076       if (cus_htab == NULL)
12077         cus_htab = allocate_dwo_unit_table (objfile);
12078
12079       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12080       *dwo_unit = create_dwo_cu_data.dwo_unit;
12081       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12082       gdb_assert (slot != NULL);
12083       if (*slot != NULL)
12084         {
12085           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12086           sect_offset dup_sect_off = dup_cu->sect_off;
12087
12088           complaint (&symfile_complaints,
12089                      _("debug cu entry at offset %s is duplicate to"
12090                        " the entry at offset %s, signature %s"),
12091                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
12092                      hex_string (dwo_unit->signature));
12093         }
12094       *slot = (void *)dwo_unit;
12095     }
12096 }
12097
12098 /* DWP file .debug_{cu,tu}_index section format:
12099    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12100
12101    DWP Version 1:
12102
12103    Both index sections have the same format, and serve to map a 64-bit
12104    signature to a set of section numbers.  Each section begins with a header,
12105    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12106    indexes, and a pool of 32-bit section numbers.  The index sections will be
12107    aligned at 8-byte boundaries in the file.
12108
12109    The index section header consists of:
12110
12111     V, 32 bit version number
12112     -, 32 bits unused
12113     N, 32 bit number of compilation units or type units in the index
12114     M, 32 bit number of slots in the hash table
12115
12116    Numbers are recorded using the byte order of the application binary.
12117
12118    The hash table begins at offset 16 in the section, and consists of an array
12119    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12120    order of the application binary).  Unused slots in the hash table are 0.
12121    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12122
12123    The parallel table begins immediately after the hash table
12124    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12125    array of 32-bit indexes (using the byte order of the application binary),
12126    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12127    table contains a 32-bit index into the pool of section numbers.  For unused
12128    hash table slots, the corresponding entry in the parallel table will be 0.
12129
12130    The pool of section numbers begins immediately following the hash table
12131    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12132    section numbers consists of an array of 32-bit words (using the byte order
12133    of the application binary).  Each item in the array is indexed starting
12134    from 0.  The hash table entry provides the index of the first section
12135    number in the set.  Additional section numbers in the set follow, and the
12136    set is terminated by a 0 entry (section number 0 is not used in ELF).
12137
12138    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12139    section must be the first entry in the set, and the .debug_abbrev.dwo must
12140    be the second entry. Other members of the set may follow in any order.
12141
12142    ---
12143
12144    DWP Version 2:
12145
12146    DWP Version 2 combines all the .debug_info, etc. sections into one,
12147    and the entries in the index tables are now offsets into these sections.
12148    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12149    section.
12150
12151    Index Section Contents:
12152     Header
12153     Hash Table of Signatures   dwp_hash_table.hash_table
12154     Parallel Table of Indices  dwp_hash_table.unit_table
12155     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12156     Table of Section Sizes     dwp_hash_table.v2.sizes
12157
12158    The index section header consists of:
12159
12160     V, 32 bit version number
12161     L, 32 bit number of columns in the table of section offsets
12162     N, 32 bit number of compilation units or type units in the index
12163     M, 32 bit number of slots in the hash table
12164
12165    Numbers are recorded using the byte order of the application binary.
12166
12167    The hash table has the same format as version 1.
12168    The parallel table of indices has the same format as version 1,
12169    except that the entries are origin-1 indices into the table of sections
12170    offsets and the table of section sizes.
12171
12172    The table of offsets begins immediately following the parallel table
12173    (at offset 16 + 12 * M from the beginning of the section).  The table is
12174    a two-dimensional array of 32-bit words (using the byte order of the
12175    application binary), with L columns and N+1 rows, in row-major order.
12176    Each row in the array is indexed starting from 0.  The first row provides
12177    a key to the remaining rows: each column in this row provides an identifier
12178    for a debug section, and the offsets in the same column of subsequent rows
12179    refer to that section.  The section identifiers are:
12180
12181     DW_SECT_INFO         1  .debug_info.dwo
12182     DW_SECT_TYPES        2  .debug_types.dwo
12183     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12184     DW_SECT_LINE         4  .debug_line.dwo
12185     DW_SECT_LOC          5  .debug_loc.dwo
12186     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12187     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12188     DW_SECT_MACRO        8  .debug_macro.dwo
12189
12190    The offsets provided by the CU and TU index sections are the base offsets
12191    for the contributions made by each CU or TU to the corresponding section
12192    in the package file.  Each CU and TU header contains an abbrev_offset
12193    field, used to find the abbreviations table for that CU or TU within the
12194    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12195    be interpreted as relative to the base offset given in the index section.
12196    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12197    should be interpreted as relative to the base offset for .debug_line.dwo,
12198    and offsets into other debug sections obtained from DWARF attributes should
12199    also be interpreted as relative to the corresponding base offset.
12200
12201    The table of sizes begins immediately following the table of offsets.
12202    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12203    with L columns and N rows, in row-major order.  Each row in the array is
12204    indexed starting from 1 (row 0 is shared by the two tables).
12205
12206    ---
12207
12208    Hash table lookup is handled the same in version 1 and 2:
12209
12210    We assume that N and M will not exceed 2^32 - 1.
12211    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12212
12213    Given a 64-bit compilation unit signature or a type signature S, an entry
12214    in the hash table is located as follows:
12215
12216    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12217       the low-order k bits all set to 1.
12218
12219    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12220
12221    3) If the hash table entry at index H matches the signature, use that
12222       entry.  If the hash table entry at index H is unused (all zeroes),
12223       terminate the search: the signature is not present in the table.
12224
12225    4) Let H = (H + H') modulo M. Repeat at Step 3.
12226
12227    Because M > N and H' and M are relatively prime, the search is guaranteed
12228    to stop at an unused slot or find the match.  */
12229
12230 /* Create a hash table to map DWO IDs to their CU/TU entry in
12231    .debug_{info,types}.dwo in DWP_FILE.
12232    Returns NULL if there isn't one.
12233    Note: This function processes DWP files only, not DWO files.  */
12234
12235 static struct dwp_hash_table *
12236 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12237                        struct dwp_file *dwp_file, int is_debug_types)
12238 {
12239   struct objfile *objfile = dwarf2_per_objfile->objfile;
12240   bfd *dbfd = dwp_file->dbfd;
12241   const gdb_byte *index_ptr, *index_end;
12242   struct dwarf2_section_info *index;
12243   uint32_t version, nr_columns, nr_units, nr_slots;
12244   struct dwp_hash_table *htab;
12245
12246   if (is_debug_types)
12247     index = &dwp_file->sections.tu_index;
12248   else
12249     index = &dwp_file->sections.cu_index;
12250
12251   if (dwarf2_section_empty_p (index))
12252     return NULL;
12253   dwarf2_read_section (objfile, index);
12254
12255   index_ptr = index->buffer;
12256   index_end = index_ptr + index->size;
12257
12258   version = read_4_bytes (dbfd, index_ptr);
12259   index_ptr += 4;
12260   if (version == 2)
12261     nr_columns = read_4_bytes (dbfd, index_ptr);
12262   else
12263     nr_columns = 0;
12264   index_ptr += 4;
12265   nr_units = read_4_bytes (dbfd, index_ptr);
12266   index_ptr += 4;
12267   nr_slots = read_4_bytes (dbfd, index_ptr);
12268   index_ptr += 4;
12269
12270   if (version != 1 && version != 2)
12271     {
12272       error (_("Dwarf Error: unsupported DWP file version (%s)"
12273                " [in module %s]"),
12274              pulongest (version), dwp_file->name);
12275     }
12276   if (nr_slots != (nr_slots & -nr_slots))
12277     {
12278       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12279                " is not power of 2 [in module %s]"),
12280              pulongest (nr_slots), dwp_file->name);
12281     }
12282
12283   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12284   htab->version = version;
12285   htab->nr_columns = nr_columns;
12286   htab->nr_units = nr_units;
12287   htab->nr_slots = nr_slots;
12288   htab->hash_table = index_ptr;
12289   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12290
12291   /* Exit early if the table is empty.  */
12292   if (nr_slots == 0 || nr_units == 0
12293       || (version == 2 && nr_columns == 0))
12294     {
12295       /* All must be zero.  */
12296       if (nr_slots != 0 || nr_units != 0
12297           || (version == 2 && nr_columns != 0))
12298         {
12299           complaint (&symfile_complaints,
12300                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12301                        " all zero [in modules %s]"),
12302                      dwp_file->name);
12303         }
12304       return htab;
12305     }
12306
12307   if (version == 1)
12308     {
12309       htab->section_pool.v1.indices =
12310         htab->unit_table + sizeof (uint32_t) * nr_slots;
12311       /* It's harder to decide whether the section is too small in v1.
12312          V1 is deprecated anyway so we punt.  */
12313     }
12314   else
12315     {
12316       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12317       int *ids = htab->section_pool.v2.section_ids;
12318       /* Reverse map for error checking.  */
12319       int ids_seen[DW_SECT_MAX + 1];
12320       int i;
12321
12322       if (nr_columns < 2)
12323         {
12324           error (_("Dwarf Error: bad DWP hash table, too few columns"
12325                    " in section table [in module %s]"),
12326                  dwp_file->name);
12327         }
12328       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12329         {
12330           error (_("Dwarf Error: bad DWP hash table, too many columns"
12331                    " in section table [in module %s]"),
12332                  dwp_file->name);
12333         }
12334       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12335       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12336       for (i = 0; i < nr_columns; ++i)
12337         {
12338           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12339
12340           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12341             {
12342               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12343                        " in section table [in module %s]"),
12344                      id, dwp_file->name);
12345             }
12346           if (ids_seen[id] != -1)
12347             {
12348               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12349                        " id %d in section table [in module %s]"),
12350                      id, dwp_file->name);
12351             }
12352           ids_seen[id] = i;
12353           ids[i] = id;
12354         }
12355       /* Must have exactly one info or types section.  */
12356       if (((ids_seen[DW_SECT_INFO] != -1)
12357            + (ids_seen[DW_SECT_TYPES] != -1))
12358           != 1)
12359         {
12360           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12361                    " DWO info/types section [in module %s]"),
12362                  dwp_file->name);
12363         }
12364       /* Must have an abbrev section.  */
12365       if (ids_seen[DW_SECT_ABBREV] == -1)
12366         {
12367           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12368                    " section [in module %s]"),
12369                  dwp_file->name);
12370         }
12371       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12372       htab->section_pool.v2.sizes =
12373         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12374                                          * nr_units * nr_columns);
12375       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12376                                           * nr_units * nr_columns))
12377           > index_end)
12378         {
12379           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12380                    " [in module %s]"),
12381                  dwp_file->name);
12382         }
12383     }
12384
12385   return htab;
12386 }
12387
12388 /* Update SECTIONS with the data from SECTP.
12389
12390    This function is like the other "locate" section routines that are
12391    passed to bfd_map_over_sections, but in this context the sections to
12392    read comes from the DWP V1 hash table, not the full ELF section table.
12393
12394    The result is non-zero for success, or zero if an error was found.  */
12395
12396 static int
12397 locate_v1_virtual_dwo_sections (asection *sectp,
12398                                 struct virtual_v1_dwo_sections *sections)
12399 {
12400   const struct dwop_section_names *names = &dwop_section_names;
12401
12402   if (section_is_p (sectp->name, &names->abbrev_dwo))
12403     {
12404       /* There can be only one.  */
12405       if (sections->abbrev.s.section != NULL)
12406         return 0;
12407       sections->abbrev.s.section = sectp;
12408       sections->abbrev.size = bfd_get_section_size (sectp);
12409     }
12410   else if (section_is_p (sectp->name, &names->info_dwo)
12411            || section_is_p (sectp->name, &names->types_dwo))
12412     {
12413       /* There can be only one.  */
12414       if (sections->info_or_types.s.section != NULL)
12415         return 0;
12416       sections->info_or_types.s.section = sectp;
12417       sections->info_or_types.size = bfd_get_section_size (sectp);
12418     }
12419   else if (section_is_p (sectp->name, &names->line_dwo))
12420     {
12421       /* There can be only one.  */
12422       if (sections->line.s.section != NULL)
12423         return 0;
12424       sections->line.s.section = sectp;
12425       sections->line.size = bfd_get_section_size (sectp);
12426     }
12427   else if (section_is_p (sectp->name, &names->loc_dwo))
12428     {
12429       /* There can be only one.  */
12430       if (sections->loc.s.section != NULL)
12431         return 0;
12432       sections->loc.s.section = sectp;
12433       sections->loc.size = bfd_get_section_size (sectp);
12434     }
12435   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12436     {
12437       /* There can be only one.  */
12438       if (sections->macinfo.s.section != NULL)
12439         return 0;
12440       sections->macinfo.s.section = sectp;
12441       sections->macinfo.size = bfd_get_section_size (sectp);
12442     }
12443   else if (section_is_p (sectp->name, &names->macro_dwo))
12444     {
12445       /* There can be only one.  */
12446       if (sections->macro.s.section != NULL)
12447         return 0;
12448       sections->macro.s.section = sectp;
12449       sections->macro.size = bfd_get_section_size (sectp);
12450     }
12451   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12452     {
12453       /* There can be only one.  */
12454       if (sections->str_offsets.s.section != NULL)
12455         return 0;
12456       sections->str_offsets.s.section = sectp;
12457       sections->str_offsets.size = bfd_get_section_size (sectp);
12458     }
12459   else
12460     {
12461       /* No other kind of section is valid.  */
12462       return 0;
12463     }
12464
12465   return 1;
12466 }
12467
12468 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12469    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12470    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12471    This is for DWP version 1 files.  */
12472
12473 static struct dwo_unit *
12474 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12475                            struct dwp_file *dwp_file,
12476                            uint32_t unit_index,
12477                            const char *comp_dir,
12478                            ULONGEST signature, int is_debug_types)
12479 {
12480   struct objfile *objfile = dwarf2_per_objfile->objfile;
12481   const struct dwp_hash_table *dwp_htab =
12482     is_debug_types ? dwp_file->tus : dwp_file->cus;
12483   bfd *dbfd = dwp_file->dbfd;
12484   const char *kind = is_debug_types ? "TU" : "CU";
12485   struct dwo_file *dwo_file;
12486   struct dwo_unit *dwo_unit;
12487   struct virtual_v1_dwo_sections sections;
12488   void **dwo_file_slot;
12489   int i;
12490
12491   gdb_assert (dwp_file->version == 1);
12492
12493   if (dwarf_read_debug)
12494     {
12495       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12496                           kind,
12497                           pulongest (unit_index), hex_string (signature),
12498                           dwp_file->name);
12499     }
12500
12501   /* Fetch the sections of this DWO unit.
12502      Put a limit on the number of sections we look for so that bad data
12503      doesn't cause us to loop forever.  */
12504
12505 #define MAX_NR_V1_DWO_SECTIONS \
12506   (1 /* .debug_info or .debug_types */ \
12507    + 1 /* .debug_abbrev */ \
12508    + 1 /* .debug_line */ \
12509    + 1 /* .debug_loc */ \
12510    + 1 /* .debug_str_offsets */ \
12511    + 1 /* .debug_macro or .debug_macinfo */ \
12512    + 1 /* trailing zero */)
12513
12514   memset (&sections, 0, sizeof (sections));
12515
12516   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12517     {
12518       asection *sectp;
12519       uint32_t section_nr =
12520         read_4_bytes (dbfd,
12521                       dwp_htab->section_pool.v1.indices
12522                       + (unit_index + i) * sizeof (uint32_t));
12523
12524       if (section_nr == 0)
12525         break;
12526       if (section_nr >= dwp_file->num_sections)
12527         {
12528           error (_("Dwarf Error: bad DWP hash table, section number too large"
12529                    " [in module %s]"),
12530                  dwp_file->name);
12531         }
12532
12533       sectp = dwp_file->elf_sections[section_nr];
12534       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12535         {
12536           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12537                    " [in module %s]"),
12538                  dwp_file->name);
12539         }
12540     }
12541
12542   if (i < 2
12543       || dwarf2_section_empty_p (&sections.info_or_types)
12544       || dwarf2_section_empty_p (&sections.abbrev))
12545     {
12546       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12547                " [in module %s]"),
12548              dwp_file->name);
12549     }
12550   if (i == MAX_NR_V1_DWO_SECTIONS)
12551     {
12552       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12553                " [in module %s]"),
12554              dwp_file->name);
12555     }
12556
12557   /* It's easier for the rest of the code if we fake a struct dwo_file and
12558      have dwo_unit "live" in that.  At least for now.
12559
12560      The DWP file can be made up of a random collection of CUs and TUs.
12561      However, for each CU + set of TUs that came from the same original DWO
12562      file, we can combine them back into a virtual DWO file to save space
12563      (fewer struct dwo_file objects to allocate).  Remember that for really
12564      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12565
12566   std::string virtual_dwo_name =
12567     string_printf ("virtual-dwo/%d-%d-%d-%d",
12568                    get_section_id (&sections.abbrev),
12569                    get_section_id (&sections.line),
12570                    get_section_id (&sections.loc),
12571                    get_section_id (&sections.str_offsets));
12572   /* Can we use an existing virtual DWO file?  */
12573   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12574                                         virtual_dwo_name.c_str (),
12575                                         comp_dir);
12576   /* Create one if necessary.  */
12577   if (*dwo_file_slot == NULL)
12578     {
12579       if (dwarf_read_debug)
12580         {
12581           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12582                               virtual_dwo_name.c_str ());
12583         }
12584       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12585       dwo_file->dwo_name
12586         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12587                                         virtual_dwo_name.c_str (),
12588                                         virtual_dwo_name.size ());
12589       dwo_file->comp_dir = comp_dir;
12590       dwo_file->sections.abbrev = sections.abbrev;
12591       dwo_file->sections.line = sections.line;
12592       dwo_file->sections.loc = sections.loc;
12593       dwo_file->sections.macinfo = sections.macinfo;
12594       dwo_file->sections.macro = sections.macro;
12595       dwo_file->sections.str_offsets = sections.str_offsets;
12596       /* The "str" section is global to the entire DWP file.  */
12597       dwo_file->sections.str = dwp_file->sections.str;
12598       /* The info or types section is assigned below to dwo_unit,
12599          there's no need to record it in dwo_file.
12600          Also, we can't simply record type sections in dwo_file because
12601          we record a pointer into the vector in dwo_unit.  As we collect more
12602          types we'll grow the vector and eventually have to reallocate space
12603          for it, invalidating all copies of pointers into the previous
12604          contents.  */
12605       *dwo_file_slot = dwo_file;
12606     }
12607   else
12608     {
12609       if (dwarf_read_debug)
12610         {
12611           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12612                               virtual_dwo_name.c_str ());
12613         }
12614       dwo_file = (struct dwo_file *) *dwo_file_slot;
12615     }
12616
12617   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12618   dwo_unit->dwo_file = dwo_file;
12619   dwo_unit->signature = signature;
12620   dwo_unit->section =
12621     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12622   *dwo_unit->section = sections.info_or_types;
12623   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12624
12625   return dwo_unit;
12626 }
12627
12628 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12629    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12630    piece within that section used by a TU/CU, return a virtual section
12631    of just that piece.  */
12632
12633 static struct dwarf2_section_info
12634 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12635                        struct dwarf2_section_info *section,
12636                        bfd_size_type offset, bfd_size_type size)
12637 {
12638   struct dwarf2_section_info result;
12639   asection *sectp;
12640
12641   gdb_assert (section != NULL);
12642   gdb_assert (!section->is_virtual);
12643
12644   memset (&result, 0, sizeof (result));
12645   result.s.containing_section = section;
12646   result.is_virtual = 1;
12647
12648   if (size == 0)
12649     return result;
12650
12651   sectp = get_section_bfd_section (section);
12652
12653   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12654      bounds of the real section.  This is a pretty-rare event, so just
12655      flag an error (easier) instead of a warning and trying to cope.  */
12656   if (sectp == NULL
12657       || offset + size > bfd_get_section_size (sectp))
12658     {
12659       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12660                " in section %s [in module %s]"),
12661              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12662              objfile_name (dwarf2_per_objfile->objfile));
12663     }
12664
12665   result.virtual_offset = offset;
12666   result.size = size;
12667   return result;
12668 }
12669
12670 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12671    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12672    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12673    This is for DWP version 2 files.  */
12674
12675 static struct dwo_unit *
12676 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12677                            struct dwp_file *dwp_file,
12678                            uint32_t unit_index,
12679                            const char *comp_dir,
12680                            ULONGEST signature, int is_debug_types)
12681 {
12682   struct objfile *objfile = dwarf2_per_objfile->objfile;
12683   const struct dwp_hash_table *dwp_htab =
12684     is_debug_types ? dwp_file->tus : dwp_file->cus;
12685   bfd *dbfd = dwp_file->dbfd;
12686   const char *kind = is_debug_types ? "TU" : "CU";
12687   struct dwo_file *dwo_file;
12688   struct dwo_unit *dwo_unit;
12689   struct virtual_v2_dwo_sections sections;
12690   void **dwo_file_slot;
12691   int i;
12692
12693   gdb_assert (dwp_file->version == 2);
12694
12695   if (dwarf_read_debug)
12696     {
12697       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12698                           kind,
12699                           pulongest (unit_index), hex_string (signature),
12700                           dwp_file->name);
12701     }
12702
12703   /* Fetch the section offsets of this DWO unit.  */
12704
12705   memset (&sections, 0, sizeof (sections));
12706
12707   for (i = 0; i < dwp_htab->nr_columns; ++i)
12708     {
12709       uint32_t offset = read_4_bytes (dbfd,
12710                                       dwp_htab->section_pool.v2.offsets
12711                                       + (((unit_index - 1) * dwp_htab->nr_columns
12712                                           + i)
12713                                          * sizeof (uint32_t)));
12714       uint32_t size = read_4_bytes (dbfd,
12715                                     dwp_htab->section_pool.v2.sizes
12716                                     + (((unit_index - 1) * dwp_htab->nr_columns
12717                                         + i)
12718                                        * sizeof (uint32_t)));
12719
12720       switch (dwp_htab->section_pool.v2.section_ids[i])
12721         {
12722         case DW_SECT_INFO:
12723         case DW_SECT_TYPES:
12724           sections.info_or_types_offset = offset;
12725           sections.info_or_types_size = size;
12726           break;
12727         case DW_SECT_ABBREV:
12728           sections.abbrev_offset = offset;
12729           sections.abbrev_size = size;
12730           break;
12731         case DW_SECT_LINE:
12732           sections.line_offset = offset;
12733           sections.line_size = size;
12734           break;
12735         case DW_SECT_LOC:
12736           sections.loc_offset = offset;
12737           sections.loc_size = size;
12738           break;
12739         case DW_SECT_STR_OFFSETS:
12740           sections.str_offsets_offset = offset;
12741           sections.str_offsets_size = size;
12742           break;
12743         case DW_SECT_MACINFO:
12744           sections.macinfo_offset = offset;
12745           sections.macinfo_size = size;
12746           break;
12747         case DW_SECT_MACRO:
12748           sections.macro_offset = offset;
12749           sections.macro_size = size;
12750           break;
12751         }
12752     }
12753
12754   /* It's easier for the rest of the code if we fake a struct dwo_file and
12755      have dwo_unit "live" in that.  At least for now.
12756
12757      The DWP file can be made up of a random collection of CUs and TUs.
12758      However, for each CU + set of TUs that came from the same original DWO
12759      file, we can combine them back into a virtual DWO file to save space
12760      (fewer struct dwo_file objects to allocate).  Remember that for really
12761      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12762
12763   std::string virtual_dwo_name =
12764     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12765                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12766                    (long) (sections.line_size ? sections.line_offset : 0),
12767                    (long) (sections.loc_size ? sections.loc_offset : 0),
12768                    (long) (sections.str_offsets_size
12769                            ? sections.str_offsets_offset : 0));
12770   /* Can we use an existing virtual DWO file?  */
12771   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12772                                         virtual_dwo_name.c_str (),
12773                                         comp_dir);
12774   /* Create one if necessary.  */
12775   if (*dwo_file_slot == NULL)
12776     {
12777       if (dwarf_read_debug)
12778         {
12779           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12780                               virtual_dwo_name.c_str ());
12781         }
12782       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12783       dwo_file->dwo_name
12784         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12785                                         virtual_dwo_name.c_str (),
12786                                         virtual_dwo_name.size ());
12787       dwo_file->comp_dir = comp_dir;
12788       dwo_file->sections.abbrev =
12789         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12790                                sections.abbrev_offset, sections.abbrev_size);
12791       dwo_file->sections.line =
12792         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12793                                sections.line_offset, sections.line_size);
12794       dwo_file->sections.loc =
12795         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12796                                sections.loc_offset, sections.loc_size);
12797       dwo_file->sections.macinfo =
12798         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12799                                sections.macinfo_offset, sections.macinfo_size);
12800       dwo_file->sections.macro =
12801         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12802                                sections.macro_offset, sections.macro_size);
12803       dwo_file->sections.str_offsets =
12804         create_dwp_v2_section (dwarf2_per_objfile,
12805                                &dwp_file->sections.str_offsets,
12806                                sections.str_offsets_offset,
12807                                sections.str_offsets_size);
12808       /* The "str" section is global to the entire DWP file.  */
12809       dwo_file->sections.str = dwp_file->sections.str;
12810       /* The info or types section is assigned below to dwo_unit,
12811          there's no need to record it in dwo_file.
12812          Also, we can't simply record type sections in dwo_file because
12813          we record a pointer into the vector in dwo_unit.  As we collect more
12814          types we'll grow the vector and eventually have to reallocate space
12815          for it, invalidating all copies of pointers into the previous
12816          contents.  */
12817       *dwo_file_slot = dwo_file;
12818     }
12819   else
12820     {
12821       if (dwarf_read_debug)
12822         {
12823           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12824                               virtual_dwo_name.c_str ());
12825         }
12826       dwo_file = (struct dwo_file *) *dwo_file_slot;
12827     }
12828
12829   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12830   dwo_unit->dwo_file = dwo_file;
12831   dwo_unit->signature = signature;
12832   dwo_unit->section =
12833     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12834   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12835                                               is_debug_types
12836                                               ? &dwp_file->sections.types
12837                                               : &dwp_file->sections.info,
12838                                               sections.info_or_types_offset,
12839                                               sections.info_or_types_size);
12840   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12841
12842   return dwo_unit;
12843 }
12844
12845 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12846    Returns NULL if the signature isn't found.  */
12847
12848 static struct dwo_unit *
12849 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12850                         struct dwp_file *dwp_file, const char *comp_dir,
12851                         ULONGEST signature, int is_debug_types)
12852 {
12853   const struct dwp_hash_table *dwp_htab =
12854     is_debug_types ? dwp_file->tus : dwp_file->cus;
12855   bfd *dbfd = dwp_file->dbfd;
12856   uint32_t mask = dwp_htab->nr_slots - 1;
12857   uint32_t hash = signature & mask;
12858   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12859   unsigned int i;
12860   void **slot;
12861   struct dwo_unit find_dwo_cu;
12862
12863   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12864   find_dwo_cu.signature = signature;
12865   slot = htab_find_slot (is_debug_types
12866                          ? dwp_file->loaded_tus
12867                          : dwp_file->loaded_cus,
12868                          &find_dwo_cu, INSERT);
12869
12870   if (*slot != NULL)
12871     return (struct dwo_unit *) *slot;
12872
12873   /* Use a for loop so that we don't loop forever on bad debug info.  */
12874   for (i = 0; i < dwp_htab->nr_slots; ++i)
12875     {
12876       ULONGEST signature_in_table;
12877
12878       signature_in_table =
12879         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12880       if (signature_in_table == signature)
12881         {
12882           uint32_t unit_index =
12883             read_4_bytes (dbfd,
12884                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12885
12886           if (dwp_file->version == 1)
12887             {
12888               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12889                                                  dwp_file, unit_index,
12890                                                  comp_dir, signature,
12891                                                  is_debug_types);
12892             }
12893           else
12894             {
12895               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12896                                                  dwp_file, unit_index,
12897                                                  comp_dir, signature,
12898                                                  is_debug_types);
12899             }
12900           return (struct dwo_unit *) *slot;
12901         }
12902       if (signature_in_table == 0)
12903         return NULL;
12904       hash = (hash + hash2) & mask;
12905     }
12906
12907   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12908            " [in module %s]"),
12909          dwp_file->name);
12910 }
12911
12912 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12913    Open the file specified by FILE_NAME and hand it off to BFD for
12914    preliminary analysis.  Return a newly initialized bfd *, which
12915    includes a canonicalized copy of FILE_NAME.
12916    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12917    SEARCH_CWD is true if the current directory is to be searched.
12918    It will be searched before debug-file-directory.
12919    If successful, the file is added to the bfd include table of the
12920    objfile's bfd (see gdb_bfd_record_inclusion).
12921    If unable to find/open the file, return NULL.
12922    NOTE: This function is derived from symfile_bfd_open.  */
12923
12924 static gdb_bfd_ref_ptr
12925 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12926                     const char *file_name, int is_dwp, int search_cwd)
12927 {
12928   int desc;
12929   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12930      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12931      to debug_file_directory.  */
12932   const char *search_path;
12933   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12934
12935   gdb::unique_xmalloc_ptr<char> search_path_holder;
12936   if (search_cwd)
12937     {
12938       if (*debug_file_directory != '\0')
12939         {
12940           search_path_holder.reset (concat (".", dirname_separator_string,
12941                                             debug_file_directory,
12942                                             (char *) NULL));
12943           search_path = search_path_holder.get ();
12944         }
12945       else
12946         search_path = ".";
12947     }
12948   else
12949     search_path = debug_file_directory;
12950
12951   openp_flags flags = OPF_RETURN_REALPATH;
12952   if (is_dwp)
12953     flags |= OPF_SEARCH_IN_PATH;
12954
12955   gdb::unique_xmalloc_ptr<char> absolute_name;
12956   desc = openp (search_path, flags, file_name,
12957                 O_RDONLY | O_BINARY, &absolute_name);
12958   if (desc < 0)
12959     return NULL;
12960
12961   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12962                                          gnutarget, desc));
12963   if (sym_bfd == NULL)
12964     return NULL;
12965   bfd_set_cacheable (sym_bfd.get (), 1);
12966
12967   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12968     return NULL;
12969
12970   /* Success.  Record the bfd as having been included by the objfile's bfd.
12971      This is important because things like demangled_names_hash lives in the
12972      objfile's per_bfd space and may have references to things like symbol
12973      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12974   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12975
12976   return sym_bfd;
12977 }
12978
12979 /* Try to open DWO file FILE_NAME.
12980    COMP_DIR is the DW_AT_comp_dir attribute.
12981    The result is the bfd handle of the file.
12982    If there is a problem finding or opening the file, return NULL.
12983    Upon success, the canonicalized path of the file is stored in the bfd,
12984    same as symfile_bfd_open.  */
12985
12986 static gdb_bfd_ref_ptr
12987 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12988                const char *file_name, const char *comp_dir)
12989 {
12990   if (IS_ABSOLUTE_PATH (file_name))
12991     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12992                                0 /*is_dwp*/, 0 /*search_cwd*/);
12993
12994   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12995
12996   if (comp_dir != NULL)
12997     {
12998       char *path_to_try = concat (comp_dir, SLASH_STRING,
12999                                   file_name, (char *) NULL);
13000
13001       /* NOTE: If comp_dir is a relative path, this will also try the
13002          search path, which seems useful.  */
13003       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
13004                                                 path_to_try,
13005                                                 0 /*is_dwp*/,
13006                                                 1 /*search_cwd*/));
13007       xfree (path_to_try);
13008       if (abfd != NULL)
13009         return abfd;
13010     }
13011
13012   /* That didn't work, try debug-file-directory, which, despite its name,
13013      is a list of paths.  */
13014
13015   if (*debug_file_directory == '\0')
13016     return NULL;
13017
13018   return try_open_dwop_file (dwarf2_per_objfile, file_name,
13019                              0 /*is_dwp*/, 1 /*search_cwd*/);
13020 }
13021
13022 /* This function is mapped across the sections and remembers the offset and
13023    size of each of the DWO debugging sections we are interested in.  */
13024
13025 static void
13026 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
13027 {
13028   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
13029   const struct dwop_section_names *names = &dwop_section_names;
13030
13031   if (section_is_p (sectp->name, &names->abbrev_dwo))
13032     {
13033       dwo_sections->abbrev.s.section = sectp;
13034       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
13035     }
13036   else if (section_is_p (sectp->name, &names->info_dwo))
13037     {
13038       dwo_sections->info.s.section = sectp;
13039       dwo_sections->info.size = bfd_get_section_size (sectp);
13040     }
13041   else if (section_is_p (sectp->name, &names->line_dwo))
13042     {
13043       dwo_sections->line.s.section = sectp;
13044       dwo_sections->line.size = bfd_get_section_size (sectp);
13045     }
13046   else if (section_is_p (sectp->name, &names->loc_dwo))
13047     {
13048       dwo_sections->loc.s.section = sectp;
13049       dwo_sections->loc.size = bfd_get_section_size (sectp);
13050     }
13051   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13052     {
13053       dwo_sections->macinfo.s.section = sectp;
13054       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13055     }
13056   else if (section_is_p (sectp->name, &names->macro_dwo))
13057     {
13058       dwo_sections->macro.s.section = sectp;
13059       dwo_sections->macro.size = bfd_get_section_size (sectp);
13060     }
13061   else if (section_is_p (sectp->name, &names->str_dwo))
13062     {
13063       dwo_sections->str.s.section = sectp;
13064       dwo_sections->str.size = bfd_get_section_size (sectp);
13065     }
13066   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13067     {
13068       dwo_sections->str_offsets.s.section = sectp;
13069       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13070     }
13071   else if (section_is_p (sectp->name, &names->types_dwo))
13072     {
13073       struct dwarf2_section_info type_section;
13074
13075       memset (&type_section, 0, sizeof (type_section));
13076       type_section.s.section = sectp;
13077       type_section.size = bfd_get_section_size (sectp);
13078       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13079                      &type_section);
13080     }
13081 }
13082
13083 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13084    by PER_CU.  This is for the non-DWP case.
13085    The result is NULL if DWO_NAME can't be found.  */
13086
13087 static struct dwo_file *
13088 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13089                         const char *dwo_name, const char *comp_dir)
13090 {
13091   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13092   struct objfile *objfile = dwarf2_per_objfile->objfile;
13093   struct dwo_file *dwo_file;
13094   struct cleanup *cleanups;
13095
13096   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13097   if (dbfd == NULL)
13098     {
13099       if (dwarf_read_debug)
13100         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13101       return NULL;
13102     }
13103   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13104   dwo_file->dwo_name = dwo_name;
13105   dwo_file->comp_dir = comp_dir;
13106   dwo_file->dbfd = dbfd.release ();
13107
13108   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13109   cleanup_data->dwo_file = dwo_file;
13110   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13111
13112   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13113
13114   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13115                          &dwo_file->sections);
13116
13117   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13118                          dwo_file->cus);
13119
13120   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13121                                  dwo_file->sections.types, dwo_file->tus);
13122
13123   discard_cleanups (cleanups);
13124
13125   if (dwarf_read_debug)
13126     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13127
13128   return dwo_file;
13129 }
13130
13131 /* This function is mapped across the sections and remembers the offset and
13132    size of each of the DWP debugging sections common to version 1 and 2 that
13133    we are interested in.  */
13134
13135 static void
13136 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13137                                    void *dwp_file_ptr)
13138 {
13139   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13140   const struct dwop_section_names *names = &dwop_section_names;
13141   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13142
13143   /* Record the ELF section number for later lookup: this is what the
13144      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13145   gdb_assert (elf_section_nr < dwp_file->num_sections);
13146   dwp_file->elf_sections[elf_section_nr] = sectp;
13147
13148   /* Look for specific sections that we need.  */
13149   if (section_is_p (sectp->name, &names->str_dwo))
13150     {
13151       dwp_file->sections.str.s.section = sectp;
13152       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13153     }
13154   else if (section_is_p (sectp->name, &names->cu_index))
13155     {
13156       dwp_file->sections.cu_index.s.section = sectp;
13157       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13158     }
13159   else if (section_is_p (sectp->name, &names->tu_index))
13160     {
13161       dwp_file->sections.tu_index.s.section = sectp;
13162       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13163     }
13164 }
13165
13166 /* This function is mapped across the sections and remembers the offset and
13167    size of each of the DWP version 2 debugging sections that we are interested
13168    in.  This is split into a separate function because we don't know if we
13169    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13170
13171 static void
13172 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13173 {
13174   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13175   const struct dwop_section_names *names = &dwop_section_names;
13176   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13177
13178   /* Record the ELF section number for later lookup: this is what the
13179      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13180   gdb_assert (elf_section_nr < dwp_file->num_sections);
13181   dwp_file->elf_sections[elf_section_nr] = sectp;
13182
13183   /* Look for specific sections that we need.  */
13184   if (section_is_p (sectp->name, &names->abbrev_dwo))
13185     {
13186       dwp_file->sections.abbrev.s.section = sectp;
13187       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13188     }
13189   else if (section_is_p (sectp->name, &names->info_dwo))
13190     {
13191       dwp_file->sections.info.s.section = sectp;
13192       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13193     }
13194   else if (section_is_p (sectp->name, &names->line_dwo))
13195     {
13196       dwp_file->sections.line.s.section = sectp;
13197       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13198     }
13199   else if (section_is_p (sectp->name, &names->loc_dwo))
13200     {
13201       dwp_file->sections.loc.s.section = sectp;
13202       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13203     }
13204   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13205     {
13206       dwp_file->sections.macinfo.s.section = sectp;
13207       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13208     }
13209   else if (section_is_p (sectp->name, &names->macro_dwo))
13210     {
13211       dwp_file->sections.macro.s.section = sectp;
13212       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13213     }
13214   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13215     {
13216       dwp_file->sections.str_offsets.s.section = sectp;
13217       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13218     }
13219   else if (section_is_p (sectp->name, &names->types_dwo))
13220     {
13221       dwp_file->sections.types.s.section = sectp;
13222       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13223     }
13224 }
13225
13226 /* Hash function for dwp_file loaded CUs/TUs.  */
13227
13228 static hashval_t
13229 hash_dwp_loaded_cutus (const void *item)
13230 {
13231   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13232
13233   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13234   return dwo_unit->signature;
13235 }
13236
13237 /* Equality function for dwp_file loaded CUs/TUs.  */
13238
13239 static int
13240 eq_dwp_loaded_cutus (const void *a, const void *b)
13241 {
13242   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13243   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13244
13245   return dua->signature == dub->signature;
13246 }
13247
13248 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13249
13250 static htab_t
13251 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13252 {
13253   return htab_create_alloc_ex (3,
13254                                hash_dwp_loaded_cutus,
13255                                eq_dwp_loaded_cutus,
13256                                NULL,
13257                                &objfile->objfile_obstack,
13258                                hashtab_obstack_allocate,
13259                                dummy_obstack_deallocate);
13260 }
13261
13262 /* Try to open DWP file FILE_NAME.
13263    The result is the bfd handle of the file.
13264    If there is a problem finding or opening the file, return NULL.
13265    Upon success, the canonicalized path of the file is stored in the bfd,
13266    same as symfile_bfd_open.  */
13267
13268 static gdb_bfd_ref_ptr
13269 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13270                const char *file_name)
13271 {
13272   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13273                                             1 /*is_dwp*/,
13274                                             1 /*search_cwd*/));
13275   if (abfd != NULL)
13276     return abfd;
13277
13278   /* Work around upstream bug 15652.
13279      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13280      [Whether that's a "bug" is debatable, but it is getting in our way.]
13281      We have no real idea where the dwp file is, because gdb's realpath-ing
13282      of the executable's path may have discarded the needed info.
13283      [IWBN if the dwp file name was recorded in the executable, akin to
13284      .gnu_debuglink, but that doesn't exist yet.]
13285      Strip the directory from FILE_NAME and search again.  */
13286   if (*debug_file_directory != '\0')
13287     {
13288       /* Don't implicitly search the current directory here.
13289          If the user wants to search "." to handle this case,
13290          it must be added to debug-file-directory.  */
13291       return try_open_dwop_file (dwarf2_per_objfile,
13292                                  lbasename (file_name), 1 /*is_dwp*/,
13293                                  0 /*search_cwd*/);
13294     }
13295
13296   return NULL;
13297 }
13298
13299 /* Initialize the use of the DWP file for the current objfile.
13300    By convention the name of the DWP file is ${objfile}.dwp.
13301    The result is NULL if it can't be found.  */
13302
13303 static struct dwp_file *
13304 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13305 {
13306   struct objfile *objfile = dwarf2_per_objfile->objfile;
13307   struct dwp_file *dwp_file;
13308
13309   /* Try to find first .dwp for the binary file before any symbolic links
13310      resolving.  */
13311
13312   /* If the objfile is a debug file, find the name of the real binary
13313      file and get the name of dwp file from there.  */
13314   std::string dwp_name;
13315   if (objfile->separate_debug_objfile_backlink != NULL)
13316     {
13317       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13318       const char *backlink_basename = lbasename (backlink->original_name);
13319
13320       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13321     }
13322   else
13323     dwp_name = objfile->original_name;
13324
13325   dwp_name += ".dwp";
13326
13327   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13328   if (dbfd == NULL
13329       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13330     {
13331       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13332       dwp_name = objfile_name (objfile);
13333       dwp_name += ".dwp";
13334       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13335     }
13336
13337   if (dbfd == NULL)
13338     {
13339       if (dwarf_read_debug)
13340         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13341       return NULL;
13342     }
13343   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13344   dwp_file->name = bfd_get_filename (dbfd.get ());
13345   dwp_file->dbfd = dbfd.release ();
13346
13347   /* +1: section 0 is unused */
13348   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13349   dwp_file->elf_sections =
13350     OBSTACK_CALLOC (&objfile->objfile_obstack,
13351                     dwp_file->num_sections, asection *);
13352
13353   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13354                          dwp_file);
13355
13356   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13357
13358   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13359
13360   /* The DWP file version is stored in the hash table.  Oh well.  */
13361   if (dwp_file->cus && dwp_file->tus
13362       && dwp_file->cus->version != dwp_file->tus->version)
13363     {
13364       /* Technically speaking, we should try to limp along, but this is
13365          pretty bizarre.  We use pulongest here because that's the established
13366          portability solution (e.g, we cannot use %u for uint32_t).  */
13367       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13368                " TU version %s [in DWP file %s]"),
13369              pulongest (dwp_file->cus->version),
13370              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13371     }
13372
13373   if (dwp_file->cus)
13374     dwp_file->version = dwp_file->cus->version;
13375   else if (dwp_file->tus)
13376     dwp_file->version = dwp_file->tus->version;
13377   else
13378     dwp_file->version = 2;
13379
13380   if (dwp_file->version == 2)
13381     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13382                            dwp_file);
13383
13384   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13385   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13386
13387   if (dwarf_read_debug)
13388     {
13389       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13390       fprintf_unfiltered (gdb_stdlog,
13391                           "    %s CUs, %s TUs\n",
13392                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13393                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13394     }
13395
13396   return dwp_file;
13397 }
13398
13399 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13400
13401 static struct dwp_file *
13402 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13403 {
13404   if (! dwarf2_per_objfile->dwp_checked)
13405     {
13406       dwarf2_per_objfile->dwp_file
13407         = open_and_init_dwp_file (dwarf2_per_objfile);
13408       dwarf2_per_objfile->dwp_checked = 1;
13409     }
13410   return dwarf2_per_objfile->dwp_file;
13411 }
13412
13413 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13414    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13415    or in the DWP file for the objfile, referenced by THIS_UNIT.
13416    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13417    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13418
13419    This is called, for example, when wanting to read a variable with a
13420    complex location.  Therefore we don't want to do file i/o for every call.
13421    Therefore we don't want to look for a DWO file on every call.
13422    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13423    then we check if we've already seen DWO_NAME, and only THEN do we check
13424    for a DWO file.
13425
13426    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13427    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13428
13429 static struct dwo_unit *
13430 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13431                  const char *dwo_name, const char *comp_dir,
13432                  ULONGEST signature, int is_debug_types)
13433 {
13434   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13435   struct objfile *objfile = dwarf2_per_objfile->objfile;
13436   const char *kind = is_debug_types ? "TU" : "CU";
13437   void **dwo_file_slot;
13438   struct dwo_file *dwo_file;
13439   struct dwp_file *dwp_file;
13440
13441   /* First see if there's a DWP file.
13442      If we have a DWP file but didn't find the DWO inside it, don't
13443      look for the original DWO file.  It makes gdb behave differently
13444      depending on whether one is debugging in the build tree.  */
13445
13446   dwp_file = get_dwp_file (dwarf2_per_objfile);
13447   if (dwp_file != NULL)
13448     {
13449       const struct dwp_hash_table *dwp_htab =
13450         is_debug_types ? dwp_file->tus : dwp_file->cus;
13451
13452       if (dwp_htab != NULL)
13453         {
13454           struct dwo_unit *dwo_cutu =
13455             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13456                                     signature, is_debug_types);
13457
13458           if (dwo_cutu != NULL)
13459             {
13460               if (dwarf_read_debug)
13461                 {
13462                   fprintf_unfiltered (gdb_stdlog,
13463                                       "Virtual DWO %s %s found: @%s\n",
13464                                       kind, hex_string (signature),
13465                                       host_address_to_string (dwo_cutu));
13466                 }
13467               return dwo_cutu;
13468             }
13469         }
13470     }
13471   else
13472     {
13473       /* No DWP file, look for the DWO file.  */
13474
13475       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13476                                             dwo_name, comp_dir);
13477       if (*dwo_file_slot == NULL)
13478         {
13479           /* Read in the file and build a table of the CUs/TUs it contains.  */
13480           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13481         }
13482       /* NOTE: This will be NULL if unable to open the file.  */
13483       dwo_file = (struct dwo_file *) *dwo_file_slot;
13484
13485       if (dwo_file != NULL)
13486         {
13487           struct dwo_unit *dwo_cutu = NULL;
13488
13489           if (is_debug_types && dwo_file->tus)
13490             {
13491               struct dwo_unit find_dwo_cutu;
13492
13493               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13494               find_dwo_cutu.signature = signature;
13495               dwo_cutu
13496                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13497             }
13498           else if (!is_debug_types && dwo_file->cus)
13499             {
13500               struct dwo_unit find_dwo_cutu;
13501
13502               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13503               find_dwo_cutu.signature = signature;
13504               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13505                                                        &find_dwo_cutu);
13506             }
13507
13508           if (dwo_cutu != NULL)
13509             {
13510               if (dwarf_read_debug)
13511                 {
13512                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13513                                       kind, dwo_name, hex_string (signature),
13514                                       host_address_to_string (dwo_cutu));
13515                 }
13516               return dwo_cutu;
13517             }
13518         }
13519     }
13520
13521   /* We didn't find it.  This could mean a dwo_id mismatch, or
13522      someone deleted the DWO/DWP file, or the search path isn't set up
13523      correctly to find the file.  */
13524
13525   if (dwarf_read_debug)
13526     {
13527       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13528                           kind, dwo_name, hex_string (signature));
13529     }
13530
13531   /* This is a warning and not a complaint because it can be caused by
13532      pilot error (e.g., user accidentally deleting the DWO).  */
13533   {
13534     /* Print the name of the DWP file if we looked there, helps the user
13535        better diagnose the problem.  */
13536     std::string dwp_text;
13537
13538     if (dwp_file != NULL)
13539       dwp_text = string_printf (" [in DWP file %s]",
13540                                 lbasename (dwp_file->name));
13541
13542     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13543                " [in module %s]"),
13544              kind, dwo_name, hex_string (signature),
13545              dwp_text.c_str (),
13546              this_unit->is_debug_types ? "TU" : "CU",
13547              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13548   }
13549   return NULL;
13550 }
13551
13552 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13553    See lookup_dwo_cutu_unit for details.  */
13554
13555 static struct dwo_unit *
13556 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13557                       const char *dwo_name, const char *comp_dir,
13558                       ULONGEST signature)
13559 {
13560   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13561 }
13562
13563 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13564    See lookup_dwo_cutu_unit for details.  */
13565
13566 static struct dwo_unit *
13567 lookup_dwo_type_unit (struct signatured_type *this_tu,
13568                       const char *dwo_name, const char *comp_dir)
13569 {
13570   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13571 }
13572
13573 /* Traversal function for queue_and_load_all_dwo_tus.  */
13574
13575 static int
13576 queue_and_load_dwo_tu (void **slot, void *info)
13577 {
13578   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13579   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13580   ULONGEST signature = dwo_unit->signature;
13581   struct signatured_type *sig_type =
13582     lookup_dwo_signatured_type (per_cu->cu, signature);
13583
13584   if (sig_type != NULL)
13585     {
13586       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13587
13588       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13589          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13590          while processing PER_CU.  */
13591       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13592         load_full_type_unit (sig_cu);
13593       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13594     }
13595
13596   return 1;
13597 }
13598
13599 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13600    The DWO may have the only definition of the type, though it may not be
13601    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13602    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13603
13604 static void
13605 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13606 {
13607   struct dwo_unit *dwo_unit;
13608   struct dwo_file *dwo_file;
13609
13610   gdb_assert (!per_cu->is_debug_types);
13611   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13612   gdb_assert (per_cu->cu != NULL);
13613
13614   dwo_unit = per_cu->cu->dwo_unit;
13615   gdb_assert (dwo_unit != NULL);
13616
13617   dwo_file = dwo_unit->dwo_file;
13618   if (dwo_file->tus != NULL)
13619     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13620 }
13621
13622 /* Free all resources associated with DWO_FILE.
13623    Close the DWO file and munmap the sections.
13624    All memory should be on the objfile obstack.  */
13625
13626 static void
13627 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13628 {
13629
13630   /* Note: dbfd is NULL for virtual DWO files.  */
13631   gdb_bfd_unref (dwo_file->dbfd);
13632
13633   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13634 }
13635
13636 /* Wrapper for free_dwo_file for use in cleanups.  */
13637
13638 static void
13639 free_dwo_file_cleanup (void *arg)
13640 {
13641   struct free_dwo_file_cleanup_data *data
13642     = (struct free_dwo_file_cleanup_data *) arg;
13643   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13644
13645   free_dwo_file (data->dwo_file, objfile);
13646
13647   xfree (data);
13648 }
13649
13650 /* Traversal function for free_dwo_files.  */
13651
13652 static int
13653 free_dwo_file_from_slot (void **slot, void *info)
13654 {
13655   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13656   struct objfile *objfile = (struct objfile *) info;
13657
13658   free_dwo_file (dwo_file, objfile);
13659
13660   return 1;
13661 }
13662
13663 /* Free all resources associated with DWO_FILES.  */
13664
13665 static void
13666 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13667 {
13668   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13669 }
13670 \f
13671 /* Read in various DIEs.  */
13672
13673 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13674    Inherit only the children of the DW_AT_abstract_origin DIE not being
13675    already referenced by DW_AT_abstract_origin from the children of the
13676    current DIE.  */
13677
13678 static void
13679 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13680 {
13681   struct die_info *child_die;
13682   sect_offset *offsetp;
13683   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13684   struct die_info *origin_die;
13685   /* Iterator of the ORIGIN_DIE children.  */
13686   struct die_info *origin_child_die;
13687   struct attribute *attr;
13688   struct dwarf2_cu *origin_cu;
13689   struct pending **origin_previous_list_in_scope;
13690
13691   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13692   if (!attr)
13693     return;
13694
13695   /* Note that following die references may follow to a die in a
13696      different cu.  */
13697
13698   origin_cu = cu;
13699   origin_die = follow_die_ref (die, attr, &origin_cu);
13700
13701   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13702      symbols in.  */
13703   origin_previous_list_in_scope = origin_cu->list_in_scope;
13704   origin_cu->list_in_scope = cu->list_in_scope;
13705
13706   if (die->tag != origin_die->tag
13707       && !(die->tag == DW_TAG_inlined_subroutine
13708            && origin_die->tag == DW_TAG_subprogram))
13709     complaint (&symfile_complaints,
13710                _("DIE %s and its abstract origin %s have different tags"),
13711                sect_offset_str (die->sect_off),
13712                sect_offset_str (origin_die->sect_off));
13713
13714   std::vector<sect_offset> offsets;
13715
13716   for (child_die = die->child;
13717        child_die && child_die->tag;
13718        child_die = sibling_die (child_die))
13719     {
13720       struct die_info *child_origin_die;
13721       struct dwarf2_cu *child_origin_cu;
13722
13723       /* We are trying to process concrete instance entries:
13724          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13725          it's not relevant to our analysis here. i.e. detecting DIEs that are
13726          present in the abstract instance but not referenced in the concrete
13727          one.  */
13728       if (child_die->tag == DW_TAG_call_site
13729           || child_die->tag == DW_TAG_GNU_call_site)
13730         continue;
13731
13732       /* For each CHILD_DIE, find the corresponding child of
13733          ORIGIN_DIE.  If there is more than one layer of
13734          DW_AT_abstract_origin, follow them all; there shouldn't be,
13735          but GCC versions at least through 4.4 generate this (GCC PR
13736          40573).  */
13737       child_origin_die = child_die;
13738       child_origin_cu = cu;
13739       while (1)
13740         {
13741           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13742                               child_origin_cu);
13743           if (attr == NULL)
13744             break;
13745           child_origin_die = follow_die_ref (child_origin_die, attr,
13746                                              &child_origin_cu);
13747         }
13748
13749       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13750          counterpart may exist.  */
13751       if (child_origin_die != child_die)
13752         {
13753           if (child_die->tag != child_origin_die->tag
13754               && !(child_die->tag == DW_TAG_inlined_subroutine
13755                    && child_origin_die->tag == DW_TAG_subprogram))
13756             complaint (&symfile_complaints,
13757                        _("Child DIE %s and its abstract origin %s have "
13758                          "different tags"),
13759                        sect_offset_str (child_die->sect_off),
13760                        sect_offset_str (child_origin_die->sect_off));
13761           if (child_origin_die->parent != origin_die)
13762             complaint (&symfile_complaints,
13763                        _("Child DIE %s and its abstract origin %s have "
13764                          "different parents"),
13765                        sect_offset_str (child_die->sect_off),
13766                        sect_offset_str (child_origin_die->sect_off));
13767           else
13768             offsets.push_back (child_origin_die->sect_off);
13769         }
13770     }
13771   std::sort (offsets.begin (), offsets.end ());
13772   sect_offset *offsets_end = offsets.data () + offsets.size ();
13773   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13774     if (offsetp[-1] == *offsetp)
13775       complaint (&symfile_complaints,
13776                  _("Multiple children of DIE %s refer "
13777                    "to DIE %s as their abstract origin"),
13778                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13779
13780   offsetp = offsets.data ();
13781   origin_child_die = origin_die->child;
13782   while (origin_child_die && origin_child_die->tag)
13783     {
13784       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13785       while (offsetp < offsets_end
13786              && *offsetp < origin_child_die->sect_off)
13787         offsetp++;
13788       if (offsetp >= offsets_end
13789           || *offsetp > origin_child_die->sect_off)
13790         {
13791           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13792              Check whether we're already processing ORIGIN_CHILD_DIE.
13793              This can happen with mutually referenced abstract_origins.
13794              PR 16581.  */
13795           if (!origin_child_die->in_process)
13796             process_die (origin_child_die, origin_cu);
13797         }
13798       origin_child_die = sibling_die (origin_child_die);
13799     }
13800   origin_cu->list_in_scope = origin_previous_list_in_scope;
13801 }
13802
13803 static void
13804 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13805 {
13806   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13807   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13808   struct context_stack *newobj;
13809   CORE_ADDR lowpc;
13810   CORE_ADDR highpc;
13811   struct die_info *child_die;
13812   struct attribute *attr, *call_line, *call_file;
13813   const char *name;
13814   CORE_ADDR baseaddr;
13815   struct block *block;
13816   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13817   std::vector<struct symbol *> template_args;
13818   struct template_symbol *templ_func = NULL;
13819
13820   if (inlined_func)
13821     {
13822       /* If we do not have call site information, we can't show the
13823          caller of this inlined function.  That's too confusing, so
13824          only use the scope for local variables.  */
13825       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13826       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13827       if (call_line == NULL || call_file == NULL)
13828         {
13829           read_lexical_block_scope (die, cu);
13830           return;
13831         }
13832     }
13833
13834   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13835
13836   name = dwarf2_name (die, cu);
13837
13838   /* Ignore functions with missing or empty names.  These are actually
13839      illegal according to the DWARF standard.  */
13840   if (name == NULL)
13841     {
13842       complaint (&symfile_complaints,
13843                  _("missing name for subprogram DIE at %s"),
13844                  sect_offset_str (die->sect_off));
13845       return;
13846     }
13847
13848   /* Ignore functions with missing or invalid low and high pc attributes.  */
13849   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13850       <= PC_BOUNDS_INVALID)
13851     {
13852       attr = dwarf2_attr (die, DW_AT_external, cu);
13853       if (!attr || !DW_UNSND (attr))
13854         complaint (&symfile_complaints,
13855                    _("cannot get low and high bounds "
13856                      "for subprogram DIE at %s"),
13857                    sect_offset_str (die->sect_off));
13858       return;
13859     }
13860
13861   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13862   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13863
13864   /* If we have any template arguments, then we must allocate a
13865      different sort of symbol.  */
13866   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13867     {
13868       if (child_die->tag == DW_TAG_template_type_param
13869           || child_die->tag == DW_TAG_template_value_param)
13870         {
13871           templ_func = allocate_template_symbol (objfile);
13872           templ_func->subclass = SYMBOL_TEMPLATE;
13873           break;
13874         }
13875     }
13876
13877   newobj = push_context (0, lowpc);
13878   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13879                              (struct symbol *) templ_func);
13880
13881   /* If there is a location expression for DW_AT_frame_base, record
13882      it.  */
13883   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13884   if (attr)
13885     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13886
13887   /* If there is a location for the static link, record it.  */
13888   newobj->static_link = NULL;
13889   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13890   if (attr)
13891     {
13892       newobj->static_link
13893         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13894       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13895     }
13896
13897   cu->list_in_scope = &local_symbols;
13898
13899   if (die->child != NULL)
13900     {
13901       child_die = die->child;
13902       while (child_die && child_die->tag)
13903         {
13904           if (child_die->tag == DW_TAG_template_type_param
13905               || child_die->tag == DW_TAG_template_value_param)
13906             {
13907               struct symbol *arg = new_symbol (child_die, NULL, cu);
13908
13909               if (arg != NULL)
13910                 template_args.push_back (arg);
13911             }
13912           else
13913             process_die (child_die, cu);
13914           child_die = sibling_die (child_die);
13915         }
13916     }
13917
13918   inherit_abstract_dies (die, cu);
13919
13920   /* If we have a DW_AT_specification, we might need to import using
13921      directives from the context of the specification DIE.  See the
13922      comment in determine_prefix.  */
13923   if (cu->language == language_cplus
13924       && dwarf2_attr (die, DW_AT_specification, cu))
13925     {
13926       struct dwarf2_cu *spec_cu = cu;
13927       struct die_info *spec_die = die_specification (die, &spec_cu);
13928
13929       while (spec_die)
13930         {
13931           child_die = spec_die->child;
13932           while (child_die && child_die->tag)
13933             {
13934               if (child_die->tag == DW_TAG_imported_module)
13935                 process_die (child_die, spec_cu);
13936               child_die = sibling_die (child_die);
13937             }
13938
13939           /* In some cases, GCC generates specification DIEs that
13940              themselves contain DW_AT_specification attributes.  */
13941           spec_die = die_specification (spec_die, &spec_cu);
13942         }
13943     }
13944
13945   newobj = pop_context ();
13946   /* Make a block for the local symbols within.  */
13947   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13948                         newobj->static_link, lowpc, highpc);
13949
13950   /* For C++, set the block's scope.  */
13951   if ((cu->language == language_cplus
13952        || cu->language == language_fortran
13953        || cu->language == language_d
13954        || cu->language == language_rust)
13955       && cu->processing_has_namespace_info)
13956     block_set_scope (block, determine_prefix (die, cu),
13957                      &objfile->objfile_obstack);
13958
13959   /* If we have address ranges, record them.  */
13960   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13961
13962   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13963
13964   /* Attach template arguments to function.  */
13965   if (!template_args.empty ())
13966     {
13967       gdb_assert (templ_func != NULL);
13968
13969       templ_func->n_template_arguments = template_args.size ();
13970       templ_func->template_arguments
13971         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13972                      templ_func->n_template_arguments);
13973       memcpy (templ_func->template_arguments,
13974               template_args.data (),
13975               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13976     }
13977
13978   /* In C++, we can have functions nested inside functions (e.g., when
13979      a function declares a class that has methods).  This means that
13980      when we finish processing a function scope, we may need to go
13981      back to building a containing block's symbol lists.  */
13982   local_symbols = newobj->locals;
13983   local_using_directives = newobj->local_using_directives;
13984
13985   /* If we've finished processing a top-level function, subsequent
13986      symbols go in the file symbol list.  */
13987   if (outermost_context_p ())
13988     cu->list_in_scope = &file_symbols;
13989 }
13990
13991 /* Process all the DIES contained within a lexical block scope.  Start
13992    a new scope, process the dies, and then close the scope.  */
13993
13994 static void
13995 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13996 {
13997   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13998   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13999   struct context_stack *newobj;
14000   CORE_ADDR lowpc, highpc;
14001   struct die_info *child_die;
14002   CORE_ADDR baseaddr;
14003
14004   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14005
14006   /* Ignore blocks with missing or invalid low and high pc attributes.  */
14007   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
14008      as multiple lexical blocks?  Handling children in a sane way would
14009      be nasty.  Might be easier to properly extend generic blocks to
14010      describe ranges.  */
14011   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
14012     {
14013     case PC_BOUNDS_NOT_PRESENT:
14014       /* DW_TAG_lexical_block has no attributes, process its children as if
14015          there was no wrapping by that DW_TAG_lexical_block.
14016          GCC does no longer produces such DWARF since GCC r224161.  */
14017       for (child_die = die->child;
14018            child_die != NULL && child_die->tag;
14019            child_die = sibling_die (child_die))
14020         process_die (child_die, cu);
14021       return;
14022     case PC_BOUNDS_INVALID:
14023       return;
14024     }
14025   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14026   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14027
14028   push_context (0, lowpc);
14029   if (die->child != NULL)
14030     {
14031       child_die = die->child;
14032       while (child_die && child_die->tag)
14033         {
14034           process_die (child_die, cu);
14035           child_die = sibling_die (child_die);
14036         }
14037     }
14038   inherit_abstract_dies (die, cu);
14039   newobj = pop_context ();
14040
14041   if (local_symbols != NULL || local_using_directives != NULL)
14042     {
14043       struct block *block
14044         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14045                         newobj->start_addr, highpc);
14046
14047       /* Note that recording ranges after traversing children, as we
14048          do here, means that recording a parent's ranges entails
14049          walking across all its children's ranges as they appear in
14050          the address map, which is quadratic behavior.
14051
14052          It would be nicer to record the parent's ranges before
14053          traversing its children, simply overriding whatever you find
14054          there.  But since we don't even decide whether to create a
14055          block until after we've traversed its children, that's hard
14056          to do.  */
14057       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14058     }
14059   local_symbols = newobj->locals;
14060   local_using_directives = newobj->local_using_directives;
14061 }
14062
14063 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14064
14065 static void
14066 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14067 {
14068   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14069   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14070   CORE_ADDR pc, baseaddr;
14071   struct attribute *attr;
14072   struct call_site *call_site, call_site_local;
14073   void **slot;
14074   int nparams;
14075   struct die_info *child_die;
14076
14077   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14078
14079   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14080   if (attr == NULL)
14081     {
14082       /* This was a pre-DWARF-5 GNU extension alias
14083          for DW_AT_call_return_pc.  */
14084       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14085     }
14086   if (!attr)
14087     {
14088       complaint (&symfile_complaints,
14089                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14090                    "DIE %s [in module %s]"),
14091                  sect_offset_str (die->sect_off), objfile_name (objfile));
14092       return;
14093     }
14094   pc = attr_value_as_address (attr) + baseaddr;
14095   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14096
14097   if (cu->call_site_htab == NULL)
14098     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14099                                                NULL, &objfile->objfile_obstack,
14100                                                hashtab_obstack_allocate, NULL);
14101   call_site_local.pc = pc;
14102   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14103   if (*slot != NULL)
14104     {
14105       complaint (&symfile_complaints,
14106                  _("Duplicate PC %s for DW_TAG_call_site "
14107                    "DIE %s [in module %s]"),
14108                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
14109                  objfile_name (objfile));
14110       return;
14111     }
14112
14113   /* Count parameters at the caller.  */
14114
14115   nparams = 0;
14116   for (child_die = die->child; child_die && child_die->tag;
14117        child_die = sibling_die (child_die))
14118     {
14119       if (child_die->tag != DW_TAG_call_site_parameter
14120           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14121         {
14122           complaint (&symfile_complaints,
14123                      _("Tag %d is not DW_TAG_call_site_parameter in "
14124                        "DW_TAG_call_site child DIE %s [in module %s]"),
14125                      child_die->tag, sect_offset_str (child_die->sect_off),
14126                      objfile_name (objfile));
14127           continue;
14128         }
14129
14130       nparams++;
14131     }
14132
14133   call_site
14134     = ((struct call_site *)
14135        obstack_alloc (&objfile->objfile_obstack,
14136                       sizeof (*call_site)
14137                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14138   *slot = call_site;
14139   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14140   call_site->pc = pc;
14141
14142   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14143       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14144     {
14145       struct die_info *func_die;
14146
14147       /* Skip also over DW_TAG_inlined_subroutine.  */
14148       for (func_die = die->parent;
14149            func_die && func_die->tag != DW_TAG_subprogram
14150            && func_die->tag != DW_TAG_subroutine_type;
14151            func_die = func_die->parent);
14152
14153       /* DW_AT_call_all_calls is a superset
14154          of DW_AT_call_all_tail_calls.  */
14155       if (func_die
14156           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14157           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14158           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14159           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14160         {
14161           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14162              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14163              both the initial caller containing the real return address PC and
14164              the final callee containing the current PC of a chain of tail
14165              calls do not need to have the tail call list complete.  But any
14166              function candidate for a virtual tail call frame searched via
14167              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14168              determined unambiguously.  */
14169         }
14170       else
14171         {
14172           struct type *func_type = NULL;
14173
14174           if (func_die)
14175             func_type = get_die_type (func_die, cu);
14176           if (func_type != NULL)
14177             {
14178               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14179
14180               /* Enlist this call site to the function.  */
14181               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14182               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14183             }
14184           else
14185             complaint (&symfile_complaints,
14186                        _("Cannot find function owning DW_TAG_call_site "
14187                          "DIE %s [in module %s]"),
14188                        sect_offset_str (die->sect_off), objfile_name (objfile));
14189         }
14190     }
14191
14192   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14193   if (attr == NULL)
14194     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14195   if (attr == NULL)
14196     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14197   if (attr == NULL)
14198     {
14199       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14200       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14201     }
14202   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14203   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14204     /* Keep NULL DWARF_BLOCK.  */;
14205   else if (attr_form_is_block (attr))
14206     {
14207       struct dwarf2_locexpr_baton *dlbaton;
14208
14209       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14210       dlbaton->data = DW_BLOCK (attr)->data;
14211       dlbaton->size = DW_BLOCK (attr)->size;
14212       dlbaton->per_cu = cu->per_cu;
14213
14214       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14215     }
14216   else if (attr_form_is_ref (attr))
14217     {
14218       struct dwarf2_cu *target_cu = cu;
14219       struct die_info *target_die;
14220
14221       target_die = follow_die_ref (die, attr, &target_cu);
14222       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14223       if (die_is_declaration (target_die, target_cu))
14224         {
14225           const char *target_physname;
14226
14227           /* Prefer the mangled name; otherwise compute the demangled one.  */
14228           target_physname = dw2_linkage_name (target_die, target_cu);
14229           if (target_physname == NULL)
14230             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14231           if (target_physname == NULL)
14232             complaint (&symfile_complaints,
14233                        _("DW_AT_call_target target DIE has invalid "
14234                          "physname, for referencing DIE %s [in module %s]"),
14235                        sect_offset_str (die->sect_off), objfile_name (objfile));
14236           else
14237             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14238         }
14239       else
14240         {
14241           CORE_ADDR lowpc;
14242
14243           /* DW_AT_entry_pc should be preferred.  */
14244           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14245               <= PC_BOUNDS_INVALID)
14246             complaint (&symfile_complaints,
14247                        _("DW_AT_call_target target DIE has invalid "
14248                          "low pc, for referencing DIE %s [in module %s]"),
14249                        sect_offset_str (die->sect_off), objfile_name (objfile));
14250           else
14251             {
14252               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14253               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14254             }
14255         }
14256     }
14257   else
14258     complaint (&symfile_complaints,
14259                _("DW_TAG_call_site DW_AT_call_target is neither "
14260                  "block nor reference, for DIE %s [in module %s]"),
14261                sect_offset_str (die->sect_off), objfile_name (objfile));
14262
14263   call_site->per_cu = cu->per_cu;
14264
14265   for (child_die = die->child;
14266        child_die && child_die->tag;
14267        child_die = sibling_die (child_die))
14268     {
14269       struct call_site_parameter *parameter;
14270       struct attribute *loc, *origin;
14271
14272       if (child_die->tag != DW_TAG_call_site_parameter
14273           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14274         {
14275           /* Already printed the complaint above.  */
14276           continue;
14277         }
14278
14279       gdb_assert (call_site->parameter_count < nparams);
14280       parameter = &call_site->parameter[call_site->parameter_count];
14281
14282       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14283          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14284          register is contained in DW_AT_call_value.  */
14285
14286       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14287       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14288       if (origin == NULL)
14289         {
14290           /* This was a pre-DWARF-5 GNU extension alias
14291              for DW_AT_call_parameter.  */
14292           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14293         }
14294       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14295         {
14296           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14297
14298           sect_offset sect_off
14299             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14300           if (!offset_in_cu_p (&cu->header, sect_off))
14301             {
14302               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14303                  binding can be done only inside one CU.  Such referenced DIE
14304                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14305               complaint (&symfile_complaints,
14306                          _("DW_AT_call_parameter offset is not in CU for "
14307                            "DW_TAG_call_site child DIE %s [in module %s]"),
14308                          sect_offset_str (child_die->sect_off),
14309                          objfile_name (objfile));
14310               continue;
14311             }
14312           parameter->u.param_cu_off
14313             = (cu_offset) (sect_off - cu->header.sect_off);
14314         }
14315       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14316         {
14317           complaint (&symfile_complaints,
14318                      _("No DW_FORM_block* DW_AT_location for "
14319                        "DW_TAG_call_site child DIE %s [in module %s]"),
14320                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14321           continue;
14322         }
14323       else
14324         {
14325           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14326             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14327           if (parameter->u.dwarf_reg != -1)
14328             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14329           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14330                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14331                                              &parameter->u.fb_offset))
14332             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14333           else
14334             {
14335               complaint (&symfile_complaints,
14336                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14337                            "for DW_FORM_block* DW_AT_location is supported for "
14338                            "DW_TAG_call_site child DIE %s "
14339                            "[in module %s]"),
14340                          sect_offset_str (child_die->sect_off),
14341                          objfile_name (objfile));
14342               continue;
14343             }
14344         }
14345
14346       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14347       if (attr == NULL)
14348         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14349       if (!attr_form_is_block (attr))
14350         {
14351           complaint (&symfile_complaints,
14352                      _("No DW_FORM_block* DW_AT_call_value for "
14353                        "DW_TAG_call_site child DIE %s [in module %s]"),
14354                      sect_offset_str (child_die->sect_off),
14355                      objfile_name (objfile));
14356           continue;
14357         }
14358       parameter->value = DW_BLOCK (attr)->data;
14359       parameter->value_size = DW_BLOCK (attr)->size;
14360
14361       /* Parameters are not pre-cleared by memset above.  */
14362       parameter->data_value = NULL;
14363       parameter->data_value_size = 0;
14364       call_site->parameter_count++;
14365
14366       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14367       if (attr == NULL)
14368         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14369       if (attr)
14370         {
14371           if (!attr_form_is_block (attr))
14372             complaint (&symfile_complaints,
14373                        _("No DW_FORM_block* DW_AT_call_data_value for "
14374                          "DW_TAG_call_site child DIE %s [in module %s]"),
14375                        sect_offset_str (child_die->sect_off),
14376                        objfile_name (objfile));
14377           else
14378             {
14379               parameter->data_value = DW_BLOCK (attr)->data;
14380               parameter->data_value_size = DW_BLOCK (attr)->size;
14381             }
14382         }
14383     }
14384 }
14385
14386 /* Helper function for read_variable.  If DIE represents a virtual
14387    table, then return the type of the concrete object that is
14388    associated with the virtual table.  Otherwise, return NULL.  */
14389
14390 static struct type *
14391 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14392 {
14393   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14394   if (attr == NULL)
14395     return NULL;
14396
14397   /* Find the type DIE.  */
14398   struct die_info *type_die = NULL;
14399   struct dwarf2_cu *type_cu = cu;
14400
14401   if (attr_form_is_ref (attr))
14402     type_die = follow_die_ref (die, attr, &type_cu);
14403   if (type_die == NULL)
14404     return NULL;
14405
14406   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14407     return NULL;
14408   return die_containing_type (type_die, type_cu);
14409 }
14410
14411 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14412
14413 static void
14414 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14415 {
14416   struct rust_vtable_symbol *storage = NULL;
14417
14418   if (cu->language == language_rust)
14419     {
14420       struct type *containing_type = rust_containing_type (die, cu);
14421
14422       if (containing_type != NULL)
14423         {
14424           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14425
14426           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14427                                     struct rust_vtable_symbol);
14428           initialize_objfile_symbol (storage);
14429           storage->concrete_type = containing_type;
14430           storage->subclass = SYMBOL_RUST_VTABLE;
14431         }
14432     }
14433
14434   new_symbol (die, NULL, cu, storage);
14435 }
14436
14437 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14438    reading .debug_rnglists.
14439    Callback's type should be:
14440     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14441    Return true if the attributes are present and valid, otherwise,
14442    return false.  */
14443
14444 template <typename Callback>
14445 static bool
14446 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14447                          Callback &&callback)
14448 {
14449   struct dwarf2_per_objfile *dwarf2_per_objfile
14450     = cu->per_cu->dwarf2_per_objfile;
14451   struct objfile *objfile = dwarf2_per_objfile->objfile;
14452   bfd *obfd = objfile->obfd;
14453   /* Base address selection entry.  */
14454   CORE_ADDR base;
14455   int found_base;
14456   const gdb_byte *buffer;
14457   CORE_ADDR baseaddr;
14458   bool overflow = false;
14459
14460   found_base = cu->base_known;
14461   base = cu->base_address;
14462
14463   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14464   if (offset >= dwarf2_per_objfile->rnglists.size)
14465     {
14466       complaint (&symfile_complaints,
14467                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14468                  offset);
14469       return false;
14470     }
14471   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14472
14473   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14474
14475   while (1)
14476     {
14477       /* Initialize it due to a false compiler warning.  */
14478       CORE_ADDR range_beginning = 0, range_end = 0;
14479       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14480                                  + dwarf2_per_objfile->rnglists.size);
14481       unsigned int bytes_read;
14482
14483       if (buffer == buf_end)
14484         {
14485           overflow = true;
14486           break;
14487         }
14488       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14489       switch (rlet)
14490         {
14491         case DW_RLE_end_of_list:
14492           break;
14493         case DW_RLE_base_address:
14494           if (buffer + cu->header.addr_size > buf_end)
14495             {
14496               overflow = true;
14497               break;
14498             }
14499           base = read_address (obfd, buffer, cu, &bytes_read);
14500           found_base = 1;
14501           buffer += bytes_read;
14502           break;
14503         case DW_RLE_start_length:
14504           if (buffer + cu->header.addr_size > buf_end)
14505             {
14506               overflow = true;
14507               break;
14508             }
14509           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14510           buffer += bytes_read;
14511           range_end = (range_beginning
14512                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14513           buffer += bytes_read;
14514           if (buffer > buf_end)
14515             {
14516               overflow = true;
14517               break;
14518             }
14519           break;
14520         case DW_RLE_offset_pair:
14521           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14522           buffer += bytes_read;
14523           if (buffer > buf_end)
14524             {
14525               overflow = true;
14526               break;
14527             }
14528           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14529           buffer += bytes_read;
14530           if (buffer > buf_end)
14531             {
14532               overflow = true;
14533               break;
14534             }
14535           break;
14536         case DW_RLE_start_end:
14537           if (buffer + 2 * cu->header.addr_size > buf_end)
14538             {
14539               overflow = true;
14540               break;
14541             }
14542           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14543           buffer += bytes_read;
14544           range_end = read_address (obfd, buffer, cu, &bytes_read);
14545           buffer += bytes_read;
14546           break;
14547         default:
14548           complaint (&symfile_complaints,
14549                      _("Invalid .debug_rnglists data (no base address)"));
14550           return false;
14551         }
14552       if (rlet == DW_RLE_end_of_list || overflow)
14553         break;
14554       if (rlet == DW_RLE_base_address)
14555         continue;
14556
14557       if (!found_base)
14558         {
14559           /* We have no valid base address for the ranges
14560              data.  */
14561           complaint (&symfile_complaints,
14562                      _("Invalid .debug_rnglists data (no base address)"));
14563           return false;
14564         }
14565
14566       if (range_beginning > range_end)
14567         {
14568           /* Inverted range entries are invalid.  */
14569           complaint (&symfile_complaints,
14570                      _("Invalid .debug_rnglists data (inverted range)"));
14571           return false;
14572         }
14573
14574       /* Empty range entries have no effect.  */
14575       if (range_beginning == range_end)
14576         continue;
14577
14578       range_beginning += base;
14579       range_end += base;
14580
14581       /* A not-uncommon case of bad debug info.
14582          Don't pollute the addrmap with bad data.  */
14583       if (range_beginning + baseaddr == 0
14584           && !dwarf2_per_objfile->has_section_at_zero)
14585         {
14586           complaint (&symfile_complaints,
14587                      _(".debug_rnglists entry has start address of zero"
14588                        " [in module %s]"), objfile_name (objfile));
14589           continue;
14590         }
14591
14592       callback (range_beginning, range_end);
14593     }
14594
14595   if (overflow)
14596     {
14597       complaint (&symfile_complaints,
14598                  _("Offset %d is not terminated "
14599                    "for DW_AT_ranges attribute"),
14600                  offset);
14601       return false;
14602     }
14603
14604   return true;
14605 }
14606
14607 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14608    Callback's type should be:
14609     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14610    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14611
14612 template <typename Callback>
14613 static int
14614 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14615                        Callback &&callback)
14616 {
14617   struct dwarf2_per_objfile *dwarf2_per_objfile
14618       = cu->per_cu->dwarf2_per_objfile;
14619   struct objfile *objfile = dwarf2_per_objfile->objfile;
14620   struct comp_unit_head *cu_header = &cu->header;
14621   bfd *obfd = objfile->obfd;
14622   unsigned int addr_size = cu_header->addr_size;
14623   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14624   /* Base address selection entry.  */
14625   CORE_ADDR base;
14626   int found_base;
14627   unsigned int dummy;
14628   const gdb_byte *buffer;
14629   CORE_ADDR baseaddr;
14630
14631   if (cu_header->version >= 5)
14632     return dwarf2_rnglists_process (offset, cu, callback);
14633
14634   found_base = cu->base_known;
14635   base = cu->base_address;
14636
14637   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14638   if (offset >= dwarf2_per_objfile->ranges.size)
14639     {
14640       complaint (&symfile_complaints,
14641                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14642                  offset);
14643       return 0;
14644     }
14645   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14646
14647   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14648
14649   while (1)
14650     {
14651       CORE_ADDR range_beginning, range_end;
14652
14653       range_beginning = read_address (obfd, buffer, cu, &dummy);
14654       buffer += addr_size;
14655       range_end = read_address (obfd, buffer, cu, &dummy);
14656       buffer += addr_size;
14657       offset += 2 * addr_size;
14658
14659       /* An end of list marker is a pair of zero addresses.  */
14660       if (range_beginning == 0 && range_end == 0)
14661         /* Found the end of list entry.  */
14662         break;
14663
14664       /* Each base address selection entry is a pair of 2 values.
14665          The first is the largest possible address, the second is
14666          the base address.  Check for a base address here.  */
14667       if ((range_beginning & mask) == mask)
14668         {
14669           /* If we found the largest possible address, then we already
14670              have the base address in range_end.  */
14671           base = range_end;
14672           found_base = 1;
14673           continue;
14674         }
14675
14676       if (!found_base)
14677         {
14678           /* We have no valid base address for the ranges
14679              data.  */
14680           complaint (&symfile_complaints,
14681                      _("Invalid .debug_ranges data (no base address)"));
14682           return 0;
14683         }
14684
14685       if (range_beginning > range_end)
14686         {
14687           /* Inverted range entries are invalid.  */
14688           complaint (&symfile_complaints,
14689                      _("Invalid .debug_ranges data (inverted range)"));
14690           return 0;
14691         }
14692
14693       /* Empty range entries have no effect.  */
14694       if (range_beginning == range_end)
14695         continue;
14696
14697       range_beginning += base;
14698       range_end += base;
14699
14700       /* A not-uncommon case of bad debug info.
14701          Don't pollute the addrmap with bad data.  */
14702       if (range_beginning + baseaddr == 0
14703           && !dwarf2_per_objfile->has_section_at_zero)
14704         {
14705           complaint (&symfile_complaints,
14706                      _(".debug_ranges entry has start address of zero"
14707                        " [in module %s]"), objfile_name (objfile));
14708           continue;
14709         }
14710
14711       callback (range_beginning, range_end);
14712     }
14713
14714   return 1;
14715 }
14716
14717 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14718    Return 1 if the attributes are present and valid, otherwise, return 0.
14719    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14720
14721 static int
14722 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14723                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14724                     struct partial_symtab *ranges_pst)
14725 {
14726   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14727   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14728   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14729                                        SECT_OFF_TEXT (objfile));
14730   int low_set = 0;
14731   CORE_ADDR low = 0;
14732   CORE_ADDR high = 0;
14733   int retval;
14734
14735   retval = dwarf2_ranges_process (offset, cu,
14736     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14737     {
14738       if (ranges_pst != NULL)
14739         {
14740           CORE_ADDR lowpc;
14741           CORE_ADDR highpc;
14742
14743           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14744                                               range_beginning + baseaddr);
14745           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14746                                                range_end + baseaddr);
14747           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14748                              ranges_pst);
14749         }
14750
14751       /* FIXME: This is recording everything as a low-high
14752          segment of consecutive addresses.  We should have a
14753          data structure for discontiguous block ranges
14754          instead.  */
14755       if (! low_set)
14756         {
14757           low = range_beginning;
14758           high = range_end;
14759           low_set = 1;
14760         }
14761       else
14762         {
14763           if (range_beginning < low)
14764             low = range_beginning;
14765           if (range_end > high)
14766             high = range_end;
14767         }
14768     });
14769   if (!retval)
14770     return 0;
14771
14772   if (! low_set)
14773     /* If the first entry is an end-of-list marker, the range
14774        describes an empty scope, i.e. no instructions.  */
14775     return 0;
14776
14777   if (low_return)
14778     *low_return = low;
14779   if (high_return)
14780     *high_return = high;
14781   return 1;
14782 }
14783
14784 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14785    definition for the return value.  *LOWPC and *HIGHPC are set iff
14786    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14787
14788 static enum pc_bounds_kind
14789 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14790                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14791                       struct partial_symtab *pst)
14792 {
14793   struct dwarf2_per_objfile *dwarf2_per_objfile
14794     = cu->per_cu->dwarf2_per_objfile;
14795   struct attribute *attr;
14796   struct attribute *attr_high;
14797   CORE_ADDR low = 0;
14798   CORE_ADDR high = 0;
14799   enum pc_bounds_kind ret;
14800
14801   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14802   if (attr_high)
14803     {
14804       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14805       if (attr)
14806         {
14807           low = attr_value_as_address (attr);
14808           high = attr_value_as_address (attr_high);
14809           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14810             high += low;
14811         }
14812       else
14813         /* Found high w/o low attribute.  */
14814         return PC_BOUNDS_INVALID;
14815
14816       /* Found consecutive range of addresses.  */
14817       ret = PC_BOUNDS_HIGH_LOW;
14818     }
14819   else
14820     {
14821       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14822       if (attr != NULL)
14823         {
14824           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14825              We take advantage of the fact that DW_AT_ranges does not appear
14826              in DW_TAG_compile_unit of DWO files.  */
14827           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14828           unsigned int ranges_offset = (DW_UNSND (attr)
14829                                         + (need_ranges_base
14830                                            ? cu->ranges_base
14831                                            : 0));
14832
14833           /* Value of the DW_AT_ranges attribute is the offset in the
14834              .debug_ranges section.  */
14835           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14836             return PC_BOUNDS_INVALID;
14837           /* Found discontinuous range of addresses.  */
14838           ret = PC_BOUNDS_RANGES;
14839         }
14840       else
14841         return PC_BOUNDS_NOT_PRESENT;
14842     }
14843
14844   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14845   if (high <= low)
14846     return PC_BOUNDS_INVALID;
14847
14848   /* When using the GNU linker, .gnu.linkonce. sections are used to
14849      eliminate duplicate copies of functions and vtables and such.
14850      The linker will arbitrarily choose one and discard the others.
14851      The AT_*_pc values for such functions refer to local labels in
14852      these sections.  If the section from that file was discarded, the
14853      labels are not in the output, so the relocs get a value of 0.
14854      If this is a discarded function, mark the pc bounds as invalid,
14855      so that GDB will ignore it.  */
14856   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14857     return PC_BOUNDS_INVALID;
14858
14859   *lowpc = low;
14860   if (highpc)
14861     *highpc = high;
14862   return ret;
14863 }
14864
14865 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14866    its low and high PC addresses.  Do nothing if these addresses could not
14867    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14868    and HIGHPC to the high address if greater than HIGHPC.  */
14869
14870 static void
14871 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14872                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14873                                  struct dwarf2_cu *cu)
14874 {
14875   CORE_ADDR low, high;
14876   struct die_info *child = die->child;
14877
14878   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14879     {
14880       *lowpc = std::min (*lowpc, low);
14881       *highpc = std::max (*highpc, high);
14882     }
14883
14884   /* If the language does not allow nested subprograms (either inside
14885      subprograms or lexical blocks), we're done.  */
14886   if (cu->language != language_ada)
14887     return;
14888
14889   /* Check all the children of the given DIE.  If it contains nested
14890      subprograms, then check their pc bounds.  Likewise, we need to
14891      check lexical blocks as well, as they may also contain subprogram
14892      definitions.  */
14893   while (child && child->tag)
14894     {
14895       if (child->tag == DW_TAG_subprogram
14896           || child->tag == DW_TAG_lexical_block)
14897         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14898       child = sibling_die (child);
14899     }
14900 }
14901
14902 /* Get the low and high pc's represented by the scope DIE, and store
14903    them in *LOWPC and *HIGHPC.  If the correct values can't be
14904    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14905
14906 static void
14907 get_scope_pc_bounds (struct die_info *die,
14908                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14909                      struct dwarf2_cu *cu)
14910 {
14911   CORE_ADDR best_low = (CORE_ADDR) -1;
14912   CORE_ADDR best_high = (CORE_ADDR) 0;
14913   CORE_ADDR current_low, current_high;
14914
14915   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14916       >= PC_BOUNDS_RANGES)
14917     {
14918       best_low = current_low;
14919       best_high = current_high;
14920     }
14921   else
14922     {
14923       struct die_info *child = die->child;
14924
14925       while (child && child->tag)
14926         {
14927           switch (child->tag) {
14928           case DW_TAG_subprogram:
14929             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14930             break;
14931           case DW_TAG_namespace:
14932           case DW_TAG_module:
14933             /* FIXME: carlton/2004-01-16: Should we do this for
14934                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14935                that current GCC's always emit the DIEs corresponding
14936                to definitions of methods of classes as children of a
14937                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14938                the DIEs giving the declarations, which could be
14939                anywhere).  But I don't see any reason why the
14940                standards says that they have to be there.  */
14941             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14942
14943             if (current_low != ((CORE_ADDR) -1))
14944               {
14945                 best_low = std::min (best_low, current_low);
14946                 best_high = std::max (best_high, current_high);
14947               }
14948             break;
14949           default:
14950             /* Ignore.  */
14951             break;
14952           }
14953
14954           child = sibling_die (child);
14955         }
14956     }
14957
14958   *lowpc = best_low;
14959   *highpc = best_high;
14960 }
14961
14962 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14963    in DIE.  */
14964
14965 static void
14966 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14967                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14968 {
14969   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14970   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14971   struct attribute *attr;
14972   struct attribute *attr_high;
14973
14974   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14975   if (attr_high)
14976     {
14977       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14978       if (attr)
14979         {
14980           CORE_ADDR low = attr_value_as_address (attr);
14981           CORE_ADDR high = attr_value_as_address (attr_high);
14982
14983           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14984             high += low;
14985
14986           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14987           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14988           record_block_range (block, low, high - 1);
14989         }
14990     }
14991
14992   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14993   if (attr)
14994     {
14995       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14996          We take advantage of the fact that DW_AT_ranges does not appear
14997          in DW_TAG_compile_unit of DWO files.  */
14998       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14999
15000       /* The value of the DW_AT_ranges attribute is the offset of the
15001          address range list in the .debug_ranges section.  */
15002       unsigned long offset = (DW_UNSND (attr)
15003                               + (need_ranges_base ? cu->ranges_base : 0));
15004       const gdb_byte *buffer;
15005
15006       /* For some target architectures, but not others, the
15007          read_address function sign-extends the addresses it returns.
15008          To recognize base address selection entries, we need a
15009          mask.  */
15010       unsigned int addr_size = cu->header.addr_size;
15011       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
15012
15013       /* The base address, to which the next pair is relative.  Note
15014          that this 'base' is a DWARF concept: most entries in a range
15015          list are relative, to reduce the number of relocs against the
15016          debugging information.  This is separate from this function's
15017          'baseaddr' argument, which GDB uses to relocate debugging
15018          information from a shared library based on the address at
15019          which the library was loaded.  */
15020       CORE_ADDR base = cu->base_address;
15021       int base_known = cu->base_known;
15022
15023       dwarf2_ranges_process (offset, cu,
15024         [&] (CORE_ADDR start, CORE_ADDR end)
15025         {
15026           start += baseaddr;
15027           end += baseaddr;
15028           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
15029           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
15030           record_block_range (block, start, end - 1);
15031         });
15032     }
15033 }
15034
15035 /* Check whether the producer field indicates either of GCC < 4.6, or the
15036    Intel C/C++ compiler, and cache the result in CU.  */
15037
15038 static void
15039 check_producer (struct dwarf2_cu *cu)
15040 {
15041   int major, minor;
15042
15043   if (cu->producer == NULL)
15044     {
15045       /* For unknown compilers expect their behavior is DWARF version
15046          compliant.
15047
15048          GCC started to support .debug_types sections by -gdwarf-4 since
15049          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15050          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15051          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15052          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15053     }
15054   else if (producer_is_gcc (cu->producer, &major, &minor))
15055     {
15056       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15057       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15058     }
15059   else if (producer_is_icc (cu->producer, &major, &minor))
15060     cu->producer_is_icc_lt_14 = major < 14;
15061   else
15062     {
15063       /* For other non-GCC compilers, expect their behavior is DWARF version
15064          compliant.  */
15065     }
15066
15067   cu->checked_producer = 1;
15068 }
15069
15070 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15071    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15072    during 4.6.0 experimental.  */
15073
15074 static int
15075 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15076 {
15077   if (!cu->checked_producer)
15078     check_producer (cu);
15079
15080   return cu->producer_is_gxx_lt_4_6;
15081 }
15082
15083 /* Return the default accessibility type if it is not overriden by
15084    DW_AT_accessibility.  */
15085
15086 static enum dwarf_access_attribute
15087 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15088 {
15089   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15090     {
15091       /* The default DWARF 2 accessibility for members is public, the default
15092          accessibility for inheritance is private.  */
15093
15094       if (die->tag != DW_TAG_inheritance)
15095         return DW_ACCESS_public;
15096       else
15097         return DW_ACCESS_private;
15098     }
15099   else
15100     {
15101       /* DWARF 3+ defines the default accessibility a different way.  The same
15102          rules apply now for DW_TAG_inheritance as for the members and it only
15103          depends on the container kind.  */
15104
15105       if (die->parent->tag == DW_TAG_class_type)
15106         return DW_ACCESS_private;
15107       else
15108         return DW_ACCESS_public;
15109     }
15110 }
15111
15112 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15113    offset.  If the attribute was not found return 0, otherwise return
15114    1.  If it was found but could not properly be handled, set *OFFSET
15115    to 0.  */
15116
15117 static int
15118 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15119                              LONGEST *offset)
15120 {
15121   struct attribute *attr;
15122
15123   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15124   if (attr != NULL)
15125     {
15126       *offset = 0;
15127
15128       /* Note that we do not check for a section offset first here.
15129          This is because DW_AT_data_member_location is new in DWARF 4,
15130          so if we see it, we can assume that a constant form is really
15131          a constant and not a section offset.  */
15132       if (attr_form_is_constant (attr))
15133         *offset = dwarf2_get_attr_constant_value (attr, 0);
15134       else if (attr_form_is_section_offset (attr))
15135         dwarf2_complex_location_expr_complaint ();
15136       else if (attr_form_is_block (attr))
15137         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15138       else
15139         dwarf2_complex_location_expr_complaint ();
15140
15141       return 1;
15142     }
15143
15144   return 0;
15145 }
15146
15147 /* Add an aggregate field to the field list.  */
15148
15149 static void
15150 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15151                   struct dwarf2_cu *cu)
15152 {
15153   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15154   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15155   struct nextfield *new_field;
15156   struct attribute *attr;
15157   struct field *fp;
15158   const char *fieldname = "";
15159
15160   /* Allocate a new field list entry and link it in.  */
15161   new_field = XNEW (struct nextfield);
15162   make_cleanup (xfree, new_field);
15163   memset (new_field, 0, sizeof (struct nextfield));
15164
15165   if (die->tag == DW_TAG_inheritance)
15166     {
15167       new_field->next = fip->baseclasses;
15168       fip->baseclasses = new_field;
15169     }
15170   else
15171     {
15172       new_field->next = fip->fields;
15173       fip->fields = new_field;
15174     }
15175   fip->nfields++;
15176
15177   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15178   if (attr)
15179     new_field->accessibility = DW_UNSND (attr);
15180   else
15181     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15182   if (new_field->accessibility != DW_ACCESS_public)
15183     fip->non_public_fields = 1;
15184
15185   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15186   if (attr)
15187     new_field->virtuality = DW_UNSND (attr);
15188   else
15189     new_field->virtuality = DW_VIRTUALITY_none;
15190
15191   fp = &new_field->field;
15192
15193   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15194     {
15195       LONGEST offset;
15196
15197       /* Data member other than a C++ static data member.  */
15198
15199       /* Get type of field.  */
15200       fp->type = die_type (die, cu);
15201
15202       SET_FIELD_BITPOS (*fp, 0);
15203
15204       /* Get bit size of field (zero if none).  */
15205       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15206       if (attr)
15207         {
15208           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15209         }
15210       else
15211         {
15212           FIELD_BITSIZE (*fp) = 0;
15213         }
15214
15215       /* Get bit offset of field.  */
15216       if (handle_data_member_location (die, cu, &offset))
15217         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15218       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15219       if (attr)
15220         {
15221           if (gdbarch_bits_big_endian (gdbarch))
15222             {
15223               /* For big endian bits, the DW_AT_bit_offset gives the
15224                  additional bit offset from the MSB of the containing
15225                  anonymous object to the MSB of the field.  We don't
15226                  have to do anything special since we don't need to
15227                  know the size of the anonymous object.  */
15228               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15229             }
15230           else
15231             {
15232               /* For little endian bits, compute the bit offset to the
15233                  MSB of the anonymous object, subtract off the number of
15234                  bits from the MSB of the field to the MSB of the
15235                  object, and then subtract off the number of bits of
15236                  the field itself.  The result is the bit offset of
15237                  the LSB of the field.  */
15238               int anonymous_size;
15239               int bit_offset = DW_UNSND (attr);
15240
15241               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15242               if (attr)
15243                 {
15244                   /* The size of the anonymous object containing
15245                      the bit field is explicit, so use the
15246                      indicated size (in bytes).  */
15247                   anonymous_size = DW_UNSND (attr);
15248                 }
15249               else
15250                 {
15251                   /* The size of the anonymous object containing
15252                      the bit field must be inferred from the type
15253                      attribute of the data member containing the
15254                      bit field.  */
15255                   anonymous_size = TYPE_LENGTH (fp->type);
15256                 }
15257               SET_FIELD_BITPOS (*fp,
15258                                 (FIELD_BITPOS (*fp)
15259                                  + anonymous_size * bits_per_byte
15260                                  - bit_offset - FIELD_BITSIZE (*fp)));
15261             }
15262         }
15263       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15264       if (attr != NULL)
15265         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15266                                 + dwarf2_get_attr_constant_value (attr, 0)));
15267
15268       /* Get name of field.  */
15269       fieldname = dwarf2_name (die, cu);
15270       if (fieldname == NULL)
15271         fieldname = "";
15272
15273       /* The name is already allocated along with this objfile, so we don't
15274          need to duplicate it for the type.  */
15275       fp->name = fieldname;
15276
15277       /* Change accessibility for artificial fields (e.g. virtual table
15278          pointer or virtual base class pointer) to private.  */
15279       if (dwarf2_attr (die, DW_AT_artificial, cu))
15280         {
15281           FIELD_ARTIFICIAL (*fp) = 1;
15282           new_field->accessibility = DW_ACCESS_private;
15283           fip->non_public_fields = 1;
15284         }
15285     }
15286   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15287     {
15288       /* C++ static member.  */
15289
15290       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15291          is a declaration, but all versions of G++ as of this writing
15292          (so through at least 3.2.1) incorrectly generate
15293          DW_TAG_variable tags.  */
15294
15295       const char *physname;
15296
15297       /* Get name of field.  */
15298       fieldname = dwarf2_name (die, cu);
15299       if (fieldname == NULL)
15300         return;
15301
15302       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15303       if (attr
15304           /* Only create a symbol if this is an external value.
15305              new_symbol checks this and puts the value in the global symbol
15306              table, which we want.  If it is not external, new_symbol
15307              will try to put the value in cu->list_in_scope which is wrong.  */
15308           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15309         {
15310           /* A static const member, not much different than an enum as far as
15311              we're concerned, except that we can support more types.  */
15312           new_symbol (die, NULL, cu);
15313         }
15314
15315       /* Get physical name.  */
15316       physname = dwarf2_physname (fieldname, die, cu);
15317
15318       /* The name is already allocated along with this objfile, so we don't
15319          need to duplicate it for the type.  */
15320       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15321       FIELD_TYPE (*fp) = die_type (die, cu);
15322       FIELD_NAME (*fp) = fieldname;
15323     }
15324   else if (die->tag == DW_TAG_inheritance)
15325     {
15326       LONGEST offset;
15327
15328       /* C++ base class field.  */
15329       if (handle_data_member_location (die, cu, &offset))
15330         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15331       FIELD_BITSIZE (*fp) = 0;
15332       FIELD_TYPE (*fp) = die_type (die, cu);
15333       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15334       fip->nbaseclasses++;
15335     }
15336 }
15337
15338 /* Can the type given by DIE define another type?  */
15339
15340 static bool
15341 type_can_define_types (const struct die_info *die)
15342 {
15343   switch (die->tag)
15344     {
15345     case DW_TAG_typedef:
15346     case DW_TAG_class_type:
15347     case DW_TAG_structure_type:
15348     case DW_TAG_union_type:
15349     case DW_TAG_enumeration_type:
15350       return true;
15351
15352     default:
15353       return false;
15354     }
15355 }
15356
15357 /* Add a type definition defined in the scope of the FIP's class.  */
15358
15359 static void
15360 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15361                       struct dwarf2_cu *cu)
15362 {
15363   struct decl_field_list *new_field;
15364   struct decl_field *fp;
15365
15366   /* Allocate a new field list entry and link it in.  */
15367   new_field = XCNEW (struct decl_field_list);
15368   make_cleanup (xfree, new_field);
15369
15370   gdb_assert (type_can_define_types (die));
15371
15372   fp = &new_field->field;
15373
15374   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15375   fp->name = dwarf2_name (die, cu);
15376   fp->type = read_type_die (die, cu);
15377
15378   /* Save accessibility.  */
15379   enum dwarf_access_attribute accessibility;
15380   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15381   if (attr != NULL)
15382     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15383   else
15384     accessibility = dwarf2_default_access_attribute (die, cu);
15385   switch (accessibility)
15386     {
15387     case DW_ACCESS_public:
15388       /* The assumed value if neither private nor protected.  */
15389       break;
15390     case DW_ACCESS_private:
15391       fp->is_private = 1;
15392       break;
15393     case DW_ACCESS_protected:
15394       fp->is_protected = 1;
15395       break;
15396     default:
15397       complaint (&symfile_complaints,
15398                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15399     }
15400
15401   if (die->tag == DW_TAG_typedef)
15402     {
15403       new_field->next = fip->typedef_field_list;
15404       fip->typedef_field_list = new_field;
15405       fip->typedef_field_list_count++;
15406     }
15407   else
15408     {
15409       new_field->next = fip->nested_types_list;
15410       fip->nested_types_list = new_field;
15411       fip->nested_types_list_count++;
15412     }
15413 }
15414
15415 /* Create the vector of fields, and attach it to the type.  */
15416
15417 static void
15418 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15419                               struct dwarf2_cu *cu)
15420 {
15421   int nfields = fip->nfields;
15422
15423   /* Record the field count, allocate space for the array of fields,
15424      and create blank accessibility bitfields if necessary.  */
15425   TYPE_NFIELDS (type) = nfields;
15426   TYPE_FIELDS (type) = (struct field *)
15427     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15428   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15429
15430   if (fip->non_public_fields && cu->language != language_ada)
15431     {
15432       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15433
15434       TYPE_FIELD_PRIVATE_BITS (type) =
15435         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15436       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15437
15438       TYPE_FIELD_PROTECTED_BITS (type) =
15439         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15440       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15441
15442       TYPE_FIELD_IGNORE_BITS (type) =
15443         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15444       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15445     }
15446
15447   /* If the type has baseclasses, allocate and clear a bit vector for
15448      TYPE_FIELD_VIRTUAL_BITS.  */
15449   if (fip->nbaseclasses && cu->language != language_ada)
15450     {
15451       int num_bytes = B_BYTES (fip->nbaseclasses);
15452       unsigned char *pointer;
15453
15454       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15455       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15456       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15457       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15458       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15459     }
15460
15461   /* Copy the saved-up fields into the field vector.  Start from the head of
15462      the list, adding to the tail of the field array, so that they end up in
15463      the same order in the array in which they were added to the list.  */
15464   while (nfields-- > 0)
15465     {
15466       struct nextfield *fieldp;
15467
15468       if (fip->fields)
15469         {
15470           fieldp = fip->fields;
15471           fip->fields = fieldp->next;
15472         }
15473       else
15474         {
15475           fieldp = fip->baseclasses;
15476           fip->baseclasses = fieldp->next;
15477         }
15478
15479       TYPE_FIELD (type, nfields) = fieldp->field;
15480       switch (fieldp->accessibility)
15481         {
15482         case DW_ACCESS_private:
15483           if (cu->language != language_ada)
15484             SET_TYPE_FIELD_PRIVATE (type, nfields);
15485           break;
15486
15487         case DW_ACCESS_protected:
15488           if (cu->language != language_ada)
15489             SET_TYPE_FIELD_PROTECTED (type, nfields);
15490           break;
15491
15492         case DW_ACCESS_public:
15493           break;
15494
15495         default:
15496           /* Unknown accessibility.  Complain and treat it as public.  */
15497           {
15498             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15499                        fieldp->accessibility);
15500           }
15501           break;
15502         }
15503       if (nfields < fip->nbaseclasses)
15504         {
15505           switch (fieldp->virtuality)
15506             {
15507             case DW_VIRTUALITY_virtual:
15508             case DW_VIRTUALITY_pure_virtual:
15509               if (cu->language == language_ada)
15510                 error (_("unexpected virtuality in component of Ada type"));
15511               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15512               break;
15513             }
15514         }
15515     }
15516 }
15517
15518 /* Return true if this member function is a constructor, false
15519    otherwise.  */
15520
15521 static int
15522 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15523 {
15524   const char *fieldname;
15525   const char *type_name;
15526   int len;
15527
15528   if (die->parent == NULL)
15529     return 0;
15530
15531   if (die->parent->tag != DW_TAG_structure_type
15532       && die->parent->tag != DW_TAG_union_type
15533       && die->parent->tag != DW_TAG_class_type)
15534     return 0;
15535
15536   fieldname = dwarf2_name (die, cu);
15537   type_name = dwarf2_name (die->parent, cu);
15538   if (fieldname == NULL || type_name == NULL)
15539     return 0;
15540
15541   len = strlen (fieldname);
15542   return (strncmp (fieldname, type_name, len) == 0
15543           && (type_name[len] == '\0' || type_name[len] == '<'));
15544 }
15545
15546 /* Add a member function to the proper fieldlist.  */
15547
15548 static void
15549 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15550                       struct type *type, struct dwarf2_cu *cu)
15551 {
15552   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15553   struct attribute *attr;
15554   struct fnfieldlist *flp;
15555   int i;
15556   struct fn_field *fnp;
15557   const char *fieldname;
15558   struct nextfnfield *new_fnfield;
15559   struct type *this_type;
15560   enum dwarf_access_attribute accessibility;
15561
15562   if (cu->language == language_ada)
15563     error (_("unexpected member function in Ada type"));
15564
15565   /* Get name of member function.  */
15566   fieldname = dwarf2_name (die, cu);
15567   if (fieldname == NULL)
15568     return;
15569
15570   /* Look up member function name in fieldlist.  */
15571   for (i = 0; i < fip->nfnfields; i++)
15572     {
15573       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15574         break;
15575     }
15576
15577   /* Create new list element if necessary.  */
15578   if (i < fip->nfnfields)
15579     flp = &fip->fnfieldlists[i];
15580   else
15581     {
15582       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15583         {
15584           fip->fnfieldlists = (struct fnfieldlist *)
15585             xrealloc (fip->fnfieldlists,
15586                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15587                       * sizeof (struct fnfieldlist));
15588           if (fip->nfnfields == 0)
15589             make_cleanup (free_current_contents, &fip->fnfieldlists);
15590         }
15591       flp = &fip->fnfieldlists[fip->nfnfields];
15592       flp->name = fieldname;
15593       flp->length = 0;
15594       flp->head = NULL;
15595       i = fip->nfnfields++;
15596     }
15597
15598   /* Create a new member function field and chain it to the field list
15599      entry.  */
15600   new_fnfield = XNEW (struct nextfnfield);
15601   make_cleanup (xfree, new_fnfield);
15602   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15603   new_fnfield->next = flp->head;
15604   flp->head = new_fnfield;
15605   flp->length++;
15606
15607   /* Fill in the member function field info.  */
15608   fnp = &new_fnfield->fnfield;
15609
15610   /* Delay processing of the physname until later.  */
15611   if (cu->language == language_cplus)
15612     {
15613       add_to_method_list (type, i, flp->length - 1, fieldname,
15614                           die, cu);
15615     }
15616   else
15617     {
15618       const char *physname = dwarf2_physname (fieldname, die, cu);
15619       fnp->physname = physname ? physname : "";
15620     }
15621
15622   fnp->type = alloc_type (objfile);
15623   this_type = read_type_die (die, cu);
15624   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15625     {
15626       int nparams = TYPE_NFIELDS (this_type);
15627
15628       /* TYPE is the domain of this method, and THIS_TYPE is the type
15629            of the method itself (TYPE_CODE_METHOD).  */
15630       smash_to_method_type (fnp->type, type,
15631                             TYPE_TARGET_TYPE (this_type),
15632                             TYPE_FIELDS (this_type),
15633                             TYPE_NFIELDS (this_type),
15634                             TYPE_VARARGS (this_type));
15635
15636       /* Handle static member functions.
15637          Dwarf2 has no clean way to discern C++ static and non-static
15638          member functions.  G++ helps GDB by marking the first
15639          parameter for non-static member functions (which is the this
15640          pointer) as artificial.  We obtain this information from
15641          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15642       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15643         fnp->voffset = VOFFSET_STATIC;
15644     }
15645   else
15646     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15647                dwarf2_full_name (fieldname, die, cu));
15648
15649   /* Get fcontext from DW_AT_containing_type if present.  */
15650   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15651     fnp->fcontext = die_containing_type (die, cu);
15652
15653   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15654      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15655
15656   /* Get accessibility.  */
15657   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15658   if (attr)
15659     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15660   else
15661     accessibility = dwarf2_default_access_attribute (die, cu);
15662   switch (accessibility)
15663     {
15664     case DW_ACCESS_private:
15665       fnp->is_private = 1;
15666       break;
15667     case DW_ACCESS_protected:
15668       fnp->is_protected = 1;
15669       break;
15670     }
15671
15672   /* Check for artificial methods.  */
15673   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15674   if (attr && DW_UNSND (attr) != 0)
15675     fnp->is_artificial = 1;
15676
15677   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15678
15679   /* Get index in virtual function table if it is a virtual member
15680      function.  For older versions of GCC, this is an offset in the
15681      appropriate virtual table, as specified by DW_AT_containing_type.
15682      For everyone else, it is an expression to be evaluated relative
15683      to the object address.  */
15684
15685   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15686   if (attr)
15687     {
15688       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15689         {
15690           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15691             {
15692               /* Old-style GCC.  */
15693               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15694             }
15695           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15696                    || (DW_BLOCK (attr)->size > 1
15697                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15698                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15699             {
15700               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15701               if ((fnp->voffset % cu->header.addr_size) != 0)
15702                 dwarf2_complex_location_expr_complaint ();
15703               else
15704                 fnp->voffset /= cu->header.addr_size;
15705               fnp->voffset += 2;
15706             }
15707           else
15708             dwarf2_complex_location_expr_complaint ();
15709
15710           if (!fnp->fcontext)
15711             {
15712               /* If there is no `this' field and no DW_AT_containing_type,
15713                  we cannot actually find a base class context for the
15714                  vtable!  */
15715               if (TYPE_NFIELDS (this_type) == 0
15716                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15717                 {
15718                   complaint (&symfile_complaints,
15719                              _("cannot determine context for virtual member "
15720                                "function \"%s\" (offset %s)"),
15721                              fieldname, sect_offset_str (die->sect_off));
15722                 }
15723               else
15724                 {
15725                   fnp->fcontext
15726                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15727                 }
15728             }
15729         }
15730       else if (attr_form_is_section_offset (attr))
15731         {
15732           dwarf2_complex_location_expr_complaint ();
15733         }
15734       else
15735         {
15736           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15737                                                  fieldname);
15738         }
15739     }
15740   else
15741     {
15742       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15743       if (attr && DW_UNSND (attr))
15744         {
15745           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15746           complaint (&symfile_complaints,
15747                      _("Member function \"%s\" (offset %s) is virtual "
15748                        "but the vtable offset is not specified"),
15749                      fieldname, sect_offset_str (die->sect_off));
15750           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15751           TYPE_CPLUS_DYNAMIC (type) = 1;
15752         }
15753     }
15754 }
15755
15756 /* Create the vector of member function fields, and attach it to the type.  */
15757
15758 static void
15759 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15760                                  struct dwarf2_cu *cu)
15761 {
15762   struct fnfieldlist *flp;
15763   int i;
15764
15765   if (cu->language == language_ada)
15766     error (_("unexpected member functions in Ada type"));
15767
15768   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15769   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15770     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15771
15772   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15773     {
15774       struct nextfnfield *nfp = flp->head;
15775       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15776       int k;
15777
15778       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15779       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15780       fn_flp->fn_fields = (struct fn_field *)
15781         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15782       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15783         fn_flp->fn_fields[k] = nfp->fnfield;
15784     }
15785
15786   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15787 }
15788
15789 /* Returns non-zero if NAME is the name of a vtable member in CU's
15790    language, zero otherwise.  */
15791 static int
15792 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15793 {
15794   static const char vptr[] = "_vptr";
15795
15796   /* Look for the C++ form of the vtable.  */
15797   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15798     return 1;
15799
15800   return 0;
15801 }
15802
15803 /* GCC outputs unnamed structures that are really pointers to member
15804    functions, with the ABI-specified layout.  If TYPE describes
15805    such a structure, smash it into a member function type.
15806
15807    GCC shouldn't do this; it should just output pointer to member DIEs.
15808    This is GCC PR debug/28767.  */
15809
15810 static void
15811 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15812 {
15813   struct type *pfn_type, *self_type, *new_type;
15814
15815   /* Check for a structure with no name and two children.  */
15816   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15817     return;
15818
15819   /* Check for __pfn and __delta members.  */
15820   if (TYPE_FIELD_NAME (type, 0) == NULL
15821       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15822       || TYPE_FIELD_NAME (type, 1) == NULL
15823       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15824     return;
15825
15826   /* Find the type of the method.  */
15827   pfn_type = TYPE_FIELD_TYPE (type, 0);
15828   if (pfn_type == NULL
15829       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15830       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15831     return;
15832
15833   /* Look for the "this" argument.  */
15834   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15835   if (TYPE_NFIELDS (pfn_type) == 0
15836       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15837       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15838     return;
15839
15840   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15841   new_type = alloc_type (objfile);
15842   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15843                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15844                         TYPE_VARARGS (pfn_type));
15845   smash_to_methodptr_type (type, new_type);
15846 }
15847
15848
15849 /* Called when we find the DIE that starts a structure or union scope
15850    (definition) to create a type for the structure or union.  Fill in
15851    the type's name and general properties; the members will not be
15852    processed until process_structure_scope.  A symbol table entry for
15853    the type will also not be done until process_structure_scope (assuming
15854    the type has a name).
15855
15856    NOTE: we need to call these functions regardless of whether or not the
15857    DIE has a DW_AT_name attribute, since it might be an anonymous
15858    structure or union.  This gets the type entered into our set of
15859    user defined types.  */
15860
15861 static struct type *
15862 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15863 {
15864   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15865   struct type *type;
15866   struct attribute *attr;
15867   const char *name;
15868
15869   /* If the definition of this type lives in .debug_types, read that type.
15870      Don't follow DW_AT_specification though, that will take us back up
15871      the chain and we want to go down.  */
15872   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15873   if (attr)
15874     {
15875       type = get_DW_AT_signature_type (die, attr, cu);
15876
15877       /* The type's CU may not be the same as CU.
15878          Ensure TYPE is recorded with CU in die_type_hash.  */
15879       return set_die_type (die, type, cu);
15880     }
15881
15882   type = alloc_type (objfile);
15883   INIT_CPLUS_SPECIFIC (type);
15884
15885   name = dwarf2_name (die, cu);
15886   if (name != NULL)
15887     {
15888       if (cu->language == language_cplus
15889           || cu->language == language_d
15890           || cu->language == language_rust)
15891         {
15892           const char *full_name = dwarf2_full_name (name, die, cu);
15893
15894           /* dwarf2_full_name might have already finished building the DIE's
15895              type.  If so, there is no need to continue.  */
15896           if (get_die_type (die, cu) != NULL)
15897             return get_die_type (die, cu);
15898
15899           TYPE_TAG_NAME (type) = full_name;
15900           if (die->tag == DW_TAG_structure_type
15901               || die->tag == DW_TAG_class_type)
15902             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15903         }
15904       else
15905         {
15906           /* The name is already allocated along with this objfile, so
15907              we don't need to duplicate it for the type.  */
15908           TYPE_TAG_NAME (type) = name;
15909           if (die->tag == DW_TAG_class_type)
15910             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15911         }
15912     }
15913
15914   if (die->tag == DW_TAG_structure_type)
15915     {
15916       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15917     }
15918   else if (die->tag == DW_TAG_union_type)
15919     {
15920       TYPE_CODE (type) = TYPE_CODE_UNION;
15921     }
15922   else
15923     {
15924       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15925     }
15926
15927   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15928     TYPE_DECLARED_CLASS (type) = 1;
15929
15930   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15931   if (attr)
15932     {
15933       if (attr_form_is_constant (attr))
15934         TYPE_LENGTH (type) = DW_UNSND (attr);
15935       else
15936         {
15937           /* For the moment, dynamic type sizes are not supported
15938              by GDB's struct type.  The actual size is determined
15939              on-demand when resolving the type of a given object,
15940              so set the type's length to zero for now.  Otherwise,
15941              we record an expression as the length, and that expression
15942              could lead to a very large value, which could eventually
15943              lead to us trying to allocate that much memory when creating
15944              a value of that type.  */
15945           TYPE_LENGTH (type) = 0;
15946         }
15947     }
15948   else
15949     {
15950       TYPE_LENGTH (type) = 0;
15951     }
15952
15953   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15954     {
15955       /* ICC<14 does not output the required DW_AT_declaration on
15956          incomplete types, but gives them a size of zero.  */
15957       TYPE_STUB (type) = 1;
15958     }
15959   else
15960     TYPE_STUB_SUPPORTED (type) = 1;
15961
15962   if (die_is_declaration (die, cu))
15963     TYPE_STUB (type) = 1;
15964   else if (attr == NULL && die->child == NULL
15965            && producer_is_realview (cu->producer))
15966     /* RealView does not output the required DW_AT_declaration
15967        on incomplete types.  */
15968     TYPE_STUB (type) = 1;
15969
15970   /* We need to add the type field to the die immediately so we don't
15971      infinitely recurse when dealing with pointers to the structure
15972      type within the structure itself.  */
15973   set_die_type (die, type, cu);
15974
15975   /* set_die_type should be already done.  */
15976   set_descriptive_type (type, die, cu);
15977
15978   return type;
15979 }
15980
15981 /* Finish creating a structure or union type, including filling in
15982    its members and creating a symbol for it.  */
15983
15984 static void
15985 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15986 {
15987   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15988   struct die_info *child_die;
15989   struct type *type;
15990
15991   type = get_die_type (die, cu);
15992   if (type == NULL)
15993     type = read_structure_type (die, cu);
15994
15995   if (die->child != NULL && ! die_is_declaration (die, cu))
15996     {
15997       struct field_info fi;
15998       std::vector<struct symbol *> template_args;
15999       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
16000
16001       memset (&fi, 0, sizeof (struct field_info));
16002
16003       child_die = die->child;
16004
16005       while (child_die && child_die->tag)
16006         {
16007           if (child_die->tag == DW_TAG_member
16008               || child_die->tag == DW_TAG_variable)
16009             {
16010               /* NOTE: carlton/2002-11-05: A C++ static data member
16011                  should be a DW_TAG_member that is a declaration, but
16012                  all versions of G++ as of this writing (so through at
16013                  least 3.2.1) incorrectly generate DW_TAG_variable
16014                  tags for them instead.  */
16015               dwarf2_add_field (&fi, child_die, cu);
16016             }
16017           else if (child_die->tag == DW_TAG_subprogram)
16018             {
16019               /* Rust doesn't have member functions in the C++ sense.
16020                  However, it does emit ordinary functions as children
16021                  of a struct DIE.  */
16022               if (cu->language == language_rust)
16023                 read_func_scope (child_die, cu);
16024               else
16025                 {
16026                   /* C++ member function.  */
16027                   dwarf2_add_member_fn (&fi, child_die, type, cu);
16028                 }
16029             }
16030           else if (child_die->tag == DW_TAG_inheritance)
16031             {
16032               /* C++ base class field.  */
16033               dwarf2_add_field (&fi, child_die, cu);
16034             }
16035           else if (type_can_define_types (child_die))
16036             dwarf2_add_type_defn (&fi, child_die, cu);
16037           else if (child_die->tag == DW_TAG_template_type_param
16038                    || child_die->tag == DW_TAG_template_value_param)
16039             {
16040               struct symbol *arg = new_symbol (child_die, NULL, cu);
16041
16042               if (arg != NULL)
16043                 template_args.push_back (arg);
16044             }
16045
16046           child_die = sibling_die (child_die);
16047         }
16048
16049       /* Attach template arguments to type.  */
16050       if (!template_args.empty ())
16051         {
16052           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16053           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16054           TYPE_TEMPLATE_ARGUMENTS (type)
16055             = XOBNEWVEC (&objfile->objfile_obstack,
16056                          struct symbol *,
16057                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16058           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16059                   template_args.data (),
16060                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16061                    * sizeof (struct symbol *)));
16062         }
16063
16064       /* Attach fields and member functions to the type.  */
16065       if (fi.nfields)
16066         dwarf2_attach_fields_to_type (&fi, type, cu);
16067       if (fi.nfnfields)
16068         {
16069           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16070
16071           /* Get the type which refers to the base class (possibly this
16072              class itself) which contains the vtable pointer for the current
16073              class from the DW_AT_containing_type attribute.  This use of
16074              DW_AT_containing_type is a GNU extension.  */
16075
16076           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16077             {
16078               struct type *t = die_containing_type (die, cu);
16079
16080               set_type_vptr_basetype (type, t);
16081               if (type == t)
16082                 {
16083                   int i;
16084
16085                   /* Our own class provides vtbl ptr.  */
16086                   for (i = TYPE_NFIELDS (t) - 1;
16087                        i >= TYPE_N_BASECLASSES (t);
16088                        --i)
16089                     {
16090                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16091
16092                       if (is_vtable_name (fieldname, cu))
16093                         {
16094                           set_type_vptr_fieldno (type, i);
16095                           break;
16096                         }
16097                     }
16098
16099                   /* Complain if virtual function table field not found.  */
16100                   if (i < TYPE_N_BASECLASSES (t))
16101                     complaint (&symfile_complaints,
16102                                _("virtual function table pointer "
16103                                  "not found when defining class '%s'"),
16104                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16105                                "");
16106                 }
16107               else
16108                 {
16109                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16110                 }
16111             }
16112           else if (cu->producer
16113                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16114             {
16115               /* The IBM XLC compiler does not provide direct indication
16116                  of the containing type, but the vtable pointer is
16117                  always named __vfp.  */
16118
16119               int i;
16120
16121               for (i = TYPE_NFIELDS (type) - 1;
16122                    i >= TYPE_N_BASECLASSES (type);
16123                    --i)
16124                 {
16125                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16126                     {
16127                       set_type_vptr_fieldno (type, i);
16128                       set_type_vptr_basetype (type, type);
16129                       break;
16130                     }
16131                 }
16132             }
16133         }
16134
16135       /* Copy fi.typedef_field_list linked list elements content into the
16136          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16137       if (fi.typedef_field_list)
16138         {
16139           int i = fi.typedef_field_list_count;
16140
16141           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16142           TYPE_TYPEDEF_FIELD_ARRAY (type)
16143             = ((struct decl_field *)
16144                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16145           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16146
16147           /* Reverse the list order to keep the debug info elements order.  */
16148           while (--i >= 0)
16149             {
16150               struct decl_field *dest, *src;
16151
16152               dest = &TYPE_TYPEDEF_FIELD (type, i);
16153               src = &fi.typedef_field_list->field;
16154               fi.typedef_field_list = fi.typedef_field_list->next;
16155               *dest = *src;
16156             }
16157         }
16158
16159       /* Copy fi.nested_types_list linked list elements content into the
16160          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16161       if (fi.nested_types_list != NULL && cu->language != language_ada)
16162         {
16163           int i = fi.nested_types_list_count;
16164
16165           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16166           TYPE_NESTED_TYPES_ARRAY (type)
16167             = ((struct decl_field *)
16168                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16169           TYPE_NESTED_TYPES_COUNT (type) = i;
16170
16171           /* Reverse the list order to keep the debug info elements order.  */
16172           while (--i >= 0)
16173             {
16174               struct decl_field *dest, *src;
16175
16176               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16177               src = &fi.nested_types_list->field;
16178               fi.nested_types_list = fi.nested_types_list->next;
16179               *dest = *src;
16180             }
16181         }
16182
16183       do_cleanups (back_to);
16184     }
16185
16186   quirk_gcc_member_function_pointer (type, objfile);
16187
16188   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16189      snapshots) has been known to create a die giving a declaration
16190      for a class that has, as a child, a die giving a definition for a
16191      nested class.  So we have to process our children even if the
16192      current die is a declaration.  Normally, of course, a declaration
16193      won't have any children at all.  */
16194
16195   child_die = die->child;
16196
16197   while (child_die != NULL && child_die->tag)
16198     {
16199       if (child_die->tag == DW_TAG_member
16200           || child_die->tag == DW_TAG_variable
16201           || child_die->tag == DW_TAG_inheritance
16202           || child_die->tag == DW_TAG_template_value_param
16203           || child_die->tag == DW_TAG_template_type_param)
16204         {
16205           /* Do nothing.  */
16206         }
16207       else
16208         process_die (child_die, cu);
16209
16210       child_die = sibling_die (child_die);
16211     }
16212
16213   /* Do not consider external references.  According to the DWARF standard,
16214      these DIEs are identified by the fact that they have no byte_size
16215      attribute, and a declaration attribute.  */
16216   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16217       || !die_is_declaration (die, cu))
16218     new_symbol (die, type, cu);
16219 }
16220
16221 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16222    update TYPE using some information only available in DIE's children.  */
16223
16224 static void
16225 update_enumeration_type_from_children (struct die_info *die,
16226                                        struct type *type,
16227                                        struct dwarf2_cu *cu)
16228 {
16229   struct die_info *child_die;
16230   int unsigned_enum = 1;
16231   int flag_enum = 1;
16232   ULONGEST mask = 0;
16233
16234   auto_obstack obstack;
16235
16236   for (child_die = die->child;
16237        child_die != NULL && child_die->tag;
16238        child_die = sibling_die (child_die))
16239     {
16240       struct attribute *attr;
16241       LONGEST value;
16242       const gdb_byte *bytes;
16243       struct dwarf2_locexpr_baton *baton;
16244       const char *name;
16245
16246       if (child_die->tag != DW_TAG_enumerator)
16247         continue;
16248
16249       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16250       if (attr == NULL)
16251         continue;
16252
16253       name = dwarf2_name (child_die, cu);
16254       if (name == NULL)
16255         name = "<anonymous enumerator>";
16256
16257       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16258                                &value, &bytes, &baton);
16259       if (value < 0)
16260         {
16261           unsigned_enum = 0;
16262           flag_enum = 0;
16263         }
16264       else if ((mask & value) != 0)
16265         flag_enum = 0;
16266       else
16267         mask |= value;
16268
16269       /* If we already know that the enum type is neither unsigned, nor
16270          a flag type, no need to look at the rest of the enumerates.  */
16271       if (!unsigned_enum && !flag_enum)
16272         break;
16273     }
16274
16275   if (unsigned_enum)
16276     TYPE_UNSIGNED (type) = 1;
16277   if (flag_enum)
16278     TYPE_FLAG_ENUM (type) = 1;
16279 }
16280
16281 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16282    complete the type's fields yet, or create any symbols.  */
16283
16284 static struct type *
16285 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16286 {
16287   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16288   struct type *type;
16289   struct attribute *attr;
16290   const char *name;
16291
16292   /* If the definition of this type lives in .debug_types, read that type.
16293      Don't follow DW_AT_specification though, that will take us back up
16294      the chain and we want to go down.  */
16295   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16296   if (attr)
16297     {
16298       type = get_DW_AT_signature_type (die, attr, cu);
16299
16300       /* The type's CU may not be the same as CU.
16301          Ensure TYPE is recorded with CU in die_type_hash.  */
16302       return set_die_type (die, type, cu);
16303     }
16304
16305   type = alloc_type (objfile);
16306
16307   TYPE_CODE (type) = TYPE_CODE_ENUM;
16308   name = dwarf2_full_name (NULL, die, cu);
16309   if (name != NULL)
16310     TYPE_TAG_NAME (type) = name;
16311
16312   attr = dwarf2_attr (die, DW_AT_type, cu);
16313   if (attr != NULL)
16314     {
16315       struct type *underlying_type = die_type (die, cu);
16316
16317       TYPE_TARGET_TYPE (type) = underlying_type;
16318     }
16319
16320   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16321   if (attr)
16322     {
16323       TYPE_LENGTH (type) = DW_UNSND (attr);
16324     }
16325   else
16326     {
16327       TYPE_LENGTH (type) = 0;
16328     }
16329
16330   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16331      declared as private in the package spec, and then defined only
16332      inside the package body.  Such types are known as Taft Amendment
16333      Types.  When another package uses such a type, an incomplete DIE
16334      may be generated by the compiler.  */
16335   if (die_is_declaration (die, cu))
16336     TYPE_STUB (type) = 1;
16337
16338   /* Finish the creation of this type by using the enum's children.
16339      We must call this even when the underlying type has been provided
16340      so that we can determine if we're looking at a "flag" enum.  */
16341   update_enumeration_type_from_children (die, type, cu);
16342
16343   /* If this type has an underlying type that is not a stub, then we
16344      may use its attributes.  We always use the "unsigned" attribute
16345      in this situation, because ordinarily we guess whether the type
16346      is unsigned -- but the guess can be wrong and the underlying type
16347      can tell us the reality.  However, we defer to a local size
16348      attribute if one exists, because this lets the compiler override
16349      the underlying type if needed.  */
16350   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16351     {
16352       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16353       if (TYPE_LENGTH (type) == 0)
16354         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16355     }
16356
16357   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16358
16359   return set_die_type (die, type, cu);
16360 }
16361
16362 /* Given a pointer to a die which begins an enumeration, process all
16363    the dies that define the members of the enumeration, and create the
16364    symbol for the enumeration type.
16365
16366    NOTE: We reverse the order of the element list.  */
16367
16368 static void
16369 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16370 {
16371   struct type *this_type;
16372
16373   this_type = get_die_type (die, cu);
16374   if (this_type == NULL)
16375     this_type = read_enumeration_type (die, cu);
16376
16377   if (die->child != NULL)
16378     {
16379       struct die_info *child_die;
16380       struct symbol *sym;
16381       struct field *fields = NULL;
16382       int num_fields = 0;
16383       const char *name;
16384
16385       child_die = die->child;
16386       while (child_die && child_die->tag)
16387         {
16388           if (child_die->tag != DW_TAG_enumerator)
16389             {
16390               process_die (child_die, cu);
16391             }
16392           else
16393             {
16394               name = dwarf2_name (child_die, cu);
16395               if (name)
16396                 {
16397                   sym = new_symbol (child_die, this_type, cu);
16398
16399                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16400                     {
16401                       fields = (struct field *)
16402                         xrealloc (fields,
16403                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16404                                   * sizeof (struct field));
16405                     }
16406
16407                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16408                   FIELD_TYPE (fields[num_fields]) = NULL;
16409                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16410                   FIELD_BITSIZE (fields[num_fields]) = 0;
16411
16412                   num_fields++;
16413                 }
16414             }
16415
16416           child_die = sibling_die (child_die);
16417         }
16418
16419       if (num_fields)
16420         {
16421           TYPE_NFIELDS (this_type) = num_fields;
16422           TYPE_FIELDS (this_type) = (struct field *)
16423             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16424           memcpy (TYPE_FIELDS (this_type), fields,
16425                   sizeof (struct field) * num_fields);
16426           xfree (fields);
16427         }
16428     }
16429
16430   /* If we are reading an enum from a .debug_types unit, and the enum
16431      is a declaration, and the enum is not the signatured type in the
16432      unit, then we do not want to add a symbol for it.  Adding a
16433      symbol would in some cases obscure the true definition of the
16434      enum, giving users an incomplete type when the definition is
16435      actually available.  Note that we do not want to do this for all
16436      enums which are just declarations, because C++0x allows forward
16437      enum declarations.  */
16438   if (cu->per_cu->is_debug_types
16439       && die_is_declaration (die, cu))
16440     {
16441       struct signatured_type *sig_type;
16442
16443       sig_type = (struct signatured_type *) cu->per_cu;
16444       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16445       if (sig_type->type_offset_in_section != die->sect_off)
16446         return;
16447     }
16448
16449   new_symbol (die, this_type, cu);
16450 }
16451
16452 /* Extract all information from a DW_TAG_array_type DIE and put it in
16453    the DIE's type field.  For now, this only handles one dimensional
16454    arrays.  */
16455
16456 static struct type *
16457 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16458 {
16459   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16460   struct die_info *child_die;
16461   struct type *type;
16462   struct type *element_type, *range_type, *index_type;
16463   struct attribute *attr;
16464   const char *name;
16465   struct dynamic_prop *byte_stride_prop = NULL;
16466   unsigned int bit_stride = 0;
16467
16468   element_type = die_type (die, cu);
16469
16470   /* The die_type call above may have already set the type for this DIE.  */
16471   type = get_die_type (die, cu);
16472   if (type)
16473     return type;
16474
16475   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16476   if (attr != NULL)
16477     {
16478       int stride_ok;
16479
16480       byte_stride_prop
16481         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16482       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16483       if (!stride_ok)
16484         {
16485           complaint (&symfile_complaints,
16486                      _("unable to read array DW_AT_byte_stride "
16487                        " - DIE at %s [in module %s]"),
16488                      sect_offset_str (die->sect_off),
16489                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16490           /* Ignore this attribute.  We will likely not be able to print
16491              arrays of this type correctly, but there is little we can do
16492              to help if we cannot read the attribute's value.  */
16493           byte_stride_prop = NULL;
16494         }
16495     }
16496
16497   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16498   if (attr != NULL)
16499     bit_stride = DW_UNSND (attr);
16500
16501   /* Irix 6.2 native cc creates array types without children for
16502      arrays with unspecified length.  */
16503   if (die->child == NULL)
16504     {
16505       index_type = objfile_type (objfile)->builtin_int;
16506       range_type = create_static_range_type (NULL, index_type, 0, -1);
16507       type = create_array_type_with_stride (NULL, element_type, range_type,
16508                                             byte_stride_prop, bit_stride);
16509       return set_die_type (die, type, cu);
16510     }
16511
16512   std::vector<struct type *> range_types;
16513   child_die = die->child;
16514   while (child_die && child_die->tag)
16515     {
16516       if (child_die->tag == DW_TAG_subrange_type)
16517         {
16518           struct type *child_type = read_type_die (child_die, cu);
16519
16520           if (child_type != NULL)
16521             {
16522               /* The range type was succesfully read.  Save it for the
16523                  array type creation.  */
16524               range_types.push_back (child_type);
16525             }
16526         }
16527       child_die = sibling_die (child_die);
16528     }
16529
16530   /* Dwarf2 dimensions are output from left to right, create the
16531      necessary array types in backwards order.  */
16532
16533   type = element_type;
16534
16535   if (read_array_order (die, cu) == DW_ORD_col_major)
16536     {
16537       int i = 0;
16538
16539       while (i < range_types.size ())
16540         type = create_array_type_with_stride (NULL, type, range_types[i++],
16541                                               byte_stride_prop, bit_stride);
16542     }
16543   else
16544     {
16545       size_t ndim = range_types.size ();
16546       while (ndim-- > 0)
16547         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16548                                               byte_stride_prop, bit_stride);
16549     }
16550
16551   /* Understand Dwarf2 support for vector types (like they occur on
16552      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16553      array type.  This is not part of the Dwarf2/3 standard yet, but a
16554      custom vendor extension.  The main difference between a regular
16555      array and the vector variant is that vectors are passed by value
16556      to functions.  */
16557   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16558   if (attr)
16559     make_vector_type (type);
16560
16561   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16562      implementation may choose to implement triple vectors using this
16563      attribute.  */
16564   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16565   if (attr)
16566     {
16567       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16568         TYPE_LENGTH (type) = DW_UNSND (attr);
16569       else
16570         complaint (&symfile_complaints,
16571                    _("DW_AT_byte_size for array type smaller "
16572                      "than the total size of elements"));
16573     }
16574
16575   name = dwarf2_name (die, cu);
16576   if (name)
16577     TYPE_NAME (type) = name;
16578
16579   /* Install the type in the die.  */
16580   set_die_type (die, type, cu);
16581
16582   /* set_die_type should be already done.  */
16583   set_descriptive_type (type, die, cu);
16584
16585   return type;
16586 }
16587
16588 static enum dwarf_array_dim_ordering
16589 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16590 {
16591   struct attribute *attr;
16592
16593   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16594
16595   if (attr)
16596     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16597
16598   /* GNU F77 is a special case, as at 08/2004 array type info is the
16599      opposite order to the dwarf2 specification, but data is still
16600      laid out as per normal fortran.
16601
16602      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16603      version checking.  */
16604
16605   if (cu->language == language_fortran
16606       && cu->producer && strstr (cu->producer, "GNU F77"))
16607     {
16608       return DW_ORD_row_major;
16609     }
16610
16611   switch (cu->language_defn->la_array_ordering)
16612     {
16613     case array_column_major:
16614       return DW_ORD_col_major;
16615     case array_row_major:
16616     default:
16617       return DW_ORD_row_major;
16618     };
16619 }
16620
16621 /* Extract all information from a DW_TAG_set_type DIE and put it in
16622    the DIE's type field.  */
16623
16624 static struct type *
16625 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16626 {
16627   struct type *domain_type, *set_type;
16628   struct attribute *attr;
16629
16630   domain_type = die_type (die, cu);
16631
16632   /* The die_type call above may have already set the type for this DIE.  */
16633   set_type = get_die_type (die, cu);
16634   if (set_type)
16635     return set_type;
16636
16637   set_type = create_set_type (NULL, domain_type);
16638
16639   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16640   if (attr)
16641     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16642
16643   return set_die_type (die, set_type, cu);
16644 }
16645
16646 /* A helper for read_common_block that creates a locexpr baton.
16647    SYM is the symbol which we are marking as computed.
16648    COMMON_DIE is the DIE for the common block.
16649    COMMON_LOC is the location expression attribute for the common
16650    block itself.
16651    MEMBER_LOC is the location expression attribute for the particular
16652    member of the common block that we are processing.
16653    CU is the CU from which the above come.  */
16654
16655 static void
16656 mark_common_block_symbol_computed (struct symbol *sym,
16657                                    struct die_info *common_die,
16658                                    struct attribute *common_loc,
16659                                    struct attribute *member_loc,
16660                                    struct dwarf2_cu *cu)
16661 {
16662   struct dwarf2_per_objfile *dwarf2_per_objfile
16663     = cu->per_cu->dwarf2_per_objfile;
16664   struct objfile *objfile = dwarf2_per_objfile->objfile;
16665   struct dwarf2_locexpr_baton *baton;
16666   gdb_byte *ptr;
16667   unsigned int cu_off;
16668   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16669   LONGEST offset = 0;
16670
16671   gdb_assert (common_loc && member_loc);
16672   gdb_assert (attr_form_is_block (common_loc));
16673   gdb_assert (attr_form_is_block (member_loc)
16674               || attr_form_is_constant (member_loc));
16675
16676   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16677   baton->per_cu = cu->per_cu;
16678   gdb_assert (baton->per_cu);
16679
16680   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16681
16682   if (attr_form_is_constant (member_loc))
16683     {
16684       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16685       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16686     }
16687   else
16688     baton->size += DW_BLOCK (member_loc)->size;
16689
16690   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16691   baton->data = ptr;
16692
16693   *ptr++ = DW_OP_call4;
16694   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16695   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16696   ptr += 4;
16697
16698   if (attr_form_is_constant (member_loc))
16699     {
16700       *ptr++ = DW_OP_addr;
16701       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16702       ptr += cu->header.addr_size;
16703     }
16704   else
16705     {
16706       /* We have to copy the data here, because DW_OP_call4 will only
16707          use a DW_AT_location attribute.  */
16708       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16709       ptr += DW_BLOCK (member_loc)->size;
16710     }
16711
16712   *ptr++ = DW_OP_plus;
16713   gdb_assert (ptr - baton->data == baton->size);
16714
16715   SYMBOL_LOCATION_BATON (sym) = baton;
16716   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16717 }
16718
16719 /* Create appropriate locally-scoped variables for all the
16720    DW_TAG_common_block entries.  Also create a struct common_block
16721    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16722    is used to sepate the common blocks name namespace from regular
16723    variable names.  */
16724
16725 static void
16726 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16727 {
16728   struct attribute *attr;
16729
16730   attr = dwarf2_attr (die, DW_AT_location, cu);
16731   if (attr)
16732     {
16733       /* Support the .debug_loc offsets.  */
16734       if (attr_form_is_block (attr))
16735         {
16736           /* Ok.  */
16737         }
16738       else if (attr_form_is_section_offset (attr))
16739         {
16740           dwarf2_complex_location_expr_complaint ();
16741           attr = NULL;
16742         }
16743       else
16744         {
16745           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16746                                                  "common block member");
16747           attr = NULL;
16748         }
16749     }
16750
16751   if (die->child != NULL)
16752     {
16753       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16754       struct die_info *child_die;
16755       size_t n_entries = 0, size;
16756       struct common_block *common_block;
16757       struct symbol *sym;
16758
16759       for (child_die = die->child;
16760            child_die && child_die->tag;
16761            child_die = sibling_die (child_die))
16762         ++n_entries;
16763
16764       size = (sizeof (struct common_block)
16765               + (n_entries - 1) * sizeof (struct symbol *));
16766       common_block
16767         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16768                                                  size);
16769       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16770       common_block->n_entries = 0;
16771
16772       for (child_die = die->child;
16773            child_die && child_die->tag;
16774            child_die = sibling_die (child_die))
16775         {
16776           /* Create the symbol in the DW_TAG_common_block block in the current
16777              symbol scope.  */
16778           sym = new_symbol (child_die, NULL, cu);
16779           if (sym != NULL)
16780             {
16781               struct attribute *member_loc;
16782
16783               common_block->contents[common_block->n_entries++] = sym;
16784
16785               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16786                                         cu);
16787               if (member_loc)
16788                 {
16789                   /* GDB has handled this for a long time, but it is
16790                      not specified by DWARF.  It seems to have been
16791                      emitted by gfortran at least as recently as:
16792                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16793                   complaint (&symfile_complaints,
16794                              _("Variable in common block has "
16795                                "DW_AT_data_member_location "
16796                                "- DIE at %s [in module %s]"),
16797                                sect_offset_str (child_die->sect_off),
16798                              objfile_name (objfile));
16799
16800                   if (attr_form_is_section_offset (member_loc))
16801                     dwarf2_complex_location_expr_complaint ();
16802                   else if (attr_form_is_constant (member_loc)
16803                            || attr_form_is_block (member_loc))
16804                     {
16805                       if (attr)
16806                         mark_common_block_symbol_computed (sym, die, attr,
16807                                                            member_loc, cu);
16808                     }
16809                   else
16810                     dwarf2_complex_location_expr_complaint ();
16811                 }
16812             }
16813         }
16814
16815       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16816       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16817     }
16818 }
16819
16820 /* Create a type for a C++ namespace.  */
16821
16822 static struct type *
16823 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16824 {
16825   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16826   const char *previous_prefix, *name;
16827   int is_anonymous;
16828   struct type *type;
16829
16830   /* For extensions, reuse the type of the original namespace.  */
16831   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16832     {
16833       struct die_info *ext_die;
16834       struct dwarf2_cu *ext_cu = cu;
16835
16836       ext_die = dwarf2_extension (die, &ext_cu);
16837       type = read_type_die (ext_die, ext_cu);
16838
16839       /* EXT_CU may not be the same as CU.
16840          Ensure TYPE is recorded with CU in die_type_hash.  */
16841       return set_die_type (die, type, cu);
16842     }
16843
16844   name = namespace_name (die, &is_anonymous, cu);
16845
16846   /* Now build the name of the current namespace.  */
16847
16848   previous_prefix = determine_prefix (die, cu);
16849   if (previous_prefix[0] != '\0')
16850     name = typename_concat (&objfile->objfile_obstack,
16851                             previous_prefix, name, 0, cu);
16852
16853   /* Create the type.  */
16854   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16855   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16856
16857   return set_die_type (die, type, cu);
16858 }
16859
16860 /* Read a namespace scope.  */
16861
16862 static void
16863 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16864 {
16865   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16866   int is_anonymous;
16867
16868   /* Add a symbol associated to this if we haven't seen the namespace
16869      before.  Also, add a using directive if it's an anonymous
16870      namespace.  */
16871
16872   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16873     {
16874       struct type *type;
16875
16876       type = read_type_die (die, cu);
16877       new_symbol (die, type, cu);
16878
16879       namespace_name (die, &is_anonymous, cu);
16880       if (is_anonymous)
16881         {
16882           const char *previous_prefix = determine_prefix (die, cu);
16883
16884           std::vector<const char *> excludes;
16885           add_using_directive (using_directives (cu->language),
16886                                previous_prefix, TYPE_NAME (type), NULL,
16887                                NULL, excludes, 0, &objfile->objfile_obstack);
16888         }
16889     }
16890
16891   if (die->child != NULL)
16892     {
16893       struct die_info *child_die = die->child;
16894
16895       while (child_die && child_die->tag)
16896         {
16897           process_die (child_die, cu);
16898           child_die = sibling_die (child_die);
16899         }
16900     }
16901 }
16902
16903 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16904    imported module.  Still we need that type as local Fortran "use ... only"
16905    declaration imports depend on the created type in determine_prefix.  */
16906
16907 static struct type *
16908 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16909 {
16910   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16911   const char *module_name;
16912   struct type *type;
16913
16914   module_name = dwarf2_name (die, cu);
16915   if (!module_name)
16916     complaint (&symfile_complaints,
16917                _("DW_TAG_module has no name, offset %s"),
16918                sect_offset_str (die->sect_off));
16919   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16920
16921   /* determine_prefix uses TYPE_TAG_NAME.  */
16922   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16923
16924   return set_die_type (die, type, cu);
16925 }
16926
16927 /* Read a Fortran module.  */
16928
16929 static void
16930 read_module (struct die_info *die, struct dwarf2_cu *cu)
16931 {
16932   struct die_info *child_die = die->child;
16933   struct type *type;
16934
16935   type = read_type_die (die, cu);
16936   new_symbol (die, type, cu);
16937
16938   while (child_die && child_die->tag)
16939     {
16940       process_die (child_die, cu);
16941       child_die = sibling_die (child_die);
16942     }
16943 }
16944
16945 /* Return the name of the namespace represented by DIE.  Set
16946    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16947    namespace.  */
16948
16949 static const char *
16950 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16951 {
16952   struct die_info *current_die;
16953   const char *name = NULL;
16954
16955   /* Loop through the extensions until we find a name.  */
16956
16957   for (current_die = die;
16958        current_die != NULL;
16959        current_die = dwarf2_extension (die, &cu))
16960     {
16961       /* We don't use dwarf2_name here so that we can detect the absence
16962          of a name -> anonymous namespace.  */
16963       name = dwarf2_string_attr (die, DW_AT_name, cu);
16964
16965       if (name != NULL)
16966         break;
16967     }
16968
16969   /* Is it an anonymous namespace?  */
16970
16971   *is_anonymous = (name == NULL);
16972   if (*is_anonymous)
16973     name = CP_ANONYMOUS_NAMESPACE_STR;
16974
16975   return name;
16976 }
16977
16978 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16979    the user defined type vector.  */
16980
16981 static struct type *
16982 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16983 {
16984   struct gdbarch *gdbarch
16985     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16986   struct comp_unit_head *cu_header = &cu->header;
16987   struct type *type;
16988   struct attribute *attr_byte_size;
16989   struct attribute *attr_address_class;
16990   int byte_size, addr_class;
16991   struct type *target_type;
16992
16993   target_type = die_type (die, cu);
16994
16995   /* The die_type call above may have already set the type for this DIE.  */
16996   type = get_die_type (die, cu);
16997   if (type)
16998     return type;
16999
17000   type = lookup_pointer_type (target_type);
17001
17002   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17003   if (attr_byte_size)
17004     byte_size = DW_UNSND (attr_byte_size);
17005   else
17006     byte_size = cu_header->addr_size;
17007
17008   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17009   if (attr_address_class)
17010     addr_class = DW_UNSND (attr_address_class);
17011   else
17012     addr_class = DW_ADDR_none;
17013
17014   /* If the pointer size or address class is different than the
17015      default, create a type variant marked as such and set the
17016      length accordingly.  */
17017   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
17018     {
17019       if (gdbarch_address_class_type_flags_p (gdbarch))
17020         {
17021           int type_flags;
17022
17023           type_flags = gdbarch_address_class_type_flags
17024                          (gdbarch, byte_size, addr_class);
17025           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17026                       == 0);
17027           type = make_type_with_address_space (type, type_flags);
17028         }
17029       else if (TYPE_LENGTH (type) != byte_size)
17030         {
17031           complaint (&symfile_complaints,
17032                      _("invalid pointer size %d"), byte_size);
17033         }
17034       else
17035         {
17036           /* Should we also complain about unhandled address classes?  */
17037         }
17038     }
17039
17040   TYPE_LENGTH (type) = byte_size;
17041   return set_die_type (die, type, cu);
17042 }
17043
17044 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17045    the user defined type vector.  */
17046
17047 static struct type *
17048 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17049 {
17050   struct type *type;
17051   struct type *to_type;
17052   struct type *domain;
17053
17054   to_type = die_type (die, cu);
17055   domain = die_containing_type (die, cu);
17056
17057   /* The calls above may have already set the type for this DIE.  */
17058   type = get_die_type (die, cu);
17059   if (type)
17060     return type;
17061
17062   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17063     type = lookup_methodptr_type (to_type);
17064   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17065     {
17066       struct type *new_type
17067         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17068
17069       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17070                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17071                             TYPE_VARARGS (to_type));
17072       type = lookup_methodptr_type (new_type);
17073     }
17074   else
17075     type = lookup_memberptr_type (to_type, domain);
17076
17077   return set_die_type (die, type, cu);
17078 }
17079
17080 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17081    the user defined type vector.  */
17082
17083 static struct type *
17084 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17085                           enum type_code refcode)
17086 {
17087   struct comp_unit_head *cu_header = &cu->header;
17088   struct type *type, *target_type;
17089   struct attribute *attr;
17090
17091   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17092
17093   target_type = die_type (die, cu);
17094
17095   /* The die_type call above may have already set the type for this DIE.  */
17096   type = get_die_type (die, cu);
17097   if (type)
17098     return type;
17099
17100   type = lookup_reference_type (target_type, refcode);
17101   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17102   if (attr)
17103     {
17104       TYPE_LENGTH (type) = DW_UNSND (attr);
17105     }
17106   else
17107     {
17108       TYPE_LENGTH (type) = cu_header->addr_size;
17109     }
17110   return set_die_type (die, type, cu);
17111 }
17112
17113 /* Add the given cv-qualifiers to the element type of the array.  GCC
17114    outputs DWARF type qualifiers that apply to an array, not the
17115    element type.  But GDB relies on the array element type to carry
17116    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17117    specification.  */
17118
17119 static struct type *
17120 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17121                    struct type *base_type, int cnst, int voltl)
17122 {
17123   struct type *el_type, *inner_array;
17124
17125   base_type = copy_type (base_type);
17126   inner_array = base_type;
17127
17128   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17129     {
17130       TYPE_TARGET_TYPE (inner_array) =
17131         copy_type (TYPE_TARGET_TYPE (inner_array));
17132       inner_array = TYPE_TARGET_TYPE (inner_array);
17133     }
17134
17135   el_type = TYPE_TARGET_TYPE (inner_array);
17136   cnst |= TYPE_CONST (el_type);
17137   voltl |= TYPE_VOLATILE (el_type);
17138   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17139
17140   return set_die_type (die, base_type, cu);
17141 }
17142
17143 static struct type *
17144 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17145 {
17146   struct type *base_type, *cv_type;
17147
17148   base_type = die_type (die, cu);
17149
17150   /* The die_type call above may have already set the type for this DIE.  */
17151   cv_type = get_die_type (die, cu);
17152   if (cv_type)
17153     return cv_type;
17154
17155   /* In case the const qualifier is applied to an array type, the element type
17156      is so qualified, not the array type (section 6.7.3 of C99).  */
17157   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17158     return add_array_cv_type (die, cu, base_type, 1, 0);
17159
17160   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17161   return set_die_type (die, cv_type, cu);
17162 }
17163
17164 static struct type *
17165 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17166 {
17167   struct type *base_type, *cv_type;
17168
17169   base_type = die_type (die, cu);
17170
17171   /* The die_type call above may have already set the type for this DIE.  */
17172   cv_type = get_die_type (die, cu);
17173   if (cv_type)
17174     return cv_type;
17175
17176   /* In case the volatile qualifier is applied to an array type, the
17177      element type is so qualified, not the array type (section 6.7.3
17178      of C99).  */
17179   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17180     return add_array_cv_type (die, cu, base_type, 0, 1);
17181
17182   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17183   return set_die_type (die, cv_type, cu);
17184 }
17185
17186 /* Handle DW_TAG_restrict_type.  */
17187
17188 static struct type *
17189 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17190 {
17191   struct type *base_type, *cv_type;
17192
17193   base_type = die_type (die, cu);
17194
17195   /* The die_type call above may have already set the type for this DIE.  */
17196   cv_type = get_die_type (die, cu);
17197   if (cv_type)
17198     return cv_type;
17199
17200   cv_type = make_restrict_type (base_type);
17201   return set_die_type (die, cv_type, cu);
17202 }
17203
17204 /* Handle DW_TAG_atomic_type.  */
17205
17206 static struct type *
17207 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17208 {
17209   struct type *base_type, *cv_type;
17210
17211   base_type = die_type (die, cu);
17212
17213   /* The die_type call above may have already set the type for this DIE.  */
17214   cv_type = get_die_type (die, cu);
17215   if (cv_type)
17216     return cv_type;
17217
17218   cv_type = make_atomic_type (base_type);
17219   return set_die_type (die, cv_type, cu);
17220 }
17221
17222 /* Extract all information from a DW_TAG_string_type DIE and add to
17223    the user defined type vector.  It isn't really a user defined type,
17224    but it behaves like one, with other DIE's using an AT_user_def_type
17225    attribute to reference it.  */
17226
17227 static struct type *
17228 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17229 {
17230   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17231   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17232   struct type *type, *range_type, *index_type, *char_type;
17233   struct attribute *attr;
17234   unsigned int length;
17235
17236   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17237   if (attr)
17238     {
17239       length = DW_UNSND (attr);
17240     }
17241   else
17242     {
17243       /* Check for the DW_AT_byte_size attribute.  */
17244       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17245       if (attr)
17246         {
17247           length = DW_UNSND (attr);
17248         }
17249       else
17250         {
17251           length = 1;
17252         }
17253     }
17254
17255   index_type = objfile_type (objfile)->builtin_int;
17256   range_type = create_static_range_type (NULL, index_type, 1, length);
17257   char_type = language_string_char_type (cu->language_defn, gdbarch);
17258   type = create_string_type (NULL, char_type, range_type);
17259
17260   return set_die_type (die, type, cu);
17261 }
17262
17263 /* Assuming that DIE corresponds to a function, returns nonzero
17264    if the function is prototyped.  */
17265
17266 static int
17267 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17268 {
17269   struct attribute *attr;
17270
17271   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17272   if (attr && (DW_UNSND (attr) != 0))
17273     return 1;
17274
17275   /* The DWARF standard implies that the DW_AT_prototyped attribute
17276      is only meaninful for C, but the concept also extends to other
17277      languages that allow unprototyped functions (Eg: Objective C).
17278      For all other languages, assume that functions are always
17279      prototyped.  */
17280   if (cu->language != language_c
17281       && cu->language != language_objc
17282       && cu->language != language_opencl)
17283     return 1;
17284
17285   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17286      prototyped and unprototyped functions; default to prototyped,
17287      since that is more common in modern code (and RealView warns
17288      about unprototyped functions).  */
17289   if (producer_is_realview (cu->producer))
17290     return 1;
17291
17292   return 0;
17293 }
17294
17295 /* Handle DIES due to C code like:
17296
17297    struct foo
17298    {
17299    int (*funcp)(int a, long l);
17300    int b;
17301    };
17302
17303    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17304
17305 static struct type *
17306 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17307 {
17308   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17309   struct type *type;            /* Type that this function returns.  */
17310   struct type *ftype;           /* Function that returns above type.  */
17311   struct attribute *attr;
17312
17313   type = die_type (die, cu);
17314
17315   /* The die_type call above may have already set the type for this DIE.  */
17316   ftype = get_die_type (die, cu);
17317   if (ftype)
17318     return ftype;
17319
17320   ftype = lookup_function_type (type);
17321
17322   if (prototyped_function_p (die, cu))
17323     TYPE_PROTOTYPED (ftype) = 1;
17324
17325   /* Store the calling convention in the type if it's available in
17326      the subroutine die.  Otherwise set the calling convention to
17327      the default value DW_CC_normal.  */
17328   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17329   if (attr)
17330     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17331   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17332     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17333   else
17334     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17335
17336   /* Record whether the function returns normally to its caller or not
17337      if the DWARF producer set that information.  */
17338   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17339   if (attr && (DW_UNSND (attr) != 0))
17340     TYPE_NO_RETURN (ftype) = 1;
17341
17342   /* We need to add the subroutine type to the die immediately so
17343      we don't infinitely recurse when dealing with parameters
17344      declared as the same subroutine type.  */
17345   set_die_type (die, ftype, cu);
17346
17347   if (die->child != NULL)
17348     {
17349       struct type *void_type = objfile_type (objfile)->builtin_void;
17350       struct die_info *child_die;
17351       int nparams, iparams;
17352
17353       /* Count the number of parameters.
17354          FIXME: GDB currently ignores vararg functions, but knows about
17355          vararg member functions.  */
17356       nparams = 0;
17357       child_die = die->child;
17358       while (child_die && child_die->tag)
17359         {
17360           if (child_die->tag == DW_TAG_formal_parameter)
17361             nparams++;
17362           else if (child_die->tag == DW_TAG_unspecified_parameters)
17363             TYPE_VARARGS (ftype) = 1;
17364           child_die = sibling_die (child_die);
17365         }
17366
17367       /* Allocate storage for parameters and fill them in.  */
17368       TYPE_NFIELDS (ftype) = nparams;
17369       TYPE_FIELDS (ftype) = (struct field *)
17370         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17371
17372       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17373          even if we error out during the parameters reading below.  */
17374       for (iparams = 0; iparams < nparams; iparams++)
17375         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17376
17377       iparams = 0;
17378       child_die = die->child;
17379       while (child_die && child_die->tag)
17380         {
17381           if (child_die->tag == DW_TAG_formal_parameter)
17382             {
17383               struct type *arg_type;
17384
17385               /* DWARF version 2 has no clean way to discern C++
17386                  static and non-static member functions.  G++ helps
17387                  GDB by marking the first parameter for non-static
17388                  member functions (which is the this pointer) as
17389                  artificial.  We pass this information to
17390                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17391
17392                  DWARF version 3 added DW_AT_object_pointer, which GCC
17393                  4.5 does not yet generate.  */
17394               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17395               if (attr)
17396                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17397               else
17398                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17399               arg_type = die_type (child_die, cu);
17400
17401               /* RealView does not mark THIS as const, which the testsuite
17402                  expects.  GCC marks THIS as const in method definitions,
17403                  but not in the class specifications (GCC PR 43053).  */
17404               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17405                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17406                 {
17407                   int is_this = 0;
17408                   struct dwarf2_cu *arg_cu = cu;
17409                   const char *name = dwarf2_name (child_die, cu);
17410
17411                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17412                   if (attr)
17413                     {
17414                       /* If the compiler emits this, use it.  */
17415                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17416                         is_this = 1;
17417                     }
17418                   else if (name && strcmp (name, "this") == 0)
17419                     /* Function definitions will have the argument names.  */
17420                     is_this = 1;
17421                   else if (name == NULL && iparams == 0)
17422                     /* Declarations may not have the names, so like
17423                        elsewhere in GDB, assume an artificial first
17424                        argument is "this".  */
17425                     is_this = 1;
17426
17427                   if (is_this)
17428                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17429                                              arg_type, 0);
17430                 }
17431
17432               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17433               iparams++;
17434             }
17435           child_die = sibling_die (child_die);
17436         }
17437     }
17438
17439   return ftype;
17440 }
17441
17442 static struct type *
17443 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17444 {
17445   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17446   const char *name = NULL;
17447   struct type *this_type, *target_type;
17448
17449   name = dwarf2_full_name (NULL, die, cu);
17450   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17451   TYPE_TARGET_STUB (this_type) = 1;
17452   set_die_type (die, this_type, cu);
17453   target_type = die_type (die, cu);
17454   if (target_type != this_type)
17455     TYPE_TARGET_TYPE (this_type) = target_type;
17456   else
17457     {
17458       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17459          spec and cause infinite loops in GDB.  */
17460       complaint (&symfile_complaints,
17461                  _("Self-referential DW_TAG_typedef "
17462                    "- DIE at %s [in module %s]"),
17463                  sect_offset_str (die->sect_off), objfile_name (objfile));
17464       TYPE_TARGET_TYPE (this_type) = NULL;
17465     }
17466   return this_type;
17467 }
17468
17469 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17470    (which may be different from NAME) to the architecture back-end to allow
17471    it to guess the correct format if necessary.  */
17472
17473 static struct type *
17474 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17475                         const char *name_hint)
17476 {
17477   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17478   const struct floatformat **format;
17479   struct type *type;
17480
17481   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17482   if (format)
17483     type = init_float_type (objfile, bits, name, format);
17484   else
17485     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17486
17487   return type;
17488 }
17489
17490 /* Find a representation of a given base type and install
17491    it in the TYPE field of the die.  */
17492
17493 static struct type *
17494 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17495 {
17496   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17497   struct type *type;
17498   struct attribute *attr;
17499   int encoding = 0, bits = 0;
17500   const char *name;
17501
17502   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17503   if (attr)
17504     {
17505       encoding = DW_UNSND (attr);
17506     }
17507   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17508   if (attr)
17509     {
17510       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17511     }
17512   name = dwarf2_name (die, cu);
17513   if (!name)
17514     {
17515       complaint (&symfile_complaints,
17516                  _("DW_AT_name missing from DW_TAG_base_type"));
17517     }
17518
17519   switch (encoding)
17520     {
17521       case DW_ATE_address:
17522         /* Turn DW_ATE_address into a void * pointer.  */
17523         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17524         type = init_pointer_type (objfile, bits, name, type);
17525         break;
17526       case DW_ATE_boolean:
17527         type = init_boolean_type (objfile, bits, 1, name);
17528         break;
17529       case DW_ATE_complex_float:
17530         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17531         type = init_complex_type (objfile, name, type);
17532         break;
17533       case DW_ATE_decimal_float:
17534         type = init_decfloat_type (objfile, bits, name);
17535         break;
17536       case DW_ATE_float:
17537         type = dwarf2_init_float_type (objfile, bits, name, name);
17538         break;
17539       case DW_ATE_signed:
17540         type = init_integer_type (objfile, bits, 0, name);
17541         break;
17542       case DW_ATE_unsigned:
17543         if (cu->language == language_fortran
17544             && name
17545             && startswith (name, "character("))
17546           type = init_character_type (objfile, bits, 1, name);
17547         else
17548           type = init_integer_type (objfile, bits, 1, name);
17549         break;
17550       case DW_ATE_signed_char:
17551         if (cu->language == language_ada || cu->language == language_m2
17552             || cu->language == language_pascal
17553             || cu->language == language_fortran)
17554           type = init_character_type (objfile, bits, 0, name);
17555         else
17556           type = init_integer_type (objfile, bits, 0, name);
17557         break;
17558       case DW_ATE_unsigned_char:
17559         if (cu->language == language_ada || cu->language == language_m2
17560             || cu->language == language_pascal
17561             || cu->language == language_fortran
17562             || cu->language == language_rust)
17563           type = init_character_type (objfile, bits, 1, name);
17564         else
17565           type = init_integer_type (objfile, bits, 1, name);
17566         break;
17567       case DW_ATE_UTF:
17568         {
17569           gdbarch *arch = get_objfile_arch (objfile);
17570
17571           if (bits == 16)
17572             type = builtin_type (arch)->builtin_char16;
17573           else if (bits == 32)
17574             type = builtin_type (arch)->builtin_char32;
17575           else
17576             {
17577               complaint (&symfile_complaints,
17578                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17579                          bits);
17580               type = init_integer_type (objfile, bits, 1, name);
17581             }
17582           return set_die_type (die, type, cu);
17583         }
17584         break;
17585
17586       default:
17587         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17588                    dwarf_type_encoding_name (encoding));
17589         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17590         break;
17591     }
17592
17593   if (name && strcmp (name, "char") == 0)
17594     TYPE_NOSIGN (type) = 1;
17595
17596   return set_die_type (die, type, cu);
17597 }
17598
17599 /* Parse dwarf attribute if it's a block, reference or constant and put the
17600    resulting value of the attribute into struct bound_prop.
17601    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17602
17603 static int
17604 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17605                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17606 {
17607   struct dwarf2_property_baton *baton;
17608   struct obstack *obstack
17609     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17610
17611   if (attr == NULL || prop == NULL)
17612     return 0;
17613
17614   if (attr_form_is_block (attr))
17615     {
17616       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17617       baton->referenced_type = NULL;
17618       baton->locexpr.per_cu = cu->per_cu;
17619       baton->locexpr.size = DW_BLOCK (attr)->size;
17620       baton->locexpr.data = DW_BLOCK (attr)->data;
17621       prop->data.baton = baton;
17622       prop->kind = PROP_LOCEXPR;
17623       gdb_assert (prop->data.baton != NULL);
17624     }
17625   else if (attr_form_is_ref (attr))
17626     {
17627       struct dwarf2_cu *target_cu = cu;
17628       struct die_info *target_die;
17629       struct attribute *target_attr;
17630
17631       target_die = follow_die_ref (die, attr, &target_cu);
17632       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17633       if (target_attr == NULL)
17634         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17635                                    target_cu);
17636       if (target_attr == NULL)
17637         return 0;
17638
17639       switch (target_attr->name)
17640         {
17641           case DW_AT_location:
17642             if (attr_form_is_section_offset (target_attr))
17643               {
17644                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17645                 baton->referenced_type = die_type (target_die, target_cu);
17646                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17647                 prop->data.baton = baton;
17648                 prop->kind = PROP_LOCLIST;
17649                 gdb_assert (prop->data.baton != NULL);
17650               }
17651             else if (attr_form_is_block (target_attr))
17652               {
17653                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17654                 baton->referenced_type = die_type (target_die, target_cu);
17655                 baton->locexpr.per_cu = cu->per_cu;
17656                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17657                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17658                 prop->data.baton = baton;
17659                 prop->kind = PROP_LOCEXPR;
17660                 gdb_assert (prop->data.baton != NULL);
17661               }
17662             else
17663               {
17664                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17665                                                        "dynamic property");
17666                 return 0;
17667               }
17668             break;
17669           case DW_AT_data_member_location:
17670             {
17671               LONGEST offset;
17672
17673               if (!handle_data_member_location (target_die, target_cu,
17674                                                 &offset))
17675                 return 0;
17676
17677               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17678               baton->referenced_type = read_type_die (target_die->parent,
17679                                                       target_cu);
17680               baton->offset_info.offset = offset;
17681               baton->offset_info.type = die_type (target_die, target_cu);
17682               prop->data.baton = baton;
17683               prop->kind = PROP_ADDR_OFFSET;
17684               break;
17685             }
17686         }
17687     }
17688   else if (attr_form_is_constant (attr))
17689     {
17690       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17691       prop->kind = PROP_CONST;
17692     }
17693   else
17694     {
17695       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17696                                              dwarf2_name (die, cu));
17697       return 0;
17698     }
17699
17700   return 1;
17701 }
17702
17703 /* Read the given DW_AT_subrange DIE.  */
17704
17705 static struct type *
17706 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17707 {
17708   struct type *base_type, *orig_base_type;
17709   struct type *range_type;
17710   struct attribute *attr;
17711   struct dynamic_prop low, high;
17712   int low_default_is_valid;
17713   int high_bound_is_count = 0;
17714   const char *name;
17715   LONGEST negative_mask;
17716
17717   orig_base_type = die_type (die, cu);
17718   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17719      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17720      creating the range type, but we use the result of check_typedef
17721      when examining properties of the type.  */
17722   base_type = check_typedef (orig_base_type);
17723
17724   /* The die_type call above may have already set the type for this DIE.  */
17725   range_type = get_die_type (die, cu);
17726   if (range_type)
17727     return range_type;
17728
17729   low.kind = PROP_CONST;
17730   high.kind = PROP_CONST;
17731   high.data.const_val = 0;
17732
17733   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17734      omitting DW_AT_lower_bound.  */
17735   switch (cu->language)
17736     {
17737     case language_c:
17738     case language_cplus:
17739       low.data.const_val = 0;
17740       low_default_is_valid = 1;
17741       break;
17742     case language_fortran:
17743       low.data.const_val = 1;
17744       low_default_is_valid = 1;
17745       break;
17746     case language_d:
17747     case language_objc:
17748     case language_rust:
17749       low.data.const_val = 0;
17750       low_default_is_valid = (cu->header.version >= 4);
17751       break;
17752     case language_ada:
17753     case language_m2:
17754     case language_pascal:
17755       low.data.const_val = 1;
17756       low_default_is_valid = (cu->header.version >= 4);
17757       break;
17758     default:
17759       low.data.const_val = 0;
17760       low_default_is_valid = 0;
17761       break;
17762     }
17763
17764   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17765   if (attr)
17766     attr_to_dynamic_prop (attr, die, cu, &low);
17767   else if (!low_default_is_valid)
17768     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17769                                       "- DIE at %s [in module %s]"),
17770                sect_offset_str (die->sect_off),
17771                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17772
17773   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17774   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17775     {
17776       attr = dwarf2_attr (die, DW_AT_count, cu);
17777       if (attr_to_dynamic_prop (attr, die, cu, &high))
17778         {
17779           /* If bounds are constant do the final calculation here.  */
17780           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17781             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17782           else
17783             high_bound_is_count = 1;
17784         }
17785     }
17786
17787   /* Dwarf-2 specifications explicitly allows to create subrange types
17788      without specifying a base type.
17789      In that case, the base type must be set to the type of
17790      the lower bound, upper bound or count, in that order, if any of these
17791      three attributes references an object that has a type.
17792      If no base type is found, the Dwarf-2 specifications say that
17793      a signed integer type of size equal to the size of an address should
17794      be used.
17795      For the following C code: `extern char gdb_int [];'
17796      GCC produces an empty range DIE.
17797      FIXME: muller/2010-05-28: Possible references to object for low bound,
17798      high bound or count are not yet handled by this code.  */
17799   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17800     {
17801       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17802       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17803       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17804       struct type *int_type = objfile_type (objfile)->builtin_int;
17805
17806       /* Test "int", "long int", and "long long int" objfile types,
17807          and select the first one having a size above or equal to the
17808          architecture address size.  */
17809       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17810         base_type = int_type;
17811       else
17812         {
17813           int_type = objfile_type (objfile)->builtin_long;
17814           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17815             base_type = int_type;
17816           else
17817             {
17818               int_type = objfile_type (objfile)->builtin_long_long;
17819               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17820                 base_type = int_type;
17821             }
17822         }
17823     }
17824
17825   /* Normally, the DWARF producers are expected to use a signed
17826      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17827      But this is unfortunately not always the case, as witnessed
17828      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17829      is used instead.  To work around that ambiguity, we treat
17830      the bounds as signed, and thus sign-extend their values, when
17831      the base type is signed.  */
17832   negative_mask =
17833     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17834   if (low.kind == PROP_CONST
17835       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17836     low.data.const_val |= negative_mask;
17837   if (high.kind == PROP_CONST
17838       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17839     high.data.const_val |= negative_mask;
17840
17841   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17842
17843   if (high_bound_is_count)
17844     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17845
17846   /* Ada expects an empty array on no boundary attributes.  */
17847   if (attr == NULL && cu->language != language_ada)
17848     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17849
17850   name = dwarf2_name (die, cu);
17851   if (name)
17852     TYPE_NAME (range_type) = name;
17853
17854   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17855   if (attr)
17856     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17857
17858   set_die_type (die, range_type, cu);
17859
17860   /* set_die_type should be already done.  */
17861   set_descriptive_type (range_type, die, cu);
17862
17863   return range_type;
17864 }
17865
17866 static struct type *
17867 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17868 {
17869   struct type *type;
17870
17871   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17872                     NULL);
17873   TYPE_NAME (type) = dwarf2_name (die, cu);
17874
17875   /* In Ada, an unspecified type is typically used when the description
17876      of the type is defered to a different unit.  When encountering
17877      such a type, we treat it as a stub, and try to resolve it later on,
17878      when needed.  */
17879   if (cu->language == language_ada)
17880     TYPE_STUB (type) = 1;
17881
17882   return set_die_type (die, type, cu);
17883 }
17884
17885 /* Read a single die and all its descendents.  Set the die's sibling
17886    field to NULL; set other fields in the die correctly, and set all
17887    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17888    location of the info_ptr after reading all of those dies.  PARENT
17889    is the parent of the die in question.  */
17890
17891 static struct die_info *
17892 read_die_and_children (const struct die_reader_specs *reader,
17893                        const gdb_byte *info_ptr,
17894                        const gdb_byte **new_info_ptr,
17895                        struct die_info *parent)
17896 {
17897   struct die_info *die;
17898   const gdb_byte *cur_ptr;
17899   int has_children;
17900
17901   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17902   if (die == NULL)
17903     {
17904       *new_info_ptr = cur_ptr;
17905       return NULL;
17906     }
17907   store_in_ref_table (die, reader->cu);
17908
17909   if (has_children)
17910     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17911   else
17912     {
17913       die->child = NULL;
17914       *new_info_ptr = cur_ptr;
17915     }
17916
17917   die->sibling = NULL;
17918   die->parent = parent;
17919   return die;
17920 }
17921
17922 /* Read a die, all of its descendents, and all of its siblings; set
17923    all of the fields of all of the dies correctly.  Arguments are as
17924    in read_die_and_children.  */
17925
17926 static struct die_info *
17927 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17928                          const gdb_byte *info_ptr,
17929                          const gdb_byte **new_info_ptr,
17930                          struct die_info *parent)
17931 {
17932   struct die_info *first_die, *last_sibling;
17933   const gdb_byte *cur_ptr;
17934
17935   cur_ptr = info_ptr;
17936   first_die = last_sibling = NULL;
17937
17938   while (1)
17939     {
17940       struct die_info *die
17941         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17942
17943       if (die == NULL)
17944         {
17945           *new_info_ptr = cur_ptr;
17946           return first_die;
17947         }
17948
17949       if (!first_die)
17950         first_die = die;
17951       else
17952         last_sibling->sibling = die;
17953
17954       last_sibling = die;
17955     }
17956 }
17957
17958 /* Read a die, all of its descendents, and all of its siblings; set
17959    all of the fields of all of the dies correctly.  Arguments are as
17960    in read_die_and_children.
17961    This the main entry point for reading a DIE and all its children.  */
17962
17963 static struct die_info *
17964 read_die_and_siblings (const struct die_reader_specs *reader,
17965                        const gdb_byte *info_ptr,
17966                        const gdb_byte **new_info_ptr,
17967                        struct die_info *parent)
17968 {
17969   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17970                                                   new_info_ptr, parent);
17971
17972   if (dwarf_die_debug)
17973     {
17974       fprintf_unfiltered (gdb_stdlog,
17975                           "Read die from %s@0x%x of %s:\n",
17976                           get_section_name (reader->die_section),
17977                           (unsigned) (info_ptr - reader->die_section->buffer),
17978                           bfd_get_filename (reader->abfd));
17979       dump_die (die, dwarf_die_debug);
17980     }
17981
17982   return die;
17983 }
17984
17985 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17986    attributes.
17987    The caller is responsible for filling in the extra attributes
17988    and updating (*DIEP)->num_attrs.
17989    Set DIEP to point to a newly allocated die with its information,
17990    except for its child, sibling, and parent fields.
17991    Set HAS_CHILDREN to tell whether the die has children or not.  */
17992
17993 static const gdb_byte *
17994 read_full_die_1 (const struct die_reader_specs *reader,
17995                  struct die_info **diep, const gdb_byte *info_ptr,
17996                  int *has_children, int num_extra_attrs)
17997 {
17998   unsigned int abbrev_number, bytes_read, i;
17999   struct abbrev_info *abbrev;
18000   struct die_info *die;
18001   struct dwarf2_cu *cu = reader->cu;
18002   bfd *abfd = reader->abfd;
18003
18004   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18005   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18006   info_ptr += bytes_read;
18007   if (!abbrev_number)
18008     {
18009       *diep = NULL;
18010       *has_children = 0;
18011       return info_ptr;
18012     }
18013
18014   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18015   if (!abbrev)
18016     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18017            abbrev_number,
18018            bfd_get_filename (abfd));
18019
18020   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18021   die->sect_off = sect_off;
18022   die->tag = abbrev->tag;
18023   die->abbrev = abbrev_number;
18024
18025   /* Make the result usable.
18026      The caller needs to update num_attrs after adding the extra
18027      attributes.  */
18028   die->num_attrs = abbrev->num_attrs;
18029
18030   for (i = 0; i < abbrev->num_attrs; ++i)
18031     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18032                                info_ptr);
18033
18034   *diep = die;
18035   *has_children = abbrev->has_children;
18036   return info_ptr;
18037 }
18038
18039 /* Read a die and all its attributes.
18040    Set DIEP to point to a newly allocated die with its information,
18041    except for its child, sibling, and parent fields.
18042    Set HAS_CHILDREN to tell whether the die has children or not.  */
18043
18044 static const gdb_byte *
18045 read_full_die (const struct die_reader_specs *reader,
18046                struct die_info **diep, const gdb_byte *info_ptr,
18047                int *has_children)
18048 {
18049   const gdb_byte *result;
18050
18051   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18052
18053   if (dwarf_die_debug)
18054     {
18055       fprintf_unfiltered (gdb_stdlog,
18056                           "Read die from %s@0x%x of %s:\n",
18057                           get_section_name (reader->die_section),
18058                           (unsigned) (info_ptr - reader->die_section->buffer),
18059                           bfd_get_filename (reader->abfd));
18060       dump_die (*diep, dwarf_die_debug);
18061     }
18062
18063   return result;
18064 }
18065 \f
18066 /* Abbreviation tables.
18067
18068    In DWARF version 2, the description of the debugging information is
18069    stored in a separate .debug_abbrev section.  Before we read any
18070    dies from a section we read in all abbreviations and install them
18071    in a hash table.  */
18072
18073 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18074
18075 struct abbrev_info *
18076 abbrev_table::alloc_abbrev ()
18077 {
18078   struct abbrev_info *abbrev;
18079
18080   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18081   memset (abbrev, 0, sizeof (struct abbrev_info));
18082
18083   return abbrev;
18084 }
18085
18086 /* Add an abbreviation to the table.  */
18087
18088 void
18089 abbrev_table::add_abbrev (unsigned int abbrev_number,
18090                           struct abbrev_info *abbrev)
18091 {
18092   unsigned int hash_number;
18093
18094   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18095   abbrev->next = m_abbrevs[hash_number];
18096   m_abbrevs[hash_number] = abbrev;
18097 }
18098
18099 /* Look up an abbrev in the table.
18100    Returns NULL if the abbrev is not found.  */
18101
18102 struct abbrev_info *
18103 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18104 {
18105   unsigned int hash_number;
18106   struct abbrev_info *abbrev;
18107
18108   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18109   abbrev = m_abbrevs[hash_number];
18110
18111   while (abbrev)
18112     {
18113       if (abbrev->number == abbrev_number)
18114         return abbrev;
18115       abbrev = abbrev->next;
18116     }
18117   return NULL;
18118 }
18119
18120 /* Read in an abbrev table.  */
18121
18122 static abbrev_table_up
18123 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18124                          struct dwarf2_section_info *section,
18125                          sect_offset sect_off)
18126 {
18127   struct objfile *objfile = dwarf2_per_objfile->objfile;
18128   bfd *abfd = get_section_bfd_owner (section);
18129   const gdb_byte *abbrev_ptr;
18130   struct abbrev_info *cur_abbrev;
18131   unsigned int abbrev_number, bytes_read, abbrev_name;
18132   unsigned int abbrev_form;
18133   struct attr_abbrev *cur_attrs;
18134   unsigned int allocated_attrs;
18135
18136   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18137
18138   dwarf2_read_section (objfile, section);
18139   abbrev_ptr = section->buffer + to_underlying (sect_off);
18140   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18141   abbrev_ptr += bytes_read;
18142
18143   allocated_attrs = ATTR_ALLOC_CHUNK;
18144   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18145
18146   /* Loop until we reach an abbrev number of 0.  */
18147   while (abbrev_number)
18148     {
18149       cur_abbrev = abbrev_table->alloc_abbrev ();
18150
18151       /* read in abbrev header */
18152       cur_abbrev->number = abbrev_number;
18153       cur_abbrev->tag
18154         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18155       abbrev_ptr += bytes_read;
18156       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18157       abbrev_ptr += 1;
18158
18159       /* now read in declarations */
18160       for (;;)
18161         {
18162           LONGEST implicit_const;
18163
18164           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18165           abbrev_ptr += bytes_read;
18166           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18167           abbrev_ptr += bytes_read;
18168           if (abbrev_form == DW_FORM_implicit_const)
18169             {
18170               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18171                                                    &bytes_read);
18172               abbrev_ptr += bytes_read;
18173             }
18174           else
18175             {
18176               /* Initialize it due to a false compiler warning.  */
18177               implicit_const = -1;
18178             }
18179
18180           if (abbrev_name == 0)
18181             break;
18182
18183           if (cur_abbrev->num_attrs == allocated_attrs)
18184             {
18185               allocated_attrs += ATTR_ALLOC_CHUNK;
18186               cur_attrs
18187                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18188             }
18189
18190           cur_attrs[cur_abbrev->num_attrs].name
18191             = (enum dwarf_attribute) abbrev_name;
18192           cur_attrs[cur_abbrev->num_attrs].form
18193             = (enum dwarf_form) abbrev_form;
18194           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18195           ++cur_abbrev->num_attrs;
18196         }
18197
18198       cur_abbrev->attrs =
18199         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18200                    cur_abbrev->num_attrs);
18201       memcpy (cur_abbrev->attrs, cur_attrs,
18202               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18203
18204       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18205
18206       /* Get next abbreviation.
18207          Under Irix6 the abbreviations for a compilation unit are not
18208          always properly terminated with an abbrev number of 0.
18209          Exit loop if we encounter an abbreviation which we have
18210          already read (which means we are about to read the abbreviations
18211          for the next compile unit) or if the end of the abbreviation
18212          table is reached.  */
18213       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18214         break;
18215       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18216       abbrev_ptr += bytes_read;
18217       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18218         break;
18219     }
18220
18221   xfree (cur_attrs);
18222   return abbrev_table;
18223 }
18224
18225 /* Returns nonzero if TAG represents a type that we might generate a partial
18226    symbol for.  */
18227
18228 static int
18229 is_type_tag_for_partial (int tag)
18230 {
18231   switch (tag)
18232     {
18233 #if 0
18234     /* Some types that would be reasonable to generate partial symbols for,
18235        that we don't at present.  */
18236     case DW_TAG_array_type:
18237     case DW_TAG_file_type:
18238     case DW_TAG_ptr_to_member_type:
18239     case DW_TAG_set_type:
18240     case DW_TAG_string_type:
18241     case DW_TAG_subroutine_type:
18242 #endif
18243     case DW_TAG_base_type:
18244     case DW_TAG_class_type:
18245     case DW_TAG_interface_type:
18246     case DW_TAG_enumeration_type:
18247     case DW_TAG_structure_type:
18248     case DW_TAG_subrange_type:
18249     case DW_TAG_typedef:
18250     case DW_TAG_union_type:
18251       return 1;
18252     default:
18253       return 0;
18254     }
18255 }
18256
18257 /* Load all DIEs that are interesting for partial symbols into memory.  */
18258
18259 static struct partial_die_info *
18260 load_partial_dies (const struct die_reader_specs *reader,
18261                    const gdb_byte *info_ptr, int building_psymtab)
18262 {
18263   struct dwarf2_cu *cu = reader->cu;
18264   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18265   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18266   unsigned int bytes_read;
18267   unsigned int load_all = 0;
18268   int nesting_level = 1;
18269
18270   parent_die = NULL;
18271   last_die = NULL;
18272
18273   gdb_assert (cu->per_cu != NULL);
18274   if (cu->per_cu->load_all_dies)
18275     load_all = 1;
18276
18277   cu->partial_dies
18278     = htab_create_alloc_ex (cu->header.length / 12,
18279                             partial_die_hash,
18280                             partial_die_eq,
18281                             NULL,
18282                             &cu->comp_unit_obstack,
18283                             hashtab_obstack_allocate,
18284                             dummy_obstack_deallocate);
18285
18286   while (1)
18287     {
18288       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18289
18290       /* A NULL abbrev means the end of a series of children.  */
18291       if (abbrev == NULL)
18292         {
18293           if (--nesting_level == 0)
18294             return first_die;
18295
18296           info_ptr += bytes_read;
18297           last_die = parent_die;
18298           parent_die = parent_die->die_parent;
18299           continue;
18300         }
18301
18302       /* Check for template arguments.  We never save these; if
18303          they're seen, we just mark the parent, and go on our way.  */
18304       if (parent_die != NULL
18305           && cu->language == language_cplus
18306           && (abbrev->tag == DW_TAG_template_type_param
18307               || abbrev->tag == DW_TAG_template_value_param))
18308         {
18309           parent_die->has_template_arguments = 1;
18310
18311           if (!load_all)
18312             {
18313               /* We don't need a partial DIE for the template argument.  */
18314               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18315               continue;
18316             }
18317         }
18318
18319       /* We only recurse into c++ subprograms looking for template arguments.
18320          Skip their other children.  */
18321       if (!load_all
18322           && cu->language == language_cplus
18323           && parent_die != NULL
18324           && parent_die->tag == DW_TAG_subprogram)
18325         {
18326           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18327           continue;
18328         }
18329
18330       /* Check whether this DIE is interesting enough to save.  Normally
18331          we would not be interested in members here, but there may be
18332          later variables referencing them via DW_AT_specification (for
18333          static members).  */
18334       if (!load_all
18335           && !is_type_tag_for_partial (abbrev->tag)
18336           && abbrev->tag != DW_TAG_constant
18337           && abbrev->tag != DW_TAG_enumerator
18338           && abbrev->tag != DW_TAG_subprogram
18339           && abbrev->tag != DW_TAG_inlined_subroutine
18340           && abbrev->tag != DW_TAG_lexical_block
18341           && abbrev->tag != DW_TAG_variable
18342           && abbrev->tag != DW_TAG_namespace
18343           && abbrev->tag != DW_TAG_module
18344           && abbrev->tag != DW_TAG_member
18345           && abbrev->tag != DW_TAG_imported_unit
18346           && abbrev->tag != DW_TAG_imported_declaration)
18347         {
18348           /* Otherwise we skip to the next sibling, if any.  */
18349           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18350           continue;
18351         }
18352
18353       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18354                                    abbrev);
18355
18356       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18357
18358       /* This two-pass algorithm for processing partial symbols has a
18359          high cost in cache pressure.  Thus, handle some simple cases
18360          here which cover the majority of C partial symbols.  DIEs
18361          which neither have specification tags in them, nor could have
18362          specification tags elsewhere pointing at them, can simply be
18363          processed and discarded.
18364
18365          This segment is also optional; scan_partial_symbols and
18366          add_partial_symbol will handle these DIEs if we chain
18367          them in normally.  When compilers which do not emit large
18368          quantities of duplicate debug information are more common,
18369          this code can probably be removed.  */
18370
18371       /* Any complete simple types at the top level (pretty much all
18372          of them, for a language without namespaces), can be processed
18373          directly.  */
18374       if (parent_die == NULL
18375           && pdi.has_specification == 0
18376           && pdi.is_declaration == 0
18377           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18378               || pdi.tag == DW_TAG_base_type
18379               || pdi.tag == DW_TAG_subrange_type))
18380         {
18381           if (building_psymtab && pdi.name != NULL)
18382             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18383                                  VAR_DOMAIN, LOC_TYPEDEF,
18384                                  &objfile->static_psymbols,
18385                                  0, cu->language, objfile);
18386           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18387           continue;
18388         }
18389
18390       /* The exception for DW_TAG_typedef with has_children above is
18391          a workaround of GCC PR debug/47510.  In the case of this complaint
18392          type_name_no_tag_or_error will error on such types later.
18393
18394          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18395          it could not find the child DIEs referenced later, this is checked
18396          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18397
18398       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18399         complaint (&symfile_complaints,
18400                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18401                      "- DIE at %s [in module %s]"),
18402                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18403
18404       /* If we're at the second level, and we're an enumerator, and
18405          our parent has no specification (meaning possibly lives in a
18406          namespace elsewhere), then we can add the partial symbol now
18407          instead of queueing it.  */
18408       if (pdi.tag == DW_TAG_enumerator
18409           && parent_die != NULL
18410           && parent_die->die_parent == NULL
18411           && parent_die->tag == DW_TAG_enumeration_type
18412           && parent_die->has_specification == 0)
18413         {
18414           if (pdi.name == NULL)
18415             complaint (&symfile_complaints,
18416                        _("malformed enumerator DIE ignored"));
18417           else if (building_psymtab)
18418             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18419                                  VAR_DOMAIN, LOC_CONST,
18420                                  cu->language == language_cplus
18421                                  ? &objfile->global_psymbols
18422                                  : &objfile->static_psymbols,
18423                                  0, cu->language, objfile);
18424
18425           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18426           continue;
18427         }
18428
18429       struct partial_die_info *part_die
18430         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18431
18432       /* We'll save this DIE so link it in.  */
18433       part_die->die_parent = parent_die;
18434       part_die->die_sibling = NULL;
18435       part_die->die_child = NULL;
18436
18437       if (last_die && last_die == parent_die)
18438         last_die->die_child = part_die;
18439       else if (last_die)
18440         last_die->die_sibling = part_die;
18441
18442       last_die = part_die;
18443
18444       if (first_die == NULL)
18445         first_die = part_die;
18446
18447       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18448          find interesting need to be in the hash table, because we
18449          also have the parent/sibling/child chains; only those that we
18450          might refer to by offset later during partial symbol reading.
18451
18452          For now this means things that might have be the target of a
18453          DW_AT_specification, DW_AT_abstract_origin, or
18454          DW_AT_extension.  DW_AT_extension will refer only to
18455          namespaces; DW_AT_abstract_origin refers to functions (and
18456          many things under the function DIE, but we do not recurse
18457          into function DIEs during partial symbol reading) and
18458          possibly variables as well; DW_AT_specification refers to
18459          declarations.  Declarations ought to have the DW_AT_declaration
18460          flag.  It happens that GCC forgets to put it in sometimes, but
18461          only for functions, not for types.
18462
18463          Adding more things than necessary to the hash table is harmless
18464          except for the performance cost.  Adding too few will result in
18465          wasted time in find_partial_die, when we reread the compilation
18466          unit with load_all_dies set.  */
18467
18468       if (load_all
18469           || abbrev->tag == DW_TAG_constant
18470           || abbrev->tag == DW_TAG_subprogram
18471           || abbrev->tag == DW_TAG_variable
18472           || abbrev->tag == DW_TAG_namespace
18473           || part_die->is_declaration)
18474         {
18475           void **slot;
18476
18477           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18478                                            to_underlying (part_die->sect_off),
18479                                            INSERT);
18480           *slot = part_die;
18481         }
18482
18483       /* For some DIEs we want to follow their children (if any).  For C
18484          we have no reason to follow the children of structures; for other
18485          languages we have to, so that we can get at method physnames
18486          to infer fully qualified class names, for DW_AT_specification,
18487          and for C++ template arguments.  For C++, we also look one level
18488          inside functions to find template arguments (if the name of the
18489          function does not already contain the template arguments).
18490
18491          For Ada, we need to scan the children of subprograms and lexical
18492          blocks as well because Ada allows the definition of nested
18493          entities that could be interesting for the debugger, such as
18494          nested subprograms for instance.  */
18495       if (last_die->has_children
18496           && (load_all
18497               || last_die->tag == DW_TAG_namespace
18498               || last_die->tag == DW_TAG_module
18499               || last_die->tag == DW_TAG_enumeration_type
18500               || (cu->language == language_cplus
18501                   && last_die->tag == DW_TAG_subprogram
18502                   && (last_die->name == NULL
18503                       || strchr (last_die->name, '<') == NULL))
18504               || (cu->language != language_c
18505                   && (last_die->tag == DW_TAG_class_type
18506                       || last_die->tag == DW_TAG_interface_type
18507                       || last_die->tag == DW_TAG_structure_type
18508                       || last_die->tag == DW_TAG_union_type))
18509               || (cu->language == language_ada
18510                   && (last_die->tag == DW_TAG_subprogram
18511                       || last_die->tag == DW_TAG_lexical_block))))
18512         {
18513           nesting_level++;
18514           parent_die = last_die;
18515           continue;
18516         }
18517
18518       /* Otherwise we skip to the next sibling, if any.  */
18519       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18520
18521       /* Back to the top, do it again.  */
18522     }
18523 }
18524
18525 partial_die_info::partial_die_info (sect_offset sect_off_,
18526                                     struct abbrev_info *abbrev)
18527   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18528 {
18529 }
18530
18531 /* Read a minimal amount of information into the minimal die structure.
18532    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18533
18534 const gdb_byte *
18535 partial_die_info::read (const struct die_reader_specs *reader,
18536                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18537 {
18538   struct dwarf2_cu *cu = reader->cu;
18539   struct dwarf2_per_objfile *dwarf2_per_objfile
18540     = cu->per_cu->dwarf2_per_objfile;
18541   unsigned int i;
18542   int has_low_pc_attr = 0;
18543   int has_high_pc_attr = 0;
18544   int high_pc_relative = 0;
18545
18546   for (i = 0; i < abbrev.num_attrs; ++i)
18547     {
18548       struct attribute attr;
18549
18550       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18551
18552       /* Store the data if it is of an attribute we want to keep in a
18553          partial symbol table.  */
18554       switch (attr.name)
18555         {
18556         case DW_AT_name:
18557           switch (tag)
18558             {
18559             case DW_TAG_compile_unit:
18560             case DW_TAG_partial_unit:
18561             case DW_TAG_type_unit:
18562               /* Compilation units have a DW_AT_name that is a filename, not
18563                  a source language identifier.  */
18564             case DW_TAG_enumeration_type:
18565             case DW_TAG_enumerator:
18566               /* These tags always have simple identifiers already; no need
18567                  to canonicalize them.  */
18568               name = DW_STRING (&attr);
18569               break;
18570             default:
18571               {
18572                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18573
18574                 name
18575                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18576                                               &objfile->per_bfd->storage_obstack);
18577               }
18578               break;
18579             }
18580           break;
18581         case DW_AT_linkage_name:
18582         case DW_AT_MIPS_linkage_name:
18583           /* Note that both forms of linkage name might appear.  We
18584              assume they will be the same, and we only store the last
18585              one we see.  */
18586           if (cu->language == language_ada)
18587             name = DW_STRING (&attr);
18588           linkage_name = DW_STRING (&attr);
18589           break;
18590         case DW_AT_low_pc:
18591           has_low_pc_attr = 1;
18592           lowpc = attr_value_as_address (&attr);
18593           break;
18594         case DW_AT_high_pc:
18595           has_high_pc_attr = 1;
18596           highpc = attr_value_as_address (&attr);
18597           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18598                 high_pc_relative = 1;
18599           break;
18600         case DW_AT_location:
18601           /* Support the .debug_loc offsets.  */
18602           if (attr_form_is_block (&attr))
18603             {
18604                d.locdesc = DW_BLOCK (&attr);
18605             }
18606           else if (attr_form_is_section_offset (&attr))
18607             {
18608               dwarf2_complex_location_expr_complaint ();
18609             }
18610           else
18611             {
18612               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18613                                                      "partial symbol information");
18614             }
18615           break;
18616         case DW_AT_external:
18617           is_external = DW_UNSND (&attr);
18618           break;
18619         case DW_AT_declaration:
18620           is_declaration = DW_UNSND (&attr);
18621           break;
18622         case DW_AT_type:
18623           has_type = 1;
18624           break;
18625         case DW_AT_abstract_origin:
18626         case DW_AT_specification:
18627         case DW_AT_extension:
18628           has_specification = 1;
18629           spec_offset = dwarf2_get_ref_die_offset (&attr);
18630           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18631                                    || cu->per_cu->is_dwz);
18632           break;
18633         case DW_AT_sibling:
18634           /* Ignore absolute siblings, they might point outside of
18635              the current compile unit.  */
18636           if (attr.form == DW_FORM_ref_addr)
18637             complaint (&symfile_complaints,
18638                        _("ignoring absolute DW_AT_sibling"));
18639           else
18640             {
18641               const gdb_byte *buffer = reader->buffer;
18642               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18643               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18644
18645               if (sibling_ptr < info_ptr)
18646                 complaint (&symfile_complaints,
18647                            _("DW_AT_sibling points backwards"));
18648               else if (sibling_ptr > reader->buffer_end)
18649                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18650               else
18651                 sibling = sibling_ptr;
18652             }
18653           break;
18654         case DW_AT_byte_size:
18655           has_byte_size = 1;
18656           break;
18657         case DW_AT_const_value:
18658           has_const_value = 1;
18659           break;
18660         case DW_AT_calling_convention:
18661           /* DWARF doesn't provide a way to identify a program's source-level
18662              entry point.  DW_AT_calling_convention attributes are only meant
18663              to describe functions' calling conventions.
18664
18665              However, because it's a necessary piece of information in
18666              Fortran, and before DWARF 4 DW_CC_program was the only
18667              piece of debugging information whose definition refers to
18668              a 'main program' at all, several compilers marked Fortran
18669              main programs with DW_CC_program --- even when those
18670              functions use the standard calling conventions.
18671
18672              Although DWARF now specifies a way to provide this
18673              information, we support this practice for backward
18674              compatibility.  */
18675           if (DW_UNSND (&attr) == DW_CC_program
18676               && cu->language == language_fortran)
18677             main_subprogram = 1;
18678           break;
18679         case DW_AT_inline:
18680           if (DW_UNSND (&attr) == DW_INL_inlined
18681               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18682             may_be_inlined = 1;
18683           break;
18684
18685         case DW_AT_import:
18686           if (tag == DW_TAG_imported_unit)
18687             {
18688               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18689               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18690                                   || cu->per_cu->is_dwz);
18691             }
18692           break;
18693
18694         case DW_AT_main_subprogram:
18695           main_subprogram = DW_UNSND (&attr);
18696           break;
18697
18698         default:
18699           break;
18700         }
18701     }
18702
18703   if (high_pc_relative)
18704     highpc += lowpc;
18705
18706   if (has_low_pc_attr && has_high_pc_attr)
18707     {
18708       /* When using the GNU linker, .gnu.linkonce. sections are used to
18709          eliminate duplicate copies of functions and vtables and such.
18710          The linker will arbitrarily choose one and discard the others.
18711          The AT_*_pc values for such functions refer to local labels in
18712          these sections.  If the section from that file was discarded, the
18713          labels are not in the output, so the relocs get a value of 0.
18714          If this is a discarded function, mark the pc bounds as invalid,
18715          so that GDB will ignore it.  */
18716       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18717         {
18718           struct objfile *objfile = dwarf2_per_objfile->objfile;
18719           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18720
18721           complaint (&symfile_complaints,
18722                      _("DW_AT_low_pc %s is zero "
18723                        "for DIE at %s [in module %s]"),
18724                      paddress (gdbarch, lowpc),
18725                      sect_offset_str (sect_off),
18726                      objfile_name (objfile));
18727         }
18728       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18729       else if (lowpc >= highpc)
18730         {
18731           struct objfile *objfile = dwarf2_per_objfile->objfile;
18732           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18733
18734           complaint (&symfile_complaints,
18735                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18736                        "for DIE at %s [in module %s]"),
18737                      paddress (gdbarch, lowpc),
18738                      paddress (gdbarch, highpc),
18739                      sect_offset_str (sect_off),
18740                      objfile_name (objfile));
18741         }
18742       else
18743         has_pc_info = 1;
18744     }
18745
18746   return info_ptr;
18747 }
18748
18749 /* Find a cached partial DIE at OFFSET in CU.  */
18750
18751 struct partial_die_info *
18752 dwarf2_cu::find_partial_die (sect_offset sect_off)
18753 {
18754   struct partial_die_info *lookup_die = NULL;
18755   struct partial_die_info part_die (sect_off);
18756
18757   lookup_die = ((struct partial_die_info *)
18758                 htab_find_with_hash (partial_dies, &part_die,
18759                                      to_underlying (sect_off)));
18760
18761   return lookup_die;
18762 }
18763
18764 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18765    except in the case of .debug_types DIEs which do not reference
18766    outside their CU (they do however referencing other types via
18767    DW_FORM_ref_sig8).  */
18768
18769 static struct partial_die_info *
18770 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18771 {
18772   struct dwarf2_per_objfile *dwarf2_per_objfile
18773     = cu->per_cu->dwarf2_per_objfile;
18774   struct objfile *objfile = dwarf2_per_objfile->objfile;
18775   struct dwarf2_per_cu_data *per_cu = NULL;
18776   struct partial_die_info *pd = NULL;
18777
18778   if (offset_in_dwz == cu->per_cu->is_dwz
18779       && offset_in_cu_p (&cu->header, sect_off))
18780     {
18781       pd = cu->find_partial_die (sect_off);
18782       if (pd != NULL)
18783         return pd;
18784       /* We missed recording what we needed.
18785          Load all dies and try again.  */
18786       per_cu = cu->per_cu;
18787     }
18788   else
18789     {
18790       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18791       if (cu->per_cu->is_debug_types)
18792         {
18793           error (_("Dwarf Error: Type Unit at offset %s contains"
18794                    " external reference to offset %s [in module %s].\n"),
18795                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18796                  bfd_get_filename (objfile->obfd));
18797         }
18798       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18799                                                  dwarf2_per_objfile);
18800
18801       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18802         load_partial_comp_unit (per_cu);
18803
18804       per_cu->cu->last_used = 0;
18805       pd = per_cu->cu->find_partial_die (sect_off);
18806     }
18807
18808   /* If we didn't find it, and not all dies have been loaded,
18809      load them all and try again.  */
18810
18811   if (pd == NULL && per_cu->load_all_dies == 0)
18812     {
18813       per_cu->load_all_dies = 1;
18814
18815       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18816          THIS_CU->cu may already be in use.  So we can't just free it and
18817          replace its DIEs with the ones we read in.  Instead, we leave those
18818          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18819          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18820          set.  */
18821       load_partial_comp_unit (per_cu);
18822
18823       pd = per_cu->cu->find_partial_die (sect_off);
18824     }
18825
18826   if (pd == NULL)
18827     internal_error (__FILE__, __LINE__,
18828                     _("could not find partial DIE %s "
18829                       "in cache [from module %s]\n"),
18830                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18831   return pd;
18832 }
18833
18834 /* See if we can figure out if the class lives in a namespace.  We do
18835    this by looking for a member function; its demangled name will
18836    contain namespace info, if there is any.  */
18837
18838 static void
18839 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18840                                   struct dwarf2_cu *cu)
18841 {
18842   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18843      what template types look like, because the demangler
18844      frequently doesn't give the same name as the debug info.  We
18845      could fix this by only using the demangled name to get the
18846      prefix (but see comment in read_structure_type).  */
18847
18848   struct partial_die_info *real_pdi;
18849   struct partial_die_info *child_pdi;
18850
18851   /* If this DIE (this DIE's specification, if any) has a parent, then
18852      we should not do this.  We'll prepend the parent's fully qualified
18853      name when we create the partial symbol.  */
18854
18855   real_pdi = struct_pdi;
18856   while (real_pdi->has_specification)
18857     real_pdi = find_partial_die (real_pdi->spec_offset,
18858                                  real_pdi->spec_is_dwz, cu);
18859
18860   if (real_pdi->die_parent != NULL)
18861     return;
18862
18863   for (child_pdi = struct_pdi->die_child;
18864        child_pdi != NULL;
18865        child_pdi = child_pdi->die_sibling)
18866     {
18867       if (child_pdi->tag == DW_TAG_subprogram
18868           && child_pdi->linkage_name != NULL)
18869         {
18870           char *actual_class_name
18871             = language_class_name_from_physname (cu->language_defn,
18872                                                  child_pdi->linkage_name);
18873           if (actual_class_name != NULL)
18874             {
18875               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18876               struct_pdi->name
18877                 = ((const char *)
18878                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18879                                   actual_class_name,
18880                                   strlen (actual_class_name)));
18881               xfree (actual_class_name);
18882             }
18883           break;
18884         }
18885     }
18886 }
18887
18888 void
18889 partial_die_info::fixup (struct dwarf2_cu *cu)
18890 {
18891   /* Once we've fixed up a die, there's no point in doing so again.
18892      This also avoids a memory leak if we were to call
18893      guess_partial_die_structure_name multiple times.  */
18894   if (fixup_called)
18895     return;
18896
18897   /* If we found a reference attribute and the DIE has no name, try
18898      to find a name in the referred to DIE.  */
18899
18900   if (name == NULL && has_specification)
18901     {
18902       struct partial_die_info *spec_die;
18903
18904       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18905
18906       spec_die->fixup (cu);
18907
18908       if (spec_die->name)
18909         {
18910           name = spec_die->name;
18911
18912           /* Copy DW_AT_external attribute if it is set.  */
18913           if (spec_die->is_external)
18914             is_external = spec_die->is_external;
18915         }
18916     }
18917
18918   /* Set default names for some unnamed DIEs.  */
18919
18920   if (name == NULL && tag == DW_TAG_namespace)
18921     name = CP_ANONYMOUS_NAMESPACE_STR;
18922
18923   /* If there is no parent die to provide a namespace, and there are
18924      children, see if we can determine the namespace from their linkage
18925      name.  */
18926   if (cu->language == language_cplus
18927       && !VEC_empty (dwarf2_section_info_def,
18928                      cu->per_cu->dwarf2_per_objfile->types)
18929       && die_parent == NULL
18930       && has_children
18931       && (tag == DW_TAG_class_type
18932           || tag == DW_TAG_structure_type
18933           || tag == DW_TAG_union_type))
18934     guess_partial_die_structure_name (this, cu);
18935
18936   /* GCC might emit a nameless struct or union that has a linkage
18937      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18938   if (name == NULL
18939       && (tag == DW_TAG_class_type
18940           || tag == DW_TAG_interface_type
18941           || tag == DW_TAG_structure_type
18942           || tag == DW_TAG_union_type)
18943       && linkage_name != NULL)
18944     {
18945       char *demangled;
18946
18947       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18948       if (demangled)
18949         {
18950           const char *base;
18951
18952           /* Strip any leading namespaces/classes, keep only the base name.
18953              DW_AT_name for named DIEs does not contain the prefixes.  */
18954           base = strrchr (demangled, ':');
18955           if (base && base > demangled && base[-1] == ':')
18956             base++;
18957           else
18958             base = demangled;
18959
18960           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18961           name
18962             = ((const char *)
18963                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18964                               base, strlen (base)));
18965           xfree (demangled);
18966         }
18967     }
18968
18969   fixup_called = 1;
18970 }
18971
18972 /* Read an attribute value described by an attribute form.  */
18973
18974 static const gdb_byte *
18975 read_attribute_value (const struct die_reader_specs *reader,
18976                       struct attribute *attr, unsigned form,
18977                       LONGEST implicit_const, const gdb_byte *info_ptr)
18978 {
18979   struct dwarf2_cu *cu = reader->cu;
18980   struct dwarf2_per_objfile *dwarf2_per_objfile
18981     = cu->per_cu->dwarf2_per_objfile;
18982   struct objfile *objfile = dwarf2_per_objfile->objfile;
18983   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18984   bfd *abfd = reader->abfd;
18985   struct comp_unit_head *cu_header = &cu->header;
18986   unsigned int bytes_read;
18987   struct dwarf_block *blk;
18988
18989   attr->form = (enum dwarf_form) form;
18990   switch (form)
18991     {
18992     case DW_FORM_ref_addr:
18993       if (cu->header.version == 2)
18994         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18995       else
18996         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18997                                        &cu->header, &bytes_read);
18998       info_ptr += bytes_read;
18999       break;
19000     case DW_FORM_GNU_ref_alt:
19001       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19002       info_ptr += bytes_read;
19003       break;
19004     case DW_FORM_addr:
19005       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19006       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19007       info_ptr += bytes_read;
19008       break;
19009     case DW_FORM_block2:
19010       blk = dwarf_alloc_block (cu);
19011       blk->size = read_2_bytes (abfd, info_ptr);
19012       info_ptr += 2;
19013       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19014       info_ptr += blk->size;
19015       DW_BLOCK (attr) = blk;
19016       break;
19017     case DW_FORM_block4:
19018       blk = dwarf_alloc_block (cu);
19019       blk->size = read_4_bytes (abfd, info_ptr);
19020       info_ptr += 4;
19021       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19022       info_ptr += blk->size;
19023       DW_BLOCK (attr) = blk;
19024       break;
19025     case DW_FORM_data2:
19026       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19027       info_ptr += 2;
19028       break;
19029     case DW_FORM_data4:
19030       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19031       info_ptr += 4;
19032       break;
19033     case DW_FORM_data8:
19034       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19035       info_ptr += 8;
19036       break;
19037     case DW_FORM_data16:
19038       blk = dwarf_alloc_block (cu);
19039       blk->size = 16;
19040       blk->data = read_n_bytes (abfd, info_ptr, 16);
19041       info_ptr += 16;
19042       DW_BLOCK (attr) = blk;
19043       break;
19044     case DW_FORM_sec_offset:
19045       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19046       info_ptr += bytes_read;
19047       break;
19048     case DW_FORM_string:
19049       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19050       DW_STRING_IS_CANONICAL (attr) = 0;
19051       info_ptr += bytes_read;
19052       break;
19053     case DW_FORM_strp:
19054       if (!cu->per_cu->is_dwz)
19055         {
19056           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19057                                                    abfd, info_ptr, cu_header,
19058                                                    &bytes_read);
19059           DW_STRING_IS_CANONICAL (attr) = 0;
19060           info_ptr += bytes_read;
19061           break;
19062         }
19063       /* FALLTHROUGH */
19064     case DW_FORM_line_strp:
19065       if (!cu->per_cu->is_dwz)
19066         {
19067           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19068                                                         abfd, info_ptr,
19069                                                         cu_header, &bytes_read);
19070           DW_STRING_IS_CANONICAL (attr) = 0;
19071           info_ptr += bytes_read;
19072           break;
19073         }
19074       /* FALLTHROUGH */
19075     case DW_FORM_GNU_strp_alt:
19076       {
19077         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19078         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19079                                           &bytes_read);
19080
19081         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19082                                                           dwz, str_offset);
19083         DW_STRING_IS_CANONICAL (attr) = 0;
19084         info_ptr += bytes_read;
19085       }
19086       break;
19087     case DW_FORM_exprloc:
19088     case DW_FORM_block:
19089       blk = dwarf_alloc_block (cu);
19090       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19091       info_ptr += bytes_read;
19092       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19093       info_ptr += blk->size;
19094       DW_BLOCK (attr) = blk;
19095       break;
19096     case DW_FORM_block1:
19097       blk = dwarf_alloc_block (cu);
19098       blk->size = read_1_byte (abfd, info_ptr);
19099       info_ptr += 1;
19100       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19101       info_ptr += blk->size;
19102       DW_BLOCK (attr) = blk;
19103       break;
19104     case DW_FORM_data1:
19105       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19106       info_ptr += 1;
19107       break;
19108     case DW_FORM_flag:
19109       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19110       info_ptr += 1;
19111       break;
19112     case DW_FORM_flag_present:
19113       DW_UNSND (attr) = 1;
19114       break;
19115     case DW_FORM_sdata:
19116       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19117       info_ptr += bytes_read;
19118       break;
19119     case DW_FORM_udata:
19120       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19121       info_ptr += bytes_read;
19122       break;
19123     case DW_FORM_ref1:
19124       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19125                          + read_1_byte (abfd, info_ptr));
19126       info_ptr += 1;
19127       break;
19128     case DW_FORM_ref2:
19129       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19130                          + read_2_bytes (abfd, info_ptr));
19131       info_ptr += 2;
19132       break;
19133     case DW_FORM_ref4:
19134       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19135                          + read_4_bytes (abfd, info_ptr));
19136       info_ptr += 4;
19137       break;
19138     case DW_FORM_ref8:
19139       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19140                          + read_8_bytes (abfd, info_ptr));
19141       info_ptr += 8;
19142       break;
19143     case DW_FORM_ref_sig8:
19144       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19145       info_ptr += 8;
19146       break;
19147     case DW_FORM_ref_udata:
19148       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19149                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19150       info_ptr += bytes_read;
19151       break;
19152     case DW_FORM_indirect:
19153       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19154       info_ptr += bytes_read;
19155       if (form == DW_FORM_implicit_const)
19156         {
19157           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19158           info_ptr += bytes_read;
19159         }
19160       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19161                                        info_ptr);
19162       break;
19163     case DW_FORM_implicit_const:
19164       DW_SND (attr) = implicit_const;
19165       break;
19166     case DW_FORM_GNU_addr_index:
19167       if (reader->dwo_file == NULL)
19168         {
19169           /* For now flag a hard error.
19170              Later we can turn this into a complaint.  */
19171           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19172                  dwarf_form_name (form),
19173                  bfd_get_filename (abfd));
19174         }
19175       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19176       info_ptr += bytes_read;
19177       break;
19178     case DW_FORM_GNU_str_index:
19179       if (reader->dwo_file == NULL)
19180         {
19181           /* For now flag a hard error.
19182              Later we can turn this into a complaint if warranted.  */
19183           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19184                  dwarf_form_name (form),
19185                  bfd_get_filename (abfd));
19186         }
19187       {
19188         ULONGEST str_index =
19189           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19190
19191         DW_STRING (attr) = read_str_index (reader, str_index);
19192         DW_STRING_IS_CANONICAL (attr) = 0;
19193         info_ptr += bytes_read;
19194       }
19195       break;
19196     default:
19197       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19198              dwarf_form_name (form),
19199              bfd_get_filename (abfd));
19200     }
19201
19202   /* Super hack.  */
19203   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19204     attr->form = DW_FORM_GNU_ref_alt;
19205
19206   /* We have seen instances where the compiler tried to emit a byte
19207      size attribute of -1 which ended up being encoded as an unsigned
19208      0xffffffff.  Although 0xffffffff is technically a valid size value,
19209      an object of this size seems pretty unlikely so we can relatively
19210      safely treat these cases as if the size attribute was invalid and
19211      treat them as zero by default.  */
19212   if (attr->name == DW_AT_byte_size
19213       && form == DW_FORM_data4
19214       && DW_UNSND (attr) >= 0xffffffff)
19215     {
19216       complaint
19217         (&symfile_complaints,
19218          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19219          hex_string (DW_UNSND (attr)));
19220       DW_UNSND (attr) = 0;
19221     }
19222
19223   return info_ptr;
19224 }
19225
19226 /* Read an attribute described by an abbreviated attribute.  */
19227
19228 static const gdb_byte *
19229 read_attribute (const struct die_reader_specs *reader,
19230                 struct attribute *attr, struct attr_abbrev *abbrev,
19231                 const gdb_byte *info_ptr)
19232 {
19233   attr->name = abbrev->name;
19234   return read_attribute_value (reader, attr, abbrev->form,
19235                                abbrev->implicit_const, info_ptr);
19236 }
19237
19238 /* Read dwarf information from a buffer.  */
19239
19240 static unsigned int
19241 read_1_byte (bfd *abfd, const gdb_byte *buf)
19242 {
19243   return bfd_get_8 (abfd, buf);
19244 }
19245
19246 static int
19247 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19248 {
19249   return bfd_get_signed_8 (abfd, buf);
19250 }
19251
19252 static unsigned int
19253 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19254 {
19255   return bfd_get_16 (abfd, buf);
19256 }
19257
19258 static int
19259 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19260 {
19261   return bfd_get_signed_16 (abfd, buf);
19262 }
19263
19264 static unsigned int
19265 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19266 {
19267   return bfd_get_32 (abfd, buf);
19268 }
19269
19270 static int
19271 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19272 {
19273   return bfd_get_signed_32 (abfd, buf);
19274 }
19275
19276 static ULONGEST
19277 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19278 {
19279   return bfd_get_64 (abfd, buf);
19280 }
19281
19282 static CORE_ADDR
19283 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19284               unsigned int *bytes_read)
19285 {
19286   struct comp_unit_head *cu_header = &cu->header;
19287   CORE_ADDR retval = 0;
19288
19289   if (cu_header->signed_addr_p)
19290     {
19291       switch (cu_header->addr_size)
19292         {
19293         case 2:
19294           retval = bfd_get_signed_16 (abfd, buf);
19295           break;
19296         case 4:
19297           retval = bfd_get_signed_32 (abfd, buf);
19298           break;
19299         case 8:
19300           retval = bfd_get_signed_64 (abfd, buf);
19301           break;
19302         default:
19303           internal_error (__FILE__, __LINE__,
19304                           _("read_address: bad switch, signed [in module %s]"),
19305                           bfd_get_filename (abfd));
19306         }
19307     }
19308   else
19309     {
19310       switch (cu_header->addr_size)
19311         {
19312         case 2:
19313           retval = bfd_get_16 (abfd, buf);
19314           break;
19315         case 4:
19316           retval = bfd_get_32 (abfd, buf);
19317           break;
19318         case 8:
19319           retval = bfd_get_64 (abfd, buf);
19320           break;
19321         default:
19322           internal_error (__FILE__, __LINE__,
19323                           _("read_address: bad switch, "
19324                             "unsigned [in module %s]"),
19325                           bfd_get_filename (abfd));
19326         }
19327     }
19328
19329   *bytes_read = cu_header->addr_size;
19330   return retval;
19331 }
19332
19333 /* Read the initial length from a section.  The (draft) DWARF 3
19334    specification allows the initial length to take up either 4 bytes
19335    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19336    bytes describe the length and all offsets will be 8 bytes in length
19337    instead of 4.
19338
19339    An older, non-standard 64-bit format is also handled by this
19340    function.  The older format in question stores the initial length
19341    as an 8-byte quantity without an escape value.  Lengths greater
19342    than 2^32 aren't very common which means that the initial 4 bytes
19343    is almost always zero.  Since a length value of zero doesn't make
19344    sense for the 32-bit format, this initial zero can be considered to
19345    be an escape value which indicates the presence of the older 64-bit
19346    format.  As written, the code can't detect (old format) lengths
19347    greater than 4GB.  If it becomes necessary to handle lengths
19348    somewhat larger than 4GB, we could allow other small values (such
19349    as the non-sensical values of 1, 2, and 3) to also be used as
19350    escape values indicating the presence of the old format.
19351
19352    The value returned via bytes_read should be used to increment the
19353    relevant pointer after calling read_initial_length().
19354
19355    [ Note:  read_initial_length() and read_offset() are based on the
19356      document entitled "DWARF Debugging Information Format", revision
19357      3, draft 8, dated November 19, 2001.  This document was obtained
19358      from:
19359
19360         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19361
19362      This document is only a draft and is subject to change.  (So beware.)
19363
19364      Details regarding the older, non-standard 64-bit format were
19365      determined empirically by examining 64-bit ELF files produced by
19366      the SGI toolchain on an IRIX 6.5 machine.
19367
19368      - Kevin, July 16, 2002
19369    ] */
19370
19371 static LONGEST
19372 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19373 {
19374   LONGEST length = bfd_get_32 (abfd, buf);
19375
19376   if (length == 0xffffffff)
19377     {
19378       length = bfd_get_64 (abfd, buf + 4);
19379       *bytes_read = 12;
19380     }
19381   else if (length == 0)
19382     {
19383       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19384       length = bfd_get_64 (abfd, buf);
19385       *bytes_read = 8;
19386     }
19387   else
19388     {
19389       *bytes_read = 4;
19390     }
19391
19392   return length;
19393 }
19394
19395 /* Cover function for read_initial_length.
19396    Returns the length of the object at BUF, and stores the size of the
19397    initial length in *BYTES_READ and stores the size that offsets will be in
19398    *OFFSET_SIZE.
19399    If the initial length size is not equivalent to that specified in
19400    CU_HEADER then issue a complaint.
19401    This is useful when reading non-comp-unit headers.  */
19402
19403 static LONGEST
19404 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19405                                         const struct comp_unit_head *cu_header,
19406                                         unsigned int *bytes_read,
19407                                         unsigned int *offset_size)
19408 {
19409   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19410
19411   gdb_assert (cu_header->initial_length_size == 4
19412               || cu_header->initial_length_size == 8
19413               || cu_header->initial_length_size == 12);
19414
19415   if (cu_header->initial_length_size != *bytes_read)
19416     complaint (&symfile_complaints,
19417                _("intermixed 32-bit and 64-bit DWARF sections"));
19418
19419   *offset_size = (*bytes_read == 4) ? 4 : 8;
19420   return length;
19421 }
19422
19423 /* Read an offset from the data stream.  The size of the offset is
19424    given by cu_header->offset_size.  */
19425
19426 static LONGEST
19427 read_offset (bfd *abfd, const gdb_byte *buf,
19428              const struct comp_unit_head *cu_header,
19429              unsigned int *bytes_read)
19430 {
19431   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19432
19433   *bytes_read = cu_header->offset_size;
19434   return offset;
19435 }
19436
19437 /* Read an offset from the data stream.  */
19438
19439 static LONGEST
19440 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19441 {
19442   LONGEST retval = 0;
19443
19444   switch (offset_size)
19445     {
19446     case 4:
19447       retval = bfd_get_32 (abfd, buf);
19448       break;
19449     case 8:
19450       retval = bfd_get_64 (abfd, buf);
19451       break;
19452     default:
19453       internal_error (__FILE__, __LINE__,
19454                       _("read_offset_1: bad switch [in module %s]"),
19455                       bfd_get_filename (abfd));
19456     }
19457
19458   return retval;
19459 }
19460
19461 static const gdb_byte *
19462 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19463 {
19464   /* If the size of a host char is 8 bits, we can return a pointer
19465      to the buffer, otherwise we have to copy the data to a buffer
19466      allocated on the temporary obstack.  */
19467   gdb_assert (HOST_CHAR_BIT == 8);
19468   return buf;
19469 }
19470
19471 static const char *
19472 read_direct_string (bfd *abfd, const gdb_byte *buf,
19473                     unsigned int *bytes_read_ptr)
19474 {
19475   /* If the size of a host char is 8 bits, we can return a pointer
19476      to the string, otherwise we have to copy the string to a buffer
19477      allocated on the temporary obstack.  */
19478   gdb_assert (HOST_CHAR_BIT == 8);
19479   if (*buf == '\0')
19480     {
19481       *bytes_read_ptr = 1;
19482       return NULL;
19483     }
19484   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19485   return (const char *) buf;
19486 }
19487
19488 /* Return pointer to string at section SECT offset STR_OFFSET with error
19489    reporting strings FORM_NAME and SECT_NAME.  */
19490
19491 static const char *
19492 read_indirect_string_at_offset_from (struct objfile *objfile,
19493                                      bfd *abfd, LONGEST str_offset,
19494                                      struct dwarf2_section_info *sect,
19495                                      const char *form_name,
19496                                      const char *sect_name)
19497 {
19498   dwarf2_read_section (objfile, sect);
19499   if (sect->buffer == NULL)
19500     error (_("%s used without %s section [in module %s]"),
19501            form_name, sect_name, bfd_get_filename (abfd));
19502   if (str_offset >= sect->size)
19503     error (_("%s pointing outside of %s section [in module %s]"),
19504            form_name, sect_name, bfd_get_filename (abfd));
19505   gdb_assert (HOST_CHAR_BIT == 8);
19506   if (sect->buffer[str_offset] == '\0')
19507     return NULL;
19508   return (const char *) (sect->buffer + str_offset);
19509 }
19510
19511 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19512
19513 static const char *
19514 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19515                                 bfd *abfd, LONGEST str_offset)
19516 {
19517   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19518                                               abfd, str_offset,
19519                                               &dwarf2_per_objfile->str,
19520                                               "DW_FORM_strp", ".debug_str");
19521 }
19522
19523 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19524
19525 static const char *
19526 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19527                                      bfd *abfd, LONGEST str_offset)
19528 {
19529   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19530                                               abfd, str_offset,
19531                                               &dwarf2_per_objfile->line_str,
19532                                               "DW_FORM_line_strp",
19533                                               ".debug_line_str");
19534 }
19535
19536 /* Read a string at offset STR_OFFSET in the .debug_str section from
19537    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19538    the string consists of a single NUL byte, return NULL; otherwise
19539    return a pointer to the string.  */
19540
19541 static const char *
19542 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19543                                LONGEST str_offset)
19544 {
19545   dwarf2_read_section (objfile, &dwz->str);
19546
19547   if (dwz->str.buffer == NULL)
19548     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19549              "section [in module %s]"),
19550            bfd_get_filename (dwz->dwz_bfd));
19551   if (str_offset >= dwz->str.size)
19552     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19553              ".debug_str section [in module %s]"),
19554            bfd_get_filename (dwz->dwz_bfd));
19555   gdb_assert (HOST_CHAR_BIT == 8);
19556   if (dwz->str.buffer[str_offset] == '\0')
19557     return NULL;
19558   return (const char *) (dwz->str.buffer + str_offset);
19559 }
19560
19561 /* Return pointer to string at .debug_str offset as read from BUF.
19562    BUF is assumed to be in a compilation unit described by CU_HEADER.
19563    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19564
19565 static const char *
19566 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19567                       const gdb_byte *buf,
19568                       const struct comp_unit_head *cu_header,
19569                       unsigned int *bytes_read_ptr)
19570 {
19571   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19572
19573   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19574 }
19575
19576 /* Return pointer to string at .debug_line_str offset as read from BUF.
19577    BUF is assumed to be in a compilation unit described by CU_HEADER.
19578    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19579
19580 static const char *
19581 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19582                            bfd *abfd, const gdb_byte *buf,
19583                            const struct comp_unit_head *cu_header,
19584                            unsigned int *bytes_read_ptr)
19585 {
19586   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19587
19588   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19589                                               str_offset);
19590 }
19591
19592 ULONGEST
19593 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19594                           unsigned int *bytes_read_ptr)
19595 {
19596   ULONGEST result;
19597   unsigned int num_read;
19598   int shift;
19599   unsigned char byte;
19600
19601   result = 0;
19602   shift = 0;
19603   num_read = 0;
19604   while (1)
19605     {
19606       byte = bfd_get_8 (abfd, buf);
19607       buf++;
19608       num_read++;
19609       result |= ((ULONGEST) (byte & 127) << shift);
19610       if ((byte & 128) == 0)
19611         {
19612           break;
19613         }
19614       shift += 7;
19615     }
19616   *bytes_read_ptr = num_read;
19617   return result;
19618 }
19619
19620 static LONGEST
19621 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19622                     unsigned int *bytes_read_ptr)
19623 {
19624   LONGEST result;
19625   int shift, num_read;
19626   unsigned char byte;
19627
19628   result = 0;
19629   shift = 0;
19630   num_read = 0;
19631   while (1)
19632     {
19633       byte = bfd_get_8 (abfd, buf);
19634       buf++;
19635       num_read++;
19636       result |= ((LONGEST) (byte & 127) << shift);
19637       shift += 7;
19638       if ((byte & 128) == 0)
19639         {
19640           break;
19641         }
19642     }
19643   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19644     result |= -(((LONGEST) 1) << shift);
19645   *bytes_read_ptr = num_read;
19646   return result;
19647 }
19648
19649 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19650    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19651    ADDR_SIZE is the size of addresses from the CU header.  */
19652
19653 static CORE_ADDR
19654 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19655                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19656 {
19657   struct objfile *objfile = dwarf2_per_objfile->objfile;
19658   bfd *abfd = objfile->obfd;
19659   const gdb_byte *info_ptr;
19660
19661   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19662   if (dwarf2_per_objfile->addr.buffer == NULL)
19663     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19664            objfile_name (objfile));
19665   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19666     error (_("DW_FORM_addr_index pointing outside of "
19667              ".debug_addr section [in module %s]"),
19668            objfile_name (objfile));
19669   info_ptr = (dwarf2_per_objfile->addr.buffer
19670               + addr_base + addr_index * addr_size);
19671   if (addr_size == 4)
19672     return bfd_get_32 (abfd, info_ptr);
19673   else
19674     return bfd_get_64 (abfd, info_ptr);
19675 }
19676
19677 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19678
19679 static CORE_ADDR
19680 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19681 {
19682   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19683                             cu->addr_base, cu->header.addr_size);
19684 }
19685
19686 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19687
19688 static CORE_ADDR
19689 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19690                              unsigned int *bytes_read)
19691 {
19692   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19693   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19694
19695   return read_addr_index (cu, addr_index);
19696 }
19697
19698 /* Data structure to pass results from dwarf2_read_addr_index_reader
19699    back to dwarf2_read_addr_index.  */
19700
19701 struct dwarf2_read_addr_index_data
19702 {
19703   ULONGEST addr_base;
19704   int addr_size;
19705 };
19706
19707 /* die_reader_func for dwarf2_read_addr_index.  */
19708
19709 static void
19710 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19711                                const gdb_byte *info_ptr,
19712                                struct die_info *comp_unit_die,
19713                                int has_children,
19714                                void *data)
19715 {
19716   struct dwarf2_cu *cu = reader->cu;
19717   struct dwarf2_read_addr_index_data *aidata =
19718     (struct dwarf2_read_addr_index_data *) data;
19719
19720   aidata->addr_base = cu->addr_base;
19721   aidata->addr_size = cu->header.addr_size;
19722 }
19723
19724 /* Given an index in .debug_addr, fetch the value.
19725    NOTE: This can be called during dwarf expression evaluation,
19726    long after the debug information has been read, and thus per_cu->cu
19727    may no longer exist.  */
19728
19729 CORE_ADDR
19730 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19731                         unsigned int addr_index)
19732 {
19733   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19734   struct objfile *objfile = dwarf2_per_objfile->objfile;
19735   struct dwarf2_cu *cu = per_cu->cu;
19736   ULONGEST addr_base;
19737   int addr_size;
19738
19739   /* We need addr_base and addr_size.
19740      If we don't have PER_CU->cu, we have to get it.
19741      Nasty, but the alternative is storing the needed info in PER_CU,
19742      which at this point doesn't seem justified: it's not clear how frequently
19743      it would get used and it would increase the size of every PER_CU.
19744      Entry points like dwarf2_per_cu_addr_size do a similar thing
19745      so we're not in uncharted territory here.
19746      Alas we need to be a bit more complicated as addr_base is contained
19747      in the DIE.
19748
19749      We don't need to read the entire CU(/TU).
19750      We just need the header and top level die.
19751
19752      IWBN to use the aging mechanism to let us lazily later discard the CU.
19753      For now we skip this optimization.  */
19754
19755   if (cu != NULL)
19756     {
19757       addr_base = cu->addr_base;
19758       addr_size = cu->header.addr_size;
19759     }
19760   else
19761     {
19762       struct dwarf2_read_addr_index_data aidata;
19763
19764       /* Note: We can't use init_cutu_and_read_dies_simple here,
19765          we need addr_base.  */
19766       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19767                                dwarf2_read_addr_index_reader, &aidata);
19768       addr_base = aidata.addr_base;
19769       addr_size = aidata.addr_size;
19770     }
19771
19772   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19773                             addr_size);
19774 }
19775
19776 /* Given a DW_FORM_GNU_str_index, fetch the string.
19777    This is only used by the Fission support.  */
19778
19779 static const char *
19780 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19781 {
19782   struct dwarf2_cu *cu = reader->cu;
19783   struct dwarf2_per_objfile *dwarf2_per_objfile
19784     = cu->per_cu->dwarf2_per_objfile;
19785   struct objfile *objfile = dwarf2_per_objfile->objfile;
19786   const char *objf_name = objfile_name (objfile);
19787   bfd *abfd = objfile->obfd;
19788   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19789   struct dwarf2_section_info *str_offsets_section =
19790     &reader->dwo_file->sections.str_offsets;
19791   const gdb_byte *info_ptr;
19792   ULONGEST str_offset;
19793   static const char form_name[] = "DW_FORM_GNU_str_index";
19794
19795   dwarf2_read_section (objfile, str_section);
19796   dwarf2_read_section (objfile, str_offsets_section);
19797   if (str_section->buffer == NULL)
19798     error (_("%s used without .debug_str.dwo section"
19799              " in CU at offset %s [in module %s]"),
19800            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19801   if (str_offsets_section->buffer == NULL)
19802     error (_("%s used without .debug_str_offsets.dwo section"
19803              " in CU at offset %s [in module %s]"),
19804            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19805   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19806     error (_("%s pointing outside of .debug_str_offsets.dwo"
19807              " section in CU at offset %s [in module %s]"),
19808            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19809   info_ptr = (str_offsets_section->buffer
19810               + str_index * cu->header.offset_size);
19811   if (cu->header.offset_size == 4)
19812     str_offset = bfd_get_32 (abfd, info_ptr);
19813   else
19814     str_offset = bfd_get_64 (abfd, info_ptr);
19815   if (str_offset >= str_section->size)
19816     error (_("Offset from %s pointing outside of"
19817              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19818            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19819   return (const char *) (str_section->buffer + str_offset);
19820 }
19821
19822 /* Return the length of an LEB128 number in BUF.  */
19823
19824 static int
19825 leb128_size (const gdb_byte *buf)
19826 {
19827   const gdb_byte *begin = buf;
19828   gdb_byte byte;
19829
19830   while (1)
19831     {
19832       byte = *buf++;
19833       if ((byte & 128) == 0)
19834         return buf - begin;
19835     }
19836 }
19837
19838 static void
19839 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19840 {
19841   switch (lang)
19842     {
19843     case DW_LANG_C89:
19844     case DW_LANG_C99:
19845     case DW_LANG_C11:
19846     case DW_LANG_C:
19847     case DW_LANG_UPC:
19848       cu->language = language_c;
19849       break;
19850     case DW_LANG_Java:
19851     case DW_LANG_C_plus_plus:
19852     case DW_LANG_C_plus_plus_11:
19853     case DW_LANG_C_plus_plus_14:
19854       cu->language = language_cplus;
19855       break;
19856     case DW_LANG_D:
19857       cu->language = language_d;
19858       break;
19859     case DW_LANG_Fortran77:
19860     case DW_LANG_Fortran90:
19861     case DW_LANG_Fortran95:
19862     case DW_LANG_Fortran03:
19863     case DW_LANG_Fortran08:
19864       cu->language = language_fortran;
19865       break;
19866     case DW_LANG_Go:
19867       cu->language = language_go;
19868       break;
19869     case DW_LANG_Mips_Assembler:
19870       cu->language = language_asm;
19871       break;
19872     case DW_LANG_Ada83:
19873     case DW_LANG_Ada95:
19874       cu->language = language_ada;
19875       break;
19876     case DW_LANG_Modula2:
19877       cu->language = language_m2;
19878       break;
19879     case DW_LANG_Pascal83:
19880       cu->language = language_pascal;
19881       break;
19882     case DW_LANG_ObjC:
19883       cu->language = language_objc;
19884       break;
19885     case DW_LANG_Rust:
19886     case DW_LANG_Rust_old:
19887       cu->language = language_rust;
19888       break;
19889     case DW_LANG_Cobol74:
19890     case DW_LANG_Cobol85:
19891     default:
19892       cu->language = language_minimal;
19893       break;
19894     }
19895   cu->language_defn = language_def (cu->language);
19896 }
19897
19898 /* Return the named attribute or NULL if not there.  */
19899
19900 static struct attribute *
19901 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19902 {
19903   for (;;)
19904     {
19905       unsigned int i;
19906       struct attribute *spec = NULL;
19907
19908       for (i = 0; i < die->num_attrs; ++i)
19909         {
19910           if (die->attrs[i].name == name)
19911             return &die->attrs[i];
19912           if (die->attrs[i].name == DW_AT_specification
19913               || die->attrs[i].name == DW_AT_abstract_origin)
19914             spec = &die->attrs[i];
19915         }
19916
19917       if (!spec)
19918         break;
19919
19920       die = follow_die_ref (die, spec, &cu);
19921     }
19922
19923   return NULL;
19924 }
19925
19926 /* Return the named attribute or NULL if not there,
19927    but do not follow DW_AT_specification, etc.
19928    This is for use in contexts where we're reading .debug_types dies.
19929    Following DW_AT_specification, DW_AT_abstract_origin will take us
19930    back up the chain, and we want to go down.  */
19931
19932 static struct attribute *
19933 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19934 {
19935   unsigned int i;
19936
19937   for (i = 0; i < die->num_attrs; ++i)
19938     if (die->attrs[i].name == name)
19939       return &die->attrs[i];
19940
19941   return NULL;
19942 }
19943
19944 /* Return the string associated with a string-typed attribute, or NULL if it
19945    is either not found or is of an incorrect type.  */
19946
19947 static const char *
19948 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19949 {
19950   struct attribute *attr;
19951   const char *str = NULL;
19952
19953   attr = dwarf2_attr (die, name, cu);
19954
19955   if (attr != NULL)
19956     {
19957       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19958           || attr->form == DW_FORM_string
19959           || attr->form == DW_FORM_GNU_str_index
19960           || attr->form == DW_FORM_GNU_strp_alt)
19961         str = DW_STRING (attr);
19962       else
19963         complaint (&symfile_complaints,
19964                    _("string type expected for attribute %s for "
19965                      "DIE at %s in module %s"),
19966                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19967                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19968     }
19969
19970   return str;
19971 }
19972
19973 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19974    and holds a non-zero value.  This function should only be used for
19975    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19976
19977 static int
19978 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19979 {
19980   struct attribute *attr = dwarf2_attr (die, name, cu);
19981
19982   return (attr && DW_UNSND (attr));
19983 }
19984
19985 static int
19986 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19987 {
19988   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19989      which value is non-zero.  However, we have to be careful with
19990      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19991      (via dwarf2_flag_true_p) follows this attribute.  So we may
19992      end up accidently finding a declaration attribute that belongs
19993      to a different DIE referenced by the specification attribute,
19994      even though the given DIE does not have a declaration attribute.  */
19995   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19996           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19997 }
19998
19999 /* Return the die giving the specification for DIE, if there is
20000    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20001    containing the return value on output.  If there is no
20002    specification, but there is an abstract origin, that is
20003    returned.  */
20004
20005 static struct die_info *
20006 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20007 {
20008   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20009                                              *spec_cu);
20010
20011   if (spec_attr == NULL)
20012     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20013
20014   if (spec_attr == NULL)
20015     return NULL;
20016   else
20017     return follow_die_ref (die, spec_attr, spec_cu);
20018 }
20019
20020 /* Stub for free_line_header to match void * callback types.  */
20021
20022 static void
20023 free_line_header_voidp (void *arg)
20024 {
20025   struct line_header *lh = (struct line_header *) arg;
20026
20027   delete lh;
20028 }
20029
20030 void
20031 line_header::add_include_dir (const char *include_dir)
20032 {
20033   if (dwarf_line_debug >= 2)
20034     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20035                         include_dirs.size () + 1, include_dir);
20036
20037   include_dirs.push_back (include_dir);
20038 }
20039
20040 void
20041 line_header::add_file_name (const char *name,
20042                             dir_index d_index,
20043                             unsigned int mod_time,
20044                             unsigned int length)
20045 {
20046   if (dwarf_line_debug >= 2)
20047     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20048                         (unsigned) file_names.size () + 1, name);
20049
20050   file_names.emplace_back (name, d_index, mod_time, length);
20051 }
20052
20053 /* A convenience function to find the proper .debug_line section for a CU.  */
20054
20055 static struct dwarf2_section_info *
20056 get_debug_line_section (struct dwarf2_cu *cu)
20057 {
20058   struct dwarf2_section_info *section;
20059   struct dwarf2_per_objfile *dwarf2_per_objfile
20060     = cu->per_cu->dwarf2_per_objfile;
20061
20062   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20063      DWO file.  */
20064   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20065     section = &cu->dwo_unit->dwo_file->sections.line;
20066   else if (cu->per_cu->is_dwz)
20067     {
20068       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20069
20070       section = &dwz->line;
20071     }
20072   else
20073     section = &dwarf2_per_objfile->line;
20074
20075   return section;
20076 }
20077
20078 /* Read directory or file name entry format, starting with byte of
20079    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20080    entries count and the entries themselves in the described entry
20081    format.  */
20082
20083 static void
20084 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20085                         bfd *abfd, const gdb_byte **bufp,
20086                         struct line_header *lh,
20087                         const struct comp_unit_head *cu_header,
20088                         void (*callback) (struct line_header *lh,
20089                                           const char *name,
20090                                           dir_index d_index,
20091                                           unsigned int mod_time,
20092                                           unsigned int length))
20093 {
20094   gdb_byte format_count, formati;
20095   ULONGEST data_count, datai;
20096   const gdb_byte *buf = *bufp;
20097   const gdb_byte *format_header_data;
20098   unsigned int bytes_read;
20099
20100   format_count = read_1_byte (abfd, buf);
20101   buf += 1;
20102   format_header_data = buf;
20103   for (formati = 0; formati < format_count; formati++)
20104     {
20105       read_unsigned_leb128 (abfd, buf, &bytes_read);
20106       buf += bytes_read;
20107       read_unsigned_leb128 (abfd, buf, &bytes_read);
20108       buf += bytes_read;
20109     }
20110
20111   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20112   buf += bytes_read;
20113   for (datai = 0; datai < data_count; datai++)
20114     {
20115       const gdb_byte *format = format_header_data;
20116       struct file_entry fe;
20117
20118       for (formati = 0; formati < format_count; formati++)
20119         {
20120           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20121           format += bytes_read;
20122
20123           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20124           format += bytes_read;
20125
20126           gdb::optional<const char *> string;
20127           gdb::optional<unsigned int> uint;
20128
20129           switch (form)
20130             {
20131             case DW_FORM_string:
20132               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20133               buf += bytes_read;
20134               break;
20135
20136             case DW_FORM_line_strp:
20137               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20138                                                          abfd, buf,
20139                                                          cu_header,
20140                                                          &bytes_read));
20141               buf += bytes_read;
20142               break;
20143
20144             case DW_FORM_data1:
20145               uint.emplace (read_1_byte (abfd, buf));
20146               buf += 1;
20147               break;
20148
20149             case DW_FORM_data2:
20150               uint.emplace (read_2_bytes (abfd, buf));
20151               buf += 2;
20152               break;
20153
20154             case DW_FORM_data4:
20155               uint.emplace (read_4_bytes (abfd, buf));
20156               buf += 4;
20157               break;
20158
20159             case DW_FORM_data8:
20160               uint.emplace (read_8_bytes (abfd, buf));
20161               buf += 8;
20162               break;
20163
20164             case DW_FORM_udata:
20165               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20166               buf += bytes_read;
20167               break;
20168
20169             case DW_FORM_block:
20170               /* It is valid only for DW_LNCT_timestamp which is ignored by
20171                  current GDB.  */
20172               break;
20173             }
20174
20175           switch (content_type)
20176             {
20177             case DW_LNCT_path:
20178               if (string.has_value ())
20179                 fe.name = *string;
20180               break;
20181             case DW_LNCT_directory_index:
20182               if (uint.has_value ())
20183                 fe.d_index = (dir_index) *uint;
20184               break;
20185             case DW_LNCT_timestamp:
20186               if (uint.has_value ())
20187                 fe.mod_time = *uint;
20188               break;
20189             case DW_LNCT_size:
20190               if (uint.has_value ())
20191                 fe.length = *uint;
20192               break;
20193             case DW_LNCT_MD5:
20194               break;
20195             default:
20196               complaint (&symfile_complaints,
20197                          _("Unknown format content type %s"),
20198                          pulongest (content_type));
20199             }
20200         }
20201
20202       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20203     }
20204
20205   *bufp = buf;
20206 }
20207
20208 /* Read the statement program header starting at OFFSET in
20209    .debug_line, or .debug_line.dwo.  Return a pointer
20210    to a struct line_header, allocated using xmalloc.
20211    Returns NULL if there is a problem reading the header, e.g., if it
20212    has a version we don't understand.
20213
20214    NOTE: the strings in the include directory and file name tables of
20215    the returned object point into the dwarf line section buffer,
20216    and must not be freed.  */
20217
20218 static line_header_up
20219 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20220 {
20221   const gdb_byte *line_ptr;
20222   unsigned int bytes_read, offset_size;
20223   int i;
20224   const char *cur_dir, *cur_file;
20225   struct dwarf2_section_info *section;
20226   bfd *abfd;
20227   struct dwarf2_per_objfile *dwarf2_per_objfile
20228     = cu->per_cu->dwarf2_per_objfile;
20229
20230   section = get_debug_line_section (cu);
20231   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20232   if (section->buffer == NULL)
20233     {
20234       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20235         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20236       else
20237         complaint (&symfile_complaints, _("missing .debug_line section"));
20238       return 0;
20239     }
20240
20241   /* We can't do this until we know the section is non-empty.
20242      Only then do we know we have such a section.  */
20243   abfd = get_section_bfd_owner (section);
20244
20245   /* Make sure that at least there's room for the total_length field.
20246      That could be 12 bytes long, but we're just going to fudge that.  */
20247   if (to_underlying (sect_off) + 4 >= section->size)
20248     {
20249       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20250       return 0;
20251     }
20252
20253   line_header_up lh (new line_header ());
20254
20255   lh->sect_off = sect_off;
20256   lh->offset_in_dwz = cu->per_cu->is_dwz;
20257
20258   line_ptr = section->buffer + to_underlying (sect_off);
20259
20260   /* Read in the header.  */
20261   lh->total_length =
20262     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20263                                             &bytes_read, &offset_size);
20264   line_ptr += bytes_read;
20265   if (line_ptr + lh->total_length > (section->buffer + section->size))
20266     {
20267       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20268       return 0;
20269     }
20270   lh->statement_program_end = line_ptr + lh->total_length;
20271   lh->version = read_2_bytes (abfd, line_ptr);
20272   line_ptr += 2;
20273   if (lh->version > 5)
20274     {
20275       /* This is a version we don't understand.  The format could have
20276          changed in ways we don't handle properly so just punt.  */
20277       complaint (&symfile_complaints,
20278                  _("unsupported version in .debug_line section"));
20279       return NULL;
20280     }
20281   if (lh->version >= 5)
20282     {
20283       gdb_byte segment_selector_size;
20284
20285       /* Skip address size.  */
20286       read_1_byte (abfd, line_ptr);
20287       line_ptr += 1;
20288
20289       segment_selector_size = read_1_byte (abfd, line_ptr);
20290       line_ptr += 1;
20291       if (segment_selector_size != 0)
20292         {
20293           complaint (&symfile_complaints,
20294                      _("unsupported segment selector size %u "
20295                        "in .debug_line section"),
20296                      segment_selector_size);
20297           return NULL;
20298         }
20299     }
20300   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20301   line_ptr += offset_size;
20302   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20303   line_ptr += 1;
20304   if (lh->version >= 4)
20305     {
20306       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20307       line_ptr += 1;
20308     }
20309   else
20310     lh->maximum_ops_per_instruction = 1;
20311
20312   if (lh->maximum_ops_per_instruction == 0)
20313     {
20314       lh->maximum_ops_per_instruction = 1;
20315       complaint (&symfile_complaints,
20316                  _("invalid maximum_ops_per_instruction "
20317                    "in `.debug_line' section"));
20318     }
20319
20320   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20321   line_ptr += 1;
20322   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20323   line_ptr += 1;
20324   lh->line_range = read_1_byte (abfd, line_ptr);
20325   line_ptr += 1;
20326   lh->opcode_base = read_1_byte (abfd, line_ptr);
20327   line_ptr += 1;
20328   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20329
20330   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20331   for (i = 1; i < lh->opcode_base; ++i)
20332     {
20333       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20334       line_ptr += 1;
20335     }
20336
20337   if (lh->version >= 5)
20338     {
20339       /* Read directory table.  */
20340       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20341                               &cu->header,
20342                               [] (struct line_header *lh, const char *name,
20343                                   dir_index d_index, unsigned int mod_time,
20344                                   unsigned int length)
20345         {
20346           lh->add_include_dir (name);
20347         });
20348
20349       /* Read file name table.  */
20350       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20351                               &cu->header,
20352                               [] (struct line_header *lh, const char *name,
20353                                   dir_index d_index, unsigned int mod_time,
20354                                   unsigned int length)
20355         {
20356           lh->add_file_name (name, d_index, mod_time, length);
20357         });
20358     }
20359   else
20360     {
20361       /* Read directory table.  */
20362       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20363         {
20364           line_ptr += bytes_read;
20365           lh->add_include_dir (cur_dir);
20366         }
20367       line_ptr += bytes_read;
20368
20369       /* Read file name table.  */
20370       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20371         {
20372           unsigned int mod_time, length;
20373           dir_index d_index;
20374
20375           line_ptr += bytes_read;
20376           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20377           line_ptr += bytes_read;
20378           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20379           line_ptr += bytes_read;
20380           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20381           line_ptr += bytes_read;
20382
20383           lh->add_file_name (cur_file, d_index, mod_time, length);
20384         }
20385       line_ptr += bytes_read;
20386     }
20387   lh->statement_program_start = line_ptr;
20388
20389   if (line_ptr > (section->buffer + section->size))
20390     complaint (&symfile_complaints,
20391                _("line number info header doesn't "
20392                  "fit in `.debug_line' section"));
20393
20394   return lh;
20395 }
20396
20397 /* Subroutine of dwarf_decode_lines to simplify it.
20398    Return the file name of the psymtab for included file FILE_INDEX
20399    in line header LH of PST.
20400    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20401    If space for the result is malloc'd, *NAME_HOLDER will be set.
20402    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20403
20404 static const char *
20405 psymtab_include_file_name (const struct line_header *lh, int file_index,
20406                            const struct partial_symtab *pst,
20407                            const char *comp_dir,
20408                            gdb::unique_xmalloc_ptr<char> *name_holder)
20409 {
20410   const file_entry &fe = lh->file_names[file_index];
20411   const char *include_name = fe.name;
20412   const char *include_name_to_compare = include_name;
20413   const char *pst_filename;
20414   int file_is_pst;
20415
20416   const char *dir_name = fe.include_dir (lh);
20417
20418   gdb::unique_xmalloc_ptr<char> hold_compare;
20419   if (!IS_ABSOLUTE_PATH (include_name)
20420       && (dir_name != NULL || comp_dir != NULL))
20421     {
20422       /* Avoid creating a duplicate psymtab for PST.
20423          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20424          Before we do the comparison, however, we need to account
20425          for DIR_NAME and COMP_DIR.
20426          First prepend dir_name (if non-NULL).  If we still don't
20427          have an absolute path prepend comp_dir (if non-NULL).
20428          However, the directory we record in the include-file's
20429          psymtab does not contain COMP_DIR (to match the
20430          corresponding symtab(s)).
20431
20432          Example:
20433
20434          bash$ cd /tmp
20435          bash$ gcc -g ./hello.c
20436          include_name = "hello.c"
20437          dir_name = "."
20438          DW_AT_comp_dir = comp_dir = "/tmp"
20439          DW_AT_name = "./hello.c"
20440
20441       */
20442
20443       if (dir_name != NULL)
20444         {
20445           name_holder->reset (concat (dir_name, SLASH_STRING,
20446                                       include_name, (char *) NULL));
20447           include_name = name_holder->get ();
20448           include_name_to_compare = include_name;
20449         }
20450       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20451         {
20452           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20453                                       include_name, (char *) NULL));
20454           include_name_to_compare = hold_compare.get ();
20455         }
20456     }
20457
20458   pst_filename = pst->filename;
20459   gdb::unique_xmalloc_ptr<char> copied_name;
20460   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20461     {
20462       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20463                                  pst_filename, (char *) NULL));
20464       pst_filename = copied_name.get ();
20465     }
20466
20467   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20468
20469   if (file_is_pst)
20470     return NULL;
20471   return include_name;
20472 }
20473
20474 /* State machine to track the state of the line number program.  */
20475
20476 class lnp_state_machine
20477 {
20478 public:
20479   /* Initialize a machine state for the start of a line number
20480      program.  */
20481   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20482
20483   file_entry *current_file ()
20484   {
20485     /* lh->file_names is 0-based, but the file name numbers in the
20486        statement program are 1-based.  */
20487     return m_line_header->file_name_at (m_file);
20488   }
20489
20490   /* Record the line in the state machine.  END_SEQUENCE is true if
20491      we're processing the end of a sequence.  */
20492   void record_line (bool end_sequence);
20493
20494   /* Check address and if invalid nop-out the rest of the lines in this
20495      sequence.  */
20496   void check_line_address (struct dwarf2_cu *cu,
20497                            const gdb_byte *line_ptr,
20498                            CORE_ADDR lowpc, CORE_ADDR address);
20499
20500   void handle_set_discriminator (unsigned int discriminator)
20501   {
20502     m_discriminator = discriminator;
20503     m_line_has_non_zero_discriminator |= discriminator != 0;
20504   }
20505
20506   /* Handle DW_LNE_set_address.  */
20507   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20508   {
20509     m_op_index = 0;
20510     address += baseaddr;
20511     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20512   }
20513
20514   /* Handle DW_LNS_advance_pc.  */
20515   void handle_advance_pc (CORE_ADDR adjust);
20516
20517   /* Handle a special opcode.  */
20518   void handle_special_opcode (unsigned char op_code);
20519
20520   /* Handle DW_LNS_advance_line.  */
20521   void handle_advance_line (int line_delta)
20522   {
20523     advance_line (line_delta);
20524   }
20525
20526   /* Handle DW_LNS_set_file.  */
20527   void handle_set_file (file_name_index file);
20528
20529   /* Handle DW_LNS_negate_stmt.  */
20530   void handle_negate_stmt ()
20531   {
20532     m_is_stmt = !m_is_stmt;
20533   }
20534
20535   /* Handle DW_LNS_const_add_pc.  */
20536   void handle_const_add_pc ();
20537
20538   /* Handle DW_LNS_fixed_advance_pc.  */
20539   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20540   {
20541     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20542     m_op_index = 0;
20543   }
20544
20545   /* Handle DW_LNS_copy.  */
20546   void handle_copy ()
20547   {
20548     record_line (false);
20549     m_discriminator = 0;
20550   }
20551
20552   /* Handle DW_LNE_end_sequence.  */
20553   void handle_end_sequence ()
20554   {
20555     m_record_line_callback = ::record_line;
20556   }
20557
20558 private:
20559   /* Advance the line by LINE_DELTA.  */
20560   void advance_line (int line_delta)
20561   {
20562     m_line += line_delta;
20563
20564     if (line_delta != 0)
20565       m_line_has_non_zero_discriminator = m_discriminator != 0;
20566   }
20567
20568   gdbarch *m_gdbarch;
20569
20570   /* True if we're recording lines.
20571      Otherwise we're building partial symtabs and are just interested in
20572      finding include files mentioned by the line number program.  */
20573   bool m_record_lines_p;
20574
20575   /* The line number header.  */
20576   line_header *m_line_header;
20577
20578   /* These are part of the standard DWARF line number state machine,
20579      and initialized according to the DWARF spec.  */
20580
20581   unsigned char m_op_index = 0;
20582   /* The line table index (1-based) of the current file.  */
20583   file_name_index m_file = (file_name_index) 1;
20584   unsigned int m_line = 1;
20585
20586   /* These are initialized in the constructor.  */
20587
20588   CORE_ADDR m_address;
20589   bool m_is_stmt;
20590   unsigned int m_discriminator;
20591
20592   /* Additional bits of state we need to track.  */
20593
20594   /* The last file that we called dwarf2_start_subfile for.
20595      This is only used for TLLs.  */
20596   unsigned int m_last_file = 0;
20597   /* The last file a line number was recorded for.  */
20598   struct subfile *m_last_subfile = NULL;
20599
20600   /* The function to call to record a line.  */
20601   record_line_ftype *m_record_line_callback = NULL;
20602
20603   /* The last line number that was recorded, used to coalesce
20604      consecutive entries for the same line.  This can happen, for
20605      example, when discriminators are present.  PR 17276.  */
20606   unsigned int m_last_line = 0;
20607   bool m_line_has_non_zero_discriminator = false;
20608 };
20609
20610 void
20611 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20612 {
20613   CORE_ADDR addr_adj = (((m_op_index + adjust)
20614                          / m_line_header->maximum_ops_per_instruction)
20615                         * m_line_header->minimum_instruction_length);
20616   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20617   m_op_index = ((m_op_index + adjust)
20618                 % m_line_header->maximum_ops_per_instruction);
20619 }
20620
20621 void
20622 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20623 {
20624   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20625   CORE_ADDR addr_adj = (((m_op_index
20626                           + (adj_opcode / m_line_header->line_range))
20627                          / m_line_header->maximum_ops_per_instruction)
20628                         * m_line_header->minimum_instruction_length);
20629   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20630   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20631                 % m_line_header->maximum_ops_per_instruction);
20632
20633   int line_delta = (m_line_header->line_base
20634                     + (adj_opcode % m_line_header->line_range));
20635   advance_line (line_delta);
20636   record_line (false);
20637   m_discriminator = 0;
20638 }
20639
20640 void
20641 lnp_state_machine::handle_set_file (file_name_index file)
20642 {
20643   m_file = file;
20644
20645   const file_entry *fe = current_file ();
20646   if (fe == NULL)
20647     dwarf2_debug_line_missing_file_complaint ();
20648   else if (m_record_lines_p)
20649     {
20650       const char *dir = fe->include_dir (m_line_header);
20651
20652       m_last_subfile = current_subfile;
20653       m_line_has_non_zero_discriminator = m_discriminator != 0;
20654       dwarf2_start_subfile (fe->name, dir);
20655     }
20656 }
20657
20658 void
20659 lnp_state_machine::handle_const_add_pc ()
20660 {
20661   CORE_ADDR adjust
20662     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20663
20664   CORE_ADDR addr_adj
20665     = (((m_op_index + adjust)
20666         / m_line_header->maximum_ops_per_instruction)
20667        * m_line_header->minimum_instruction_length);
20668
20669   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20670   m_op_index = ((m_op_index + adjust)
20671                 % m_line_header->maximum_ops_per_instruction);
20672 }
20673
20674 /* Ignore this record_line request.  */
20675
20676 static void
20677 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20678 {
20679   return;
20680 }
20681
20682 /* Return non-zero if we should add LINE to the line number table.
20683    LINE is the line to add, LAST_LINE is the last line that was added,
20684    LAST_SUBFILE is the subfile for LAST_LINE.
20685    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20686    had a non-zero discriminator.
20687
20688    We have to be careful in the presence of discriminators.
20689    E.g., for this line:
20690
20691      for (i = 0; i < 100000; i++);
20692
20693    clang can emit four line number entries for that one line,
20694    each with a different discriminator.
20695    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20696
20697    However, we want gdb to coalesce all four entries into one.
20698    Otherwise the user could stepi into the middle of the line and
20699    gdb would get confused about whether the pc really was in the
20700    middle of the line.
20701
20702    Things are further complicated by the fact that two consecutive
20703    line number entries for the same line is a heuristic used by gcc
20704    to denote the end of the prologue.  So we can't just discard duplicate
20705    entries, we have to be selective about it.  The heuristic we use is
20706    that we only collapse consecutive entries for the same line if at least
20707    one of those entries has a non-zero discriminator.  PR 17276.
20708
20709    Note: Addresses in the line number state machine can never go backwards
20710    within one sequence, thus this coalescing is ok.  */
20711
20712 static int
20713 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20714                      int line_has_non_zero_discriminator,
20715                      struct subfile *last_subfile)
20716 {
20717   if (current_subfile != last_subfile)
20718     return 1;
20719   if (line != last_line)
20720     return 1;
20721   /* Same line for the same file that we've seen already.
20722      As a last check, for pr 17276, only record the line if the line
20723      has never had a non-zero discriminator.  */
20724   if (!line_has_non_zero_discriminator)
20725     return 1;
20726   return 0;
20727 }
20728
20729 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20730    in the line table of subfile SUBFILE.  */
20731
20732 static void
20733 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20734                      unsigned int line, CORE_ADDR address,
20735                      record_line_ftype p_record_line)
20736 {
20737   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20738
20739   if (dwarf_line_debug)
20740     {
20741       fprintf_unfiltered (gdb_stdlog,
20742                           "Recording line %u, file %s, address %s\n",
20743                           line, lbasename (subfile->name),
20744                           paddress (gdbarch, address));
20745     }
20746
20747   (*p_record_line) (subfile, line, addr);
20748 }
20749
20750 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20751    Mark the end of a set of line number records.
20752    The arguments are the same as for dwarf_record_line_1.
20753    If SUBFILE is NULL the request is ignored.  */
20754
20755 static void
20756 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20757                    CORE_ADDR address, record_line_ftype p_record_line)
20758 {
20759   if (subfile == NULL)
20760     return;
20761
20762   if (dwarf_line_debug)
20763     {
20764       fprintf_unfiltered (gdb_stdlog,
20765                           "Finishing current line, file %s, address %s\n",
20766                           lbasename (subfile->name),
20767                           paddress (gdbarch, address));
20768     }
20769
20770   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20771 }
20772
20773 void
20774 lnp_state_machine::record_line (bool end_sequence)
20775 {
20776   if (dwarf_line_debug)
20777     {
20778       fprintf_unfiltered (gdb_stdlog,
20779                           "Processing actual line %u: file %u,"
20780                           " address %s, is_stmt %u, discrim %u\n",
20781                           m_line, to_underlying (m_file),
20782                           paddress (m_gdbarch, m_address),
20783                           m_is_stmt, m_discriminator);
20784     }
20785
20786   file_entry *fe = current_file ();
20787
20788   if (fe == NULL)
20789     dwarf2_debug_line_missing_file_complaint ();
20790   /* For now we ignore lines not starting on an instruction boundary.
20791      But not when processing end_sequence for compatibility with the
20792      previous version of the code.  */
20793   else if (m_op_index == 0 || end_sequence)
20794     {
20795       fe->included_p = 1;
20796       if (m_record_lines_p && m_is_stmt)
20797         {
20798           if (m_last_subfile != current_subfile || end_sequence)
20799             {
20800               dwarf_finish_line (m_gdbarch, m_last_subfile,
20801                                  m_address, m_record_line_callback);
20802             }
20803
20804           if (!end_sequence)
20805             {
20806               if (dwarf_record_line_p (m_line, m_last_line,
20807                                        m_line_has_non_zero_discriminator,
20808                                        m_last_subfile))
20809                 {
20810                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20811                                        m_line, m_address,
20812                                        m_record_line_callback);
20813                 }
20814               m_last_subfile = current_subfile;
20815               m_last_line = m_line;
20816             }
20817         }
20818     }
20819 }
20820
20821 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20822                                       bool record_lines_p)
20823 {
20824   m_gdbarch = arch;
20825   m_record_lines_p = record_lines_p;
20826   m_line_header = lh;
20827
20828   m_record_line_callback = ::record_line;
20829
20830   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20831      was a line entry for it so that the backend has a chance to adjust it
20832      and also record it in case it needs it.  This is currently used by MIPS
20833      code, cf. `mips_adjust_dwarf2_line'.  */
20834   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20835   m_is_stmt = lh->default_is_stmt;
20836   m_discriminator = 0;
20837 }
20838
20839 void
20840 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20841                                        const gdb_byte *line_ptr,
20842                                        CORE_ADDR lowpc, CORE_ADDR address)
20843 {
20844   /* If address < lowpc then it's not a usable value, it's outside the
20845      pc range of the CU.  However, we restrict the test to only address
20846      values of zero to preserve GDB's previous behaviour which is to
20847      handle the specific case of a function being GC'd by the linker.  */
20848
20849   if (address == 0 && address < lowpc)
20850     {
20851       /* This line table is for a function which has been
20852          GCd by the linker.  Ignore it.  PR gdb/12528 */
20853
20854       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20855       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20856
20857       complaint (&symfile_complaints,
20858                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20859                  line_offset, objfile_name (objfile));
20860       m_record_line_callback = noop_record_line;
20861       /* Note: record_line_callback is left as noop_record_line until
20862          we see DW_LNE_end_sequence.  */
20863     }
20864 }
20865
20866 /* Subroutine of dwarf_decode_lines to simplify it.
20867    Process the line number information in LH.
20868    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20869    program in order to set included_p for every referenced header.  */
20870
20871 static void
20872 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20873                       const int decode_for_pst_p, CORE_ADDR lowpc)
20874 {
20875   const gdb_byte *line_ptr, *extended_end;
20876   const gdb_byte *line_end;
20877   unsigned int bytes_read, extended_len;
20878   unsigned char op_code, extended_op;
20879   CORE_ADDR baseaddr;
20880   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20881   bfd *abfd = objfile->obfd;
20882   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20883   /* True if we're recording line info (as opposed to building partial
20884      symtabs and just interested in finding include files mentioned by
20885      the line number program).  */
20886   bool record_lines_p = !decode_for_pst_p;
20887
20888   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20889
20890   line_ptr = lh->statement_program_start;
20891   line_end = lh->statement_program_end;
20892
20893   /* Read the statement sequences until there's nothing left.  */
20894   while (line_ptr < line_end)
20895     {
20896       /* The DWARF line number program state machine.  Reset the state
20897          machine at the start of each sequence.  */
20898       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20899       bool end_sequence = false;
20900
20901       if (record_lines_p)
20902         {
20903           /* Start a subfile for the current file of the state
20904              machine.  */
20905           const file_entry *fe = state_machine.current_file ();
20906
20907           if (fe != NULL)
20908             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20909         }
20910
20911       /* Decode the table.  */
20912       while (line_ptr < line_end && !end_sequence)
20913         {
20914           op_code = read_1_byte (abfd, line_ptr);
20915           line_ptr += 1;
20916
20917           if (op_code >= lh->opcode_base)
20918             {
20919               /* Special opcode.  */
20920               state_machine.handle_special_opcode (op_code);
20921             }
20922           else switch (op_code)
20923             {
20924             case DW_LNS_extended_op:
20925               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20926                                                    &bytes_read);
20927               line_ptr += bytes_read;
20928               extended_end = line_ptr + extended_len;
20929               extended_op = read_1_byte (abfd, line_ptr);
20930               line_ptr += 1;
20931               switch (extended_op)
20932                 {
20933                 case DW_LNE_end_sequence:
20934                   state_machine.handle_end_sequence ();
20935                   end_sequence = true;
20936                   break;
20937                 case DW_LNE_set_address:
20938                   {
20939                     CORE_ADDR address
20940                       = read_address (abfd, line_ptr, cu, &bytes_read);
20941                     line_ptr += bytes_read;
20942
20943                     state_machine.check_line_address (cu, line_ptr,
20944                                                       lowpc, address);
20945                     state_machine.handle_set_address (baseaddr, address);
20946                   }
20947                   break;
20948                 case DW_LNE_define_file:
20949                   {
20950                     const char *cur_file;
20951                     unsigned int mod_time, length;
20952                     dir_index dindex;
20953
20954                     cur_file = read_direct_string (abfd, line_ptr,
20955                                                    &bytes_read);
20956                     line_ptr += bytes_read;
20957                     dindex = (dir_index)
20958                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20959                     line_ptr += bytes_read;
20960                     mod_time =
20961                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20962                     line_ptr += bytes_read;
20963                     length =
20964                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20965                     line_ptr += bytes_read;
20966                     lh->add_file_name (cur_file, dindex, mod_time, length);
20967                   }
20968                   break;
20969                 case DW_LNE_set_discriminator:
20970                   {
20971                     /* The discriminator is not interesting to the
20972                        debugger; just ignore it.  We still need to
20973                        check its value though:
20974                        if there are consecutive entries for the same
20975                        (non-prologue) line we want to coalesce them.
20976                        PR 17276.  */
20977                     unsigned int discr
20978                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20979                     line_ptr += bytes_read;
20980
20981                     state_machine.handle_set_discriminator (discr);
20982                   }
20983                   break;
20984                 default:
20985                   complaint (&symfile_complaints,
20986                              _("mangled .debug_line section"));
20987                   return;
20988                 }
20989               /* Make sure that we parsed the extended op correctly.  If e.g.
20990                  we expected a different address size than the producer used,
20991                  we may have read the wrong number of bytes.  */
20992               if (line_ptr != extended_end)
20993                 {
20994                   complaint (&symfile_complaints,
20995                              _("mangled .debug_line section"));
20996                   return;
20997                 }
20998               break;
20999             case DW_LNS_copy:
21000               state_machine.handle_copy ();
21001               break;
21002             case DW_LNS_advance_pc:
21003               {
21004                 CORE_ADDR adjust
21005                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21006                 line_ptr += bytes_read;
21007
21008                 state_machine.handle_advance_pc (adjust);
21009               }
21010               break;
21011             case DW_LNS_advance_line:
21012               {
21013                 int line_delta
21014                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21015                 line_ptr += bytes_read;
21016
21017                 state_machine.handle_advance_line (line_delta);
21018               }
21019               break;
21020             case DW_LNS_set_file:
21021               {
21022                 file_name_index file
21023                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21024                                                             &bytes_read);
21025                 line_ptr += bytes_read;
21026
21027                 state_machine.handle_set_file (file);
21028               }
21029               break;
21030             case DW_LNS_set_column:
21031               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21032               line_ptr += bytes_read;
21033               break;
21034             case DW_LNS_negate_stmt:
21035               state_machine.handle_negate_stmt ();
21036               break;
21037             case DW_LNS_set_basic_block:
21038               break;
21039             /* Add to the address register of the state machine the
21040                address increment value corresponding to special opcode
21041                255.  I.e., this value is scaled by the minimum
21042                instruction length since special opcode 255 would have
21043                scaled the increment.  */
21044             case DW_LNS_const_add_pc:
21045               state_machine.handle_const_add_pc ();
21046               break;
21047             case DW_LNS_fixed_advance_pc:
21048               {
21049                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21050                 line_ptr += 2;
21051
21052                 state_machine.handle_fixed_advance_pc (addr_adj);
21053               }
21054               break;
21055             default:
21056               {
21057                 /* Unknown standard opcode, ignore it.  */
21058                 int i;
21059
21060                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21061                   {
21062                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21063                     line_ptr += bytes_read;
21064                   }
21065               }
21066             }
21067         }
21068
21069       if (!end_sequence)
21070         dwarf2_debug_line_missing_end_sequence_complaint ();
21071
21072       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21073          in which case we still finish recording the last line).  */
21074       state_machine.record_line (true);
21075     }
21076 }
21077
21078 /* Decode the Line Number Program (LNP) for the given line_header
21079    structure and CU.  The actual information extracted and the type
21080    of structures created from the LNP depends on the value of PST.
21081
21082    1. If PST is NULL, then this procedure uses the data from the program
21083       to create all necessary symbol tables, and their linetables.
21084
21085    2. If PST is not NULL, this procedure reads the program to determine
21086       the list of files included by the unit represented by PST, and
21087       builds all the associated partial symbol tables.
21088
21089    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21090    It is used for relative paths in the line table.
21091    NOTE: When processing partial symtabs (pst != NULL),
21092    comp_dir == pst->dirname.
21093
21094    NOTE: It is important that psymtabs have the same file name (via strcmp)
21095    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21096    symtab we don't use it in the name of the psymtabs we create.
21097    E.g. expand_line_sal requires this when finding psymtabs to expand.
21098    A good testcase for this is mb-inline.exp.
21099
21100    LOWPC is the lowest address in CU (or 0 if not known).
21101
21102    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21103    for its PC<->lines mapping information.  Otherwise only the filename
21104    table is read in.  */
21105
21106 static void
21107 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21108                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21109                     CORE_ADDR lowpc, int decode_mapping)
21110 {
21111   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21112   const int decode_for_pst_p = (pst != NULL);
21113
21114   if (decode_mapping)
21115     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21116
21117   if (decode_for_pst_p)
21118     {
21119       int file_index;
21120
21121       /* Now that we're done scanning the Line Header Program, we can
21122          create the psymtab of each included file.  */
21123       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21124         if (lh->file_names[file_index].included_p == 1)
21125           {
21126             gdb::unique_xmalloc_ptr<char> name_holder;
21127             const char *include_name =
21128               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21129                                          &name_holder);
21130             if (include_name != NULL)
21131               dwarf2_create_include_psymtab (include_name, pst, objfile);
21132           }
21133     }
21134   else
21135     {
21136       /* Make sure a symtab is created for every file, even files
21137          which contain only variables (i.e. no code with associated
21138          line numbers).  */
21139       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21140       int i;
21141
21142       for (i = 0; i < lh->file_names.size (); i++)
21143         {
21144           file_entry &fe = lh->file_names[i];
21145
21146           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21147
21148           if (current_subfile->symtab == NULL)
21149             {
21150               current_subfile->symtab
21151                 = allocate_symtab (cust, current_subfile->name);
21152             }
21153           fe.symtab = current_subfile->symtab;
21154         }
21155     }
21156 }
21157
21158 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21159    DIRNAME the name of the source directory which contains FILENAME
21160    or NULL if not known.
21161    This routine tries to keep line numbers from identical absolute and
21162    relative file names in a common subfile.
21163
21164    Using the `list' example from the GDB testsuite, which resides in
21165    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21166    of /srcdir/list0.c yields the following debugging information for list0.c:
21167
21168    DW_AT_name:          /srcdir/list0.c
21169    DW_AT_comp_dir:      /compdir
21170    files.files[0].name: list0.h
21171    files.files[0].dir:  /srcdir
21172    files.files[1].name: list0.c
21173    files.files[1].dir:  /srcdir
21174
21175    The line number information for list0.c has to end up in a single
21176    subfile, so that `break /srcdir/list0.c:1' works as expected.
21177    start_subfile will ensure that this happens provided that we pass the
21178    concatenation of files.files[1].dir and files.files[1].name as the
21179    subfile's name.  */
21180
21181 static void
21182 dwarf2_start_subfile (const char *filename, const char *dirname)
21183 {
21184   char *copy = NULL;
21185
21186   /* In order not to lose the line information directory,
21187      we concatenate it to the filename when it makes sense.
21188      Note that the Dwarf3 standard says (speaking of filenames in line
21189      information): ``The directory index is ignored for file names
21190      that represent full path names''.  Thus ignoring dirname in the
21191      `else' branch below isn't an issue.  */
21192
21193   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21194     {
21195       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21196       filename = copy;
21197     }
21198
21199   start_subfile (filename);
21200
21201   if (copy != NULL)
21202     xfree (copy);
21203 }
21204
21205 /* Start a symtab for DWARF.
21206    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21207
21208 static struct compunit_symtab *
21209 dwarf2_start_symtab (struct dwarf2_cu *cu,
21210                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21211 {
21212   struct compunit_symtab *cust
21213     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21214                     low_pc, cu->language);
21215
21216   record_debugformat ("DWARF 2");
21217   record_producer (cu->producer);
21218
21219   /* We assume that we're processing GCC output.  */
21220   processing_gcc_compilation = 2;
21221
21222   cu->processing_has_namespace_info = 0;
21223
21224   return cust;
21225 }
21226
21227 static void
21228 var_decode_location (struct attribute *attr, struct symbol *sym,
21229                      struct dwarf2_cu *cu)
21230 {
21231   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21232   struct comp_unit_head *cu_header = &cu->header;
21233
21234   /* NOTE drow/2003-01-30: There used to be a comment and some special
21235      code here to turn a symbol with DW_AT_external and a
21236      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21237      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21238      with some versions of binutils) where shared libraries could have
21239      relocations against symbols in their debug information - the
21240      minimal symbol would have the right address, but the debug info
21241      would not.  It's no longer necessary, because we will explicitly
21242      apply relocations when we read in the debug information now.  */
21243
21244   /* A DW_AT_location attribute with no contents indicates that a
21245      variable has been optimized away.  */
21246   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21247     {
21248       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21249       return;
21250     }
21251
21252   /* Handle one degenerate form of location expression specially, to
21253      preserve GDB's previous behavior when section offsets are
21254      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21255      then mark this symbol as LOC_STATIC.  */
21256
21257   if (attr_form_is_block (attr)
21258       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21259            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21260           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21261               && (DW_BLOCK (attr)->size
21262                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21263     {
21264       unsigned int dummy;
21265
21266       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21267         SYMBOL_VALUE_ADDRESS (sym) =
21268           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21269       else
21270         SYMBOL_VALUE_ADDRESS (sym) =
21271           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21272       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21273       fixup_symbol_section (sym, objfile);
21274       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21275                                               SYMBOL_SECTION (sym));
21276       return;
21277     }
21278
21279   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21280      expression evaluator, and use LOC_COMPUTED only when necessary
21281      (i.e. when the value of a register or memory location is
21282      referenced, or a thread-local block, etc.).  Then again, it might
21283      not be worthwhile.  I'm assuming that it isn't unless performance
21284      or memory numbers show me otherwise.  */
21285
21286   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21287
21288   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21289     cu->has_loclist = 1;
21290 }
21291
21292 /* Given a pointer to a DWARF information entry, figure out if we need
21293    to make a symbol table entry for it, and if so, create a new entry
21294    and return a pointer to it.
21295    If TYPE is NULL, determine symbol type from the die, otherwise
21296    used the passed type.
21297    If SPACE is not NULL, use it to hold the new symbol.  If it is
21298    NULL, allocate a new symbol on the objfile's obstack.  */
21299
21300 static struct symbol *
21301 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21302             struct symbol *space)
21303 {
21304   struct dwarf2_per_objfile *dwarf2_per_objfile
21305     = cu->per_cu->dwarf2_per_objfile;
21306   struct objfile *objfile = dwarf2_per_objfile->objfile;
21307   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21308   struct symbol *sym = NULL;
21309   const char *name;
21310   struct attribute *attr = NULL;
21311   struct attribute *attr2 = NULL;
21312   CORE_ADDR baseaddr;
21313   struct pending **list_to_add = NULL;
21314
21315   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21316
21317   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21318
21319   name = dwarf2_name (die, cu);
21320   if (name)
21321     {
21322       const char *linkagename;
21323       int suppress_add = 0;
21324
21325       if (space)
21326         sym = space;
21327       else
21328         sym = allocate_symbol (objfile);
21329       OBJSTAT (objfile, n_syms++);
21330
21331       /* Cache this symbol's name and the name's demangled form (if any).  */
21332       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21333       linkagename = dwarf2_physname (name, die, cu);
21334       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21335
21336       /* Fortran does not have mangling standard and the mangling does differ
21337          between gfortran, iFort etc.  */
21338       if (cu->language == language_fortran
21339           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21340         symbol_set_demangled_name (&(sym->ginfo),
21341                                    dwarf2_full_name (name, die, cu),
21342                                    NULL);
21343
21344       /* Default assumptions.
21345          Use the passed type or decode it from the die.  */
21346       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21347       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21348       if (type != NULL)
21349         SYMBOL_TYPE (sym) = type;
21350       else
21351         SYMBOL_TYPE (sym) = die_type (die, cu);
21352       attr = dwarf2_attr (die,
21353                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21354                           cu);
21355       if (attr)
21356         {
21357           SYMBOL_LINE (sym) = DW_UNSND (attr);
21358         }
21359
21360       attr = dwarf2_attr (die,
21361                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21362                           cu);
21363       if (attr)
21364         {
21365           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21366           struct file_entry *fe;
21367
21368           if (cu->line_header != NULL)
21369             fe = cu->line_header->file_name_at (file_index);
21370           else
21371             fe = NULL;
21372
21373           if (fe == NULL)
21374             complaint (&symfile_complaints,
21375                        _("file index out of range"));
21376           else
21377             symbol_set_symtab (sym, fe->symtab);
21378         }
21379
21380       switch (die->tag)
21381         {
21382         case DW_TAG_label:
21383           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21384           if (attr)
21385             {
21386               CORE_ADDR addr;
21387
21388               addr = attr_value_as_address (attr);
21389               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21390               SYMBOL_VALUE_ADDRESS (sym) = addr;
21391             }
21392           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21393           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21394           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21395           add_symbol_to_list (sym, cu->list_in_scope);
21396           break;
21397         case DW_TAG_subprogram:
21398           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21399              finish_block.  */
21400           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21401           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21402           if ((attr2 && (DW_UNSND (attr2) != 0))
21403               || cu->language == language_ada)
21404             {
21405               /* Subprograms marked external are stored as a global symbol.
21406                  Ada subprograms, whether marked external or not, are always
21407                  stored as a global symbol, because we want to be able to
21408                  access them globally.  For instance, we want to be able
21409                  to break on a nested subprogram without having to
21410                  specify the context.  */
21411               list_to_add = &global_symbols;
21412             }
21413           else
21414             {
21415               list_to_add = cu->list_in_scope;
21416             }
21417           break;
21418         case DW_TAG_inlined_subroutine:
21419           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21420              finish_block.  */
21421           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21422           SYMBOL_INLINED (sym) = 1;
21423           list_to_add = cu->list_in_scope;
21424           break;
21425         case DW_TAG_template_value_param:
21426           suppress_add = 1;
21427           /* Fall through.  */
21428         case DW_TAG_constant:
21429         case DW_TAG_variable:
21430         case DW_TAG_member:
21431           /* Compilation with minimal debug info may result in
21432              variables with missing type entries.  Change the
21433              misleading `void' type to something sensible.  */
21434           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21435             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21436
21437           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21438           /* In the case of DW_TAG_member, we should only be called for
21439              static const members.  */
21440           if (die->tag == DW_TAG_member)
21441             {
21442               /* dwarf2_add_field uses die_is_declaration,
21443                  so we do the same.  */
21444               gdb_assert (die_is_declaration (die, cu));
21445               gdb_assert (attr);
21446             }
21447           if (attr)
21448             {
21449               dwarf2_const_value (attr, sym, cu);
21450               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21451               if (!suppress_add)
21452                 {
21453                   if (attr2 && (DW_UNSND (attr2) != 0))
21454                     list_to_add = &global_symbols;
21455                   else
21456                     list_to_add = cu->list_in_scope;
21457                 }
21458               break;
21459             }
21460           attr = dwarf2_attr (die, DW_AT_location, cu);
21461           if (attr)
21462             {
21463               var_decode_location (attr, sym, cu);
21464               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21465
21466               /* Fortran explicitly imports any global symbols to the local
21467                  scope by DW_TAG_common_block.  */
21468               if (cu->language == language_fortran && die->parent
21469                   && die->parent->tag == DW_TAG_common_block)
21470                 attr2 = NULL;
21471
21472               if (SYMBOL_CLASS (sym) == LOC_STATIC
21473                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21474                   && !dwarf2_per_objfile->has_section_at_zero)
21475                 {
21476                   /* When a static variable is eliminated by the linker,
21477                      the corresponding debug information is not stripped
21478                      out, but the variable address is set to null;
21479                      do not add such variables into symbol table.  */
21480                 }
21481               else if (attr2 && (DW_UNSND (attr2) != 0))
21482                 {
21483                   /* Workaround gfortran PR debug/40040 - it uses
21484                      DW_AT_location for variables in -fPIC libraries which may
21485                      get overriden by other libraries/executable and get
21486                      a different address.  Resolve it by the minimal symbol
21487                      which may come from inferior's executable using copy
21488                      relocation.  Make this workaround only for gfortran as for
21489                      other compilers GDB cannot guess the minimal symbol
21490                      Fortran mangling kind.  */
21491                   if (cu->language == language_fortran && die->parent
21492                       && die->parent->tag == DW_TAG_module
21493                       && cu->producer
21494                       && startswith (cu->producer, "GNU Fortran"))
21495                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21496
21497                   /* A variable with DW_AT_external is never static,
21498                      but it may be block-scoped.  */
21499                   list_to_add = (cu->list_in_scope == &file_symbols
21500                                  ? &global_symbols : cu->list_in_scope);
21501                 }
21502               else
21503                 list_to_add = cu->list_in_scope;
21504             }
21505           else
21506             {
21507               /* We do not know the address of this symbol.
21508                  If it is an external symbol and we have type information
21509                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21510                  The address of the variable will then be determined from
21511                  the minimal symbol table whenever the variable is
21512                  referenced.  */
21513               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21514
21515               /* Fortran explicitly imports any global symbols to the local
21516                  scope by DW_TAG_common_block.  */
21517               if (cu->language == language_fortran && die->parent
21518                   && die->parent->tag == DW_TAG_common_block)
21519                 {
21520                   /* SYMBOL_CLASS doesn't matter here because
21521                      read_common_block is going to reset it.  */
21522                   if (!suppress_add)
21523                     list_to_add = cu->list_in_scope;
21524                 }
21525               else if (attr2 && (DW_UNSND (attr2) != 0)
21526                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21527                 {
21528                   /* A variable with DW_AT_external is never static, but it
21529                      may be block-scoped.  */
21530                   list_to_add = (cu->list_in_scope == &file_symbols
21531                                  ? &global_symbols : cu->list_in_scope);
21532
21533                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21534                 }
21535               else if (!die_is_declaration (die, cu))
21536                 {
21537                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21538                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21539                   if (!suppress_add)
21540                     list_to_add = cu->list_in_scope;
21541                 }
21542             }
21543           break;
21544         case DW_TAG_formal_parameter:
21545           /* If we are inside a function, mark this as an argument.  If
21546              not, we might be looking at an argument to an inlined function
21547              when we do not have enough information to show inlined frames;
21548              pretend it's a local variable in that case so that the user can
21549              still see it.  */
21550           if (context_stack_depth > 0
21551               && context_stack[context_stack_depth - 1].name != NULL)
21552             SYMBOL_IS_ARGUMENT (sym) = 1;
21553           attr = dwarf2_attr (die, DW_AT_location, cu);
21554           if (attr)
21555             {
21556               var_decode_location (attr, sym, cu);
21557             }
21558           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21559           if (attr)
21560             {
21561               dwarf2_const_value (attr, sym, cu);
21562             }
21563
21564           list_to_add = cu->list_in_scope;
21565           break;
21566         case DW_TAG_unspecified_parameters:
21567           /* From varargs functions; gdb doesn't seem to have any
21568              interest in this information, so just ignore it for now.
21569              (FIXME?) */
21570           break;
21571         case DW_TAG_template_type_param:
21572           suppress_add = 1;
21573           /* Fall through.  */
21574         case DW_TAG_class_type:
21575         case DW_TAG_interface_type:
21576         case DW_TAG_structure_type:
21577         case DW_TAG_union_type:
21578         case DW_TAG_set_type:
21579         case DW_TAG_enumeration_type:
21580           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21581           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21582
21583           {
21584             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21585                really ever be static objects: otherwise, if you try
21586                to, say, break of a class's method and you're in a file
21587                which doesn't mention that class, it won't work unless
21588                the check for all static symbols in lookup_symbol_aux
21589                saves you.  See the OtherFileClass tests in
21590                gdb.c++/namespace.exp.  */
21591
21592             if (!suppress_add)
21593               {
21594                 list_to_add = (cu->list_in_scope == &file_symbols
21595                                && cu->language == language_cplus
21596                                ? &global_symbols : cu->list_in_scope);
21597
21598                 /* The semantics of C++ state that "struct foo {
21599                    ... }" also defines a typedef for "foo".  */
21600                 if (cu->language == language_cplus
21601                     || cu->language == language_ada
21602                     || cu->language == language_d
21603                     || cu->language == language_rust)
21604                   {
21605                     /* The symbol's name is already allocated along
21606                        with this objfile, so we don't need to
21607                        duplicate it for the type.  */
21608                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21609                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21610                   }
21611               }
21612           }
21613           break;
21614         case DW_TAG_typedef:
21615           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21616           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21617           list_to_add = cu->list_in_scope;
21618           break;
21619         case DW_TAG_base_type:
21620         case DW_TAG_subrange_type:
21621           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21622           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21623           list_to_add = cu->list_in_scope;
21624           break;
21625         case DW_TAG_enumerator:
21626           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21627           if (attr)
21628             {
21629               dwarf2_const_value (attr, sym, cu);
21630             }
21631           {
21632             /* NOTE: carlton/2003-11-10: See comment above in the
21633                DW_TAG_class_type, etc. block.  */
21634
21635             list_to_add = (cu->list_in_scope == &file_symbols
21636                            && cu->language == language_cplus
21637                            ? &global_symbols : cu->list_in_scope);
21638           }
21639           break;
21640         case DW_TAG_imported_declaration:
21641         case DW_TAG_namespace:
21642           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21643           list_to_add = &global_symbols;
21644           break;
21645         case DW_TAG_module:
21646           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21647           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21648           list_to_add = &global_symbols;
21649           break;
21650         case DW_TAG_common_block:
21651           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21652           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21653           add_symbol_to_list (sym, cu->list_in_scope);
21654           break;
21655         default:
21656           /* Not a tag we recognize.  Hopefully we aren't processing
21657              trash data, but since we must specifically ignore things
21658              we don't recognize, there is nothing else we should do at
21659              this point.  */
21660           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21661                      dwarf_tag_name (die->tag));
21662           break;
21663         }
21664
21665       if (suppress_add)
21666         {
21667           sym->hash_next = objfile->template_symbols;
21668           objfile->template_symbols = sym;
21669           list_to_add = NULL;
21670         }
21671
21672       if (list_to_add != NULL)
21673         add_symbol_to_list (sym, list_to_add);
21674
21675       /* For the benefit of old versions of GCC, check for anonymous
21676          namespaces based on the demangled name.  */
21677       if (!cu->processing_has_namespace_info
21678           && cu->language == language_cplus)
21679         cp_scan_for_anonymous_namespaces (sym, objfile);
21680     }
21681   return (sym);
21682 }
21683
21684 /* Given an attr with a DW_FORM_dataN value in host byte order,
21685    zero-extend it as appropriate for the symbol's type.  The DWARF
21686    standard (v4) is not entirely clear about the meaning of using
21687    DW_FORM_dataN for a constant with a signed type, where the type is
21688    wider than the data.  The conclusion of a discussion on the DWARF
21689    list was that this is unspecified.  We choose to always zero-extend
21690    because that is the interpretation long in use by GCC.  */
21691
21692 static gdb_byte *
21693 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21694                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21695 {
21696   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21697   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21698                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21699   LONGEST l = DW_UNSND (attr);
21700
21701   if (bits < sizeof (*value) * 8)
21702     {
21703       l &= ((LONGEST) 1 << bits) - 1;
21704       *value = l;
21705     }
21706   else if (bits == sizeof (*value) * 8)
21707     *value = l;
21708   else
21709     {
21710       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21711       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21712       return bytes;
21713     }
21714
21715   return NULL;
21716 }
21717
21718 /* Read a constant value from an attribute.  Either set *VALUE, or if
21719    the value does not fit in *VALUE, set *BYTES - either already
21720    allocated on the objfile obstack, or newly allocated on OBSTACK,
21721    or, set *BATON, if we translated the constant to a location
21722    expression.  */
21723
21724 static void
21725 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21726                          const char *name, struct obstack *obstack,
21727                          struct dwarf2_cu *cu,
21728                          LONGEST *value, const gdb_byte **bytes,
21729                          struct dwarf2_locexpr_baton **baton)
21730 {
21731   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21732   struct comp_unit_head *cu_header = &cu->header;
21733   struct dwarf_block *blk;
21734   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21735                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21736
21737   *value = 0;
21738   *bytes = NULL;
21739   *baton = NULL;
21740
21741   switch (attr->form)
21742     {
21743     case DW_FORM_addr:
21744     case DW_FORM_GNU_addr_index:
21745       {
21746         gdb_byte *data;
21747
21748         if (TYPE_LENGTH (type) != cu_header->addr_size)
21749           dwarf2_const_value_length_mismatch_complaint (name,
21750                                                         cu_header->addr_size,
21751                                                         TYPE_LENGTH (type));
21752         /* Symbols of this form are reasonably rare, so we just
21753            piggyback on the existing location code rather than writing
21754            a new implementation of symbol_computed_ops.  */
21755         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21756         (*baton)->per_cu = cu->per_cu;
21757         gdb_assert ((*baton)->per_cu);
21758
21759         (*baton)->size = 2 + cu_header->addr_size;
21760         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21761         (*baton)->data = data;
21762
21763         data[0] = DW_OP_addr;
21764         store_unsigned_integer (&data[1], cu_header->addr_size,
21765                                 byte_order, DW_ADDR (attr));
21766         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21767       }
21768       break;
21769     case DW_FORM_string:
21770     case DW_FORM_strp:
21771     case DW_FORM_GNU_str_index:
21772     case DW_FORM_GNU_strp_alt:
21773       /* DW_STRING is already allocated on the objfile obstack, point
21774          directly to it.  */
21775       *bytes = (const gdb_byte *) DW_STRING (attr);
21776       break;
21777     case DW_FORM_block1:
21778     case DW_FORM_block2:
21779     case DW_FORM_block4:
21780     case DW_FORM_block:
21781     case DW_FORM_exprloc:
21782     case DW_FORM_data16:
21783       blk = DW_BLOCK (attr);
21784       if (TYPE_LENGTH (type) != blk->size)
21785         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21786                                                       TYPE_LENGTH (type));
21787       *bytes = blk->data;
21788       break;
21789
21790       /* The DW_AT_const_value attributes are supposed to carry the
21791          symbol's value "represented as it would be on the target
21792          architecture."  By the time we get here, it's already been
21793          converted to host endianness, so we just need to sign- or
21794          zero-extend it as appropriate.  */
21795     case DW_FORM_data1:
21796       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21797       break;
21798     case DW_FORM_data2:
21799       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21800       break;
21801     case DW_FORM_data4:
21802       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21803       break;
21804     case DW_FORM_data8:
21805       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21806       break;
21807
21808     case DW_FORM_sdata:
21809     case DW_FORM_implicit_const:
21810       *value = DW_SND (attr);
21811       break;
21812
21813     case DW_FORM_udata:
21814       *value = DW_UNSND (attr);
21815       break;
21816
21817     default:
21818       complaint (&symfile_complaints,
21819                  _("unsupported const value attribute form: '%s'"),
21820                  dwarf_form_name (attr->form));
21821       *value = 0;
21822       break;
21823     }
21824 }
21825
21826
21827 /* Copy constant value from an attribute to a symbol.  */
21828
21829 static void
21830 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21831                     struct dwarf2_cu *cu)
21832 {
21833   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21834   LONGEST value;
21835   const gdb_byte *bytes;
21836   struct dwarf2_locexpr_baton *baton;
21837
21838   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21839                            SYMBOL_PRINT_NAME (sym),
21840                            &objfile->objfile_obstack, cu,
21841                            &value, &bytes, &baton);
21842
21843   if (baton != NULL)
21844     {
21845       SYMBOL_LOCATION_BATON (sym) = baton;
21846       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21847     }
21848   else if (bytes != NULL)
21849      {
21850       SYMBOL_VALUE_BYTES (sym) = bytes;
21851       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21852     }
21853   else
21854     {
21855       SYMBOL_VALUE (sym) = value;
21856       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21857     }
21858 }
21859
21860 /* Return the type of the die in question using its DW_AT_type attribute.  */
21861
21862 static struct type *
21863 die_type (struct die_info *die, struct dwarf2_cu *cu)
21864 {
21865   struct attribute *type_attr;
21866
21867   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21868   if (!type_attr)
21869     {
21870       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21871       /* A missing DW_AT_type represents a void type.  */
21872       return objfile_type (objfile)->builtin_void;
21873     }
21874
21875   return lookup_die_type (die, type_attr, cu);
21876 }
21877
21878 /* True iff CU's producer generates GNAT Ada auxiliary information
21879    that allows to find parallel types through that information instead
21880    of having to do expensive parallel lookups by type name.  */
21881
21882 static int
21883 need_gnat_info (struct dwarf2_cu *cu)
21884 {
21885   /* Assume that the Ada compiler was GNAT, which always produces
21886      the auxiliary information.  */
21887   return (cu->language == language_ada);
21888 }
21889
21890 /* Return the auxiliary type of the die in question using its
21891    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21892    attribute is not present.  */
21893
21894 static struct type *
21895 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21896 {
21897   struct attribute *type_attr;
21898
21899   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21900   if (!type_attr)
21901     return NULL;
21902
21903   return lookup_die_type (die, type_attr, cu);
21904 }
21905
21906 /* If DIE has a descriptive_type attribute, then set the TYPE's
21907    descriptive type accordingly.  */
21908
21909 static void
21910 set_descriptive_type (struct type *type, struct die_info *die,
21911                       struct dwarf2_cu *cu)
21912 {
21913   struct type *descriptive_type = die_descriptive_type (die, cu);
21914
21915   if (descriptive_type)
21916     {
21917       ALLOCATE_GNAT_AUX_TYPE (type);
21918       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21919     }
21920 }
21921
21922 /* Return the containing type of the die in question using its
21923    DW_AT_containing_type attribute.  */
21924
21925 static struct type *
21926 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21927 {
21928   struct attribute *type_attr;
21929   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21930
21931   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21932   if (!type_attr)
21933     error (_("Dwarf Error: Problem turning containing type into gdb type "
21934              "[in module %s]"), objfile_name (objfile));
21935
21936   return lookup_die_type (die, type_attr, cu);
21937 }
21938
21939 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21940
21941 static struct type *
21942 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21943 {
21944   struct dwarf2_per_objfile *dwarf2_per_objfile
21945     = cu->per_cu->dwarf2_per_objfile;
21946   struct objfile *objfile = dwarf2_per_objfile->objfile;
21947   char *message, *saved;
21948
21949   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21950                         objfile_name (objfile),
21951                         sect_offset_str (cu->header.sect_off),
21952                         sect_offset_str (die->sect_off));
21953   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21954                                   message, strlen (message));
21955   xfree (message);
21956
21957   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21958 }
21959
21960 /* Look up the type of DIE in CU using its type attribute ATTR.
21961    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21962    DW_AT_containing_type.
21963    If there is no type substitute an error marker.  */
21964
21965 static struct type *
21966 lookup_die_type (struct die_info *die, const struct attribute *attr,
21967                  struct dwarf2_cu *cu)
21968 {
21969   struct dwarf2_per_objfile *dwarf2_per_objfile
21970     = cu->per_cu->dwarf2_per_objfile;
21971   struct objfile *objfile = dwarf2_per_objfile->objfile;
21972   struct type *this_type;
21973
21974   gdb_assert (attr->name == DW_AT_type
21975               || attr->name == DW_AT_GNAT_descriptive_type
21976               || attr->name == DW_AT_containing_type);
21977
21978   /* First see if we have it cached.  */
21979
21980   if (attr->form == DW_FORM_GNU_ref_alt)
21981     {
21982       struct dwarf2_per_cu_data *per_cu;
21983       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21984
21985       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21986                                                  dwarf2_per_objfile);
21987       this_type = get_die_type_at_offset (sect_off, per_cu);
21988     }
21989   else if (attr_form_is_ref (attr))
21990     {
21991       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21992
21993       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21994     }
21995   else if (attr->form == DW_FORM_ref_sig8)
21996     {
21997       ULONGEST signature = DW_SIGNATURE (attr);
21998
21999       return get_signatured_type (die, signature, cu);
22000     }
22001   else
22002     {
22003       complaint (&symfile_complaints,
22004                  _("Dwarf Error: Bad type attribute %s in DIE"
22005                    " at %s [in module %s]"),
22006                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22007                  objfile_name (objfile));
22008       return build_error_marker_type (cu, die);
22009     }
22010
22011   /* If not cached we need to read it in.  */
22012
22013   if (this_type == NULL)
22014     {
22015       struct die_info *type_die = NULL;
22016       struct dwarf2_cu *type_cu = cu;
22017
22018       if (attr_form_is_ref (attr))
22019         type_die = follow_die_ref (die, attr, &type_cu);
22020       if (type_die == NULL)
22021         return build_error_marker_type (cu, die);
22022       /* If we find the type now, it's probably because the type came
22023          from an inter-CU reference and the type's CU got expanded before
22024          ours.  */
22025       this_type = read_type_die (type_die, type_cu);
22026     }
22027
22028   /* If we still don't have a type use an error marker.  */
22029
22030   if (this_type == NULL)
22031     return build_error_marker_type (cu, die);
22032
22033   return this_type;
22034 }
22035
22036 /* Return the type in DIE, CU.
22037    Returns NULL for invalid types.
22038
22039    This first does a lookup in die_type_hash,
22040    and only reads the die in if necessary.
22041
22042    NOTE: This can be called when reading in partial or full symbols.  */
22043
22044 static struct type *
22045 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22046 {
22047   struct type *this_type;
22048
22049   this_type = get_die_type (die, cu);
22050   if (this_type)
22051     return this_type;
22052
22053   return read_type_die_1 (die, cu);
22054 }
22055
22056 /* Read the type in DIE, CU.
22057    Returns NULL for invalid types.  */
22058
22059 static struct type *
22060 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22061 {
22062   struct type *this_type = NULL;
22063
22064   switch (die->tag)
22065     {
22066     case DW_TAG_class_type:
22067     case DW_TAG_interface_type:
22068     case DW_TAG_structure_type:
22069     case DW_TAG_union_type:
22070       this_type = read_structure_type (die, cu);
22071       break;
22072     case DW_TAG_enumeration_type:
22073       this_type = read_enumeration_type (die, cu);
22074       break;
22075     case DW_TAG_subprogram:
22076     case DW_TAG_subroutine_type:
22077     case DW_TAG_inlined_subroutine:
22078       this_type = read_subroutine_type (die, cu);
22079       break;
22080     case DW_TAG_array_type:
22081       this_type = read_array_type (die, cu);
22082       break;
22083     case DW_TAG_set_type:
22084       this_type = read_set_type (die, cu);
22085       break;
22086     case DW_TAG_pointer_type:
22087       this_type = read_tag_pointer_type (die, cu);
22088       break;
22089     case DW_TAG_ptr_to_member_type:
22090       this_type = read_tag_ptr_to_member_type (die, cu);
22091       break;
22092     case DW_TAG_reference_type:
22093       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22094       break;
22095     case DW_TAG_rvalue_reference_type:
22096       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22097       break;
22098     case DW_TAG_const_type:
22099       this_type = read_tag_const_type (die, cu);
22100       break;
22101     case DW_TAG_volatile_type:
22102       this_type = read_tag_volatile_type (die, cu);
22103       break;
22104     case DW_TAG_restrict_type:
22105       this_type = read_tag_restrict_type (die, cu);
22106       break;
22107     case DW_TAG_string_type:
22108       this_type = read_tag_string_type (die, cu);
22109       break;
22110     case DW_TAG_typedef:
22111       this_type = read_typedef (die, cu);
22112       break;
22113     case DW_TAG_subrange_type:
22114       this_type = read_subrange_type (die, cu);
22115       break;
22116     case DW_TAG_base_type:
22117       this_type = read_base_type (die, cu);
22118       break;
22119     case DW_TAG_unspecified_type:
22120       this_type = read_unspecified_type (die, cu);
22121       break;
22122     case DW_TAG_namespace:
22123       this_type = read_namespace_type (die, cu);
22124       break;
22125     case DW_TAG_module:
22126       this_type = read_module_type (die, cu);
22127       break;
22128     case DW_TAG_atomic_type:
22129       this_type = read_tag_atomic_type (die, cu);
22130       break;
22131     default:
22132       complaint (&symfile_complaints,
22133                  _("unexpected tag in read_type_die: '%s'"),
22134                  dwarf_tag_name (die->tag));
22135       break;
22136     }
22137
22138   return this_type;
22139 }
22140
22141 /* See if we can figure out if the class lives in a namespace.  We do
22142    this by looking for a member function; its demangled name will
22143    contain namespace info, if there is any.
22144    Return the computed name or NULL.
22145    Space for the result is allocated on the objfile's obstack.
22146    This is the full-die version of guess_partial_die_structure_name.
22147    In this case we know DIE has no useful parent.  */
22148
22149 static char *
22150 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22151 {
22152   struct die_info *spec_die;
22153   struct dwarf2_cu *spec_cu;
22154   struct die_info *child;
22155   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22156
22157   spec_cu = cu;
22158   spec_die = die_specification (die, &spec_cu);
22159   if (spec_die != NULL)
22160     {
22161       die = spec_die;
22162       cu = spec_cu;
22163     }
22164
22165   for (child = die->child;
22166        child != NULL;
22167        child = child->sibling)
22168     {
22169       if (child->tag == DW_TAG_subprogram)
22170         {
22171           const char *linkage_name = dw2_linkage_name (child, cu);
22172
22173           if (linkage_name != NULL)
22174             {
22175               char *actual_name
22176                 = language_class_name_from_physname (cu->language_defn,
22177                                                      linkage_name);
22178               char *name = NULL;
22179
22180               if (actual_name != NULL)
22181                 {
22182                   const char *die_name = dwarf2_name (die, cu);
22183
22184                   if (die_name != NULL
22185                       && strcmp (die_name, actual_name) != 0)
22186                     {
22187                       /* Strip off the class name from the full name.
22188                          We want the prefix.  */
22189                       int die_name_len = strlen (die_name);
22190                       int actual_name_len = strlen (actual_name);
22191
22192                       /* Test for '::' as a sanity check.  */
22193                       if (actual_name_len > die_name_len + 2
22194                           && actual_name[actual_name_len
22195                                          - die_name_len - 1] == ':')
22196                         name = (char *) obstack_copy0 (
22197                           &objfile->per_bfd->storage_obstack,
22198                           actual_name, actual_name_len - die_name_len - 2);
22199                     }
22200                 }
22201               xfree (actual_name);
22202               return name;
22203             }
22204         }
22205     }
22206
22207   return NULL;
22208 }
22209
22210 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22211    prefix part in such case.  See
22212    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22213
22214 static const char *
22215 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22216 {
22217   struct attribute *attr;
22218   const char *base;
22219
22220   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22221       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22222     return NULL;
22223
22224   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22225     return NULL;
22226
22227   attr = dw2_linkage_name_attr (die, cu);
22228   if (attr == NULL || DW_STRING (attr) == NULL)
22229     return NULL;
22230
22231   /* dwarf2_name had to be already called.  */
22232   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22233
22234   /* Strip the base name, keep any leading namespaces/classes.  */
22235   base = strrchr (DW_STRING (attr), ':');
22236   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22237     return "";
22238
22239   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22240   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22241                                  DW_STRING (attr),
22242                                  &base[-1] - DW_STRING (attr));
22243 }
22244
22245 /* Return the name of the namespace/class that DIE is defined within,
22246    or "" if we can't tell.  The caller should not xfree the result.
22247
22248    For example, if we're within the method foo() in the following
22249    code:
22250
22251    namespace N {
22252      class C {
22253        void foo () {
22254        }
22255      };
22256    }
22257
22258    then determine_prefix on foo's die will return "N::C".  */
22259
22260 static const char *
22261 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22262 {
22263   struct dwarf2_per_objfile *dwarf2_per_objfile
22264     = cu->per_cu->dwarf2_per_objfile;
22265   struct die_info *parent, *spec_die;
22266   struct dwarf2_cu *spec_cu;
22267   struct type *parent_type;
22268   const char *retval;
22269
22270   if (cu->language != language_cplus
22271       && cu->language != language_fortran && cu->language != language_d
22272       && cu->language != language_rust)
22273     return "";
22274
22275   retval = anonymous_struct_prefix (die, cu);
22276   if (retval)
22277     return retval;
22278
22279   /* We have to be careful in the presence of DW_AT_specification.
22280      For example, with GCC 3.4, given the code
22281
22282      namespace N {
22283        void foo() {
22284          // Definition of N::foo.
22285        }
22286      }
22287
22288      then we'll have a tree of DIEs like this:
22289
22290      1: DW_TAG_compile_unit
22291        2: DW_TAG_namespace        // N
22292          3: DW_TAG_subprogram     // declaration of N::foo
22293        4: DW_TAG_subprogram       // definition of N::foo
22294             DW_AT_specification   // refers to die #3
22295
22296      Thus, when processing die #4, we have to pretend that we're in
22297      the context of its DW_AT_specification, namely the contex of die
22298      #3.  */
22299   spec_cu = cu;
22300   spec_die = die_specification (die, &spec_cu);
22301   if (spec_die == NULL)
22302     parent = die->parent;
22303   else
22304     {
22305       parent = spec_die->parent;
22306       cu = spec_cu;
22307     }
22308
22309   if (parent == NULL)
22310     return "";
22311   else if (parent->building_fullname)
22312     {
22313       const char *name;
22314       const char *parent_name;
22315
22316       /* It has been seen on RealView 2.2 built binaries,
22317          DW_TAG_template_type_param types actually _defined_ as
22318          children of the parent class:
22319
22320          enum E {};
22321          template class <class Enum> Class{};
22322          Class<enum E> class_e;
22323
22324          1: DW_TAG_class_type (Class)
22325            2: DW_TAG_enumeration_type (E)
22326              3: DW_TAG_enumerator (enum1:0)
22327              3: DW_TAG_enumerator (enum2:1)
22328              ...
22329            2: DW_TAG_template_type_param
22330               DW_AT_type  DW_FORM_ref_udata (E)
22331
22332          Besides being broken debug info, it can put GDB into an
22333          infinite loop.  Consider:
22334
22335          When we're building the full name for Class<E>, we'll start
22336          at Class, and go look over its template type parameters,
22337          finding E.  We'll then try to build the full name of E, and
22338          reach here.  We're now trying to build the full name of E,
22339          and look over the parent DIE for containing scope.  In the
22340          broken case, if we followed the parent DIE of E, we'd again
22341          find Class, and once again go look at its template type
22342          arguments, etc., etc.  Simply don't consider such parent die
22343          as source-level parent of this die (it can't be, the language
22344          doesn't allow it), and break the loop here.  */
22345       name = dwarf2_name (die, cu);
22346       parent_name = dwarf2_name (parent, cu);
22347       complaint (&symfile_complaints,
22348                  _("template param type '%s' defined within parent '%s'"),
22349                  name ? name : "<unknown>",
22350                  parent_name ? parent_name : "<unknown>");
22351       return "";
22352     }
22353   else
22354     switch (parent->tag)
22355       {
22356       case DW_TAG_namespace:
22357         parent_type = read_type_die (parent, cu);
22358         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22359            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22360            Work around this problem here.  */
22361         if (cu->language == language_cplus
22362             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22363           return "";
22364         /* We give a name to even anonymous namespaces.  */
22365         return TYPE_TAG_NAME (parent_type);
22366       case DW_TAG_class_type:
22367       case DW_TAG_interface_type:
22368       case DW_TAG_structure_type:
22369       case DW_TAG_union_type:
22370       case DW_TAG_module:
22371         parent_type = read_type_die (parent, cu);
22372         if (TYPE_TAG_NAME (parent_type) != NULL)
22373           return TYPE_TAG_NAME (parent_type);
22374         else
22375           /* An anonymous structure is only allowed non-static data
22376              members; no typedefs, no member functions, et cetera.
22377              So it does not need a prefix.  */
22378           return "";
22379       case DW_TAG_compile_unit:
22380       case DW_TAG_partial_unit:
22381         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22382         if (cu->language == language_cplus
22383             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22384             && die->child != NULL
22385             && (die->tag == DW_TAG_class_type
22386                 || die->tag == DW_TAG_structure_type
22387                 || die->tag == DW_TAG_union_type))
22388           {
22389             char *name = guess_full_die_structure_name (die, cu);
22390             if (name != NULL)
22391               return name;
22392           }
22393         return "";
22394       case DW_TAG_enumeration_type:
22395         parent_type = read_type_die (parent, cu);
22396         if (TYPE_DECLARED_CLASS (parent_type))
22397           {
22398             if (TYPE_TAG_NAME (parent_type) != NULL)
22399               return TYPE_TAG_NAME (parent_type);
22400             return "";
22401           }
22402         /* Fall through.  */
22403       default:
22404         return determine_prefix (parent, cu);
22405       }
22406 }
22407
22408 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22409    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22410    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22411    an obconcat, otherwise allocate storage for the result.  The CU argument is
22412    used to determine the language and hence, the appropriate separator.  */
22413
22414 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22415
22416 static char *
22417 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22418                  int physname, struct dwarf2_cu *cu)
22419 {
22420   const char *lead = "";
22421   const char *sep;
22422
22423   if (suffix == NULL || suffix[0] == '\0'
22424       || prefix == NULL || prefix[0] == '\0')
22425     sep = "";
22426   else if (cu->language == language_d)
22427     {
22428       /* For D, the 'main' function could be defined in any module, but it
22429          should never be prefixed.  */
22430       if (strcmp (suffix, "D main") == 0)
22431         {
22432           prefix = "";
22433           sep = "";
22434         }
22435       else
22436         sep = ".";
22437     }
22438   else if (cu->language == language_fortran && physname)
22439     {
22440       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22441          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22442
22443       lead = "__";
22444       sep = "_MOD_";
22445     }
22446   else
22447     sep = "::";
22448
22449   if (prefix == NULL)
22450     prefix = "";
22451   if (suffix == NULL)
22452     suffix = "";
22453
22454   if (obs == NULL)
22455     {
22456       char *retval
22457         = ((char *)
22458            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22459
22460       strcpy (retval, lead);
22461       strcat (retval, prefix);
22462       strcat (retval, sep);
22463       strcat (retval, suffix);
22464       return retval;
22465     }
22466   else
22467     {
22468       /* We have an obstack.  */
22469       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22470     }
22471 }
22472
22473 /* Return sibling of die, NULL if no sibling.  */
22474
22475 static struct die_info *
22476 sibling_die (struct die_info *die)
22477 {
22478   return die->sibling;
22479 }
22480
22481 /* Get name of a die, return NULL if not found.  */
22482
22483 static const char *
22484 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22485                           struct obstack *obstack)
22486 {
22487   if (name && cu->language == language_cplus)
22488     {
22489       std::string canon_name = cp_canonicalize_string (name);
22490
22491       if (!canon_name.empty ())
22492         {
22493           if (canon_name != name)
22494             name = (const char *) obstack_copy0 (obstack,
22495                                                  canon_name.c_str (),
22496                                                  canon_name.length ());
22497         }
22498     }
22499
22500   return name;
22501 }
22502
22503 /* Get name of a die, return NULL if not found.
22504    Anonymous namespaces are converted to their magic string.  */
22505
22506 static const char *
22507 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22508 {
22509   struct attribute *attr;
22510   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22511
22512   attr = dwarf2_attr (die, DW_AT_name, cu);
22513   if ((!attr || !DW_STRING (attr))
22514       && die->tag != DW_TAG_namespace
22515       && die->tag != DW_TAG_class_type
22516       && die->tag != DW_TAG_interface_type
22517       && die->tag != DW_TAG_structure_type
22518       && die->tag != DW_TAG_union_type)
22519     return NULL;
22520
22521   switch (die->tag)
22522     {
22523     case DW_TAG_compile_unit:
22524     case DW_TAG_partial_unit:
22525       /* Compilation units have a DW_AT_name that is a filename, not
22526          a source language identifier.  */
22527     case DW_TAG_enumeration_type:
22528     case DW_TAG_enumerator:
22529       /* These tags always have simple identifiers already; no need
22530          to canonicalize them.  */
22531       return DW_STRING (attr);
22532
22533     case DW_TAG_namespace:
22534       if (attr != NULL && DW_STRING (attr) != NULL)
22535         return DW_STRING (attr);
22536       return CP_ANONYMOUS_NAMESPACE_STR;
22537
22538     case DW_TAG_class_type:
22539     case DW_TAG_interface_type:
22540     case DW_TAG_structure_type:
22541     case DW_TAG_union_type:
22542       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22543          structures or unions.  These were of the form "._%d" in GCC 4.1,
22544          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22545          and GCC 4.4.  We work around this problem by ignoring these.  */
22546       if (attr && DW_STRING (attr)
22547           && (startswith (DW_STRING (attr), "._")
22548               || startswith (DW_STRING (attr), "<anonymous")))
22549         return NULL;
22550
22551       /* GCC might emit a nameless typedef that has a linkage name.  See
22552          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22553       if (!attr || DW_STRING (attr) == NULL)
22554         {
22555           char *demangled = NULL;
22556
22557           attr = dw2_linkage_name_attr (die, cu);
22558           if (attr == NULL || DW_STRING (attr) == NULL)
22559             return NULL;
22560
22561           /* Avoid demangling DW_STRING (attr) the second time on a second
22562              call for the same DIE.  */
22563           if (!DW_STRING_IS_CANONICAL (attr))
22564             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22565
22566           if (demangled)
22567             {
22568               const char *base;
22569
22570               /* FIXME: we already did this for the partial symbol... */
22571               DW_STRING (attr)
22572                 = ((const char *)
22573                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22574                                   demangled, strlen (demangled)));
22575               DW_STRING_IS_CANONICAL (attr) = 1;
22576               xfree (demangled);
22577
22578               /* Strip any leading namespaces/classes, keep only the base name.
22579                  DW_AT_name for named DIEs does not contain the prefixes.  */
22580               base = strrchr (DW_STRING (attr), ':');
22581               if (base && base > DW_STRING (attr) && base[-1] == ':')
22582                 return &base[1];
22583               else
22584                 return DW_STRING (attr);
22585             }
22586         }
22587       break;
22588
22589     default:
22590       break;
22591     }
22592
22593   if (!DW_STRING_IS_CANONICAL (attr))
22594     {
22595       DW_STRING (attr)
22596         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22597                                     &objfile->per_bfd->storage_obstack);
22598       DW_STRING_IS_CANONICAL (attr) = 1;
22599     }
22600   return DW_STRING (attr);
22601 }
22602
22603 /* Return the die that this die in an extension of, or NULL if there
22604    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22605    containing the return value on output.  */
22606
22607 static struct die_info *
22608 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22609 {
22610   struct attribute *attr;
22611
22612   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22613   if (attr == NULL)
22614     return NULL;
22615
22616   return follow_die_ref (die, attr, ext_cu);
22617 }
22618
22619 /* Convert a DIE tag into its string name.  */
22620
22621 static const char *
22622 dwarf_tag_name (unsigned tag)
22623 {
22624   const char *name = get_DW_TAG_name (tag);
22625
22626   if (name == NULL)
22627     return "DW_TAG_<unknown>";
22628
22629   return name;
22630 }
22631
22632 /* Convert a DWARF attribute code into its string name.  */
22633
22634 static const char *
22635 dwarf_attr_name (unsigned attr)
22636 {
22637   const char *name;
22638
22639 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22640   if (attr == DW_AT_MIPS_fde)
22641     return "DW_AT_MIPS_fde";
22642 #else
22643   if (attr == DW_AT_HP_block_index)
22644     return "DW_AT_HP_block_index";
22645 #endif
22646
22647   name = get_DW_AT_name (attr);
22648
22649   if (name == NULL)
22650     return "DW_AT_<unknown>";
22651
22652   return name;
22653 }
22654
22655 /* Convert a DWARF value form code into its string name.  */
22656
22657 static const char *
22658 dwarf_form_name (unsigned form)
22659 {
22660   const char *name = get_DW_FORM_name (form);
22661
22662   if (name == NULL)
22663     return "DW_FORM_<unknown>";
22664
22665   return name;
22666 }
22667
22668 static const char *
22669 dwarf_bool_name (unsigned mybool)
22670 {
22671   if (mybool)
22672     return "TRUE";
22673   else
22674     return "FALSE";
22675 }
22676
22677 /* Convert a DWARF type code into its string name.  */
22678
22679 static const char *
22680 dwarf_type_encoding_name (unsigned enc)
22681 {
22682   const char *name = get_DW_ATE_name (enc);
22683
22684   if (name == NULL)
22685     return "DW_ATE_<unknown>";
22686
22687   return name;
22688 }
22689
22690 static void
22691 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22692 {
22693   unsigned int i;
22694
22695   print_spaces (indent, f);
22696   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22697                       dwarf_tag_name (die->tag), die->abbrev,
22698                       sect_offset_str (die->sect_off));
22699
22700   if (die->parent != NULL)
22701     {
22702       print_spaces (indent, f);
22703       fprintf_unfiltered (f, "  parent at offset: %s\n",
22704                           sect_offset_str (die->parent->sect_off));
22705     }
22706
22707   print_spaces (indent, f);
22708   fprintf_unfiltered (f, "  has children: %s\n",
22709            dwarf_bool_name (die->child != NULL));
22710
22711   print_spaces (indent, f);
22712   fprintf_unfiltered (f, "  attributes:\n");
22713
22714   for (i = 0; i < die->num_attrs; ++i)
22715     {
22716       print_spaces (indent, f);
22717       fprintf_unfiltered (f, "    %s (%s) ",
22718                dwarf_attr_name (die->attrs[i].name),
22719                dwarf_form_name (die->attrs[i].form));
22720
22721       switch (die->attrs[i].form)
22722         {
22723         case DW_FORM_addr:
22724         case DW_FORM_GNU_addr_index:
22725           fprintf_unfiltered (f, "address: ");
22726           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22727           break;
22728         case DW_FORM_block2:
22729         case DW_FORM_block4:
22730         case DW_FORM_block:
22731         case DW_FORM_block1:
22732           fprintf_unfiltered (f, "block: size %s",
22733                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22734           break;
22735         case DW_FORM_exprloc:
22736           fprintf_unfiltered (f, "expression: size %s",
22737                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22738           break;
22739         case DW_FORM_data16:
22740           fprintf_unfiltered (f, "constant of 16 bytes");
22741           break;
22742         case DW_FORM_ref_addr:
22743           fprintf_unfiltered (f, "ref address: ");
22744           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22745           break;
22746         case DW_FORM_GNU_ref_alt:
22747           fprintf_unfiltered (f, "alt ref address: ");
22748           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22749           break;
22750         case DW_FORM_ref1:
22751         case DW_FORM_ref2:
22752         case DW_FORM_ref4:
22753         case DW_FORM_ref8:
22754         case DW_FORM_ref_udata:
22755           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22756                               (long) (DW_UNSND (&die->attrs[i])));
22757           break;
22758         case DW_FORM_data1:
22759         case DW_FORM_data2:
22760         case DW_FORM_data4:
22761         case DW_FORM_data8:
22762         case DW_FORM_udata:
22763         case DW_FORM_sdata:
22764           fprintf_unfiltered (f, "constant: %s",
22765                               pulongest (DW_UNSND (&die->attrs[i])));
22766           break;
22767         case DW_FORM_sec_offset:
22768           fprintf_unfiltered (f, "section offset: %s",
22769                               pulongest (DW_UNSND (&die->attrs[i])));
22770           break;
22771         case DW_FORM_ref_sig8:
22772           fprintf_unfiltered (f, "signature: %s",
22773                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22774           break;
22775         case DW_FORM_string:
22776         case DW_FORM_strp:
22777         case DW_FORM_line_strp:
22778         case DW_FORM_GNU_str_index:
22779         case DW_FORM_GNU_strp_alt:
22780           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22781                    DW_STRING (&die->attrs[i])
22782                    ? DW_STRING (&die->attrs[i]) : "",
22783                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22784           break;
22785         case DW_FORM_flag:
22786           if (DW_UNSND (&die->attrs[i]))
22787             fprintf_unfiltered (f, "flag: TRUE");
22788           else
22789             fprintf_unfiltered (f, "flag: FALSE");
22790           break;
22791         case DW_FORM_flag_present:
22792           fprintf_unfiltered (f, "flag: TRUE");
22793           break;
22794         case DW_FORM_indirect:
22795           /* The reader will have reduced the indirect form to
22796              the "base form" so this form should not occur.  */
22797           fprintf_unfiltered (f, 
22798                               "unexpected attribute form: DW_FORM_indirect");
22799           break;
22800         case DW_FORM_implicit_const:
22801           fprintf_unfiltered (f, "constant: %s",
22802                               plongest (DW_SND (&die->attrs[i])));
22803           break;
22804         default:
22805           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22806                    die->attrs[i].form);
22807           break;
22808         }
22809       fprintf_unfiltered (f, "\n");
22810     }
22811 }
22812
22813 static void
22814 dump_die_for_error (struct die_info *die)
22815 {
22816   dump_die_shallow (gdb_stderr, 0, die);
22817 }
22818
22819 static void
22820 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22821 {
22822   int indent = level * 4;
22823
22824   gdb_assert (die != NULL);
22825
22826   if (level >= max_level)
22827     return;
22828
22829   dump_die_shallow (f, indent, die);
22830
22831   if (die->child != NULL)
22832     {
22833       print_spaces (indent, f);
22834       fprintf_unfiltered (f, "  Children:");
22835       if (level + 1 < max_level)
22836         {
22837           fprintf_unfiltered (f, "\n");
22838           dump_die_1 (f, level + 1, max_level, die->child);
22839         }
22840       else
22841         {
22842           fprintf_unfiltered (f,
22843                               " [not printed, max nesting level reached]\n");
22844         }
22845     }
22846
22847   if (die->sibling != NULL && level > 0)
22848     {
22849       dump_die_1 (f, level, max_level, die->sibling);
22850     }
22851 }
22852
22853 /* This is called from the pdie macro in gdbinit.in.
22854    It's not static so gcc will keep a copy callable from gdb.  */
22855
22856 void
22857 dump_die (struct die_info *die, int max_level)
22858 {
22859   dump_die_1 (gdb_stdlog, 0, max_level, die);
22860 }
22861
22862 static void
22863 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22864 {
22865   void **slot;
22866
22867   slot = htab_find_slot_with_hash (cu->die_hash, die,
22868                                    to_underlying (die->sect_off),
22869                                    INSERT);
22870
22871   *slot = die;
22872 }
22873
22874 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22875    required kind.  */
22876
22877 static sect_offset
22878 dwarf2_get_ref_die_offset (const struct attribute *attr)
22879 {
22880   if (attr_form_is_ref (attr))
22881     return (sect_offset) DW_UNSND (attr);
22882
22883   complaint (&symfile_complaints,
22884              _("unsupported die ref attribute form: '%s'"),
22885              dwarf_form_name (attr->form));
22886   return {};
22887 }
22888
22889 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22890  * the value held by the attribute is not constant.  */
22891
22892 static LONGEST
22893 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22894 {
22895   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22896     return DW_SND (attr);
22897   else if (attr->form == DW_FORM_udata
22898            || attr->form == DW_FORM_data1
22899            || attr->form == DW_FORM_data2
22900            || attr->form == DW_FORM_data4
22901            || attr->form == DW_FORM_data8)
22902     return DW_UNSND (attr);
22903   else
22904     {
22905       /* For DW_FORM_data16 see attr_form_is_constant.  */
22906       complaint (&symfile_complaints,
22907                  _("Attribute value is not a constant (%s)"),
22908                  dwarf_form_name (attr->form));
22909       return default_value;
22910     }
22911 }
22912
22913 /* Follow reference or signature attribute ATTR of SRC_DIE.
22914    On entry *REF_CU is the CU of SRC_DIE.
22915    On exit *REF_CU is the CU of the result.  */
22916
22917 static struct die_info *
22918 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22919                        struct dwarf2_cu **ref_cu)
22920 {
22921   struct die_info *die;
22922
22923   if (attr_form_is_ref (attr))
22924     die = follow_die_ref (src_die, attr, ref_cu);
22925   else if (attr->form == DW_FORM_ref_sig8)
22926     die = follow_die_sig (src_die, attr, ref_cu);
22927   else
22928     {
22929       dump_die_for_error (src_die);
22930       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22931              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22932     }
22933
22934   return die;
22935 }
22936
22937 /* Follow reference OFFSET.
22938    On entry *REF_CU is the CU of the source die referencing OFFSET.
22939    On exit *REF_CU is the CU of the result.
22940    Returns NULL if OFFSET is invalid.  */
22941
22942 static struct die_info *
22943 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22944                    struct dwarf2_cu **ref_cu)
22945 {
22946   struct die_info temp_die;
22947   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22948   struct dwarf2_per_objfile *dwarf2_per_objfile
22949     = cu->per_cu->dwarf2_per_objfile;
22950   struct objfile *objfile = dwarf2_per_objfile->objfile;
22951
22952   gdb_assert (cu->per_cu != NULL);
22953
22954   target_cu = cu;
22955
22956   if (cu->per_cu->is_debug_types)
22957     {
22958       /* .debug_types CUs cannot reference anything outside their CU.
22959          If they need to, they have to reference a signatured type via
22960          DW_FORM_ref_sig8.  */
22961       if (!offset_in_cu_p (&cu->header, sect_off))
22962         return NULL;
22963     }
22964   else if (offset_in_dwz != cu->per_cu->is_dwz
22965            || !offset_in_cu_p (&cu->header, sect_off))
22966     {
22967       struct dwarf2_per_cu_data *per_cu;
22968
22969       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22970                                                  dwarf2_per_objfile);
22971
22972       /* If necessary, add it to the queue and load its DIEs.  */
22973       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22974         load_full_comp_unit (per_cu, cu->language);
22975
22976       target_cu = per_cu->cu;
22977     }
22978   else if (cu->dies == NULL)
22979     {
22980       /* We're loading full DIEs during partial symbol reading.  */
22981       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22982       load_full_comp_unit (cu->per_cu, language_minimal);
22983     }
22984
22985   *ref_cu = target_cu;
22986   temp_die.sect_off = sect_off;
22987   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22988                                                   &temp_die,
22989                                                   to_underlying (sect_off));
22990 }
22991
22992 /* Follow reference attribute ATTR of SRC_DIE.
22993    On entry *REF_CU is the CU of SRC_DIE.
22994    On exit *REF_CU is the CU of the result.  */
22995
22996 static struct die_info *
22997 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22998                 struct dwarf2_cu **ref_cu)
22999 {
23000   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23001   struct dwarf2_cu *cu = *ref_cu;
23002   struct die_info *die;
23003
23004   die = follow_die_offset (sect_off,
23005                            (attr->form == DW_FORM_GNU_ref_alt
23006                             || cu->per_cu->is_dwz),
23007                            ref_cu);
23008   if (!die)
23009     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23010            "at %s [in module %s]"),
23011            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23012            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23013
23014   return die;
23015 }
23016
23017 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23018    Returned value is intended for DW_OP_call*.  Returned
23019    dwarf2_locexpr_baton->data has lifetime of
23020    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23021
23022 struct dwarf2_locexpr_baton
23023 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23024                                struct dwarf2_per_cu_data *per_cu,
23025                                CORE_ADDR (*get_frame_pc) (void *baton),
23026                                void *baton)
23027 {
23028   struct dwarf2_cu *cu;
23029   struct die_info *die;
23030   struct attribute *attr;
23031   struct dwarf2_locexpr_baton retval;
23032   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23033   struct dwarf2_per_objfile *dwarf2_per_objfile
23034     = get_dwarf2_per_objfile (objfile);
23035
23036   if (per_cu->cu == NULL)
23037     load_cu (per_cu);
23038   cu = per_cu->cu;
23039   if (cu == NULL)
23040     {
23041       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23042          Instead just throw an error, not much else we can do.  */
23043       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23044              sect_offset_str (sect_off), objfile_name (objfile));
23045     }
23046
23047   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23048   if (!die)
23049     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23050            sect_offset_str (sect_off), objfile_name (objfile));
23051
23052   attr = dwarf2_attr (die, DW_AT_location, cu);
23053   if (!attr)
23054     {
23055       /* DWARF: "If there is no such attribute, then there is no effect.".
23056          DATA is ignored if SIZE is 0.  */
23057
23058       retval.data = NULL;
23059       retval.size = 0;
23060     }
23061   else if (attr_form_is_section_offset (attr))
23062     {
23063       struct dwarf2_loclist_baton loclist_baton;
23064       CORE_ADDR pc = (*get_frame_pc) (baton);
23065       size_t size;
23066
23067       fill_in_loclist_baton (cu, &loclist_baton, attr);
23068
23069       retval.data = dwarf2_find_location_expression (&loclist_baton,
23070                                                      &size, pc);
23071       retval.size = size;
23072     }
23073   else
23074     {
23075       if (!attr_form_is_block (attr))
23076         error (_("Dwarf Error: DIE at %s referenced in module %s "
23077                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23078                sect_offset_str (sect_off), objfile_name (objfile));
23079
23080       retval.data = DW_BLOCK (attr)->data;
23081       retval.size = DW_BLOCK (attr)->size;
23082     }
23083   retval.per_cu = cu->per_cu;
23084
23085   age_cached_comp_units (dwarf2_per_objfile);
23086
23087   return retval;
23088 }
23089
23090 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23091    offset.  */
23092
23093 struct dwarf2_locexpr_baton
23094 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23095                              struct dwarf2_per_cu_data *per_cu,
23096                              CORE_ADDR (*get_frame_pc) (void *baton),
23097                              void *baton)
23098 {
23099   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23100
23101   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23102 }
23103
23104 /* Write a constant of a given type as target-ordered bytes into
23105    OBSTACK.  */
23106
23107 static const gdb_byte *
23108 write_constant_as_bytes (struct obstack *obstack,
23109                          enum bfd_endian byte_order,
23110                          struct type *type,
23111                          ULONGEST value,
23112                          LONGEST *len)
23113 {
23114   gdb_byte *result;
23115
23116   *len = TYPE_LENGTH (type);
23117   result = (gdb_byte *) obstack_alloc (obstack, *len);
23118   store_unsigned_integer (result, *len, byte_order, value);
23119
23120   return result;
23121 }
23122
23123 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23124    pointer to the constant bytes and set LEN to the length of the
23125    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23126    does not have a DW_AT_const_value, return NULL.  */
23127
23128 const gdb_byte *
23129 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23130                              struct dwarf2_per_cu_data *per_cu,
23131                              struct obstack *obstack,
23132                              LONGEST *len)
23133 {
23134   struct dwarf2_cu *cu;
23135   struct die_info *die;
23136   struct attribute *attr;
23137   const gdb_byte *result = NULL;
23138   struct type *type;
23139   LONGEST value;
23140   enum bfd_endian byte_order;
23141   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23142
23143   if (per_cu->cu == NULL)
23144     load_cu (per_cu);
23145   cu = per_cu->cu;
23146   if (cu == NULL)
23147     {
23148       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23149          Instead just throw an error, not much else we can do.  */
23150       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23151              sect_offset_str (sect_off), objfile_name (objfile));
23152     }
23153
23154   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23155   if (!die)
23156     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23157            sect_offset_str (sect_off), objfile_name (objfile));
23158
23159   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23160   if (attr == NULL)
23161     return NULL;
23162
23163   byte_order = (bfd_big_endian (objfile->obfd)
23164                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23165
23166   switch (attr->form)
23167     {
23168     case DW_FORM_addr:
23169     case DW_FORM_GNU_addr_index:
23170       {
23171         gdb_byte *tem;
23172
23173         *len = cu->header.addr_size;
23174         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23175         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23176         result = tem;
23177       }
23178       break;
23179     case DW_FORM_string:
23180     case DW_FORM_strp:
23181     case DW_FORM_GNU_str_index:
23182     case DW_FORM_GNU_strp_alt:
23183       /* DW_STRING is already allocated on the objfile obstack, point
23184          directly to it.  */
23185       result = (const gdb_byte *) DW_STRING (attr);
23186       *len = strlen (DW_STRING (attr));
23187       break;
23188     case DW_FORM_block1:
23189     case DW_FORM_block2:
23190     case DW_FORM_block4:
23191     case DW_FORM_block:
23192     case DW_FORM_exprloc:
23193     case DW_FORM_data16:
23194       result = DW_BLOCK (attr)->data;
23195       *len = DW_BLOCK (attr)->size;
23196       break;
23197
23198       /* The DW_AT_const_value attributes are supposed to carry the
23199          symbol's value "represented as it would be on the target
23200          architecture."  By the time we get here, it's already been
23201          converted to host endianness, so we just need to sign- or
23202          zero-extend it as appropriate.  */
23203     case DW_FORM_data1:
23204       type = die_type (die, cu);
23205       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23206       if (result == NULL)
23207         result = write_constant_as_bytes (obstack, byte_order,
23208                                           type, value, len);
23209       break;
23210     case DW_FORM_data2:
23211       type = die_type (die, cu);
23212       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23213       if (result == NULL)
23214         result = write_constant_as_bytes (obstack, byte_order,
23215                                           type, value, len);
23216       break;
23217     case DW_FORM_data4:
23218       type = die_type (die, cu);
23219       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23220       if (result == NULL)
23221         result = write_constant_as_bytes (obstack, byte_order,
23222                                           type, value, len);
23223       break;
23224     case DW_FORM_data8:
23225       type = die_type (die, cu);
23226       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23227       if (result == NULL)
23228         result = write_constant_as_bytes (obstack, byte_order,
23229                                           type, value, len);
23230       break;
23231
23232     case DW_FORM_sdata:
23233     case DW_FORM_implicit_const:
23234       type = die_type (die, cu);
23235       result = write_constant_as_bytes (obstack, byte_order,
23236                                         type, DW_SND (attr), len);
23237       break;
23238
23239     case DW_FORM_udata:
23240       type = die_type (die, cu);
23241       result = write_constant_as_bytes (obstack, byte_order,
23242                                         type, DW_UNSND (attr), len);
23243       break;
23244
23245     default:
23246       complaint (&symfile_complaints,
23247                  _("unsupported const value attribute form: '%s'"),
23248                  dwarf_form_name (attr->form));
23249       break;
23250     }
23251
23252   return result;
23253 }
23254
23255 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23256    valid type for this die is found.  */
23257
23258 struct type *
23259 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23260                                 struct dwarf2_per_cu_data *per_cu)
23261 {
23262   struct dwarf2_cu *cu;
23263   struct die_info *die;
23264
23265   if (per_cu->cu == NULL)
23266     load_cu (per_cu);
23267   cu = per_cu->cu;
23268   if (!cu)
23269     return NULL;
23270
23271   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23272   if (!die)
23273     return NULL;
23274
23275   return die_type (die, cu);
23276 }
23277
23278 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23279    PER_CU.  */
23280
23281 struct type *
23282 dwarf2_get_die_type (cu_offset die_offset,
23283                      struct dwarf2_per_cu_data *per_cu)
23284 {
23285   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23286   return get_die_type_at_offset (die_offset_sect, per_cu);
23287 }
23288
23289 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23290    On entry *REF_CU is the CU of SRC_DIE.
23291    On exit *REF_CU is the CU of the result.
23292    Returns NULL if the referenced DIE isn't found.  */
23293
23294 static struct die_info *
23295 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23296                   struct dwarf2_cu **ref_cu)
23297 {
23298   struct die_info temp_die;
23299   struct dwarf2_cu *sig_cu;
23300   struct die_info *die;
23301
23302   /* While it might be nice to assert sig_type->type == NULL here,
23303      we can get here for DW_AT_imported_declaration where we need
23304      the DIE not the type.  */
23305
23306   /* If necessary, add it to the queue and load its DIEs.  */
23307
23308   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23309     read_signatured_type (sig_type);
23310
23311   sig_cu = sig_type->per_cu.cu;
23312   gdb_assert (sig_cu != NULL);
23313   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23314   temp_die.sect_off = sig_type->type_offset_in_section;
23315   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23316                                                  to_underlying (temp_die.sect_off));
23317   if (die)
23318     {
23319       struct dwarf2_per_objfile *dwarf2_per_objfile
23320         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23321
23322       /* For .gdb_index version 7 keep track of included TUs.
23323          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23324       if (dwarf2_per_objfile->index_table != NULL
23325           && dwarf2_per_objfile->index_table->version <= 7)
23326         {
23327           VEC_safe_push (dwarf2_per_cu_ptr,
23328                          (*ref_cu)->per_cu->imported_symtabs,
23329                          sig_cu->per_cu);
23330         }
23331
23332       *ref_cu = sig_cu;
23333       return die;
23334     }
23335
23336   return NULL;
23337 }
23338
23339 /* Follow signatured type referenced by ATTR in SRC_DIE.
23340    On entry *REF_CU is the CU of SRC_DIE.
23341    On exit *REF_CU is the CU of the result.
23342    The result is the DIE of the type.
23343    If the referenced type cannot be found an error is thrown.  */
23344
23345 static struct die_info *
23346 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23347                 struct dwarf2_cu **ref_cu)
23348 {
23349   ULONGEST signature = DW_SIGNATURE (attr);
23350   struct signatured_type *sig_type;
23351   struct die_info *die;
23352
23353   gdb_assert (attr->form == DW_FORM_ref_sig8);
23354
23355   sig_type = lookup_signatured_type (*ref_cu, signature);
23356   /* sig_type will be NULL if the signatured type is missing from
23357      the debug info.  */
23358   if (sig_type == NULL)
23359     {
23360       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23361                " from DIE at %s [in module %s]"),
23362              hex_string (signature), sect_offset_str (src_die->sect_off),
23363              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23364     }
23365
23366   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23367   if (die == NULL)
23368     {
23369       dump_die_for_error (src_die);
23370       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23371                " from DIE at %s [in module %s]"),
23372              hex_string (signature), sect_offset_str (src_die->sect_off),
23373              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23374     }
23375
23376   return die;
23377 }
23378
23379 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23380    reading in and processing the type unit if necessary.  */
23381
23382 static struct type *
23383 get_signatured_type (struct die_info *die, ULONGEST signature,
23384                      struct dwarf2_cu *cu)
23385 {
23386   struct dwarf2_per_objfile *dwarf2_per_objfile
23387     = cu->per_cu->dwarf2_per_objfile;
23388   struct signatured_type *sig_type;
23389   struct dwarf2_cu *type_cu;
23390   struct die_info *type_die;
23391   struct type *type;
23392
23393   sig_type = lookup_signatured_type (cu, signature);
23394   /* sig_type will be NULL if the signatured type is missing from
23395      the debug info.  */
23396   if (sig_type == NULL)
23397     {
23398       complaint (&symfile_complaints,
23399                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23400                    " from DIE at %s [in module %s]"),
23401                  hex_string (signature), sect_offset_str (die->sect_off),
23402                  objfile_name (dwarf2_per_objfile->objfile));
23403       return build_error_marker_type (cu, die);
23404     }
23405
23406   /* If we already know the type we're done.  */
23407   if (sig_type->type != NULL)
23408     return sig_type->type;
23409
23410   type_cu = cu;
23411   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23412   if (type_die != NULL)
23413     {
23414       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23415          is created.  This is important, for example, because for c++ classes
23416          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23417       type = read_type_die (type_die, type_cu);
23418       if (type == NULL)
23419         {
23420           complaint (&symfile_complaints,
23421                      _("Dwarf Error: Cannot build signatured type %s"
23422                        " referenced from DIE at %s [in module %s]"),
23423                      hex_string (signature), sect_offset_str (die->sect_off),
23424                      objfile_name (dwarf2_per_objfile->objfile));
23425           type = build_error_marker_type (cu, die);
23426         }
23427     }
23428   else
23429     {
23430       complaint (&symfile_complaints,
23431                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23432                    " from DIE at %s [in module %s]"),
23433                  hex_string (signature), sect_offset_str (die->sect_off),
23434                  objfile_name (dwarf2_per_objfile->objfile));
23435       type = build_error_marker_type (cu, die);
23436     }
23437   sig_type->type = type;
23438
23439   return type;
23440 }
23441
23442 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23443    reading in and processing the type unit if necessary.  */
23444
23445 static struct type *
23446 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23447                           struct dwarf2_cu *cu) /* ARI: editCase function */
23448 {
23449   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23450   if (attr_form_is_ref (attr))
23451     {
23452       struct dwarf2_cu *type_cu = cu;
23453       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23454
23455       return read_type_die (type_die, type_cu);
23456     }
23457   else if (attr->form == DW_FORM_ref_sig8)
23458     {
23459       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23460     }
23461   else
23462     {
23463       struct dwarf2_per_objfile *dwarf2_per_objfile
23464         = cu->per_cu->dwarf2_per_objfile;
23465
23466       complaint (&symfile_complaints,
23467                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23468                    " at %s [in module %s]"),
23469                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23470                  objfile_name (dwarf2_per_objfile->objfile));
23471       return build_error_marker_type (cu, die);
23472     }
23473 }
23474
23475 /* Load the DIEs associated with type unit PER_CU into memory.  */
23476
23477 static void
23478 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23479 {
23480   struct signatured_type *sig_type;
23481
23482   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23483   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23484
23485   /* We have the per_cu, but we need the signatured_type.
23486      Fortunately this is an easy translation.  */
23487   gdb_assert (per_cu->is_debug_types);
23488   sig_type = (struct signatured_type *) per_cu;
23489
23490   gdb_assert (per_cu->cu == NULL);
23491
23492   read_signatured_type (sig_type);
23493
23494   gdb_assert (per_cu->cu != NULL);
23495 }
23496
23497 /* die_reader_func for read_signatured_type.
23498    This is identical to load_full_comp_unit_reader,
23499    but is kept separate for now.  */
23500
23501 static void
23502 read_signatured_type_reader (const struct die_reader_specs *reader,
23503                              const gdb_byte *info_ptr,
23504                              struct die_info *comp_unit_die,
23505                              int has_children,
23506                              void *data)
23507 {
23508   struct dwarf2_cu *cu = reader->cu;
23509
23510   gdb_assert (cu->die_hash == NULL);
23511   cu->die_hash =
23512     htab_create_alloc_ex (cu->header.length / 12,
23513                           die_hash,
23514                           die_eq,
23515                           NULL,
23516                           &cu->comp_unit_obstack,
23517                           hashtab_obstack_allocate,
23518                           dummy_obstack_deallocate);
23519
23520   if (has_children)
23521     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23522                                                   &info_ptr, comp_unit_die);
23523   cu->dies = comp_unit_die;
23524   /* comp_unit_die is not stored in die_hash, no need.  */
23525
23526   /* We try not to read any attributes in this function, because not
23527      all CUs needed for references have been loaded yet, and symbol
23528      table processing isn't initialized.  But we have to set the CU language,
23529      or we won't be able to build types correctly.
23530      Similarly, if we do not read the producer, we can not apply
23531      producer-specific interpretation.  */
23532   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23533 }
23534
23535 /* Read in a signatured type and build its CU and DIEs.
23536    If the type is a stub for the real type in a DWO file,
23537    read in the real type from the DWO file as well.  */
23538
23539 static void
23540 read_signatured_type (struct signatured_type *sig_type)
23541 {
23542   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23543
23544   gdb_assert (per_cu->is_debug_types);
23545   gdb_assert (per_cu->cu == NULL);
23546
23547   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23548                            read_signatured_type_reader, NULL);
23549   sig_type->per_cu.tu_read = 1;
23550 }
23551
23552 /* Decode simple location descriptions.
23553    Given a pointer to a dwarf block that defines a location, compute
23554    the location and return the value.
23555
23556    NOTE drow/2003-11-18: This function is called in two situations
23557    now: for the address of static or global variables (partial symbols
23558    only) and for offsets into structures which are expected to be
23559    (more or less) constant.  The partial symbol case should go away,
23560    and only the constant case should remain.  That will let this
23561    function complain more accurately.  A few special modes are allowed
23562    without complaint for global variables (for instance, global
23563    register values and thread-local values).
23564
23565    A location description containing no operations indicates that the
23566    object is optimized out.  The return value is 0 for that case.
23567    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23568    callers will only want a very basic result and this can become a
23569    complaint.
23570
23571    Note that stack[0] is unused except as a default error return.  */
23572
23573 static CORE_ADDR
23574 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23575 {
23576   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23577   size_t i;
23578   size_t size = blk->size;
23579   const gdb_byte *data = blk->data;
23580   CORE_ADDR stack[64];
23581   int stacki;
23582   unsigned int bytes_read, unsnd;
23583   gdb_byte op;
23584
23585   i = 0;
23586   stacki = 0;
23587   stack[stacki] = 0;
23588   stack[++stacki] = 0;
23589
23590   while (i < size)
23591     {
23592       op = data[i++];
23593       switch (op)
23594         {
23595         case DW_OP_lit0:
23596         case DW_OP_lit1:
23597         case DW_OP_lit2:
23598         case DW_OP_lit3:
23599         case DW_OP_lit4:
23600         case DW_OP_lit5:
23601         case DW_OP_lit6:
23602         case DW_OP_lit7:
23603         case DW_OP_lit8:
23604         case DW_OP_lit9:
23605         case DW_OP_lit10:
23606         case DW_OP_lit11:
23607         case DW_OP_lit12:
23608         case DW_OP_lit13:
23609         case DW_OP_lit14:
23610         case DW_OP_lit15:
23611         case DW_OP_lit16:
23612         case DW_OP_lit17:
23613         case DW_OP_lit18:
23614         case DW_OP_lit19:
23615         case DW_OP_lit20:
23616         case DW_OP_lit21:
23617         case DW_OP_lit22:
23618         case DW_OP_lit23:
23619         case DW_OP_lit24:
23620         case DW_OP_lit25:
23621         case DW_OP_lit26:
23622         case DW_OP_lit27:
23623         case DW_OP_lit28:
23624         case DW_OP_lit29:
23625         case DW_OP_lit30:
23626         case DW_OP_lit31:
23627           stack[++stacki] = op - DW_OP_lit0;
23628           break;
23629
23630         case DW_OP_reg0:
23631         case DW_OP_reg1:
23632         case DW_OP_reg2:
23633         case DW_OP_reg3:
23634         case DW_OP_reg4:
23635         case DW_OP_reg5:
23636         case DW_OP_reg6:
23637         case DW_OP_reg7:
23638         case DW_OP_reg8:
23639         case DW_OP_reg9:
23640         case DW_OP_reg10:
23641         case DW_OP_reg11:
23642         case DW_OP_reg12:
23643         case DW_OP_reg13:
23644         case DW_OP_reg14:
23645         case DW_OP_reg15:
23646         case DW_OP_reg16:
23647         case DW_OP_reg17:
23648         case DW_OP_reg18:
23649         case DW_OP_reg19:
23650         case DW_OP_reg20:
23651         case DW_OP_reg21:
23652         case DW_OP_reg22:
23653         case DW_OP_reg23:
23654         case DW_OP_reg24:
23655         case DW_OP_reg25:
23656         case DW_OP_reg26:
23657         case DW_OP_reg27:
23658         case DW_OP_reg28:
23659         case DW_OP_reg29:
23660         case DW_OP_reg30:
23661         case DW_OP_reg31:
23662           stack[++stacki] = op - DW_OP_reg0;
23663           if (i < size)
23664             dwarf2_complex_location_expr_complaint ();
23665           break;
23666
23667         case DW_OP_regx:
23668           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23669           i += bytes_read;
23670           stack[++stacki] = unsnd;
23671           if (i < size)
23672             dwarf2_complex_location_expr_complaint ();
23673           break;
23674
23675         case DW_OP_addr:
23676           stack[++stacki] = read_address (objfile->obfd, &data[i],
23677                                           cu, &bytes_read);
23678           i += bytes_read;
23679           break;
23680
23681         case DW_OP_const1u:
23682           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23683           i += 1;
23684           break;
23685
23686         case DW_OP_const1s:
23687           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23688           i += 1;
23689           break;
23690
23691         case DW_OP_const2u:
23692           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23693           i += 2;
23694           break;
23695
23696         case DW_OP_const2s:
23697           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23698           i += 2;
23699           break;
23700
23701         case DW_OP_const4u:
23702           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23703           i += 4;
23704           break;
23705
23706         case DW_OP_const4s:
23707           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23708           i += 4;
23709           break;
23710
23711         case DW_OP_const8u:
23712           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23713           i += 8;
23714           break;
23715
23716         case DW_OP_constu:
23717           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23718                                                   &bytes_read);
23719           i += bytes_read;
23720           break;
23721
23722         case DW_OP_consts:
23723           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23724           i += bytes_read;
23725           break;
23726
23727         case DW_OP_dup:
23728           stack[stacki + 1] = stack[stacki];
23729           stacki++;
23730           break;
23731
23732         case DW_OP_plus:
23733           stack[stacki - 1] += stack[stacki];
23734           stacki--;
23735           break;
23736
23737         case DW_OP_plus_uconst:
23738           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23739                                                  &bytes_read);
23740           i += bytes_read;
23741           break;
23742
23743         case DW_OP_minus:
23744           stack[stacki - 1] -= stack[stacki];
23745           stacki--;
23746           break;
23747
23748         case DW_OP_deref:
23749           /* If we're not the last op, then we definitely can't encode
23750              this using GDB's address_class enum.  This is valid for partial
23751              global symbols, although the variable's address will be bogus
23752              in the psymtab.  */
23753           if (i < size)
23754             dwarf2_complex_location_expr_complaint ();
23755           break;
23756
23757         case DW_OP_GNU_push_tls_address:
23758         case DW_OP_form_tls_address:
23759           /* The top of the stack has the offset from the beginning
23760              of the thread control block at which the variable is located.  */
23761           /* Nothing should follow this operator, so the top of stack would
23762              be returned.  */
23763           /* This is valid for partial global symbols, but the variable's
23764              address will be bogus in the psymtab.  Make it always at least
23765              non-zero to not look as a variable garbage collected by linker
23766              which have DW_OP_addr 0.  */
23767           if (i < size)
23768             dwarf2_complex_location_expr_complaint ();
23769           stack[stacki]++;
23770           break;
23771
23772         case DW_OP_GNU_uninit:
23773           break;
23774
23775         case DW_OP_GNU_addr_index:
23776         case DW_OP_GNU_const_index:
23777           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23778                                                          &bytes_read);
23779           i += bytes_read;
23780           break;
23781
23782         default:
23783           {
23784             const char *name = get_DW_OP_name (op);
23785
23786             if (name)
23787               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23788                          name);
23789             else
23790               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23791                          op);
23792           }
23793
23794           return (stack[stacki]);
23795         }
23796
23797       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23798          outside of the allocated space.  Also enforce minimum>0.  */
23799       if (stacki >= ARRAY_SIZE (stack) - 1)
23800         {
23801           complaint (&symfile_complaints,
23802                      _("location description stack overflow"));
23803           return 0;
23804         }
23805
23806       if (stacki <= 0)
23807         {
23808           complaint (&symfile_complaints,
23809                      _("location description stack underflow"));
23810           return 0;
23811         }
23812     }
23813   return (stack[stacki]);
23814 }
23815
23816 /* memory allocation interface */
23817
23818 static struct dwarf_block *
23819 dwarf_alloc_block (struct dwarf2_cu *cu)
23820 {
23821   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23822 }
23823
23824 static struct die_info *
23825 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23826 {
23827   struct die_info *die;
23828   size_t size = sizeof (struct die_info);
23829
23830   if (num_attrs > 1)
23831     size += (num_attrs - 1) * sizeof (struct attribute);
23832
23833   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23834   memset (die, 0, sizeof (struct die_info));
23835   return (die);
23836 }
23837
23838 \f
23839 /* Macro support.  */
23840
23841 /* Return file name relative to the compilation directory of file number I in
23842    *LH's file name table.  The result is allocated using xmalloc; the caller is
23843    responsible for freeing it.  */
23844
23845 static char *
23846 file_file_name (int file, struct line_header *lh)
23847 {
23848   /* Is the file number a valid index into the line header's file name
23849      table?  Remember that file numbers start with one, not zero.  */
23850   if (1 <= file && file <= lh->file_names.size ())
23851     {
23852       const file_entry &fe = lh->file_names[file - 1];
23853
23854       if (!IS_ABSOLUTE_PATH (fe.name))
23855         {
23856           const char *dir = fe.include_dir (lh);
23857           if (dir != NULL)
23858             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23859         }
23860       return xstrdup (fe.name);
23861     }
23862   else
23863     {
23864       /* The compiler produced a bogus file number.  We can at least
23865          record the macro definitions made in the file, even if we
23866          won't be able to find the file by name.  */
23867       char fake_name[80];
23868
23869       xsnprintf (fake_name, sizeof (fake_name),
23870                  "<bad macro file number %d>", file);
23871
23872       complaint (&symfile_complaints,
23873                  _("bad file number in macro information (%d)"),
23874                  file);
23875
23876       return xstrdup (fake_name);
23877     }
23878 }
23879
23880 /* Return the full name of file number I in *LH's file name table.
23881    Use COMP_DIR as the name of the current directory of the
23882    compilation.  The result is allocated using xmalloc; the caller is
23883    responsible for freeing it.  */
23884 static char *
23885 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23886 {
23887   /* Is the file number a valid index into the line header's file name
23888      table?  Remember that file numbers start with one, not zero.  */
23889   if (1 <= file && file <= lh->file_names.size ())
23890     {
23891       char *relative = file_file_name (file, lh);
23892
23893       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23894         return relative;
23895       return reconcat (relative, comp_dir, SLASH_STRING,
23896                        relative, (char *) NULL);
23897     }
23898   else
23899     return file_file_name (file, lh);
23900 }
23901
23902
23903 static struct macro_source_file *
23904 macro_start_file (int file, int line,
23905                   struct macro_source_file *current_file,
23906                   struct line_header *lh)
23907 {
23908   /* File name relative to the compilation directory of this source file.  */
23909   char *file_name = file_file_name (file, lh);
23910
23911   if (! current_file)
23912     {
23913       /* Note: We don't create a macro table for this compilation unit
23914          at all until we actually get a filename.  */
23915       struct macro_table *macro_table = get_macro_table ();
23916
23917       /* If we have no current file, then this must be the start_file
23918          directive for the compilation unit's main source file.  */
23919       current_file = macro_set_main (macro_table, file_name);
23920       macro_define_special (macro_table);
23921     }
23922   else
23923     current_file = macro_include (current_file, line, file_name);
23924
23925   xfree (file_name);
23926
23927   return current_file;
23928 }
23929
23930 static const char *
23931 consume_improper_spaces (const char *p, const char *body)
23932 {
23933   if (*p == ' ')
23934     {
23935       complaint (&symfile_complaints,
23936                  _("macro definition contains spaces "
23937                    "in formal argument list:\n`%s'"),
23938                  body);
23939
23940       while (*p == ' ')
23941         p++;
23942     }
23943
23944   return p;
23945 }
23946
23947
23948 static void
23949 parse_macro_definition (struct macro_source_file *file, int line,
23950                         const char *body)
23951 {
23952   const char *p;
23953
23954   /* The body string takes one of two forms.  For object-like macro
23955      definitions, it should be:
23956
23957         <macro name> " " <definition>
23958
23959      For function-like macro definitions, it should be:
23960
23961         <macro name> "() " <definition>
23962      or
23963         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23964
23965      Spaces may appear only where explicitly indicated, and in the
23966      <definition>.
23967
23968      The Dwarf 2 spec says that an object-like macro's name is always
23969      followed by a space, but versions of GCC around March 2002 omit
23970      the space when the macro's definition is the empty string.
23971
23972      The Dwarf 2 spec says that there should be no spaces between the
23973      formal arguments in a function-like macro's formal argument list,
23974      but versions of GCC around March 2002 include spaces after the
23975      commas.  */
23976
23977
23978   /* Find the extent of the macro name.  The macro name is terminated
23979      by either a space or null character (for an object-like macro) or
23980      an opening paren (for a function-like macro).  */
23981   for (p = body; *p; p++)
23982     if (*p == ' ' || *p == '(')
23983       break;
23984
23985   if (*p == ' ' || *p == '\0')
23986     {
23987       /* It's an object-like macro.  */
23988       int name_len = p - body;
23989       char *name = savestring (body, name_len);
23990       const char *replacement;
23991
23992       if (*p == ' ')
23993         replacement = body + name_len + 1;
23994       else
23995         {
23996           dwarf2_macro_malformed_definition_complaint (body);
23997           replacement = body + name_len;
23998         }
23999
24000       macro_define_object (file, line, name, replacement);
24001
24002       xfree (name);
24003     }
24004   else if (*p == '(')
24005     {
24006       /* It's a function-like macro.  */
24007       char *name = savestring (body, p - body);
24008       int argc = 0;
24009       int argv_size = 1;
24010       char **argv = XNEWVEC (char *, argv_size);
24011
24012       p++;
24013
24014       p = consume_improper_spaces (p, body);
24015
24016       /* Parse the formal argument list.  */
24017       while (*p && *p != ')')
24018         {
24019           /* Find the extent of the current argument name.  */
24020           const char *arg_start = p;
24021
24022           while (*p && *p != ',' && *p != ')' && *p != ' ')
24023             p++;
24024
24025           if (! *p || p == arg_start)
24026             dwarf2_macro_malformed_definition_complaint (body);
24027           else
24028             {
24029               /* Make sure argv has room for the new argument.  */
24030               if (argc >= argv_size)
24031                 {
24032                   argv_size *= 2;
24033                   argv = XRESIZEVEC (char *, argv, argv_size);
24034                 }
24035
24036               argv[argc++] = savestring (arg_start, p - arg_start);
24037             }
24038
24039           p = consume_improper_spaces (p, body);
24040
24041           /* Consume the comma, if present.  */
24042           if (*p == ',')
24043             {
24044               p++;
24045
24046               p = consume_improper_spaces (p, body);
24047             }
24048         }
24049
24050       if (*p == ')')
24051         {
24052           p++;
24053
24054           if (*p == ' ')
24055             /* Perfectly formed definition, no complaints.  */
24056             macro_define_function (file, line, name,
24057                                    argc, (const char **) argv,
24058                                    p + 1);
24059           else if (*p == '\0')
24060             {
24061               /* Complain, but do define it.  */
24062               dwarf2_macro_malformed_definition_complaint (body);
24063               macro_define_function (file, line, name,
24064                                      argc, (const char **) argv,
24065                                      p);
24066             }
24067           else
24068             /* Just complain.  */
24069             dwarf2_macro_malformed_definition_complaint (body);
24070         }
24071       else
24072         /* Just complain.  */
24073         dwarf2_macro_malformed_definition_complaint (body);
24074
24075       xfree (name);
24076       {
24077         int i;
24078
24079         for (i = 0; i < argc; i++)
24080           xfree (argv[i]);
24081       }
24082       xfree (argv);
24083     }
24084   else
24085     dwarf2_macro_malformed_definition_complaint (body);
24086 }
24087
24088 /* Skip some bytes from BYTES according to the form given in FORM.
24089    Returns the new pointer.  */
24090
24091 static const gdb_byte *
24092 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24093                  enum dwarf_form form,
24094                  unsigned int offset_size,
24095                  struct dwarf2_section_info *section)
24096 {
24097   unsigned int bytes_read;
24098
24099   switch (form)
24100     {
24101     case DW_FORM_data1:
24102     case DW_FORM_flag:
24103       ++bytes;
24104       break;
24105
24106     case DW_FORM_data2:
24107       bytes += 2;
24108       break;
24109
24110     case DW_FORM_data4:
24111       bytes += 4;
24112       break;
24113
24114     case DW_FORM_data8:
24115       bytes += 8;
24116       break;
24117
24118     case DW_FORM_data16:
24119       bytes += 16;
24120       break;
24121
24122     case DW_FORM_string:
24123       read_direct_string (abfd, bytes, &bytes_read);
24124       bytes += bytes_read;
24125       break;
24126
24127     case DW_FORM_sec_offset:
24128     case DW_FORM_strp:
24129     case DW_FORM_GNU_strp_alt:
24130       bytes += offset_size;
24131       break;
24132
24133     case DW_FORM_block:
24134       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24135       bytes += bytes_read;
24136       break;
24137
24138     case DW_FORM_block1:
24139       bytes += 1 + read_1_byte (abfd, bytes);
24140       break;
24141     case DW_FORM_block2:
24142       bytes += 2 + read_2_bytes (abfd, bytes);
24143       break;
24144     case DW_FORM_block4:
24145       bytes += 4 + read_4_bytes (abfd, bytes);
24146       break;
24147
24148     case DW_FORM_sdata:
24149     case DW_FORM_udata:
24150     case DW_FORM_GNU_addr_index:
24151     case DW_FORM_GNU_str_index:
24152       bytes = gdb_skip_leb128 (bytes, buffer_end);
24153       if (bytes == NULL)
24154         {
24155           dwarf2_section_buffer_overflow_complaint (section);
24156           return NULL;
24157         }
24158       break;
24159
24160     case DW_FORM_implicit_const:
24161       break;
24162
24163     default:
24164       {
24165         complaint (&symfile_complaints,
24166                    _("invalid form 0x%x in `%s'"),
24167                    form, get_section_name (section));
24168         return NULL;
24169       }
24170     }
24171
24172   return bytes;
24173 }
24174
24175 /* A helper for dwarf_decode_macros that handles skipping an unknown
24176    opcode.  Returns an updated pointer to the macro data buffer; or,
24177    on error, issues a complaint and returns NULL.  */
24178
24179 static const gdb_byte *
24180 skip_unknown_opcode (unsigned int opcode,
24181                      const gdb_byte **opcode_definitions,
24182                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24183                      bfd *abfd,
24184                      unsigned int offset_size,
24185                      struct dwarf2_section_info *section)
24186 {
24187   unsigned int bytes_read, i;
24188   unsigned long arg;
24189   const gdb_byte *defn;
24190
24191   if (opcode_definitions[opcode] == NULL)
24192     {
24193       complaint (&symfile_complaints,
24194                  _("unrecognized DW_MACFINO opcode 0x%x"),
24195                  opcode);
24196       return NULL;
24197     }
24198
24199   defn = opcode_definitions[opcode];
24200   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24201   defn += bytes_read;
24202
24203   for (i = 0; i < arg; ++i)
24204     {
24205       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24206                                  (enum dwarf_form) defn[i], offset_size,
24207                                  section);
24208       if (mac_ptr == NULL)
24209         {
24210           /* skip_form_bytes already issued the complaint.  */
24211           return NULL;
24212         }
24213     }
24214
24215   return mac_ptr;
24216 }
24217
24218 /* A helper function which parses the header of a macro section.
24219    If the macro section is the extended (for now called "GNU") type,
24220    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24221    the header, or issues a complaint and returns NULL on error.  */
24222
24223 static const gdb_byte *
24224 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24225                           bfd *abfd,
24226                           const gdb_byte *mac_ptr,
24227                           unsigned int *offset_size,
24228                           int section_is_gnu)
24229 {
24230   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24231
24232   if (section_is_gnu)
24233     {
24234       unsigned int version, flags;
24235
24236       version = read_2_bytes (abfd, mac_ptr);
24237       if (version != 4 && version != 5)
24238         {
24239           complaint (&symfile_complaints,
24240                      _("unrecognized version `%d' in .debug_macro section"),
24241                      version);
24242           return NULL;
24243         }
24244       mac_ptr += 2;
24245
24246       flags = read_1_byte (abfd, mac_ptr);
24247       ++mac_ptr;
24248       *offset_size = (flags & 1) ? 8 : 4;
24249
24250       if ((flags & 2) != 0)
24251         /* We don't need the line table offset.  */
24252         mac_ptr += *offset_size;
24253
24254       /* Vendor opcode descriptions.  */
24255       if ((flags & 4) != 0)
24256         {
24257           unsigned int i, count;
24258
24259           count = read_1_byte (abfd, mac_ptr);
24260           ++mac_ptr;
24261           for (i = 0; i < count; ++i)
24262             {
24263               unsigned int opcode, bytes_read;
24264               unsigned long arg;
24265
24266               opcode = read_1_byte (abfd, mac_ptr);
24267               ++mac_ptr;
24268               opcode_definitions[opcode] = mac_ptr;
24269               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24270               mac_ptr += bytes_read;
24271               mac_ptr += arg;
24272             }
24273         }
24274     }
24275
24276   return mac_ptr;
24277 }
24278
24279 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24280    including DW_MACRO_import.  */
24281
24282 static void
24283 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24284                           bfd *abfd,
24285                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24286                           struct macro_source_file *current_file,
24287                           struct line_header *lh,
24288                           struct dwarf2_section_info *section,
24289                           int section_is_gnu, int section_is_dwz,
24290                           unsigned int offset_size,
24291                           htab_t include_hash)
24292 {
24293   struct objfile *objfile = dwarf2_per_objfile->objfile;
24294   enum dwarf_macro_record_type macinfo_type;
24295   int at_commandline;
24296   const gdb_byte *opcode_definitions[256];
24297
24298   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24299                                       &offset_size, section_is_gnu);
24300   if (mac_ptr == NULL)
24301     {
24302       /* We already issued a complaint.  */
24303       return;
24304     }
24305
24306   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24307      GDB is still reading the definitions from command line.  First
24308      DW_MACINFO_start_file will need to be ignored as it was already executed
24309      to create CURRENT_FILE for the main source holding also the command line
24310      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24311      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24312
24313   at_commandline = 1;
24314
24315   do
24316     {
24317       /* Do we at least have room for a macinfo type byte?  */
24318       if (mac_ptr >= mac_end)
24319         {
24320           dwarf2_section_buffer_overflow_complaint (section);
24321           break;
24322         }
24323
24324       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24325       mac_ptr++;
24326
24327       /* Note that we rely on the fact that the corresponding GNU and
24328          DWARF constants are the same.  */
24329       DIAGNOSTIC_PUSH
24330       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24331       switch (macinfo_type)
24332         {
24333           /* A zero macinfo type indicates the end of the macro
24334              information.  */
24335         case 0:
24336           break;
24337
24338         case DW_MACRO_define:
24339         case DW_MACRO_undef:
24340         case DW_MACRO_define_strp:
24341         case DW_MACRO_undef_strp:
24342         case DW_MACRO_define_sup:
24343         case DW_MACRO_undef_sup:
24344           {
24345             unsigned int bytes_read;
24346             int line;
24347             const char *body;
24348             int is_define;
24349
24350             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24351             mac_ptr += bytes_read;
24352
24353             if (macinfo_type == DW_MACRO_define
24354                 || macinfo_type == DW_MACRO_undef)
24355               {
24356                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24357                 mac_ptr += bytes_read;
24358               }
24359             else
24360               {
24361                 LONGEST str_offset;
24362
24363                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24364                 mac_ptr += offset_size;
24365
24366                 if (macinfo_type == DW_MACRO_define_sup
24367                     || macinfo_type == DW_MACRO_undef_sup
24368                     || section_is_dwz)
24369                   {
24370                     struct dwz_file *dwz
24371                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24372
24373                     body = read_indirect_string_from_dwz (objfile,
24374                                                           dwz, str_offset);
24375                   }
24376                 else
24377                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24378                                                          abfd, str_offset);
24379               }
24380
24381             is_define = (macinfo_type == DW_MACRO_define
24382                          || macinfo_type == DW_MACRO_define_strp
24383                          || macinfo_type == DW_MACRO_define_sup);
24384             if (! current_file)
24385               {
24386                 /* DWARF violation as no main source is present.  */
24387                 complaint (&symfile_complaints,
24388                            _("debug info with no main source gives macro %s "
24389                              "on line %d: %s"),
24390                            is_define ? _("definition") : _("undefinition"),
24391                            line, body);
24392                 break;
24393               }
24394             if ((line == 0 && !at_commandline)
24395                 || (line != 0 && at_commandline))
24396               complaint (&symfile_complaints,
24397                          _("debug info gives %s macro %s with %s line %d: %s"),
24398                          at_commandline ? _("command-line") : _("in-file"),
24399                          is_define ? _("definition") : _("undefinition"),
24400                          line == 0 ? _("zero") : _("non-zero"), line, body);
24401
24402             if (is_define)
24403               parse_macro_definition (current_file, line, body);
24404             else
24405               {
24406                 gdb_assert (macinfo_type == DW_MACRO_undef
24407                             || macinfo_type == DW_MACRO_undef_strp
24408                             || macinfo_type == DW_MACRO_undef_sup);
24409                 macro_undef (current_file, line, body);
24410               }
24411           }
24412           break;
24413
24414         case DW_MACRO_start_file:
24415           {
24416             unsigned int bytes_read;
24417             int line, file;
24418
24419             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24420             mac_ptr += bytes_read;
24421             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24422             mac_ptr += bytes_read;
24423
24424             if ((line == 0 && !at_commandline)
24425                 || (line != 0 && at_commandline))
24426               complaint (&symfile_complaints,
24427                          _("debug info gives source %d included "
24428                            "from %s at %s line %d"),
24429                          file, at_commandline ? _("command-line") : _("file"),
24430                          line == 0 ? _("zero") : _("non-zero"), line);
24431
24432             if (at_commandline)
24433               {
24434                 /* This DW_MACRO_start_file was executed in the
24435                    pass one.  */
24436                 at_commandline = 0;
24437               }
24438             else
24439               current_file = macro_start_file (file, line, current_file, lh);
24440           }
24441           break;
24442
24443         case DW_MACRO_end_file:
24444           if (! current_file)
24445             complaint (&symfile_complaints,
24446                        _("macro debug info has an unmatched "
24447                          "`close_file' directive"));
24448           else
24449             {
24450               current_file = current_file->included_by;
24451               if (! current_file)
24452                 {
24453                   enum dwarf_macro_record_type next_type;
24454
24455                   /* GCC circa March 2002 doesn't produce the zero
24456                      type byte marking the end of the compilation
24457                      unit.  Complain if it's not there, but exit no
24458                      matter what.  */
24459
24460                   /* Do we at least have room for a macinfo type byte?  */
24461                   if (mac_ptr >= mac_end)
24462                     {
24463                       dwarf2_section_buffer_overflow_complaint (section);
24464                       return;
24465                     }
24466
24467                   /* We don't increment mac_ptr here, so this is just
24468                      a look-ahead.  */
24469                   next_type
24470                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24471                                                                   mac_ptr);
24472                   if (next_type != 0)
24473                     complaint (&symfile_complaints,
24474                                _("no terminating 0-type entry for "
24475                                  "macros in `.debug_macinfo' section"));
24476
24477                   return;
24478                 }
24479             }
24480           break;
24481
24482         case DW_MACRO_import:
24483         case DW_MACRO_import_sup:
24484           {
24485             LONGEST offset;
24486             void **slot;
24487             bfd *include_bfd = abfd;
24488             struct dwarf2_section_info *include_section = section;
24489             const gdb_byte *include_mac_end = mac_end;
24490             int is_dwz = section_is_dwz;
24491             const gdb_byte *new_mac_ptr;
24492
24493             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24494             mac_ptr += offset_size;
24495
24496             if (macinfo_type == DW_MACRO_import_sup)
24497               {
24498                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24499
24500                 dwarf2_read_section (objfile, &dwz->macro);
24501
24502                 include_section = &dwz->macro;
24503                 include_bfd = get_section_bfd_owner (include_section);
24504                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24505                 is_dwz = 1;
24506               }
24507
24508             new_mac_ptr = include_section->buffer + offset;
24509             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24510
24511             if (*slot != NULL)
24512               {
24513                 /* This has actually happened; see
24514                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24515                 complaint (&symfile_complaints,
24516                            _("recursive DW_MACRO_import in "
24517                              ".debug_macro section"));
24518               }
24519             else
24520               {
24521                 *slot = (void *) new_mac_ptr;
24522
24523                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24524                                           include_bfd, new_mac_ptr,
24525                                           include_mac_end, current_file, lh,
24526                                           section, section_is_gnu, is_dwz,
24527                                           offset_size, include_hash);
24528
24529                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24530               }
24531           }
24532           break;
24533
24534         case DW_MACINFO_vendor_ext:
24535           if (!section_is_gnu)
24536             {
24537               unsigned int bytes_read;
24538
24539               /* This reads the constant, but since we don't recognize
24540                  any vendor extensions, we ignore it.  */
24541               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24542               mac_ptr += bytes_read;
24543               read_direct_string (abfd, mac_ptr, &bytes_read);
24544               mac_ptr += bytes_read;
24545
24546               /* We don't recognize any vendor extensions.  */
24547               break;
24548             }
24549           /* FALLTHROUGH */
24550
24551         default:
24552           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24553                                          mac_ptr, mac_end, abfd, offset_size,
24554                                          section);
24555           if (mac_ptr == NULL)
24556             return;
24557           break;
24558         }
24559       DIAGNOSTIC_POP
24560     } while (macinfo_type != 0);
24561 }
24562
24563 static void
24564 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24565                      int section_is_gnu)
24566 {
24567   struct dwarf2_per_objfile *dwarf2_per_objfile
24568     = cu->per_cu->dwarf2_per_objfile;
24569   struct objfile *objfile = dwarf2_per_objfile->objfile;
24570   struct line_header *lh = cu->line_header;
24571   bfd *abfd;
24572   const gdb_byte *mac_ptr, *mac_end;
24573   struct macro_source_file *current_file = 0;
24574   enum dwarf_macro_record_type macinfo_type;
24575   unsigned int offset_size = cu->header.offset_size;
24576   const gdb_byte *opcode_definitions[256];
24577   void **slot;
24578   struct dwarf2_section_info *section;
24579   const char *section_name;
24580
24581   if (cu->dwo_unit != NULL)
24582     {
24583       if (section_is_gnu)
24584         {
24585           section = &cu->dwo_unit->dwo_file->sections.macro;
24586           section_name = ".debug_macro.dwo";
24587         }
24588       else
24589         {
24590           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24591           section_name = ".debug_macinfo.dwo";
24592         }
24593     }
24594   else
24595     {
24596       if (section_is_gnu)
24597         {
24598           section = &dwarf2_per_objfile->macro;
24599           section_name = ".debug_macro";
24600         }
24601       else
24602         {
24603           section = &dwarf2_per_objfile->macinfo;
24604           section_name = ".debug_macinfo";
24605         }
24606     }
24607
24608   dwarf2_read_section (objfile, section);
24609   if (section->buffer == NULL)
24610     {
24611       complaint (&symfile_complaints, _("missing %s section"), section_name);
24612       return;
24613     }
24614   abfd = get_section_bfd_owner (section);
24615
24616   /* First pass: Find the name of the base filename.
24617      This filename is needed in order to process all macros whose definition
24618      (or undefinition) comes from the command line.  These macros are defined
24619      before the first DW_MACINFO_start_file entry, and yet still need to be
24620      associated to the base file.
24621
24622      To determine the base file name, we scan the macro definitions until we
24623      reach the first DW_MACINFO_start_file entry.  We then initialize
24624      CURRENT_FILE accordingly so that any macro definition found before the
24625      first DW_MACINFO_start_file can still be associated to the base file.  */
24626
24627   mac_ptr = section->buffer + offset;
24628   mac_end = section->buffer + section->size;
24629
24630   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24631                                       &offset_size, section_is_gnu);
24632   if (mac_ptr == NULL)
24633     {
24634       /* We already issued a complaint.  */
24635       return;
24636     }
24637
24638   do
24639     {
24640       /* Do we at least have room for a macinfo type byte?  */
24641       if (mac_ptr >= mac_end)
24642         {
24643           /* Complaint is printed during the second pass as GDB will probably
24644              stop the first pass earlier upon finding
24645              DW_MACINFO_start_file.  */
24646           break;
24647         }
24648
24649       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24650       mac_ptr++;
24651
24652       /* Note that we rely on the fact that the corresponding GNU and
24653          DWARF constants are the same.  */
24654       DIAGNOSTIC_PUSH
24655       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24656       switch (macinfo_type)
24657         {
24658           /* A zero macinfo type indicates the end of the macro
24659              information.  */
24660         case 0:
24661           break;
24662
24663         case DW_MACRO_define:
24664         case DW_MACRO_undef:
24665           /* Only skip the data by MAC_PTR.  */
24666           {
24667             unsigned int bytes_read;
24668
24669             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24670             mac_ptr += bytes_read;
24671             read_direct_string (abfd, mac_ptr, &bytes_read);
24672             mac_ptr += bytes_read;
24673           }
24674           break;
24675
24676         case DW_MACRO_start_file:
24677           {
24678             unsigned int bytes_read;
24679             int line, file;
24680
24681             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24682             mac_ptr += bytes_read;
24683             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24684             mac_ptr += bytes_read;
24685
24686             current_file = macro_start_file (file, line, current_file, lh);
24687           }
24688           break;
24689
24690         case DW_MACRO_end_file:
24691           /* No data to skip by MAC_PTR.  */
24692           break;
24693
24694         case DW_MACRO_define_strp:
24695         case DW_MACRO_undef_strp:
24696         case DW_MACRO_define_sup:
24697         case DW_MACRO_undef_sup:
24698           {
24699             unsigned int bytes_read;
24700
24701             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24702             mac_ptr += bytes_read;
24703             mac_ptr += offset_size;
24704           }
24705           break;
24706
24707         case DW_MACRO_import:
24708         case DW_MACRO_import_sup:
24709           /* Note that, according to the spec, a transparent include
24710              chain cannot call DW_MACRO_start_file.  So, we can just
24711              skip this opcode.  */
24712           mac_ptr += offset_size;
24713           break;
24714
24715         case DW_MACINFO_vendor_ext:
24716           /* Only skip the data by MAC_PTR.  */
24717           if (!section_is_gnu)
24718             {
24719               unsigned int bytes_read;
24720
24721               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24722               mac_ptr += bytes_read;
24723               read_direct_string (abfd, mac_ptr, &bytes_read);
24724               mac_ptr += bytes_read;
24725             }
24726           /* FALLTHROUGH */
24727
24728         default:
24729           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24730                                          mac_ptr, mac_end, abfd, offset_size,
24731                                          section);
24732           if (mac_ptr == NULL)
24733             return;
24734           break;
24735         }
24736       DIAGNOSTIC_POP
24737     } while (macinfo_type != 0 && current_file == NULL);
24738
24739   /* Second pass: Process all entries.
24740
24741      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24742      command-line macro definitions/undefinitions.  This flag is unset when we
24743      reach the first DW_MACINFO_start_file entry.  */
24744
24745   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24746                                            htab_eq_pointer,
24747                                            NULL, xcalloc, xfree));
24748   mac_ptr = section->buffer + offset;
24749   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24750   *slot = (void *) mac_ptr;
24751   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24752                             abfd, mac_ptr, mac_end,
24753                             current_file, lh, section,
24754                             section_is_gnu, 0, offset_size,
24755                             include_hash.get ());
24756 }
24757
24758 /* Check if the attribute's form is a DW_FORM_block*
24759    if so return true else false.  */
24760
24761 static int
24762 attr_form_is_block (const struct attribute *attr)
24763 {
24764   return (attr == NULL ? 0 :
24765       attr->form == DW_FORM_block1
24766       || attr->form == DW_FORM_block2
24767       || attr->form == DW_FORM_block4
24768       || attr->form == DW_FORM_block
24769       || attr->form == DW_FORM_exprloc);
24770 }
24771
24772 /* Return non-zero if ATTR's value is a section offset --- classes
24773    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24774    You may use DW_UNSND (attr) to retrieve such offsets.
24775
24776    Section 7.5.4, "Attribute Encodings", explains that no attribute
24777    may have a value that belongs to more than one of these classes; it
24778    would be ambiguous if we did, because we use the same forms for all
24779    of them.  */
24780
24781 static int
24782 attr_form_is_section_offset (const struct attribute *attr)
24783 {
24784   return (attr->form == DW_FORM_data4
24785           || attr->form == DW_FORM_data8
24786           || attr->form == DW_FORM_sec_offset);
24787 }
24788
24789 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24790    zero otherwise.  When this function returns true, you can apply
24791    dwarf2_get_attr_constant_value to it.
24792
24793    However, note that for some attributes you must check
24794    attr_form_is_section_offset before using this test.  DW_FORM_data4
24795    and DW_FORM_data8 are members of both the constant class, and of
24796    the classes that contain offsets into other debug sections
24797    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24798    that, if an attribute's can be either a constant or one of the
24799    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24800    taken as section offsets, not constants.
24801
24802    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24803    cannot handle that.  */
24804
24805 static int
24806 attr_form_is_constant (const struct attribute *attr)
24807 {
24808   switch (attr->form)
24809     {
24810     case DW_FORM_sdata:
24811     case DW_FORM_udata:
24812     case DW_FORM_data1:
24813     case DW_FORM_data2:
24814     case DW_FORM_data4:
24815     case DW_FORM_data8:
24816     case DW_FORM_implicit_const:
24817       return 1;
24818     default:
24819       return 0;
24820     }
24821 }
24822
24823
24824 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24825    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24826
24827 static int
24828 attr_form_is_ref (const struct attribute *attr)
24829 {
24830   switch (attr->form)
24831     {
24832     case DW_FORM_ref_addr:
24833     case DW_FORM_ref1:
24834     case DW_FORM_ref2:
24835     case DW_FORM_ref4:
24836     case DW_FORM_ref8:
24837     case DW_FORM_ref_udata:
24838     case DW_FORM_GNU_ref_alt:
24839       return 1;
24840     default:
24841       return 0;
24842     }
24843 }
24844
24845 /* Return the .debug_loc section to use for CU.
24846    For DWO files use .debug_loc.dwo.  */
24847
24848 static struct dwarf2_section_info *
24849 cu_debug_loc_section (struct dwarf2_cu *cu)
24850 {
24851   struct dwarf2_per_objfile *dwarf2_per_objfile
24852     = cu->per_cu->dwarf2_per_objfile;
24853
24854   if (cu->dwo_unit)
24855     {
24856       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24857       
24858       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24859     }
24860   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24861                                   : &dwarf2_per_objfile->loc);
24862 }
24863
24864 /* A helper function that fills in a dwarf2_loclist_baton.  */
24865
24866 static void
24867 fill_in_loclist_baton (struct dwarf2_cu *cu,
24868                        struct dwarf2_loclist_baton *baton,
24869                        const struct attribute *attr)
24870 {
24871   struct dwarf2_per_objfile *dwarf2_per_objfile
24872     = cu->per_cu->dwarf2_per_objfile;
24873   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24874
24875   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24876
24877   baton->per_cu = cu->per_cu;
24878   gdb_assert (baton->per_cu);
24879   /* We don't know how long the location list is, but make sure we
24880      don't run off the edge of the section.  */
24881   baton->size = section->size - DW_UNSND (attr);
24882   baton->data = section->buffer + DW_UNSND (attr);
24883   baton->base_address = cu->base_address;
24884   baton->from_dwo = cu->dwo_unit != NULL;
24885 }
24886
24887 static void
24888 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24889                              struct dwarf2_cu *cu, int is_block)
24890 {
24891   struct dwarf2_per_objfile *dwarf2_per_objfile
24892     = cu->per_cu->dwarf2_per_objfile;
24893   struct objfile *objfile = dwarf2_per_objfile->objfile;
24894   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24895
24896   if (attr_form_is_section_offset (attr)
24897       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24898          the section.  If so, fall through to the complaint in the
24899          other branch.  */
24900       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24901     {
24902       struct dwarf2_loclist_baton *baton;
24903
24904       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24905
24906       fill_in_loclist_baton (cu, baton, attr);
24907
24908       if (cu->base_known == 0)
24909         complaint (&symfile_complaints,
24910                    _("Location list used without "
24911                      "specifying the CU base address."));
24912
24913       SYMBOL_ACLASS_INDEX (sym) = (is_block
24914                                    ? dwarf2_loclist_block_index
24915                                    : dwarf2_loclist_index);
24916       SYMBOL_LOCATION_BATON (sym) = baton;
24917     }
24918   else
24919     {
24920       struct dwarf2_locexpr_baton *baton;
24921
24922       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24923       baton->per_cu = cu->per_cu;
24924       gdb_assert (baton->per_cu);
24925
24926       if (attr_form_is_block (attr))
24927         {
24928           /* Note that we're just copying the block's data pointer
24929              here, not the actual data.  We're still pointing into the
24930              info_buffer for SYM's objfile; right now we never release
24931              that buffer, but when we do clean up properly this may
24932              need to change.  */
24933           baton->size = DW_BLOCK (attr)->size;
24934           baton->data = DW_BLOCK (attr)->data;
24935         }
24936       else
24937         {
24938           dwarf2_invalid_attrib_class_complaint ("location description",
24939                                                  SYMBOL_NATURAL_NAME (sym));
24940           baton->size = 0;
24941         }
24942
24943       SYMBOL_ACLASS_INDEX (sym) = (is_block
24944                                    ? dwarf2_locexpr_block_index
24945                                    : dwarf2_locexpr_index);
24946       SYMBOL_LOCATION_BATON (sym) = baton;
24947     }
24948 }
24949
24950 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24951    came from a separate debuginfo file, then the master objfile is
24952    returned.  */
24953
24954 struct objfile *
24955 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24956 {
24957   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24958
24959   /* Return the master objfile, so that we can report and look up the
24960      correct file containing this variable.  */
24961   if (objfile->separate_debug_objfile_backlink)
24962     objfile = objfile->separate_debug_objfile_backlink;
24963
24964   return objfile;
24965 }
24966
24967 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24968    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24969    CU_HEADERP first.  */
24970
24971 static const struct comp_unit_head *
24972 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24973                        struct dwarf2_per_cu_data *per_cu)
24974 {
24975   const gdb_byte *info_ptr;
24976
24977   if (per_cu->cu)
24978     return &per_cu->cu->header;
24979
24980   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24981
24982   memset (cu_headerp, 0, sizeof (*cu_headerp));
24983   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24984                        rcuh_kind::COMPILE);
24985
24986   return cu_headerp;
24987 }
24988
24989 /* Return the address size given in the compilation unit header for CU.  */
24990
24991 int
24992 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24993 {
24994   struct comp_unit_head cu_header_local;
24995   const struct comp_unit_head *cu_headerp;
24996
24997   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24998
24999   return cu_headerp->addr_size;
25000 }
25001
25002 /* Return the offset size given in the compilation unit header for CU.  */
25003
25004 int
25005 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25006 {
25007   struct comp_unit_head cu_header_local;
25008   const struct comp_unit_head *cu_headerp;
25009
25010   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25011
25012   return cu_headerp->offset_size;
25013 }
25014
25015 /* See its dwarf2loc.h declaration.  */
25016
25017 int
25018 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25019 {
25020   struct comp_unit_head cu_header_local;
25021   const struct comp_unit_head *cu_headerp;
25022
25023   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25024
25025   if (cu_headerp->version == 2)
25026     return cu_headerp->addr_size;
25027   else
25028     return cu_headerp->offset_size;
25029 }
25030
25031 /* Return the text offset of the CU.  The returned offset comes from
25032    this CU's objfile.  If this objfile came from a separate debuginfo
25033    file, then the offset may be different from the corresponding
25034    offset in the parent objfile.  */
25035
25036 CORE_ADDR
25037 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25038 {
25039   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25040
25041   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25042 }
25043
25044 /* Return DWARF version number of PER_CU.  */
25045
25046 short
25047 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25048 {
25049   return per_cu->dwarf_version;
25050 }
25051
25052 /* Locate the .debug_info compilation unit from CU's objfile which contains
25053    the DIE at OFFSET.  Raises an error on failure.  */
25054
25055 static struct dwarf2_per_cu_data *
25056 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25057                                   unsigned int offset_in_dwz,
25058                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25059 {
25060   struct dwarf2_per_cu_data *this_cu;
25061   int low, high;
25062   const sect_offset *cu_off;
25063
25064   low = 0;
25065   high = dwarf2_per_objfile->n_comp_units - 1;
25066   while (high > low)
25067     {
25068       struct dwarf2_per_cu_data *mid_cu;
25069       int mid = low + (high - low) / 2;
25070
25071       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25072       cu_off = &mid_cu->sect_off;
25073       if (mid_cu->is_dwz > offset_in_dwz
25074           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25075         high = mid;
25076       else
25077         low = mid + 1;
25078     }
25079   gdb_assert (low == high);
25080   this_cu = dwarf2_per_objfile->all_comp_units[low];
25081   cu_off = &this_cu->sect_off;
25082   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25083     {
25084       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25085         error (_("Dwarf Error: could not find partial DIE containing "
25086                "offset %s [in module %s]"),
25087                sect_offset_str (sect_off),
25088                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25089
25090       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25091                   <= sect_off);
25092       return dwarf2_per_objfile->all_comp_units[low-1];
25093     }
25094   else
25095     {
25096       this_cu = dwarf2_per_objfile->all_comp_units[low];
25097       if (low == dwarf2_per_objfile->n_comp_units - 1
25098           && sect_off >= this_cu->sect_off + this_cu->length)
25099         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25100       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25101       return this_cu;
25102     }
25103 }
25104
25105 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25106
25107 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25108   : per_cu (per_cu_),
25109     mark (0),
25110     has_loclist (0),
25111     checked_producer (0),
25112     producer_is_gxx_lt_4_6 (0),
25113     producer_is_gcc_lt_4_3 (0),
25114     producer_is_icc_lt_14 (0),
25115     processing_has_namespace_info (0)
25116 {
25117   per_cu->cu = this;
25118 }
25119
25120 /* Destroy a dwarf2_cu.  */
25121
25122 dwarf2_cu::~dwarf2_cu ()
25123 {
25124   per_cu->cu = NULL;
25125 }
25126
25127 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25128
25129 static void
25130 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25131                        enum language pretend_language)
25132 {
25133   struct attribute *attr;
25134
25135   /* Set the language we're debugging.  */
25136   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25137   if (attr)
25138     set_cu_language (DW_UNSND (attr), cu);
25139   else
25140     {
25141       cu->language = pretend_language;
25142       cu->language_defn = language_def (cu->language);
25143     }
25144
25145   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25146 }
25147
25148 /* Free all cached compilation units.  */
25149
25150 static void
25151 free_cached_comp_units (void *data)
25152 {
25153   struct dwarf2_per_objfile *dwarf2_per_objfile
25154     = (struct dwarf2_per_objfile *) data;
25155
25156   dwarf2_per_objfile->free_cached_comp_units ();
25157 }
25158
25159 /* Increase the age counter on each cached compilation unit, and free
25160    any that are too old.  */
25161
25162 static void
25163 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25164 {
25165   struct dwarf2_per_cu_data *per_cu, **last_chain;
25166
25167   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25168   per_cu = dwarf2_per_objfile->read_in_chain;
25169   while (per_cu != NULL)
25170     {
25171       per_cu->cu->last_used ++;
25172       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25173         dwarf2_mark (per_cu->cu);
25174       per_cu = per_cu->cu->read_in_chain;
25175     }
25176
25177   per_cu = dwarf2_per_objfile->read_in_chain;
25178   last_chain = &dwarf2_per_objfile->read_in_chain;
25179   while (per_cu != NULL)
25180     {
25181       struct dwarf2_per_cu_data *next_cu;
25182
25183       next_cu = per_cu->cu->read_in_chain;
25184
25185       if (!per_cu->cu->mark)
25186         {
25187           delete per_cu->cu;
25188           *last_chain = next_cu;
25189         }
25190       else
25191         last_chain = &per_cu->cu->read_in_chain;
25192
25193       per_cu = next_cu;
25194     }
25195 }
25196
25197 /* Remove a single compilation unit from the cache.  */
25198
25199 static void
25200 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25201 {
25202   struct dwarf2_per_cu_data *per_cu, **last_chain;
25203   struct dwarf2_per_objfile *dwarf2_per_objfile
25204     = target_per_cu->dwarf2_per_objfile;
25205
25206   per_cu = dwarf2_per_objfile->read_in_chain;
25207   last_chain = &dwarf2_per_objfile->read_in_chain;
25208   while (per_cu != NULL)
25209     {
25210       struct dwarf2_per_cu_data *next_cu;
25211
25212       next_cu = per_cu->cu->read_in_chain;
25213
25214       if (per_cu == target_per_cu)
25215         {
25216           delete per_cu->cu;
25217           per_cu->cu = NULL;
25218           *last_chain = next_cu;
25219           break;
25220         }
25221       else
25222         last_chain = &per_cu->cu->read_in_chain;
25223
25224       per_cu = next_cu;
25225     }
25226 }
25227
25228 /* Release all extra memory associated with OBJFILE.  */
25229
25230 void
25231 dwarf2_free_objfile (struct objfile *objfile)
25232 {
25233   struct dwarf2_per_objfile *dwarf2_per_objfile
25234     = get_dwarf2_per_objfile (objfile);
25235
25236   delete dwarf2_per_objfile;
25237 }
25238
25239 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25240    We store these in a hash table separate from the DIEs, and preserve them
25241    when the DIEs are flushed out of cache.
25242
25243    The CU "per_cu" pointer is needed because offset alone is not enough to
25244    uniquely identify the type.  A file may have multiple .debug_types sections,
25245    or the type may come from a DWO file.  Furthermore, while it's more logical
25246    to use per_cu->section+offset, with Fission the section with the data is in
25247    the DWO file but we don't know that section at the point we need it.
25248    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25249    because we can enter the lookup routine, get_die_type_at_offset, from
25250    outside this file, and thus won't necessarily have PER_CU->cu.
25251    Fortunately, PER_CU is stable for the life of the objfile.  */
25252
25253 struct dwarf2_per_cu_offset_and_type
25254 {
25255   const struct dwarf2_per_cu_data *per_cu;
25256   sect_offset sect_off;
25257   struct type *type;
25258 };
25259
25260 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25261
25262 static hashval_t
25263 per_cu_offset_and_type_hash (const void *item)
25264 {
25265   const struct dwarf2_per_cu_offset_and_type *ofs
25266     = (const struct dwarf2_per_cu_offset_and_type *) item;
25267
25268   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25269 }
25270
25271 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25272
25273 static int
25274 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25275 {
25276   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25277     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25278   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25279     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25280
25281   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25282           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25283 }
25284
25285 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25286    table if necessary.  For convenience, return TYPE.
25287
25288    The DIEs reading must have careful ordering to:
25289     * Not cause infite loops trying to read in DIEs as a prerequisite for
25290       reading current DIE.
25291     * Not trying to dereference contents of still incompletely read in types
25292       while reading in other DIEs.
25293     * Enable referencing still incompletely read in types just by a pointer to
25294       the type without accessing its fields.
25295
25296    Therefore caller should follow these rules:
25297      * Try to fetch any prerequisite types we may need to build this DIE type
25298        before building the type and calling set_die_type.
25299      * After building type call set_die_type for current DIE as soon as
25300        possible before fetching more types to complete the current type.
25301      * Make the type as complete as possible before fetching more types.  */
25302
25303 static struct type *
25304 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25305 {
25306   struct dwarf2_per_objfile *dwarf2_per_objfile
25307     = cu->per_cu->dwarf2_per_objfile;
25308   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25309   struct objfile *objfile = dwarf2_per_objfile->objfile;
25310   struct attribute *attr;
25311   struct dynamic_prop prop;
25312
25313   /* For Ada types, make sure that the gnat-specific data is always
25314      initialized (if not already set).  There are a few types where
25315      we should not be doing so, because the type-specific area is
25316      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25317      where the type-specific area is used to store the floatformat).
25318      But this is not a problem, because the gnat-specific information
25319      is actually not needed for these types.  */
25320   if (need_gnat_info (cu)
25321       && TYPE_CODE (type) != TYPE_CODE_FUNC
25322       && TYPE_CODE (type) != TYPE_CODE_FLT
25323       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25324       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25325       && TYPE_CODE (type) != TYPE_CODE_METHOD
25326       && !HAVE_GNAT_AUX_INFO (type))
25327     INIT_GNAT_SPECIFIC (type);
25328
25329   /* Read DW_AT_allocated and set in type.  */
25330   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25331   if (attr_form_is_block (attr))
25332     {
25333       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25334         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25335     }
25336   else if (attr != NULL)
25337     {
25338       complaint (&symfile_complaints,
25339                  _("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25340                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25341                  sect_offset_str (die->sect_off));
25342     }
25343
25344   /* Read DW_AT_associated and set in type.  */
25345   attr = dwarf2_attr (die, DW_AT_associated, cu);
25346   if (attr_form_is_block (attr))
25347     {
25348       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25349         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25350     }
25351   else if (attr != NULL)
25352     {
25353       complaint (&symfile_complaints,
25354                  _("DW_AT_associated has the wrong form (%s) at DIE %s"),
25355                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25356                  sect_offset_str (die->sect_off));
25357     }
25358
25359   /* Read DW_AT_data_location and set in type.  */
25360   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25361   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25362     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25363
25364   if (dwarf2_per_objfile->die_type_hash == NULL)
25365     {
25366       dwarf2_per_objfile->die_type_hash =
25367         htab_create_alloc_ex (127,
25368                               per_cu_offset_and_type_hash,
25369                               per_cu_offset_and_type_eq,
25370                               NULL,
25371                               &objfile->objfile_obstack,
25372                               hashtab_obstack_allocate,
25373                               dummy_obstack_deallocate);
25374     }
25375
25376   ofs.per_cu = cu->per_cu;
25377   ofs.sect_off = die->sect_off;
25378   ofs.type = type;
25379   slot = (struct dwarf2_per_cu_offset_and_type **)
25380     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25381   if (*slot)
25382     complaint (&symfile_complaints,
25383                _("A problem internal to GDB: DIE %s has type already set"),
25384                sect_offset_str (die->sect_off));
25385   *slot = XOBNEW (&objfile->objfile_obstack,
25386                   struct dwarf2_per_cu_offset_and_type);
25387   **slot = ofs;
25388   return type;
25389 }
25390
25391 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25392    or return NULL if the die does not have a saved type.  */
25393
25394 static struct type *
25395 get_die_type_at_offset (sect_offset sect_off,
25396                         struct dwarf2_per_cu_data *per_cu)
25397 {
25398   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25399   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25400
25401   if (dwarf2_per_objfile->die_type_hash == NULL)
25402     return NULL;
25403
25404   ofs.per_cu = per_cu;
25405   ofs.sect_off = sect_off;
25406   slot = ((struct dwarf2_per_cu_offset_and_type *)
25407           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25408   if (slot)
25409     return slot->type;
25410   else
25411     return NULL;
25412 }
25413
25414 /* Look up the type for DIE in CU in die_type_hash,
25415    or return NULL if DIE does not have a saved type.  */
25416
25417 static struct type *
25418 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25419 {
25420   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25421 }
25422
25423 /* Add a dependence relationship from CU to REF_PER_CU.  */
25424
25425 static void
25426 dwarf2_add_dependence (struct dwarf2_cu *cu,
25427                        struct dwarf2_per_cu_data *ref_per_cu)
25428 {
25429   void **slot;
25430
25431   if (cu->dependencies == NULL)
25432     cu->dependencies
25433       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25434                               NULL, &cu->comp_unit_obstack,
25435                               hashtab_obstack_allocate,
25436                               dummy_obstack_deallocate);
25437
25438   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25439   if (*slot == NULL)
25440     *slot = ref_per_cu;
25441 }
25442
25443 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25444    Set the mark field in every compilation unit in the
25445    cache that we must keep because we are keeping CU.  */
25446
25447 static int
25448 dwarf2_mark_helper (void **slot, void *data)
25449 {
25450   struct dwarf2_per_cu_data *per_cu;
25451
25452   per_cu = (struct dwarf2_per_cu_data *) *slot;
25453
25454   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25455      reading of the chain.  As such dependencies remain valid it is not much
25456      useful to track and undo them during QUIT cleanups.  */
25457   if (per_cu->cu == NULL)
25458     return 1;
25459
25460   if (per_cu->cu->mark)
25461     return 1;
25462   per_cu->cu->mark = 1;
25463
25464   if (per_cu->cu->dependencies != NULL)
25465     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25466
25467   return 1;
25468 }
25469
25470 /* Set the mark field in CU and in every other compilation unit in the
25471    cache that we must keep because we are keeping CU.  */
25472
25473 static void
25474 dwarf2_mark (struct dwarf2_cu *cu)
25475 {
25476   if (cu->mark)
25477     return;
25478   cu->mark = 1;
25479   if (cu->dependencies != NULL)
25480     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25481 }
25482
25483 static void
25484 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25485 {
25486   while (per_cu)
25487     {
25488       per_cu->cu->mark = 0;
25489       per_cu = per_cu->cu->read_in_chain;
25490     }
25491 }
25492
25493 /* Trivial hash function for partial_die_info: the hash value of a DIE
25494    is its offset in .debug_info for this objfile.  */
25495
25496 static hashval_t
25497 partial_die_hash (const void *item)
25498 {
25499   const struct partial_die_info *part_die
25500     = (const struct partial_die_info *) item;
25501
25502   return to_underlying (part_die->sect_off);
25503 }
25504
25505 /* Trivial comparison function for partial_die_info structures: two DIEs
25506    are equal if they have the same offset.  */
25507
25508 static int
25509 partial_die_eq (const void *item_lhs, const void *item_rhs)
25510 {
25511   const struct partial_die_info *part_die_lhs
25512     = (const struct partial_die_info *) item_lhs;
25513   const struct partial_die_info *part_die_rhs
25514     = (const struct partial_die_info *) item_rhs;
25515
25516   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25517 }
25518
25519 static struct cmd_list_element *set_dwarf_cmdlist;
25520 static struct cmd_list_element *show_dwarf_cmdlist;
25521
25522 static void
25523 set_dwarf_cmd (const char *args, int from_tty)
25524 {
25525   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25526              gdb_stdout);
25527 }
25528
25529 static void
25530 show_dwarf_cmd (const char *args, int from_tty)
25531 {
25532   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25533 }
25534
25535 /* The "save gdb-index" command.  */
25536
25537 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25538    error checking.  */
25539
25540 static void
25541 file_write (FILE *file, const void *data, size_t size)
25542 {
25543   if (fwrite (data, 1, size, file) != size)
25544     error (_("couldn't data write to file"));
25545 }
25546
25547 /* Write the contents of VEC to FILE, with error checking.  */
25548
25549 template<typename Elem, typename Alloc>
25550 static void
25551 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25552 {
25553   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25554 }
25555
25556 /* In-memory buffer to prepare data to be written later to a file.  */
25557 class data_buf
25558 {
25559 public:
25560   /* Copy DATA to the end of the buffer.  */
25561   template<typename T>
25562   void append_data (const T &data)
25563   {
25564     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25565                reinterpret_cast<const gdb_byte *> (&data + 1),
25566                grow (sizeof (data)));
25567   }
25568
25569   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25570      terminating zero is appended too.  */
25571   void append_cstr0 (const char *cstr)
25572   {
25573     const size_t size = strlen (cstr) + 1;
25574     std::copy (cstr, cstr + size, grow (size));
25575   }
25576
25577   /* Store INPUT as ULEB128 to the end of buffer.  */
25578   void append_unsigned_leb128 (ULONGEST input)
25579   {
25580     for (;;)
25581       {
25582         gdb_byte output = input & 0x7f;
25583         input >>= 7;
25584         if (input)
25585           output |= 0x80;
25586         append_data (output);
25587         if (input == 0)
25588           break;
25589       }
25590   }
25591
25592   /* Accept a host-format integer in VAL and append it to the buffer
25593      as a target-format integer which is LEN bytes long.  */
25594   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25595   {
25596     ::store_unsigned_integer (grow (len), len, byte_order, val);
25597   }
25598
25599   /* Return the size of the buffer.  */
25600   size_t size () const
25601   {
25602     return m_vec.size ();
25603   }
25604
25605   /* Return true iff the buffer is empty.  */
25606   bool empty () const
25607   {
25608     return m_vec.empty ();
25609   }
25610
25611   /* Write the buffer to FILE.  */
25612   void file_write (FILE *file) const
25613   {
25614     ::file_write (file, m_vec);
25615   }
25616
25617 private:
25618   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25619      the start of the new block.  */
25620   gdb_byte *grow (size_t size)
25621   {
25622     m_vec.resize (m_vec.size () + size);
25623     return &*m_vec.end () - size;
25624   }
25625
25626   gdb::byte_vector m_vec;
25627 };
25628
25629 /* An entry in the symbol table.  */
25630 struct symtab_index_entry
25631 {
25632   /* The name of the symbol.  */
25633   const char *name;
25634   /* The offset of the name in the constant pool.  */
25635   offset_type index_offset;
25636   /* A sorted vector of the indices of all the CUs that hold an object
25637      of this name.  */
25638   std::vector<offset_type> cu_indices;
25639 };
25640
25641 /* The symbol table.  This is a power-of-2-sized hash table.  */
25642 struct mapped_symtab
25643 {
25644   mapped_symtab ()
25645   {
25646     data.resize (1024);
25647   }
25648
25649   offset_type n_elements = 0;
25650   std::vector<symtab_index_entry> data;
25651 };
25652
25653 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25654    the slot.
25655    
25656    Function is used only during write_hash_table so no index format backward
25657    compatibility is needed.  */
25658
25659 static symtab_index_entry &
25660 find_slot (struct mapped_symtab *symtab, const char *name)
25661 {
25662   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25663
25664   index = hash & (symtab->data.size () - 1);
25665   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25666
25667   for (;;)
25668     {
25669       if (symtab->data[index].name == NULL
25670           || strcmp (name, symtab->data[index].name) == 0)
25671         return symtab->data[index];
25672       index = (index + step) & (symtab->data.size () - 1);
25673     }
25674 }
25675
25676 /* Expand SYMTAB's hash table.  */
25677
25678 static void
25679 hash_expand (struct mapped_symtab *symtab)
25680 {
25681   auto old_entries = std::move (symtab->data);
25682
25683   symtab->data.clear ();
25684   symtab->data.resize (old_entries.size () * 2);
25685
25686   for (auto &it : old_entries)
25687     if (it.name != NULL)
25688       {
25689         auto &ref = find_slot (symtab, it.name);
25690         ref = std::move (it);
25691       }
25692 }
25693
25694 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25695    CU_INDEX is the index of the CU in which the symbol appears.
25696    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25697
25698 static void
25699 add_index_entry (struct mapped_symtab *symtab, const char *name,
25700                  int is_static, gdb_index_symbol_kind kind,
25701                  offset_type cu_index)
25702 {
25703   offset_type cu_index_and_attrs;
25704
25705   ++symtab->n_elements;
25706   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25707     hash_expand (symtab);
25708
25709   symtab_index_entry &slot = find_slot (symtab, name);
25710   if (slot.name == NULL)
25711     {
25712       slot.name = name;
25713       /* index_offset is set later.  */
25714     }
25715
25716   cu_index_and_attrs = 0;
25717   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25718   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25719   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25720
25721   /* We don't want to record an index value twice as we want to avoid the
25722      duplication.
25723      We process all global symbols and then all static symbols
25724      (which would allow us to avoid the duplication by only having to check
25725      the last entry pushed), but a symbol could have multiple kinds in one CU.
25726      To keep things simple we don't worry about the duplication here and
25727      sort and uniqufy the list after we've processed all symbols.  */
25728   slot.cu_indices.push_back (cu_index_and_attrs);
25729 }
25730
25731 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25732
25733 static void
25734 uniquify_cu_indices (struct mapped_symtab *symtab)
25735 {
25736   for (auto &entry : symtab->data)
25737     {
25738       if (entry.name != NULL && !entry.cu_indices.empty ())
25739         {
25740           auto &cu_indices = entry.cu_indices;
25741           std::sort (cu_indices.begin (), cu_indices.end ());
25742           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25743           cu_indices.erase (from, cu_indices.end ());
25744         }
25745     }
25746 }
25747
25748 /* A form of 'const char *' suitable for container keys.  Only the
25749    pointer is stored.  The strings themselves are compared, not the
25750    pointers.  */
25751 class c_str_view
25752 {
25753 public:
25754   c_str_view (const char *cstr)
25755     : m_cstr (cstr)
25756   {}
25757
25758   bool operator== (const c_str_view &other) const
25759   {
25760     return strcmp (m_cstr, other.m_cstr) == 0;
25761   }
25762
25763   /* Return the underlying C string.  Note, the returned string is
25764      only a reference with lifetime of this object.  */
25765   const char *c_str () const
25766   {
25767     return m_cstr;
25768   }
25769
25770 private:
25771   friend class c_str_view_hasher;
25772   const char *const m_cstr;
25773 };
25774
25775 /* A std::unordered_map::hasher for c_str_view that uses the right
25776    hash function for strings in a mapped index.  */
25777 class c_str_view_hasher
25778 {
25779 public:
25780   size_t operator () (const c_str_view &x) const
25781   {
25782     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25783   }
25784 };
25785
25786 /* A std::unordered_map::hasher for std::vector<>.  */
25787 template<typename T>
25788 class vector_hasher
25789 {
25790 public:
25791   size_t operator () (const std::vector<T> &key) const
25792   {
25793     return iterative_hash (key.data (),
25794                            sizeof (key.front ()) * key.size (), 0);
25795   }
25796 };
25797
25798 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25799    constant pool entries going into the data buffer CPOOL.  */
25800
25801 static void
25802 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25803 {
25804   {
25805     /* Elements are sorted vectors of the indices of all the CUs that
25806        hold an object of this name.  */
25807     std::unordered_map<std::vector<offset_type>, offset_type,
25808                        vector_hasher<offset_type>>
25809       symbol_hash_table;
25810
25811     /* We add all the index vectors to the constant pool first, to
25812        ensure alignment is ok.  */
25813     for (symtab_index_entry &entry : symtab->data)
25814       {
25815         if (entry.name == NULL)
25816           continue;
25817         gdb_assert (entry.index_offset == 0);
25818
25819         /* Finding before inserting is faster than always trying to
25820            insert, because inserting always allocates a node, does the
25821            lookup, and then destroys the new node if another node
25822            already had the same key.  C++17 try_emplace will avoid
25823            this.  */
25824         const auto found
25825           = symbol_hash_table.find (entry.cu_indices);
25826         if (found != symbol_hash_table.end ())
25827           {
25828             entry.index_offset = found->second;
25829             continue;
25830           }
25831
25832         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25833         entry.index_offset = cpool.size ();
25834         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25835         for (const auto index : entry.cu_indices)
25836           cpool.append_data (MAYBE_SWAP (index));
25837       }
25838   }
25839
25840   /* Now write out the hash table.  */
25841   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25842   for (const auto &entry : symtab->data)
25843     {
25844       offset_type str_off, vec_off;
25845
25846       if (entry.name != NULL)
25847         {
25848           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25849           if (insertpair.second)
25850             cpool.append_cstr0 (entry.name);
25851           str_off = insertpair.first->second;
25852           vec_off = entry.index_offset;
25853         }
25854       else
25855         {
25856           /* While 0 is a valid constant pool index, it is not valid
25857              to have 0 for both offsets.  */
25858           str_off = 0;
25859           vec_off = 0;
25860         }
25861
25862       output.append_data (MAYBE_SWAP (str_off));
25863       output.append_data (MAYBE_SWAP (vec_off));
25864     }
25865 }
25866
25867 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25868
25869 /* Helper struct for building the address table.  */
25870 struct addrmap_index_data
25871 {
25872   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25873     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25874   {}
25875
25876   struct objfile *objfile;
25877   data_buf &addr_vec;
25878   psym_index_map &cu_index_htab;
25879
25880   /* Non-zero if the previous_* fields are valid.
25881      We can't write an entry until we see the next entry (since it is only then
25882      that we know the end of the entry).  */
25883   int previous_valid;
25884   /* Index of the CU in the table of all CUs in the index file.  */
25885   unsigned int previous_cu_index;
25886   /* Start address of the CU.  */
25887   CORE_ADDR previous_cu_start;
25888 };
25889
25890 /* Write an address entry to ADDR_VEC.  */
25891
25892 static void
25893 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25894                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25895 {
25896   CORE_ADDR baseaddr;
25897
25898   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25899
25900   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25901   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25902   addr_vec.append_data (MAYBE_SWAP (cu_index));
25903 }
25904
25905 /* Worker function for traversing an addrmap to build the address table.  */
25906
25907 static int
25908 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25909 {
25910   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25911   struct partial_symtab *pst = (struct partial_symtab *) obj;
25912
25913   if (data->previous_valid)
25914     add_address_entry (data->objfile, data->addr_vec,
25915                        data->previous_cu_start, start_addr,
25916                        data->previous_cu_index);
25917
25918   data->previous_cu_start = start_addr;
25919   if (pst != NULL)
25920     {
25921       const auto it = data->cu_index_htab.find (pst);
25922       gdb_assert (it != data->cu_index_htab.cend ());
25923       data->previous_cu_index = it->second;
25924       data->previous_valid = 1;
25925     }
25926   else
25927     data->previous_valid = 0;
25928
25929   return 0;
25930 }
25931
25932 /* Write OBJFILE's address map to ADDR_VEC.
25933    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25934    in the index file.  */
25935
25936 static void
25937 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25938                    psym_index_map &cu_index_htab)
25939 {
25940   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25941
25942   /* When writing the address table, we have to cope with the fact that
25943      the addrmap iterator only provides the start of a region; we have to
25944      wait until the next invocation to get the start of the next region.  */
25945
25946   addrmap_index_data.objfile = objfile;
25947   addrmap_index_data.previous_valid = 0;
25948
25949   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25950                    &addrmap_index_data);
25951
25952   /* It's highly unlikely the last entry (end address = 0xff...ff)
25953      is valid, but we should still handle it.
25954      The end address is recorded as the start of the next region, but that
25955      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25956      anyway.  */
25957   if (addrmap_index_data.previous_valid)
25958     add_address_entry (objfile, addr_vec,
25959                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25960                        addrmap_index_data.previous_cu_index);
25961 }
25962
25963 /* Return the symbol kind of PSYM.  */
25964
25965 static gdb_index_symbol_kind
25966 symbol_kind (struct partial_symbol *psym)
25967 {
25968   domain_enum domain = PSYMBOL_DOMAIN (psym);
25969   enum address_class aclass = PSYMBOL_CLASS (psym);
25970
25971   switch (domain)
25972     {
25973     case VAR_DOMAIN:
25974       switch (aclass)
25975         {
25976         case LOC_BLOCK:
25977           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25978         case LOC_TYPEDEF:
25979           return GDB_INDEX_SYMBOL_KIND_TYPE;
25980         case LOC_COMPUTED:
25981         case LOC_CONST_BYTES:
25982         case LOC_OPTIMIZED_OUT:
25983         case LOC_STATIC:
25984           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25985         case LOC_CONST:
25986           /* Note: It's currently impossible to recognize psyms as enum values
25987              short of reading the type info.  For now punt.  */
25988           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25989         default:
25990           /* There are other LOC_FOO values that one might want to classify
25991              as variables, but dwarf2read.c doesn't currently use them.  */
25992           return GDB_INDEX_SYMBOL_KIND_OTHER;
25993         }
25994     case STRUCT_DOMAIN:
25995       return GDB_INDEX_SYMBOL_KIND_TYPE;
25996     default:
25997       return GDB_INDEX_SYMBOL_KIND_OTHER;
25998     }
25999 }
26000
26001 /* Add a list of partial symbols to SYMTAB.  */
26002
26003 static void
26004 write_psymbols (struct mapped_symtab *symtab,
26005                 std::unordered_set<partial_symbol *> &psyms_seen,
26006                 struct partial_symbol **psymp,
26007                 int count,
26008                 offset_type cu_index,
26009                 int is_static)
26010 {
26011   for (; count-- > 0; ++psymp)
26012     {
26013       struct partial_symbol *psym = *psymp;
26014
26015       if (SYMBOL_LANGUAGE (psym) == language_ada)
26016         error (_("Ada is not currently supported by the index"));
26017
26018       /* Only add a given psymbol once.  */
26019       if (psyms_seen.insert (psym).second)
26020         {
26021           gdb_index_symbol_kind kind = symbol_kind (psym);
26022
26023           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
26024                            is_static, kind, cu_index);
26025         }
26026     }
26027 }
26028
26029 /* A helper struct used when iterating over debug_types.  */
26030 struct signatured_type_index_data
26031 {
26032   signatured_type_index_data (data_buf &types_list_,
26033                               std::unordered_set<partial_symbol *> &psyms_seen_)
26034     : types_list (types_list_), psyms_seen (psyms_seen_)
26035   {}
26036
26037   struct objfile *objfile;
26038   struct mapped_symtab *symtab;
26039   data_buf &types_list;
26040   std::unordered_set<partial_symbol *> &psyms_seen;
26041   int cu_index;
26042 };
26043
26044 /* A helper function that writes a single signatured_type to an
26045    obstack.  */
26046
26047 static int
26048 write_one_signatured_type (void **slot, void *d)
26049 {
26050   struct signatured_type_index_data *info
26051     = (struct signatured_type_index_data *) d;
26052   struct signatured_type *entry = (struct signatured_type *) *slot;
26053   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26054
26055   write_psymbols (info->symtab,
26056                   info->psyms_seen,
26057                   &info->objfile->global_psymbols[psymtab->globals_offset],
26058                   psymtab->n_global_syms, info->cu_index,
26059                   0);
26060   write_psymbols (info->symtab,
26061                   info->psyms_seen,
26062                   &info->objfile->static_psymbols[psymtab->statics_offset],
26063                   psymtab->n_static_syms, info->cu_index,
26064                   1);
26065
26066   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26067                                 to_underlying (entry->per_cu.sect_off));
26068   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26069                                 to_underlying (entry->type_offset_in_tu));
26070   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26071
26072   ++info->cu_index;
26073
26074   return 1;
26075 }
26076
26077 /* Recurse into all "included" dependencies and count their symbols as
26078    if they appeared in this psymtab.  */
26079
26080 static void
26081 recursively_count_psymbols (struct partial_symtab *psymtab,
26082                             size_t &psyms_seen)
26083 {
26084   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26085     if (psymtab->dependencies[i]->user != NULL)
26086       recursively_count_psymbols (psymtab->dependencies[i],
26087                                   psyms_seen);
26088
26089   psyms_seen += psymtab->n_global_syms;
26090   psyms_seen += psymtab->n_static_syms;
26091 }
26092
26093 /* Recurse into all "included" dependencies and write their symbols as
26094    if they appeared in this psymtab.  */
26095
26096 static void
26097 recursively_write_psymbols (struct objfile *objfile,
26098                             struct partial_symtab *psymtab,
26099                             struct mapped_symtab *symtab,
26100                             std::unordered_set<partial_symbol *> &psyms_seen,
26101                             offset_type cu_index)
26102 {
26103   int i;
26104
26105   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26106     if (psymtab->dependencies[i]->user != NULL)
26107       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26108                                   symtab, psyms_seen, cu_index);
26109
26110   write_psymbols (symtab,
26111                   psyms_seen,
26112                   &objfile->global_psymbols[psymtab->globals_offset],
26113                   psymtab->n_global_syms, cu_index,
26114                   0);
26115   write_psymbols (symtab,
26116                   psyms_seen,
26117                   &objfile->static_psymbols[psymtab->statics_offset],
26118                   psymtab->n_static_syms, cu_index,
26119                   1);
26120 }
26121
26122 /* DWARF-5 .debug_names builder.  */
26123 class debug_names
26124 {
26125 public:
26126   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26127                bfd_endian dwarf5_byte_order)
26128     : m_dwarf5_byte_order (dwarf5_byte_order),
26129       m_dwarf32 (dwarf5_byte_order),
26130       m_dwarf64 (dwarf5_byte_order),
26131       m_dwarf (is_dwarf64
26132                ? static_cast<dwarf &> (m_dwarf64)
26133                : static_cast<dwarf &> (m_dwarf32)),
26134       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26135       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26136       m_debugstrlookup (dwarf2_per_objfile)
26137   {}
26138
26139   int dwarf5_offset_size () const
26140   {
26141     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26142     return dwarf5_is_dwarf64 ? 8 : 4;
26143   }
26144
26145   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26146   enum class unit_kind { cu, tu };
26147
26148   /* Insert one symbol.  */
26149   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26150                unit_kind kind)
26151   {
26152     const int dwarf_tag = psymbol_tag (psym);
26153     if (dwarf_tag == 0)
26154       return;
26155     const char *const name = SYMBOL_SEARCH_NAME (psym);
26156     const auto insertpair
26157       = m_name_to_value_set.emplace (c_str_view (name),
26158                                      std::set<symbol_value> ());
26159     std::set<symbol_value> &value_set = insertpair.first->second;
26160     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26161   }
26162
26163   /* Build all the tables.  All symbols must be already inserted.
26164      This function does not call file_write, caller has to do it
26165      afterwards.  */
26166   void build ()
26167   {
26168     /* Verify the build method has not be called twice.  */
26169     gdb_assert (m_abbrev_table.empty ());
26170     const size_t name_count = m_name_to_value_set.size ();
26171     m_bucket_table.resize
26172       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26173     m_hash_table.reserve (name_count);
26174     m_name_table_string_offs.reserve (name_count);
26175     m_name_table_entry_offs.reserve (name_count);
26176
26177     /* Map each hash of symbol to its name and value.  */
26178     struct hash_it_pair
26179     {
26180       uint32_t hash;
26181       decltype (m_name_to_value_set)::const_iterator it;
26182     };
26183     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26184     bucket_hash.resize (m_bucket_table.size ());
26185     for (decltype (m_name_to_value_set)::const_iterator it
26186            = m_name_to_value_set.cbegin ();
26187          it != m_name_to_value_set.cend ();
26188          ++it)
26189       {
26190         const char *const name = it->first.c_str ();
26191         const uint32_t hash = dwarf5_djb_hash (name);
26192         hash_it_pair hashitpair;
26193         hashitpair.hash = hash;
26194         hashitpair.it = it;
26195         auto &slot = bucket_hash[hash % bucket_hash.size()];
26196         slot.push_front (std::move (hashitpair));
26197       }
26198     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26199       {
26200         const std::forward_list<hash_it_pair> &hashitlist
26201           = bucket_hash[bucket_ix];
26202         if (hashitlist.empty ())
26203           continue;
26204         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26205         /* The hashes array is indexed starting at 1.  */
26206         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26207                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26208                                 m_hash_table.size () + 1);
26209         for (const hash_it_pair &hashitpair : hashitlist)
26210           {
26211             m_hash_table.push_back (0);
26212             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26213                                                         (&m_hash_table.back ()),
26214                                     sizeof (m_hash_table.back ()),
26215                                     m_dwarf5_byte_order, hashitpair.hash);
26216             const c_str_view &name = hashitpair.it->first;
26217             const std::set<symbol_value> &value_set = hashitpair.it->second;
26218             m_name_table_string_offs.push_back_reorder
26219               (m_debugstrlookup.lookup (name.c_str ()));
26220             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26221             gdb_assert (!value_set.empty ());
26222             for (const symbol_value &value : value_set)
26223               {
26224                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26225                                                         value.is_static,
26226                                                         value.kind)];
26227                 if (idx == 0)
26228                   {
26229                     idx = m_idx_next++;
26230                     m_abbrev_table.append_unsigned_leb128 (idx);
26231                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26232                     m_abbrev_table.append_unsigned_leb128
26233                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26234                                                            : DW_IDX_type_unit);
26235                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26236                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26237                                                            ? DW_IDX_GNU_internal
26238                                                            : DW_IDX_GNU_external);
26239                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26240
26241                     /* Terminate attributes list.  */
26242                     m_abbrev_table.append_unsigned_leb128 (0);
26243                     m_abbrev_table.append_unsigned_leb128 (0);
26244                   }
26245
26246                 m_entry_pool.append_unsigned_leb128 (idx);
26247                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26248               }
26249
26250             /* Terminate the list of CUs.  */
26251             m_entry_pool.append_unsigned_leb128 (0);
26252           }
26253       }
26254     gdb_assert (m_hash_table.size () == name_count);
26255
26256     /* Terminate tags list.  */
26257     m_abbrev_table.append_unsigned_leb128 (0);
26258   }
26259
26260   /* Return .debug_names bucket count.  This must be called only after
26261      calling the build method.  */
26262   uint32_t bucket_count () const
26263   {
26264     /* Verify the build method has been already called.  */
26265     gdb_assert (!m_abbrev_table.empty ());
26266     const uint32_t retval = m_bucket_table.size ();
26267
26268     /* Check for overflow.  */
26269     gdb_assert (retval == m_bucket_table.size ());
26270     return retval;
26271   }
26272
26273   /* Return .debug_names names count.  This must be called only after
26274      calling the build method.  */
26275   uint32_t name_count () const
26276   {
26277     /* Verify the build method has been already called.  */
26278     gdb_assert (!m_abbrev_table.empty ());
26279     const uint32_t retval = m_hash_table.size ();
26280
26281     /* Check for overflow.  */
26282     gdb_assert (retval == m_hash_table.size ());
26283     return retval;
26284   }
26285
26286   /* Return number of bytes of .debug_names abbreviation table.  This
26287      must be called only after calling the build method.  */
26288   uint32_t abbrev_table_bytes () const
26289   {
26290     gdb_assert (!m_abbrev_table.empty ());
26291     return m_abbrev_table.size ();
26292   }
26293
26294   /* Recurse into all "included" dependencies and store their symbols
26295      as if they appeared in this psymtab.  */
26296   void recursively_write_psymbols
26297     (struct objfile *objfile,
26298      struct partial_symtab *psymtab,
26299      std::unordered_set<partial_symbol *> &psyms_seen,
26300      int cu_index)
26301   {
26302     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26303       if (psymtab->dependencies[i]->user != NULL)
26304         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26305                                     psyms_seen, cu_index);
26306
26307     write_psymbols (psyms_seen,
26308                     &objfile->global_psymbols[psymtab->globals_offset],
26309                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26310     write_psymbols (psyms_seen,
26311                     &objfile->static_psymbols[psymtab->statics_offset],
26312                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26313   }
26314
26315   /* Return number of bytes the .debug_names section will have.  This
26316      must be called only after calling the build method.  */
26317   size_t bytes () const
26318   {
26319     /* Verify the build method has been already called.  */
26320     gdb_assert (!m_abbrev_table.empty ());
26321     size_t expected_bytes = 0;
26322     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26323     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26324     expected_bytes += m_name_table_string_offs.bytes ();
26325     expected_bytes += m_name_table_entry_offs.bytes ();
26326     expected_bytes += m_abbrev_table.size ();
26327     expected_bytes += m_entry_pool.size ();
26328     return expected_bytes;
26329   }
26330
26331   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26332      FILE_STR.  This must be called only after calling the build
26333      method.  */
26334   void file_write (FILE *file_names, FILE *file_str) const
26335   {
26336     /* Verify the build method has been already called.  */
26337     gdb_assert (!m_abbrev_table.empty ());
26338     ::file_write (file_names, m_bucket_table);
26339     ::file_write (file_names, m_hash_table);
26340     m_name_table_string_offs.file_write (file_names);
26341     m_name_table_entry_offs.file_write (file_names);
26342     m_abbrev_table.file_write (file_names);
26343     m_entry_pool.file_write (file_names);
26344     m_debugstrlookup.file_write (file_str);
26345   }
26346
26347   /* A helper user data for write_one_signatured_type.  */
26348   class write_one_signatured_type_data
26349   {
26350   public:
26351     write_one_signatured_type_data (debug_names &nametable_,
26352                                     signatured_type_index_data &&info_)
26353     : nametable (nametable_), info (std::move (info_))
26354     {}
26355     debug_names &nametable;
26356     struct signatured_type_index_data info;
26357   };
26358
26359   /* A helper function to pass write_one_signatured_type to
26360      htab_traverse_noresize.  */
26361   static int
26362   write_one_signatured_type (void **slot, void *d)
26363   {
26364     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26365     struct signatured_type_index_data *info = &data->info;
26366     struct signatured_type *entry = (struct signatured_type *) *slot;
26367
26368     data->nametable.write_one_signatured_type (entry, info);
26369
26370     return 1;
26371   }
26372
26373 private:
26374
26375   /* Storage for symbol names mapping them to their .debug_str section
26376      offsets.  */
26377   class debug_str_lookup
26378   {
26379   public:
26380
26381     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26382        All .debug_str section strings are automatically stored.  */
26383     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26384       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26385         m_dwarf2_per_objfile (dwarf2_per_objfile)
26386     {
26387       dwarf2_read_section (dwarf2_per_objfile->objfile,
26388                            &dwarf2_per_objfile->str);
26389       if (dwarf2_per_objfile->str.buffer == NULL)
26390         return;
26391       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26392            data < (dwarf2_per_objfile->str.buffer
26393                    + dwarf2_per_objfile->str.size);)
26394         {
26395           const char *const s = reinterpret_cast<const char *> (data);
26396           const auto insertpair
26397             = m_str_table.emplace (c_str_view (s),
26398                                    data - dwarf2_per_objfile->str.buffer);
26399           if (!insertpair.second)
26400             complaint (&symfile_complaints,
26401                        _("Duplicate string \"%s\" in "
26402                          ".debug_str section [in module %s]"),
26403                        s, bfd_get_filename (m_abfd));
26404           data += strlen (s) + 1;
26405         }
26406     }
26407
26408     /* Return offset of symbol name S in the .debug_str section.  Add
26409        such symbol to the section's end if it does not exist there
26410        yet.  */
26411     size_t lookup (const char *s)
26412     {
26413       const auto it = m_str_table.find (c_str_view (s));
26414       if (it != m_str_table.end ())
26415         return it->second;
26416       const size_t offset = (m_dwarf2_per_objfile->str.size
26417                              + m_str_add_buf.size ());
26418       m_str_table.emplace (c_str_view (s), offset);
26419       m_str_add_buf.append_cstr0 (s);
26420       return offset;
26421     }
26422
26423     /* Append the end of the .debug_str section to FILE.  */
26424     void file_write (FILE *file) const
26425     {
26426       m_str_add_buf.file_write (file);
26427     }
26428
26429   private:
26430     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26431     bfd *const m_abfd;
26432     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26433
26434     /* Data to add at the end of .debug_str for new needed symbol names.  */
26435     data_buf m_str_add_buf;
26436   };
26437
26438   /* Container to map used DWARF tags to their .debug_names abbreviation
26439      tags.  */
26440   class index_key
26441   {
26442   public:
26443     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26444       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26445     {
26446     }
26447
26448     bool
26449     operator== (const index_key &other) const
26450     {
26451       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26452               && kind == other.kind);
26453     }
26454
26455     const int dwarf_tag;
26456     const bool is_static;
26457     const unit_kind kind;
26458   };
26459
26460   /* Provide std::unordered_map::hasher for index_key.  */
26461   class index_key_hasher
26462   {
26463   public:
26464     size_t
26465     operator () (const index_key &key) const
26466     {
26467       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26468     }
26469   };
26470
26471   /* Parameters of one symbol entry.  */
26472   class symbol_value
26473   {
26474   public:
26475     const int dwarf_tag, cu_index;
26476     const bool is_static;
26477     const unit_kind kind;
26478
26479     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26480                   unit_kind kind_)
26481       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26482         kind (kind_)
26483     {}
26484
26485     bool
26486     operator< (const symbol_value &other) const
26487     {
26488 #define X(n) \
26489   do \
26490     { \
26491       if (n < other.n) \
26492         return true; \
26493       if (n > other.n) \
26494         return false; \
26495     } \
26496   while (0)
26497       X (dwarf_tag);
26498       X (is_static);
26499       X (kind);
26500       X (cu_index);
26501 #undef X
26502       return false;
26503     }
26504   };
26505
26506   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26507      output.  */
26508   class offset_vec
26509   {
26510   protected:
26511     const bfd_endian dwarf5_byte_order;
26512   public:
26513     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26514       : dwarf5_byte_order (dwarf5_byte_order_)
26515     {}
26516
26517     /* Call std::vector::reserve for NELEM elements.  */
26518     virtual void reserve (size_t nelem) = 0;
26519
26520     /* Call std::vector::push_back with store_unsigned_integer byte
26521        reordering for ELEM.  */
26522     virtual void push_back_reorder (size_t elem) = 0;
26523
26524     /* Return expected output size in bytes.  */
26525     virtual size_t bytes () const = 0;
26526
26527     /* Write name table to FILE.  */
26528     virtual void file_write (FILE *file) const = 0;
26529   };
26530
26531   /* Template to unify DWARF-32 and DWARF-64 output.  */
26532   template<typename OffsetSize>
26533   class offset_vec_tmpl : public offset_vec
26534   {
26535   public:
26536     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26537       : offset_vec (dwarf5_byte_order_)
26538     {}
26539
26540     /* Implement offset_vec::reserve.  */
26541     void reserve (size_t nelem) override
26542     {
26543       m_vec.reserve (nelem);
26544     }
26545
26546     /* Implement offset_vec::push_back_reorder.  */
26547     void push_back_reorder (size_t elem) override
26548     {
26549       m_vec.push_back (elem);
26550       /* Check for overflow.  */
26551       gdb_assert (m_vec.back () == elem);
26552       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26553                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26554     }
26555
26556     /* Implement offset_vec::bytes.  */
26557     size_t bytes () const override
26558     {
26559       return m_vec.size () * sizeof (m_vec[0]);
26560     }
26561
26562     /* Implement offset_vec::file_write.  */
26563     void file_write (FILE *file) const override
26564     {
26565       ::file_write (file, m_vec);
26566     }
26567
26568   private:
26569     std::vector<OffsetSize> m_vec;
26570   };
26571
26572   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26573      respecting name table width.  */
26574   class dwarf
26575   {
26576   public:
26577     offset_vec &name_table_string_offs, &name_table_entry_offs;
26578
26579     dwarf (offset_vec &name_table_string_offs_,
26580            offset_vec &name_table_entry_offs_)
26581       : name_table_string_offs (name_table_string_offs_),
26582         name_table_entry_offs (name_table_entry_offs_)
26583     {
26584     }
26585   };
26586
26587   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26588      respecting name table width.  */
26589   template<typename OffsetSize>
26590   class dwarf_tmpl : public dwarf
26591   {
26592   public:
26593     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26594       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26595         m_name_table_string_offs (dwarf5_byte_order_),
26596         m_name_table_entry_offs (dwarf5_byte_order_)
26597     {}
26598
26599   private:
26600     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26601     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26602   };
26603
26604   /* Try to reconstruct original DWARF tag for given partial_symbol.
26605      This function is not DWARF-5 compliant but it is sufficient for
26606      GDB as a DWARF-5 index consumer.  */
26607   static int psymbol_tag (const struct partial_symbol *psym)
26608   {
26609     domain_enum domain = PSYMBOL_DOMAIN (psym);
26610     enum address_class aclass = PSYMBOL_CLASS (psym);
26611
26612     switch (domain)
26613       {
26614       case VAR_DOMAIN:
26615         switch (aclass)
26616           {
26617           case LOC_BLOCK:
26618             return DW_TAG_subprogram;
26619           case LOC_TYPEDEF:
26620             return DW_TAG_typedef;
26621           case LOC_COMPUTED:
26622           case LOC_CONST_BYTES:
26623           case LOC_OPTIMIZED_OUT:
26624           case LOC_STATIC:
26625             return DW_TAG_variable;
26626           case LOC_CONST:
26627             /* Note: It's currently impossible to recognize psyms as enum values
26628                short of reading the type info.  For now punt.  */
26629             return DW_TAG_variable;
26630           default:
26631             /* There are other LOC_FOO values that one might want to classify
26632                as variables, but dwarf2read.c doesn't currently use them.  */
26633             return DW_TAG_variable;
26634           }
26635       case STRUCT_DOMAIN:
26636         return DW_TAG_structure_type;
26637       default:
26638         return 0;
26639       }
26640   }
26641
26642   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26643   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26644                        struct partial_symbol **psymp, int count, int cu_index,
26645                        bool is_static, unit_kind kind)
26646   {
26647     for (; count-- > 0; ++psymp)
26648       {
26649         struct partial_symbol *psym = *psymp;
26650
26651         if (SYMBOL_LANGUAGE (psym) == language_ada)
26652           error (_("Ada is not currently supported by the index"));
26653
26654         /* Only add a given psymbol once.  */
26655         if (psyms_seen.insert (psym).second)
26656           insert (psym, cu_index, is_static, kind);
26657       }
26658   }
26659
26660   /* A helper function that writes a single signatured_type
26661      to a debug_names.  */
26662   void
26663   write_one_signatured_type (struct signatured_type *entry,
26664                              struct signatured_type_index_data *info)
26665   {
26666     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26667
26668     write_psymbols (info->psyms_seen,
26669                     &info->objfile->global_psymbols[psymtab->globals_offset],
26670                     psymtab->n_global_syms, info->cu_index, false,
26671                     unit_kind::tu);
26672     write_psymbols (info->psyms_seen,
26673                     &info->objfile->static_psymbols[psymtab->statics_offset],
26674                     psymtab->n_static_syms, info->cu_index, true,
26675                     unit_kind::tu);
26676
26677     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26678                                   to_underlying (entry->per_cu.sect_off));
26679
26680     ++info->cu_index;
26681   }
26682
26683   /* Store value of each symbol.  */
26684   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26685     m_name_to_value_set;
26686
26687   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26688      order.  */
26689   std::vector<uint32_t> m_bucket_table;
26690   std::vector<uint32_t> m_hash_table;
26691
26692   const bfd_endian m_dwarf5_byte_order;
26693   dwarf_tmpl<uint32_t> m_dwarf32;
26694   dwarf_tmpl<uint64_t> m_dwarf64;
26695   dwarf &m_dwarf;
26696   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26697   debug_str_lookup m_debugstrlookup;
26698
26699   /* Map each used .debug_names abbreviation tag parameter to its
26700      index value.  */
26701   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26702
26703   /* Next unused .debug_names abbreviation tag for
26704      m_indexkey_to_idx.  */
26705   int m_idx_next = 1;
26706
26707   /* .debug_names abbreviation table.  */
26708   data_buf m_abbrev_table;
26709
26710   /* .debug_names entry pool.  */
26711   data_buf m_entry_pool;
26712 };
26713
26714 /* Return iff any of the needed offsets does not fit into 32-bit
26715    .debug_names section.  */
26716
26717 static bool
26718 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26719 {
26720   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26721     {
26722       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26723
26724       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26725         return true;
26726     }
26727   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26728     {
26729       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26730       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26731
26732       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26733         return true;
26734     }
26735   return false;
26736 }
26737
26738 /* The psyms_seen set is potentially going to be largish (~40k
26739    elements when indexing a -g3 build of GDB itself).  Estimate the
26740    number of elements in order to avoid too many rehashes, which
26741    require rebuilding buckets and thus many trips to
26742    malloc/free.  */
26743
26744 static size_t
26745 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26746 {
26747   size_t psyms_count = 0;
26748   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26749     {
26750       struct dwarf2_per_cu_data *per_cu
26751         = dwarf2_per_objfile->all_comp_units[i];
26752       struct partial_symtab *psymtab = per_cu->v.psymtab;
26753
26754       if (psymtab != NULL && psymtab->user == NULL)
26755         recursively_count_psymbols (psymtab, psyms_count);
26756     }
26757   /* Generating an index for gdb itself shows a ratio of
26758      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26759   return psyms_count / 4;
26760 }
26761
26762 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26763    Return how many bytes were expected to be written into OUT_FILE.  */
26764
26765 static size_t
26766 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26767 {
26768   struct objfile *objfile = dwarf2_per_objfile->objfile;
26769   mapped_symtab symtab;
26770   data_buf cu_list;
26771
26772   /* While we're scanning CU's create a table that maps a psymtab pointer
26773      (which is what addrmap records) to its index (which is what is recorded
26774      in the index file).  This will later be needed to write the address
26775      table.  */
26776   psym_index_map cu_index_htab;
26777   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26778
26779   /* The CU list is already sorted, so we don't need to do additional
26780      work here.  Also, the debug_types entries do not appear in
26781      all_comp_units, but only in their own hash table.  */
26782
26783   std::unordered_set<partial_symbol *> psyms_seen
26784     (psyms_seen_size (dwarf2_per_objfile));
26785   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26786     {
26787       struct dwarf2_per_cu_data *per_cu
26788         = dwarf2_per_objfile->all_comp_units[i];
26789       struct partial_symtab *psymtab = per_cu->v.psymtab;
26790
26791       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26792          It may be referenced from a local scope but in such case it does not
26793          need to be present in .gdb_index.  */
26794       if (psymtab == NULL)
26795         continue;
26796
26797       if (psymtab->user == NULL)
26798         recursively_write_psymbols (objfile, psymtab, &symtab,
26799                                     psyms_seen, i);
26800
26801       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26802       gdb_assert (insertpair.second);
26803
26804       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26805                            to_underlying (per_cu->sect_off));
26806       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26807     }
26808
26809   /* Dump the address map.  */
26810   data_buf addr_vec;
26811   write_address_map (objfile, addr_vec, cu_index_htab);
26812
26813   /* Write out the .debug_type entries, if any.  */
26814   data_buf types_cu_list;
26815   if (dwarf2_per_objfile->signatured_types)
26816     {
26817       signatured_type_index_data sig_data (types_cu_list,
26818                                            psyms_seen);
26819
26820       sig_data.objfile = objfile;
26821       sig_data.symtab = &symtab;
26822       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26823       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26824                               write_one_signatured_type, &sig_data);
26825     }
26826
26827   /* Now that we've processed all symbols we can shrink their cu_indices
26828      lists.  */
26829   uniquify_cu_indices (&symtab);
26830
26831   data_buf symtab_vec, constant_pool;
26832   write_hash_table (&symtab, symtab_vec, constant_pool);
26833
26834   data_buf contents;
26835   const offset_type size_of_contents = 6 * sizeof (offset_type);
26836   offset_type total_len = size_of_contents;
26837
26838   /* The version number.  */
26839   contents.append_data (MAYBE_SWAP (8));
26840
26841   /* The offset of the CU list from the start of the file.  */
26842   contents.append_data (MAYBE_SWAP (total_len));
26843   total_len += cu_list.size ();
26844
26845   /* The offset of the types CU list from the start of the file.  */
26846   contents.append_data (MAYBE_SWAP (total_len));
26847   total_len += types_cu_list.size ();
26848
26849   /* The offset of the address table from the start of the file.  */
26850   contents.append_data (MAYBE_SWAP (total_len));
26851   total_len += addr_vec.size ();
26852
26853   /* The offset of the symbol table from the start of the file.  */
26854   contents.append_data (MAYBE_SWAP (total_len));
26855   total_len += symtab_vec.size ();
26856
26857   /* The offset of the constant pool from the start of the file.  */
26858   contents.append_data (MAYBE_SWAP (total_len));
26859   total_len += constant_pool.size ();
26860
26861   gdb_assert (contents.size () == size_of_contents);
26862
26863   contents.file_write (out_file);
26864   cu_list.file_write (out_file);
26865   types_cu_list.file_write (out_file);
26866   addr_vec.file_write (out_file);
26867   symtab_vec.file_write (out_file);
26868   constant_pool.file_write (out_file);
26869
26870   return total_len;
26871 }
26872
26873 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26874 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26875
26876 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26877    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26878    many bytes were expected to be written into OUT_FILE.  */
26879
26880 static size_t
26881 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
26882                    FILE *out_file, FILE *out_file_str)
26883 {
26884   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
26885   struct objfile *objfile = dwarf2_per_objfile->objfile;
26886   const enum bfd_endian dwarf5_byte_order
26887     = gdbarch_byte_order (get_objfile_arch (objfile));
26888
26889   /* The CU list is already sorted, so we don't need to do additional
26890      work here.  Also, the debug_types entries do not appear in
26891      all_comp_units, but only in their own hash table.  */
26892   data_buf cu_list;
26893   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
26894                          dwarf5_byte_order);
26895   std::unordered_set<partial_symbol *>
26896     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
26897   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26898     {
26899       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26900       partial_symtab *psymtab = per_cu->v.psymtab;
26901
26902       /* CU of a shared file from 'dwz -m' may be unused by this main
26903          file.  It may be referenced from a local scope but in such
26904          case it does not need to be present in .debug_names.  */
26905       if (psymtab == NULL)
26906         continue;
26907
26908       if (psymtab->user == NULL)
26909         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26910
26911       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
26912                            to_underlying (per_cu->sect_off));
26913     }
26914
26915   /* Write out the .debug_type entries, if any.  */
26916   data_buf types_cu_list;
26917   if (dwarf2_per_objfile->signatured_types)
26918     {
26919       debug_names::write_one_signatured_type_data sig_data (nametable,
26920                         signatured_type_index_data (types_cu_list, psyms_seen));
26921
26922       sig_data.info.objfile = objfile;
26923       /* It is used only for gdb_index.  */
26924       sig_data.info.symtab = nullptr;
26925       sig_data.info.cu_index = 0;
26926       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26927                               debug_names::write_one_signatured_type,
26928                               &sig_data);
26929     }
26930
26931   nametable.build ();
26932
26933   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26934
26935   const offset_type bytes_of_header
26936     = ((dwarf5_is_dwarf64 ? 12 : 4)
26937        + 2 + 2 + 7 * 4
26938        + sizeof (dwarf5_gdb_augmentation));
26939   size_t expected_bytes = 0;
26940   expected_bytes += bytes_of_header;
26941   expected_bytes += cu_list.size ();
26942   expected_bytes += types_cu_list.size ();
26943   expected_bytes += nametable.bytes ();
26944   data_buf header;
26945
26946   if (!dwarf5_is_dwarf64)
26947     {
26948       const uint64_t size64 = expected_bytes - 4;
26949       gdb_assert (size64 < 0xfffffff0);
26950       header.append_uint (4, dwarf5_byte_order, size64);
26951     }
26952   else
26953     {
26954       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26955       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26956     }
26957
26958   /* The version number.  */
26959   header.append_uint (2, dwarf5_byte_order, 5);
26960
26961   /* Padding.  */
26962   header.append_uint (2, dwarf5_byte_order, 0);
26963
26964   /* comp_unit_count - The number of CUs in the CU list.  */
26965   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26966
26967   /* local_type_unit_count - The number of TUs in the local TU
26968      list.  */
26969   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26970
26971   /* foreign_type_unit_count - The number of TUs in the foreign TU
26972      list.  */
26973   header.append_uint (4, dwarf5_byte_order, 0);
26974
26975   /* bucket_count - The number of hash buckets in the hash lookup
26976      table.  */
26977   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26978
26979   /* name_count - The number of unique names in the index.  */
26980   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26981
26982   /* abbrev_table_size - The size in bytes of the abbreviations
26983      table.  */
26984   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26985
26986   /* augmentation_string_size - The size in bytes of the augmentation
26987      string.  This value is rounded up to a multiple of 4.  */
26988   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26989   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26990   header.append_data (dwarf5_gdb_augmentation);
26991
26992   gdb_assert (header.size () == bytes_of_header);
26993
26994   header.file_write (out_file);
26995   cu_list.file_write (out_file);
26996   types_cu_list.file_write (out_file);
26997   nametable.file_write (out_file, out_file_str);
26998
26999   return expected_bytes;
27000 }
27001
27002 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
27003    position is at the end of the file.  */
27004
27005 static void
27006 assert_file_size (FILE *file, const char *filename, size_t expected_size)
27007 {
27008   const auto file_size = ftell (file);
27009   if (file_size == -1)
27010     error (_("Can't get `%s' size"), filename);
27011   gdb_assert (file_size == expected_size);
27012 }
27013
27014 /* Create an index file for OBJFILE in the directory DIR.  */
27015
27016 static void
27017 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
27018                          const char *dir,
27019                          dw_index_kind index_kind)
27020 {
27021   struct objfile *objfile = dwarf2_per_objfile->objfile;
27022
27023   if (dwarf2_per_objfile->using_index)
27024     error (_("Cannot use an index to create the index"));
27025
27026   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
27027     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27028
27029   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27030     return;
27031
27032   struct stat st;
27033   if (stat (objfile_name (objfile), &st) < 0)
27034     perror_with_name (objfile_name (objfile));
27035
27036   std::string filename (std::string (dir) + SLASH_STRING
27037                         + lbasename (objfile_name (objfile))
27038                         + (index_kind == dw_index_kind::DEBUG_NAMES
27039                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27040
27041   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27042   if (!out_file)
27043     error (_("Can't open `%s' for writing"), filename.c_str ());
27044
27045   /* Order matters here; we want FILE to be closed before FILENAME is
27046      unlinked, because on MS-Windows one cannot delete a file that is
27047      still open.  (Don't call anything here that might throw until
27048      file_closer is created.)  */
27049   gdb::unlinker unlink_file (filename.c_str ());
27050   gdb_file_up close_out_file (out_file);
27051
27052   if (index_kind == dw_index_kind::DEBUG_NAMES)
27053     {
27054       std::string filename_str (std::string (dir) + SLASH_STRING
27055                                 + lbasename (objfile_name (objfile))
27056                                 + DEBUG_STR_SUFFIX);
27057       FILE *out_file_str
27058         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27059       if (!out_file_str)
27060         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27061       gdb::unlinker unlink_file_str (filename_str.c_str ());
27062       gdb_file_up close_out_file_str (out_file_str);
27063
27064       const size_t total_len
27065         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27066       assert_file_size (out_file, filename.c_str (), total_len);
27067
27068       /* We want to keep the file .debug_str file too.  */
27069       unlink_file_str.keep ();
27070     }
27071   else
27072     {
27073       const size_t total_len
27074         = write_gdbindex (dwarf2_per_objfile, out_file);
27075       assert_file_size (out_file, filename.c_str (), total_len);
27076     }
27077
27078   /* We want to keep the file.  */
27079   unlink_file.keep ();
27080 }
27081
27082 /* Implementation of the `save gdb-index' command.
27083    
27084    Note that the .gdb_index file format used by this command is
27085    documented in the GDB manual.  Any changes here must be documented
27086    there.  */
27087
27088 static void
27089 save_gdb_index_command (const char *arg, int from_tty)
27090 {
27091   struct objfile *objfile;
27092   const char dwarf5space[] = "-dwarf-5 ";
27093   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27094
27095   if (!arg)
27096     arg = "";
27097
27098   arg = skip_spaces (arg);
27099   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27100     {
27101       index_kind = dw_index_kind::DEBUG_NAMES;
27102       arg += strlen (dwarf5space);
27103       arg = skip_spaces (arg);
27104     }
27105
27106   if (!*arg)
27107     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27108
27109   ALL_OBJFILES (objfile)
27110   {
27111     struct stat st;
27112
27113     /* If the objfile does not correspond to an actual file, skip it.  */
27114     if (stat (objfile_name (objfile), &st) < 0)
27115       continue;
27116
27117     struct dwarf2_per_objfile *dwarf2_per_objfile
27118       = get_dwarf2_per_objfile (objfile);
27119
27120     if (dwarf2_per_objfile != NULL)
27121       {
27122         TRY
27123           {
27124             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27125           }
27126         CATCH (except, RETURN_MASK_ERROR)
27127           {
27128             exception_fprintf (gdb_stderr, except,
27129                                _("Error while writing index for `%s': "),
27130                                objfile_name (objfile));
27131           }
27132         END_CATCH
27133       }
27134
27135   }
27136 }
27137
27138 \f
27139
27140 int dwarf_always_disassemble;
27141
27142 static void
27143 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27144                                struct cmd_list_element *c, const char *value)
27145 {
27146   fprintf_filtered (file,
27147                     _("Whether to always disassemble "
27148                       "DWARF expressions is %s.\n"),
27149                     value);
27150 }
27151
27152 static void
27153 show_check_physname (struct ui_file *file, int from_tty,
27154                      struct cmd_list_element *c, const char *value)
27155 {
27156   fprintf_filtered (file,
27157                     _("Whether to check \"physname\" is %s.\n"),
27158                     value);
27159 }
27160
27161 void
27162 _initialize_dwarf2_read (void)
27163 {
27164   struct cmd_list_element *c;
27165
27166   dwarf2_objfile_data_key = register_objfile_data ();
27167
27168   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27169 Set DWARF specific variables.\n\
27170 Configure DWARF variables such as the cache size"),
27171                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27172                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27173
27174   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27175 Show DWARF specific variables\n\
27176 Show DWARF variables such as the cache size"),
27177                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27178                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27179
27180   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27181                             &dwarf_max_cache_age, _("\
27182 Set the upper bound on the age of cached DWARF compilation units."), _("\
27183 Show the upper bound on the age of cached DWARF compilation units."), _("\
27184 A higher limit means that cached compilation units will be stored\n\
27185 in memory longer, and more total memory will be used.  Zero disables\n\
27186 caching, which can slow down startup."),
27187                             NULL,
27188                             show_dwarf_max_cache_age,
27189                             &set_dwarf_cmdlist,
27190                             &show_dwarf_cmdlist);
27191
27192   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27193                            &dwarf_always_disassemble, _("\
27194 Set whether `info address' always disassembles DWARF expressions."), _("\
27195 Show whether `info address' always disassembles DWARF expressions."), _("\
27196 When enabled, DWARF expressions are always printed in an assembly-like\n\
27197 syntax.  When disabled, expressions will be printed in a more\n\
27198 conversational style, when possible."),
27199                            NULL,
27200                            show_dwarf_always_disassemble,
27201                            &set_dwarf_cmdlist,
27202                            &show_dwarf_cmdlist);
27203
27204   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27205 Set debugging of the DWARF reader."), _("\
27206 Show debugging of the DWARF reader."), _("\
27207 When enabled (non-zero), debugging messages are printed during DWARF\n\
27208 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27209 information.  A value greater than 1 provides more verbose information."),
27210                             NULL,
27211                             NULL,
27212                             &setdebuglist, &showdebuglist);
27213
27214   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27215 Set debugging of the DWARF DIE reader."), _("\
27216 Show debugging of the DWARF DIE reader."), _("\
27217 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27218 The value is the maximum depth to print."),
27219                              NULL,
27220                              NULL,
27221                              &setdebuglist, &showdebuglist);
27222
27223   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27224 Set debugging of the dwarf line reader."), _("\
27225 Show debugging of the dwarf line reader."), _("\
27226 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27227 A value of 1 (one) provides basic information.\n\
27228 A value greater than 1 provides more verbose information."),
27229                              NULL,
27230                              NULL,
27231                              &setdebuglist, &showdebuglist);
27232
27233   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27234 Set cross-checking of \"physname\" code against demangler."), _("\
27235 Show cross-checking of \"physname\" code against demangler."), _("\
27236 When enabled, GDB's internal \"physname\" code is checked against\n\
27237 the demangler."),
27238                            NULL, show_check_physname,
27239                            &setdebuglist, &showdebuglist);
27240
27241   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27242                            no_class, &use_deprecated_index_sections, _("\
27243 Set whether to use deprecated gdb_index sections."), _("\
27244 Show whether to use deprecated gdb_index sections."), _("\
27245 When enabled, deprecated .gdb_index sections are used anyway.\n\
27246 Normally they are ignored either because of a missing feature or\n\
27247 performance issue.\n\
27248 Warning: This option must be enabled before gdb reads the file."),
27249                            NULL,
27250                            NULL,
27251                            &setlist, &showlist);
27252
27253   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27254                _("\
27255 Save a gdb-index file.\n\
27256 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27257 \n\
27258 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27259 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27260 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27261                &save_cmdlist);
27262   set_cmd_completer (c, filename_completer);
27263
27264   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27265                                                         &dwarf2_locexpr_funcs);
27266   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27267                                                         &dwarf2_loclist_funcs);
27268
27269   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27270                                         &dwarf2_block_frame_base_locexpr_funcs);
27271   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27272                                         &dwarf2_block_frame_base_loclist_funcs);
27273
27274 #if GDB_SELF_TEST
27275   selftests::register_test ("dw2_expand_symtabs_matching",
27276                             selftests::dw2_expand_symtabs_matching::run_test);
27277 #endif
27278 }