Move comment in gdb/dwarf2read.c::dwarf2_physname
[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
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
790 /* Persistent data held for a compilation unit, even when not
791    processing it.  We put a pointer to this structure in the
792    read_symtab_private field of the psymtab.  */
793
794 struct dwarf2_per_cu_data
795 {
796   /* The start offset and length of this compilation unit.
797      NOTE: Unlike comp_unit_head.length, this length includes
798      initial_length_size.
799      If the DIE refers to a DWO file, this is always of the original die,
800      not the DWO file.  */
801   sect_offset sect_off;
802   unsigned int length;
803
804   /* DWARF standard version this data has been read from (such as 4 or 5).  */
805   short dwarf_version;
806
807   /* Flag indicating this compilation unit will be read in before
808      any of the current compilation units are processed.  */
809   unsigned int queued : 1;
810
811   /* This flag will be set when reading partial DIEs if we need to load
812      absolutely all DIEs for this compilation unit, instead of just the ones
813      we think are interesting.  It gets set if we look for a DIE in the
814      hash table and don't find it.  */
815   unsigned int load_all_dies : 1;
816
817   /* Non-zero if this CU is from .debug_types.
818      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
819      this is non-zero.  */
820   unsigned int is_debug_types : 1;
821
822   /* Non-zero if this CU is from the .dwz file.  */
823   unsigned int is_dwz : 1;
824
825   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
826      This flag is only valid if is_debug_types is true.
827      We can't read a CU directly from a DWO file: There are required
828      attributes in the stub.  */
829   unsigned int reading_dwo_directly : 1;
830
831   /* Non-zero if the TU has been read.
832      This is used to assist the "Stay in DWO Optimization" for Fission:
833      When reading a DWO, it's faster to read TUs from the DWO instead of
834      fetching them from random other DWOs (due to comdat folding).
835      If the TU has already been read, the optimization is unnecessary
836      (and unwise - we don't want to change where gdb thinks the TU lives
837      "midflight").
838      This flag is only valid if is_debug_types is true.  */
839   unsigned int tu_read : 1;
840
841   /* The section this CU/TU lives in.
842      If the DIE refers to a DWO file, this is always the original die,
843      not the DWO file.  */
844   struct dwarf2_section_info *section;
845
846   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
847      of the CU cache it gets reset to NULL again.  This is left as NULL for
848      dummy CUs (a CU header, but nothing else).  */
849   struct dwarf2_cu *cu;
850
851   /* The corresponding dwarf2_per_objfile.  */
852   struct dwarf2_per_objfile *dwarf2_per_objfile;
853
854   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
855      is active.  Otherwise, the 'psymtab' field is active.  */
856   union
857   {
858     /* The partial symbol table associated with this compilation unit,
859        or NULL for unread partial units.  */
860     struct partial_symtab *psymtab;
861
862     /* Data needed by the "quick" functions.  */
863     struct dwarf2_per_cu_quick_data *quick;
864   } v;
865
866   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
867      while reading psymtabs, used to compute the psymtab dependencies,
868      and then cleared.  Then it is filled in again while reading full
869      symbols, and only deleted when the objfile is destroyed.
870
871      This is also used to work around a difference between the way gold
872      generates .gdb_index version <=7 and the way gdb does.  Arguably this
873      is a gold bug.  For symbols coming from TUs, gold records in the index
874      the CU that includes the TU instead of the TU itself.  This breaks
875      dw2_lookup_symbol: It assumes that if the index says symbol X lives
876      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
877      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
878      we need to look in TU Z to find X.  Fortunately, this is akin to
879      DW_TAG_imported_unit, so we just use the same mechanism: For
880      .gdb_index version <=7 this also records the TUs that the CU referred
881      to.  Concurrently with this change gdb was modified to emit version 8
882      indices so we only pay a price for gold generated indices.
883      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
884   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
885 };
886
887 /* Entry in the signatured_types hash table.  */
888
889 struct signatured_type
890 {
891   /* The "per_cu" object of this type.
892      This struct is used iff per_cu.is_debug_types.
893      N.B.: This is the first member so that it's easy to convert pointers
894      between them.  */
895   struct dwarf2_per_cu_data per_cu;
896
897   /* The type's signature.  */
898   ULONGEST signature;
899
900   /* Offset in the TU of the type's DIE, as read from the TU header.
901      If this TU is a DWO stub and the definition lives in a DWO file
902      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
903   cu_offset type_offset_in_tu;
904
905   /* Offset in the section of the type's DIE.
906      If the definition lives in a DWO file, this is the offset in the
907      .debug_types.dwo section.
908      The value is zero until the actual value is known.
909      Zero is otherwise not a valid section offset.  */
910   sect_offset type_offset_in_section;
911
912   /* Type units are grouped by their DW_AT_stmt_list entry so that they
913      can share them.  This points to the containing symtab.  */
914   struct type_unit_group *type_unit_group;
915
916   /* The type.
917      The first time we encounter this type we fully read it in and install it
918      in the symbol tables.  Subsequent times we only need the type.  */
919   struct type *type;
920
921   /* Containing DWO unit.
922      This field is valid iff per_cu.reading_dwo_directly.  */
923   struct dwo_unit *dwo_unit;
924 };
925
926 typedef struct signatured_type *sig_type_ptr;
927 DEF_VEC_P (sig_type_ptr);
928
929 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
930    This includes type_unit_group and quick_file_names.  */
931
932 struct stmt_list_hash
933 {
934   /* The DWO unit this table is from or NULL if there is none.  */
935   struct dwo_unit *dwo_unit;
936
937   /* Offset in .debug_line or .debug_line.dwo.  */
938   sect_offset line_sect_off;
939 };
940
941 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
942    an object of this type.  */
943
944 struct type_unit_group
945 {
946   /* dwarf2read.c's main "handle" on a TU symtab.
947      To simplify things we create an artificial CU that "includes" all the
948      type units using this stmt_list so that the rest of the code still has
949      a "per_cu" handle on the symtab.
950      This PER_CU is recognized by having no section.  */
951 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
952   struct dwarf2_per_cu_data per_cu;
953
954   /* The TUs that share this DW_AT_stmt_list entry.
955      This is added to while parsing type units to build partial symtabs,
956      and is deleted afterwards and not used again.  */
957   VEC (sig_type_ptr) *tus;
958
959   /* The compunit symtab.
960      Type units in a group needn't all be defined in the same source file,
961      so we create an essentially anonymous symtab as the compunit symtab.  */
962   struct compunit_symtab *compunit_symtab;
963
964   /* The data used to construct the hash key.  */
965   struct stmt_list_hash hash;
966
967   /* The number of symtabs from the line header.
968      The value here must match line_header.num_file_names.  */
969   unsigned int num_symtabs;
970
971   /* The symbol tables for this TU (obtained from the files listed in
972      DW_AT_stmt_list).
973      WARNING: The order of entries here must match the order of entries
974      in the line header.  After the first TU using this type_unit_group, the
975      line header for the subsequent TUs is recreated from this.  This is done
976      because we need to use the same symtabs for each TU using the same
977      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
978      there's no guarantee the line header doesn't have duplicate entries.  */
979   struct symtab **symtabs;
980 };
981
982 /* These sections are what may appear in a (real or virtual) DWO file.  */
983
984 struct dwo_sections
985 {
986   struct dwarf2_section_info abbrev;
987   struct dwarf2_section_info line;
988   struct dwarf2_section_info loc;
989   struct dwarf2_section_info loclists;
990   struct dwarf2_section_info macinfo;
991   struct dwarf2_section_info macro;
992   struct dwarf2_section_info str;
993   struct dwarf2_section_info str_offsets;
994   /* In the case of a virtual DWO file, these two are unused.  */
995   struct dwarf2_section_info info;
996   VEC (dwarf2_section_info_def) *types;
997 };
998
999 /* CUs/TUs in DWP/DWO files.  */
1000
1001 struct dwo_unit
1002 {
1003   /* Backlink to the containing struct dwo_file.  */
1004   struct dwo_file *dwo_file;
1005
1006   /* The "id" that distinguishes this CU/TU.
1007      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1008      Since signatures came first, we stick with it for consistency.  */
1009   ULONGEST signature;
1010
1011   /* The section this CU/TU lives in, in the DWO file.  */
1012   struct dwarf2_section_info *section;
1013
1014   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1015   sect_offset sect_off;
1016   unsigned int length;
1017
1018   /* For types, offset in the type's DIE of the type defined by this TU.  */
1019   cu_offset type_offset_in_tu;
1020 };
1021
1022 /* include/dwarf2.h defines the DWP section codes.
1023    It defines a max value but it doesn't define a min value, which we
1024    use for error checking, so provide one.  */
1025
1026 enum dwp_v2_section_ids
1027 {
1028   DW_SECT_MIN = 1
1029 };
1030
1031 /* Data for one DWO file.
1032
1033    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1034    appears in a DWP file).  DWP files don't really have DWO files per se -
1035    comdat folding of types "loses" the DWO file they came from, and from
1036    a high level view DWP files appear to contain a mass of random types.
1037    However, to maintain consistency with the non-DWP case we pretend DWP
1038    files contain virtual DWO files, and we assign each TU with one virtual
1039    DWO file (generally based on the line and abbrev section offsets -
1040    a heuristic that seems to work in practice).  */
1041
1042 struct dwo_file
1043 {
1044   /* The DW_AT_GNU_dwo_name attribute.
1045      For virtual DWO files the name is constructed from the section offsets
1046      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1047      from related CU+TUs.  */
1048   const char *dwo_name;
1049
1050   /* The DW_AT_comp_dir attribute.  */
1051   const char *comp_dir;
1052
1053   /* The bfd, when the file is open.  Otherwise this is NULL.
1054      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1055   bfd *dbfd;
1056
1057   /* The sections that make up this DWO file.
1058      Remember that for virtual DWO files in DWP V2, these are virtual
1059      sections (for lack of a better name).  */
1060   struct dwo_sections sections;
1061
1062   /* The CUs in the file.
1063      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1064      an extension to handle LLVM's Link Time Optimization output (where
1065      multiple source files may be compiled into a single object/dwo pair). */
1066   htab_t cus;
1067
1068   /* Table of TUs in the file.
1069      Each element is a struct dwo_unit.  */
1070   htab_t tus;
1071 };
1072
1073 /* These sections are what may appear in a DWP file.  */
1074
1075 struct dwp_sections
1076 {
1077   /* These are used by both DWP version 1 and 2.  */
1078   struct dwarf2_section_info str;
1079   struct dwarf2_section_info cu_index;
1080   struct dwarf2_section_info tu_index;
1081
1082   /* These are only used by DWP version 2 files.
1083      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1084      sections are referenced by section number, and are not recorded here.
1085      In DWP version 2 there is at most one copy of all these sections, each
1086      section being (effectively) comprised of the concatenation of all of the
1087      individual sections that exist in the version 1 format.
1088      To keep the code simple we treat each of these concatenated pieces as a
1089      section itself (a virtual section?).  */
1090   struct dwarf2_section_info abbrev;
1091   struct dwarf2_section_info info;
1092   struct dwarf2_section_info line;
1093   struct dwarf2_section_info loc;
1094   struct dwarf2_section_info macinfo;
1095   struct dwarf2_section_info macro;
1096   struct dwarf2_section_info str_offsets;
1097   struct dwarf2_section_info types;
1098 };
1099
1100 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1101    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1102
1103 struct virtual_v1_dwo_sections
1104 {
1105   struct dwarf2_section_info abbrev;
1106   struct dwarf2_section_info line;
1107   struct dwarf2_section_info loc;
1108   struct dwarf2_section_info macinfo;
1109   struct dwarf2_section_info macro;
1110   struct dwarf2_section_info str_offsets;
1111   /* Each DWP hash table entry records one CU or one TU.
1112      That is recorded here, and copied to dwo_unit.section.  */
1113   struct dwarf2_section_info info_or_types;
1114 };
1115
1116 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1117    In version 2, the sections of the DWO files are concatenated together
1118    and stored in one section of that name.  Thus each ELF section contains
1119    several "virtual" sections.  */
1120
1121 struct virtual_v2_dwo_sections
1122 {
1123   bfd_size_type abbrev_offset;
1124   bfd_size_type abbrev_size;
1125
1126   bfd_size_type line_offset;
1127   bfd_size_type line_size;
1128
1129   bfd_size_type loc_offset;
1130   bfd_size_type loc_size;
1131
1132   bfd_size_type macinfo_offset;
1133   bfd_size_type macinfo_size;
1134
1135   bfd_size_type macro_offset;
1136   bfd_size_type macro_size;
1137
1138   bfd_size_type str_offsets_offset;
1139   bfd_size_type str_offsets_size;
1140
1141   /* Each DWP hash table entry records one CU or one TU.
1142      That is recorded here, and copied to dwo_unit.section.  */
1143   bfd_size_type info_or_types_offset;
1144   bfd_size_type info_or_types_size;
1145 };
1146
1147 /* Contents of DWP hash tables.  */
1148
1149 struct dwp_hash_table
1150 {
1151   uint32_t version, nr_columns;
1152   uint32_t nr_units, nr_slots;
1153   const gdb_byte *hash_table, *unit_table;
1154   union
1155   {
1156     struct
1157     {
1158       const gdb_byte *indices;
1159     } v1;
1160     struct
1161     {
1162       /* This is indexed by column number and gives the id of the section
1163          in that column.  */
1164 #define MAX_NR_V2_DWO_SECTIONS \
1165   (1 /* .debug_info or .debug_types */ \
1166    + 1 /* .debug_abbrev */ \
1167    + 1 /* .debug_line */ \
1168    + 1 /* .debug_loc */ \
1169    + 1 /* .debug_str_offsets */ \
1170    + 1 /* .debug_macro or .debug_macinfo */)
1171       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1172       const gdb_byte *offsets;
1173       const gdb_byte *sizes;
1174     } v2;
1175   } section_pool;
1176 };
1177
1178 /* Data for one DWP file.  */
1179
1180 struct dwp_file
1181 {
1182   /* Name of the file.  */
1183   const char *name;
1184
1185   /* File format version.  */
1186   int version;
1187
1188   /* The bfd.  */
1189   bfd *dbfd;
1190
1191   /* Section info for this file.  */
1192   struct dwp_sections sections;
1193
1194   /* Table of CUs in the file.  */
1195   const struct dwp_hash_table *cus;
1196
1197   /* Table of TUs in the file.  */
1198   const struct dwp_hash_table *tus;
1199
1200   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1201   htab_t loaded_cus;
1202   htab_t loaded_tus;
1203
1204   /* Table to map ELF section numbers to their sections.
1205      This is only needed for the DWP V1 file format.  */
1206   unsigned int num_sections;
1207   asection **elf_sections;
1208 };
1209
1210 /* This represents a '.dwz' file.  */
1211
1212 struct dwz_file
1213 {
1214   /* A dwz file can only contain a few sections.  */
1215   struct dwarf2_section_info abbrev;
1216   struct dwarf2_section_info info;
1217   struct dwarf2_section_info str;
1218   struct dwarf2_section_info line;
1219   struct dwarf2_section_info macro;
1220   struct dwarf2_section_info gdb_index;
1221   struct dwarf2_section_info debug_names;
1222
1223   /* The dwz's BFD.  */
1224   bfd *dwz_bfd;
1225 };
1226
1227 /* Struct used to pass misc. parameters to read_die_and_children, et
1228    al.  which are used for both .debug_info and .debug_types dies.
1229    All parameters here are unchanging for the life of the call.  This
1230    struct exists to abstract away the constant parameters of die reading.  */
1231
1232 struct die_reader_specs
1233 {
1234   /* The bfd of die_section.  */
1235   bfd* abfd;
1236
1237   /* The CU of the DIE we are parsing.  */
1238   struct dwarf2_cu *cu;
1239
1240   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1241   struct dwo_file *dwo_file;
1242
1243   /* The section the die comes from.
1244      This is either .debug_info or .debug_types, or the .dwo variants.  */
1245   struct dwarf2_section_info *die_section;
1246
1247   /* die_section->buffer.  */
1248   const gdb_byte *buffer;
1249
1250   /* The end of the buffer.  */
1251   const gdb_byte *buffer_end;
1252
1253   /* The value of the DW_AT_comp_dir attribute.  */
1254   const char *comp_dir;
1255
1256   /* The abbreviation table to use when reading the DIEs.  */
1257   struct abbrev_table *abbrev_table;
1258 };
1259
1260 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1261 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1262                                       const gdb_byte *info_ptr,
1263                                       struct die_info *comp_unit_die,
1264                                       int has_children,
1265                                       void *data);
1266
1267 /* A 1-based directory index.  This is a strong typedef to prevent
1268    accidentally using a directory index as a 0-based index into an
1269    array/vector.  */
1270 enum class dir_index : unsigned int {};
1271
1272 /* Likewise, a 1-based file name index.  */
1273 enum class file_name_index : unsigned int {};
1274
1275 struct file_entry
1276 {
1277   file_entry () = default;
1278
1279   file_entry (const char *name_, dir_index d_index_,
1280               unsigned int mod_time_, unsigned int length_)
1281     : name (name_),
1282       d_index (d_index_),
1283       mod_time (mod_time_),
1284       length (length_)
1285   {}
1286
1287   /* Return the include directory at D_INDEX stored in LH.  Returns
1288      NULL if D_INDEX is out of bounds.  */
1289   const char *include_dir (const line_header *lh) const;
1290
1291   /* The file name.  Note this is an observing pointer.  The memory is
1292      owned by debug_line_buffer.  */
1293   const char *name {};
1294
1295   /* The directory index (1-based).  */
1296   dir_index d_index {};
1297
1298   unsigned int mod_time {};
1299
1300   unsigned int length {};
1301
1302   /* True if referenced by the Line Number Program.  */
1303   bool included_p {};
1304
1305   /* The associated symbol table, if any.  */
1306   struct symtab *symtab {};
1307 };
1308
1309 /* The line number information for a compilation unit (found in the
1310    .debug_line section) begins with a "statement program header",
1311    which contains the following information.  */
1312 struct line_header
1313 {
1314   line_header ()
1315     : offset_in_dwz {}
1316   {}
1317
1318   /* Add an entry to the include directory table.  */
1319   void add_include_dir (const char *include_dir);
1320
1321   /* Add an entry to the file name table.  */
1322   void add_file_name (const char *name, dir_index d_index,
1323                       unsigned int mod_time, unsigned int length);
1324
1325   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1326      is out of bounds.  */
1327   const char *include_dir_at (dir_index index) const
1328   {
1329     /* Convert directory index number (1-based) to vector index
1330        (0-based).  */
1331     size_t vec_index = to_underlying (index) - 1;
1332
1333     if (vec_index >= include_dirs.size ())
1334       return NULL;
1335     return include_dirs[vec_index];
1336   }
1337
1338   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1339      is out of bounds.  */
1340   file_entry *file_name_at (file_name_index index)
1341   {
1342     /* Convert file name index number (1-based) to vector index
1343        (0-based).  */
1344     size_t vec_index = to_underlying (index) - 1;
1345
1346     if (vec_index >= file_names.size ())
1347       return NULL;
1348     return &file_names[vec_index];
1349   }
1350
1351   /* Const version of the above.  */
1352   const file_entry *file_name_at (unsigned int index) const
1353   {
1354     if (index >= file_names.size ())
1355       return NULL;
1356     return &file_names[index];
1357   }
1358
1359   /* Offset of line number information in .debug_line section.  */
1360   sect_offset sect_off {};
1361
1362   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1363   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1364
1365   unsigned int total_length {};
1366   unsigned short version {};
1367   unsigned int header_length {};
1368   unsigned char minimum_instruction_length {};
1369   unsigned char maximum_ops_per_instruction {};
1370   unsigned char default_is_stmt {};
1371   int line_base {};
1372   unsigned char line_range {};
1373   unsigned char opcode_base {};
1374
1375   /* standard_opcode_lengths[i] is the number of operands for the
1376      standard opcode whose value is i.  This means that
1377      standard_opcode_lengths[0] is unused, and the last meaningful
1378      element is standard_opcode_lengths[opcode_base - 1].  */
1379   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1380
1381   /* The include_directories table.  Note these are observing
1382      pointers.  The memory is owned by debug_line_buffer.  */
1383   std::vector<const char *> include_dirs;
1384
1385   /* The file_names table.  */
1386   std::vector<file_entry> file_names;
1387
1388   /* The start and end of the statement program following this
1389      header.  These point into dwarf2_per_objfile->line_buffer.  */
1390   const gdb_byte *statement_program_start {}, *statement_program_end {};
1391 };
1392
1393 typedef std::unique_ptr<line_header> line_header_up;
1394
1395 const char *
1396 file_entry::include_dir (const line_header *lh) const
1397 {
1398   return lh->include_dir_at (d_index);
1399 }
1400
1401 /* When we construct a partial symbol table entry we only
1402    need this much information.  */
1403 struct partial_die_info
1404   {
1405     /* Offset of this DIE.  */
1406     sect_offset sect_off;
1407
1408     /* DWARF-2 tag for this DIE.  */
1409     ENUM_BITFIELD(dwarf_tag) tag : 16;
1410
1411     /* Assorted flags describing the data found in this DIE.  */
1412     unsigned int has_children : 1;
1413     unsigned int is_external : 1;
1414     unsigned int is_declaration : 1;
1415     unsigned int has_type : 1;
1416     unsigned int has_specification : 1;
1417     unsigned int has_pc_info : 1;
1418     unsigned int may_be_inlined : 1;
1419
1420     /* This DIE has been marked DW_AT_main_subprogram.  */
1421     unsigned int main_subprogram : 1;
1422
1423     /* Flag set if the SCOPE field of this structure has been
1424        computed.  */
1425     unsigned int scope_set : 1;
1426
1427     /* Flag set if the DIE has a byte_size attribute.  */
1428     unsigned int has_byte_size : 1;
1429
1430     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1431     unsigned int has_const_value : 1;
1432
1433     /* Flag set if any of the DIE's children are template arguments.  */
1434     unsigned int has_template_arguments : 1;
1435
1436     /* Flag set if fixup_partial_die has been called on this die.  */
1437     unsigned int fixup_called : 1;
1438
1439     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1440     unsigned int is_dwz : 1;
1441
1442     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1443     unsigned int spec_is_dwz : 1;
1444
1445     /* The name of this DIE.  Normally the value of DW_AT_name, but
1446        sometimes a default name for unnamed DIEs.  */
1447     const char *name;
1448
1449     /* The linkage name, if present.  */
1450     const char *linkage_name;
1451
1452     /* The scope to prepend to our children.  This is generally
1453        allocated on the comp_unit_obstack, so will disappear
1454        when this compilation unit leaves the cache.  */
1455     const char *scope;
1456
1457     /* Some data associated with the partial DIE.  The tag determines
1458        which field is live.  */
1459     union
1460     {
1461       /* The location description associated with this DIE, if any.  */
1462       struct dwarf_block *locdesc;
1463       /* The offset of an import, for DW_TAG_imported_unit.  */
1464       sect_offset sect_off;
1465     } d;
1466
1467     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1468     CORE_ADDR lowpc;
1469     CORE_ADDR highpc;
1470
1471     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1472        DW_AT_sibling, if any.  */
1473     /* NOTE: This member isn't strictly necessary, read_partial_die could
1474        return DW_AT_sibling values to its caller load_partial_dies.  */
1475     const gdb_byte *sibling;
1476
1477     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1478        DW_AT_specification (or DW_AT_abstract_origin or
1479        DW_AT_extension).  */
1480     sect_offset spec_offset;
1481
1482     /* Pointers to this DIE's parent, first child, and next sibling,
1483        if any.  */
1484     struct partial_die_info *die_parent, *die_child, *die_sibling;
1485   };
1486
1487 /* This data structure holds the information of an abbrev.  */
1488 struct abbrev_info
1489   {
1490     unsigned int number;        /* number identifying abbrev */
1491     enum dwarf_tag tag;         /* dwarf tag */
1492     unsigned short has_children;                /* boolean */
1493     unsigned short num_attrs;   /* number of attributes */
1494     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1495     struct abbrev_info *next;   /* next in chain */
1496   };
1497
1498 struct attr_abbrev
1499   {
1500     ENUM_BITFIELD(dwarf_attribute) name : 16;
1501     ENUM_BITFIELD(dwarf_form) form : 16;
1502
1503     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1504     LONGEST implicit_const;
1505   };
1506
1507 /* Size of abbrev_table.abbrev_hash_table.  */
1508 #define ABBREV_HASH_SIZE 121
1509
1510 /* Top level data structure to contain an abbreviation table.  */
1511
1512 struct abbrev_table
1513 {
1514   explicit abbrev_table (sect_offset off)
1515     : sect_off (off)
1516   {
1517     m_abbrevs =
1518       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1519     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1520   }
1521
1522   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1523
1524   /* Allocate space for a struct abbrev_info object in
1525      ABBREV_TABLE.  */
1526   struct abbrev_info *alloc_abbrev ();
1527
1528   /* Add an abbreviation to the table.  */
1529   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1530
1531   /* Look up an abbrev in the table.
1532      Returns NULL if the abbrev is not found.  */
1533
1534   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1535
1536
1537   /* Where the abbrev table came from.
1538      This is used as a sanity check when the table is used.  */
1539   const sect_offset sect_off;
1540
1541   /* Storage for the abbrev table.  */
1542   auto_obstack abbrev_obstack;
1543
1544 private:
1545
1546   /* Hash table of abbrevs.
1547      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1548      It could be statically allocated, but the previous code didn't so we
1549      don't either.  */
1550   struct abbrev_info **m_abbrevs;
1551 };
1552
1553 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1554
1555 /* Attributes have a name and a value.  */
1556 struct attribute
1557   {
1558     ENUM_BITFIELD(dwarf_attribute) name : 16;
1559     ENUM_BITFIELD(dwarf_form) form : 15;
1560
1561     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1562        field should be in u.str (existing only for DW_STRING) but it is kept
1563        here for better struct attribute alignment.  */
1564     unsigned int string_is_canonical : 1;
1565
1566     union
1567       {
1568         const char *str;
1569         struct dwarf_block *blk;
1570         ULONGEST unsnd;
1571         LONGEST snd;
1572         CORE_ADDR addr;
1573         ULONGEST signature;
1574       }
1575     u;
1576   };
1577
1578 /* This data structure holds a complete die structure.  */
1579 struct die_info
1580   {
1581     /* DWARF-2 tag for this DIE.  */
1582     ENUM_BITFIELD(dwarf_tag) tag : 16;
1583
1584     /* Number of attributes */
1585     unsigned char num_attrs;
1586
1587     /* True if we're presently building the full type name for the
1588        type derived from this DIE.  */
1589     unsigned char building_fullname : 1;
1590
1591     /* True if this die is in process.  PR 16581.  */
1592     unsigned char in_process : 1;
1593
1594     /* Abbrev number */
1595     unsigned int abbrev;
1596
1597     /* Offset in .debug_info or .debug_types section.  */
1598     sect_offset sect_off;
1599
1600     /* The dies in a compilation unit form an n-ary tree.  PARENT
1601        points to this die's parent; CHILD points to the first child of
1602        this node; and all the children of a given node are chained
1603        together via their SIBLING fields.  */
1604     struct die_info *child;     /* Its first child, if any.  */
1605     struct die_info *sibling;   /* Its next sibling, if any.  */
1606     struct die_info *parent;    /* Its parent, if any.  */
1607
1608     /* An array of attributes, with NUM_ATTRS elements.  There may be
1609        zero, but it's not common and zero-sized arrays are not
1610        sufficiently portable C.  */
1611     struct attribute attrs[1];
1612   };
1613
1614 /* Get at parts of an attribute structure.  */
1615
1616 #define DW_STRING(attr)    ((attr)->u.str)
1617 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1618 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1619 #define DW_BLOCK(attr)     ((attr)->u.blk)
1620 #define DW_SND(attr)       ((attr)->u.snd)
1621 #define DW_ADDR(attr)      ((attr)->u.addr)
1622 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1623
1624 /* Blocks are a bunch of untyped bytes.  */
1625 struct dwarf_block
1626   {
1627     size_t size;
1628
1629     /* Valid only if SIZE is not zero.  */
1630     const gdb_byte *data;
1631   };
1632
1633 #ifndef ATTR_ALLOC_CHUNK
1634 #define ATTR_ALLOC_CHUNK 4
1635 #endif
1636
1637 /* Allocate fields for structs, unions and enums in this size.  */
1638 #ifndef DW_FIELD_ALLOC_CHUNK
1639 #define DW_FIELD_ALLOC_CHUNK 4
1640 #endif
1641
1642 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1643    but this would require a corresponding change in unpack_field_as_long
1644    and friends.  */
1645 static int bits_per_byte = 8;
1646
1647 struct nextfield
1648 {
1649   struct nextfield *next;
1650   int accessibility;
1651   int virtuality;
1652   struct field field;
1653 };
1654
1655 struct nextfnfield
1656 {
1657   struct nextfnfield *next;
1658   struct fn_field fnfield;
1659 };
1660
1661 struct fnfieldlist
1662 {
1663   const char *name;
1664   int length;
1665   struct nextfnfield *head;
1666 };
1667
1668 struct decl_field_list
1669 {
1670   struct decl_field field;
1671   struct decl_field_list *next;
1672 };
1673
1674 /* The routines that read and process dies for a C struct or C++ class
1675    pass lists of data member fields and lists of member function fields
1676    in an instance of a field_info structure, as defined below.  */
1677 struct field_info
1678   {
1679     /* List of data member and baseclasses fields.  */
1680     struct nextfield *fields, *baseclasses;
1681
1682     /* Number of fields (including baseclasses).  */
1683     int nfields;
1684
1685     /* Number of baseclasses.  */
1686     int nbaseclasses;
1687
1688     /* Set if the accesibility of one of the fields is not public.  */
1689     int non_public_fields;
1690
1691     /* Member function fieldlist array, contains name of possibly overloaded
1692        member function, number of overloaded member functions and a pointer
1693        to the head of the member function field chain.  */
1694     struct fnfieldlist *fnfieldlists;
1695
1696     /* Number of entries in the fnfieldlists array.  */
1697     int nfnfields;
1698
1699     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1700        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1701     struct decl_field_list *typedef_field_list;
1702     unsigned typedef_field_list_count;
1703
1704     /* Nested types defined by this class and the number of elements in this
1705        list.  */
1706     struct decl_field_list *nested_types_list;
1707     unsigned nested_types_list_count;
1708   };
1709
1710 /* One item on the queue of compilation units to read in full symbols
1711    for.  */
1712 struct dwarf2_queue_item
1713 {
1714   struct dwarf2_per_cu_data *per_cu;
1715   enum language pretend_language;
1716   struct dwarf2_queue_item *next;
1717 };
1718
1719 /* The current queue.  */
1720 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1721
1722 /* Loaded secondary compilation units are kept in memory until they
1723    have not been referenced for the processing of this many
1724    compilation units.  Set this to zero to disable caching.  Cache
1725    sizes of up to at least twenty will improve startup time for
1726    typical inter-CU-reference binaries, at an obvious memory cost.  */
1727 static int dwarf_max_cache_age = 5;
1728 static void
1729 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1730                           struct cmd_list_element *c, const char *value)
1731 {
1732   fprintf_filtered (file, _("The upper bound on the age of cached "
1733                             "DWARF compilation units is %s.\n"),
1734                     value);
1735 }
1736 \f
1737 /* local function prototypes */
1738
1739 static const char *get_section_name (const struct dwarf2_section_info *);
1740
1741 static const char *get_section_file_name (const struct dwarf2_section_info *);
1742
1743 static void dwarf2_find_base_address (struct die_info *die,
1744                                       struct dwarf2_cu *cu);
1745
1746 static struct partial_symtab *create_partial_symtab
1747   (struct dwarf2_per_cu_data *per_cu, const char *name);
1748
1749 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1750                                         const gdb_byte *info_ptr,
1751                                         struct die_info *type_unit_die,
1752                                         int has_children, void *data);
1753
1754 static void dwarf2_build_psymtabs_hard
1755   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1756
1757 static void scan_partial_symbols (struct partial_die_info *,
1758                                   CORE_ADDR *, CORE_ADDR *,
1759                                   int, struct dwarf2_cu *);
1760
1761 static void add_partial_symbol (struct partial_die_info *,
1762                                 struct dwarf2_cu *);
1763
1764 static void add_partial_namespace (struct partial_die_info *pdi,
1765                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1766                                    int set_addrmap, struct dwarf2_cu *cu);
1767
1768 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1769                                 CORE_ADDR *highpc, int set_addrmap,
1770                                 struct dwarf2_cu *cu);
1771
1772 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1773                                      struct dwarf2_cu *cu);
1774
1775 static void add_partial_subprogram (struct partial_die_info *pdi,
1776                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1777                                     int need_pc, struct dwarf2_cu *cu);
1778
1779 static void dwarf2_read_symtab (struct partial_symtab *,
1780                                 struct objfile *);
1781
1782 static void psymtab_to_symtab_1 (struct partial_symtab *);
1783
1784 static abbrev_table_up abbrev_table_read_table
1785   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1786    sect_offset);
1787
1788 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1789
1790 static struct partial_die_info *load_partial_dies
1791   (const struct die_reader_specs *, const gdb_byte *, int);
1792
1793 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1794                                          struct partial_die_info *,
1795                                          struct abbrev_info *,
1796                                          unsigned int,
1797                                          const gdb_byte *);
1798
1799 static struct partial_die_info *find_partial_die (sect_offset, int,
1800                                                   struct dwarf2_cu *);
1801
1802 static void fixup_partial_die (struct partial_die_info *,
1803                                struct dwarf2_cu *);
1804
1805 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1806                                        struct attribute *, struct attr_abbrev *,
1807                                        const gdb_byte *);
1808
1809 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1810
1811 static int read_1_signed_byte (bfd *, const gdb_byte *);
1812
1813 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1814
1815 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1816
1817 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1818
1819 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1820                                unsigned int *);
1821
1822 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1823
1824 static LONGEST read_checked_initial_length_and_offset
1825   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1826    unsigned int *, unsigned int *);
1827
1828 static LONGEST read_offset (bfd *, const gdb_byte *,
1829                             const struct comp_unit_head *,
1830                             unsigned int *);
1831
1832 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1833
1834 static sect_offset read_abbrev_offset
1835   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1836    struct dwarf2_section_info *, sect_offset);
1837
1838 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1839
1840 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1841
1842 static const char *read_indirect_string
1843   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1844    const struct comp_unit_head *, unsigned int *);
1845
1846 static const char *read_indirect_line_string
1847   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1848    const struct comp_unit_head *, unsigned int *);
1849
1850 static const char *read_indirect_string_at_offset
1851   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1852    LONGEST str_offset);
1853
1854 static const char *read_indirect_string_from_dwz
1855   (struct objfile *objfile, struct dwz_file *, LONGEST);
1856
1857 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1858
1859 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1860                                               const gdb_byte *,
1861                                               unsigned int *);
1862
1863 static const char *read_str_index (const struct die_reader_specs *reader,
1864                                    ULONGEST str_index);
1865
1866 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1867
1868 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1869                                       struct dwarf2_cu *);
1870
1871 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1872                                                 unsigned int);
1873
1874 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1875                                        struct dwarf2_cu *cu);
1876
1877 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1878                                struct dwarf2_cu *cu);
1879
1880 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1881
1882 static struct die_info *die_specification (struct die_info *die,
1883                                            struct dwarf2_cu **);
1884
1885 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1886                                                 struct dwarf2_cu *cu);
1887
1888 static void dwarf_decode_lines (struct line_header *, const char *,
1889                                 struct dwarf2_cu *, struct partial_symtab *,
1890                                 CORE_ADDR, int decode_mapping);
1891
1892 static void dwarf2_start_subfile (const char *, const char *);
1893
1894 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1895                                                     const char *, const char *,
1896                                                     CORE_ADDR);
1897
1898 static struct symbol *new_symbol (struct die_info *, struct type *,
1899                                   struct dwarf2_cu *, struct symbol * = NULL);
1900
1901 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1902                                 struct dwarf2_cu *);
1903
1904 static void dwarf2_const_value_attr (const struct attribute *attr,
1905                                      struct type *type,
1906                                      const char *name,
1907                                      struct obstack *obstack,
1908                                      struct dwarf2_cu *cu, LONGEST *value,
1909                                      const gdb_byte **bytes,
1910                                      struct dwarf2_locexpr_baton **baton);
1911
1912 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1913
1914 static int need_gnat_info (struct dwarf2_cu *);
1915
1916 static struct type *die_descriptive_type (struct die_info *,
1917                                           struct dwarf2_cu *);
1918
1919 static void set_descriptive_type (struct type *, struct die_info *,
1920                                   struct dwarf2_cu *);
1921
1922 static struct type *die_containing_type (struct die_info *,
1923                                          struct dwarf2_cu *);
1924
1925 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1926                                      struct dwarf2_cu *);
1927
1928 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1929
1930 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1931
1932 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1933
1934 static char *typename_concat (struct obstack *obs, const char *prefix,
1935                               const char *suffix, int physname,
1936                               struct dwarf2_cu *cu);
1937
1938 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1939
1940 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1941
1942 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1943
1944 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1945
1946 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1947
1948 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1949
1950 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1951                                struct dwarf2_cu *, struct partial_symtab *);
1952
1953 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1954    values.  Keep the items ordered with increasing constraints compliance.  */
1955 enum pc_bounds_kind
1956 {
1957   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1958   PC_BOUNDS_NOT_PRESENT,
1959
1960   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1961      were present but they do not form a valid range of PC addresses.  */
1962   PC_BOUNDS_INVALID,
1963
1964   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1965   PC_BOUNDS_RANGES,
1966
1967   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1968   PC_BOUNDS_HIGH_LOW,
1969 };
1970
1971 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1972                                                  CORE_ADDR *, CORE_ADDR *,
1973                                                  struct dwarf2_cu *,
1974                                                  struct partial_symtab *);
1975
1976 static void get_scope_pc_bounds (struct die_info *,
1977                                  CORE_ADDR *, CORE_ADDR *,
1978                                  struct dwarf2_cu *);
1979
1980 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1981                                         CORE_ADDR, struct dwarf2_cu *);
1982
1983 static void dwarf2_add_field (struct field_info *, struct die_info *,
1984                               struct dwarf2_cu *);
1985
1986 static void dwarf2_attach_fields_to_type (struct field_info *,
1987                                           struct type *, struct dwarf2_cu *);
1988
1989 static void dwarf2_add_member_fn (struct field_info *,
1990                                   struct die_info *, struct type *,
1991                                   struct dwarf2_cu *);
1992
1993 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1994                                              struct type *,
1995                                              struct dwarf2_cu *);
1996
1997 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1998
1999 static void read_common_block (struct die_info *, struct dwarf2_cu *);
2000
2001 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2002
2003 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2004
2005 static struct using_direct **using_directives (enum language);
2006
2007 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2008
2009 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2010
2011 static struct type *read_module_type (struct die_info *die,
2012                                       struct dwarf2_cu *cu);
2013
2014 static const char *namespace_name (struct die_info *die,
2015                                    int *is_anonymous, struct dwarf2_cu *);
2016
2017 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2018
2019 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2020
2021 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2022                                                        struct dwarf2_cu *);
2023
2024 static struct die_info *read_die_and_siblings_1
2025   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2026    struct die_info *);
2027
2028 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2029                                                const gdb_byte *info_ptr,
2030                                                const gdb_byte **new_info_ptr,
2031                                                struct die_info *parent);
2032
2033 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2034                                         struct die_info **, const gdb_byte *,
2035                                         int *, int);
2036
2037 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2038                                       struct die_info **, const gdb_byte *,
2039                                       int *);
2040
2041 static void process_die (struct die_info *, struct dwarf2_cu *);
2042
2043 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2044                                              struct obstack *);
2045
2046 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2047
2048 static const char *dwarf2_full_name (const char *name,
2049                                      struct die_info *die,
2050                                      struct dwarf2_cu *cu);
2051
2052 static const char *dwarf2_physname (const char *name, struct die_info *die,
2053                                     struct dwarf2_cu *cu);
2054
2055 static struct die_info *dwarf2_extension (struct die_info *die,
2056                                           struct dwarf2_cu **);
2057
2058 static const char *dwarf_tag_name (unsigned int);
2059
2060 static const char *dwarf_attr_name (unsigned int);
2061
2062 static const char *dwarf_form_name (unsigned int);
2063
2064 static const char *dwarf_bool_name (unsigned int);
2065
2066 static const char *dwarf_type_encoding_name (unsigned int);
2067
2068 static struct die_info *sibling_die (struct die_info *);
2069
2070 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2071
2072 static void dump_die_for_error (struct die_info *);
2073
2074 static void dump_die_1 (struct ui_file *, int level, int max_level,
2075                         struct die_info *);
2076
2077 /*static*/ void dump_die (struct die_info *, int max_level);
2078
2079 static void store_in_ref_table (struct die_info *,
2080                                 struct dwarf2_cu *);
2081
2082 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2083
2084 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2085
2086 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2087                                                const struct attribute *,
2088                                                struct dwarf2_cu **);
2089
2090 static struct die_info *follow_die_ref (struct die_info *,
2091                                         const struct attribute *,
2092                                         struct dwarf2_cu **);
2093
2094 static struct die_info *follow_die_sig (struct die_info *,
2095                                         const struct attribute *,
2096                                         struct dwarf2_cu **);
2097
2098 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2099                                          struct dwarf2_cu *);
2100
2101 static struct type *get_DW_AT_signature_type (struct die_info *,
2102                                               const struct attribute *,
2103                                               struct dwarf2_cu *);
2104
2105 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2106
2107 static void read_signatured_type (struct signatured_type *);
2108
2109 static int attr_to_dynamic_prop (const struct attribute *attr,
2110                                  struct die_info *die, struct dwarf2_cu *cu,
2111                                  struct dynamic_prop *prop);
2112
2113 /* memory allocation interface */
2114
2115 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2116
2117 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2118
2119 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2120
2121 static int attr_form_is_block (const struct attribute *);
2122
2123 static int attr_form_is_section_offset (const struct attribute *);
2124
2125 static int attr_form_is_constant (const struct attribute *);
2126
2127 static int attr_form_is_ref (const struct attribute *);
2128
2129 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2130                                    struct dwarf2_loclist_baton *baton,
2131                                    const struct attribute *attr);
2132
2133 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2134                                          struct symbol *sym,
2135                                          struct dwarf2_cu *cu,
2136                                          int is_block);
2137
2138 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2139                                      const gdb_byte *info_ptr,
2140                                      struct abbrev_info *abbrev);
2141
2142 static hashval_t partial_die_hash (const void *item);
2143
2144 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2145
2146 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2147   (sect_offset sect_off, unsigned int offset_in_dwz,
2148    struct dwarf2_per_objfile *dwarf2_per_objfile);
2149
2150 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2151                                    struct die_info *comp_unit_die,
2152                                    enum language pretend_language);
2153
2154 static void free_cached_comp_units (void *);
2155
2156 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2157
2158 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2159
2160 static struct type *set_die_type (struct die_info *, struct type *,
2161                                   struct dwarf2_cu *);
2162
2163 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2164
2165 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2166
2167 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2168                                  enum language);
2169
2170 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2171                                     enum language);
2172
2173 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2174                                     enum language);
2175
2176 static void dwarf2_add_dependence (struct dwarf2_cu *,
2177                                    struct dwarf2_per_cu_data *);
2178
2179 static void dwarf2_mark (struct dwarf2_cu *);
2180
2181 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2182
2183 static struct type *get_die_type_at_offset (sect_offset,
2184                                             struct dwarf2_per_cu_data *);
2185
2186 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2187
2188 static void dwarf2_release_queue (void *dummy);
2189
2190 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2191                              enum language pretend_language);
2192
2193 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2194
2195 /* The return type of find_file_and_directory.  Note, the enclosed
2196    string pointers are only valid while this object is valid.  */
2197
2198 struct file_and_directory
2199 {
2200   /* The filename.  This is never NULL.  */
2201   const char *name;
2202
2203   /* The compilation directory.  NULL if not known.  If we needed to
2204      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2205      points directly to the DW_AT_comp_dir string attribute owned by
2206      the obstack that owns the DIE.  */
2207   const char *comp_dir;
2208
2209   /* If we needed to build a new string for comp_dir, this is what
2210      owns the storage.  */
2211   std::string comp_dir_storage;
2212 };
2213
2214 static file_and_directory find_file_and_directory (struct die_info *die,
2215                                                    struct dwarf2_cu *cu);
2216
2217 static char *file_full_name (int file, struct line_header *lh,
2218                              const char *comp_dir);
2219
2220 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2221 enum class rcuh_kind { COMPILE, TYPE };
2222
2223 static const gdb_byte *read_and_check_comp_unit_head
2224   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2225    struct comp_unit_head *header,
2226    struct dwarf2_section_info *section,
2227    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2228    rcuh_kind section_kind);
2229
2230 static void init_cutu_and_read_dies
2231   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2232    int use_existing_cu, int keep,
2233    die_reader_func_ftype *die_reader_func, void *data);
2234
2235 static void init_cutu_and_read_dies_simple
2236   (struct dwarf2_per_cu_data *this_cu,
2237    die_reader_func_ftype *die_reader_func, void *data);
2238
2239 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2240
2241 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2242
2243 static struct dwo_unit *lookup_dwo_unit_in_dwp
2244   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2245    struct dwp_file *dwp_file, const char *comp_dir,
2246    ULONGEST signature, int is_debug_types);
2247
2248 static struct dwp_file *get_dwp_file
2249   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2250
2251 static struct dwo_unit *lookup_dwo_comp_unit
2252   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2253
2254 static struct dwo_unit *lookup_dwo_type_unit
2255   (struct signatured_type *, const char *, const char *);
2256
2257 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2258
2259 static void free_dwo_file_cleanup (void *);
2260
2261 struct free_dwo_file_cleanup_data
2262 {
2263   struct dwo_file *dwo_file;
2264   struct dwarf2_per_objfile *dwarf2_per_objfile;
2265 };
2266
2267 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2268
2269 static void check_producer (struct dwarf2_cu *cu);
2270
2271 static void free_line_header_voidp (void *arg);
2272 \f
2273 /* Various complaints about symbol reading that don't abort the process.  */
2274
2275 static void
2276 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2277 {
2278   complaint (&symfile_complaints,
2279              _("statement list doesn't fit in .debug_line section"));
2280 }
2281
2282 static void
2283 dwarf2_debug_line_missing_file_complaint (void)
2284 {
2285   complaint (&symfile_complaints,
2286              _(".debug_line section has line data without a file"));
2287 }
2288
2289 static void
2290 dwarf2_debug_line_missing_end_sequence_complaint (void)
2291 {
2292   complaint (&symfile_complaints,
2293              _(".debug_line section has line "
2294                "program sequence without an end"));
2295 }
2296
2297 static void
2298 dwarf2_complex_location_expr_complaint (void)
2299 {
2300   complaint (&symfile_complaints, _("location expression too complex"));
2301 }
2302
2303 static void
2304 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2305                                               int arg3)
2306 {
2307   complaint (&symfile_complaints,
2308              _("const value length mismatch for '%s', got %d, expected %d"),
2309              arg1, arg2, arg3);
2310 }
2311
2312 static void
2313 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2314 {
2315   complaint (&symfile_complaints,
2316              _("debug info runs off end of %s section"
2317                " [in module %s]"),
2318              get_section_name (section),
2319              get_section_file_name (section));
2320 }
2321
2322 static void
2323 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2324 {
2325   complaint (&symfile_complaints,
2326              _("macro debug info contains a "
2327                "malformed macro definition:\n`%s'"),
2328              arg1);
2329 }
2330
2331 static void
2332 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2333 {
2334   complaint (&symfile_complaints,
2335              _("invalid attribute class or form for '%s' in '%s'"),
2336              arg1, arg2);
2337 }
2338
2339 /* Hash function for line_header_hash.  */
2340
2341 static hashval_t
2342 line_header_hash (const struct line_header *ofs)
2343 {
2344   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2345 }
2346
2347 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2348
2349 static hashval_t
2350 line_header_hash_voidp (const void *item)
2351 {
2352   const struct line_header *ofs = (const struct line_header *) item;
2353
2354   return line_header_hash (ofs);
2355 }
2356
2357 /* Equality function for line_header_hash.  */
2358
2359 static int
2360 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2361 {
2362   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2363   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2364
2365   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2366           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2367 }
2368
2369 \f
2370
2371 /* Read the given attribute value as an address, taking the attribute's
2372    form into account.  */
2373
2374 static CORE_ADDR
2375 attr_value_as_address (struct attribute *attr)
2376 {
2377   CORE_ADDR addr;
2378
2379   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2380     {
2381       /* Aside from a few clearly defined exceptions, attributes that
2382          contain an address must always be in DW_FORM_addr form.
2383          Unfortunately, some compilers happen to be violating this
2384          requirement by encoding addresses using other forms, such
2385          as DW_FORM_data4 for example.  For those broken compilers,
2386          we try to do our best, without any guarantee of success,
2387          to interpret the address correctly.  It would also be nice
2388          to generate a complaint, but that would require us to maintain
2389          a list of legitimate cases where a non-address form is allowed,
2390          as well as update callers to pass in at least the CU's DWARF
2391          version.  This is more overhead than what we're willing to
2392          expand for a pretty rare case.  */
2393       addr = DW_UNSND (attr);
2394     }
2395   else
2396     addr = DW_ADDR (attr);
2397
2398   return addr;
2399 }
2400
2401 /* The suffix for an index file.  */
2402 #define INDEX4_SUFFIX ".gdb-index"
2403 #define INDEX5_SUFFIX ".debug_names"
2404 #define DEBUG_STR_SUFFIX ".debug_str"
2405
2406 /* See declaration.  */
2407
2408 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2409                                         const dwarf2_debug_sections *names)
2410   : objfile (objfile_)
2411 {
2412   if (names == NULL)
2413     names = &dwarf2_elf_names;
2414
2415   bfd *obfd = objfile->obfd;
2416
2417   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2418     locate_sections (obfd, sec, *names);
2419 }
2420
2421 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2422
2423 dwarf2_per_objfile::~dwarf2_per_objfile ()
2424 {
2425   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2426   free_cached_comp_units ();
2427
2428   if (quick_file_names_table)
2429     htab_delete (quick_file_names_table);
2430
2431   if (line_header_hash)
2432     htab_delete (line_header_hash);
2433
2434   for (int ix = 0; ix < n_comp_units; ++ix)
2435    VEC_free (dwarf2_per_cu_ptr, all_comp_units[ix]->imported_symtabs);
2436
2437   for (int ix = 0; ix < n_type_units; ++ix)
2438     VEC_free (dwarf2_per_cu_ptr,
2439               all_type_units[ix]->per_cu.imported_symtabs);
2440   xfree (all_type_units);
2441
2442   VEC_free (dwarf2_section_info_def, types);
2443
2444   if (dwo_files != NULL)
2445     free_dwo_files (dwo_files, objfile);
2446   if (dwp_file != NULL)
2447     gdb_bfd_unref (dwp_file->dbfd);
2448
2449   if (dwz_file != NULL && dwz_file->dwz_bfd)
2450     gdb_bfd_unref (dwz_file->dwz_bfd);
2451
2452   if (index_table != NULL)
2453     index_table->~mapped_index ();
2454
2455   /* Everything else should be on the objfile obstack.  */
2456 }
2457
2458 /* See declaration.  */
2459
2460 void
2461 dwarf2_per_objfile::free_cached_comp_units ()
2462 {
2463   dwarf2_per_cu_data *per_cu = read_in_chain;
2464   dwarf2_per_cu_data **last_chain = &read_in_chain;
2465   while (per_cu != NULL)
2466     {
2467       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2468
2469       delete per_cu->cu;
2470       *last_chain = next_cu;
2471       per_cu = next_cu;
2472     }
2473 }
2474
2475 /* Try to locate the sections we need for DWARF 2 debugging
2476    information and return true if we have enough to do something.
2477    NAMES points to the dwarf2 section names, or is NULL if the standard
2478    ELF names are used.  */
2479
2480 int
2481 dwarf2_has_info (struct objfile *objfile,
2482                  const struct dwarf2_debug_sections *names)
2483 {
2484   if (objfile->flags & OBJF_READNEVER)
2485     return 0;
2486
2487   struct dwarf2_per_objfile *dwarf2_per_objfile
2488     = get_dwarf2_per_objfile (objfile);
2489
2490   if (dwarf2_per_objfile == NULL)
2491     {
2492       /* Initialize per-objfile state.  */
2493       struct dwarf2_per_objfile *data
2494         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2495
2496       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2497       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2498     }
2499   return (!dwarf2_per_objfile->info.is_virtual
2500           && dwarf2_per_objfile->info.s.section != NULL
2501           && !dwarf2_per_objfile->abbrev.is_virtual
2502           && dwarf2_per_objfile->abbrev.s.section != NULL);
2503 }
2504
2505 /* Return the containing section of virtual section SECTION.  */
2506
2507 static struct dwarf2_section_info *
2508 get_containing_section (const struct dwarf2_section_info *section)
2509 {
2510   gdb_assert (section->is_virtual);
2511   return section->s.containing_section;
2512 }
2513
2514 /* Return the bfd owner of SECTION.  */
2515
2516 static struct bfd *
2517 get_section_bfd_owner (const struct dwarf2_section_info *section)
2518 {
2519   if (section->is_virtual)
2520     {
2521       section = get_containing_section (section);
2522       gdb_assert (!section->is_virtual);
2523     }
2524   return section->s.section->owner;
2525 }
2526
2527 /* Return the bfd section of SECTION.
2528    Returns NULL if the section is not present.  */
2529
2530 static asection *
2531 get_section_bfd_section (const struct dwarf2_section_info *section)
2532 {
2533   if (section->is_virtual)
2534     {
2535       section = get_containing_section (section);
2536       gdb_assert (!section->is_virtual);
2537     }
2538   return section->s.section;
2539 }
2540
2541 /* Return the name of SECTION.  */
2542
2543 static const char *
2544 get_section_name (const struct dwarf2_section_info *section)
2545 {
2546   asection *sectp = get_section_bfd_section (section);
2547
2548   gdb_assert (sectp != NULL);
2549   return bfd_section_name (get_section_bfd_owner (section), sectp);
2550 }
2551
2552 /* Return the name of the file SECTION is in.  */
2553
2554 static const char *
2555 get_section_file_name (const struct dwarf2_section_info *section)
2556 {
2557   bfd *abfd = get_section_bfd_owner (section);
2558
2559   return bfd_get_filename (abfd);
2560 }
2561
2562 /* Return the id of SECTION.
2563    Returns 0 if SECTION doesn't exist.  */
2564
2565 static int
2566 get_section_id (const struct dwarf2_section_info *section)
2567 {
2568   asection *sectp = get_section_bfd_section (section);
2569
2570   if (sectp == NULL)
2571     return 0;
2572   return sectp->id;
2573 }
2574
2575 /* Return the flags of SECTION.
2576    SECTION (or containing section if this is a virtual section) must exist.  */
2577
2578 static int
2579 get_section_flags (const struct dwarf2_section_info *section)
2580 {
2581   asection *sectp = get_section_bfd_section (section);
2582
2583   gdb_assert (sectp != NULL);
2584   return bfd_get_section_flags (sectp->owner, sectp);
2585 }
2586
2587 /* When loading sections, we look either for uncompressed section or for
2588    compressed section names.  */
2589
2590 static int
2591 section_is_p (const char *section_name,
2592               const struct dwarf2_section_names *names)
2593 {
2594   if (names->normal != NULL
2595       && strcmp (section_name, names->normal) == 0)
2596     return 1;
2597   if (names->compressed != NULL
2598       && strcmp (section_name, names->compressed) == 0)
2599     return 1;
2600   return 0;
2601 }
2602
2603 /* See declaration.  */
2604
2605 void
2606 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2607                                      const dwarf2_debug_sections &names)
2608 {
2609   flagword aflag = bfd_get_section_flags (abfd, sectp);
2610
2611   if ((aflag & SEC_HAS_CONTENTS) == 0)
2612     {
2613     }
2614   else if (section_is_p (sectp->name, &names.info))
2615     {
2616       this->info.s.section = sectp;
2617       this->info.size = bfd_get_section_size (sectp);
2618     }
2619   else if (section_is_p (sectp->name, &names.abbrev))
2620     {
2621       this->abbrev.s.section = sectp;
2622       this->abbrev.size = bfd_get_section_size (sectp);
2623     }
2624   else if (section_is_p (sectp->name, &names.line))
2625     {
2626       this->line.s.section = sectp;
2627       this->line.size = bfd_get_section_size (sectp);
2628     }
2629   else if (section_is_p (sectp->name, &names.loc))
2630     {
2631       this->loc.s.section = sectp;
2632       this->loc.size = bfd_get_section_size (sectp);
2633     }
2634   else if (section_is_p (sectp->name, &names.loclists))
2635     {
2636       this->loclists.s.section = sectp;
2637       this->loclists.size = bfd_get_section_size (sectp);
2638     }
2639   else if (section_is_p (sectp->name, &names.macinfo))
2640     {
2641       this->macinfo.s.section = sectp;
2642       this->macinfo.size = bfd_get_section_size (sectp);
2643     }
2644   else if (section_is_p (sectp->name, &names.macro))
2645     {
2646       this->macro.s.section = sectp;
2647       this->macro.size = bfd_get_section_size (sectp);
2648     }
2649   else if (section_is_p (sectp->name, &names.str))
2650     {
2651       this->str.s.section = sectp;
2652       this->str.size = bfd_get_section_size (sectp);
2653     }
2654   else if (section_is_p (sectp->name, &names.line_str))
2655     {
2656       this->line_str.s.section = sectp;
2657       this->line_str.size = bfd_get_section_size (sectp);
2658     }
2659   else if (section_is_p (sectp->name, &names.addr))
2660     {
2661       this->addr.s.section = sectp;
2662       this->addr.size = bfd_get_section_size (sectp);
2663     }
2664   else if (section_is_p (sectp->name, &names.frame))
2665     {
2666       this->frame.s.section = sectp;
2667       this->frame.size = bfd_get_section_size (sectp);
2668     }
2669   else if (section_is_p (sectp->name, &names.eh_frame))
2670     {
2671       this->eh_frame.s.section = sectp;
2672       this->eh_frame.size = bfd_get_section_size (sectp);
2673     }
2674   else if (section_is_p (sectp->name, &names.ranges))
2675     {
2676       this->ranges.s.section = sectp;
2677       this->ranges.size = bfd_get_section_size (sectp);
2678     }
2679   else if (section_is_p (sectp->name, &names.rnglists))
2680     {
2681       this->rnglists.s.section = sectp;
2682       this->rnglists.size = bfd_get_section_size (sectp);
2683     }
2684   else if (section_is_p (sectp->name, &names.types))
2685     {
2686       struct dwarf2_section_info type_section;
2687
2688       memset (&type_section, 0, sizeof (type_section));
2689       type_section.s.section = sectp;
2690       type_section.size = bfd_get_section_size (sectp);
2691
2692       VEC_safe_push (dwarf2_section_info_def, this->types,
2693                      &type_section);
2694     }
2695   else if (section_is_p (sectp->name, &names.gdb_index))
2696     {
2697       this->gdb_index.s.section = sectp;
2698       this->gdb_index.size = bfd_get_section_size (sectp);
2699     }
2700   else if (section_is_p (sectp->name, &names.debug_names))
2701     {
2702       this->debug_names.s.section = sectp;
2703       this->debug_names.size = bfd_get_section_size (sectp);
2704     }
2705   else if (section_is_p (sectp->name, &names.debug_aranges))
2706     {
2707       this->debug_aranges.s.section = sectp;
2708       this->debug_aranges.size = bfd_get_section_size (sectp);
2709     }
2710
2711   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2712       && bfd_section_vma (abfd, sectp) == 0)
2713     this->has_section_at_zero = true;
2714 }
2715
2716 /* A helper function that decides whether a section is empty,
2717    or not present.  */
2718
2719 static int
2720 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2721 {
2722   if (section->is_virtual)
2723     return section->size == 0;
2724   return section->s.section == NULL || section->size == 0;
2725 }
2726
2727 /* Read the contents of the section INFO.
2728    OBJFILE is the main object file, but not necessarily the file where
2729    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2730    of the DWO file.
2731    If the section is compressed, uncompress it before returning.  */
2732
2733 static void
2734 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2735 {
2736   asection *sectp;
2737   bfd *abfd;
2738   gdb_byte *buf, *retbuf;
2739
2740   if (info->readin)
2741     return;
2742   info->buffer = NULL;
2743   info->readin = 1;
2744
2745   if (dwarf2_section_empty_p (info))
2746     return;
2747
2748   sectp = get_section_bfd_section (info);
2749
2750   /* If this is a virtual section we need to read in the real one first.  */
2751   if (info->is_virtual)
2752     {
2753       struct dwarf2_section_info *containing_section =
2754         get_containing_section (info);
2755
2756       gdb_assert (sectp != NULL);
2757       if ((sectp->flags & SEC_RELOC) != 0)
2758         {
2759           error (_("Dwarf Error: DWP format V2 with relocations is not"
2760                    " supported in section %s [in module %s]"),
2761                  get_section_name (info), get_section_file_name (info));
2762         }
2763       dwarf2_read_section (objfile, containing_section);
2764       /* Other code should have already caught virtual sections that don't
2765          fit.  */
2766       gdb_assert (info->virtual_offset + info->size
2767                   <= containing_section->size);
2768       /* If the real section is empty or there was a problem reading the
2769          section we shouldn't get here.  */
2770       gdb_assert (containing_section->buffer != NULL);
2771       info->buffer = containing_section->buffer + info->virtual_offset;
2772       return;
2773     }
2774
2775   /* If the section has relocations, we must read it ourselves.
2776      Otherwise we attach it to the BFD.  */
2777   if ((sectp->flags & SEC_RELOC) == 0)
2778     {
2779       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2780       return;
2781     }
2782
2783   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2784   info->buffer = buf;
2785
2786   /* When debugging .o files, we may need to apply relocations; see
2787      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2788      We never compress sections in .o files, so we only need to
2789      try this when the section is not compressed.  */
2790   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2791   if (retbuf != NULL)
2792     {
2793       info->buffer = retbuf;
2794       return;
2795     }
2796
2797   abfd = get_section_bfd_owner (info);
2798   gdb_assert (abfd != NULL);
2799
2800   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2801       || bfd_bread (buf, info->size, abfd) != info->size)
2802     {
2803       error (_("Dwarf Error: Can't read DWARF data"
2804                " in section %s [in module %s]"),
2805              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2806     }
2807 }
2808
2809 /* A helper function that returns the size of a section in a safe way.
2810    If you are positive that the section has been read before using the
2811    size, then it is safe to refer to the dwarf2_section_info object's
2812    "size" field directly.  In other cases, you must call this
2813    function, because for compressed sections the size field is not set
2814    correctly until the section has been read.  */
2815
2816 static bfd_size_type
2817 dwarf2_section_size (struct objfile *objfile,
2818                      struct dwarf2_section_info *info)
2819 {
2820   if (!info->readin)
2821     dwarf2_read_section (objfile, info);
2822   return info->size;
2823 }
2824
2825 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2826    SECTION_NAME.  */
2827
2828 void
2829 dwarf2_get_section_info (struct objfile *objfile,
2830                          enum dwarf2_section_enum sect,
2831                          asection **sectp, const gdb_byte **bufp,
2832                          bfd_size_type *sizep)
2833 {
2834   struct dwarf2_per_objfile *data
2835     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2836                                                   dwarf2_objfile_data_key);
2837   struct dwarf2_section_info *info;
2838
2839   /* We may see an objfile without any DWARF, in which case we just
2840      return nothing.  */
2841   if (data == NULL)
2842     {
2843       *sectp = NULL;
2844       *bufp = NULL;
2845       *sizep = 0;
2846       return;
2847     }
2848   switch (sect)
2849     {
2850     case DWARF2_DEBUG_FRAME:
2851       info = &data->frame;
2852       break;
2853     case DWARF2_EH_FRAME:
2854       info = &data->eh_frame;
2855       break;
2856     default:
2857       gdb_assert_not_reached ("unexpected section");
2858     }
2859
2860   dwarf2_read_section (objfile, info);
2861
2862   *sectp = get_section_bfd_section (info);
2863   *bufp = info->buffer;
2864   *sizep = info->size;
2865 }
2866
2867 /* A helper function to find the sections for a .dwz file.  */
2868
2869 static void
2870 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2871 {
2872   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2873
2874   /* Note that we only support the standard ELF names, because .dwz
2875      is ELF-only (at the time of writing).  */
2876   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2877     {
2878       dwz_file->abbrev.s.section = sectp;
2879       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2880     }
2881   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2882     {
2883       dwz_file->info.s.section = sectp;
2884       dwz_file->info.size = bfd_get_section_size (sectp);
2885     }
2886   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2887     {
2888       dwz_file->str.s.section = sectp;
2889       dwz_file->str.size = bfd_get_section_size (sectp);
2890     }
2891   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2892     {
2893       dwz_file->line.s.section = sectp;
2894       dwz_file->line.size = bfd_get_section_size (sectp);
2895     }
2896   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2897     {
2898       dwz_file->macro.s.section = sectp;
2899       dwz_file->macro.size = bfd_get_section_size (sectp);
2900     }
2901   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2902     {
2903       dwz_file->gdb_index.s.section = sectp;
2904       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2905     }
2906   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2907     {
2908       dwz_file->debug_names.s.section = sectp;
2909       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2910     }
2911 }
2912
2913 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2914    there is no .gnu_debugaltlink section in the file.  Error if there
2915    is such a section but the file cannot be found.  */
2916
2917 static struct dwz_file *
2918 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2919 {
2920   const char *filename;
2921   struct dwz_file *result;
2922   bfd_size_type buildid_len_arg;
2923   size_t buildid_len;
2924   bfd_byte *buildid;
2925
2926   if (dwarf2_per_objfile->dwz_file != NULL)
2927     return dwarf2_per_objfile->dwz_file;
2928
2929   bfd_set_error (bfd_error_no_error);
2930   gdb::unique_xmalloc_ptr<char> data
2931     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2932                                   &buildid_len_arg, &buildid));
2933   if (data == NULL)
2934     {
2935       if (bfd_get_error () == bfd_error_no_error)
2936         return NULL;
2937       error (_("could not read '.gnu_debugaltlink' section: %s"),
2938              bfd_errmsg (bfd_get_error ()));
2939     }
2940
2941   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2942
2943   buildid_len = (size_t) buildid_len_arg;
2944
2945   filename = data.get ();
2946
2947   std::string abs_storage;
2948   if (!IS_ABSOLUTE_PATH (filename))
2949     {
2950       gdb::unique_xmalloc_ptr<char> abs
2951         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2952
2953       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2954       filename = abs_storage.c_str ();
2955     }
2956
2957   /* First try the file name given in the section.  If that doesn't
2958      work, try to use the build-id instead.  */
2959   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2960   if (dwz_bfd != NULL)
2961     {
2962       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2963         dwz_bfd.release ();
2964     }
2965
2966   if (dwz_bfd == NULL)
2967     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2968
2969   if (dwz_bfd == NULL)
2970     error (_("could not find '.gnu_debugaltlink' file for %s"),
2971            objfile_name (dwarf2_per_objfile->objfile));
2972
2973   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2974                            struct dwz_file);
2975   result->dwz_bfd = dwz_bfd.release ();
2976
2977   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2978
2979   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2980   dwarf2_per_objfile->dwz_file = result;
2981   return result;
2982 }
2983 \f
2984 /* DWARF quick_symbols_functions support.  */
2985
2986 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2987    unique line tables, so we maintain a separate table of all .debug_line
2988    derived entries to support the sharing.
2989    All the quick functions need is the list of file names.  We discard the
2990    line_header when we're done and don't need to record it here.  */
2991 struct quick_file_names
2992 {
2993   /* The data used to construct the hash key.  */
2994   struct stmt_list_hash hash;
2995
2996   /* The number of entries in file_names, real_names.  */
2997   unsigned int num_file_names;
2998
2999   /* The file names from the line table, after being run through
3000      file_full_name.  */
3001   const char **file_names;
3002
3003   /* The file names from the line table after being run through
3004      gdb_realpath.  These are computed lazily.  */
3005   const char **real_names;
3006 };
3007
3008 /* When using the index (and thus not using psymtabs), each CU has an
3009    object of this type.  This is used to hold information needed by
3010    the various "quick" methods.  */
3011 struct dwarf2_per_cu_quick_data
3012 {
3013   /* The file table.  This can be NULL if there was no file table
3014      or it's currently not read in.
3015      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
3016   struct quick_file_names *file_names;
3017
3018   /* The corresponding symbol table.  This is NULL if symbols for this
3019      CU have not yet been read.  */
3020   struct compunit_symtab *compunit_symtab;
3021
3022   /* A temporary mark bit used when iterating over all CUs in
3023      expand_symtabs_matching.  */
3024   unsigned int mark : 1;
3025
3026   /* True if we've tried to read the file table and found there isn't one.
3027      There will be no point in trying to read it again next time.  */
3028   unsigned int no_file_data : 1;
3029 };
3030
3031 /* Utility hash function for a stmt_list_hash.  */
3032
3033 static hashval_t
3034 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3035 {
3036   hashval_t v = 0;
3037
3038   if (stmt_list_hash->dwo_unit != NULL)
3039     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3040   v += to_underlying (stmt_list_hash->line_sect_off);
3041   return v;
3042 }
3043
3044 /* Utility equality function for a stmt_list_hash.  */
3045
3046 static int
3047 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3048                     const struct stmt_list_hash *rhs)
3049 {
3050   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3051     return 0;
3052   if (lhs->dwo_unit != NULL
3053       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3054     return 0;
3055
3056   return lhs->line_sect_off == rhs->line_sect_off;
3057 }
3058
3059 /* Hash function for a quick_file_names.  */
3060
3061 static hashval_t
3062 hash_file_name_entry (const void *e)
3063 {
3064   const struct quick_file_names *file_data
3065     = (const struct quick_file_names *) e;
3066
3067   return hash_stmt_list_entry (&file_data->hash);
3068 }
3069
3070 /* Equality function for a quick_file_names.  */
3071
3072 static int
3073 eq_file_name_entry (const void *a, const void *b)
3074 {
3075   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3076   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3077
3078   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3079 }
3080
3081 /* Delete function for a quick_file_names.  */
3082
3083 static void
3084 delete_file_name_entry (void *e)
3085 {
3086   struct quick_file_names *file_data = (struct quick_file_names *) e;
3087   int i;
3088
3089   for (i = 0; i < file_data->num_file_names; ++i)
3090     {
3091       xfree ((void*) file_data->file_names[i]);
3092       if (file_data->real_names)
3093         xfree ((void*) file_data->real_names[i]);
3094     }
3095
3096   /* The space for the struct itself lives on objfile_obstack,
3097      so we don't free it here.  */
3098 }
3099
3100 /* Create a quick_file_names hash table.  */
3101
3102 static htab_t
3103 create_quick_file_names_table (unsigned int nr_initial_entries)
3104 {
3105   return htab_create_alloc (nr_initial_entries,
3106                             hash_file_name_entry, eq_file_name_entry,
3107                             delete_file_name_entry, xcalloc, xfree);
3108 }
3109
3110 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3111    have to be created afterwards.  You should call age_cached_comp_units after
3112    processing PER_CU->CU.  dw2_setup must have been already called.  */
3113
3114 static void
3115 load_cu (struct dwarf2_per_cu_data *per_cu)
3116 {
3117   if (per_cu->is_debug_types)
3118     load_full_type_unit (per_cu);
3119   else
3120     load_full_comp_unit (per_cu, language_minimal);
3121
3122   if (per_cu->cu == NULL)
3123     return;  /* Dummy CU.  */
3124
3125   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3126 }
3127
3128 /* Read in the symbols for PER_CU.  */
3129
3130 static void
3131 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3132 {
3133   struct cleanup *back_to;
3134   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3135
3136   /* Skip type_unit_groups, reading the type units they contain
3137      is handled elsewhere.  */
3138   if (IS_TYPE_UNIT_GROUP (per_cu))
3139     return;
3140
3141   back_to = make_cleanup (dwarf2_release_queue, NULL);
3142
3143   if (dwarf2_per_objfile->using_index
3144       ? per_cu->v.quick->compunit_symtab == NULL
3145       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3146     {
3147       queue_comp_unit (per_cu, language_minimal);
3148       load_cu (per_cu);
3149
3150       /* If we just loaded a CU from a DWO, and we're working with an index
3151          that may badly handle TUs, load all the TUs in that DWO as well.
3152          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3153       if (!per_cu->is_debug_types
3154           && per_cu->cu != NULL
3155           && per_cu->cu->dwo_unit != NULL
3156           && dwarf2_per_objfile->index_table != NULL
3157           && dwarf2_per_objfile->index_table->version <= 7
3158           /* DWP files aren't supported yet.  */
3159           && get_dwp_file (dwarf2_per_objfile) == NULL)
3160         queue_and_load_all_dwo_tus (per_cu);
3161     }
3162
3163   process_queue (dwarf2_per_objfile);
3164
3165   /* Age the cache, releasing compilation units that have not
3166      been used recently.  */
3167   age_cached_comp_units (dwarf2_per_objfile);
3168
3169   do_cleanups (back_to);
3170 }
3171
3172 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3173    the objfile from which this CU came.  Returns the resulting symbol
3174    table.  */
3175
3176 static struct compunit_symtab *
3177 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3178 {
3179   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3180
3181   gdb_assert (dwarf2_per_objfile->using_index);
3182   if (!per_cu->v.quick->compunit_symtab)
3183     {
3184       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3185                                               dwarf2_per_objfile);
3186       scoped_restore decrementer = increment_reading_symtab ();
3187       dw2_do_instantiate_symtab (per_cu);
3188       process_cu_includes (dwarf2_per_objfile);
3189       do_cleanups (back_to);
3190     }
3191
3192   return per_cu->v.quick->compunit_symtab;
3193 }
3194
3195 /* Return the CU/TU given its index.
3196
3197    This is intended for loops like:
3198
3199    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3200                     + dwarf2_per_objfile->n_type_units); ++i)
3201      {
3202        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3203
3204        ...;
3205      }
3206 */
3207
3208 static struct dwarf2_per_cu_data *
3209 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3210               int index)
3211 {
3212   if (index >= dwarf2_per_objfile->n_comp_units)
3213     {
3214       index -= dwarf2_per_objfile->n_comp_units;
3215       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3216       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3217     }
3218
3219   return dwarf2_per_objfile->all_comp_units[index];
3220 }
3221
3222 /* Return the CU given its index.
3223    This differs from dw2_get_cutu in that it's for when you know INDEX
3224    refers to a CU.  */
3225
3226 static struct dwarf2_per_cu_data *
3227 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3228 {
3229   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3230
3231   return dwarf2_per_objfile->all_comp_units[index];
3232 }
3233
3234 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3235    objfile_obstack, and constructed with the specified field
3236    values.  */
3237
3238 static dwarf2_per_cu_data *
3239 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3240                           struct dwarf2_section_info *section,
3241                           int is_dwz,
3242                           sect_offset sect_off, ULONGEST length)
3243 {
3244   struct objfile *objfile = dwarf2_per_objfile->objfile;
3245   dwarf2_per_cu_data *the_cu
3246     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3247                      struct dwarf2_per_cu_data);
3248   the_cu->sect_off = sect_off;
3249   the_cu->length = length;
3250   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3251   the_cu->section = section;
3252   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3253                                    struct dwarf2_per_cu_quick_data);
3254   the_cu->is_dwz = is_dwz;
3255   return the_cu;
3256 }
3257
3258 /* A helper for create_cus_from_index that handles a given list of
3259    CUs.  */
3260
3261 static void
3262 create_cus_from_index_list (struct objfile *objfile,
3263                             const gdb_byte *cu_list, offset_type n_elements,
3264                             struct dwarf2_section_info *section,
3265                             int is_dwz,
3266                             int base_offset)
3267 {
3268   offset_type i;
3269   struct dwarf2_per_objfile *dwarf2_per_objfile
3270     = get_dwarf2_per_objfile (objfile);
3271
3272   for (i = 0; i < n_elements; i += 2)
3273     {
3274       gdb_static_assert (sizeof (ULONGEST) >= 8);
3275
3276       sect_offset sect_off
3277         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3278       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3279       cu_list += 2 * 8;
3280
3281       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3282         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3283                                      sect_off, length);
3284     }
3285 }
3286
3287 /* Read the CU list from the mapped index, and use it to create all
3288    the CU objects for this objfile.  */
3289
3290 static void
3291 create_cus_from_index (struct objfile *objfile,
3292                        const gdb_byte *cu_list, offset_type cu_list_elements,
3293                        const gdb_byte *dwz_list, offset_type dwz_elements)
3294 {
3295   struct dwz_file *dwz;
3296   struct dwarf2_per_objfile *dwarf2_per_objfile
3297     = get_dwarf2_per_objfile (objfile);
3298
3299   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3300   dwarf2_per_objfile->all_comp_units =
3301     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3302                dwarf2_per_objfile->n_comp_units);
3303
3304   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3305                               &dwarf2_per_objfile->info, 0, 0);
3306
3307   if (dwz_elements == 0)
3308     return;
3309
3310   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3311   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3312                               cu_list_elements / 2);
3313 }
3314
3315 /* Create the signatured type hash table from the index.  */
3316
3317 static void
3318 create_signatured_type_table_from_index (struct objfile *objfile,
3319                                          struct dwarf2_section_info *section,
3320                                          const gdb_byte *bytes,
3321                                          offset_type elements)
3322 {
3323   offset_type i;
3324   htab_t sig_types_hash;
3325   struct dwarf2_per_objfile *dwarf2_per_objfile
3326     = get_dwarf2_per_objfile (objfile);
3327
3328   dwarf2_per_objfile->n_type_units
3329     = dwarf2_per_objfile->n_allocated_type_units
3330     = elements / 3;
3331   dwarf2_per_objfile->all_type_units =
3332     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3333
3334   sig_types_hash = allocate_signatured_type_table (objfile);
3335
3336   for (i = 0; i < elements; i += 3)
3337     {
3338       struct signatured_type *sig_type;
3339       ULONGEST signature;
3340       void **slot;
3341       cu_offset type_offset_in_tu;
3342
3343       gdb_static_assert (sizeof (ULONGEST) >= 8);
3344       sect_offset sect_off
3345         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3346       type_offset_in_tu
3347         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3348                                                 BFD_ENDIAN_LITTLE);
3349       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3350       bytes += 3 * 8;
3351
3352       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3353                                  struct signatured_type);
3354       sig_type->signature = signature;
3355       sig_type->type_offset_in_tu = type_offset_in_tu;
3356       sig_type->per_cu.is_debug_types = 1;
3357       sig_type->per_cu.section = section;
3358       sig_type->per_cu.sect_off = sect_off;
3359       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3360       sig_type->per_cu.v.quick
3361         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3362                           struct dwarf2_per_cu_quick_data);
3363
3364       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3365       *slot = sig_type;
3366
3367       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3368     }
3369
3370   dwarf2_per_objfile->signatured_types = sig_types_hash;
3371 }
3372
3373 /* Create the signatured type hash table from .debug_names.  */
3374
3375 static void
3376 create_signatured_type_table_from_debug_names
3377   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3378    const mapped_debug_names &map,
3379    struct dwarf2_section_info *section,
3380    struct dwarf2_section_info *abbrev_section)
3381 {
3382   struct objfile *objfile = dwarf2_per_objfile->objfile;
3383
3384   dwarf2_read_section (objfile, section);
3385   dwarf2_read_section (objfile, abbrev_section);
3386
3387   dwarf2_per_objfile->n_type_units
3388     = dwarf2_per_objfile->n_allocated_type_units
3389     = map.tu_count;
3390   dwarf2_per_objfile->all_type_units
3391     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3392
3393   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3394
3395   for (uint32_t i = 0; i < map.tu_count; ++i)
3396     {
3397       struct signatured_type *sig_type;
3398       ULONGEST signature;
3399       void **slot;
3400       cu_offset type_offset_in_tu;
3401
3402       sect_offset sect_off
3403         = (sect_offset) (extract_unsigned_integer
3404                          (map.tu_table_reordered + i * map.offset_size,
3405                           map.offset_size,
3406                           map.dwarf5_byte_order));
3407
3408       comp_unit_head cu_header;
3409       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3410                                      abbrev_section,
3411                                      section->buffer + to_underlying (sect_off),
3412                                      rcuh_kind::TYPE);
3413
3414       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3415                                  struct signatured_type);
3416       sig_type->signature = cu_header.signature;
3417       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3418       sig_type->per_cu.is_debug_types = 1;
3419       sig_type->per_cu.section = section;
3420       sig_type->per_cu.sect_off = sect_off;
3421       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3422       sig_type->per_cu.v.quick
3423         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3424                           struct dwarf2_per_cu_quick_data);
3425
3426       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3427       *slot = sig_type;
3428
3429       dwarf2_per_objfile->all_type_units[i] = sig_type;
3430     }
3431
3432   dwarf2_per_objfile->signatured_types = sig_types_hash;
3433 }
3434
3435 /* Read the address map data from the mapped index, and use it to
3436    populate the objfile's psymtabs_addrmap.  */
3437
3438 static void
3439 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3440                            struct mapped_index *index)
3441 {
3442   struct objfile *objfile = dwarf2_per_objfile->objfile;
3443   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3444   const gdb_byte *iter, *end;
3445   struct addrmap *mutable_map;
3446   CORE_ADDR baseaddr;
3447
3448   auto_obstack temp_obstack;
3449
3450   mutable_map = addrmap_create_mutable (&temp_obstack);
3451
3452   iter = index->address_table.data ();
3453   end = iter + index->address_table.size ();
3454
3455   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3456
3457   while (iter < end)
3458     {
3459       ULONGEST hi, lo, cu_index;
3460       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3461       iter += 8;
3462       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3463       iter += 8;
3464       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3465       iter += 4;
3466
3467       if (lo > hi)
3468         {
3469           complaint (&symfile_complaints,
3470                      _(".gdb_index address table has invalid range (%s - %s)"),
3471                      hex_string (lo), hex_string (hi));
3472           continue;
3473         }
3474
3475       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3476         {
3477           complaint (&symfile_complaints,
3478                      _(".gdb_index address table has invalid CU number %u"),
3479                      (unsigned) cu_index);
3480           continue;
3481         }
3482
3483       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3484       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3485       addrmap_set_empty (mutable_map, lo, hi - 1,
3486                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3487     }
3488
3489   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3490                                                     &objfile->objfile_obstack);
3491 }
3492
3493 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3494    populate the objfile's psymtabs_addrmap.  */
3495
3496 static void
3497 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3498                              struct dwarf2_section_info *section)
3499 {
3500   struct objfile *objfile = dwarf2_per_objfile->objfile;
3501   bfd *abfd = objfile->obfd;
3502   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3503   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3504                                        SECT_OFF_TEXT (objfile));
3505
3506   auto_obstack temp_obstack;
3507   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3508
3509   std::unordered_map<sect_offset,
3510                      dwarf2_per_cu_data *,
3511                      gdb::hash_enum<sect_offset>>
3512     debug_info_offset_to_per_cu;
3513   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3514     {
3515       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3516       const auto insertpair
3517         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3518       if (!insertpair.second)
3519         {
3520           warning (_("Section .debug_aranges in %s has duplicate "
3521                      "debug_info_offset %u, ignoring .debug_aranges."),
3522                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3523           return;
3524         }
3525     }
3526
3527   dwarf2_read_section (objfile, section);
3528
3529   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3530
3531   const gdb_byte *addr = section->buffer;
3532
3533   while (addr < section->buffer + section->size)
3534     {
3535       const gdb_byte *const entry_addr = addr;
3536       unsigned int bytes_read;
3537
3538       const LONGEST entry_length = read_initial_length (abfd, addr,
3539                                                         &bytes_read);
3540       addr += bytes_read;
3541
3542       const gdb_byte *const entry_end = addr + entry_length;
3543       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3544       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3545       if (addr + entry_length > section->buffer + section->size)
3546         {
3547           warning (_("Section .debug_aranges in %s entry at offset %zu "
3548                      "length %s exceeds section length %s, "
3549                      "ignoring .debug_aranges."),
3550                    objfile_name (objfile), entry_addr - section->buffer,
3551                    plongest (bytes_read + entry_length),
3552                    pulongest (section->size));
3553           return;
3554         }
3555
3556       /* The version number.  */
3557       const uint16_t version = read_2_bytes (abfd, addr);
3558       addr += 2;
3559       if (version != 2)
3560         {
3561           warning (_("Section .debug_aranges in %s entry at offset %zu "
3562                      "has unsupported version %d, ignoring .debug_aranges."),
3563                    objfile_name (objfile), entry_addr - section->buffer,
3564                    version);
3565           return;
3566         }
3567
3568       const uint64_t debug_info_offset
3569         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3570       addr += offset_size;
3571       const auto per_cu_it
3572         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3573       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3574         {
3575           warning (_("Section .debug_aranges in %s entry at offset %zu "
3576                      "debug_info_offset %s does not exists, "
3577                      "ignoring .debug_aranges."),
3578                    objfile_name (objfile), entry_addr - section->buffer,
3579                    pulongest (debug_info_offset));
3580           return;
3581         }
3582       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3583
3584       const uint8_t address_size = *addr++;
3585       if (address_size < 1 || address_size > 8)
3586         {
3587           warning (_("Section .debug_aranges in %s entry at offset %zu "
3588                      "address_size %u is invalid, ignoring .debug_aranges."),
3589                    objfile_name (objfile), entry_addr - section->buffer,
3590                    address_size);
3591           return;
3592         }
3593
3594       const uint8_t segment_selector_size = *addr++;
3595       if (segment_selector_size != 0)
3596         {
3597           warning (_("Section .debug_aranges in %s entry at offset %zu "
3598                      "segment_selector_size %u is not supported, "
3599                      "ignoring .debug_aranges."),
3600                    objfile_name (objfile), entry_addr - section->buffer,
3601                    segment_selector_size);
3602           return;
3603         }
3604
3605       /* Must pad to an alignment boundary that is twice the address
3606          size.  It is undocumented by the DWARF standard but GCC does
3607          use it.  */
3608       for (size_t padding = ((-(addr - section->buffer))
3609                              & (2 * address_size - 1));
3610            padding > 0; padding--)
3611         if (*addr++ != 0)
3612           {
3613             warning (_("Section .debug_aranges in %s entry at offset %zu "
3614                        "padding is not zero, ignoring .debug_aranges."),
3615                      objfile_name (objfile), entry_addr - section->buffer);
3616             return;
3617           }
3618
3619       for (;;)
3620         {
3621           if (addr + 2 * address_size > entry_end)
3622             {
3623               warning (_("Section .debug_aranges in %s entry at offset %zu "
3624                          "address list is not properly terminated, "
3625                          "ignoring .debug_aranges."),
3626                        objfile_name (objfile), entry_addr - section->buffer);
3627               return;
3628             }
3629           ULONGEST start = extract_unsigned_integer (addr, address_size,
3630                                                      dwarf5_byte_order);
3631           addr += address_size;
3632           ULONGEST length = extract_unsigned_integer (addr, address_size,
3633                                                       dwarf5_byte_order);
3634           addr += address_size;
3635           if (start == 0 && length == 0)
3636             break;
3637           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3638             {
3639               /* Symbol was eliminated due to a COMDAT group.  */
3640               continue;
3641             }
3642           ULONGEST end = start + length;
3643           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3644           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3645           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3646         }
3647     }
3648
3649   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3650                                                     &objfile->objfile_obstack);
3651 }
3652
3653 /* The hash function for strings in the mapped index.  This is the same as
3654    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3655    implementation.  This is necessary because the hash function is tied to the
3656    format of the mapped index file.  The hash values do not have to match with
3657    SYMBOL_HASH_NEXT.
3658    
3659    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3660
3661 static hashval_t
3662 mapped_index_string_hash (int index_version, const void *p)
3663 {
3664   const unsigned char *str = (const unsigned char *) p;
3665   hashval_t r = 0;
3666   unsigned char c;
3667
3668   while ((c = *str++) != 0)
3669     {
3670       if (index_version >= 5)
3671         c = tolower (c);
3672       r = r * 67 + c - 113;
3673     }
3674
3675   return r;
3676 }
3677
3678 /* Find a slot in the mapped index INDEX for the object named NAME.
3679    If NAME is found, set *VEC_OUT to point to the CU vector in the
3680    constant pool and return true.  If NAME cannot be found, return
3681    false.  */
3682
3683 static bool
3684 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3685                           offset_type **vec_out)
3686 {
3687   offset_type hash;
3688   offset_type slot, step;
3689   int (*cmp) (const char *, const char *);
3690
3691   gdb::unique_xmalloc_ptr<char> without_params;
3692   if (current_language->la_language == language_cplus
3693       || current_language->la_language == language_fortran
3694       || current_language->la_language == language_d)
3695     {
3696       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3697          not contain any.  */
3698
3699       if (strchr (name, '(') != NULL)
3700         {
3701           without_params = cp_remove_params (name);
3702
3703           if (without_params != NULL)
3704             name = without_params.get ();
3705         }
3706     }
3707
3708   /* Index version 4 did not support case insensitive searches.  But the
3709      indices for case insensitive languages are built in lowercase, therefore
3710      simulate our NAME being searched is also lowercased.  */
3711   hash = mapped_index_string_hash ((index->version == 4
3712                                     && case_sensitivity == case_sensitive_off
3713                                     ? 5 : index->version),
3714                                    name);
3715
3716   slot = hash & (index->symbol_table.size () - 1);
3717   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3718   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3719
3720   for (;;)
3721     {
3722       const char *str;
3723
3724       const auto &bucket = index->symbol_table[slot];
3725       if (bucket.name == 0 && bucket.vec == 0)
3726         return false;
3727
3728       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3729       if (!cmp (name, str))
3730         {
3731           *vec_out = (offset_type *) (index->constant_pool
3732                                       + MAYBE_SWAP (bucket.vec));
3733           return true;
3734         }
3735
3736       slot = (slot + step) & (index->symbol_table.size () - 1);
3737     }
3738 }
3739
3740 /* A helper function that reads the .gdb_index from SECTION and fills
3741    in MAP.  FILENAME is the name of the file containing the section;
3742    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3743    ok to use deprecated sections.
3744
3745    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3746    out parameters that are filled in with information about the CU and
3747    TU lists in the section.
3748
3749    Returns 1 if all went well, 0 otherwise.  */
3750
3751 static int
3752 read_index_from_section (struct objfile *objfile,
3753                          const char *filename,
3754                          int deprecated_ok,
3755                          struct dwarf2_section_info *section,
3756                          struct mapped_index *map,
3757                          const gdb_byte **cu_list,
3758                          offset_type *cu_list_elements,
3759                          const gdb_byte **types_list,
3760                          offset_type *types_list_elements)
3761 {
3762   const gdb_byte *addr;
3763   offset_type version;
3764   offset_type *metadata;
3765   int i;
3766
3767   if (dwarf2_section_empty_p (section))
3768     return 0;
3769
3770   /* Older elfutils strip versions could keep the section in the main
3771      executable while splitting it for the separate debug info file.  */
3772   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3773     return 0;
3774
3775   dwarf2_read_section (objfile, section);
3776
3777   addr = section->buffer;
3778   /* Version check.  */
3779   version = MAYBE_SWAP (*(offset_type *) addr);
3780   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3781      causes the index to behave very poorly for certain requests.  Version 3
3782      contained incomplete addrmap.  So, it seems better to just ignore such
3783      indices.  */
3784   if (version < 4)
3785     {
3786       static int warning_printed = 0;
3787       if (!warning_printed)
3788         {
3789           warning (_("Skipping obsolete .gdb_index section in %s."),
3790                    filename);
3791           warning_printed = 1;
3792         }
3793       return 0;
3794     }
3795   /* Index version 4 uses a different hash function than index version
3796      5 and later.
3797
3798      Versions earlier than 6 did not emit psymbols for inlined
3799      functions.  Using these files will cause GDB not to be able to
3800      set breakpoints on inlined functions by name, so we ignore these
3801      indices unless the user has done
3802      "set use-deprecated-index-sections on".  */
3803   if (version < 6 && !deprecated_ok)
3804     {
3805       static int warning_printed = 0;
3806       if (!warning_printed)
3807         {
3808           warning (_("\
3809 Skipping deprecated .gdb_index section in %s.\n\
3810 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3811 to use the section anyway."),
3812                    filename);
3813           warning_printed = 1;
3814         }
3815       return 0;
3816     }
3817   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3818      of the TU (for symbols coming from TUs),
3819      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3820      Plus gold-generated indices can have duplicate entries for global symbols,
3821      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3822      These are just performance bugs, and we can't distinguish gdb-generated
3823      indices from gold-generated ones, so issue no warning here.  */
3824
3825   /* Indexes with higher version than the one supported by GDB may be no
3826      longer backward compatible.  */
3827   if (version > 8)
3828     return 0;
3829
3830   map->version = version;
3831   map->total_size = section->size;
3832
3833   metadata = (offset_type *) (addr + sizeof (offset_type));
3834
3835   i = 0;
3836   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3837   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3838                        / 8);
3839   ++i;
3840
3841   *types_list = addr + MAYBE_SWAP (metadata[i]);
3842   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3843                            - MAYBE_SWAP (metadata[i]))
3844                           / 8);
3845   ++i;
3846
3847   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3848   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3849   map->address_table
3850     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3851   ++i;
3852
3853   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3854   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3855   map->symbol_table
3856     = gdb::array_view<mapped_index::symbol_table_slot>
3857        ((mapped_index::symbol_table_slot *) symbol_table,
3858         (mapped_index::symbol_table_slot *) symbol_table_end);
3859
3860   ++i;
3861   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3862
3863   return 1;
3864 }
3865
3866 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3867    elements of all the CUs and return 1.  Otherwise, return 0.  */
3868
3869 static int
3870 dwarf2_read_index (struct objfile *objfile)
3871 {
3872   struct mapped_index local_map, *map;
3873   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3874   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3875   struct dwz_file *dwz;
3876   struct dwarf2_per_objfile *dwarf2_per_objfile
3877     = get_dwarf2_per_objfile (objfile);
3878
3879   if (!read_index_from_section (objfile, objfile_name (objfile),
3880                                 use_deprecated_index_sections,
3881                                 &dwarf2_per_objfile->gdb_index, &local_map,
3882                                 &cu_list, &cu_list_elements,
3883                                 &types_list, &types_list_elements))
3884     return 0;
3885
3886   /* Don't use the index if it's empty.  */
3887   if (local_map.symbol_table.empty ())
3888     return 0;
3889
3890   /* If there is a .dwz file, read it so we can get its CU list as
3891      well.  */
3892   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3893   if (dwz != NULL)
3894     {
3895       struct mapped_index dwz_map;
3896       const gdb_byte *dwz_types_ignore;
3897       offset_type dwz_types_elements_ignore;
3898
3899       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3900                                     1,
3901                                     &dwz->gdb_index, &dwz_map,
3902                                     &dwz_list, &dwz_list_elements,
3903                                     &dwz_types_ignore,
3904                                     &dwz_types_elements_ignore))
3905         {
3906           warning (_("could not read '.gdb_index' section from %s; skipping"),
3907                    bfd_get_filename (dwz->dwz_bfd));
3908           return 0;
3909         }
3910     }
3911
3912   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3913                          dwz_list_elements);
3914
3915   if (types_list_elements)
3916     {
3917       struct dwarf2_section_info *section;
3918
3919       /* We can only handle a single .debug_types when we have an
3920          index.  */
3921       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3922         return 0;
3923
3924       section = VEC_index (dwarf2_section_info_def,
3925                            dwarf2_per_objfile->types, 0);
3926
3927       create_signatured_type_table_from_index (objfile, section, types_list,
3928                                                types_list_elements);
3929     }
3930
3931   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3932
3933   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3934   map = new (map) mapped_index ();
3935   *map = local_map;
3936
3937   dwarf2_per_objfile->index_table = map;
3938   dwarf2_per_objfile->using_index = 1;
3939   dwarf2_per_objfile->quick_file_names_table =
3940     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3941
3942   return 1;
3943 }
3944
3945 /* die_reader_func for dw2_get_file_names.  */
3946
3947 static void
3948 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3949                            const gdb_byte *info_ptr,
3950                            struct die_info *comp_unit_die,
3951                            int has_children,
3952                            void *data)
3953 {
3954   struct dwarf2_cu *cu = reader->cu;
3955   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3956   struct dwarf2_per_objfile *dwarf2_per_objfile
3957     = cu->per_cu->dwarf2_per_objfile;
3958   struct objfile *objfile = dwarf2_per_objfile->objfile;
3959   struct dwarf2_per_cu_data *lh_cu;
3960   struct attribute *attr;
3961   int i;
3962   void **slot;
3963   struct quick_file_names *qfn;
3964
3965   gdb_assert (! this_cu->is_debug_types);
3966
3967   /* Our callers never want to match partial units -- instead they
3968      will match the enclosing full CU.  */
3969   if (comp_unit_die->tag == DW_TAG_partial_unit)
3970     {
3971       this_cu->v.quick->no_file_data = 1;
3972       return;
3973     }
3974
3975   lh_cu = this_cu;
3976   slot = NULL;
3977
3978   line_header_up lh;
3979   sect_offset line_offset {};
3980
3981   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3982   if (attr)
3983     {
3984       struct quick_file_names find_entry;
3985
3986       line_offset = (sect_offset) DW_UNSND (attr);
3987
3988       /* We may have already read in this line header (TU line header sharing).
3989          If we have we're done.  */
3990       find_entry.hash.dwo_unit = cu->dwo_unit;
3991       find_entry.hash.line_sect_off = line_offset;
3992       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3993                              &find_entry, INSERT);
3994       if (*slot != NULL)
3995         {
3996           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3997           return;
3998         }
3999
4000       lh = dwarf_decode_line_header (line_offset, cu);
4001     }
4002   if (lh == NULL)
4003     {
4004       lh_cu->v.quick->no_file_data = 1;
4005       return;
4006     }
4007
4008   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
4009   qfn->hash.dwo_unit = cu->dwo_unit;
4010   qfn->hash.line_sect_off = line_offset;
4011   gdb_assert (slot != NULL);
4012   *slot = qfn;
4013
4014   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
4015
4016   qfn->num_file_names = lh->file_names.size ();
4017   qfn->file_names =
4018     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
4019   for (i = 0; i < lh->file_names.size (); ++i)
4020     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
4021   qfn->real_names = NULL;
4022
4023   lh_cu->v.quick->file_names = qfn;
4024 }
4025
4026 /* A helper for the "quick" functions which attempts to read the line
4027    table for THIS_CU.  */
4028
4029 static struct quick_file_names *
4030 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4031 {
4032   /* This should never be called for TUs.  */
4033   gdb_assert (! this_cu->is_debug_types);
4034   /* Nor type unit groups.  */
4035   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4036
4037   if (this_cu->v.quick->file_names != NULL)
4038     return this_cu->v.quick->file_names;
4039   /* If we know there is no line data, no point in looking again.  */
4040   if (this_cu->v.quick->no_file_data)
4041     return NULL;
4042
4043   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4044
4045   if (this_cu->v.quick->no_file_data)
4046     return NULL;
4047   return this_cu->v.quick->file_names;
4048 }
4049
4050 /* A helper for the "quick" functions which computes and caches the
4051    real path for a given file name from the line table.  */
4052
4053 static const char *
4054 dw2_get_real_path (struct objfile *objfile,
4055                    struct quick_file_names *qfn, int index)
4056 {
4057   if (qfn->real_names == NULL)
4058     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4059                                       qfn->num_file_names, const char *);
4060
4061   if (qfn->real_names[index] == NULL)
4062     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4063
4064   return qfn->real_names[index];
4065 }
4066
4067 static struct symtab *
4068 dw2_find_last_source_symtab (struct objfile *objfile)
4069 {
4070   struct dwarf2_per_objfile *dwarf2_per_objfile
4071     = get_dwarf2_per_objfile (objfile);
4072   int index = dwarf2_per_objfile->n_comp_units - 1;
4073   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4074   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4075
4076   if (cust == NULL)
4077     return NULL;
4078
4079   return compunit_primary_filetab (cust);
4080 }
4081
4082 /* Traversal function for dw2_forget_cached_source_info.  */
4083
4084 static int
4085 dw2_free_cached_file_names (void **slot, void *info)
4086 {
4087   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4088
4089   if (file_data->real_names)
4090     {
4091       int i;
4092
4093       for (i = 0; i < file_data->num_file_names; ++i)
4094         {
4095           xfree ((void*) file_data->real_names[i]);
4096           file_data->real_names[i] = NULL;
4097         }
4098     }
4099
4100   return 1;
4101 }
4102
4103 static void
4104 dw2_forget_cached_source_info (struct objfile *objfile)
4105 {
4106   struct dwarf2_per_objfile *dwarf2_per_objfile
4107     = get_dwarf2_per_objfile (objfile);
4108
4109   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4110                           dw2_free_cached_file_names, NULL);
4111 }
4112
4113 /* Helper function for dw2_map_symtabs_matching_filename that expands
4114    the symtabs and calls the iterator.  */
4115
4116 static int
4117 dw2_map_expand_apply (struct objfile *objfile,
4118                       struct dwarf2_per_cu_data *per_cu,
4119                       const char *name, const char *real_path,
4120                       gdb::function_view<bool (symtab *)> callback)
4121 {
4122   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4123
4124   /* Don't visit already-expanded CUs.  */
4125   if (per_cu->v.quick->compunit_symtab)
4126     return 0;
4127
4128   /* This may expand more than one symtab, and we want to iterate over
4129      all of them.  */
4130   dw2_instantiate_symtab (per_cu);
4131
4132   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4133                                     last_made, callback);
4134 }
4135
4136 /* Implementation of the map_symtabs_matching_filename method.  */
4137
4138 static bool
4139 dw2_map_symtabs_matching_filename
4140   (struct objfile *objfile, const char *name, const char *real_path,
4141    gdb::function_view<bool (symtab *)> callback)
4142 {
4143   int i;
4144   const char *name_basename = lbasename (name);
4145   struct dwarf2_per_objfile *dwarf2_per_objfile
4146     = get_dwarf2_per_objfile (objfile);
4147
4148   /* The rule is CUs specify all the files, including those used by
4149      any TU, so there's no need to scan TUs here.  */
4150
4151   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4152     {
4153       int j;
4154       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4155       struct quick_file_names *file_data;
4156
4157       /* We only need to look at symtabs not already expanded.  */
4158       if (per_cu->v.quick->compunit_symtab)
4159         continue;
4160
4161       file_data = dw2_get_file_names (per_cu);
4162       if (file_data == NULL)
4163         continue;
4164
4165       for (j = 0; j < file_data->num_file_names; ++j)
4166         {
4167           const char *this_name = file_data->file_names[j];
4168           const char *this_real_name;
4169
4170           if (compare_filenames_for_search (this_name, name))
4171             {
4172               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4173                                         callback))
4174                 return true;
4175               continue;
4176             }
4177
4178           /* Before we invoke realpath, which can get expensive when many
4179              files are involved, do a quick comparison of the basenames.  */
4180           if (! basenames_may_differ
4181               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4182             continue;
4183
4184           this_real_name = dw2_get_real_path (objfile, file_data, j);
4185           if (compare_filenames_for_search (this_real_name, name))
4186             {
4187               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4188                                         callback))
4189                 return true;
4190               continue;
4191             }
4192
4193           if (real_path != NULL)
4194             {
4195               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4196               gdb_assert (IS_ABSOLUTE_PATH (name));
4197               if (this_real_name != NULL
4198                   && FILENAME_CMP (real_path, this_real_name) == 0)
4199                 {
4200                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4201                                             callback))
4202                     return true;
4203                   continue;
4204                 }
4205             }
4206         }
4207     }
4208
4209   return false;
4210 }
4211
4212 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4213
4214 struct dw2_symtab_iterator
4215 {
4216   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4217   struct dwarf2_per_objfile *dwarf2_per_objfile;
4218   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4219   int want_specific_block;
4220   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4221      Unused if !WANT_SPECIFIC_BLOCK.  */
4222   int block_index;
4223   /* The kind of symbol we're looking for.  */
4224   domain_enum domain;
4225   /* The list of CUs from the index entry of the symbol,
4226      or NULL if not found.  */
4227   offset_type *vec;
4228   /* The next element in VEC to look at.  */
4229   int next;
4230   /* The number of elements in VEC, or zero if there is no match.  */
4231   int length;
4232   /* Have we seen a global version of the symbol?
4233      If so we can ignore all further global instances.
4234      This is to work around gold/15646, inefficient gold-generated
4235      indices.  */
4236   int global_seen;
4237 };
4238
4239 /* Initialize the index symtab iterator ITER.
4240    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4241    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4242
4243 static void
4244 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4245                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4246                       int want_specific_block,
4247                       int block_index,
4248                       domain_enum domain,
4249                       const char *name)
4250 {
4251   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4252   iter->want_specific_block = want_specific_block;
4253   iter->block_index = block_index;
4254   iter->domain = domain;
4255   iter->next = 0;
4256   iter->global_seen = 0;
4257
4258   mapped_index *index = dwarf2_per_objfile->index_table;
4259
4260   /* index is NULL if OBJF_READNOW.  */
4261   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4262     iter->length = MAYBE_SWAP (*iter->vec);
4263   else
4264     {
4265       iter->vec = NULL;
4266       iter->length = 0;
4267     }
4268 }
4269
4270 /* Return the next matching CU or NULL if there are no more.  */
4271
4272 static struct dwarf2_per_cu_data *
4273 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4274 {
4275   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4276
4277   for ( ; iter->next < iter->length; ++iter->next)
4278     {
4279       offset_type cu_index_and_attrs =
4280         MAYBE_SWAP (iter->vec[iter->next + 1]);
4281       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4282       struct dwarf2_per_cu_data *per_cu;
4283       int want_static = iter->block_index != GLOBAL_BLOCK;
4284       /* This value is only valid for index versions >= 7.  */
4285       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4286       gdb_index_symbol_kind symbol_kind =
4287         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4288       /* Only check the symbol attributes if they're present.
4289          Indices prior to version 7 don't record them,
4290          and indices >= 7 may elide them for certain symbols
4291          (gold does this).  */
4292       int attrs_valid =
4293         (dwarf2_per_objfile->index_table->version >= 7
4294          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4295
4296       /* Don't crash on bad data.  */
4297       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4298                        + dwarf2_per_objfile->n_type_units))
4299         {
4300           complaint (&symfile_complaints,
4301                      _(".gdb_index entry has bad CU index"
4302                        " [in module %s]"),
4303                      objfile_name (dwarf2_per_objfile->objfile));
4304           continue;
4305         }
4306
4307       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4308
4309       /* Skip if already read in.  */
4310       if (per_cu->v.quick->compunit_symtab)
4311         continue;
4312
4313       /* Check static vs global.  */
4314       if (attrs_valid)
4315         {
4316           if (iter->want_specific_block
4317               && want_static != is_static)
4318             continue;
4319           /* Work around gold/15646.  */
4320           if (!is_static && iter->global_seen)
4321             continue;
4322           if (!is_static)
4323             iter->global_seen = 1;
4324         }
4325
4326       /* Only check the symbol's kind if it has one.  */
4327       if (attrs_valid)
4328         {
4329           switch (iter->domain)
4330             {
4331             case VAR_DOMAIN:
4332               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4333                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4334                   /* Some types are also in VAR_DOMAIN.  */
4335                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4336                 continue;
4337               break;
4338             case STRUCT_DOMAIN:
4339               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4340                 continue;
4341               break;
4342             case LABEL_DOMAIN:
4343               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4344                 continue;
4345               break;
4346             default:
4347               break;
4348             }
4349         }
4350
4351       ++iter->next;
4352       return per_cu;
4353     }
4354
4355   return NULL;
4356 }
4357
4358 static struct compunit_symtab *
4359 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4360                    const char *name, domain_enum domain)
4361 {
4362   struct compunit_symtab *stab_best = NULL;
4363   struct dwarf2_per_objfile *dwarf2_per_objfile
4364     = get_dwarf2_per_objfile (objfile);
4365
4366   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4367
4368   struct dw2_symtab_iterator iter;
4369   struct dwarf2_per_cu_data *per_cu;
4370
4371   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4372
4373   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4374     {
4375       struct symbol *sym, *with_opaque = NULL;
4376       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4377       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4378       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4379
4380       sym = block_find_symbol (block, name, domain,
4381                                block_find_non_opaque_type_preferred,
4382                                &with_opaque);
4383
4384       /* Some caution must be observed with overloaded functions
4385          and methods, since the index will not contain any overload
4386          information (but NAME might contain it).  */
4387
4388       if (sym != NULL
4389           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4390         return stab;
4391       if (with_opaque != NULL
4392           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4393         stab_best = stab;
4394
4395       /* Keep looking through other CUs.  */
4396     }
4397
4398   return stab_best;
4399 }
4400
4401 static void
4402 dw2_print_stats (struct objfile *objfile)
4403 {
4404   struct dwarf2_per_objfile *dwarf2_per_objfile
4405     = get_dwarf2_per_objfile (objfile);
4406   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4407   int count = 0;
4408
4409   for (int i = 0; i < total; ++i)
4410     {
4411       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4412
4413       if (!per_cu->v.quick->compunit_symtab)
4414         ++count;
4415     }
4416   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4417   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4418 }
4419
4420 /* This dumps minimal information about the index.
4421    It is called via "mt print objfiles".
4422    One use is to verify .gdb_index has been loaded by the
4423    gdb.dwarf2/gdb-index.exp testcase.  */
4424
4425 static void
4426 dw2_dump (struct objfile *objfile)
4427 {
4428   struct dwarf2_per_objfile *dwarf2_per_objfile
4429     = get_dwarf2_per_objfile (objfile);
4430
4431   gdb_assert (dwarf2_per_objfile->using_index);
4432   printf_filtered (".gdb_index:");
4433   if (dwarf2_per_objfile->index_table != NULL)
4434     {
4435       printf_filtered (" version %d\n",
4436                        dwarf2_per_objfile->index_table->version);
4437     }
4438   else
4439     printf_filtered (" faked for \"readnow\"\n");
4440   printf_filtered ("\n");
4441 }
4442
4443 static void
4444 dw2_relocate (struct objfile *objfile,
4445               const struct section_offsets *new_offsets,
4446               const struct section_offsets *delta)
4447 {
4448   /* There's nothing to relocate here.  */
4449 }
4450
4451 static void
4452 dw2_expand_symtabs_for_function (struct objfile *objfile,
4453                                  const char *func_name)
4454 {
4455   struct dwarf2_per_objfile *dwarf2_per_objfile
4456     = get_dwarf2_per_objfile (objfile);
4457
4458   struct dw2_symtab_iterator iter;
4459   struct dwarf2_per_cu_data *per_cu;
4460
4461   /* Note: It doesn't matter what we pass for block_index here.  */
4462   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4463                         func_name);
4464
4465   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4466     dw2_instantiate_symtab (per_cu);
4467
4468 }
4469
4470 static void
4471 dw2_expand_all_symtabs (struct objfile *objfile)
4472 {
4473   struct dwarf2_per_objfile *dwarf2_per_objfile
4474     = get_dwarf2_per_objfile (objfile);
4475   int total_units = (dwarf2_per_objfile->n_comp_units
4476                      + dwarf2_per_objfile->n_type_units);
4477
4478   for (int i = 0; i < total_units; ++i)
4479     {
4480       struct dwarf2_per_cu_data *per_cu
4481         = dw2_get_cutu (dwarf2_per_objfile, i);
4482
4483       dw2_instantiate_symtab (per_cu);
4484     }
4485 }
4486
4487 static void
4488 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4489                                   const char *fullname)
4490 {
4491   struct dwarf2_per_objfile *dwarf2_per_objfile
4492     = get_dwarf2_per_objfile (objfile);
4493
4494   /* We don't need to consider type units here.
4495      This is only called for examining code, e.g. expand_line_sal.
4496      There can be an order of magnitude (or more) more type units
4497      than comp units, and we avoid them if we can.  */
4498
4499   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4500     {
4501       int j;
4502       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4503       struct quick_file_names *file_data;
4504
4505       /* We only need to look at symtabs not already expanded.  */
4506       if (per_cu->v.quick->compunit_symtab)
4507         continue;
4508
4509       file_data = dw2_get_file_names (per_cu);
4510       if (file_data == NULL)
4511         continue;
4512
4513       for (j = 0; j < file_data->num_file_names; ++j)
4514         {
4515           const char *this_fullname = file_data->file_names[j];
4516
4517           if (filename_cmp (this_fullname, fullname) == 0)
4518             {
4519               dw2_instantiate_symtab (per_cu);
4520               break;
4521             }
4522         }
4523     }
4524 }
4525
4526 static void
4527 dw2_map_matching_symbols (struct objfile *objfile,
4528                           const char * name, domain_enum domain,
4529                           int global,
4530                           int (*callback) (struct block *,
4531                                            struct symbol *, void *),
4532                           void *data, symbol_name_match_type match,
4533                           symbol_compare_ftype *ordered_compare)
4534 {
4535   /* Currently unimplemented; used for Ada.  The function can be called if the
4536      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4537      does not look for non-Ada symbols this function should just return.  */
4538 }
4539
4540 /* Symbol name matcher for .gdb_index names.
4541
4542    Symbol names in .gdb_index have a few particularities:
4543
4544    - There's no indication of which is the language of each symbol.
4545
4546      Since each language has its own symbol name matching algorithm,
4547      and we don't know which language is the right one, we must match
4548      each symbol against all languages.  This would be a potential
4549      performance problem if it were not mitigated by the
4550      mapped_index::name_components lookup table, which significantly
4551      reduces the number of times we need to call into this matcher,
4552      making it a non-issue.
4553
4554    - Symbol names in the index have no overload (parameter)
4555      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4556      appear as "foo" in the index, for example.
4557
4558      This means that the lookup names passed to the symbol name
4559      matcher functions must have no parameter information either
4560      because (e.g.) symbol search name "foo" does not match
4561      lookup-name "foo(int)" [while swapping search name for lookup
4562      name would match].
4563 */
4564 class gdb_index_symbol_name_matcher
4565 {
4566 public:
4567   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4568   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4569
4570   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4571      Returns true if any matcher matches.  */
4572   bool matches (const char *symbol_name);
4573
4574 private:
4575   /* A reference to the lookup name we're matching against.  */
4576   const lookup_name_info &m_lookup_name;
4577
4578   /* A vector holding all the different symbol name matchers, for all
4579      languages.  */
4580   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4581 };
4582
4583 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4584   (const lookup_name_info &lookup_name)
4585     : m_lookup_name (lookup_name)
4586 {
4587   /* Prepare the vector of comparison functions upfront, to avoid
4588      doing the same work for each symbol.  Care is taken to avoid
4589      matching with the same matcher more than once if/when multiple
4590      languages use the same matcher function.  */
4591   auto &matchers = m_symbol_name_matcher_funcs;
4592   matchers.reserve (nr_languages);
4593
4594   matchers.push_back (default_symbol_name_matcher);
4595
4596   for (int i = 0; i < nr_languages; i++)
4597     {
4598       const language_defn *lang = language_def ((enum language) i);
4599       symbol_name_matcher_ftype *name_matcher
4600         = get_symbol_name_matcher (lang, m_lookup_name);
4601
4602       /* Don't insert the same comparison routine more than once.
4603          Note that we do this linear walk instead of a seemingly
4604          cheaper sorted insert, or use a std::set or something like
4605          that, because relative order of function addresses is not
4606          stable.  This is not a problem in practice because the number
4607          of supported languages is low, and the cost here is tiny
4608          compared to the number of searches we'll do afterwards using
4609          this object.  */
4610       if (name_matcher != default_symbol_name_matcher
4611           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4612               == matchers.end ()))
4613         matchers.push_back (name_matcher);
4614     }
4615 }
4616
4617 bool
4618 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4619 {
4620   for (auto matches_name : m_symbol_name_matcher_funcs)
4621     if (matches_name (symbol_name, m_lookup_name, NULL))
4622       return true;
4623
4624   return false;
4625 }
4626
4627 /* Starting from a search name, return the string that finds the upper
4628    bound of all strings that start with SEARCH_NAME in a sorted name
4629    list.  Returns the empty string to indicate that the upper bound is
4630    the end of the list.  */
4631
4632 static std::string
4633 make_sort_after_prefix_name (const char *search_name)
4634 {
4635   /* When looking to complete "func", we find the upper bound of all
4636      symbols that start with "func" by looking for where we'd insert
4637      the closest string that would follow "func" in lexicographical
4638      order.  Usually, that's "func"-with-last-character-incremented,
4639      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4640      will be UTF-8 multi-byte sequences, but we can't be certain.
4641      Especially mind the 0xff character, which is a valid character in
4642      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4643      rule out compilers allowing it in identifiers.  Note that
4644      conveniently, strcmp/strcasecmp are specified to compare
4645      characters interpreted as unsigned char.  So what we do is treat
4646      the whole string as a base 256 number composed of a sequence of
4647      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4648      to 0, and carries 1 to the following more-significant position.
4649      If the very first character in SEARCH_NAME ends up incremented
4650      and carries/overflows, then the upper bound is the end of the
4651      list.  The string after the empty string is also the empty
4652      string.
4653
4654      Some examples of this operation:
4655
4656        SEARCH_NAME  => "+1" RESULT
4657
4658        "abc"              => "abd"
4659        "ab\xff"           => "ac"
4660        "\xff" "a" "\xff"  => "\xff" "b"
4661        "\xff"             => ""
4662        "\xff\xff"         => ""
4663        ""                 => ""
4664
4665      Then, with these symbols for example:
4666
4667       func
4668       func1
4669       fund
4670
4671      completing "func" looks for symbols between "func" and
4672      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4673      which finds "func" and "func1", but not "fund".
4674
4675      And with:
4676
4677       funcÿ     (Latin1 'ÿ' [0xff])
4678       funcÿ1
4679       fund
4680
4681      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4682      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4683
4684      And with:
4685
4686       ÿÿ        (Latin1 'ÿ' [0xff])
4687       ÿÿ1
4688
4689      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4690      the end of the list.
4691   */
4692   std::string after = search_name;
4693   while (!after.empty () && (unsigned char) after.back () == 0xff)
4694     after.pop_back ();
4695   if (!after.empty ())
4696     after.back () = (unsigned char) after.back () + 1;
4697   return after;
4698 }
4699
4700 /* See declaration.  */
4701
4702 std::pair<std::vector<name_component>::const_iterator,
4703           std::vector<name_component>::const_iterator>
4704 mapped_index_base::find_name_components_bounds
4705   (const lookup_name_info &lookup_name_without_params) const
4706 {
4707   auto *name_cmp
4708     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4709
4710   const char *cplus
4711     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4712
4713   /* Comparison function object for lower_bound that matches against a
4714      given symbol name.  */
4715   auto lookup_compare_lower = [&] (const name_component &elem,
4716                                    const char *name)
4717     {
4718       const char *elem_qualified = this->symbol_name_at (elem.idx);
4719       const char *elem_name = elem_qualified + elem.name_offset;
4720       return name_cmp (elem_name, name) < 0;
4721     };
4722
4723   /* Comparison function object for upper_bound that matches against a
4724      given symbol name.  */
4725   auto lookup_compare_upper = [&] (const char *name,
4726                                    const name_component &elem)
4727     {
4728       const char *elem_qualified = this->symbol_name_at (elem.idx);
4729       const char *elem_name = elem_qualified + elem.name_offset;
4730       return name_cmp (name, elem_name) < 0;
4731     };
4732
4733   auto begin = this->name_components.begin ();
4734   auto end = this->name_components.end ();
4735
4736   /* Find the lower bound.  */
4737   auto lower = [&] ()
4738     {
4739       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4740         return begin;
4741       else
4742         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4743     } ();
4744
4745   /* Find the upper bound.  */
4746   auto upper = [&] ()
4747     {
4748       if (lookup_name_without_params.completion_mode ())
4749         {
4750           /* In completion mode, we want UPPER to point past all
4751              symbols names that have the same prefix.  I.e., with
4752              these symbols, and completing "func":
4753
4754               function        << lower bound
4755               function1
4756               other_function  << upper bound
4757
4758              We find the upper bound by looking for the insertion
4759              point of "func"-with-last-character-incremented,
4760              i.e. "fund".  */
4761           std::string after = make_sort_after_prefix_name (cplus);
4762           if (after.empty ())
4763             return end;
4764           return std::lower_bound (lower, end, after.c_str (),
4765                                    lookup_compare_lower);
4766         }
4767       else
4768         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4769     } ();
4770
4771   return {lower, upper};
4772 }
4773
4774 /* See declaration.  */
4775
4776 void
4777 mapped_index_base::build_name_components ()
4778 {
4779   if (!this->name_components.empty ())
4780     return;
4781
4782   this->name_components_casing = case_sensitivity;
4783   auto *name_cmp
4784     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4785
4786   /* The code below only knows how to break apart components of C++
4787      symbol names (and other languages that use '::' as
4788      namespace/module separator).  If we add support for wild matching
4789      to some language that uses some other operator (E.g., Ada, Go and
4790      D use '.'), then we'll need to try splitting the symbol name
4791      according to that language too.  Note that Ada does support wild
4792      matching, but doesn't currently support .gdb_index.  */
4793   auto count = this->symbol_name_count ();
4794   for (offset_type idx = 0; idx < count; idx++)
4795     {
4796       if (this->symbol_name_slot_invalid (idx))
4797         continue;
4798
4799       const char *name = this->symbol_name_at (idx);
4800
4801       /* Add each name component to the name component table.  */
4802       unsigned int previous_len = 0;
4803       for (unsigned int current_len = cp_find_first_component (name);
4804            name[current_len] != '\0';
4805            current_len += cp_find_first_component (name + current_len))
4806         {
4807           gdb_assert (name[current_len] == ':');
4808           this->name_components.push_back ({previous_len, idx});
4809           /* Skip the '::'.  */
4810           current_len += 2;
4811           previous_len = current_len;
4812         }
4813       this->name_components.push_back ({previous_len, idx});
4814     }
4815
4816   /* Sort name_components elements by name.  */
4817   auto name_comp_compare = [&] (const name_component &left,
4818                                 const name_component &right)
4819     {
4820       const char *left_qualified = this->symbol_name_at (left.idx);
4821       const char *right_qualified = this->symbol_name_at (right.idx);
4822
4823       const char *left_name = left_qualified + left.name_offset;
4824       const char *right_name = right_qualified + right.name_offset;
4825
4826       return name_cmp (left_name, right_name) < 0;
4827     };
4828
4829   std::sort (this->name_components.begin (),
4830              this->name_components.end (),
4831              name_comp_compare);
4832 }
4833
4834 /* Helper for dw2_expand_symtabs_matching that works with a
4835    mapped_index_base instead of the containing objfile.  This is split
4836    to a separate function in order to be able to unit test the
4837    name_components matching using a mock mapped_index_base.  For each
4838    symbol name that matches, calls MATCH_CALLBACK, passing it the
4839    symbol's index in the mapped_index_base symbol table.  */
4840
4841 static void
4842 dw2_expand_symtabs_matching_symbol
4843   (mapped_index_base &index,
4844    const lookup_name_info &lookup_name_in,
4845    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4846    enum search_domain kind,
4847    gdb::function_view<void (offset_type)> match_callback)
4848 {
4849   lookup_name_info lookup_name_without_params
4850     = lookup_name_in.make_ignore_params ();
4851   gdb_index_symbol_name_matcher lookup_name_matcher
4852     (lookup_name_without_params);
4853
4854   /* Build the symbol name component sorted vector, if we haven't
4855      yet.  */
4856   index.build_name_components ();
4857
4858   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4859
4860   /* Now for each symbol name in range, check to see if we have a name
4861      match, and if so, call the MATCH_CALLBACK callback.  */
4862
4863   /* The same symbol may appear more than once in the range though.
4864      E.g., if we're looking for symbols that complete "w", and we have
4865      a symbol named "w1::w2", we'll find the two name components for
4866      that same symbol in the range.  To be sure we only call the
4867      callback once per symbol, we first collect the symbol name
4868      indexes that matched in a temporary vector and ignore
4869      duplicates.  */
4870   std::vector<offset_type> matches;
4871   matches.reserve (std::distance (bounds.first, bounds.second));
4872
4873   for (; bounds.first != bounds.second; ++bounds.first)
4874     {
4875       const char *qualified = index.symbol_name_at (bounds.first->idx);
4876
4877       if (!lookup_name_matcher.matches (qualified)
4878           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4879         continue;
4880
4881       matches.push_back (bounds.first->idx);
4882     }
4883
4884   std::sort (matches.begin (), matches.end ());
4885
4886   /* Finally call the callback, once per match.  */
4887   ULONGEST prev = -1;
4888   for (offset_type idx : matches)
4889     {
4890       if (prev != idx)
4891         {
4892           match_callback (idx);
4893           prev = idx;
4894         }
4895     }
4896
4897   /* Above we use a type wider than idx's for 'prev', since 0 and
4898      (offset_type)-1 are both possible values.  */
4899   static_assert (sizeof (prev) > sizeof (offset_type), "");
4900 }
4901
4902 #if GDB_SELF_TEST
4903
4904 namespace selftests { namespace dw2_expand_symtabs_matching {
4905
4906 /* A mock .gdb_index/.debug_names-like name index table, enough to
4907    exercise dw2_expand_symtabs_matching_symbol, which works with the
4908    mapped_index_base interface.  Builds an index from the symbol list
4909    passed as parameter to the constructor.  */
4910 class mock_mapped_index : public mapped_index_base
4911 {
4912 public:
4913   mock_mapped_index (gdb::array_view<const char *> symbols)
4914     : m_symbol_table (symbols)
4915   {}
4916
4917   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4918
4919   /* Return the number of names in the symbol table.  */
4920   virtual size_t symbol_name_count () const
4921   {
4922     return m_symbol_table.size ();
4923   }
4924
4925   /* Get the name of the symbol at IDX in the symbol table.  */
4926   virtual const char *symbol_name_at (offset_type idx) const
4927   {
4928     return m_symbol_table[idx];
4929   }
4930
4931 private:
4932   gdb::array_view<const char *> m_symbol_table;
4933 };
4934
4935 /* Convenience function that converts a NULL pointer to a "<null>"
4936    string, to pass to print routines.  */
4937
4938 static const char *
4939 string_or_null (const char *str)
4940 {
4941   return str != NULL ? str : "<null>";
4942 }
4943
4944 /* Check if a lookup_name_info built from
4945    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4946    index.  EXPECTED_LIST is the list of expected matches, in expected
4947    matching order.  If no match expected, then an empty list is
4948    specified.  Returns true on success.  On failure prints a warning
4949    indicating the file:line that failed, and returns false.  */
4950
4951 static bool
4952 check_match (const char *file, int line,
4953              mock_mapped_index &mock_index,
4954              const char *name, symbol_name_match_type match_type,
4955              bool completion_mode,
4956              std::initializer_list<const char *> expected_list)
4957 {
4958   lookup_name_info lookup_name (name, match_type, completion_mode);
4959
4960   bool matched = true;
4961
4962   auto mismatch = [&] (const char *expected_str,
4963                        const char *got)
4964   {
4965     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4966                "expected=\"%s\", got=\"%s\"\n"),
4967              file, line,
4968              (match_type == symbol_name_match_type::FULL
4969               ? "FULL" : "WILD"),
4970              name, string_or_null (expected_str), string_or_null (got));
4971     matched = false;
4972   };
4973
4974   auto expected_it = expected_list.begin ();
4975   auto expected_end = expected_list.end ();
4976
4977   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4978                                       NULL, ALL_DOMAIN,
4979                                       [&] (offset_type idx)
4980   {
4981     const char *matched_name = mock_index.symbol_name_at (idx);
4982     const char *expected_str
4983       = expected_it == expected_end ? NULL : *expected_it++;
4984
4985     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4986       mismatch (expected_str, matched_name);
4987   });
4988
4989   const char *expected_str
4990   = expected_it == expected_end ? NULL : *expected_it++;
4991   if (expected_str != NULL)
4992     mismatch (expected_str, NULL);
4993
4994   return matched;
4995 }
4996
4997 /* The symbols added to the mock mapped_index for testing (in
4998    canonical form).  */
4999 static const char *test_symbols[] = {
5000   "function",
5001   "std::bar",
5002   "std::zfunction",
5003   "std::zfunction2",
5004   "w1::w2",
5005   "ns::foo<char*>",
5006   "ns::foo<int>",
5007   "ns::foo<long>",
5008   "ns2::tmpl<int>::foo2",
5009   "(anonymous namespace)::A::B::C",
5010
5011   /* These are used to check that the increment-last-char in the
5012      matching algorithm for completion doesn't match "t1_fund" when
5013      completing "t1_func".  */
5014   "t1_func",
5015   "t1_func1",
5016   "t1_fund",
5017   "t1_fund1",
5018
5019   /* A UTF-8 name with multi-byte sequences to make sure that
5020      cp-name-parser understands this as a single identifier ("função"
5021      is "function" in PT).  */
5022   u8"u8função",
5023
5024   /* \377 (0xff) is Latin1 'ÿ'.  */
5025   "yfunc\377",
5026
5027   /* \377 (0xff) is Latin1 'ÿ'.  */
5028   "\377",
5029   "\377\377123",
5030
5031   /* A name with all sorts of complications.  Starts with "z" to make
5032      it easier for the completion tests below.  */
5033 #define Z_SYM_NAME \
5034   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5035     "::tuple<(anonymous namespace)::ui*, " \
5036     "std::default_delete<(anonymous namespace)::ui>, void>"
5037
5038   Z_SYM_NAME
5039 };
5040
5041 /* Returns true if the mapped_index_base::find_name_component_bounds
5042    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5043    in completion mode.  */
5044
5045 static bool
5046 check_find_bounds_finds (mapped_index_base &index,
5047                          const char *search_name,
5048                          gdb::array_view<const char *> expected_syms)
5049 {
5050   lookup_name_info lookup_name (search_name,
5051                                 symbol_name_match_type::FULL, true);
5052
5053   auto bounds = index.find_name_components_bounds (lookup_name);
5054
5055   size_t distance = std::distance (bounds.first, bounds.second);
5056   if (distance != expected_syms.size ())
5057     return false;
5058
5059   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5060     {
5061       auto nc_elem = bounds.first + exp_elem;
5062       const char *qualified = index.symbol_name_at (nc_elem->idx);
5063       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5064         return false;
5065     }
5066
5067   return true;
5068 }
5069
5070 /* Test the lower-level mapped_index::find_name_component_bounds
5071    method.  */
5072
5073 static void
5074 test_mapped_index_find_name_component_bounds ()
5075 {
5076   mock_mapped_index mock_index (test_symbols);
5077
5078   mock_index.build_name_components ();
5079
5080   /* Test the lower-level mapped_index::find_name_component_bounds
5081      method in completion mode.  */
5082   {
5083     static const char *expected_syms[] = {
5084       "t1_func",
5085       "t1_func1",
5086     };
5087
5088     SELF_CHECK (check_find_bounds_finds (mock_index,
5089                                          "t1_func", expected_syms));
5090   }
5091
5092   /* Check that the increment-last-char in the name matching algorithm
5093      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5094   {
5095     static const char *expected_syms1[] = {
5096       "\377",
5097       "\377\377123",
5098     };
5099     SELF_CHECK (check_find_bounds_finds (mock_index,
5100                                          "\377", expected_syms1));
5101
5102     static const char *expected_syms2[] = {
5103       "\377\377123",
5104     };
5105     SELF_CHECK (check_find_bounds_finds (mock_index,
5106                                          "\377\377", expected_syms2));
5107   }
5108 }
5109
5110 /* Test dw2_expand_symtabs_matching_symbol.  */
5111
5112 static void
5113 test_dw2_expand_symtabs_matching_symbol ()
5114 {
5115   mock_mapped_index mock_index (test_symbols);
5116
5117   /* We let all tests run until the end even if some fails, for debug
5118      convenience.  */
5119   bool any_mismatch = false;
5120
5121   /* Create the expected symbols list (an initializer_list).  Needed
5122      because lists have commas, and we need to pass them to CHECK,
5123      which is a macro.  */
5124 #define EXPECT(...) { __VA_ARGS__ }
5125
5126   /* Wrapper for check_match that passes down the current
5127      __FILE__/__LINE__.  */
5128 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5129   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5130                                 mock_index,                             \
5131                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5132                                 EXPECTED_LIST)
5133
5134   /* Identity checks.  */
5135   for (const char *sym : test_symbols)
5136     {
5137       /* Should be able to match all existing symbols.  */
5138       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5139                    EXPECT (sym));
5140
5141       /* Should be able to match all existing symbols with
5142          parameters.  */
5143       std::string with_params = std::string (sym) + "(int)";
5144       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5145                    EXPECT (sym));
5146
5147       /* Should be able to match all existing symbols with
5148          parameters and qualifiers.  */
5149       with_params = std::string (sym) + " ( int ) const";
5150       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5151                    EXPECT (sym));
5152
5153       /* This should really find sym, but cp-name-parser.y doesn't
5154          know about lvalue/rvalue qualifiers yet.  */
5155       with_params = std::string (sym) + " ( int ) &&";
5156       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5157                    {});
5158     }
5159
5160   /* Check that the name matching algorithm for completion doesn't get
5161      confused with Latin1 'ÿ' / 0xff.  */
5162   {
5163     static const char str[] = "\377";
5164     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5165                  EXPECT ("\377", "\377\377123"));
5166   }
5167
5168   /* Check that the increment-last-char in the matching algorithm for
5169      completion doesn't match "t1_fund" when completing "t1_func".  */
5170   {
5171     static const char str[] = "t1_func";
5172     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5173                  EXPECT ("t1_func", "t1_func1"));
5174   }
5175
5176   /* Check that completion mode works at each prefix of the expected
5177      symbol name.  */
5178   {
5179     static const char str[] = "function(int)";
5180     size_t len = strlen (str);
5181     std::string lookup;
5182
5183     for (size_t i = 1; i < len; i++)
5184       {
5185         lookup.assign (str, i);
5186         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5187                      EXPECT ("function"));
5188       }
5189   }
5190
5191   /* While "w" is a prefix of both components, the match function
5192      should still only be called once.  */
5193   {
5194     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5195                  EXPECT ("w1::w2"));
5196     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5197                  EXPECT ("w1::w2"));
5198   }
5199
5200   /* Same, with a "complicated" symbol.  */
5201   {
5202     static const char str[] = Z_SYM_NAME;
5203     size_t len = strlen (str);
5204     std::string lookup;
5205
5206     for (size_t i = 1; i < len; i++)
5207       {
5208         lookup.assign (str, i);
5209         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5210                      EXPECT (Z_SYM_NAME));
5211       }
5212   }
5213
5214   /* In FULL mode, an incomplete symbol doesn't match.  */
5215   {
5216     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5217                  {});
5218   }
5219
5220   /* A complete symbol with parameters matches any overload, since the
5221      index has no overload info.  */
5222   {
5223     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5224                  EXPECT ("std::zfunction", "std::zfunction2"));
5225     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5226                  EXPECT ("std::zfunction", "std::zfunction2"));
5227     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5228                  EXPECT ("std::zfunction", "std::zfunction2"));
5229   }
5230
5231   /* Check that whitespace is ignored appropriately.  A symbol with a
5232      template argument list. */
5233   {
5234     static const char expected[] = "ns::foo<int>";
5235     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5236                  EXPECT (expected));
5237     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5238                  EXPECT (expected));
5239   }
5240
5241   /* Check that whitespace is ignored appropriately.  A symbol with a
5242      template argument list that includes a pointer.  */
5243   {
5244     static const char expected[] = "ns::foo<char*>";
5245     /* Try both completion and non-completion modes.  */
5246     static const bool completion_mode[2] = {false, true};
5247     for (size_t i = 0; i < 2; i++)
5248       {
5249         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5250                      completion_mode[i], EXPECT (expected));
5251         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5252                      completion_mode[i], EXPECT (expected));
5253
5254         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5255                      completion_mode[i], EXPECT (expected));
5256         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5257                      completion_mode[i], EXPECT (expected));
5258       }
5259   }
5260
5261   {
5262     /* Check method qualifiers are ignored.  */
5263     static const char expected[] = "ns::foo<char*>";
5264     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5265                  symbol_name_match_type::FULL, true, EXPECT (expected));
5266     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5267                  symbol_name_match_type::FULL, true, EXPECT (expected));
5268     CHECK_MATCH ("foo < char * >  ( int ) const",
5269                  symbol_name_match_type::WILD, true, EXPECT (expected));
5270     CHECK_MATCH ("foo < char * >  ( int ) &&",
5271                  symbol_name_match_type::WILD, true, EXPECT (expected));
5272   }
5273
5274   /* Test lookup names that don't match anything.  */
5275   {
5276     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5277                  {});
5278
5279     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5280                  {});
5281   }
5282
5283   /* Some wild matching tests, exercising "(anonymous namespace)",
5284      which should not be confused with a parameter list.  */
5285   {
5286     static const char *syms[] = {
5287       "A::B::C",
5288       "B::C",
5289       "C",
5290       "A :: B :: C ( int )",
5291       "B :: C ( int )",
5292       "C ( int )",
5293     };
5294
5295     for (const char *s : syms)
5296       {
5297         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5298                      EXPECT ("(anonymous namespace)::A::B::C"));
5299       }
5300   }
5301
5302   {
5303     static const char expected[] = "ns2::tmpl<int>::foo2";
5304     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5305                  EXPECT (expected));
5306     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5307                  EXPECT (expected));
5308   }
5309
5310   SELF_CHECK (!any_mismatch);
5311
5312 #undef EXPECT
5313 #undef CHECK_MATCH
5314 }
5315
5316 static void
5317 run_test ()
5318 {
5319   test_mapped_index_find_name_component_bounds ();
5320   test_dw2_expand_symtabs_matching_symbol ();
5321 }
5322
5323 }} // namespace selftests::dw2_expand_symtabs_matching
5324
5325 #endif /* GDB_SELF_TEST */
5326
5327 /* If FILE_MATCHER is NULL or if PER_CU has
5328    dwarf2_per_cu_quick_data::MARK set (see
5329    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5330    EXPANSION_NOTIFY on it.  */
5331
5332 static void
5333 dw2_expand_symtabs_matching_one
5334   (struct dwarf2_per_cu_data *per_cu,
5335    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5336    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5337 {
5338   if (file_matcher == NULL || per_cu->v.quick->mark)
5339     {
5340       bool symtab_was_null
5341         = (per_cu->v.quick->compunit_symtab == NULL);
5342
5343       dw2_instantiate_symtab (per_cu);
5344
5345       if (expansion_notify != NULL
5346           && symtab_was_null
5347           && per_cu->v.quick->compunit_symtab != NULL)
5348         expansion_notify (per_cu->v.quick->compunit_symtab);
5349     }
5350 }
5351
5352 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5353    matched, to expand corresponding CUs that were marked.  IDX is the
5354    index of the symbol name that matched.  */
5355
5356 static void
5357 dw2_expand_marked_cus
5358   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5359    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5360    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5361    search_domain kind)
5362 {
5363   offset_type *vec, vec_len, vec_idx;
5364   bool global_seen = false;
5365   mapped_index &index = *dwarf2_per_objfile->index_table;
5366
5367   vec = (offset_type *) (index.constant_pool
5368                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5369   vec_len = MAYBE_SWAP (vec[0]);
5370   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5371     {
5372       struct dwarf2_per_cu_data *per_cu;
5373       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5374       /* This value is only valid for index versions >= 7.  */
5375       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5376       gdb_index_symbol_kind symbol_kind =
5377         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5378       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5379       /* Only check the symbol attributes if they're present.
5380          Indices prior to version 7 don't record them,
5381          and indices >= 7 may elide them for certain symbols
5382          (gold does this).  */
5383       int attrs_valid =
5384         (index.version >= 7
5385          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5386
5387       /* Work around gold/15646.  */
5388       if (attrs_valid)
5389         {
5390           if (!is_static && global_seen)
5391             continue;
5392           if (!is_static)
5393             global_seen = true;
5394         }
5395
5396       /* Only check the symbol's kind if it has one.  */
5397       if (attrs_valid)
5398         {
5399           switch (kind)
5400             {
5401             case VARIABLES_DOMAIN:
5402               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5403                 continue;
5404               break;
5405             case FUNCTIONS_DOMAIN:
5406               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5407                 continue;
5408               break;
5409             case TYPES_DOMAIN:
5410               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5411                 continue;
5412               break;
5413             default:
5414               break;
5415             }
5416         }
5417
5418       /* Don't crash on bad data.  */
5419       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5420                        + dwarf2_per_objfile->n_type_units))
5421         {
5422           complaint (&symfile_complaints,
5423                      _(".gdb_index entry has bad CU index"
5424                        " [in module %s]"),
5425                        objfile_name (dwarf2_per_objfile->objfile));
5426           continue;
5427         }
5428
5429       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5430       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5431                                        expansion_notify);
5432     }
5433 }
5434
5435 /* If FILE_MATCHER is non-NULL, set all the
5436    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5437    that match FILE_MATCHER.  */
5438
5439 static void
5440 dw_expand_symtabs_matching_file_matcher
5441   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5442    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5443 {
5444   if (file_matcher == NULL)
5445     return;
5446
5447   objfile *const objfile = dwarf2_per_objfile->objfile;
5448
5449   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5450                                             htab_eq_pointer,
5451                                             NULL, xcalloc, xfree));
5452   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5453                                                 htab_eq_pointer,
5454                                                 NULL, xcalloc, xfree));
5455
5456   /* The rule is CUs specify all the files, including those used by
5457      any TU, so there's no need to scan TUs here.  */
5458
5459   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5460     {
5461       int j;
5462       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5463       struct quick_file_names *file_data;
5464       void **slot;
5465
5466       QUIT;
5467
5468       per_cu->v.quick->mark = 0;
5469
5470       /* We only need to look at symtabs not already expanded.  */
5471       if (per_cu->v.quick->compunit_symtab)
5472         continue;
5473
5474       file_data = dw2_get_file_names (per_cu);
5475       if (file_data == NULL)
5476         continue;
5477
5478       if (htab_find (visited_not_found.get (), file_data) != NULL)
5479         continue;
5480       else if (htab_find (visited_found.get (), file_data) != NULL)
5481         {
5482           per_cu->v.quick->mark = 1;
5483           continue;
5484         }
5485
5486       for (j = 0; j < file_data->num_file_names; ++j)
5487         {
5488           const char *this_real_name;
5489
5490           if (file_matcher (file_data->file_names[j], false))
5491             {
5492               per_cu->v.quick->mark = 1;
5493               break;
5494             }
5495
5496           /* Before we invoke realpath, which can get expensive when many
5497              files are involved, do a quick comparison of the basenames.  */
5498           if (!basenames_may_differ
5499               && !file_matcher (lbasename (file_data->file_names[j]),
5500                                 true))
5501             continue;
5502
5503           this_real_name = dw2_get_real_path (objfile, file_data, j);
5504           if (file_matcher (this_real_name, false))
5505             {
5506               per_cu->v.quick->mark = 1;
5507               break;
5508             }
5509         }
5510
5511       slot = htab_find_slot (per_cu->v.quick->mark
5512                              ? visited_found.get ()
5513                              : visited_not_found.get (),
5514                              file_data, INSERT);
5515       *slot = file_data;
5516     }
5517 }
5518
5519 static void
5520 dw2_expand_symtabs_matching
5521   (struct objfile *objfile,
5522    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5523    const lookup_name_info &lookup_name,
5524    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5525    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5526    enum search_domain kind)
5527 {
5528   struct dwarf2_per_objfile *dwarf2_per_objfile
5529     = get_dwarf2_per_objfile (objfile);
5530
5531   /* index_table is NULL if OBJF_READNOW.  */
5532   if (!dwarf2_per_objfile->index_table)
5533     return;
5534
5535   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5536
5537   mapped_index &index = *dwarf2_per_objfile->index_table;
5538
5539   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5540                                       symbol_matcher,
5541                                       kind, [&] (offset_type idx)
5542     {
5543       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5544                              expansion_notify, kind);
5545     });
5546 }
5547
5548 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5549    symtab.  */
5550
5551 static struct compunit_symtab *
5552 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5553                                           CORE_ADDR pc)
5554 {
5555   int i;
5556
5557   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5558       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5559     return cust;
5560
5561   if (cust->includes == NULL)
5562     return NULL;
5563
5564   for (i = 0; cust->includes[i]; ++i)
5565     {
5566       struct compunit_symtab *s = cust->includes[i];
5567
5568       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5569       if (s != NULL)
5570         return s;
5571     }
5572
5573   return NULL;
5574 }
5575
5576 static struct compunit_symtab *
5577 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5578                                   struct bound_minimal_symbol msymbol,
5579                                   CORE_ADDR pc,
5580                                   struct obj_section *section,
5581                                   int warn_if_readin)
5582 {
5583   struct dwarf2_per_cu_data *data;
5584   struct compunit_symtab *result;
5585
5586   if (!objfile->psymtabs_addrmap)
5587     return NULL;
5588
5589   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5590                                                      pc);
5591   if (!data)
5592     return NULL;
5593
5594   if (warn_if_readin && data->v.quick->compunit_symtab)
5595     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5596              paddress (get_objfile_arch (objfile), pc));
5597
5598   result
5599     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5600                                                 pc);
5601   gdb_assert (result != NULL);
5602   return result;
5603 }
5604
5605 static void
5606 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5607                           void *data, int need_fullname)
5608 {
5609   struct dwarf2_per_objfile *dwarf2_per_objfile
5610     = get_dwarf2_per_objfile (objfile);
5611
5612   if (!dwarf2_per_objfile->filenames_cache)
5613     {
5614       dwarf2_per_objfile->filenames_cache.emplace ();
5615
5616       htab_up visited (htab_create_alloc (10,
5617                                           htab_hash_pointer, htab_eq_pointer,
5618                                           NULL, xcalloc, xfree));
5619
5620       /* The rule is CUs specify all the files, including those used
5621          by any TU, so there's no need to scan TUs here.  We can
5622          ignore file names coming from already-expanded CUs.  */
5623
5624       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5625         {
5626           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5627
5628           if (per_cu->v.quick->compunit_symtab)
5629             {
5630               void **slot = htab_find_slot (visited.get (),
5631                                             per_cu->v.quick->file_names,
5632                                             INSERT);
5633
5634               *slot = per_cu->v.quick->file_names;
5635             }
5636         }
5637
5638       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5639         {
5640           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5641           struct quick_file_names *file_data;
5642           void **slot;
5643
5644           /* We only need to look at symtabs not already expanded.  */
5645           if (per_cu->v.quick->compunit_symtab)
5646             continue;
5647
5648           file_data = dw2_get_file_names (per_cu);
5649           if (file_data == NULL)
5650             continue;
5651
5652           slot = htab_find_slot (visited.get (), file_data, INSERT);
5653           if (*slot)
5654             {
5655               /* Already visited.  */
5656               continue;
5657             }
5658           *slot = file_data;
5659
5660           for (int j = 0; j < file_data->num_file_names; ++j)
5661             {
5662               const char *filename = file_data->file_names[j];
5663               dwarf2_per_objfile->filenames_cache->seen (filename);
5664             }
5665         }
5666     }
5667
5668   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5669     {
5670       gdb::unique_xmalloc_ptr<char> this_real_name;
5671
5672       if (need_fullname)
5673         this_real_name = gdb_realpath (filename);
5674       (*fun) (filename, this_real_name.get (), data);
5675     });
5676 }
5677
5678 static int
5679 dw2_has_symbols (struct objfile *objfile)
5680 {
5681   return 1;
5682 }
5683
5684 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5685 {
5686   dw2_has_symbols,
5687   dw2_find_last_source_symtab,
5688   dw2_forget_cached_source_info,
5689   dw2_map_symtabs_matching_filename,
5690   dw2_lookup_symbol,
5691   dw2_print_stats,
5692   dw2_dump,
5693   dw2_relocate,
5694   dw2_expand_symtabs_for_function,
5695   dw2_expand_all_symtabs,
5696   dw2_expand_symtabs_with_fullname,
5697   dw2_map_matching_symbols,
5698   dw2_expand_symtabs_matching,
5699   dw2_find_pc_sect_compunit_symtab,
5700   NULL,
5701   dw2_map_symbol_filenames
5702 };
5703
5704 /* DWARF-5 debug_names reader.  */
5705
5706 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5707 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5708
5709 /* A helper function that reads the .debug_names section in SECTION
5710    and fills in MAP.  FILENAME is the name of the file containing the
5711    section; it is used for error reporting.
5712
5713    Returns true if all went well, false otherwise.  */
5714
5715 static bool
5716 read_debug_names_from_section (struct objfile *objfile,
5717                                const char *filename,
5718                                struct dwarf2_section_info *section,
5719                                mapped_debug_names &map)
5720 {
5721   if (dwarf2_section_empty_p (section))
5722     return false;
5723
5724   /* Older elfutils strip versions could keep the section in the main
5725      executable while splitting it for the separate debug info file.  */
5726   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5727     return false;
5728
5729   dwarf2_read_section (objfile, section);
5730
5731   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5732
5733   const gdb_byte *addr = section->buffer;
5734
5735   bfd *const abfd = get_section_bfd_owner (section);
5736
5737   unsigned int bytes_read;
5738   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5739   addr += bytes_read;
5740
5741   map.dwarf5_is_dwarf64 = bytes_read != 4;
5742   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5743   if (bytes_read + length != section->size)
5744     {
5745       /* There may be multiple per-CU indices.  */
5746       warning (_("Section .debug_names in %s length %s does not match "
5747                  "section length %s, ignoring .debug_names."),
5748                filename, plongest (bytes_read + length),
5749                pulongest (section->size));
5750       return false;
5751     }
5752
5753   /* The version number.  */
5754   uint16_t version = read_2_bytes (abfd, addr);
5755   addr += 2;
5756   if (version != 5)
5757     {
5758       warning (_("Section .debug_names in %s has unsupported version %d, "
5759                  "ignoring .debug_names."),
5760                filename, version);
5761       return false;
5762     }
5763
5764   /* Padding.  */
5765   uint16_t padding = read_2_bytes (abfd, addr);
5766   addr += 2;
5767   if (padding != 0)
5768     {
5769       warning (_("Section .debug_names in %s has unsupported padding %d, "
5770                  "ignoring .debug_names."),
5771                filename, padding);
5772       return false;
5773     }
5774
5775   /* comp_unit_count - The number of CUs in the CU list.  */
5776   map.cu_count = read_4_bytes (abfd, addr);
5777   addr += 4;
5778
5779   /* local_type_unit_count - The number of TUs in the local TU
5780      list.  */
5781   map.tu_count = read_4_bytes (abfd, addr);
5782   addr += 4;
5783
5784   /* foreign_type_unit_count - The number of TUs in the foreign TU
5785      list.  */
5786   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5787   addr += 4;
5788   if (foreign_tu_count != 0)
5789     {
5790       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5791                  "ignoring .debug_names."),
5792                filename, static_cast<unsigned long> (foreign_tu_count));
5793       return false;
5794     }
5795
5796   /* bucket_count - The number of hash buckets in the hash lookup
5797      table.  */
5798   map.bucket_count = read_4_bytes (abfd, addr);
5799   addr += 4;
5800
5801   /* name_count - The number of unique names in the index.  */
5802   map.name_count = read_4_bytes (abfd, addr);
5803   addr += 4;
5804
5805   /* abbrev_table_size - The size in bytes of the abbreviations
5806      table.  */
5807   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5808   addr += 4;
5809
5810   /* augmentation_string_size - The size in bytes of the augmentation
5811      string.  This value is rounded up to a multiple of 4.  */
5812   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5813   addr += 4;
5814   map.augmentation_is_gdb = ((augmentation_string_size
5815                               == sizeof (dwarf5_augmentation))
5816                              && memcmp (addr, dwarf5_augmentation,
5817                                         sizeof (dwarf5_augmentation)) == 0);
5818   augmentation_string_size += (-augmentation_string_size) & 3;
5819   addr += augmentation_string_size;
5820
5821   /* List of CUs */
5822   map.cu_table_reordered = addr;
5823   addr += map.cu_count * map.offset_size;
5824
5825   /* List of Local TUs */
5826   map.tu_table_reordered = addr;
5827   addr += map.tu_count * map.offset_size;
5828
5829   /* Hash Lookup Table */
5830   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5831   addr += map.bucket_count * 4;
5832   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5833   addr += map.name_count * 4;
5834
5835   /* Name Table */
5836   map.name_table_string_offs_reordered = addr;
5837   addr += map.name_count * map.offset_size;
5838   map.name_table_entry_offs_reordered = addr;
5839   addr += map.name_count * map.offset_size;
5840
5841   const gdb_byte *abbrev_table_start = addr;
5842   for (;;)
5843     {
5844       unsigned int bytes_read;
5845       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5846       addr += bytes_read;
5847       if (index_num == 0)
5848         break;
5849
5850       const auto insertpair
5851         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5852       if (!insertpair.second)
5853         {
5854           warning (_("Section .debug_names in %s has duplicate index %s, "
5855                      "ignoring .debug_names."),
5856                    filename, pulongest (index_num));
5857           return false;
5858         }
5859       mapped_debug_names::index_val &indexval = insertpair.first->second;
5860       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5861       addr += bytes_read;
5862
5863       for (;;)
5864         {
5865           mapped_debug_names::index_val::attr attr;
5866           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5867           addr += bytes_read;
5868           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5869           addr += bytes_read;
5870           if (attr.form == DW_FORM_implicit_const)
5871             {
5872               attr.implicit_const = read_signed_leb128 (abfd, addr,
5873                                                         &bytes_read);
5874               addr += bytes_read;
5875             }
5876           if (attr.dw_idx == 0 && attr.form == 0)
5877             break;
5878           indexval.attr_vec.push_back (std::move (attr));
5879         }
5880     }
5881   if (addr != abbrev_table_start + abbrev_table_size)
5882     {
5883       warning (_("Section .debug_names in %s has abbreviation_table "
5884                  "of size %zu vs. written as %u, ignoring .debug_names."),
5885                filename, addr - abbrev_table_start, abbrev_table_size);
5886       return false;
5887     }
5888   map.entry_pool = addr;
5889
5890   return true;
5891 }
5892
5893 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5894    list.  */
5895
5896 static void
5897 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5898                                   const mapped_debug_names &map,
5899                                   dwarf2_section_info &section,
5900                                   bool is_dwz, int base_offset)
5901 {
5902   sect_offset sect_off_prev;
5903   for (uint32_t i = 0; i <= map.cu_count; ++i)
5904     {
5905       sect_offset sect_off_next;
5906       if (i < map.cu_count)
5907         {
5908           sect_off_next
5909             = (sect_offset) (extract_unsigned_integer
5910                              (map.cu_table_reordered + i * map.offset_size,
5911                               map.offset_size,
5912                               map.dwarf5_byte_order));
5913         }
5914       else
5915         sect_off_next = (sect_offset) section.size;
5916       if (i >= 1)
5917         {
5918           const ULONGEST length = sect_off_next - sect_off_prev;
5919           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5920             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5921                                          sect_off_prev, length);
5922         }
5923       sect_off_prev = sect_off_next;
5924     }
5925 }
5926
5927 /* Read the CU list from the mapped index, and use it to create all
5928    the CU objects for this dwarf2_per_objfile.  */
5929
5930 static void
5931 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5932                              const mapped_debug_names &map,
5933                              const mapped_debug_names &dwz_map)
5934 {
5935   struct objfile *objfile = dwarf2_per_objfile->objfile;
5936
5937   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5938   dwarf2_per_objfile->all_comp_units
5939     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5940                  dwarf2_per_objfile->n_comp_units);
5941
5942   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5943                                     dwarf2_per_objfile->info,
5944                                     false /* is_dwz */,
5945                                     0 /* base_offset */);
5946
5947   if (dwz_map.cu_count == 0)
5948     return;
5949
5950   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5951   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5952                                     true /* is_dwz */,
5953                                     map.cu_count /* base_offset */);
5954 }
5955
5956 /* Read .debug_names.  If everything went ok, initialize the "quick"
5957    elements of all the CUs and return true.  Otherwise, return false.  */
5958
5959 static bool
5960 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5961 {
5962   mapped_debug_names local_map (dwarf2_per_objfile);
5963   mapped_debug_names dwz_map (dwarf2_per_objfile);
5964   struct objfile *objfile = dwarf2_per_objfile->objfile;
5965
5966   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5967                                       &dwarf2_per_objfile->debug_names,
5968                                       local_map))
5969     return false;
5970
5971   /* Don't use the index if it's empty.  */
5972   if (local_map.name_count == 0)
5973     return false;
5974
5975   /* If there is a .dwz file, read it so we can get its CU list as
5976      well.  */
5977   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5978   if (dwz != NULL)
5979     {
5980       if (!read_debug_names_from_section (objfile,
5981                                           bfd_get_filename (dwz->dwz_bfd),
5982                                           &dwz->debug_names, dwz_map))
5983         {
5984           warning (_("could not read '.debug_names' section from %s; skipping"),
5985                    bfd_get_filename (dwz->dwz_bfd));
5986           return false;
5987         }
5988     }
5989
5990   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
5991
5992   if (local_map.tu_count != 0)
5993     {
5994       /* We can only handle a single .debug_types when we have an
5995          index.  */
5996       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5997         return false;
5998
5999       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
6000                                                 dwarf2_per_objfile->types, 0);
6001
6002       create_signatured_type_table_from_debug_names
6003         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
6004     }
6005
6006   create_addrmap_from_aranges (dwarf2_per_objfile,
6007                                &dwarf2_per_objfile->debug_aranges);
6008
6009   dwarf2_per_objfile->debug_names_table.reset
6010     (new mapped_debug_names (dwarf2_per_objfile));
6011   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
6012   dwarf2_per_objfile->using_index = 1;
6013   dwarf2_per_objfile->quick_file_names_table =
6014     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6015
6016   return true;
6017 }
6018
6019 /* Symbol name hashing function as specified by DWARF-5.  */
6020
6021 static uint32_t
6022 dwarf5_djb_hash (const char *str_)
6023 {
6024   const unsigned char *str = (const unsigned char *) str_;
6025
6026   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6027      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6028
6029   uint32_t hash = 5381;
6030   while (int c = *str++)
6031     hash = hash * 33 + tolower (c);
6032   return hash;
6033 }
6034
6035 /* Type used to manage iterating over all CUs looking for a symbol for
6036    .debug_names.  */
6037
6038 class dw2_debug_names_iterator
6039 {
6040 public:
6041   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6042      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6043   dw2_debug_names_iterator (const mapped_debug_names &map,
6044                             bool want_specific_block,
6045                             block_enum block_index, domain_enum domain,
6046                             const char *name)
6047     : m_map (map), m_want_specific_block (want_specific_block),
6048       m_block_index (block_index), m_domain (domain),
6049       m_addr (find_vec_in_debug_names (map, name))
6050   {}
6051
6052   dw2_debug_names_iterator (const mapped_debug_names &map,
6053                             search_domain search, uint32_t namei)
6054     : m_map (map),
6055       m_search (search),
6056       m_addr (find_vec_in_debug_names (map, namei))
6057   {}
6058
6059   /* Return the next matching CU or NULL if there are no more.  */
6060   dwarf2_per_cu_data *next ();
6061
6062 private:
6063   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6064                                                   const char *name);
6065   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6066                                                   uint32_t namei);
6067
6068   /* The internalized form of .debug_names.  */
6069   const mapped_debug_names &m_map;
6070
6071   /* If true, only look for symbols that match BLOCK_INDEX.  */
6072   const bool m_want_specific_block = false;
6073
6074   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6075      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6076      value.  */
6077   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6078
6079   /* The kind of symbol we're looking for.  */
6080   const domain_enum m_domain = UNDEF_DOMAIN;
6081   const search_domain m_search = ALL_DOMAIN;
6082
6083   /* The list of CUs from the index entry of the symbol, or NULL if
6084      not found.  */
6085   const gdb_byte *m_addr;
6086 };
6087
6088 const char *
6089 mapped_debug_names::namei_to_name (uint32_t namei) const
6090 {
6091   const ULONGEST namei_string_offs
6092     = extract_unsigned_integer ((name_table_string_offs_reordered
6093                                  + namei * offset_size),
6094                                 offset_size,
6095                                 dwarf5_byte_order);
6096   return read_indirect_string_at_offset
6097     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6098 }
6099
6100 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6101    found, return pointer to its pool data.  If NAME cannot be found,
6102    return NULL.  */
6103
6104 const gdb_byte *
6105 dw2_debug_names_iterator::find_vec_in_debug_names
6106   (const mapped_debug_names &map, const char *name)
6107 {
6108   int (*cmp) (const char *, const char *);
6109
6110   if (current_language->la_language == language_cplus
6111       || current_language->la_language == language_fortran
6112       || current_language->la_language == language_d)
6113     {
6114       /* NAME is already canonical.  Drop any qualifiers as
6115          .debug_names does not contain any.  */
6116
6117       if (strchr (name, '(') != NULL)
6118         {
6119           gdb::unique_xmalloc_ptr<char> without_params
6120             = cp_remove_params (name);
6121
6122           if (without_params != NULL)
6123             {
6124               name = without_params.get();
6125             }
6126         }
6127     }
6128
6129   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6130
6131   const uint32_t full_hash = dwarf5_djb_hash (name);
6132   uint32_t namei
6133     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6134                                 (map.bucket_table_reordered
6135                                  + (full_hash % map.bucket_count)), 4,
6136                                 map.dwarf5_byte_order);
6137   if (namei == 0)
6138     return NULL;
6139   --namei;
6140   if (namei >= map.name_count)
6141     {
6142       complaint (&symfile_complaints,
6143                  _("Wrong .debug_names with name index %u but name_count=%u "
6144                    "[in module %s]"),
6145                  namei, map.name_count,
6146                  objfile_name (map.dwarf2_per_objfile->objfile));
6147       return NULL;
6148     }
6149
6150   for (;;)
6151     {
6152       const uint32_t namei_full_hash
6153         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6154                                     (map.hash_table_reordered + namei), 4,
6155                                     map.dwarf5_byte_order);
6156       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6157         return NULL;
6158
6159       if (full_hash == namei_full_hash)
6160         {
6161           const char *const namei_string = map.namei_to_name (namei);
6162
6163 #if 0 /* An expensive sanity check.  */
6164           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6165             {
6166               complaint (&symfile_complaints,
6167                          _("Wrong .debug_names hash for string at index %u "
6168                            "[in module %s]"),
6169                          namei, objfile_name (dwarf2_per_objfile->objfile));
6170               return NULL;
6171             }
6172 #endif
6173
6174           if (cmp (namei_string, name) == 0)
6175             {
6176               const ULONGEST namei_entry_offs
6177                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6178                                              + namei * map.offset_size),
6179                                             map.offset_size, map.dwarf5_byte_order);
6180               return map.entry_pool + namei_entry_offs;
6181             }
6182         }
6183
6184       ++namei;
6185       if (namei >= map.name_count)
6186         return NULL;
6187     }
6188 }
6189
6190 const gdb_byte *
6191 dw2_debug_names_iterator::find_vec_in_debug_names
6192   (const mapped_debug_names &map, uint32_t namei)
6193 {
6194   if (namei >= map.name_count)
6195     {
6196       complaint (&symfile_complaints,
6197                  _("Wrong .debug_names with name index %u but name_count=%u "
6198                    "[in module %s]"),
6199                  namei, map.name_count,
6200                  objfile_name (map.dwarf2_per_objfile->objfile));
6201       return NULL;
6202     }
6203
6204   const ULONGEST namei_entry_offs
6205     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6206                                  + namei * map.offset_size),
6207                                 map.offset_size, map.dwarf5_byte_order);
6208   return map.entry_pool + namei_entry_offs;
6209 }
6210
6211 /* See dw2_debug_names_iterator.  */
6212
6213 dwarf2_per_cu_data *
6214 dw2_debug_names_iterator::next ()
6215 {
6216   if (m_addr == NULL)
6217     return NULL;
6218
6219   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6220   struct objfile *objfile = dwarf2_per_objfile->objfile;
6221   bfd *const abfd = objfile->obfd;
6222
6223  again:
6224
6225   unsigned int bytes_read;
6226   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6227   m_addr += bytes_read;
6228   if (abbrev == 0)
6229     return NULL;
6230
6231   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6232   if (indexval_it == m_map.abbrev_map.cend ())
6233     {
6234       complaint (&symfile_complaints,
6235                  _("Wrong .debug_names undefined abbrev code %s "
6236                    "[in module %s]"),
6237                  pulongest (abbrev), objfile_name (objfile));
6238       return NULL;
6239     }
6240   const mapped_debug_names::index_val &indexval = indexval_it->second;
6241   bool have_is_static = false;
6242   bool is_static;
6243   dwarf2_per_cu_data *per_cu = NULL;
6244   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6245     {
6246       ULONGEST ull;
6247       switch (attr.form)
6248         {
6249         case DW_FORM_implicit_const:
6250           ull = attr.implicit_const;
6251           break;
6252         case DW_FORM_flag_present:
6253           ull = 1;
6254           break;
6255         case DW_FORM_udata:
6256           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6257           m_addr += bytes_read;
6258           break;
6259         default:
6260           complaint (&symfile_complaints,
6261                      _("Unsupported .debug_names form %s [in module %s]"),
6262                      dwarf_form_name (attr.form),
6263                      objfile_name (objfile));
6264           return NULL;
6265         }
6266       switch (attr.dw_idx)
6267         {
6268         case DW_IDX_compile_unit:
6269           /* Don't crash on bad data.  */
6270           if (ull >= dwarf2_per_objfile->n_comp_units)
6271             {
6272               complaint (&symfile_complaints,
6273                          _(".debug_names entry has bad CU index %s"
6274                            " [in module %s]"),
6275                          pulongest (ull),
6276                          objfile_name (dwarf2_per_objfile->objfile));
6277               continue;
6278             }
6279           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6280           break;
6281         case DW_IDX_type_unit:
6282           /* Don't crash on bad data.  */
6283           if (ull >= dwarf2_per_objfile->n_type_units)
6284             {
6285               complaint (&symfile_complaints,
6286                          _(".debug_names entry has bad TU index %s"
6287                            " [in module %s]"),
6288                          pulongest (ull),
6289                          objfile_name (dwarf2_per_objfile->objfile));
6290               continue;
6291             }
6292           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6293                                  dwarf2_per_objfile->n_comp_units + ull);
6294           break;
6295         case DW_IDX_GNU_internal:
6296           if (!m_map.augmentation_is_gdb)
6297             break;
6298           have_is_static = true;
6299           is_static = true;
6300           break;
6301         case DW_IDX_GNU_external:
6302           if (!m_map.augmentation_is_gdb)
6303             break;
6304           have_is_static = true;
6305           is_static = false;
6306           break;
6307         }
6308     }
6309
6310   /* Skip if already read in.  */
6311   if (per_cu->v.quick->compunit_symtab)
6312     goto again;
6313
6314   /* Check static vs global.  */
6315   if (have_is_static)
6316     {
6317       const bool want_static = m_block_index != GLOBAL_BLOCK;
6318       if (m_want_specific_block && want_static != is_static)
6319         goto again;
6320     }
6321
6322   /* Match dw2_symtab_iter_next, symbol_kind
6323      and debug_names::psymbol_tag.  */
6324   switch (m_domain)
6325     {
6326     case VAR_DOMAIN:
6327       switch (indexval.dwarf_tag)
6328         {
6329         case DW_TAG_variable:
6330         case DW_TAG_subprogram:
6331         /* Some types are also in VAR_DOMAIN.  */
6332         case DW_TAG_typedef:
6333         case DW_TAG_structure_type:
6334           break;
6335         default:
6336           goto again;
6337         }
6338       break;
6339     case STRUCT_DOMAIN:
6340       switch (indexval.dwarf_tag)
6341         {
6342         case DW_TAG_typedef:
6343         case DW_TAG_structure_type:
6344           break;
6345         default:
6346           goto again;
6347         }
6348       break;
6349     case LABEL_DOMAIN:
6350       switch (indexval.dwarf_tag)
6351         {
6352         case 0:
6353         case DW_TAG_variable:
6354           break;
6355         default:
6356           goto again;
6357         }
6358       break;
6359     default:
6360       break;
6361     }
6362
6363   /* Match dw2_expand_symtabs_matching, symbol_kind and
6364      debug_names::psymbol_tag.  */
6365   switch (m_search)
6366     {
6367     case VARIABLES_DOMAIN:
6368       switch (indexval.dwarf_tag)
6369         {
6370         case DW_TAG_variable:
6371           break;
6372         default:
6373           goto again;
6374         }
6375       break;
6376     case FUNCTIONS_DOMAIN:
6377       switch (indexval.dwarf_tag)
6378         {
6379         case DW_TAG_subprogram:
6380           break;
6381         default:
6382           goto again;
6383         }
6384       break;
6385     case TYPES_DOMAIN:
6386       switch (indexval.dwarf_tag)
6387         {
6388         case DW_TAG_typedef:
6389         case DW_TAG_structure_type:
6390           break;
6391         default:
6392           goto again;
6393         }
6394       break;
6395     default:
6396       break;
6397     }
6398
6399   return per_cu;
6400 }
6401
6402 static struct compunit_symtab *
6403 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6404                                const char *name, domain_enum domain)
6405 {
6406   const block_enum block_index = static_cast<block_enum> (block_index_int);
6407   struct dwarf2_per_objfile *dwarf2_per_objfile
6408     = get_dwarf2_per_objfile (objfile);
6409
6410   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6411   if (!mapp)
6412     {
6413       /* index is NULL if OBJF_READNOW.  */
6414       return NULL;
6415     }
6416   const auto &map = *mapp;
6417
6418   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6419                                  block_index, domain, name);
6420
6421   struct compunit_symtab *stab_best = NULL;
6422   struct dwarf2_per_cu_data *per_cu;
6423   while ((per_cu = iter.next ()) != NULL)
6424     {
6425       struct symbol *sym, *with_opaque = NULL;
6426       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6427       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6428       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6429
6430       sym = block_find_symbol (block, name, domain,
6431                                block_find_non_opaque_type_preferred,
6432                                &with_opaque);
6433
6434       /* Some caution must be observed with overloaded functions and
6435          methods, since the index will not contain any overload
6436          information (but NAME might contain it).  */
6437
6438       if (sym != NULL
6439           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6440         return stab;
6441       if (with_opaque != NULL
6442           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6443         stab_best = stab;
6444
6445       /* Keep looking through other CUs.  */
6446     }
6447
6448   return stab_best;
6449 }
6450
6451 /* This dumps minimal information about .debug_names.  It is called
6452    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6453    uses this to verify that .debug_names has been loaded.  */
6454
6455 static void
6456 dw2_debug_names_dump (struct objfile *objfile)
6457 {
6458   struct dwarf2_per_objfile *dwarf2_per_objfile
6459     = get_dwarf2_per_objfile (objfile);
6460
6461   gdb_assert (dwarf2_per_objfile->using_index);
6462   printf_filtered (".debug_names:");
6463   if (dwarf2_per_objfile->debug_names_table)
6464     printf_filtered (" exists\n");
6465   else
6466     printf_filtered (" faked for \"readnow\"\n");
6467   printf_filtered ("\n");
6468 }
6469
6470 static void
6471 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6472                                              const char *func_name)
6473 {
6474   struct dwarf2_per_objfile *dwarf2_per_objfile
6475     = get_dwarf2_per_objfile (objfile);
6476
6477   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6478   if (dwarf2_per_objfile->debug_names_table)
6479     {
6480       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6481
6482       /* Note: It doesn't matter what we pass for block_index here.  */
6483       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6484                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6485
6486       struct dwarf2_per_cu_data *per_cu;
6487       while ((per_cu = iter.next ()) != NULL)
6488         dw2_instantiate_symtab (per_cu);
6489     }
6490 }
6491
6492 static void
6493 dw2_debug_names_expand_symtabs_matching
6494   (struct objfile *objfile,
6495    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6496    const lookup_name_info &lookup_name,
6497    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6498    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6499    enum search_domain kind)
6500 {
6501   struct dwarf2_per_objfile *dwarf2_per_objfile
6502     = get_dwarf2_per_objfile (objfile);
6503
6504   /* debug_names_table is NULL if OBJF_READNOW.  */
6505   if (!dwarf2_per_objfile->debug_names_table)
6506     return;
6507
6508   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6509
6510   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6511
6512   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6513                                       symbol_matcher,
6514                                       kind, [&] (offset_type namei)
6515     {
6516       /* The name was matched, now expand corresponding CUs that were
6517          marked.  */
6518       dw2_debug_names_iterator iter (map, kind, namei);
6519
6520       struct dwarf2_per_cu_data *per_cu;
6521       while ((per_cu = iter.next ()) != NULL)
6522         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6523                                          expansion_notify);
6524     });
6525 }
6526
6527 const struct quick_symbol_functions dwarf2_debug_names_functions =
6528 {
6529   dw2_has_symbols,
6530   dw2_find_last_source_symtab,
6531   dw2_forget_cached_source_info,
6532   dw2_map_symtabs_matching_filename,
6533   dw2_debug_names_lookup_symbol,
6534   dw2_print_stats,
6535   dw2_debug_names_dump,
6536   dw2_relocate,
6537   dw2_debug_names_expand_symtabs_for_function,
6538   dw2_expand_all_symtabs,
6539   dw2_expand_symtabs_with_fullname,
6540   dw2_map_matching_symbols,
6541   dw2_debug_names_expand_symtabs_matching,
6542   dw2_find_pc_sect_compunit_symtab,
6543   NULL,
6544   dw2_map_symbol_filenames
6545 };
6546
6547 /* See symfile.h.  */
6548
6549 bool
6550 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6551 {
6552   struct dwarf2_per_objfile *dwarf2_per_objfile
6553     = get_dwarf2_per_objfile (objfile);
6554
6555   /* If we're about to read full symbols, don't bother with the
6556      indices.  In this case we also don't care if some other debug
6557      format is making psymtabs, because they are all about to be
6558      expanded anyway.  */
6559   if ((objfile->flags & OBJF_READNOW))
6560     {
6561       int i;
6562
6563       dwarf2_per_objfile->using_index = 1;
6564       create_all_comp_units (dwarf2_per_objfile);
6565       create_all_type_units (dwarf2_per_objfile);
6566       dwarf2_per_objfile->quick_file_names_table =
6567         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6568
6569       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6570                        + dwarf2_per_objfile->n_type_units); ++i)
6571         {
6572           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6573
6574           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6575                                             struct dwarf2_per_cu_quick_data);
6576         }
6577
6578       /* Return 1 so that gdb sees the "quick" functions.  However,
6579          these functions will be no-ops because we will have expanded
6580          all symtabs.  */
6581       *index_kind = dw_index_kind::GDB_INDEX;
6582       return true;
6583     }
6584
6585   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6586     {
6587       *index_kind = dw_index_kind::DEBUG_NAMES;
6588       return true;
6589     }
6590
6591   if (dwarf2_read_index (objfile))
6592     {
6593       *index_kind = dw_index_kind::GDB_INDEX;
6594       return true;
6595     }
6596
6597   return false;
6598 }
6599
6600 \f
6601
6602 /* Build a partial symbol table.  */
6603
6604 void
6605 dwarf2_build_psymtabs (struct objfile *objfile)
6606 {
6607   struct dwarf2_per_objfile *dwarf2_per_objfile
6608     = get_dwarf2_per_objfile (objfile);
6609
6610   if (objfile->global_psymbols.capacity () == 0
6611       && objfile->static_psymbols.capacity () == 0)
6612     init_psymbol_list (objfile, 1024);
6613
6614   TRY
6615     {
6616       /* This isn't really ideal: all the data we allocate on the
6617          objfile's obstack is still uselessly kept around.  However,
6618          freeing it seems unsafe.  */
6619       psymtab_discarder psymtabs (objfile);
6620       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6621       psymtabs.keep ();
6622     }
6623   CATCH (except, RETURN_MASK_ERROR)
6624     {
6625       exception_print (gdb_stderr, except);
6626     }
6627   END_CATCH
6628 }
6629
6630 /* Return the total length of the CU described by HEADER.  */
6631
6632 static unsigned int
6633 get_cu_length (const struct comp_unit_head *header)
6634 {
6635   return header->initial_length_size + header->length;
6636 }
6637
6638 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6639
6640 static inline bool
6641 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6642 {
6643   sect_offset bottom = cu_header->sect_off;
6644   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6645
6646   return sect_off >= bottom && sect_off < top;
6647 }
6648
6649 /* Find the base address of the compilation unit for range lists and
6650    location lists.  It will normally be specified by DW_AT_low_pc.
6651    In DWARF-3 draft 4, the base address could be overridden by
6652    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6653    compilation units with discontinuous ranges.  */
6654
6655 static void
6656 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6657 {
6658   struct attribute *attr;
6659
6660   cu->base_known = 0;
6661   cu->base_address = 0;
6662
6663   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6664   if (attr)
6665     {
6666       cu->base_address = attr_value_as_address (attr);
6667       cu->base_known = 1;
6668     }
6669   else
6670     {
6671       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6672       if (attr)
6673         {
6674           cu->base_address = attr_value_as_address (attr);
6675           cu->base_known = 1;
6676         }
6677     }
6678 }
6679
6680 /* Read in the comp unit header information from the debug_info at info_ptr.
6681    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6682    NOTE: This leaves members offset, first_die_offset to be filled in
6683    by the caller.  */
6684
6685 static const gdb_byte *
6686 read_comp_unit_head (struct comp_unit_head *cu_header,
6687                      const gdb_byte *info_ptr,
6688                      struct dwarf2_section_info *section,
6689                      rcuh_kind section_kind)
6690 {
6691   int signed_addr;
6692   unsigned int bytes_read;
6693   const char *filename = get_section_file_name (section);
6694   bfd *abfd = get_section_bfd_owner (section);
6695
6696   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6697   cu_header->initial_length_size = bytes_read;
6698   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6699   info_ptr += bytes_read;
6700   cu_header->version = read_2_bytes (abfd, info_ptr);
6701   info_ptr += 2;
6702   if (cu_header->version < 5)
6703     switch (section_kind)
6704       {
6705       case rcuh_kind::COMPILE:
6706         cu_header->unit_type = DW_UT_compile;
6707         break;
6708       case rcuh_kind::TYPE:
6709         cu_header->unit_type = DW_UT_type;
6710         break;
6711       default:
6712         internal_error (__FILE__, __LINE__,
6713                         _("read_comp_unit_head: invalid section_kind"));
6714       }
6715   else
6716     {
6717       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6718                                                  (read_1_byte (abfd, info_ptr));
6719       info_ptr += 1;
6720       switch (cu_header->unit_type)
6721         {
6722         case DW_UT_compile:
6723           if (section_kind != rcuh_kind::COMPILE)
6724             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6725                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6726                    filename);
6727           break;
6728         case DW_UT_type:
6729           section_kind = rcuh_kind::TYPE;
6730           break;
6731         default:
6732           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6733                  "(is %d, should be %d or %d) [in module %s]"),
6734                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6735         }
6736
6737       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6738       info_ptr += 1;
6739     }
6740   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6741                                                           cu_header,
6742                                                           &bytes_read);
6743   info_ptr += bytes_read;
6744   if (cu_header->version < 5)
6745     {
6746       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6747       info_ptr += 1;
6748     }
6749   signed_addr = bfd_get_sign_extend_vma (abfd);
6750   if (signed_addr < 0)
6751     internal_error (__FILE__, __LINE__,
6752                     _("read_comp_unit_head: dwarf from non elf file"));
6753   cu_header->signed_addr_p = signed_addr;
6754
6755   if (section_kind == rcuh_kind::TYPE)
6756     {
6757       LONGEST type_offset;
6758
6759       cu_header->signature = read_8_bytes (abfd, info_ptr);
6760       info_ptr += 8;
6761
6762       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6763       info_ptr += bytes_read;
6764       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6765       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6766         error (_("Dwarf Error: Too big type_offset in compilation unit "
6767                "header (is %s) [in module %s]"), plongest (type_offset),
6768                filename);
6769     }
6770
6771   return info_ptr;
6772 }
6773
6774 /* Helper function that returns the proper abbrev section for
6775    THIS_CU.  */
6776
6777 static struct dwarf2_section_info *
6778 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6779 {
6780   struct dwarf2_section_info *abbrev;
6781   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6782
6783   if (this_cu->is_dwz)
6784     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6785   else
6786     abbrev = &dwarf2_per_objfile->abbrev;
6787
6788   return abbrev;
6789 }
6790
6791 /* Subroutine of read_and_check_comp_unit_head and
6792    read_and_check_type_unit_head to simplify them.
6793    Perform various error checking on the header.  */
6794
6795 static void
6796 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6797                             struct comp_unit_head *header,
6798                             struct dwarf2_section_info *section,
6799                             struct dwarf2_section_info *abbrev_section)
6800 {
6801   const char *filename = get_section_file_name (section);
6802
6803   if (header->version < 2 || header->version > 5)
6804     error (_("Dwarf Error: wrong version in compilation unit header "
6805            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6806            filename);
6807
6808   if (to_underlying (header->abbrev_sect_off)
6809       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6810     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6811            "(offset 0x%x + 6) [in module %s]"),
6812            to_underlying (header->abbrev_sect_off),
6813            to_underlying (header->sect_off),
6814            filename);
6815
6816   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6817      avoid potential 32-bit overflow.  */
6818   if (((ULONGEST) header->sect_off + get_cu_length (header))
6819       > section->size)
6820     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6821            "(offset 0x%x + 0) [in module %s]"),
6822            header->length, to_underlying (header->sect_off),
6823            filename);
6824 }
6825
6826 /* Read in a CU/TU header and perform some basic error checking.
6827    The contents of the header are stored in HEADER.
6828    The result is a pointer to the start of the first DIE.  */
6829
6830 static const gdb_byte *
6831 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6832                                struct comp_unit_head *header,
6833                                struct dwarf2_section_info *section,
6834                                struct dwarf2_section_info *abbrev_section,
6835                                const gdb_byte *info_ptr,
6836                                rcuh_kind section_kind)
6837 {
6838   const gdb_byte *beg_of_comp_unit = info_ptr;
6839
6840   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6841
6842   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6843
6844   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6845
6846   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6847                               abbrev_section);
6848
6849   return info_ptr;
6850 }
6851
6852 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6853
6854 static sect_offset
6855 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6856                     struct dwarf2_section_info *section,
6857                     sect_offset sect_off)
6858 {
6859   bfd *abfd = get_section_bfd_owner (section);
6860   const gdb_byte *info_ptr;
6861   unsigned int initial_length_size, offset_size;
6862   uint16_t version;
6863
6864   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6865   info_ptr = section->buffer + to_underlying (sect_off);
6866   read_initial_length (abfd, info_ptr, &initial_length_size);
6867   offset_size = initial_length_size == 4 ? 4 : 8;
6868   info_ptr += initial_length_size;
6869
6870   version = read_2_bytes (abfd, info_ptr);
6871   info_ptr += 2;
6872   if (version >= 5)
6873     {
6874       /* Skip unit type and address size.  */
6875       info_ptr += 2;
6876     }
6877
6878   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6879 }
6880
6881 /* Allocate a new partial symtab for file named NAME and mark this new
6882    partial symtab as being an include of PST.  */
6883
6884 static void
6885 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6886                                struct objfile *objfile)
6887 {
6888   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6889
6890   if (!IS_ABSOLUTE_PATH (subpst->filename))
6891     {
6892       /* It shares objfile->objfile_obstack.  */
6893       subpst->dirname = pst->dirname;
6894     }
6895
6896   subpst->textlow = 0;
6897   subpst->texthigh = 0;
6898
6899   subpst->dependencies
6900     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6901   subpst->dependencies[0] = pst;
6902   subpst->number_of_dependencies = 1;
6903
6904   subpst->globals_offset = 0;
6905   subpst->n_global_syms = 0;
6906   subpst->statics_offset = 0;
6907   subpst->n_static_syms = 0;
6908   subpst->compunit_symtab = NULL;
6909   subpst->read_symtab = pst->read_symtab;
6910   subpst->readin = 0;
6911
6912   /* No private part is necessary for include psymtabs.  This property
6913      can be used to differentiate between such include psymtabs and
6914      the regular ones.  */
6915   subpst->read_symtab_private = NULL;
6916 }
6917
6918 /* Read the Line Number Program data and extract the list of files
6919    included by the source file represented by PST.  Build an include
6920    partial symtab for each of these included files.  */
6921
6922 static void
6923 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6924                                struct die_info *die,
6925                                struct partial_symtab *pst)
6926 {
6927   line_header_up lh;
6928   struct attribute *attr;
6929
6930   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6931   if (attr)
6932     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6933   if (lh == NULL)
6934     return;  /* No linetable, so no includes.  */
6935
6936   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6937   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6938 }
6939
6940 static hashval_t
6941 hash_signatured_type (const void *item)
6942 {
6943   const struct signatured_type *sig_type
6944     = (const struct signatured_type *) item;
6945
6946   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6947   return sig_type->signature;
6948 }
6949
6950 static int
6951 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6952 {
6953   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6954   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6955
6956   return lhs->signature == rhs->signature;
6957 }
6958
6959 /* Allocate a hash table for signatured types.  */
6960
6961 static htab_t
6962 allocate_signatured_type_table (struct objfile *objfile)
6963 {
6964   return htab_create_alloc_ex (41,
6965                                hash_signatured_type,
6966                                eq_signatured_type,
6967                                NULL,
6968                                &objfile->objfile_obstack,
6969                                hashtab_obstack_allocate,
6970                                dummy_obstack_deallocate);
6971 }
6972
6973 /* A helper function to add a signatured type CU to a table.  */
6974
6975 static int
6976 add_signatured_type_cu_to_table (void **slot, void *datum)
6977 {
6978   struct signatured_type *sigt = (struct signatured_type *) *slot;
6979   struct signatured_type ***datap = (struct signatured_type ***) datum;
6980
6981   **datap = sigt;
6982   ++*datap;
6983
6984   return 1;
6985 }
6986
6987 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6988    and fill them into TYPES_HTAB.  It will process only type units,
6989    therefore DW_UT_type.  */
6990
6991 static void
6992 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6993                               struct dwo_file *dwo_file,
6994                               dwarf2_section_info *section, htab_t &types_htab,
6995                               rcuh_kind section_kind)
6996 {
6997   struct objfile *objfile = dwarf2_per_objfile->objfile;
6998   struct dwarf2_section_info *abbrev_section;
6999   bfd *abfd;
7000   const gdb_byte *info_ptr, *end_ptr;
7001
7002   abbrev_section = (dwo_file != NULL
7003                     ? &dwo_file->sections.abbrev
7004                     : &dwarf2_per_objfile->abbrev);
7005
7006   if (dwarf_read_debug)
7007     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
7008                         get_section_name (section),
7009                         get_section_file_name (abbrev_section));
7010
7011   dwarf2_read_section (objfile, section);
7012   info_ptr = section->buffer;
7013
7014   if (info_ptr == NULL)
7015     return;
7016
7017   /* We can't set abfd until now because the section may be empty or
7018      not present, in which case the bfd is unknown.  */
7019   abfd = get_section_bfd_owner (section);
7020
7021   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7022      because we don't need to read any dies: the signature is in the
7023      header.  */
7024
7025   end_ptr = info_ptr + section->size;
7026   while (info_ptr < end_ptr)
7027     {
7028       struct signatured_type *sig_type;
7029       struct dwo_unit *dwo_tu;
7030       void **slot;
7031       const gdb_byte *ptr = info_ptr;
7032       struct comp_unit_head header;
7033       unsigned int length;
7034
7035       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7036
7037       /* Initialize it due to a false compiler warning.  */
7038       header.signature = -1;
7039       header.type_cu_offset_in_tu = (cu_offset) -1;
7040
7041       /* We need to read the type's signature in order to build the hash
7042          table, but we don't need anything else just yet.  */
7043
7044       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7045                                            abbrev_section, ptr, section_kind);
7046
7047       length = get_cu_length (&header);
7048
7049       /* Skip dummy type units.  */
7050       if (ptr >= info_ptr + length
7051           || peek_abbrev_code (abfd, ptr) == 0
7052           || header.unit_type != DW_UT_type)
7053         {
7054           info_ptr += length;
7055           continue;
7056         }
7057
7058       if (types_htab == NULL)
7059         {
7060           if (dwo_file)
7061             types_htab = allocate_dwo_unit_table (objfile);
7062           else
7063             types_htab = allocate_signatured_type_table (objfile);
7064         }
7065
7066       if (dwo_file)
7067         {
7068           sig_type = NULL;
7069           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7070                                    struct dwo_unit);
7071           dwo_tu->dwo_file = dwo_file;
7072           dwo_tu->signature = header.signature;
7073           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7074           dwo_tu->section = section;
7075           dwo_tu->sect_off = sect_off;
7076           dwo_tu->length = length;
7077         }
7078       else
7079         {
7080           /* N.B.: type_offset is not usable if this type uses a DWO file.
7081              The real type_offset is in the DWO file.  */
7082           dwo_tu = NULL;
7083           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7084                                      struct signatured_type);
7085           sig_type->signature = header.signature;
7086           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7087           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7088           sig_type->per_cu.is_debug_types = 1;
7089           sig_type->per_cu.section = section;
7090           sig_type->per_cu.sect_off = sect_off;
7091           sig_type->per_cu.length = length;
7092         }
7093
7094       slot = htab_find_slot (types_htab,
7095                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7096                              INSERT);
7097       gdb_assert (slot != NULL);
7098       if (*slot != NULL)
7099         {
7100           sect_offset dup_sect_off;
7101
7102           if (dwo_file)
7103             {
7104               const struct dwo_unit *dup_tu
7105                 = (const struct dwo_unit *) *slot;
7106
7107               dup_sect_off = dup_tu->sect_off;
7108             }
7109           else
7110             {
7111               const struct signatured_type *dup_tu
7112                 = (const struct signatured_type *) *slot;
7113
7114               dup_sect_off = dup_tu->per_cu.sect_off;
7115             }
7116
7117           complaint (&symfile_complaints,
7118                      _("debug type entry at offset 0x%x is duplicate to"
7119                        " the entry at offset 0x%x, signature %s"),
7120                      to_underlying (sect_off), to_underlying (dup_sect_off),
7121                      hex_string (header.signature));
7122         }
7123       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7124
7125       if (dwarf_read_debug > 1)
7126         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7127                             to_underlying (sect_off),
7128                             hex_string (header.signature));
7129
7130       info_ptr += length;
7131     }
7132 }
7133
7134 /* Create the hash table of all entries in the .debug_types
7135    (or .debug_types.dwo) section(s).
7136    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7137    otherwise it is NULL.
7138
7139    The result is a pointer to the hash table or NULL if there are no types.
7140
7141    Note: This function processes DWO files only, not DWP files.  */
7142
7143 static void
7144 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7145                                struct dwo_file *dwo_file,
7146                                VEC (dwarf2_section_info_def) *types,
7147                                htab_t &types_htab)
7148 {
7149   int ix;
7150   struct dwarf2_section_info *section;
7151
7152   if (VEC_empty (dwarf2_section_info_def, types))
7153     return;
7154
7155   for (ix = 0;
7156        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7157        ++ix)
7158     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7159                                   types_htab, rcuh_kind::TYPE);
7160 }
7161
7162 /* Create the hash table of all entries in the .debug_types section,
7163    and initialize all_type_units.
7164    The result is zero if there is an error (e.g. missing .debug_types section),
7165    otherwise non-zero.  */
7166
7167 static int
7168 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7169 {
7170   htab_t types_htab = NULL;
7171   struct signatured_type **iter;
7172
7173   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7174                                 &dwarf2_per_objfile->info, types_htab,
7175                                 rcuh_kind::COMPILE);
7176   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7177                                  dwarf2_per_objfile->types, types_htab);
7178   if (types_htab == NULL)
7179     {
7180       dwarf2_per_objfile->signatured_types = NULL;
7181       return 0;
7182     }
7183
7184   dwarf2_per_objfile->signatured_types = types_htab;
7185
7186   dwarf2_per_objfile->n_type_units
7187     = dwarf2_per_objfile->n_allocated_type_units
7188     = htab_elements (types_htab);
7189   dwarf2_per_objfile->all_type_units =
7190     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7191   iter = &dwarf2_per_objfile->all_type_units[0];
7192   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7193   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7194               == dwarf2_per_objfile->n_type_units);
7195
7196   return 1;
7197 }
7198
7199 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7200    If SLOT is non-NULL, it is the entry to use in the hash table.
7201    Otherwise we find one.  */
7202
7203 static struct signatured_type *
7204 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7205                void **slot)
7206 {
7207   struct objfile *objfile = dwarf2_per_objfile->objfile;
7208   int n_type_units = dwarf2_per_objfile->n_type_units;
7209   struct signatured_type *sig_type;
7210
7211   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7212   ++n_type_units;
7213   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7214     {
7215       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7216         dwarf2_per_objfile->n_allocated_type_units = 1;
7217       dwarf2_per_objfile->n_allocated_type_units *= 2;
7218       dwarf2_per_objfile->all_type_units
7219         = XRESIZEVEC (struct signatured_type *,
7220                       dwarf2_per_objfile->all_type_units,
7221                       dwarf2_per_objfile->n_allocated_type_units);
7222       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7223     }
7224   dwarf2_per_objfile->n_type_units = n_type_units;
7225
7226   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7227                              struct signatured_type);
7228   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7229   sig_type->signature = sig;
7230   sig_type->per_cu.is_debug_types = 1;
7231   if (dwarf2_per_objfile->using_index)
7232     {
7233       sig_type->per_cu.v.quick =
7234         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7235                         struct dwarf2_per_cu_quick_data);
7236     }
7237
7238   if (slot == NULL)
7239     {
7240       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7241                              sig_type, INSERT);
7242     }
7243   gdb_assert (*slot == NULL);
7244   *slot = sig_type;
7245   /* The rest of sig_type must be filled in by the caller.  */
7246   return sig_type;
7247 }
7248
7249 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7250    Fill in SIG_ENTRY with DWO_ENTRY.  */
7251
7252 static void
7253 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7254                                   struct signatured_type *sig_entry,
7255                                   struct dwo_unit *dwo_entry)
7256 {
7257   /* Make sure we're not clobbering something we don't expect to.  */
7258   gdb_assert (! sig_entry->per_cu.queued);
7259   gdb_assert (sig_entry->per_cu.cu == NULL);
7260   if (dwarf2_per_objfile->using_index)
7261     {
7262       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7263       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7264     }
7265   else
7266       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7267   gdb_assert (sig_entry->signature == dwo_entry->signature);
7268   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7269   gdb_assert (sig_entry->type_unit_group == NULL);
7270   gdb_assert (sig_entry->dwo_unit == NULL);
7271
7272   sig_entry->per_cu.section = dwo_entry->section;
7273   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7274   sig_entry->per_cu.length = dwo_entry->length;
7275   sig_entry->per_cu.reading_dwo_directly = 1;
7276   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7277   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7278   sig_entry->dwo_unit = dwo_entry;
7279 }
7280
7281 /* Subroutine of lookup_signatured_type.
7282    If we haven't read the TU yet, create the signatured_type data structure
7283    for a TU to be read in directly from a DWO file, bypassing the stub.
7284    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7285    using .gdb_index, then when reading a CU we want to stay in the DWO file
7286    containing that CU.  Otherwise we could end up reading several other DWO
7287    files (due to comdat folding) to process the transitive closure of all the
7288    mentioned TUs, and that can be slow.  The current DWO file will have every
7289    type signature that it needs.
7290    We only do this for .gdb_index because in the psymtab case we already have
7291    to read all the DWOs to build the type unit groups.  */
7292
7293 static struct signatured_type *
7294 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7295 {
7296   struct dwarf2_per_objfile *dwarf2_per_objfile
7297     = cu->per_cu->dwarf2_per_objfile;
7298   struct objfile *objfile = dwarf2_per_objfile->objfile;
7299   struct dwo_file *dwo_file;
7300   struct dwo_unit find_dwo_entry, *dwo_entry;
7301   struct signatured_type find_sig_entry, *sig_entry;
7302   void **slot;
7303
7304   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7305
7306   /* If TU skeletons have been removed then we may not have read in any
7307      TUs yet.  */
7308   if (dwarf2_per_objfile->signatured_types == NULL)
7309     {
7310       dwarf2_per_objfile->signatured_types
7311         = allocate_signatured_type_table (objfile);
7312     }
7313
7314   /* We only ever need to read in one copy of a signatured type.
7315      Use the global signatured_types array to do our own comdat-folding
7316      of types.  If this is the first time we're reading this TU, and
7317      the TU has an entry in .gdb_index, replace the recorded data from
7318      .gdb_index with this TU.  */
7319
7320   find_sig_entry.signature = sig;
7321   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7322                          &find_sig_entry, INSERT);
7323   sig_entry = (struct signatured_type *) *slot;
7324
7325   /* We can get here with the TU already read, *or* in the process of being
7326      read.  Don't reassign the global entry to point to this DWO if that's
7327      the case.  Also note that if the TU is already being read, it may not
7328      have come from a DWO, the program may be a mix of Fission-compiled
7329      code and non-Fission-compiled code.  */
7330
7331   /* Have we already tried to read this TU?
7332      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7333      needn't exist in the global table yet).  */
7334   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7335     return sig_entry;
7336
7337   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7338      dwo_unit of the TU itself.  */
7339   dwo_file = cu->dwo_unit->dwo_file;
7340
7341   /* Ok, this is the first time we're reading this TU.  */
7342   if (dwo_file->tus == NULL)
7343     return NULL;
7344   find_dwo_entry.signature = sig;
7345   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7346   if (dwo_entry == NULL)
7347     return NULL;
7348
7349   /* If the global table doesn't have an entry for this TU, add one.  */
7350   if (sig_entry == NULL)
7351     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7352
7353   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7354   sig_entry->per_cu.tu_read = 1;
7355   return sig_entry;
7356 }
7357
7358 /* Subroutine of lookup_signatured_type.
7359    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7360    then try the DWP file.  If the TU stub (skeleton) has been removed then
7361    it won't be in .gdb_index.  */
7362
7363 static struct signatured_type *
7364 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7365 {
7366   struct dwarf2_per_objfile *dwarf2_per_objfile
7367     = cu->per_cu->dwarf2_per_objfile;
7368   struct objfile *objfile = dwarf2_per_objfile->objfile;
7369   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7370   struct dwo_unit *dwo_entry;
7371   struct signatured_type find_sig_entry, *sig_entry;
7372   void **slot;
7373
7374   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7375   gdb_assert (dwp_file != NULL);
7376
7377   /* If TU skeletons have been removed then we may not have read in any
7378      TUs yet.  */
7379   if (dwarf2_per_objfile->signatured_types == NULL)
7380     {
7381       dwarf2_per_objfile->signatured_types
7382         = allocate_signatured_type_table (objfile);
7383     }
7384
7385   find_sig_entry.signature = sig;
7386   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7387                          &find_sig_entry, INSERT);
7388   sig_entry = (struct signatured_type *) *slot;
7389
7390   /* Have we already tried to read this TU?
7391      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7392      needn't exist in the global table yet).  */
7393   if (sig_entry != NULL)
7394     return sig_entry;
7395
7396   if (dwp_file->tus == NULL)
7397     return NULL;
7398   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7399                                       sig, 1 /* is_debug_types */);
7400   if (dwo_entry == NULL)
7401     return NULL;
7402
7403   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7404   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7405
7406   return sig_entry;
7407 }
7408
7409 /* Lookup a signature based type for DW_FORM_ref_sig8.
7410    Returns NULL if signature SIG is not present in the table.
7411    It is up to the caller to complain about this.  */
7412
7413 static struct signatured_type *
7414 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7415 {
7416   struct dwarf2_per_objfile *dwarf2_per_objfile
7417     = cu->per_cu->dwarf2_per_objfile;
7418
7419   if (cu->dwo_unit
7420       && dwarf2_per_objfile->using_index)
7421     {
7422       /* We're in a DWO/DWP file, and we're using .gdb_index.
7423          These cases require special processing.  */
7424       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7425         return lookup_dwo_signatured_type (cu, sig);
7426       else
7427         return lookup_dwp_signatured_type (cu, sig);
7428     }
7429   else
7430     {
7431       struct signatured_type find_entry, *entry;
7432
7433       if (dwarf2_per_objfile->signatured_types == NULL)
7434         return NULL;
7435       find_entry.signature = sig;
7436       entry = ((struct signatured_type *)
7437                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7438       return entry;
7439     }
7440 }
7441 \f
7442 /* Low level DIE reading support.  */
7443
7444 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7445
7446 static void
7447 init_cu_die_reader (struct die_reader_specs *reader,
7448                     struct dwarf2_cu *cu,
7449                     struct dwarf2_section_info *section,
7450                     struct dwo_file *dwo_file,
7451                     struct abbrev_table *abbrev_table)
7452 {
7453   gdb_assert (section->readin && section->buffer != NULL);
7454   reader->abfd = get_section_bfd_owner (section);
7455   reader->cu = cu;
7456   reader->dwo_file = dwo_file;
7457   reader->die_section = section;
7458   reader->buffer = section->buffer;
7459   reader->buffer_end = section->buffer + section->size;
7460   reader->comp_dir = NULL;
7461   reader->abbrev_table = abbrev_table;
7462 }
7463
7464 /* Subroutine of init_cutu_and_read_dies to simplify it.
7465    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7466    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7467    already.
7468
7469    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7470    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7471    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7472    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7473    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7474    STUB_COMP_DIR may be non-NULL.
7475    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7476    are filled in with the info of the DIE from the DWO file.
7477    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7478    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7479    kept around for at least as long as *RESULT_READER.
7480
7481    The result is non-zero if a valid (non-dummy) DIE was found.  */
7482
7483 static int
7484 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7485                         struct dwo_unit *dwo_unit,
7486                         struct die_info *stub_comp_unit_die,
7487                         const char *stub_comp_dir,
7488                         struct die_reader_specs *result_reader,
7489                         const gdb_byte **result_info_ptr,
7490                         struct die_info **result_comp_unit_die,
7491                         int *result_has_children,
7492                         abbrev_table_up *result_dwo_abbrev_table)
7493 {
7494   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7495   struct objfile *objfile = dwarf2_per_objfile->objfile;
7496   struct dwarf2_cu *cu = this_cu->cu;
7497   bfd *abfd;
7498   const gdb_byte *begin_info_ptr, *info_ptr;
7499   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7500   int i,num_extra_attrs;
7501   struct dwarf2_section_info *dwo_abbrev_section;
7502   struct attribute *attr;
7503   struct die_info *comp_unit_die;
7504
7505   /* At most one of these may be provided.  */
7506   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7507
7508   /* These attributes aren't processed until later:
7509      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7510      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7511      referenced later.  However, these attributes are found in the stub
7512      which we won't have later.  In order to not impose this complication
7513      on the rest of the code, we read them here and copy them to the
7514      DWO CU/TU die.  */
7515
7516   stmt_list = NULL;
7517   low_pc = NULL;
7518   high_pc = NULL;
7519   ranges = NULL;
7520   comp_dir = NULL;
7521
7522   if (stub_comp_unit_die != NULL)
7523     {
7524       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7525          DWO file.  */
7526       if (! this_cu->is_debug_types)
7527         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7528       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7529       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7530       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7531       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7532
7533       /* There should be a DW_AT_addr_base attribute here (if needed).
7534          We need the value before we can process DW_FORM_GNU_addr_index.  */
7535       cu->addr_base = 0;
7536       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7537       if (attr)
7538         cu->addr_base = DW_UNSND (attr);
7539
7540       /* There should be a DW_AT_ranges_base attribute here (if needed).
7541          We need the value before we can process DW_AT_ranges.  */
7542       cu->ranges_base = 0;
7543       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7544       if (attr)
7545         cu->ranges_base = DW_UNSND (attr);
7546     }
7547   else if (stub_comp_dir != NULL)
7548     {
7549       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7550       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7551       comp_dir->name = DW_AT_comp_dir;
7552       comp_dir->form = DW_FORM_string;
7553       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7554       DW_STRING (comp_dir) = stub_comp_dir;
7555     }
7556
7557   /* Set up for reading the DWO CU/TU.  */
7558   cu->dwo_unit = dwo_unit;
7559   dwarf2_section_info *section = dwo_unit->section;
7560   dwarf2_read_section (objfile, section);
7561   abfd = get_section_bfd_owner (section);
7562   begin_info_ptr = info_ptr = (section->buffer
7563                                + to_underlying (dwo_unit->sect_off));
7564   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7565
7566   if (this_cu->is_debug_types)
7567     {
7568       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7569
7570       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7571                                                 &cu->header, section,
7572                                                 dwo_abbrev_section,
7573                                                 info_ptr, rcuh_kind::TYPE);
7574       /* This is not an assert because it can be caused by bad debug info.  */
7575       if (sig_type->signature != cu->header.signature)
7576         {
7577           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7578                    " TU at offset 0x%x [in module %s]"),
7579                  hex_string (sig_type->signature),
7580                  hex_string (cu->header.signature),
7581                  to_underlying (dwo_unit->sect_off),
7582                  bfd_get_filename (abfd));
7583         }
7584       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7585       /* For DWOs coming from DWP files, we don't know the CU length
7586          nor the type's offset in the TU until now.  */
7587       dwo_unit->length = get_cu_length (&cu->header);
7588       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7589
7590       /* Establish the type offset that can be used to lookup the type.
7591          For DWO files, we don't know it until now.  */
7592       sig_type->type_offset_in_section
7593         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7594     }
7595   else
7596     {
7597       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7598                                                 &cu->header, section,
7599                                                 dwo_abbrev_section,
7600                                                 info_ptr, rcuh_kind::COMPILE);
7601       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7602       /* For DWOs coming from DWP files, we don't know the CU length
7603          until now.  */
7604       dwo_unit->length = get_cu_length (&cu->header);
7605     }
7606
7607   *result_dwo_abbrev_table
7608     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7609                                cu->header.abbrev_sect_off);
7610   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7611                       result_dwo_abbrev_table->get ());
7612
7613   /* Read in the die, but leave space to copy over the attributes
7614      from the stub.  This has the benefit of simplifying the rest of
7615      the code - all the work to maintain the illusion of a single
7616      DW_TAG_{compile,type}_unit DIE is done here.  */
7617   num_extra_attrs = ((stmt_list != NULL)
7618                      + (low_pc != NULL)
7619                      + (high_pc != NULL)
7620                      + (ranges != NULL)
7621                      + (comp_dir != NULL));
7622   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7623                               result_has_children, num_extra_attrs);
7624
7625   /* Copy over the attributes from the stub to the DIE we just read in.  */
7626   comp_unit_die = *result_comp_unit_die;
7627   i = comp_unit_die->num_attrs;
7628   if (stmt_list != NULL)
7629     comp_unit_die->attrs[i++] = *stmt_list;
7630   if (low_pc != NULL)
7631     comp_unit_die->attrs[i++] = *low_pc;
7632   if (high_pc != NULL)
7633     comp_unit_die->attrs[i++] = *high_pc;
7634   if (ranges != NULL)
7635     comp_unit_die->attrs[i++] = *ranges;
7636   if (comp_dir != NULL)
7637     comp_unit_die->attrs[i++] = *comp_dir;
7638   comp_unit_die->num_attrs += num_extra_attrs;
7639
7640   if (dwarf_die_debug)
7641     {
7642       fprintf_unfiltered (gdb_stdlog,
7643                           "Read die from %s@0x%x of %s:\n",
7644                           get_section_name (section),
7645                           (unsigned) (begin_info_ptr - section->buffer),
7646                           bfd_get_filename (abfd));
7647       dump_die (comp_unit_die, dwarf_die_debug);
7648     }
7649
7650   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7651      TUs by skipping the stub and going directly to the entry in the DWO file.
7652      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7653      to get it via circuitous means.  Blech.  */
7654   if (comp_dir != NULL)
7655     result_reader->comp_dir = DW_STRING (comp_dir);
7656
7657   /* Skip dummy compilation units.  */
7658   if (info_ptr >= begin_info_ptr + dwo_unit->length
7659       || peek_abbrev_code (abfd, info_ptr) == 0)
7660     return 0;
7661
7662   *result_info_ptr = info_ptr;
7663   return 1;
7664 }
7665
7666 /* Subroutine of init_cutu_and_read_dies to simplify it.
7667    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7668    Returns NULL if the specified DWO unit cannot be found.  */
7669
7670 static struct dwo_unit *
7671 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7672                  struct die_info *comp_unit_die)
7673 {
7674   struct dwarf2_cu *cu = this_cu->cu;
7675   ULONGEST signature;
7676   struct dwo_unit *dwo_unit;
7677   const char *comp_dir, *dwo_name;
7678
7679   gdb_assert (cu != NULL);
7680
7681   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7682   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7683   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7684
7685   if (this_cu->is_debug_types)
7686     {
7687       struct signatured_type *sig_type;
7688
7689       /* Since this_cu is the first member of struct signatured_type,
7690          we can go from a pointer to one to a pointer to the other.  */
7691       sig_type = (struct signatured_type *) this_cu;
7692       signature = sig_type->signature;
7693       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7694     }
7695   else
7696     {
7697       struct attribute *attr;
7698
7699       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7700       if (! attr)
7701         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7702                  " [in module %s]"),
7703                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7704       signature = DW_UNSND (attr);
7705       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7706                                        signature);
7707     }
7708
7709   return dwo_unit;
7710 }
7711
7712 /* Subroutine of init_cutu_and_read_dies to simplify it.
7713    See it for a description of the parameters.
7714    Read a TU directly from a DWO file, bypassing the stub.  */
7715
7716 static void
7717 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7718                            int use_existing_cu, int keep,
7719                            die_reader_func_ftype *die_reader_func,
7720                            void *data)
7721 {
7722   std::unique_ptr<dwarf2_cu> new_cu;
7723   struct signatured_type *sig_type;
7724   struct die_reader_specs reader;
7725   const gdb_byte *info_ptr;
7726   struct die_info *comp_unit_die;
7727   int has_children;
7728   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7729
7730   /* Verify we can do the following downcast, and that we have the
7731      data we need.  */
7732   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7733   sig_type = (struct signatured_type *) this_cu;
7734   gdb_assert (sig_type->dwo_unit != NULL);
7735
7736   if (use_existing_cu && this_cu->cu != NULL)
7737     {
7738       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7739       /* There's no need to do the rereading_dwo_cu handling that
7740          init_cutu_and_read_dies does since we don't read the stub.  */
7741     }
7742   else
7743     {
7744       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7745       gdb_assert (this_cu->cu == NULL);
7746       new_cu.reset (new dwarf2_cu (this_cu));
7747     }
7748
7749   /* A future optimization, if needed, would be to use an existing
7750      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7751      could share abbrev tables.  */
7752
7753   /* The abbreviation table used by READER, this must live at least as long as
7754      READER.  */
7755   abbrev_table_up dwo_abbrev_table;
7756
7757   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7758                               NULL /* stub_comp_unit_die */,
7759                               sig_type->dwo_unit->dwo_file->comp_dir,
7760                               &reader, &info_ptr,
7761                               &comp_unit_die, &has_children,
7762                               &dwo_abbrev_table) == 0)
7763     {
7764       /* Dummy die.  */
7765       return;
7766     }
7767
7768   /* All the "real" work is done here.  */
7769   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7770
7771   /* This duplicates the code in init_cutu_and_read_dies,
7772      but the alternative is making the latter more complex.
7773      This function is only for the special case of using DWO files directly:
7774      no point in overly complicating the general case just to handle this.  */
7775   if (new_cu != NULL && keep)
7776     {
7777       /* Link this CU into read_in_chain.  */
7778       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7779       dwarf2_per_objfile->read_in_chain = this_cu;
7780       /* The chain owns it now.  */
7781       new_cu.release ();
7782     }
7783 }
7784
7785 /* Initialize a CU (or TU) and read its DIEs.
7786    If the CU defers to a DWO file, read the DWO file as well.
7787
7788    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7789    Otherwise the table specified in the comp unit header is read in and used.
7790    This is an optimization for when we already have the abbrev table.
7791
7792    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7793    Otherwise, a new CU is allocated with xmalloc.
7794
7795    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7796    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7797
7798    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7799    linker) then DIE_READER_FUNC will not get called.  */
7800
7801 static void
7802 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7803                          struct abbrev_table *abbrev_table,
7804                          int use_existing_cu, int keep,
7805                          die_reader_func_ftype *die_reader_func,
7806                          void *data)
7807 {
7808   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7809   struct objfile *objfile = dwarf2_per_objfile->objfile;
7810   struct dwarf2_section_info *section = this_cu->section;
7811   bfd *abfd = get_section_bfd_owner (section);
7812   struct dwarf2_cu *cu;
7813   const gdb_byte *begin_info_ptr, *info_ptr;
7814   struct die_reader_specs reader;
7815   struct die_info *comp_unit_die;
7816   int has_children;
7817   struct attribute *attr;
7818   struct signatured_type *sig_type = NULL;
7819   struct dwarf2_section_info *abbrev_section;
7820   /* Non-zero if CU currently points to a DWO file and we need to
7821      reread it.  When this happens we need to reread the skeleton die
7822      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7823   int rereading_dwo_cu = 0;
7824
7825   if (dwarf_die_debug)
7826     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7827                         this_cu->is_debug_types ? "type" : "comp",
7828                         to_underlying (this_cu->sect_off));
7829
7830   if (use_existing_cu)
7831     gdb_assert (keep);
7832
7833   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7834      file (instead of going through the stub), short-circuit all of this.  */
7835   if (this_cu->reading_dwo_directly)
7836     {
7837       /* Narrow down the scope of possibilities to have to understand.  */
7838       gdb_assert (this_cu->is_debug_types);
7839       gdb_assert (abbrev_table == NULL);
7840       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7841                                  die_reader_func, data);
7842       return;
7843     }
7844
7845   /* This is cheap if the section is already read in.  */
7846   dwarf2_read_section (objfile, section);
7847
7848   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7849
7850   abbrev_section = get_abbrev_section_for_cu (this_cu);
7851
7852   std::unique_ptr<dwarf2_cu> new_cu;
7853   if (use_existing_cu && this_cu->cu != NULL)
7854     {
7855       cu = this_cu->cu;
7856       /* If this CU is from a DWO file we need to start over, we need to
7857          refetch the attributes from the skeleton CU.
7858          This could be optimized by retrieving those attributes from when we
7859          were here the first time: the previous comp_unit_die was stored in
7860          comp_unit_obstack.  But there's no data yet that we need this
7861          optimization.  */
7862       if (cu->dwo_unit != NULL)
7863         rereading_dwo_cu = 1;
7864     }
7865   else
7866     {
7867       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7868       gdb_assert (this_cu->cu == NULL);
7869       new_cu.reset (new dwarf2_cu (this_cu));
7870       cu = new_cu.get ();
7871     }
7872
7873   /* Get the header.  */
7874   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7875     {
7876       /* We already have the header, there's no need to read it in again.  */
7877       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7878     }
7879   else
7880     {
7881       if (this_cu->is_debug_types)
7882         {
7883           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7884                                                     &cu->header, section,
7885                                                     abbrev_section, info_ptr,
7886                                                     rcuh_kind::TYPE);
7887
7888           /* Since per_cu is the first member of struct signatured_type,
7889              we can go from a pointer to one to a pointer to the other.  */
7890           sig_type = (struct signatured_type *) this_cu;
7891           gdb_assert (sig_type->signature == cu->header.signature);
7892           gdb_assert (sig_type->type_offset_in_tu
7893                       == cu->header.type_cu_offset_in_tu);
7894           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7895
7896           /* LENGTH has not been set yet for type units if we're
7897              using .gdb_index.  */
7898           this_cu->length = get_cu_length (&cu->header);
7899
7900           /* Establish the type offset that can be used to lookup the type.  */
7901           sig_type->type_offset_in_section =
7902             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7903
7904           this_cu->dwarf_version = cu->header.version;
7905         }
7906       else
7907         {
7908           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7909                                                     &cu->header, section,
7910                                                     abbrev_section,
7911                                                     info_ptr,
7912                                                     rcuh_kind::COMPILE);
7913
7914           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7915           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7916           this_cu->dwarf_version = cu->header.version;
7917         }
7918     }
7919
7920   /* Skip dummy compilation units.  */
7921   if (info_ptr >= begin_info_ptr + this_cu->length
7922       || peek_abbrev_code (abfd, info_ptr) == 0)
7923     return;
7924
7925   /* If we don't have them yet, read the abbrevs for this compilation unit.
7926      And if we need to read them now, make sure they're freed when we're
7927      done (own the table through ABBREV_TABLE_HOLDER).  */
7928   abbrev_table_up abbrev_table_holder;
7929   if (abbrev_table != NULL)
7930     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7931   else
7932     {
7933       abbrev_table_holder
7934         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7935                                    cu->header.abbrev_sect_off);
7936       abbrev_table = abbrev_table_holder.get ();
7937     }
7938
7939   /* Read the top level CU/TU die.  */
7940   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7941   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7942
7943   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7944      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7945      table from the DWO file and pass the ownership over to us.  It will be
7946      referenced from READER, so we must make sure to free it after we're done
7947      with READER.
7948
7949      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7950      DWO CU, that this test will fail (the attribute will not be present).  */
7951   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7952   abbrev_table_up dwo_abbrev_table;
7953   if (attr)
7954     {
7955       struct dwo_unit *dwo_unit;
7956       struct die_info *dwo_comp_unit_die;
7957
7958       if (has_children)
7959         {
7960           complaint (&symfile_complaints,
7961                      _("compilation unit with DW_AT_GNU_dwo_name"
7962                        " has children (offset 0x%x) [in module %s]"),
7963                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7964         }
7965       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7966       if (dwo_unit != NULL)
7967         {
7968           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7969                                       comp_unit_die, NULL,
7970                                       &reader, &info_ptr,
7971                                       &dwo_comp_unit_die, &has_children,
7972                                       &dwo_abbrev_table) == 0)
7973             {
7974               /* Dummy die.  */
7975               return;
7976             }
7977           comp_unit_die = dwo_comp_unit_die;
7978         }
7979       else
7980         {
7981           /* Yikes, we couldn't find the rest of the DIE, we only have
7982              the stub.  A complaint has already been logged.  There's
7983              not much more we can do except pass on the stub DIE to
7984              die_reader_func.  We don't want to throw an error on bad
7985              debug info.  */
7986         }
7987     }
7988
7989   /* All of the above is setup for this call.  Yikes.  */
7990   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7991
7992   /* Done, clean up.  */
7993   if (new_cu != NULL && keep)
7994     {
7995       /* Link this CU into read_in_chain.  */
7996       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7997       dwarf2_per_objfile->read_in_chain = this_cu;
7998       /* The chain owns it now.  */
7999       new_cu.release ();
8000     }
8001 }
8002
8003 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8004    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8005    to have already done the lookup to find the DWO file).
8006
8007    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8008    THIS_CU->is_debug_types, but nothing else.
8009
8010    We fill in THIS_CU->length.
8011
8012    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8013    linker) then DIE_READER_FUNC will not get called.
8014
8015    THIS_CU->cu is always freed when done.
8016    This is done in order to not leave THIS_CU->cu in a state where we have
8017    to care whether it refers to the "main" CU or the DWO CU.  */
8018
8019 static void
8020 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8021                                    struct dwo_file *dwo_file,
8022                                    die_reader_func_ftype *die_reader_func,
8023                                    void *data)
8024 {
8025   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8026   struct objfile *objfile = dwarf2_per_objfile->objfile;
8027   struct dwarf2_section_info *section = this_cu->section;
8028   bfd *abfd = get_section_bfd_owner (section);
8029   struct dwarf2_section_info *abbrev_section;
8030   const gdb_byte *begin_info_ptr, *info_ptr;
8031   struct die_reader_specs reader;
8032   struct die_info *comp_unit_die;
8033   int has_children;
8034
8035   if (dwarf_die_debug)
8036     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
8037                         this_cu->is_debug_types ? "type" : "comp",
8038                         to_underlying (this_cu->sect_off));
8039
8040   gdb_assert (this_cu->cu == NULL);
8041
8042   abbrev_section = (dwo_file != NULL
8043                     ? &dwo_file->sections.abbrev
8044                     : get_abbrev_section_for_cu (this_cu));
8045
8046   /* This is cheap if the section is already read in.  */
8047   dwarf2_read_section (objfile, section);
8048
8049   struct dwarf2_cu cu (this_cu);
8050
8051   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8052   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8053                                             &cu.header, section,
8054                                             abbrev_section, info_ptr,
8055                                             (this_cu->is_debug_types
8056                                              ? rcuh_kind::TYPE
8057                                              : rcuh_kind::COMPILE));
8058
8059   this_cu->length = get_cu_length (&cu.header);
8060
8061   /* Skip dummy compilation units.  */
8062   if (info_ptr >= begin_info_ptr + this_cu->length
8063       || peek_abbrev_code (abfd, info_ptr) == 0)
8064     return;
8065
8066   abbrev_table_up abbrev_table
8067     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8068                                cu.header.abbrev_sect_off);
8069
8070   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8071   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8072
8073   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8074 }
8075
8076 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8077    does not lookup the specified DWO file.
8078    This cannot be used to read DWO files.
8079
8080    THIS_CU->cu is always freed when done.
8081    This is done in order to not leave THIS_CU->cu in a state where we have
8082    to care whether it refers to the "main" CU or the DWO CU.
8083    We can revisit this if the data shows there's a performance issue.  */
8084
8085 static void
8086 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8087                                 die_reader_func_ftype *die_reader_func,
8088                                 void *data)
8089 {
8090   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8091 }
8092 \f
8093 /* Type Unit Groups.
8094
8095    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8096    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8097    so that all types coming from the same compilation (.o file) are grouped
8098    together.  A future step could be to put the types in the same symtab as
8099    the CU the types ultimately came from.  */
8100
8101 static hashval_t
8102 hash_type_unit_group (const void *item)
8103 {
8104   const struct type_unit_group *tu_group
8105     = (const struct type_unit_group *) item;
8106
8107   return hash_stmt_list_entry (&tu_group->hash);
8108 }
8109
8110 static int
8111 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8112 {
8113   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8114   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8115
8116   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8117 }
8118
8119 /* Allocate a hash table for type unit groups.  */
8120
8121 static htab_t
8122 allocate_type_unit_groups_table (struct objfile *objfile)
8123 {
8124   return htab_create_alloc_ex (3,
8125                                hash_type_unit_group,
8126                                eq_type_unit_group,
8127                                NULL,
8128                                &objfile->objfile_obstack,
8129                                hashtab_obstack_allocate,
8130                                dummy_obstack_deallocate);
8131 }
8132
8133 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8134    partial symtabs.  We combine several TUs per psymtab to not let the size
8135    of any one psymtab grow too big.  */
8136 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8137 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8138
8139 /* Helper routine for get_type_unit_group.
8140    Create the type_unit_group object used to hold one or more TUs.  */
8141
8142 static struct type_unit_group *
8143 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8144 {
8145   struct dwarf2_per_objfile *dwarf2_per_objfile
8146     = cu->per_cu->dwarf2_per_objfile;
8147   struct objfile *objfile = dwarf2_per_objfile->objfile;
8148   struct dwarf2_per_cu_data *per_cu;
8149   struct type_unit_group *tu_group;
8150
8151   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8152                              struct type_unit_group);
8153   per_cu = &tu_group->per_cu;
8154   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8155
8156   if (dwarf2_per_objfile->using_index)
8157     {
8158       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8159                                         struct dwarf2_per_cu_quick_data);
8160     }
8161   else
8162     {
8163       unsigned int line_offset = to_underlying (line_offset_struct);
8164       struct partial_symtab *pst;
8165       char *name;
8166
8167       /* Give the symtab a useful name for debug purposes.  */
8168       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8169         name = xstrprintf ("<type_units_%d>",
8170                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8171       else
8172         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8173
8174       pst = create_partial_symtab (per_cu, name);
8175       pst->anonymous = 1;
8176
8177       xfree (name);
8178     }
8179
8180   tu_group->hash.dwo_unit = cu->dwo_unit;
8181   tu_group->hash.line_sect_off = line_offset_struct;
8182
8183   return tu_group;
8184 }
8185
8186 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8187    STMT_LIST is a DW_AT_stmt_list attribute.  */
8188
8189 static struct type_unit_group *
8190 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8191 {
8192   struct dwarf2_per_objfile *dwarf2_per_objfile
8193     = cu->per_cu->dwarf2_per_objfile;
8194   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8195   struct type_unit_group *tu_group;
8196   void **slot;
8197   unsigned int line_offset;
8198   struct type_unit_group type_unit_group_for_lookup;
8199
8200   if (dwarf2_per_objfile->type_unit_groups == NULL)
8201     {
8202       dwarf2_per_objfile->type_unit_groups =
8203         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8204     }
8205
8206   /* Do we need to create a new group, or can we use an existing one?  */
8207
8208   if (stmt_list)
8209     {
8210       line_offset = DW_UNSND (stmt_list);
8211       ++tu_stats->nr_symtab_sharers;
8212     }
8213   else
8214     {
8215       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8216          We can do various things here like create one group per TU or
8217          spread them over multiple groups to split up the expansion work.
8218          To avoid worst case scenarios (too many groups or too large groups)
8219          we, umm, group them in bunches.  */
8220       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8221                      | (tu_stats->nr_stmt_less_type_units
8222                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8223       ++tu_stats->nr_stmt_less_type_units;
8224     }
8225
8226   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8227   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8228   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8229                          &type_unit_group_for_lookup, INSERT);
8230   if (*slot != NULL)
8231     {
8232       tu_group = (struct type_unit_group *) *slot;
8233       gdb_assert (tu_group != NULL);
8234     }
8235   else
8236     {
8237       sect_offset line_offset_struct = (sect_offset) line_offset;
8238       tu_group = create_type_unit_group (cu, line_offset_struct);
8239       *slot = tu_group;
8240       ++tu_stats->nr_symtabs;
8241     }
8242
8243   return tu_group;
8244 }
8245 \f
8246 /* Partial symbol tables.  */
8247
8248 /* Create a psymtab named NAME and assign it to PER_CU.
8249
8250    The caller must fill in the following details:
8251    dirname, textlow, texthigh.  */
8252
8253 static struct partial_symtab *
8254 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8255 {
8256   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8257   struct partial_symtab *pst;
8258
8259   pst = start_psymtab_common (objfile, name, 0,
8260                               objfile->global_psymbols,
8261                               objfile->static_psymbols);
8262
8263   pst->psymtabs_addrmap_supported = 1;
8264
8265   /* This is the glue that links PST into GDB's symbol API.  */
8266   pst->read_symtab_private = per_cu;
8267   pst->read_symtab = dwarf2_read_symtab;
8268   per_cu->v.psymtab = pst;
8269
8270   return pst;
8271 }
8272
8273 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8274    type.  */
8275
8276 struct process_psymtab_comp_unit_data
8277 {
8278   /* True if we are reading a DW_TAG_partial_unit.  */
8279
8280   int want_partial_unit;
8281
8282   /* The "pretend" language that is used if the CU doesn't declare a
8283      language.  */
8284
8285   enum language pretend_language;
8286 };
8287
8288 /* die_reader_func for process_psymtab_comp_unit.  */
8289
8290 static void
8291 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8292                                   const gdb_byte *info_ptr,
8293                                   struct die_info *comp_unit_die,
8294                                   int has_children,
8295                                   void *data)
8296 {
8297   struct dwarf2_cu *cu = reader->cu;
8298   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8299   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8300   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8301   CORE_ADDR baseaddr;
8302   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8303   struct partial_symtab *pst;
8304   enum pc_bounds_kind cu_bounds_kind;
8305   const char *filename;
8306   struct process_psymtab_comp_unit_data *info
8307     = (struct process_psymtab_comp_unit_data *) data;
8308
8309   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8310     return;
8311
8312   gdb_assert (! per_cu->is_debug_types);
8313
8314   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8315
8316   cu->list_in_scope = &file_symbols;
8317
8318   /* Allocate a new partial symbol table structure.  */
8319   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8320   if (filename == NULL)
8321     filename = "";
8322
8323   pst = create_partial_symtab (per_cu, filename);
8324
8325   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8326   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8327
8328   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8329
8330   dwarf2_find_base_address (comp_unit_die, cu);
8331
8332   /* Possibly set the default values of LOWPC and HIGHPC from
8333      `DW_AT_ranges'.  */
8334   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8335                                          &best_highpc, cu, pst);
8336   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8337     /* Store the contiguous range if it is not empty; it can be empty for
8338        CUs with no code.  */
8339     addrmap_set_empty (objfile->psymtabs_addrmap,
8340                        gdbarch_adjust_dwarf2_addr (gdbarch,
8341                                                    best_lowpc + baseaddr),
8342                        gdbarch_adjust_dwarf2_addr (gdbarch,
8343                                                    best_highpc + baseaddr) - 1,
8344                        pst);
8345
8346   /* Check if comp unit has_children.
8347      If so, read the rest of the partial symbols from this comp unit.
8348      If not, there's no more debug_info for this comp unit.  */
8349   if (has_children)
8350     {
8351       struct partial_die_info *first_die;
8352       CORE_ADDR lowpc, highpc;
8353
8354       lowpc = ((CORE_ADDR) -1);
8355       highpc = ((CORE_ADDR) 0);
8356
8357       first_die = load_partial_dies (reader, info_ptr, 1);
8358
8359       scan_partial_symbols (first_die, &lowpc, &highpc,
8360                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8361
8362       /* If we didn't find a lowpc, set it to highpc to avoid
8363          complaints from `maint check'.  */
8364       if (lowpc == ((CORE_ADDR) -1))
8365         lowpc = highpc;
8366
8367       /* If the compilation unit didn't have an explicit address range,
8368          then use the information extracted from its child dies.  */
8369       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8370         {
8371           best_lowpc = lowpc;
8372           best_highpc = highpc;
8373         }
8374     }
8375   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8376   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8377
8378   end_psymtab_common (objfile, pst);
8379
8380   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8381     {
8382       int i;
8383       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8384       struct dwarf2_per_cu_data *iter;
8385
8386       /* Fill in 'dependencies' here; we fill in 'users' in a
8387          post-pass.  */
8388       pst->number_of_dependencies = len;
8389       pst->dependencies =
8390         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8391       for (i = 0;
8392            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8393                         i, iter);
8394            ++i)
8395         pst->dependencies[i] = iter->v.psymtab;
8396
8397       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8398     }
8399
8400   /* Get the list of files included in the current compilation unit,
8401      and build a psymtab for each of them.  */
8402   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8403
8404   if (dwarf_read_debug)
8405     {
8406       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8407
8408       fprintf_unfiltered (gdb_stdlog,
8409                           "Psymtab for %s unit @0x%x: %s - %s"
8410                           ", %d global, %d static syms\n",
8411                           per_cu->is_debug_types ? "type" : "comp",
8412                           to_underlying (per_cu->sect_off),
8413                           paddress (gdbarch, pst->textlow),
8414                           paddress (gdbarch, pst->texthigh),
8415                           pst->n_global_syms, pst->n_static_syms);
8416     }
8417 }
8418
8419 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8420    Process compilation unit THIS_CU for a psymtab.  */
8421
8422 static void
8423 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8424                            int want_partial_unit,
8425                            enum language pretend_language)
8426 {
8427   /* If this compilation unit was already read in, free the
8428      cached copy in order to read it in again.  This is
8429      necessary because we skipped some symbols when we first
8430      read in the compilation unit (see load_partial_dies).
8431      This problem could be avoided, but the benefit is unclear.  */
8432   if (this_cu->cu != NULL)
8433     free_one_cached_comp_unit (this_cu);
8434
8435   if (this_cu->is_debug_types)
8436     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8437                              NULL);
8438   else
8439     {
8440       process_psymtab_comp_unit_data info;
8441       info.want_partial_unit = want_partial_unit;
8442       info.pretend_language = pretend_language;
8443       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8444                                process_psymtab_comp_unit_reader, &info);
8445     }
8446
8447   /* Age out any secondary CUs.  */
8448   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8449 }
8450
8451 /* Reader function for build_type_psymtabs.  */
8452
8453 static void
8454 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8455                             const gdb_byte *info_ptr,
8456                             struct die_info *type_unit_die,
8457                             int has_children,
8458                             void *data)
8459 {
8460   struct dwarf2_per_objfile *dwarf2_per_objfile
8461     = reader->cu->per_cu->dwarf2_per_objfile;
8462   struct objfile *objfile = dwarf2_per_objfile->objfile;
8463   struct dwarf2_cu *cu = reader->cu;
8464   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8465   struct signatured_type *sig_type;
8466   struct type_unit_group *tu_group;
8467   struct attribute *attr;
8468   struct partial_die_info *first_die;
8469   CORE_ADDR lowpc, highpc;
8470   struct partial_symtab *pst;
8471
8472   gdb_assert (data == NULL);
8473   gdb_assert (per_cu->is_debug_types);
8474   sig_type = (struct signatured_type *) per_cu;
8475
8476   if (! has_children)
8477     return;
8478
8479   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8480   tu_group = get_type_unit_group (cu, attr);
8481
8482   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8483
8484   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8485   cu->list_in_scope = &file_symbols;
8486   pst = create_partial_symtab (per_cu, "");
8487   pst->anonymous = 1;
8488
8489   first_die = load_partial_dies (reader, info_ptr, 1);
8490
8491   lowpc = (CORE_ADDR) -1;
8492   highpc = (CORE_ADDR) 0;
8493   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8494
8495   end_psymtab_common (objfile, pst);
8496 }
8497
8498 /* Struct used to sort TUs by their abbreviation table offset.  */
8499
8500 struct tu_abbrev_offset
8501 {
8502   struct signatured_type *sig_type;
8503   sect_offset abbrev_offset;
8504 };
8505
8506 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8507
8508 static int
8509 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8510 {
8511   const struct tu_abbrev_offset * const *a
8512     = (const struct tu_abbrev_offset * const*) ap;
8513   const struct tu_abbrev_offset * const *b
8514     = (const struct tu_abbrev_offset * const*) bp;
8515   sect_offset aoff = (*a)->abbrev_offset;
8516   sect_offset boff = (*b)->abbrev_offset;
8517
8518   return (aoff > boff) - (aoff < boff);
8519 }
8520
8521 /* Efficiently read all the type units.
8522    This does the bulk of the work for build_type_psymtabs.
8523
8524    The efficiency is because we sort TUs by the abbrev table they use and
8525    only read each abbrev table once.  In one program there are 200K TUs
8526    sharing 8K abbrev tables.
8527
8528    The main purpose of this function is to support building the
8529    dwarf2_per_objfile->type_unit_groups table.
8530    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8531    can collapse the search space by grouping them by stmt_list.
8532    The savings can be significant, in the same program from above the 200K TUs
8533    share 8K stmt_list tables.
8534
8535    FUNC is expected to call get_type_unit_group, which will create the
8536    struct type_unit_group if necessary and add it to
8537    dwarf2_per_objfile->type_unit_groups.  */
8538
8539 static void
8540 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8541 {
8542   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8543   struct cleanup *cleanups;
8544   abbrev_table_up abbrev_table;
8545   sect_offset abbrev_offset;
8546   struct tu_abbrev_offset *sorted_by_abbrev;
8547   int i;
8548
8549   /* It's up to the caller to not call us multiple times.  */
8550   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8551
8552   if (dwarf2_per_objfile->n_type_units == 0)
8553     return;
8554
8555   /* TUs typically share abbrev tables, and there can be way more TUs than
8556      abbrev tables.  Sort by abbrev table to reduce the number of times we
8557      read each abbrev table in.
8558      Alternatives are to punt or to maintain a cache of abbrev tables.
8559      This is simpler and efficient enough for now.
8560
8561      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8562      symtab to use).  Typically TUs with the same abbrev offset have the same
8563      stmt_list value too so in practice this should work well.
8564
8565      The basic algorithm here is:
8566
8567       sort TUs by abbrev table
8568       for each TU with same abbrev table:
8569         read abbrev table if first user
8570         read TU top level DIE
8571           [IWBN if DWO skeletons had DW_AT_stmt_list]
8572         call FUNC  */
8573
8574   if (dwarf_read_debug)
8575     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8576
8577   /* Sort in a separate table to maintain the order of all_type_units
8578      for .gdb_index: TU indices directly index all_type_units.  */
8579   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8580                               dwarf2_per_objfile->n_type_units);
8581   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8582     {
8583       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8584
8585       sorted_by_abbrev[i].sig_type = sig_type;
8586       sorted_by_abbrev[i].abbrev_offset =
8587         read_abbrev_offset (dwarf2_per_objfile,
8588                             sig_type->per_cu.section,
8589                             sig_type->per_cu.sect_off);
8590     }
8591   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8592   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8593          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8594
8595   abbrev_offset = (sect_offset) ~(unsigned) 0;
8596
8597   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8598     {
8599       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8600
8601       /* Switch to the next abbrev table if necessary.  */
8602       if (abbrev_table == NULL
8603           || tu->abbrev_offset != abbrev_offset)
8604         {
8605           abbrev_offset = tu->abbrev_offset;
8606           abbrev_table =
8607             abbrev_table_read_table (dwarf2_per_objfile,
8608                                      &dwarf2_per_objfile->abbrev,
8609                                      abbrev_offset);
8610           ++tu_stats->nr_uniq_abbrev_tables;
8611         }
8612
8613       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8614                                0, 0, build_type_psymtabs_reader, NULL);
8615     }
8616
8617   do_cleanups (cleanups);
8618 }
8619
8620 /* Print collected type unit statistics.  */
8621
8622 static void
8623 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8624 {
8625   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8626
8627   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8628   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8629                       dwarf2_per_objfile->n_type_units);
8630   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8631                       tu_stats->nr_uniq_abbrev_tables);
8632   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8633                       tu_stats->nr_symtabs);
8634   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8635                       tu_stats->nr_symtab_sharers);
8636   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8637                       tu_stats->nr_stmt_less_type_units);
8638   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8639                       tu_stats->nr_all_type_units_reallocs);
8640 }
8641
8642 /* Traversal function for build_type_psymtabs.  */
8643
8644 static int
8645 build_type_psymtab_dependencies (void **slot, void *info)
8646 {
8647   struct dwarf2_per_objfile *dwarf2_per_objfile
8648     = (struct dwarf2_per_objfile *) info;
8649   struct objfile *objfile = dwarf2_per_objfile->objfile;
8650   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8651   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8652   struct partial_symtab *pst = per_cu->v.psymtab;
8653   int len = VEC_length (sig_type_ptr, tu_group->tus);
8654   struct signatured_type *iter;
8655   int i;
8656
8657   gdb_assert (len > 0);
8658   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8659
8660   pst->number_of_dependencies = len;
8661   pst->dependencies =
8662     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8663   for (i = 0;
8664        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8665        ++i)
8666     {
8667       gdb_assert (iter->per_cu.is_debug_types);
8668       pst->dependencies[i] = iter->per_cu.v.psymtab;
8669       iter->type_unit_group = tu_group;
8670     }
8671
8672   VEC_free (sig_type_ptr, tu_group->tus);
8673
8674   return 1;
8675 }
8676
8677 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8678    Build partial symbol tables for the .debug_types comp-units.  */
8679
8680 static void
8681 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8682 {
8683   if (! create_all_type_units (dwarf2_per_objfile))
8684     return;
8685
8686   build_type_psymtabs_1 (dwarf2_per_objfile);
8687 }
8688
8689 /* Traversal function for process_skeletonless_type_unit.
8690    Read a TU in a DWO file and build partial symbols for it.  */
8691
8692 static int
8693 process_skeletonless_type_unit (void **slot, void *info)
8694 {
8695   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8696   struct dwarf2_per_objfile *dwarf2_per_objfile
8697     = (struct dwarf2_per_objfile *) info;
8698   struct signatured_type find_entry, *entry;
8699
8700   /* If this TU doesn't exist in the global table, add it and read it in.  */
8701
8702   if (dwarf2_per_objfile->signatured_types == NULL)
8703     {
8704       dwarf2_per_objfile->signatured_types
8705         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8706     }
8707
8708   find_entry.signature = dwo_unit->signature;
8709   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8710                          INSERT);
8711   /* If we've already seen this type there's nothing to do.  What's happening
8712      is we're doing our own version of comdat-folding here.  */
8713   if (*slot != NULL)
8714     return 1;
8715
8716   /* This does the job that create_all_type_units would have done for
8717      this TU.  */
8718   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8719   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8720   *slot = entry;
8721
8722   /* This does the job that build_type_psymtabs_1 would have done.  */
8723   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8724                            build_type_psymtabs_reader, NULL);
8725
8726   return 1;
8727 }
8728
8729 /* Traversal function for process_skeletonless_type_units.  */
8730
8731 static int
8732 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8733 {
8734   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8735
8736   if (dwo_file->tus != NULL)
8737     {
8738       htab_traverse_noresize (dwo_file->tus,
8739                               process_skeletonless_type_unit, info);
8740     }
8741
8742   return 1;
8743 }
8744
8745 /* Scan all TUs of DWO files, verifying we've processed them.
8746    This is needed in case a TU was emitted without its skeleton.
8747    Note: This can't be done until we know what all the DWO files are.  */
8748
8749 static void
8750 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8751 {
8752   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8753   if (get_dwp_file (dwarf2_per_objfile) == NULL
8754       && dwarf2_per_objfile->dwo_files != NULL)
8755     {
8756       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8757                               process_dwo_file_for_skeletonless_type_units,
8758                               dwarf2_per_objfile);
8759     }
8760 }
8761
8762 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8763
8764 static void
8765 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8766 {
8767   int i;
8768
8769   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8770     {
8771       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8772       struct partial_symtab *pst = per_cu->v.psymtab;
8773       int j;
8774
8775       if (pst == NULL)
8776         continue;
8777
8778       for (j = 0; j < pst->number_of_dependencies; ++j)
8779         {
8780           /* Set the 'user' field only if it is not already set.  */
8781           if (pst->dependencies[j]->user == NULL)
8782             pst->dependencies[j]->user = pst;
8783         }
8784     }
8785 }
8786
8787 /* Build the partial symbol table by doing a quick pass through the
8788    .debug_info and .debug_abbrev sections.  */
8789
8790 static void
8791 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8792 {
8793   struct cleanup *back_to;
8794   int i;
8795   struct objfile *objfile = dwarf2_per_objfile->objfile;
8796
8797   if (dwarf_read_debug)
8798     {
8799       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8800                           objfile_name (objfile));
8801     }
8802
8803   dwarf2_per_objfile->reading_partial_symbols = 1;
8804
8805   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8806
8807   /* Any cached compilation units will be linked by the per-objfile
8808      read_in_chain.  Make sure to free them when we're done.  */
8809   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8810
8811   build_type_psymtabs (dwarf2_per_objfile);
8812
8813   create_all_comp_units (dwarf2_per_objfile);
8814
8815   /* Create a temporary address map on a temporary obstack.  We later
8816      copy this to the final obstack.  */
8817   auto_obstack temp_obstack;
8818
8819   scoped_restore save_psymtabs_addrmap
8820     = make_scoped_restore (&objfile->psymtabs_addrmap,
8821                            addrmap_create_mutable (&temp_obstack));
8822
8823   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8824     {
8825       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8826
8827       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8828     }
8829
8830   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8831   process_skeletonless_type_units (dwarf2_per_objfile);
8832
8833   /* Now that all TUs have been processed we can fill in the dependencies.  */
8834   if (dwarf2_per_objfile->type_unit_groups != NULL)
8835     {
8836       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8837                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8838     }
8839
8840   if (dwarf_read_debug)
8841     print_tu_stats (dwarf2_per_objfile);
8842
8843   set_partial_user (dwarf2_per_objfile);
8844
8845   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8846                                                     &objfile->objfile_obstack);
8847   /* At this point we want to keep the address map.  */
8848   save_psymtabs_addrmap.release ();
8849
8850   do_cleanups (back_to);
8851
8852   if (dwarf_read_debug)
8853     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8854                         objfile_name (objfile));
8855 }
8856
8857 /* die_reader_func for load_partial_comp_unit.  */
8858
8859 static void
8860 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8861                                const gdb_byte *info_ptr,
8862                                struct die_info *comp_unit_die,
8863                                int has_children,
8864                                void *data)
8865 {
8866   struct dwarf2_cu *cu = reader->cu;
8867
8868   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8869
8870   /* Check if comp unit has_children.
8871      If so, read the rest of the partial symbols from this comp unit.
8872      If not, there's no more debug_info for this comp unit.  */
8873   if (has_children)
8874     load_partial_dies (reader, info_ptr, 0);
8875 }
8876
8877 /* Load the partial DIEs for a secondary CU into memory.
8878    This is also used when rereading a primary CU with load_all_dies.  */
8879
8880 static void
8881 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8882 {
8883   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8884                            load_partial_comp_unit_reader, NULL);
8885 }
8886
8887 static void
8888 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8889                               struct dwarf2_section_info *section,
8890                               struct dwarf2_section_info *abbrev_section,
8891                               unsigned int is_dwz,
8892                               int *n_allocated,
8893                               int *n_comp_units,
8894                               struct dwarf2_per_cu_data ***all_comp_units)
8895 {
8896   const gdb_byte *info_ptr;
8897   struct objfile *objfile = dwarf2_per_objfile->objfile;
8898
8899   if (dwarf_read_debug)
8900     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8901                         get_section_name (section),
8902                         get_section_file_name (section));
8903
8904   dwarf2_read_section (objfile, section);
8905
8906   info_ptr = section->buffer;
8907
8908   while (info_ptr < section->buffer + section->size)
8909     {
8910       struct dwarf2_per_cu_data *this_cu;
8911
8912       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8913
8914       comp_unit_head cu_header;
8915       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8916                                      abbrev_section, info_ptr,
8917                                      rcuh_kind::COMPILE);
8918
8919       /* Save the compilation unit for later lookup.  */
8920       if (cu_header.unit_type != DW_UT_type)
8921         {
8922           this_cu = XOBNEW (&objfile->objfile_obstack,
8923                             struct dwarf2_per_cu_data);
8924           memset (this_cu, 0, sizeof (*this_cu));
8925         }
8926       else
8927         {
8928           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8929                                   struct signatured_type);
8930           memset (sig_type, 0, sizeof (*sig_type));
8931           sig_type->signature = cu_header.signature;
8932           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8933           this_cu = &sig_type->per_cu;
8934         }
8935       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8936       this_cu->sect_off = sect_off;
8937       this_cu->length = cu_header.length + cu_header.initial_length_size;
8938       this_cu->is_dwz = is_dwz;
8939       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8940       this_cu->section = section;
8941
8942       if (*n_comp_units == *n_allocated)
8943         {
8944           *n_allocated *= 2;
8945           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8946                                         *all_comp_units, *n_allocated);
8947         }
8948       (*all_comp_units)[*n_comp_units] = this_cu;
8949       ++*n_comp_units;
8950
8951       info_ptr = info_ptr + this_cu->length;
8952     }
8953 }
8954
8955 /* Create a list of all compilation units in OBJFILE.
8956    This is only done for -readnow and building partial symtabs.  */
8957
8958 static void
8959 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8960 {
8961   int n_allocated;
8962   int n_comp_units;
8963   struct dwarf2_per_cu_data **all_comp_units;
8964   struct dwz_file *dwz;
8965   struct objfile *objfile = dwarf2_per_objfile->objfile;
8966
8967   n_comp_units = 0;
8968   n_allocated = 10;
8969   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
8970
8971   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8972                                 &dwarf2_per_objfile->abbrev, 0,
8973                                 &n_allocated, &n_comp_units, &all_comp_units);
8974
8975   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8976   if (dwz != NULL)
8977     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8978                                   1, &n_allocated, &n_comp_units,
8979                                   &all_comp_units);
8980
8981   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
8982                                                   struct dwarf2_per_cu_data *,
8983                                                   n_comp_units);
8984   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
8985           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
8986   xfree (all_comp_units);
8987   dwarf2_per_objfile->n_comp_units = n_comp_units;
8988 }
8989
8990 /* Process all loaded DIEs for compilation unit CU, starting at
8991    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8992    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8993    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8994    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8995
8996 static void
8997 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8998                       CORE_ADDR *highpc, int set_addrmap,
8999                       struct dwarf2_cu *cu)
9000 {
9001   struct partial_die_info *pdi;
9002
9003   /* Now, march along the PDI's, descending into ones which have
9004      interesting children but skipping the children of the other ones,
9005      until we reach the end of the compilation unit.  */
9006
9007   pdi = first_die;
9008
9009   while (pdi != NULL)
9010     {
9011       fixup_partial_die (pdi, cu);
9012
9013       /* Anonymous namespaces or modules have no name but have interesting
9014          children, so we need to look at them.  Ditto for anonymous
9015          enums.  */
9016
9017       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9018           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9019           || pdi->tag == DW_TAG_imported_unit
9020           || pdi->tag == DW_TAG_inlined_subroutine)
9021         {
9022           switch (pdi->tag)
9023             {
9024             case DW_TAG_subprogram:
9025             case DW_TAG_inlined_subroutine:
9026               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9027               break;
9028             case DW_TAG_constant:
9029             case DW_TAG_variable:
9030             case DW_TAG_typedef:
9031             case DW_TAG_union_type:
9032               if (!pdi->is_declaration)
9033                 {
9034                   add_partial_symbol (pdi, cu);
9035                 }
9036               break;
9037             case DW_TAG_class_type:
9038             case DW_TAG_interface_type:
9039             case DW_TAG_structure_type:
9040               if (!pdi->is_declaration)
9041                 {
9042                   add_partial_symbol (pdi, cu);
9043                 }
9044               if (cu->language == language_rust && pdi->has_children)
9045                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9046                                       set_addrmap, cu);
9047               break;
9048             case DW_TAG_enumeration_type:
9049               if (!pdi->is_declaration)
9050                 add_partial_enumeration (pdi, cu);
9051               break;
9052             case DW_TAG_base_type:
9053             case DW_TAG_subrange_type:
9054               /* File scope base type definitions are added to the partial
9055                  symbol table.  */
9056               add_partial_symbol (pdi, cu);
9057               break;
9058             case DW_TAG_namespace:
9059               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9060               break;
9061             case DW_TAG_module:
9062               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9063               break;
9064             case DW_TAG_imported_unit:
9065               {
9066                 struct dwarf2_per_cu_data *per_cu;
9067
9068                 /* For now we don't handle imported units in type units.  */
9069                 if (cu->per_cu->is_debug_types)
9070                   {
9071                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9072                              " supported in type units [in module %s]"),
9073                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9074                   }
9075
9076                 per_cu = dwarf2_find_containing_comp_unit
9077                            (pdi->d.sect_off, pdi->is_dwz,
9078                             cu->per_cu->dwarf2_per_objfile);
9079
9080                 /* Go read the partial unit, if needed.  */
9081                 if (per_cu->v.psymtab == NULL)
9082                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9083
9084                 VEC_safe_push (dwarf2_per_cu_ptr,
9085                                cu->per_cu->imported_symtabs, per_cu);
9086               }
9087               break;
9088             case DW_TAG_imported_declaration:
9089               add_partial_symbol (pdi, cu);
9090               break;
9091             default:
9092               break;
9093             }
9094         }
9095
9096       /* If the die has a sibling, skip to the sibling.  */
9097
9098       pdi = pdi->die_sibling;
9099     }
9100 }
9101
9102 /* Functions used to compute the fully scoped name of a partial DIE.
9103
9104    Normally, this is simple.  For C++, the parent DIE's fully scoped
9105    name is concatenated with "::" and the partial DIE's name.
9106    Enumerators are an exception; they use the scope of their parent
9107    enumeration type, i.e. the name of the enumeration type is not
9108    prepended to the enumerator.
9109
9110    There are two complexities.  One is DW_AT_specification; in this
9111    case "parent" means the parent of the target of the specification,
9112    instead of the direct parent of the DIE.  The other is compilers
9113    which do not emit DW_TAG_namespace; in this case we try to guess
9114    the fully qualified name of structure types from their members'
9115    linkage names.  This must be done using the DIE's children rather
9116    than the children of any DW_AT_specification target.  We only need
9117    to do this for structures at the top level, i.e. if the target of
9118    any DW_AT_specification (if any; otherwise the DIE itself) does not
9119    have a parent.  */
9120
9121 /* Compute the scope prefix associated with PDI's parent, in
9122    compilation unit CU.  The result will be allocated on CU's
9123    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9124    field.  NULL is returned if no prefix is necessary.  */
9125 static const char *
9126 partial_die_parent_scope (struct partial_die_info *pdi,
9127                           struct dwarf2_cu *cu)
9128 {
9129   const char *grandparent_scope;
9130   struct partial_die_info *parent, *real_pdi;
9131
9132   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9133      then this means the parent of the specification DIE.  */
9134
9135   real_pdi = pdi;
9136   while (real_pdi->has_specification)
9137     real_pdi = find_partial_die (real_pdi->spec_offset,
9138                                  real_pdi->spec_is_dwz, cu);
9139
9140   parent = real_pdi->die_parent;
9141   if (parent == NULL)
9142     return NULL;
9143
9144   if (parent->scope_set)
9145     return parent->scope;
9146
9147   fixup_partial_die (parent, cu);
9148
9149   grandparent_scope = partial_die_parent_scope (parent, cu);
9150
9151   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9152      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9153      Work around this problem here.  */
9154   if (cu->language == language_cplus
9155       && parent->tag == DW_TAG_namespace
9156       && strcmp (parent->name, "::") == 0
9157       && grandparent_scope == NULL)
9158     {
9159       parent->scope = NULL;
9160       parent->scope_set = 1;
9161       return NULL;
9162     }
9163
9164   if (pdi->tag == DW_TAG_enumerator)
9165     /* Enumerators should not get the name of the enumeration as a prefix.  */
9166     parent->scope = grandparent_scope;
9167   else if (parent->tag == DW_TAG_namespace
9168       || parent->tag == DW_TAG_module
9169       || parent->tag == DW_TAG_structure_type
9170       || parent->tag == DW_TAG_class_type
9171       || parent->tag == DW_TAG_interface_type
9172       || parent->tag == DW_TAG_union_type
9173       || parent->tag == DW_TAG_enumeration_type)
9174     {
9175       if (grandparent_scope == NULL)
9176         parent->scope = parent->name;
9177       else
9178         parent->scope = typename_concat (&cu->comp_unit_obstack,
9179                                          grandparent_scope,
9180                                          parent->name, 0, cu);
9181     }
9182   else
9183     {
9184       /* FIXME drow/2004-04-01: What should we be doing with
9185          function-local names?  For partial symbols, we should probably be
9186          ignoring them.  */
9187       complaint (&symfile_complaints,
9188                  _("unhandled containing DIE tag %d for DIE at %d"),
9189                  parent->tag, to_underlying (pdi->sect_off));
9190       parent->scope = grandparent_scope;
9191     }
9192
9193   parent->scope_set = 1;
9194   return parent->scope;
9195 }
9196
9197 /* Return the fully scoped name associated with PDI, from compilation unit
9198    CU.  The result will be allocated with malloc.  */
9199
9200 static char *
9201 partial_die_full_name (struct partial_die_info *pdi,
9202                        struct dwarf2_cu *cu)
9203 {
9204   const char *parent_scope;
9205
9206   /* If this is a template instantiation, we can not work out the
9207      template arguments from partial DIEs.  So, unfortunately, we have
9208      to go through the full DIEs.  At least any work we do building
9209      types here will be reused if full symbols are loaded later.  */
9210   if (pdi->has_template_arguments)
9211     {
9212       fixup_partial_die (pdi, cu);
9213
9214       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9215         {
9216           struct die_info *die;
9217           struct attribute attr;
9218           struct dwarf2_cu *ref_cu = cu;
9219
9220           /* DW_FORM_ref_addr is using section offset.  */
9221           attr.name = (enum dwarf_attribute) 0;
9222           attr.form = DW_FORM_ref_addr;
9223           attr.u.unsnd = to_underlying (pdi->sect_off);
9224           die = follow_die_ref (NULL, &attr, &ref_cu);
9225
9226           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9227         }
9228     }
9229
9230   parent_scope = partial_die_parent_scope (pdi, cu);
9231   if (parent_scope == NULL)
9232     return NULL;
9233   else
9234     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9235 }
9236
9237 static void
9238 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9239 {
9240   struct dwarf2_per_objfile *dwarf2_per_objfile
9241     = cu->per_cu->dwarf2_per_objfile;
9242   struct objfile *objfile = dwarf2_per_objfile->objfile;
9243   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9244   CORE_ADDR addr = 0;
9245   const char *actual_name = NULL;
9246   CORE_ADDR baseaddr;
9247   char *built_actual_name;
9248
9249   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9250
9251   built_actual_name = partial_die_full_name (pdi, cu);
9252   if (built_actual_name != NULL)
9253     actual_name = built_actual_name;
9254
9255   if (actual_name == NULL)
9256     actual_name = pdi->name;
9257
9258   switch (pdi->tag)
9259     {
9260     case DW_TAG_inlined_subroutine:
9261     case DW_TAG_subprogram:
9262       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9263       if (pdi->is_external || cu->language == language_ada)
9264         {
9265           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9266              of the global scope.  But in Ada, we want to be able to access
9267              nested procedures globally.  So all Ada subprograms are stored
9268              in the global scope.  */
9269           add_psymbol_to_list (actual_name, strlen (actual_name),
9270                                built_actual_name != NULL,
9271                                VAR_DOMAIN, LOC_BLOCK,
9272                                &objfile->global_psymbols,
9273                                addr, cu->language, objfile);
9274         }
9275       else
9276         {
9277           add_psymbol_to_list (actual_name, strlen (actual_name),
9278                                built_actual_name != NULL,
9279                                VAR_DOMAIN, LOC_BLOCK,
9280                                &objfile->static_psymbols,
9281                                addr, cu->language, objfile);
9282         }
9283
9284       if (pdi->main_subprogram && actual_name != NULL)
9285         set_objfile_main_name (objfile, actual_name, cu->language);
9286       break;
9287     case DW_TAG_constant:
9288       {
9289         std::vector<partial_symbol *> *list;
9290
9291         if (pdi->is_external)
9292           list = &objfile->global_psymbols;
9293         else
9294           list = &objfile->static_psymbols;
9295         add_psymbol_to_list (actual_name, strlen (actual_name),
9296                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9297                              list, 0, cu->language, objfile);
9298       }
9299       break;
9300     case DW_TAG_variable:
9301       if (pdi->d.locdesc)
9302         addr = decode_locdesc (pdi->d.locdesc, cu);
9303
9304       if (pdi->d.locdesc
9305           && addr == 0
9306           && !dwarf2_per_objfile->has_section_at_zero)
9307         {
9308           /* A global or static variable may also have been stripped
9309              out by the linker if unused, in which case its address
9310              will be nullified; do not add such variables into partial
9311              symbol table then.  */
9312         }
9313       else if (pdi->is_external)
9314         {
9315           /* Global Variable.
9316              Don't enter into the minimal symbol tables as there is
9317              a minimal symbol table entry from the ELF symbols already.
9318              Enter into partial symbol table if it has a location
9319              descriptor or a type.
9320              If the location descriptor is missing, new_symbol will create
9321              a LOC_UNRESOLVED symbol, the address of the variable will then
9322              be determined from the minimal symbol table whenever the variable
9323              is referenced.
9324              The address for the partial symbol table entry is not
9325              used by GDB, but it comes in handy for debugging partial symbol
9326              table building.  */
9327
9328           if (pdi->d.locdesc || pdi->has_type)
9329             add_psymbol_to_list (actual_name, strlen (actual_name),
9330                                  built_actual_name != NULL,
9331                                  VAR_DOMAIN, LOC_STATIC,
9332                                  &objfile->global_psymbols,
9333                                  addr + baseaddr,
9334                                  cu->language, objfile);
9335         }
9336       else
9337         {
9338           int has_loc = pdi->d.locdesc != NULL;
9339
9340           /* Static Variable.  Skip symbols whose value we cannot know (those
9341              without location descriptors or constant values).  */
9342           if (!has_loc && !pdi->has_const_value)
9343             {
9344               xfree (built_actual_name);
9345               return;
9346             }
9347
9348           add_psymbol_to_list (actual_name, strlen (actual_name),
9349                                built_actual_name != NULL,
9350                                VAR_DOMAIN, LOC_STATIC,
9351                                &objfile->static_psymbols,
9352                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9353                                cu->language, objfile);
9354         }
9355       break;
9356     case DW_TAG_typedef:
9357     case DW_TAG_base_type:
9358     case DW_TAG_subrange_type:
9359       add_psymbol_to_list (actual_name, strlen (actual_name),
9360                            built_actual_name != NULL,
9361                            VAR_DOMAIN, LOC_TYPEDEF,
9362                            &objfile->static_psymbols,
9363                            0, cu->language, objfile);
9364       break;
9365     case DW_TAG_imported_declaration:
9366     case DW_TAG_namespace:
9367       add_psymbol_to_list (actual_name, strlen (actual_name),
9368                            built_actual_name != NULL,
9369                            VAR_DOMAIN, LOC_TYPEDEF,
9370                            &objfile->global_psymbols,
9371                            0, cu->language, objfile);
9372       break;
9373     case DW_TAG_module:
9374       add_psymbol_to_list (actual_name, strlen (actual_name),
9375                            built_actual_name != NULL,
9376                            MODULE_DOMAIN, LOC_TYPEDEF,
9377                            &objfile->global_psymbols,
9378                            0, cu->language, objfile);
9379       break;
9380     case DW_TAG_class_type:
9381     case DW_TAG_interface_type:
9382     case DW_TAG_structure_type:
9383     case DW_TAG_union_type:
9384     case DW_TAG_enumeration_type:
9385       /* Skip external references.  The DWARF standard says in the section
9386          about "Structure, Union, and Class Type Entries": "An incomplete
9387          structure, union or class type is represented by a structure,
9388          union or class entry that does not have a byte size attribute
9389          and that has a DW_AT_declaration attribute."  */
9390       if (!pdi->has_byte_size && pdi->is_declaration)
9391         {
9392           xfree (built_actual_name);
9393           return;
9394         }
9395
9396       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9397          static vs. global.  */
9398       add_psymbol_to_list (actual_name, strlen (actual_name),
9399                            built_actual_name != NULL,
9400                            STRUCT_DOMAIN, LOC_TYPEDEF,
9401                            cu->language == language_cplus
9402                            ? &objfile->global_psymbols
9403                            : &objfile->static_psymbols,
9404                            0, cu->language, objfile);
9405
9406       break;
9407     case DW_TAG_enumerator:
9408       add_psymbol_to_list (actual_name, strlen (actual_name),
9409                            built_actual_name != NULL,
9410                            VAR_DOMAIN, LOC_CONST,
9411                            cu->language == language_cplus
9412                            ? &objfile->global_psymbols
9413                            : &objfile->static_psymbols,
9414                            0, cu->language, objfile);
9415       break;
9416     default:
9417       break;
9418     }
9419
9420   xfree (built_actual_name);
9421 }
9422
9423 /* Read a partial die corresponding to a namespace; also, add a symbol
9424    corresponding to that namespace to the symbol table.  NAMESPACE is
9425    the name of the enclosing namespace.  */
9426
9427 static void
9428 add_partial_namespace (struct partial_die_info *pdi,
9429                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9430                        int set_addrmap, struct dwarf2_cu *cu)
9431 {
9432   /* Add a symbol for the namespace.  */
9433
9434   add_partial_symbol (pdi, cu);
9435
9436   /* Now scan partial symbols in that namespace.  */
9437
9438   if (pdi->has_children)
9439     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9440 }
9441
9442 /* Read a partial die corresponding to a Fortran module.  */
9443
9444 static void
9445 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9446                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9447 {
9448   /* Add a symbol for the namespace.  */
9449
9450   add_partial_symbol (pdi, cu);
9451
9452   /* Now scan partial symbols in that module.  */
9453
9454   if (pdi->has_children)
9455     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9456 }
9457
9458 /* Read a partial die corresponding to a subprogram or an inlined
9459    subprogram and create a partial symbol for that subprogram.
9460    When the CU language allows it, this routine also defines a partial
9461    symbol for each nested subprogram that this subprogram contains.
9462    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9463    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9464
9465    PDI may also be a lexical block, in which case we simply search
9466    recursively for subprograms defined inside that lexical block.
9467    Again, this is only performed when the CU language allows this
9468    type of definitions.  */
9469
9470 static void
9471 add_partial_subprogram (struct partial_die_info *pdi,
9472                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9473                         int set_addrmap, struct dwarf2_cu *cu)
9474 {
9475   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9476     {
9477       if (pdi->has_pc_info)
9478         {
9479           if (pdi->lowpc < *lowpc)
9480             *lowpc = pdi->lowpc;
9481           if (pdi->highpc > *highpc)
9482             *highpc = pdi->highpc;
9483           if (set_addrmap)
9484             {
9485               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9486               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9487               CORE_ADDR baseaddr;
9488               CORE_ADDR highpc;
9489               CORE_ADDR lowpc;
9490
9491               baseaddr = ANOFFSET (objfile->section_offsets,
9492                                    SECT_OFF_TEXT (objfile));
9493               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9494                                                   pdi->lowpc + baseaddr);
9495               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9496                                                    pdi->highpc + baseaddr);
9497               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9498                                  cu->per_cu->v.psymtab);
9499             }
9500         }
9501
9502       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9503         {
9504           if (!pdi->is_declaration)
9505             /* Ignore subprogram DIEs that do not have a name, they are
9506                illegal.  Do not emit a complaint at this point, we will
9507                do so when we convert this psymtab into a symtab.  */
9508             if (pdi->name)
9509               add_partial_symbol (pdi, cu);
9510         }
9511     }
9512
9513   if (! pdi->has_children)
9514     return;
9515
9516   if (cu->language == language_ada)
9517     {
9518       pdi = pdi->die_child;
9519       while (pdi != NULL)
9520         {
9521           fixup_partial_die (pdi, cu);
9522           if (pdi->tag == DW_TAG_subprogram
9523               || pdi->tag == DW_TAG_inlined_subroutine
9524               || pdi->tag == DW_TAG_lexical_block)
9525             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9526           pdi = pdi->die_sibling;
9527         }
9528     }
9529 }
9530
9531 /* Read a partial die corresponding to an enumeration type.  */
9532
9533 static void
9534 add_partial_enumeration (struct partial_die_info *enum_pdi,
9535                          struct dwarf2_cu *cu)
9536 {
9537   struct partial_die_info *pdi;
9538
9539   if (enum_pdi->name != NULL)
9540     add_partial_symbol (enum_pdi, cu);
9541
9542   pdi = enum_pdi->die_child;
9543   while (pdi)
9544     {
9545       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9546         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9547       else
9548         add_partial_symbol (pdi, cu);
9549       pdi = pdi->die_sibling;
9550     }
9551 }
9552
9553 /* Return the initial uleb128 in the die at INFO_PTR.  */
9554
9555 static unsigned int
9556 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9557 {
9558   unsigned int bytes_read;
9559
9560   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9561 }
9562
9563 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9564    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9565
9566    Return the corresponding abbrev, or NULL if the number is zero (indicating
9567    an empty DIE).  In either case *BYTES_READ will be set to the length of
9568    the initial number.  */
9569
9570 static struct abbrev_info *
9571 peek_die_abbrev (const die_reader_specs &reader,
9572                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9573 {
9574   dwarf2_cu *cu = reader.cu;
9575   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9576   unsigned int abbrev_number
9577     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9578
9579   if (abbrev_number == 0)
9580     return NULL;
9581
9582   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9583   if (!abbrev)
9584     {
9585       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9586                " at offset 0x%x [in module %s]"),
9587              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9588              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9589     }
9590
9591   return abbrev;
9592 }
9593
9594 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9595    Returns a pointer to the end of a series of DIEs, terminated by an empty
9596    DIE.  Any children of the skipped DIEs will also be skipped.  */
9597
9598 static const gdb_byte *
9599 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9600 {
9601   while (1)
9602     {
9603       unsigned int bytes_read;
9604       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9605
9606       if (abbrev == NULL)
9607         return info_ptr + bytes_read;
9608       else
9609         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9610     }
9611 }
9612
9613 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9614    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9615    abbrev corresponding to that skipped uleb128 should be passed in
9616    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9617    children.  */
9618
9619 static const gdb_byte *
9620 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9621               struct abbrev_info *abbrev)
9622 {
9623   unsigned int bytes_read;
9624   struct attribute attr;
9625   bfd *abfd = reader->abfd;
9626   struct dwarf2_cu *cu = reader->cu;
9627   const gdb_byte *buffer = reader->buffer;
9628   const gdb_byte *buffer_end = reader->buffer_end;
9629   unsigned int form, i;
9630
9631   for (i = 0; i < abbrev->num_attrs; i++)
9632     {
9633       /* The only abbrev we care about is DW_AT_sibling.  */
9634       if (abbrev->attrs[i].name == DW_AT_sibling)
9635         {
9636           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9637           if (attr.form == DW_FORM_ref_addr)
9638             complaint (&symfile_complaints,
9639                        _("ignoring absolute DW_AT_sibling"));
9640           else
9641             {
9642               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9643               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9644
9645               if (sibling_ptr < info_ptr)
9646                 complaint (&symfile_complaints,
9647                            _("DW_AT_sibling points backwards"));
9648               else if (sibling_ptr > reader->buffer_end)
9649                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9650               else
9651                 return sibling_ptr;
9652             }
9653         }
9654
9655       /* If it isn't DW_AT_sibling, skip this attribute.  */
9656       form = abbrev->attrs[i].form;
9657     skip_attribute:
9658       switch (form)
9659         {
9660         case DW_FORM_ref_addr:
9661           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9662              and later it is offset sized.  */
9663           if (cu->header.version == 2)
9664             info_ptr += cu->header.addr_size;
9665           else
9666             info_ptr += cu->header.offset_size;
9667           break;
9668         case DW_FORM_GNU_ref_alt:
9669           info_ptr += cu->header.offset_size;
9670           break;
9671         case DW_FORM_addr:
9672           info_ptr += cu->header.addr_size;
9673           break;
9674         case DW_FORM_data1:
9675         case DW_FORM_ref1:
9676         case DW_FORM_flag:
9677           info_ptr += 1;
9678           break;
9679         case DW_FORM_flag_present:
9680         case DW_FORM_implicit_const:
9681           break;
9682         case DW_FORM_data2:
9683         case DW_FORM_ref2:
9684           info_ptr += 2;
9685           break;
9686         case DW_FORM_data4:
9687         case DW_FORM_ref4:
9688           info_ptr += 4;
9689           break;
9690         case DW_FORM_data8:
9691         case DW_FORM_ref8:
9692         case DW_FORM_ref_sig8:
9693           info_ptr += 8;
9694           break;
9695         case DW_FORM_data16:
9696           info_ptr += 16;
9697           break;
9698         case DW_FORM_string:
9699           read_direct_string (abfd, info_ptr, &bytes_read);
9700           info_ptr += bytes_read;
9701           break;
9702         case DW_FORM_sec_offset:
9703         case DW_FORM_strp:
9704         case DW_FORM_GNU_strp_alt:
9705           info_ptr += cu->header.offset_size;
9706           break;
9707         case DW_FORM_exprloc:
9708         case DW_FORM_block:
9709           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9710           info_ptr += bytes_read;
9711           break;
9712         case DW_FORM_block1:
9713           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9714           break;
9715         case DW_FORM_block2:
9716           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9717           break;
9718         case DW_FORM_block4:
9719           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9720           break;
9721         case DW_FORM_sdata:
9722         case DW_FORM_udata:
9723         case DW_FORM_ref_udata:
9724         case DW_FORM_GNU_addr_index:
9725         case DW_FORM_GNU_str_index:
9726           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9727           break;
9728         case DW_FORM_indirect:
9729           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9730           info_ptr += bytes_read;
9731           /* We need to continue parsing from here, so just go back to
9732              the top.  */
9733           goto skip_attribute;
9734
9735         default:
9736           error (_("Dwarf Error: Cannot handle %s "
9737                    "in DWARF reader [in module %s]"),
9738                  dwarf_form_name (form),
9739                  bfd_get_filename (abfd));
9740         }
9741     }
9742
9743   if (abbrev->has_children)
9744     return skip_children (reader, info_ptr);
9745   else
9746     return info_ptr;
9747 }
9748
9749 /* Locate ORIG_PDI's sibling.
9750    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9751
9752 static const gdb_byte *
9753 locate_pdi_sibling (const struct die_reader_specs *reader,
9754                     struct partial_die_info *orig_pdi,
9755                     const gdb_byte *info_ptr)
9756 {
9757   /* Do we know the sibling already?  */
9758
9759   if (orig_pdi->sibling)
9760     return orig_pdi->sibling;
9761
9762   /* Are there any children to deal with?  */
9763
9764   if (!orig_pdi->has_children)
9765     return info_ptr;
9766
9767   /* Skip the children the long way.  */
9768
9769   return skip_children (reader, info_ptr);
9770 }
9771
9772 /* Expand this partial symbol table into a full symbol table.  SELF is
9773    not NULL.  */
9774
9775 static void
9776 dwarf2_read_symtab (struct partial_symtab *self,
9777                     struct objfile *objfile)
9778 {
9779   struct dwarf2_per_objfile *dwarf2_per_objfile
9780     = get_dwarf2_per_objfile (objfile);
9781
9782   if (self->readin)
9783     {
9784       warning (_("bug: psymtab for %s is already read in."),
9785                self->filename);
9786     }
9787   else
9788     {
9789       if (info_verbose)
9790         {
9791           printf_filtered (_("Reading in symbols for %s..."),
9792                            self->filename);
9793           gdb_flush (gdb_stdout);
9794         }
9795
9796       /* If this psymtab is constructed from a debug-only objfile, the
9797          has_section_at_zero flag will not necessarily be correct.  We
9798          can get the correct value for this flag by looking at the data
9799          associated with the (presumably stripped) associated objfile.  */
9800       if (objfile->separate_debug_objfile_backlink)
9801         {
9802           struct dwarf2_per_objfile *dpo_backlink
9803             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9804
9805           dwarf2_per_objfile->has_section_at_zero
9806             = dpo_backlink->has_section_at_zero;
9807         }
9808
9809       dwarf2_per_objfile->reading_partial_symbols = 0;
9810
9811       psymtab_to_symtab_1 (self);
9812
9813       /* Finish up the debug error message.  */
9814       if (info_verbose)
9815         printf_filtered (_("done.\n"));
9816     }
9817
9818   process_cu_includes (dwarf2_per_objfile);
9819 }
9820 \f
9821 /* Reading in full CUs.  */
9822
9823 /* Add PER_CU to the queue.  */
9824
9825 static void
9826 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9827                  enum language pretend_language)
9828 {
9829   struct dwarf2_queue_item *item;
9830
9831   per_cu->queued = 1;
9832   item = XNEW (struct dwarf2_queue_item);
9833   item->per_cu = per_cu;
9834   item->pretend_language = pretend_language;
9835   item->next = NULL;
9836
9837   if (dwarf2_queue == NULL)
9838     dwarf2_queue = item;
9839   else
9840     dwarf2_queue_tail->next = item;
9841
9842   dwarf2_queue_tail = item;
9843 }
9844
9845 /* If PER_CU is not yet queued, add it to the queue.
9846    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9847    dependency.
9848    The result is non-zero if PER_CU was queued, otherwise the result is zero
9849    meaning either PER_CU is already queued or it is already loaded.
9850
9851    N.B. There is an invariant here that if a CU is queued then it is loaded.
9852    The caller is required to load PER_CU if we return non-zero.  */
9853
9854 static int
9855 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9856                        struct dwarf2_per_cu_data *per_cu,
9857                        enum language pretend_language)
9858 {
9859   /* We may arrive here during partial symbol reading, if we need full
9860      DIEs to process an unusual case (e.g. template arguments).  Do
9861      not queue PER_CU, just tell our caller to load its DIEs.  */
9862   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9863     {
9864       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9865         return 1;
9866       return 0;
9867     }
9868
9869   /* Mark the dependence relation so that we don't flush PER_CU
9870      too early.  */
9871   if (dependent_cu != NULL)
9872     dwarf2_add_dependence (dependent_cu, per_cu);
9873
9874   /* If it's already on the queue, we have nothing to do.  */
9875   if (per_cu->queued)
9876     return 0;
9877
9878   /* If the compilation unit is already loaded, just mark it as
9879      used.  */
9880   if (per_cu->cu != NULL)
9881     {
9882       per_cu->cu->last_used = 0;
9883       return 0;
9884     }
9885
9886   /* Add it to the queue.  */
9887   queue_comp_unit (per_cu, pretend_language);
9888
9889   return 1;
9890 }
9891
9892 /* Process the queue.  */
9893
9894 static void
9895 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9896 {
9897   struct dwarf2_queue_item *item, *next_item;
9898
9899   if (dwarf_read_debug)
9900     {
9901       fprintf_unfiltered (gdb_stdlog,
9902                           "Expanding one or more symtabs of objfile %s ...\n",
9903                           objfile_name (dwarf2_per_objfile->objfile));
9904     }
9905
9906   /* The queue starts out with one item, but following a DIE reference
9907      may load a new CU, adding it to the end of the queue.  */
9908   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9909     {
9910       if ((dwarf2_per_objfile->using_index
9911            ? !item->per_cu->v.quick->compunit_symtab
9912            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9913           /* Skip dummy CUs.  */
9914           && item->per_cu->cu != NULL)
9915         {
9916           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9917           unsigned int debug_print_threshold;
9918           char buf[100];
9919
9920           if (per_cu->is_debug_types)
9921             {
9922               struct signatured_type *sig_type =
9923                 (struct signatured_type *) per_cu;
9924
9925               sprintf (buf, "TU %s at offset 0x%x",
9926                        hex_string (sig_type->signature),
9927                        to_underlying (per_cu->sect_off));
9928               /* There can be 100s of TUs.
9929                  Only print them in verbose mode.  */
9930               debug_print_threshold = 2;
9931             }
9932           else
9933             {
9934               sprintf (buf, "CU at offset 0x%x",
9935                        to_underlying (per_cu->sect_off));
9936               debug_print_threshold = 1;
9937             }
9938
9939           if (dwarf_read_debug >= debug_print_threshold)
9940             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9941
9942           if (per_cu->is_debug_types)
9943             process_full_type_unit (per_cu, item->pretend_language);
9944           else
9945             process_full_comp_unit (per_cu, item->pretend_language);
9946
9947           if (dwarf_read_debug >= debug_print_threshold)
9948             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9949         }
9950
9951       item->per_cu->queued = 0;
9952       next_item = item->next;
9953       xfree (item);
9954     }
9955
9956   dwarf2_queue_tail = NULL;
9957
9958   if (dwarf_read_debug)
9959     {
9960       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9961                           objfile_name (dwarf2_per_objfile->objfile));
9962     }
9963 }
9964
9965 /* Free all allocated queue entries.  This function only releases anything if
9966    an error was thrown; if the queue was processed then it would have been
9967    freed as we went along.  */
9968
9969 static void
9970 dwarf2_release_queue (void *dummy)
9971 {
9972   struct dwarf2_queue_item *item, *last;
9973
9974   item = dwarf2_queue;
9975   while (item)
9976     {
9977       /* Anything still marked queued is likely to be in an
9978          inconsistent state, so discard it.  */
9979       if (item->per_cu->queued)
9980         {
9981           if (item->per_cu->cu != NULL)
9982             free_one_cached_comp_unit (item->per_cu);
9983           item->per_cu->queued = 0;
9984         }
9985
9986       last = item;
9987       item = item->next;
9988       xfree (last);
9989     }
9990
9991   dwarf2_queue = dwarf2_queue_tail = NULL;
9992 }
9993
9994 /* Read in full symbols for PST, and anything it depends on.  */
9995
9996 static void
9997 psymtab_to_symtab_1 (struct partial_symtab *pst)
9998 {
9999   struct dwarf2_per_cu_data *per_cu;
10000   int i;
10001
10002   if (pst->readin)
10003     return;
10004
10005   for (i = 0; i < pst->number_of_dependencies; i++)
10006     if (!pst->dependencies[i]->readin
10007         && pst->dependencies[i]->user == NULL)
10008       {
10009         /* Inform about additional files that need to be read in.  */
10010         if (info_verbose)
10011           {
10012             /* FIXME: i18n: Need to make this a single string.  */
10013             fputs_filtered (" ", gdb_stdout);
10014             wrap_here ("");
10015             fputs_filtered ("and ", gdb_stdout);
10016             wrap_here ("");
10017             printf_filtered ("%s...", pst->dependencies[i]->filename);
10018             wrap_here ("");     /* Flush output.  */
10019             gdb_flush (gdb_stdout);
10020           }
10021         psymtab_to_symtab_1 (pst->dependencies[i]);
10022       }
10023
10024   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10025
10026   if (per_cu == NULL)
10027     {
10028       /* It's an include file, no symbols to read for it.
10029          Everything is in the parent symtab.  */
10030       pst->readin = 1;
10031       return;
10032     }
10033
10034   dw2_do_instantiate_symtab (per_cu);
10035 }
10036
10037 /* Trivial hash function for die_info: the hash value of a DIE
10038    is its offset in .debug_info for this objfile.  */
10039
10040 static hashval_t
10041 die_hash (const void *item)
10042 {
10043   const struct die_info *die = (const struct die_info *) item;
10044
10045   return to_underlying (die->sect_off);
10046 }
10047
10048 /* Trivial comparison function for die_info structures: two DIEs
10049    are equal if they have the same offset.  */
10050
10051 static int
10052 die_eq (const void *item_lhs, const void *item_rhs)
10053 {
10054   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10055   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10056
10057   return die_lhs->sect_off == die_rhs->sect_off;
10058 }
10059
10060 /* die_reader_func for load_full_comp_unit.
10061    This is identical to read_signatured_type_reader,
10062    but is kept separate for now.  */
10063
10064 static void
10065 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10066                             const gdb_byte *info_ptr,
10067                             struct die_info *comp_unit_die,
10068                             int has_children,
10069                             void *data)
10070 {
10071   struct dwarf2_cu *cu = reader->cu;
10072   enum language *language_ptr = (enum language *) data;
10073
10074   gdb_assert (cu->die_hash == NULL);
10075   cu->die_hash =
10076     htab_create_alloc_ex (cu->header.length / 12,
10077                           die_hash,
10078                           die_eq,
10079                           NULL,
10080                           &cu->comp_unit_obstack,
10081                           hashtab_obstack_allocate,
10082                           dummy_obstack_deallocate);
10083
10084   if (has_children)
10085     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10086                                                   &info_ptr, comp_unit_die);
10087   cu->dies = comp_unit_die;
10088   /* comp_unit_die is not stored in die_hash, no need.  */
10089
10090   /* We try not to read any attributes in this function, because not
10091      all CUs needed for references have been loaded yet, and symbol
10092      table processing isn't initialized.  But we have to set the CU language,
10093      or we won't be able to build types correctly.
10094      Similarly, if we do not read the producer, we can not apply
10095      producer-specific interpretation.  */
10096   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10097 }
10098
10099 /* Load the DIEs associated with PER_CU into memory.  */
10100
10101 static void
10102 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10103                      enum language pretend_language)
10104 {
10105   gdb_assert (! this_cu->is_debug_types);
10106
10107   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10108                            load_full_comp_unit_reader, &pretend_language);
10109 }
10110
10111 /* Add a DIE to the delayed physname list.  */
10112
10113 static void
10114 add_to_method_list (struct type *type, int fnfield_index, int index,
10115                     const char *name, struct die_info *die,
10116                     struct dwarf2_cu *cu)
10117 {
10118   struct delayed_method_info mi;
10119   mi.type = type;
10120   mi.fnfield_index = fnfield_index;
10121   mi.index = index;
10122   mi.name = name;
10123   mi.die = die;
10124   cu->method_list.push_back (mi);
10125 }
10126
10127 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10128    "const" / "volatile".  If so, decrements LEN by the length of the
10129    modifier and return true.  Otherwise return false.  */
10130
10131 template<size_t N>
10132 static bool
10133 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10134 {
10135   size_t mod_len = sizeof (mod) - 1;
10136   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10137     {
10138       len -= mod_len;
10139       return true;
10140     }
10141   return false;
10142 }
10143
10144 /* Compute the physnames of any methods on the CU's method list.
10145
10146    The computation of method physnames is delayed in order to avoid the
10147    (bad) condition that one of the method's formal parameters is of an as yet
10148    incomplete type.  */
10149
10150 static void
10151 compute_delayed_physnames (struct dwarf2_cu *cu)
10152 {
10153   /* Only C++ delays computing physnames.  */
10154   if (cu->method_list.empty ())
10155     return;
10156   gdb_assert (cu->language == language_cplus);
10157
10158   for (struct delayed_method_info &mi : cu->method_list)
10159     {
10160       const char *physname;
10161       struct fn_fieldlist *fn_flp
10162         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
10163       physname = dwarf2_physname (mi.name, mi.die, cu);
10164       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
10165         = physname ? physname : "";
10166
10167       /* Since there's no tag to indicate whether a method is a
10168          const/volatile overload, extract that information out of the
10169          demangled name.  */
10170       if (physname != NULL)
10171         {
10172           size_t len = strlen (physname);
10173
10174           while (1)
10175             {
10176               if (physname[len] == ')') /* shortcut */
10177                 break;
10178               else if (check_modifier (physname, len, " const"))
10179                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
10180               else if (check_modifier (physname, len, " volatile"))
10181                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
10182               else
10183                 break;
10184             }
10185         }
10186     }
10187
10188   /* The list is no longer needed.  */
10189   cu->method_list.clear ();
10190 }
10191
10192 /* Go objects should be embedded in a DW_TAG_module DIE,
10193    and it's not clear if/how imported objects will appear.
10194    To keep Go support simple until that's worked out,
10195    go back through what we've read and create something usable.
10196    We could do this while processing each DIE, and feels kinda cleaner,
10197    but that way is more invasive.
10198    This is to, for example, allow the user to type "p var" or "b main"
10199    without having to specify the package name, and allow lookups
10200    of module.object to work in contexts that use the expression
10201    parser.  */
10202
10203 static void
10204 fixup_go_packaging (struct dwarf2_cu *cu)
10205 {
10206   char *package_name = NULL;
10207   struct pending *list;
10208   int i;
10209
10210   for (list = global_symbols; list != NULL; list = list->next)
10211     {
10212       for (i = 0; i < list->nsyms; ++i)
10213         {
10214           struct symbol *sym = list->symbol[i];
10215
10216           if (SYMBOL_LANGUAGE (sym) == language_go
10217               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10218             {
10219               char *this_package_name = go_symbol_package_name (sym);
10220
10221               if (this_package_name == NULL)
10222                 continue;
10223               if (package_name == NULL)
10224                 package_name = this_package_name;
10225               else
10226                 {
10227                   struct objfile *objfile
10228                     = cu->per_cu->dwarf2_per_objfile->objfile;
10229                   if (strcmp (package_name, this_package_name) != 0)
10230                     complaint (&symfile_complaints,
10231                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10232                                (symbol_symtab (sym) != NULL
10233                                 ? symtab_to_filename_for_display
10234                                     (symbol_symtab (sym))
10235                                 : objfile_name (objfile)),
10236                                this_package_name, package_name);
10237                   xfree (this_package_name);
10238                 }
10239             }
10240         }
10241     }
10242
10243   if (package_name != NULL)
10244     {
10245       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10246       const char *saved_package_name
10247         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10248                                         package_name,
10249                                         strlen (package_name));
10250       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10251                                      saved_package_name);
10252       struct symbol *sym;
10253
10254       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10255
10256       sym = allocate_symbol (objfile);
10257       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10258       SYMBOL_SET_NAMES (sym, saved_package_name,
10259                         strlen (saved_package_name), 0, objfile);
10260       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10261          e.g., "main" finds the "main" module and not C's main().  */
10262       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10263       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10264       SYMBOL_TYPE (sym) = type;
10265
10266       add_symbol_to_list (sym, &global_symbols);
10267
10268       xfree (package_name);
10269     }
10270 }
10271
10272 /* Return the symtab for PER_CU.  This works properly regardless of
10273    whether we're using the index or psymtabs.  */
10274
10275 static struct compunit_symtab *
10276 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10277 {
10278   return (per_cu->dwarf2_per_objfile->using_index
10279           ? per_cu->v.quick->compunit_symtab
10280           : per_cu->v.psymtab->compunit_symtab);
10281 }
10282
10283 /* A helper function for computing the list of all symbol tables
10284    included by PER_CU.  */
10285
10286 static void
10287 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10288                                 htab_t all_children, htab_t all_type_symtabs,
10289                                 struct dwarf2_per_cu_data *per_cu,
10290                                 struct compunit_symtab *immediate_parent)
10291 {
10292   void **slot;
10293   int ix;
10294   struct compunit_symtab *cust;
10295   struct dwarf2_per_cu_data *iter;
10296
10297   slot = htab_find_slot (all_children, per_cu, INSERT);
10298   if (*slot != NULL)
10299     {
10300       /* This inclusion and its children have been processed.  */
10301       return;
10302     }
10303
10304   *slot = per_cu;
10305   /* Only add a CU if it has a symbol table.  */
10306   cust = get_compunit_symtab (per_cu);
10307   if (cust != NULL)
10308     {
10309       /* If this is a type unit only add its symbol table if we haven't
10310          seen it yet (type unit per_cu's can share symtabs).  */
10311       if (per_cu->is_debug_types)
10312         {
10313           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10314           if (*slot == NULL)
10315             {
10316               *slot = cust;
10317               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10318               if (cust->user == NULL)
10319                 cust->user = immediate_parent;
10320             }
10321         }
10322       else
10323         {
10324           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10325           if (cust->user == NULL)
10326             cust->user = immediate_parent;
10327         }
10328     }
10329
10330   for (ix = 0;
10331        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10332        ++ix)
10333     {
10334       recursively_compute_inclusions (result, all_children,
10335                                       all_type_symtabs, iter, cust);
10336     }
10337 }
10338
10339 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10340    PER_CU.  */
10341
10342 static void
10343 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10344 {
10345   gdb_assert (! per_cu->is_debug_types);
10346
10347   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10348     {
10349       int ix, len;
10350       struct dwarf2_per_cu_data *per_cu_iter;
10351       struct compunit_symtab *compunit_symtab_iter;
10352       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10353       htab_t all_children, all_type_symtabs;
10354       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10355
10356       /* If we don't have a symtab, we can just skip this case.  */
10357       if (cust == NULL)
10358         return;
10359
10360       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10361                                         NULL, xcalloc, xfree);
10362       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10363                                             NULL, xcalloc, xfree);
10364
10365       for (ix = 0;
10366            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10367                         ix, per_cu_iter);
10368            ++ix)
10369         {
10370           recursively_compute_inclusions (&result_symtabs, all_children,
10371                                           all_type_symtabs, per_cu_iter,
10372                                           cust);
10373         }
10374
10375       /* Now we have a transitive closure of all the included symtabs.  */
10376       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10377       cust->includes
10378         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10379                      struct compunit_symtab *, len + 1);
10380       for (ix = 0;
10381            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10382                         compunit_symtab_iter);
10383            ++ix)
10384         cust->includes[ix] = compunit_symtab_iter;
10385       cust->includes[len] = NULL;
10386
10387       VEC_free (compunit_symtab_ptr, result_symtabs);
10388       htab_delete (all_children);
10389       htab_delete (all_type_symtabs);
10390     }
10391 }
10392
10393 /* Compute the 'includes' field for the symtabs of all the CUs we just
10394    read.  */
10395
10396 static void
10397 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10398 {
10399   int ix;
10400   struct dwarf2_per_cu_data *iter;
10401
10402   for (ix = 0;
10403        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10404                     ix, iter);
10405        ++ix)
10406     {
10407       if (! iter->is_debug_types)
10408         compute_compunit_symtab_includes (iter);
10409     }
10410
10411   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10412 }
10413
10414 /* Generate full symbol information for PER_CU, whose DIEs have
10415    already been loaded into memory.  */
10416
10417 static void
10418 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10419                         enum language pretend_language)
10420 {
10421   struct dwarf2_cu *cu = per_cu->cu;
10422   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10423   struct objfile *objfile = dwarf2_per_objfile->objfile;
10424   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10425   CORE_ADDR lowpc, highpc;
10426   struct compunit_symtab *cust;
10427   CORE_ADDR baseaddr;
10428   struct block *static_block;
10429   CORE_ADDR addr;
10430
10431   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10432
10433   buildsym_init ();
10434   scoped_free_pendings free_pending;
10435
10436   /* Clear the list here in case something was left over.  */
10437   cu->method_list.clear ();
10438
10439   cu->list_in_scope = &file_symbols;
10440
10441   cu->language = pretend_language;
10442   cu->language_defn = language_def (cu->language);
10443
10444   /* Do line number decoding in read_file_scope () */
10445   process_die (cu->dies, cu);
10446
10447   /* For now fudge the Go package.  */
10448   if (cu->language == language_go)
10449     fixup_go_packaging (cu);
10450
10451   /* Now that we have processed all the DIEs in the CU, all the types 
10452      should be complete, and it should now be safe to compute all of the
10453      physnames.  */
10454   compute_delayed_physnames (cu);
10455
10456   /* Some compilers don't define a DW_AT_high_pc attribute for the
10457      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10458      it, by scanning the DIE's below the compilation unit.  */
10459   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10460
10461   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10462   static_block = end_symtab_get_static_block (addr, 0, 1);
10463
10464   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10465      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10466      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10467      addrmap to help ensure it has an accurate map of pc values belonging to
10468      this comp unit.  */
10469   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10470
10471   cust = end_symtab_from_static_block (static_block,
10472                                        SECT_OFF_TEXT (objfile), 0);
10473
10474   if (cust != NULL)
10475     {
10476       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10477
10478       /* Set symtab language to language from DW_AT_language.  If the
10479          compilation is from a C file generated by language preprocessors, do
10480          not set the language if it was already deduced by start_subfile.  */
10481       if (!(cu->language == language_c
10482             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10483         COMPUNIT_FILETABS (cust)->language = cu->language;
10484
10485       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10486          produce DW_AT_location with location lists but it can be possibly
10487          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10488          there were bugs in prologue debug info, fixed later in GCC-4.5
10489          by "unwind info for epilogues" patch (which is not directly related).
10490
10491          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10492          needed, it would be wrong due to missing DW_AT_producer there.
10493
10494          Still one can confuse GDB by using non-standard GCC compilation
10495          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10496          */ 
10497       if (cu->has_loclist && gcc_4_minor >= 5)
10498         cust->locations_valid = 1;
10499
10500       if (gcc_4_minor >= 5)
10501         cust->epilogue_unwind_valid = 1;
10502
10503       cust->call_site_htab = cu->call_site_htab;
10504     }
10505
10506   if (dwarf2_per_objfile->using_index)
10507     per_cu->v.quick->compunit_symtab = cust;
10508   else
10509     {
10510       struct partial_symtab *pst = per_cu->v.psymtab;
10511       pst->compunit_symtab = cust;
10512       pst->readin = 1;
10513     }
10514
10515   /* Push it for inclusion processing later.  */
10516   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10517 }
10518
10519 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10520    already been loaded into memory.  */
10521
10522 static void
10523 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10524                         enum language pretend_language)
10525 {
10526   struct dwarf2_cu *cu = per_cu->cu;
10527   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10528   struct objfile *objfile = dwarf2_per_objfile->objfile;
10529   struct compunit_symtab *cust;
10530   struct signatured_type *sig_type;
10531
10532   gdb_assert (per_cu->is_debug_types);
10533   sig_type = (struct signatured_type *) per_cu;
10534
10535   buildsym_init ();
10536   scoped_free_pendings free_pending;
10537
10538   /* Clear the list here in case something was left over.  */
10539   cu->method_list.clear ();
10540
10541   cu->list_in_scope = &file_symbols;
10542
10543   cu->language = pretend_language;
10544   cu->language_defn = language_def (cu->language);
10545
10546   /* The symbol tables are set up in read_type_unit_scope.  */
10547   process_die (cu->dies, cu);
10548
10549   /* For now fudge the Go package.  */
10550   if (cu->language == language_go)
10551     fixup_go_packaging (cu);
10552
10553   /* Now that we have processed all the DIEs in the CU, all the types 
10554      should be complete, and it should now be safe to compute all of the
10555      physnames.  */
10556   compute_delayed_physnames (cu);
10557
10558   /* TUs share symbol tables.
10559      If this is the first TU to use this symtab, complete the construction
10560      of it with end_expandable_symtab.  Otherwise, complete the addition of
10561      this TU's symbols to the existing symtab.  */
10562   if (sig_type->type_unit_group->compunit_symtab == NULL)
10563     {
10564       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10565       sig_type->type_unit_group->compunit_symtab = cust;
10566
10567       if (cust != NULL)
10568         {
10569           /* Set symtab language to language from DW_AT_language.  If the
10570              compilation is from a C file generated by language preprocessors,
10571              do not set the language if it was already deduced by
10572              start_subfile.  */
10573           if (!(cu->language == language_c
10574                 && COMPUNIT_FILETABS (cust)->language != language_c))
10575             COMPUNIT_FILETABS (cust)->language = cu->language;
10576         }
10577     }
10578   else
10579     {
10580       augment_type_symtab ();
10581       cust = sig_type->type_unit_group->compunit_symtab;
10582     }
10583
10584   if (dwarf2_per_objfile->using_index)
10585     per_cu->v.quick->compunit_symtab = cust;
10586   else
10587     {
10588       struct partial_symtab *pst = per_cu->v.psymtab;
10589       pst->compunit_symtab = cust;
10590       pst->readin = 1;
10591     }
10592 }
10593
10594 /* Process an imported unit DIE.  */
10595
10596 static void
10597 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10598 {
10599   struct attribute *attr;
10600
10601   /* For now we don't handle imported units in type units.  */
10602   if (cu->per_cu->is_debug_types)
10603     {
10604       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10605                " supported in type units [in module %s]"),
10606              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10607     }
10608
10609   attr = dwarf2_attr (die, DW_AT_import, cu);
10610   if (attr != NULL)
10611     {
10612       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10613       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10614       dwarf2_per_cu_data *per_cu
10615         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10616                                             cu->per_cu->dwarf2_per_objfile);
10617
10618       /* If necessary, add it to the queue and load its DIEs.  */
10619       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10620         load_full_comp_unit (per_cu, cu->language);
10621
10622       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10623                      per_cu);
10624     }
10625 }
10626
10627 /* RAII object that represents a process_die scope: i.e.,
10628    starts/finishes processing a DIE.  */
10629 class process_die_scope
10630 {
10631 public:
10632   process_die_scope (die_info *die, dwarf2_cu *cu)
10633     : m_die (die), m_cu (cu)
10634   {
10635     /* We should only be processing DIEs not already in process.  */
10636     gdb_assert (!m_die->in_process);
10637     m_die->in_process = true;
10638   }
10639
10640   ~process_die_scope ()
10641   {
10642     m_die->in_process = false;
10643
10644     /* If we're done processing the DIE for the CU that owns the line
10645        header, we don't need the line header anymore.  */
10646     if (m_cu->line_header_die_owner == m_die)
10647       {
10648         delete m_cu->line_header;
10649         m_cu->line_header = NULL;
10650         m_cu->line_header_die_owner = NULL;
10651       }
10652   }
10653
10654 private:
10655   die_info *m_die;
10656   dwarf2_cu *m_cu;
10657 };
10658
10659 /* Process a die and its children.  */
10660
10661 static void
10662 process_die (struct die_info *die, struct dwarf2_cu *cu)
10663 {
10664   process_die_scope scope (die, cu);
10665
10666   switch (die->tag)
10667     {
10668     case DW_TAG_padding:
10669       break;
10670     case DW_TAG_compile_unit:
10671     case DW_TAG_partial_unit:
10672       read_file_scope (die, cu);
10673       break;
10674     case DW_TAG_type_unit:
10675       read_type_unit_scope (die, cu);
10676       break;
10677     case DW_TAG_subprogram:
10678     case DW_TAG_inlined_subroutine:
10679       read_func_scope (die, cu);
10680       break;
10681     case DW_TAG_lexical_block:
10682     case DW_TAG_try_block:
10683     case DW_TAG_catch_block:
10684       read_lexical_block_scope (die, cu);
10685       break;
10686     case DW_TAG_call_site:
10687     case DW_TAG_GNU_call_site:
10688       read_call_site_scope (die, cu);
10689       break;
10690     case DW_TAG_class_type:
10691     case DW_TAG_interface_type:
10692     case DW_TAG_structure_type:
10693     case DW_TAG_union_type:
10694       process_structure_scope (die, cu);
10695       break;
10696     case DW_TAG_enumeration_type:
10697       process_enumeration_scope (die, cu);
10698       break;
10699
10700     /* These dies have a type, but processing them does not create
10701        a symbol or recurse to process the children.  Therefore we can
10702        read them on-demand through read_type_die.  */
10703     case DW_TAG_subroutine_type:
10704     case DW_TAG_set_type:
10705     case DW_TAG_array_type:
10706     case DW_TAG_pointer_type:
10707     case DW_TAG_ptr_to_member_type:
10708     case DW_TAG_reference_type:
10709     case DW_TAG_rvalue_reference_type:
10710     case DW_TAG_string_type:
10711       break;
10712
10713     case DW_TAG_base_type:
10714     case DW_TAG_subrange_type:
10715     case DW_TAG_typedef:
10716       /* Add a typedef symbol for the type definition, if it has a
10717          DW_AT_name.  */
10718       new_symbol (die, read_type_die (die, cu), cu);
10719       break;
10720     case DW_TAG_common_block:
10721       read_common_block (die, cu);
10722       break;
10723     case DW_TAG_common_inclusion:
10724       break;
10725     case DW_TAG_namespace:
10726       cu->processing_has_namespace_info = 1;
10727       read_namespace (die, cu);
10728       break;
10729     case DW_TAG_module:
10730       cu->processing_has_namespace_info = 1;
10731       read_module (die, cu);
10732       break;
10733     case DW_TAG_imported_declaration:
10734       cu->processing_has_namespace_info = 1;
10735       if (read_namespace_alias (die, cu))
10736         break;
10737       /* The declaration is not a global namespace alias: fall through.  */
10738     case DW_TAG_imported_module:
10739       cu->processing_has_namespace_info = 1;
10740       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10741                                  || cu->language != language_fortran))
10742         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10743                    dwarf_tag_name (die->tag));
10744       read_import_statement (die, cu);
10745       break;
10746
10747     case DW_TAG_imported_unit:
10748       process_imported_unit_die (die, cu);
10749       break;
10750
10751     case DW_TAG_variable:
10752       read_variable (die, cu);
10753       break;
10754
10755     default:
10756       new_symbol (die, NULL, cu);
10757       break;
10758     }
10759 }
10760 \f
10761 /* DWARF name computation.  */
10762
10763 /* A helper function for dwarf2_compute_name which determines whether DIE
10764    needs to have the name of the scope prepended to the name listed in the
10765    die.  */
10766
10767 static int
10768 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10769 {
10770   struct attribute *attr;
10771
10772   switch (die->tag)
10773     {
10774     case DW_TAG_namespace:
10775     case DW_TAG_typedef:
10776     case DW_TAG_class_type:
10777     case DW_TAG_interface_type:
10778     case DW_TAG_structure_type:
10779     case DW_TAG_union_type:
10780     case DW_TAG_enumeration_type:
10781     case DW_TAG_enumerator:
10782     case DW_TAG_subprogram:
10783     case DW_TAG_inlined_subroutine:
10784     case DW_TAG_member:
10785     case DW_TAG_imported_declaration:
10786       return 1;
10787
10788     case DW_TAG_variable:
10789     case DW_TAG_constant:
10790       /* We only need to prefix "globally" visible variables.  These include
10791          any variable marked with DW_AT_external or any variable that
10792          lives in a namespace.  [Variables in anonymous namespaces
10793          require prefixing, but they are not DW_AT_external.]  */
10794
10795       if (dwarf2_attr (die, DW_AT_specification, cu))
10796         {
10797           struct dwarf2_cu *spec_cu = cu;
10798
10799           return die_needs_namespace (die_specification (die, &spec_cu),
10800                                       spec_cu);
10801         }
10802
10803       attr = dwarf2_attr (die, DW_AT_external, cu);
10804       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10805           && die->parent->tag != DW_TAG_module)
10806         return 0;
10807       /* A variable in a lexical block of some kind does not need a
10808          namespace, even though in C++ such variables may be external
10809          and have a mangled name.  */
10810       if (die->parent->tag ==  DW_TAG_lexical_block
10811           || die->parent->tag ==  DW_TAG_try_block
10812           || die->parent->tag ==  DW_TAG_catch_block
10813           || die->parent->tag == DW_TAG_subprogram)
10814         return 0;
10815       return 1;
10816
10817     default:
10818       return 0;
10819     }
10820 }
10821
10822 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10823    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10824    defined for the given DIE.  */
10825
10826 static struct attribute *
10827 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10828 {
10829   struct attribute *attr;
10830
10831   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10832   if (attr == NULL)
10833     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10834
10835   return attr;
10836 }
10837
10838 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10839    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10840    defined for the given DIE.  */
10841
10842 static const char *
10843 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10844 {
10845   const char *linkage_name;
10846
10847   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10848   if (linkage_name == NULL)
10849     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10850
10851   return linkage_name;
10852 }
10853
10854 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10855    compute the physname for the object, which include a method's:
10856    - formal parameters (C++),
10857    - receiver type (Go),
10858
10859    The term "physname" is a bit confusing.
10860    For C++, for example, it is the demangled name.
10861    For Go, for example, it's the mangled name.
10862
10863    For Ada, return the DIE's linkage name rather than the fully qualified
10864    name.  PHYSNAME is ignored..
10865
10866    The result is allocated on the objfile_obstack and canonicalized.  */
10867
10868 static const char *
10869 dwarf2_compute_name (const char *name,
10870                      struct die_info *die, struct dwarf2_cu *cu,
10871                      int physname)
10872 {
10873   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10874
10875   if (name == NULL)
10876     name = dwarf2_name (die, cu);
10877
10878   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10879      but otherwise compute it by typename_concat inside GDB.
10880      FIXME: Actually this is not really true, or at least not always true.
10881      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10882      Fortran names because there is no mangling standard.  So new_symbol
10883      will set the demangled name to the result of dwarf2_full_name, and it is
10884      the demangled name that GDB uses if it exists.  */
10885   if (cu->language == language_ada
10886       || (cu->language == language_fortran && physname))
10887     {
10888       /* For Ada unit, we prefer the linkage name over the name, as
10889          the former contains the exported name, which the user expects
10890          to be able to reference.  Ideally, we want the user to be able
10891          to reference this entity using either natural or linkage name,
10892          but we haven't started looking at this enhancement yet.  */
10893       const char *linkage_name = dw2_linkage_name (die, cu);
10894
10895       if (linkage_name != NULL)
10896         return linkage_name;
10897     }
10898
10899   /* These are the only languages we know how to qualify names in.  */
10900   if (name != NULL
10901       && (cu->language == language_cplus
10902           || cu->language == language_fortran || cu->language == language_d
10903           || cu->language == language_rust))
10904     {
10905       if (die_needs_namespace (die, cu))
10906         {
10907           const char *prefix;
10908           const char *canonical_name = NULL;
10909
10910           string_file buf;
10911
10912           prefix = determine_prefix (die, cu);
10913           if (*prefix != '\0')
10914             {
10915               char *prefixed_name = typename_concat (NULL, prefix, name,
10916                                                      physname, cu);
10917
10918               buf.puts (prefixed_name);
10919               xfree (prefixed_name);
10920             }
10921           else
10922             buf.puts (name);
10923
10924           /* Template parameters may be specified in the DIE's DW_AT_name, or
10925              as children with DW_TAG_template_type_param or
10926              DW_TAG_value_type_param.  If the latter, add them to the name
10927              here.  If the name already has template parameters, then
10928              skip this step; some versions of GCC emit both, and
10929              it is more efficient to use the pre-computed name.
10930
10931              Something to keep in mind about this process: it is very
10932              unlikely, or in some cases downright impossible, to produce
10933              something that will match the mangled name of a function.
10934              If the definition of the function has the same debug info,
10935              we should be able to match up with it anyway.  But fallbacks
10936              using the minimal symbol, for instance to find a method
10937              implemented in a stripped copy of libstdc++, will not work.
10938              If we do not have debug info for the definition, we will have to
10939              match them up some other way.
10940
10941              When we do name matching there is a related problem with function
10942              templates; two instantiated function templates are allowed to
10943              differ only by their return types, which we do not add here.  */
10944
10945           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10946             {
10947               struct attribute *attr;
10948               struct die_info *child;
10949               int first = 1;
10950
10951               die->building_fullname = 1;
10952
10953               for (child = die->child; child != NULL; child = child->sibling)
10954                 {
10955                   struct type *type;
10956                   LONGEST value;
10957                   const gdb_byte *bytes;
10958                   struct dwarf2_locexpr_baton *baton;
10959                   struct value *v;
10960
10961                   if (child->tag != DW_TAG_template_type_param
10962                       && child->tag != DW_TAG_template_value_param)
10963                     continue;
10964
10965                   if (first)
10966                     {
10967                       buf.puts ("<");
10968                       first = 0;
10969                     }
10970                   else
10971                     buf.puts (", ");
10972
10973                   attr = dwarf2_attr (child, DW_AT_type, cu);
10974                   if (attr == NULL)
10975                     {
10976                       complaint (&symfile_complaints,
10977                                  _("template parameter missing DW_AT_type"));
10978                       buf.puts ("UNKNOWN_TYPE");
10979                       continue;
10980                     }
10981                   type = die_type (child, cu);
10982
10983                   if (child->tag == DW_TAG_template_type_param)
10984                     {
10985                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10986                       continue;
10987                     }
10988
10989                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10990                   if (attr == NULL)
10991                     {
10992                       complaint (&symfile_complaints,
10993                                  _("template parameter missing "
10994                                    "DW_AT_const_value"));
10995                       buf.puts ("UNKNOWN_VALUE");
10996                       continue;
10997                     }
10998
10999                   dwarf2_const_value_attr (attr, type, name,
11000                                            &cu->comp_unit_obstack, cu,
11001                                            &value, &bytes, &baton);
11002
11003                   if (TYPE_NOSIGN (type))
11004                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11005                        changed, this can use value_print instead.  */
11006                     c_printchar (value, type, &buf);
11007                   else
11008                     {
11009                       struct value_print_options opts;
11010
11011                       if (baton != NULL)
11012                         v = dwarf2_evaluate_loc_desc (type, NULL,
11013                                                       baton->data,
11014                                                       baton->size,
11015                                                       baton->per_cu);
11016                       else if (bytes != NULL)
11017                         {
11018                           v = allocate_value (type);
11019                           memcpy (value_contents_writeable (v), bytes,
11020                                   TYPE_LENGTH (type));
11021                         }
11022                       else
11023                         v = value_from_longest (type, value);
11024
11025                       /* Specify decimal so that we do not depend on
11026                          the radix.  */
11027                       get_formatted_print_options (&opts, 'd');
11028                       opts.raw = 1;
11029                       value_print (v, &buf, &opts);
11030                       release_value (v);
11031                       value_free (v);
11032                     }
11033                 }
11034
11035               die->building_fullname = 0;
11036
11037               if (!first)
11038                 {
11039                   /* Close the argument list, with a space if necessary
11040                      (nested templates).  */
11041                   if (!buf.empty () && buf.string ().back () == '>')
11042                     buf.puts (" >");
11043                   else
11044                     buf.puts (">");
11045                 }
11046             }
11047
11048           /* For C++ methods, append formal parameter type
11049              information, if PHYSNAME.  */
11050
11051           if (physname && die->tag == DW_TAG_subprogram
11052               && cu->language == language_cplus)
11053             {
11054               struct type *type = read_type_die (die, cu);
11055
11056               c_type_print_args (type, &buf, 1, cu->language,
11057                                  &type_print_raw_options);
11058
11059               if (cu->language == language_cplus)
11060                 {
11061                   /* Assume that an artificial first parameter is
11062                      "this", but do not crash if it is not.  RealView
11063                      marks unnamed (and thus unused) parameters as
11064                      artificial; there is no way to differentiate
11065                      the two cases.  */
11066                   if (TYPE_NFIELDS (type) > 0
11067                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11068                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11069                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11070                                                                         0))))
11071                     buf.puts (" const");
11072                 }
11073             }
11074
11075           const std::string &intermediate_name = buf.string ();
11076
11077           if (cu->language == language_cplus)
11078             canonical_name
11079               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11080                                           &objfile->per_bfd->storage_obstack);
11081
11082           /* If we only computed INTERMEDIATE_NAME, or if
11083              INTERMEDIATE_NAME is already canonical, then we need to
11084              copy it to the appropriate obstack.  */
11085           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11086             name = ((const char *)
11087                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11088                                    intermediate_name.c_str (),
11089                                    intermediate_name.length ()));
11090           else
11091             name = canonical_name;
11092         }
11093     }
11094
11095   return name;
11096 }
11097
11098 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11099    If scope qualifiers are appropriate they will be added.  The result
11100    will be allocated on the storage_obstack, or NULL if the DIE does
11101    not have a name.  NAME may either be from a previous call to
11102    dwarf2_name or NULL.
11103
11104    The output string will be canonicalized (if C++).  */
11105
11106 static const char *
11107 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11108 {
11109   return dwarf2_compute_name (name, die, cu, 0);
11110 }
11111
11112 /* Construct a physname for the given DIE in CU.  NAME may either be
11113    from a previous call to dwarf2_name or NULL.  The result will be
11114    allocated on the objfile_objstack or NULL if the DIE does not have a
11115    name.
11116
11117    The output string will be canonicalized (if C++).  */
11118
11119 static const char *
11120 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11121 {
11122   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11123   const char *retval, *mangled = NULL, *canon = NULL;
11124   int need_copy = 1;
11125
11126   /* In this case dwarf2_compute_name is just a shortcut not building anything
11127      on its own.  */
11128   if (!die_needs_namespace (die, cu))
11129     return dwarf2_compute_name (name, die, cu, 1);
11130
11131   mangled = dw2_linkage_name (die, cu);
11132
11133   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11134      See https://github.com/rust-lang/rust/issues/32925.  */
11135   if (cu->language == language_rust && mangled != NULL
11136       && strchr (mangled, '{') != NULL)
11137     mangled = NULL;
11138
11139   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11140      has computed.  */
11141   gdb::unique_xmalloc_ptr<char> demangled;
11142   if (mangled != NULL)
11143     {
11144
11145       if (cu->language == language_go)
11146         {
11147           /* This is a lie, but we already lie to the caller new_symbol.
11148              new_symbol assumes we return the mangled name.
11149              This just undoes that lie until things are cleaned up.  */
11150         }
11151       else
11152         {
11153           /* Use DMGL_RET_DROP for C++ template functions to suppress
11154              their return type.  It is easier for GDB users to search
11155              for such functions as `name(params)' than `long name(params)'.
11156              In such case the minimal symbol names do not match the full
11157              symbol names but for template functions there is never a need
11158              to look up their definition from their declaration so
11159              the only disadvantage remains the minimal symbol variant
11160              `long name(params)' does not have the proper inferior type.  */
11161           demangled.reset (gdb_demangle (mangled,
11162                                          (DMGL_PARAMS | DMGL_ANSI
11163                                           | DMGL_RET_DROP)));
11164         }
11165       if (demangled)
11166         canon = demangled.get ();
11167       else
11168         {
11169           canon = mangled;
11170           need_copy = 0;
11171         }
11172     }
11173
11174   if (canon == NULL || check_physname)
11175     {
11176       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11177
11178       if (canon != NULL && strcmp (physname, canon) != 0)
11179         {
11180           /* It may not mean a bug in GDB.  The compiler could also
11181              compute DW_AT_linkage_name incorrectly.  But in such case
11182              GDB would need to be bug-to-bug compatible.  */
11183
11184           complaint (&symfile_complaints,
11185                      _("Computed physname <%s> does not match demangled <%s> "
11186                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11187                      physname, canon, mangled, to_underlying (die->sect_off),
11188                      objfile_name (objfile));
11189
11190           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11191              is available here - over computed PHYSNAME.  It is safer
11192              against both buggy GDB and buggy compilers.  */
11193
11194           retval = canon;
11195         }
11196       else
11197         {
11198           retval = physname;
11199           need_copy = 0;
11200         }
11201     }
11202   else
11203     retval = canon;
11204
11205   if (need_copy)
11206     retval = ((const char *)
11207               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11208                              retval, strlen (retval)));
11209
11210   return retval;
11211 }
11212
11213 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11214    a new symbol for it.
11215
11216    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11217
11218 static int
11219 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11220 {
11221   struct attribute *attr;
11222
11223   /* If the die does not have a name, this is not a namespace
11224      alias.  */
11225   attr = dwarf2_attr (die, DW_AT_name, cu);
11226   if (attr != NULL)
11227     {
11228       int num;
11229       struct die_info *d = die;
11230       struct dwarf2_cu *imported_cu = cu;
11231
11232       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11233          keep inspecting DIEs until we hit the underlying import.  */
11234 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11235       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11236         {
11237           attr = dwarf2_attr (d, DW_AT_import, cu);
11238           if (attr == NULL)
11239             break;
11240
11241           d = follow_die_ref (d, attr, &imported_cu);
11242           if (d->tag != DW_TAG_imported_declaration)
11243             break;
11244         }
11245
11246       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11247         {
11248           complaint (&symfile_complaints,
11249                      _("DIE at 0x%x has too many recursively imported "
11250                        "declarations"), to_underlying (d->sect_off));
11251           return 0;
11252         }
11253
11254       if (attr != NULL)
11255         {
11256           struct type *type;
11257           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11258
11259           type = get_die_type_at_offset (sect_off, cu->per_cu);
11260           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11261             {
11262               /* This declaration is a global namespace alias.  Add
11263                  a symbol for it whose type is the aliased namespace.  */
11264               new_symbol (die, type, cu);
11265               return 1;
11266             }
11267         }
11268     }
11269
11270   return 0;
11271 }
11272
11273 /* Return the using directives repository (global or local?) to use in the
11274    current context for LANGUAGE.
11275
11276    For Ada, imported declarations can materialize renamings, which *may* be
11277    global.  However it is impossible (for now?) in DWARF to distinguish
11278    "external" imported declarations and "static" ones.  As all imported
11279    declarations seem to be static in all other languages, make them all CU-wide
11280    global only in Ada.  */
11281
11282 static struct using_direct **
11283 using_directives (enum language language)
11284 {
11285   if (language == language_ada && context_stack_depth == 0)
11286     return &global_using_directives;
11287   else
11288     return &local_using_directives;
11289 }
11290
11291 /* Read the import statement specified by the given die and record it.  */
11292
11293 static void
11294 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11295 {
11296   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11297   struct attribute *import_attr;
11298   struct die_info *imported_die, *child_die;
11299   struct dwarf2_cu *imported_cu;
11300   const char *imported_name;
11301   const char *imported_name_prefix;
11302   const char *canonical_name;
11303   const char *import_alias;
11304   const char *imported_declaration = NULL;
11305   const char *import_prefix;
11306   std::vector<const char *> excludes;
11307
11308   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11309   if (import_attr == NULL)
11310     {
11311       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11312                  dwarf_tag_name (die->tag));
11313       return;
11314     }
11315
11316   imported_cu = cu;
11317   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11318   imported_name = dwarf2_name (imported_die, imported_cu);
11319   if (imported_name == NULL)
11320     {
11321       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11322
11323         The import in the following code:
11324         namespace A
11325           {
11326             typedef int B;
11327           }
11328
11329         int main ()
11330           {
11331             using A::B;
11332             B b;
11333             return b;
11334           }
11335
11336         ...
11337          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11338             <52>   DW_AT_decl_file   : 1
11339             <53>   DW_AT_decl_line   : 6
11340             <54>   DW_AT_import      : <0x75>
11341          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11342             <59>   DW_AT_name        : B
11343             <5b>   DW_AT_decl_file   : 1
11344             <5c>   DW_AT_decl_line   : 2
11345             <5d>   DW_AT_type        : <0x6e>
11346         ...
11347          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11348             <76>   DW_AT_byte_size   : 4
11349             <77>   DW_AT_encoding    : 5        (signed)
11350
11351         imports the wrong die ( 0x75 instead of 0x58 ).
11352         This case will be ignored until the gcc bug is fixed.  */
11353       return;
11354     }
11355
11356   /* Figure out the local name after import.  */
11357   import_alias = dwarf2_name (die, cu);
11358
11359   /* Figure out where the statement is being imported to.  */
11360   import_prefix = determine_prefix (die, cu);
11361
11362   /* Figure out what the scope of the imported die is and prepend it
11363      to the name of the imported die.  */
11364   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11365
11366   if (imported_die->tag != DW_TAG_namespace
11367       && imported_die->tag != DW_TAG_module)
11368     {
11369       imported_declaration = imported_name;
11370       canonical_name = imported_name_prefix;
11371     }
11372   else if (strlen (imported_name_prefix) > 0)
11373     canonical_name = obconcat (&objfile->objfile_obstack,
11374                                imported_name_prefix,
11375                                (cu->language == language_d ? "." : "::"),
11376                                imported_name, (char *) NULL);
11377   else
11378     canonical_name = imported_name;
11379
11380   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11381     for (child_die = die->child; child_die && child_die->tag;
11382          child_die = sibling_die (child_die))
11383       {
11384         /* DWARF-4: A Fortran use statement with a “rename list” may be
11385            represented by an imported module entry with an import attribute
11386            referring to the module and owned entries corresponding to those
11387            entities that are renamed as part of being imported.  */
11388
11389         if (child_die->tag != DW_TAG_imported_declaration)
11390           {
11391             complaint (&symfile_complaints,
11392                        _("child DW_TAG_imported_declaration expected "
11393                          "- DIE at 0x%x [in module %s]"),
11394                        to_underlying (child_die->sect_off), objfile_name (objfile));
11395             continue;
11396           }
11397
11398         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11399         if (import_attr == NULL)
11400           {
11401             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11402                        dwarf_tag_name (child_die->tag));
11403             continue;
11404           }
11405
11406         imported_cu = cu;
11407         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11408                                               &imported_cu);
11409         imported_name = dwarf2_name (imported_die, imported_cu);
11410         if (imported_name == NULL)
11411           {
11412             complaint (&symfile_complaints,
11413                        _("child DW_TAG_imported_declaration has unknown "
11414                          "imported name - DIE at 0x%x [in module %s]"),
11415                        to_underlying (child_die->sect_off), objfile_name (objfile));
11416             continue;
11417           }
11418
11419         excludes.push_back (imported_name);
11420
11421         process_die (child_die, cu);
11422       }
11423
11424   add_using_directive (using_directives (cu->language),
11425                        import_prefix,
11426                        canonical_name,
11427                        import_alias,
11428                        imported_declaration,
11429                        excludes,
11430                        0,
11431                        &objfile->objfile_obstack);
11432 }
11433
11434 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11435    types, but gives them a size of zero.  Starting with version 14,
11436    ICC is compatible with GCC.  */
11437
11438 static int
11439 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11440 {
11441   if (!cu->checked_producer)
11442     check_producer (cu);
11443
11444   return cu->producer_is_icc_lt_14;
11445 }
11446
11447 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11448    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11449    this, it was first present in GCC release 4.3.0.  */
11450
11451 static int
11452 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11453 {
11454   if (!cu->checked_producer)
11455     check_producer (cu);
11456
11457   return cu->producer_is_gcc_lt_4_3;
11458 }
11459
11460 static file_and_directory
11461 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11462 {
11463   file_and_directory res;
11464
11465   /* Find the filename.  Do not use dwarf2_name here, since the filename
11466      is not a source language identifier.  */
11467   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11468   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11469
11470   if (res.comp_dir == NULL
11471       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11472       && IS_ABSOLUTE_PATH (res.name))
11473     {
11474       res.comp_dir_storage = ldirname (res.name);
11475       if (!res.comp_dir_storage.empty ())
11476         res.comp_dir = res.comp_dir_storage.c_str ();
11477     }
11478   if (res.comp_dir != NULL)
11479     {
11480       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11481          directory, get rid of it.  */
11482       const char *cp = strchr (res.comp_dir, ':');
11483
11484       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11485         res.comp_dir = cp + 1;
11486     }
11487
11488   if (res.name == NULL)
11489     res.name = "<unknown>";
11490
11491   return res;
11492 }
11493
11494 /* Handle DW_AT_stmt_list for a compilation unit.
11495    DIE is the DW_TAG_compile_unit die for CU.
11496    COMP_DIR is the compilation directory.  LOWPC is passed to
11497    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11498
11499 static void
11500 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11501                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11502 {
11503   struct dwarf2_per_objfile *dwarf2_per_objfile
11504     = cu->per_cu->dwarf2_per_objfile;
11505   struct objfile *objfile = dwarf2_per_objfile->objfile;
11506   struct attribute *attr;
11507   struct line_header line_header_local;
11508   hashval_t line_header_local_hash;
11509   void **slot;
11510   int decode_mapping;
11511
11512   gdb_assert (! cu->per_cu->is_debug_types);
11513
11514   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11515   if (attr == NULL)
11516     return;
11517
11518   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11519
11520   /* The line header hash table is only created if needed (it exists to
11521      prevent redundant reading of the line table for partial_units).
11522      If we're given a partial_unit, we'll need it.  If we're given a
11523      compile_unit, then use the line header hash table if it's already
11524      created, but don't create one just yet.  */
11525
11526   if (dwarf2_per_objfile->line_header_hash == NULL
11527       && die->tag == DW_TAG_partial_unit)
11528     {
11529       dwarf2_per_objfile->line_header_hash
11530         = htab_create_alloc_ex (127, line_header_hash_voidp,
11531                                 line_header_eq_voidp,
11532                                 free_line_header_voidp,
11533                                 &objfile->objfile_obstack,
11534                                 hashtab_obstack_allocate,
11535                                 dummy_obstack_deallocate);
11536     }
11537
11538   line_header_local.sect_off = line_offset;
11539   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11540   line_header_local_hash = line_header_hash (&line_header_local);
11541   if (dwarf2_per_objfile->line_header_hash != NULL)
11542     {
11543       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11544                                        &line_header_local,
11545                                        line_header_local_hash, NO_INSERT);
11546
11547       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11548          is not present in *SLOT (since if there is something in *SLOT then
11549          it will be for a partial_unit).  */
11550       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11551         {
11552           gdb_assert (*slot != NULL);
11553           cu->line_header = (struct line_header *) *slot;
11554           return;
11555         }
11556     }
11557
11558   /* dwarf_decode_line_header does not yet provide sufficient information.
11559      We always have to call also dwarf_decode_lines for it.  */
11560   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11561   if (lh == NULL)
11562     return;
11563
11564   cu->line_header = lh.release ();
11565   cu->line_header_die_owner = die;
11566
11567   if (dwarf2_per_objfile->line_header_hash == NULL)
11568     slot = NULL;
11569   else
11570     {
11571       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11572                                        &line_header_local,
11573                                        line_header_local_hash, INSERT);
11574       gdb_assert (slot != NULL);
11575     }
11576   if (slot != NULL && *slot == NULL)
11577     {
11578       /* This newly decoded line number information unit will be owned
11579          by line_header_hash hash table.  */
11580       *slot = cu->line_header;
11581       cu->line_header_die_owner = NULL;
11582     }
11583   else
11584     {
11585       /* We cannot free any current entry in (*slot) as that struct line_header
11586          may be already used by multiple CUs.  Create only temporary decoded
11587          line_header for this CU - it may happen at most once for each line
11588          number information unit.  And if we're not using line_header_hash
11589          then this is what we want as well.  */
11590       gdb_assert (die->tag != DW_TAG_partial_unit);
11591     }
11592   decode_mapping = (die->tag != DW_TAG_partial_unit);
11593   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11594                       decode_mapping);
11595
11596 }
11597
11598 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11599
11600 static void
11601 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11602 {
11603   struct dwarf2_per_objfile *dwarf2_per_objfile
11604     = cu->per_cu->dwarf2_per_objfile;
11605   struct objfile *objfile = dwarf2_per_objfile->objfile;
11606   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11607   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11608   CORE_ADDR highpc = ((CORE_ADDR) 0);
11609   struct attribute *attr;
11610   struct die_info *child_die;
11611   CORE_ADDR baseaddr;
11612
11613   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11614
11615   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11616
11617   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11618      from finish_block.  */
11619   if (lowpc == ((CORE_ADDR) -1))
11620     lowpc = highpc;
11621   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11622
11623   file_and_directory fnd = find_file_and_directory (die, cu);
11624
11625   prepare_one_comp_unit (cu, die, cu->language);
11626
11627   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11628      standardised yet.  As a workaround for the language detection we fall
11629      back to the DW_AT_producer string.  */
11630   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11631     cu->language = language_opencl;
11632
11633   /* Similar hack for Go.  */
11634   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11635     set_cu_language (DW_LANG_Go, cu);
11636
11637   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11638
11639   /* Decode line number information if present.  We do this before
11640      processing child DIEs, so that the line header table is available
11641      for DW_AT_decl_file.  */
11642   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11643
11644   /* Process all dies in compilation unit.  */
11645   if (die->child != NULL)
11646     {
11647       child_die = die->child;
11648       while (child_die && child_die->tag)
11649         {
11650           process_die (child_die, cu);
11651           child_die = sibling_die (child_die);
11652         }
11653     }
11654
11655   /* Decode macro information, if present.  Dwarf 2 macro information
11656      refers to information in the line number info statement program
11657      header, so we can only read it if we've read the header
11658      successfully.  */
11659   attr = dwarf2_attr (die, DW_AT_macros, cu);
11660   if (attr == NULL)
11661     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11662   if (attr && cu->line_header)
11663     {
11664       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11665         complaint (&symfile_complaints,
11666                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11667
11668       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11669     }
11670   else
11671     {
11672       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11673       if (attr && cu->line_header)
11674         {
11675           unsigned int macro_offset = DW_UNSND (attr);
11676
11677           dwarf_decode_macros (cu, macro_offset, 0);
11678         }
11679     }
11680 }
11681
11682 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11683    Create the set of symtabs used by this TU, or if this TU is sharing
11684    symtabs with another TU and the symtabs have already been created
11685    then restore those symtabs in the line header.
11686    We don't need the pc/line-number mapping for type units.  */
11687
11688 static void
11689 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11690 {
11691   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11692   struct type_unit_group *tu_group;
11693   int first_time;
11694   struct attribute *attr;
11695   unsigned int i;
11696   struct signatured_type *sig_type;
11697
11698   gdb_assert (per_cu->is_debug_types);
11699   sig_type = (struct signatured_type *) per_cu;
11700
11701   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11702
11703   /* If we're using .gdb_index (includes -readnow) then
11704      per_cu->type_unit_group may not have been set up yet.  */
11705   if (sig_type->type_unit_group == NULL)
11706     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11707   tu_group = sig_type->type_unit_group;
11708
11709   /* If we've already processed this stmt_list there's no real need to
11710      do it again, we could fake it and just recreate the part we need
11711      (file name,index -> symtab mapping).  If data shows this optimization
11712      is useful we can do it then.  */
11713   first_time = tu_group->compunit_symtab == NULL;
11714
11715   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11716      debug info.  */
11717   line_header_up lh;
11718   if (attr != NULL)
11719     {
11720       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11721       lh = dwarf_decode_line_header (line_offset, cu);
11722     }
11723   if (lh == NULL)
11724     {
11725       if (first_time)
11726         dwarf2_start_symtab (cu, "", NULL, 0);
11727       else
11728         {
11729           gdb_assert (tu_group->symtabs == NULL);
11730           restart_symtab (tu_group->compunit_symtab, "", 0);
11731         }
11732       return;
11733     }
11734
11735   cu->line_header = lh.release ();
11736   cu->line_header_die_owner = die;
11737
11738   if (first_time)
11739     {
11740       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11741
11742       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11743          still initializing it, and our caller (a few levels up)
11744          process_full_type_unit still needs to know if this is the first
11745          time.  */
11746
11747       tu_group->num_symtabs = cu->line_header->file_names.size ();
11748       tu_group->symtabs = XNEWVEC (struct symtab *,
11749                                    cu->line_header->file_names.size ());
11750
11751       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11752         {
11753           file_entry &fe = cu->line_header->file_names[i];
11754
11755           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11756
11757           if (current_subfile->symtab == NULL)
11758             {
11759               /* NOTE: start_subfile will recognize when it's been
11760                  passed a file it has already seen.  So we can't
11761                  assume there's a simple mapping from
11762                  cu->line_header->file_names to subfiles, plus
11763                  cu->line_header->file_names may contain dups.  */
11764               current_subfile->symtab
11765                 = allocate_symtab (cust, current_subfile->name);
11766             }
11767
11768           fe.symtab = current_subfile->symtab;
11769           tu_group->symtabs[i] = fe.symtab;
11770         }
11771     }
11772   else
11773     {
11774       restart_symtab (tu_group->compunit_symtab, "", 0);
11775
11776       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11777         {
11778           file_entry &fe = cu->line_header->file_names[i];
11779
11780           fe.symtab = tu_group->symtabs[i];
11781         }
11782     }
11783
11784   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11785      so they don't have a "real" (so to speak) symtab anyway.
11786      There is later code that will assign the main symtab to all symbols
11787      that don't have one.  We need to handle the case of a symbol with a
11788      missing symtab (DW_AT_decl_file) anyway.  */
11789 }
11790
11791 /* Process DW_TAG_type_unit.
11792    For TUs we want to skip the first top level sibling if it's not the
11793    actual type being defined by this TU.  In this case the first top
11794    level sibling is there to provide context only.  */
11795
11796 static void
11797 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11798 {
11799   struct die_info *child_die;
11800
11801   prepare_one_comp_unit (cu, die, language_minimal);
11802
11803   /* Initialize (or reinitialize) the machinery for building symtabs.
11804      We do this before processing child DIEs, so that the line header table
11805      is available for DW_AT_decl_file.  */
11806   setup_type_unit_groups (die, cu);
11807
11808   if (die->child != NULL)
11809     {
11810       child_die = die->child;
11811       while (child_die && child_die->tag)
11812         {
11813           process_die (child_die, cu);
11814           child_die = sibling_die (child_die);
11815         }
11816     }
11817 }
11818 \f
11819 /* DWO/DWP files.
11820
11821    http://gcc.gnu.org/wiki/DebugFission
11822    http://gcc.gnu.org/wiki/DebugFissionDWP
11823
11824    To simplify handling of both DWO files ("object" files with the DWARF info)
11825    and DWP files (a file with the DWOs packaged up into one file), we treat
11826    DWP files as having a collection of virtual DWO files.  */
11827
11828 static hashval_t
11829 hash_dwo_file (const void *item)
11830 {
11831   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11832   hashval_t hash;
11833
11834   hash = htab_hash_string (dwo_file->dwo_name);
11835   if (dwo_file->comp_dir != NULL)
11836     hash += htab_hash_string (dwo_file->comp_dir);
11837   return hash;
11838 }
11839
11840 static int
11841 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11842 {
11843   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11844   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11845
11846   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11847     return 0;
11848   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11849     return lhs->comp_dir == rhs->comp_dir;
11850   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11851 }
11852
11853 /* Allocate a hash table for DWO files.  */
11854
11855 static htab_t
11856 allocate_dwo_file_hash_table (struct objfile *objfile)
11857 {
11858   return htab_create_alloc_ex (41,
11859                                hash_dwo_file,
11860                                eq_dwo_file,
11861                                NULL,
11862                                &objfile->objfile_obstack,
11863                                hashtab_obstack_allocate,
11864                                dummy_obstack_deallocate);
11865 }
11866
11867 /* Lookup DWO file DWO_NAME.  */
11868
11869 static void **
11870 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11871                       const char *dwo_name,
11872                       const char *comp_dir)
11873 {
11874   struct dwo_file find_entry;
11875   void **slot;
11876
11877   if (dwarf2_per_objfile->dwo_files == NULL)
11878     dwarf2_per_objfile->dwo_files
11879       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11880
11881   memset (&find_entry, 0, sizeof (find_entry));
11882   find_entry.dwo_name = dwo_name;
11883   find_entry.comp_dir = comp_dir;
11884   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11885
11886   return slot;
11887 }
11888
11889 static hashval_t
11890 hash_dwo_unit (const void *item)
11891 {
11892   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11893
11894   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11895   return dwo_unit->signature;
11896 }
11897
11898 static int
11899 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11900 {
11901   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11902   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11903
11904   /* The signature is assumed to be unique within the DWO file.
11905      So while object file CU dwo_id's always have the value zero,
11906      that's OK, assuming each object file DWO file has only one CU,
11907      and that's the rule for now.  */
11908   return lhs->signature == rhs->signature;
11909 }
11910
11911 /* Allocate a hash table for DWO CUs,TUs.
11912    There is one of these tables for each of CUs,TUs for each DWO file.  */
11913
11914 static htab_t
11915 allocate_dwo_unit_table (struct objfile *objfile)
11916 {
11917   /* Start out with a pretty small number.
11918      Generally DWO files contain only one CU and maybe some TUs.  */
11919   return htab_create_alloc_ex (3,
11920                                hash_dwo_unit,
11921                                eq_dwo_unit,
11922                                NULL,
11923                                &objfile->objfile_obstack,
11924                                hashtab_obstack_allocate,
11925                                dummy_obstack_deallocate);
11926 }
11927
11928 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11929
11930 struct create_dwo_cu_data
11931 {
11932   struct dwo_file *dwo_file;
11933   struct dwo_unit dwo_unit;
11934 };
11935
11936 /* die_reader_func for create_dwo_cu.  */
11937
11938 static void
11939 create_dwo_cu_reader (const struct die_reader_specs *reader,
11940                       const gdb_byte *info_ptr,
11941                       struct die_info *comp_unit_die,
11942                       int has_children,
11943                       void *datap)
11944 {
11945   struct dwarf2_cu *cu = reader->cu;
11946   sect_offset sect_off = cu->per_cu->sect_off;
11947   struct dwarf2_section_info *section = cu->per_cu->section;
11948   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11949   struct dwo_file *dwo_file = data->dwo_file;
11950   struct dwo_unit *dwo_unit = &data->dwo_unit;
11951   struct attribute *attr;
11952
11953   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11954   if (attr == NULL)
11955     {
11956       complaint (&symfile_complaints,
11957                  _("Dwarf Error: debug entry at offset 0x%x is missing"
11958                    " its dwo_id [in module %s]"),
11959                  to_underlying (sect_off), dwo_file->dwo_name);
11960       return;
11961     }
11962
11963   dwo_unit->dwo_file = dwo_file;
11964   dwo_unit->signature = DW_UNSND (attr);
11965   dwo_unit->section = section;
11966   dwo_unit->sect_off = sect_off;
11967   dwo_unit->length = cu->per_cu->length;
11968
11969   if (dwarf_read_debug)
11970     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
11971                         to_underlying (sect_off),
11972                         hex_string (dwo_unit->signature));
11973 }
11974
11975 /* Create the dwo_units for the CUs in a DWO_FILE.
11976    Note: This function processes DWO files only, not DWP files.  */
11977
11978 static void
11979 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11980                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11981                        htab_t &cus_htab)
11982 {
11983   struct objfile *objfile = dwarf2_per_objfile->objfile;
11984   const gdb_byte *info_ptr, *end_ptr;
11985
11986   dwarf2_read_section (objfile, &section);
11987   info_ptr = section.buffer;
11988
11989   if (info_ptr == NULL)
11990     return;
11991
11992   if (dwarf_read_debug)
11993     {
11994       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11995                           get_section_name (&section),
11996                           get_section_file_name (&section));
11997     }
11998
11999   end_ptr = info_ptr + section.size;
12000   while (info_ptr < end_ptr)
12001     {
12002       struct dwarf2_per_cu_data per_cu;
12003       struct create_dwo_cu_data create_dwo_cu_data;
12004       struct dwo_unit *dwo_unit;
12005       void **slot;
12006       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12007
12008       memset (&create_dwo_cu_data.dwo_unit, 0,
12009               sizeof (create_dwo_cu_data.dwo_unit));
12010       memset (&per_cu, 0, sizeof (per_cu));
12011       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12012       per_cu.is_debug_types = 0;
12013       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12014       per_cu.section = &section;
12015       create_dwo_cu_data.dwo_file = &dwo_file;
12016
12017       init_cutu_and_read_dies_no_follow (
12018           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12019       info_ptr += per_cu.length;
12020
12021       // If the unit could not be parsed, skip it.
12022       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12023         continue;
12024
12025       if (cus_htab == NULL)
12026         cus_htab = allocate_dwo_unit_table (objfile);
12027
12028       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12029       *dwo_unit = create_dwo_cu_data.dwo_unit;
12030       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12031       gdb_assert (slot != NULL);
12032       if (*slot != NULL)
12033         {
12034           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12035           sect_offset dup_sect_off = dup_cu->sect_off;
12036
12037           complaint (&symfile_complaints,
12038                      _("debug cu entry at offset 0x%x is duplicate to"
12039                        " the entry at offset 0x%x, signature %s"),
12040                      to_underlying (sect_off), to_underlying (dup_sect_off),
12041                      hex_string (dwo_unit->signature));
12042         }
12043       *slot = (void *)dwo_unit;
12044     }
12045 }
12046
12047 /* DWP file .debug_{cu,tu}_index section format:
12048    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12049
12050    DWP Version 1:
12051
12052    Both index sections have the same format, and serve to map a 64-bit
12053    signature to a set of section numbers.  Each section begins with a header,
12054    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12055    indexes, and a pool of 32-bit section numbers.  The index sections will be
12056    aligned at 8-byte boundaries in the file.
12057
12058    The index section header consists of:
12059
12060     V, 32 bit version number
12061     -, 32 bits unused
12062     N, 32 bit number of compilation units or type units in the index
12063     M, 32 bit number of slots in the hash table
12064
12065    Numbers are recorded using the byte order of the application binary.
12066
12067    The hash table begins at offset 16 in the section, and consists of an array
12068    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12069    order of the application binary).  Unused slots in the hash table are 0.
12070    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12071
12072    The parallel table begins immediately after the hash table
12073    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12074    array of 32-bit indexes (using the byte order of the application binary),
12075    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12076    table contains a 32-bit index into the pool of section numbers.  For unused
12077    hash table slots, the corresponding entry in the parallel table will be 0.
12078
12079    The pool of section numbers begins immediately following the hash table
12080    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12081    section numbers consists of an array of 32-bit words (using the byte order
12082    of the application binary).  Each item in the array is indexed starting
12083    from 0.  The hash table entry provides the index of the first section
12084    number in the set.  Additional section numbers in the set follow, and the
12085    set is terminated by a 0 entry (section number 0 is not used in ELF).
12086
12087    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12088    section must be the first entry in the set, and the .debug_abbrev.dwo must
12089    be the second entry. Other members of the set may follow in any order.
12090
12091    ---
12092
12093    DWP Version 2:
12094
12095    DWP Version 2 combines all the .debug_info, etc. sections into one,
12096    and the entries in the index tables are now offsets into these sections.
12097    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12098    section.
12099
12100    Index Section Contents:
12101     Header
12102     Hash Table of Signatures   dwp_hash_table.hash_table
12103     Parallel Table of Indices  dwp_hash_table.unit_table
12104     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12105     Table of Section Sizes     dwp_hash_table.v2.sizes
12106
12107    The index section header consists of:
12108
12109     V, 32 bit version number
12110     L, 32 bit number of columns in the table of section offsets
12111     N, 32 bit number of compilation units or type units in the index
12112     M, 32 bit number of slots in the hash table
12113
12114    Numbers are recorded using the byte order of the application binary.
12115
12116    The hash table has the same format as version 1.
12117    The parallel table of indices has the same format as version 1,
12118    except that the entries are origin-1 indices into the table of sections
12119    offsets and the table of section sizes.
12120
12121    The table of offsets begins immediately following the parallel table
12122    (at offset 16 + 12 * M from the beginning of the section).  The table is
12123    a two-dimensional array of 32-bit words (using the byte order of the
12124    application binary), with L columns and N+1 rows, in row-major order.
12125    Each row in the array is indexed starting from 0.  The first row provides
12126    a key to the remaining rows: each column in this row provides an identifier
12127    for a debug section, and the offsets in the same column of subsequent rows
12128    refer to that section.  The section identifiers are:
12129
12130     DW_SECT_INFO         1  .debug_info.dwo
12131     DW_SECT_TYPES        2  .debug_types.dwo
12132     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12133     DW_SECT_LINE         4  .debug_line.dwo
12134     DW_SECT_LOC          5  .debug_loc.dwo
12135     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12136     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12137     DW_SECT_MACRO        8  .debug_macro.dwo
12138
12139    The offsets provided by the CU and TU index sections are the base offsets
12140    for the contributions made by each CU or TU to the corresponding section
12141    in the package file.  Each CU and TU header contains an abbrev_offset
12142    field, used to find the abbreviations table for that CU or TU within the
12143    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12144    be interpreted as relative to the base offset given in the index section.
12145    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12146    should be interpreted as relative to the base offset for .debug_line.dwo,
12147    and offsets into other debug sections obtained from DWARF attributes should
12148    also be interpreted as relative to the corresponding base offset.
12149
12150    The table of sizes begins immediately following the table of offsets.
12151    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12152    with L columns and N rows, in row-major order.  Each row in the array is
12153    indexed starting from 1 (row 0 is shared by the two tables).
12154
12155    ---
12156
12157    Hash table lookup is handled the same in version 1 and 2:
12158
12159    We assume that N and M will not exceed 2^32 - 1.
12160    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12161
12162    Given a 64-bit compilation unit signature or a type signature S, an entry
12163    in the hash table is located as follows:
12164
12165    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12166       the low-order k bits all set to 1.
12167
12168    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12169
12170    3) If the hash table entry at index H matches the signature, use that
12171       entry.  If the hash table entry at index H is unused (all zeroes),
12172       terminate the search: the signature is not present in the table.
12173
12174    4) Let H = (H + H') modulo M. Repeat at Step 3.
12175
12176    Because M > N and H' and M are relatively prime, the search is guaranteed
12177    to stop at an unused slot or find the match.  */
12178
12179 /* Create a hash table to map DWO IDs to their CU/TU entry in
12180    .debug_{info,types}.dwo in DWP_FILE.
12181    Returns NULL if there isn't one.
12182    Note: This function processes DWP files only, not DWO files.  */
12183
12184 static struct dwp_hash_table *
12185 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12186                        struct dwp_file *dwp_file, int is_debug_types)
12187 {
12188   struct objfile *objfile = dwarf2_per_objfile->objfile;
12189   bfd *dbfd = dwp_file->dbfd;
12190   const gdb_byte *index_ptr, *index_end;
12191   struct dwarf2_section_info *index;
12192   uint32_t version, nr_columns, nr_units, nr_slots;
12193   struct dwp_hash_table *htab;
12194
12195   if (is_debug_types)
12196     index = &dwp_file->sections.tu_index;
12197   else
12198     index = &dwp_file->sections.cu_index;
12199
12200   if (dwarf2_section_empty_p (index))
12201     return NULL;
12202   dwarf2_read_section (objfile, index);
12203
12204   index_ptr = index->buffer;
12205   index_end = index_ptr + index->size;
12206
12207   version = read_4_bytes (dbfd, index_ptr);
12208   index_ptr += 4;
12209   if (version == 2)
12210     nr_columns = read_4_bytes (dbfd, index_ptr);
12211   else
12212     nr_columns = 0;
12213   index_ptr += 4;
12214   nr_units = read_4_bytes (dbfd, index_ptr);
12215   index_ptr += 4;
12216   nr_slots = read_4_bytes (dbfd, index_ptr);
12217   index_ptr += 4;
12218
12219   if (version != 1 && version != 2)
12220     {
12221       error (_("Dwarf Error: unsupported DWP file version (%s)"
12222                " [in module %s]"),
12223              pulongest (version), dwp_file->name);
12224     }
12225   if (nr_slots != (nr_slots & -nr_slots))
12226     {
12227       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12228                " is not power of 2 [in module %s]"),
12229              pulongest (nr_slots), dwp_file->name);
12230     }
12231
12232   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12233   htab->version = version;
12234   htab->nr_columns = nr_columns;
12235   htab->nr_units = nr_units;
12236   htab->nr_slots = nr_slots;
12237   htab->hash_table = index_ptr;
12238   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12239
12240   /* Exit early if the table is empty.  */
12241   if (nr_slots == 0 || nr_units == 0
12242       || (version == 2 && nr_columns == 0))
12243     {
12244       /* All must be zero.  */
12245       if (nr_slots != 0 || nr_units != 0
12246           || (version == 2 && nr_columns != 0))
12247         {
12248           complaint (&symfile_complaints,
12249                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12250                        " all zero [in modules %s]"),
12251                      dwp_file->name);
12252         }
12253       return htab;
12254     }
12255
12256   if (version == 1)
12257     {
12258       htab->section_pool.v1.indices =
12259         htab->unit_table + sizeof (uint32_t) * nr_slots;
12260       /* It's harder to decide whether the section is too small in v1.
12261          V1 is deprecated anyway so we punt.  */
12262     }
12263   else
12264     {
12265       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12266       int *ids = htab->section_pool.v2.section_ids;
12267       /* Reverse map for error checking.  */
12268       int ids_seen[DW_SECT_MAX + 1];
12269       int i;
12270
12271       if (nr_columns < 2)
12272         {
12273           error (_("Dwarf Error: bad DWP hash table, too few columns"
12274                    " in section table [in module %s]"),
12275                  dwp_file->name);
12276         }
12277       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12278         {
12279           error (_("Dwarf Error: bad DWP hash table, too many columns"
12280                    " in section table [in module %s]"),
12281                  dwp_file->name);
12282         }
12283       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12284       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12285       for (i = 0; i < nr_columns; ++i)
12286         {
12287           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12288
12289           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12290             {
12291               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12292                        " in section table [in module %s]"),
12293                      id, dwp_file->name);
12294             }
12295           if (ids_seen[id] != -1)
12296             {
12297               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12298                        " id %d in section table [in module %s]"),
12299                      id, dwp_file->name);
12300             }
12301           ids_seen[id] = i;
12302           ids[i] = id;
12303         }
12304       /* Must have exactly one info or types section.  */
12305       if (((ids_seen[DW_SECT_INFO] != -1)
12306            + (ids_seen[DW_SECT_TYPES] != -1))
12307           != 1)
12308         {
12309           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12310                    " DWO info/types section [in module %s]"),
12311                  dwp_file->name);
12312         }
12313       /* Must have an abbrev section.  */
12314       if (ids_seen[DW_SECT_ABBREV] == -1)
12315         {
12316           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12317                    " section [in module %s]"),
12318                  dwp_file->name);
12319         }
12320       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12321       htab->section_pool.v2.sizes =
12322         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12323                                          * nr_units * nr_columns);
12324       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12325                                           * nr_units * nr_columns))
12326           > index_end)
12327         {
12328           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12329                    " [in module %s]"),
12330                  dwp_file->name);
12331         }
12332     }
12333
12334   return htab;
12335 }
12336
12337 /* Update SECTIONS with the data from SECTP.
12338
12339    This function is like the other "locate" section routines that are
12340    passed to bfd_map_over_sections, but in this context the sections to
12341    read comes from the DWP V1 hash table, not the full ELF section table.
12342
12343    The result is non-zero for success, or zero if an error was found.  */
12344
12345 static int
12346 locate_v1_virtual_dwo_sections (asection *sectp,
12347                                 struct virtual_v1_dwo_sections *sections)
12348 {
12349   const struct dwop_section_names *names = &dwop_section_names;
12350
12351   if (section_is_p (sectp->name, &names->abbrev_dwo))
12352     {
12353       /* There can be only one.  */
12354       if (sections->abbrev.s.section != NULL)
12355         return 0;
12356       sections->abbrev.s.section = sectp;
12357       sections->abbrev.size = bfd_get_section_size (sectp);
12358     }
12359   else if (section_is_p (sectp->name, &names->info_dwo)
12360            || section_is_p (sectp->name, &names->types_dwo))
12361     {
12362       /* There can be only one.  */
12363       if (sections->info_or_types.s.section != NULL)
12364         return 0;
12365       sections->info_or_types.s.section = sectp;
12366       sections->info_or_types.size = bfd_get_section_size (sectp);
12367     }
12368   else if (section_is_p (sectp->name, &names->line_dwo))
12369     {
12370       /* There can be only one.  */
12371       if (sections->line.s.section != NULL)
12372         return 0;
12373       sections->line.s.section = sectp;
12374       sections->line.size = bfd_get_section_size (sectp);
12375     }
12376   else if (section_is_p (sectp->name, &names->loc_dwo))
12377     {
12378       /* There can be only one.  */
12379       if (sections->loc.s.section != NULL)
12380         return 0;
12381       sections->loc.s.section = sectp;
12382       sections->loc.size = bfd_get_section_size (sectp);
12383     }
12384   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12385     {
12386       /* There can be only one.  */
12387       if (sections->macinfo.s.section != NULL)
12388         return 0;
12389       sections->macinfo.s.section = sectp;
12390       sections->macinfo.size = bfd_get_section_size (sectp);
12391     }
12392   else if (section_is_p (sectp->name, &names->macro_dwo))
12393     {
12394       /* There can be only one.  */
12395       if (sections->macro.s.section != NULL)
12396         return 0;
12397       sections->macro.s.section = sectp;
12398       sections->macro.size = bfd_get_section_size (sectp);
12399     }
12400   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12401     {
12402       /* There can be only one.  */
12403       if (sections->str_offsets.s.section != NULL)
12404         return 0;
12405       sections->str_offsets.s.section = sectp;
12406       sections->str_offsets.size = bfd_get_section_size (sectp);
12407     }
12408   else
12409     {
12410       /* No other kind of section is valid.  */
12411       return 0;
12412     }
12413
12414   return 1;
12415 }
12416
12417 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12418    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12419    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12420    This is for DWP version 1 files.  */
12421
12422 static struct dwo_unit *
12423 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12424                            struct dwp_file *dwp_file,
12425                            uint32_t unit_index,
12426                            const char *comp_dir,
12427                            ULONGEST signature, int is_debug_types)
12428 {
12429   struct objfile *objfile = dwarf2_per_objfile->objfile;
12430   const struct dwp_hash_table *dwp_htab =
12431     is_debug_types ? dwp_file->tus : dwp_file->cus;
12432   bfd *dbfd = dwp_file->dbfd;
12433   const char *kind = is_debug_types ? "TU" : "CU";
12434   struct dwo_file *dwo_file;
12435   struct dwo_unit *dwo_unit;
12436   struct virtual_v1_dwo_sections sections;
12437   void **dwo_file_slot;
12438   int i;
12439
12440   gdb_assert (dwp_file->version == 1);
12441
12442   if (dwarf_read_debug)
12443     {
12444       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12445                           kind,
12446                           pulongest (unit_index), hex_string (signature),
12447                           dwp_file->name);
12448     }
12449
12450   /* Fetch the sections of this DWO unit.
12451      Put a limit on the number of sections we look for so that bad data
12452      doesn't cause us to loop forever.  */
12453
12454 #define MAX_NR_V1_DWO_SECTIONS \
12455   (1 /* .debug_info or .debug_types */ \
12456    + 1 /* .debug_abbrev */ \
12457    + 1 /* .debug_line */ \
12458    + 1 /* .debug_loc */ \
12459    + 1 /* .debug_str_offsets */ \
12460    + 1 /* .debug_macro or .debug_macinfo */ \
12461    + 1 /* trailing zero */)
12462
12463   memset (&sections, 0, sizeof (sections));
12464
12465   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12466     {
12467       asection *sectp;
12468       uint32_t section_nr =
12469         read_4_bytes (dbfd,
12470                       dwp_htab->section_pool.v1.indices
12471                       + (unit_index + i) * sizeof (uint32_t));
12472
12473       if (section_nr == 0)
12474         break;
12475       if (section_nr >= dwp_file->num_sections)
12476         {
12477           error (_("Dwarf Error: bad DWP hash table, section number too large"
12478                    " [in module %s]"),
12479                  dwp_file->name);
12480         }
12481
12482       sectp = dwp_file->elf_sections[section_nr];
12483       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12484         {
12485           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12486                    " [in module %s]"),
12487                  dwp_file->name);
12488         }
12489     }
12490
12491   if (i < 2
12492       || dwarf2_section_empty_p (&sections.info_or_types)
12493       || dwarf2_section_empty_p (&sections.abbrev))
12494     {
12495       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12496                " [in module %s]"),
12497              dwp_file->name);
12498     }
12499   if (i == MAX_NR_V1_DWO_SECTIONS)
12500     {
12501       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12502                " [in module %s]"),
12503              dwp_file->name);
12504     }
12505
12506   /* It's easier for the rest of the code if we fake a struct dwo_file and
12507      have dwo_unit "live" in that.  At least for now.
12508
12509      The DWP file can be made up of a random collection of CUs and TUs.
12510      However, for each CU + set of TUs that came from the same original DWO
12511      file, we can combine them back into a virtual DWO file to save space
12512      (fewer struct dwo_file objects to allocate).  Remember that for really
12513      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12514
12515   std::string virtual_dwo_name =
12516     string_printf ("virtual-dwo/%d-%d-%d-%d",
12517                    get_section_id (&sections.abbrev),
12518                    get_section_id (&sections.line),
12519                    get_section_id (&sections.loc),
12520                    get_section_id (&sections.str_offsets));
12521   /* Can we use an existing virtual DWO file?  */
12522   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12523                                         virtual_dwo_name.c_str (),
12524                                         comp_dir);
12525   /* Create one if necessary.  */
12526   if (*dwo_file_slot == NULL)
12527     {
12528       if (dwarf_read_debug)
12529         {
12530           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12531                               virtual_dwo_name.c_str ());
12532         }
12533       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12534       dwo_file->dwo_name
12535         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12536                                         virtual_dwo_name.c_str (),
12537                                         virtual_dwo_name.size ());
12538       dwo_file->comp_dir = comp_dir;
12539       dwo_file->sections.abbrev = sections.abbrev;
12540       dwo_file->sections.line = sections.line;
12541       dwo_file->sections.loc = sections.loc;
12542       dwo_file->sections.macinfo = sections.macinfo;
12543       dwo_file->sections.macro = sections.macro;
12544       dwo_file->sections.str_offsets = sections.str_offsets;
12545       /* The "str" section is global to the entire DWP file.  */
12546       dwo_file->sections.str = dwp_file->sections.str;
12547       /* The info or types section is assigned below to dwo_unit,
12548          there's no need to record it in dwo_file.
12549          Also, we can't simply record type sections in dwo_file because
12550          we record a pointer into the vector in dwo_unit.  As we collect more
12551          types we'll grow the vector and eventually have to reallocate space
12552          for it, invalidating all copies of pointers into the previous
12553          contents.  */
12554       *dwo_file_slot = dwo_file;
12555     }
12556   else
12557     {
12558       if (dwarf_read_debug)
12559         {
12560           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12561                               virtual_dwo_name.c_str ());
12562         }
12563       dwo_file = (struct dwo_file *) *dwo_file_slot;
12564     }
12565
12566   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12567   dwo_unit->dwo_file = dwo_file;
12568   dwo_unit->signature = signature;
12569   dwo_unit->section =
12570     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12571   *dwo_unit->section = sections.info_or_types;
12572   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12573
12574   return dwo_unit;
12575 }
12576
12577 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12578    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12579    piece within that section used by a TU/CU, return a virtual section
12580    of just that piece.  */
12581
12582 static struct dwarf2_section_info
12583 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12584                        struct dwarf2_section_info *section,
12585                        bfd_size_type offset, bfd_size_type size)
12586 {
12587   struct dwarf2_section_info result;
12588   asection *sectp;
12589
12590   gdb_assert (section != NULL);
12591   gdb_assert (!section->is_virtual);
12592
12593   memset (&result, 0, sizeof (result));
12594   result.s.containing_section = section;
12595   result.is_virtual = 1;
12596
12597   if (size == 0)
12598     return result;
12599
12600   sectp = get_section_bfd_section (section);
12601
12602   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12603      bounds of the real section.  This is a pretty-rare event, so just
12604      flag an error (easier) instead of a warning and trying to cope.  */
12605   if (sectp == NULL
12606       || offset + size > bfd_get_section_size (sectp))
12607     {
12608       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12609                " in section %s [in module %s]"),
12610              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12611              objfile_name (dwarf2_per_objfile->objfile));
12612     }
12613
12614   result.virtual_offset = offset;
12615   result.size = size;
12616   return result;
12617 }
12618
12619 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12620    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12621    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12622    This is for DWP version 2 files.  */
12623
12624 static struct dwo_unit *
12625 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12626                            struct dwp_file *dwp_file,
12627                            uint32_t unit_index,
12628                            const char *comp_dir,
12629                            ULONGEST signature, int is_debug_types)
12630 {
12631   struct objfile *objfile = dwarf2_per_objfile->objfile;
12632   const struct dwp_hash_table *dwp_htab =
12633     is_debug_types ? dwp_file->tus : dwp_file->cus;
12634   bfd *dbfd = dwp_file->dbfd;
12635   const char *kind = is_debug_types ? "TU" : "CU";
12636   struct dwo_file *dwo_file;
12637   struct dwo_unit *dwo_unit;
12638   struct virtual_v2_dwo_sections sections;
12639   void **dwo_file_slot;
12640   int i;
12641
12642   gdb_assert (dwp_file->version == 2);
12643
12644   if (dwarf_read_debug)
12645     {
12646       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12647                           kind,
12648                           pulongest (unit_index), hex_string (signature),
12649                           dwp_file->name);
12650     }
12651
12652   /* Fetch the section offsets of this DWO unit.  */
12653
12654   memset (&sections, 0, sizeof (sections));
12655
12656   for (i = 0; i < dwp_htab->nr_columns; ++i)
12657     {
12658       uint32_t offset = read_4_bytes (dbfd,
12659                                       dwp_htab->section_pool.v2.offsets
12660                                       + (((unit_index - 1) * dwp_htab->nr_columns
12661                                           + i)
12662                                          * sizeof (uint32_t)));
12663       uint32_t size = read_4_bytes (dbfd,
12664                                     dwp_htab->section_pool.v2.sizes
12665                                     + (((unit_index - 1) * dwp_htab->nr_columns
12666                                         + i)
12667                                        * sizeof (uint32_t)));
12668
12669       switch (dwp_htab->section_pool.v2.section_ids[i])
12670         {
12671         case DW_SECT_INFO:
12672         case DW_SECT_TYPES:
12673           sections.info_or_types_offset = offset;
12674           sections.info_or_types_size = size;
12675           break;
12676         case DW_SECT_ABBREV:
12677           sections.abbrev_offset = offset;
12678           sections.abbrev_size = size;
12679           break;
12680         case DW_SECT_LINE:
12681           sections.line_offset = offset;
12682           sections.line_size = size;
12683           break;
12684         case DW_SECT_LOC:
12685           sections.loc_offset = offset;
12686           sections.loc_size = size;
12687           break;
12688         case DW_SECT_STR_OFFSETS:
12689           sections.str_offsets_offset = offset;
12690           sections.str_offsets_size = size;
12691           break;
12692         case DW_SECT_MACINFO:
12693           sections.macinfo_offset = offset;
12694           sections.macinfo_size = size;
12695           break;
12696         case DW_SECT_MACRO:
12697           sections.macro_offset = offset;
12698           sections.macro_size = size;
12699           break;
12700         }
12701     }
12702
12703   /* It's easier for the rest of the code if we fake a struct dwo_file and
12704      have dwo_unit "live" in that.  At least for now.
12705
12706      The DWP file can be made up of a random collection of CUs and TUs.
12707      However, for each CU + set of TUs that came from the same original DWO
12708      file, we can combine them back into a virtual DWO file to save space
12709      (fewer struct dwo_file objects to allocate).  Remember that for really
12710      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12711
12712   std::string virtual_dwo_name =
12713     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12714                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12715                    (long) (sections.line_size ? sections.line_offset : 0),
12716                    (long) (sections.loc_size ? sections.loc_offset : 0),
12717                    (long) (sections.str_offsets_size
12718                            ? sections.str_offsets_offset : 0));
12719   /* Can we use an existing virtual DWO file?  */
12720   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12721                                         virtual_dwo_name.c_str (),
12722                                         comp_dir);
12723   /* Create one if necessary.  */
12724   if (*dwo_file_slot == NULL)
12725     {
12726       if (dwarf_read_debug)
12727         {
12728           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12729                               virtual_dwo_name.c_str ());
12730         }
12731       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12732       dwo_file->dwo_name
12733         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12734                                         virtual_dwo_name.c_str (),
12735                                         virtual_dwo_name.size ());
12736       dwo_file->comp_dir = comp_dir;
12737       dwo_file->sections.abbrev =
12738         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12739                                sections.abbrev_offset, sections.abbrev_size);
12740       dwo_file->sections.line =
12741         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12742                                sections.line_offset, sections.line_size);
12743       dwo_file->sections.loc =
12744         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12745                                sections.loc_offset, sections.loc_size);
12746       dwo_file->sections.macinfo =
12747         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12748                                sections.macinfo_offset, sections.macinfo_size);
12749       dwo_file->sections.macro =
12750         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12751                                sections.macro_offset, sections.macro_size);
12752       dwo_file->sections.str_offsets =
12753         create_dwp_v2_section (dwarf2_per_objfile,
12754                                &dwp_file->sections.str_offsets,
12755                                sections.str_offsets_offset,
12756                                sections.str_offsets_size);
12757       /* The "str" section is global to the entire DWP file.  */
12758       dwo_file->sections.str = dwp_file->sections.str;
12759       /* The info or types section is assigned below to dwo_unit,
12760          there's no need to record it in dwo_file.
12761          Also, we can't simply record type sections in dwo_file because
12762          we record a pointer into the vector in dwo_unit.  As we collect more
12763          types we'll grow the vector and eventually have to reallocate space
12764          for it, invalidating all copies of pointers into the previous
12765          contents.  */
12766       *dwo_file_slot = dwo_file;
12767     }
12768   else
12769     {
12770       if (dwarf_read_debug)
12771         {
12772           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12773                               virtual_dwo_name.c_str ());
12774         }
12775       dwo_file = (struct dwo_file *) *dwo_file_slot;
12776     }
12777
12778   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12779   dwo_unit->dwo_file = dwo_file;
12780   dwo_unit->signature = signature;
12781   dwo_unit->section =
12782     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12783   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12784                                               is_debug_types
12785                                               ? &dwp_file->sections.types
12786                                               : &dwp_file->sections.info,
12787                                               sections.info_or_types_offset,
12788                                               sections.info_or_types_size);
12789   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12790
12791   return dwo_unit;
12792 }
12793
12794 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12795    Returns NULL if the signature isn't found.  */
12796
12797 static struct dwo_unit *
12798 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12799                         struct dwp_file *dwp_file, const char *comp_dir,
12800                         ULONGEST signature, int is_debug_types)
12801 {
12802   const struct dwp_hash_table *dwp_htab =
12803     is_debug_types ? dwp_file->tus : dwp_file->cus;
12804   bfd *dbfd = dwp_file->dbfd;
12805   uint32_t mask = dwp_htab->nr_slots - 1;
12806   uint32_t hash = signature & mask;
12807   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12808   unsigned int i;
12809   void **slot;
12810   struct dwo_unit find_dwo_cu;
12811
12812   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12813   find_dwo_cu.signature = signature;
12814   slot = htab_find_slot (is_debug_types
12815                          ? dwp_file->loaded_tus
12816                          : dwp_file->loaded_cus,
12817                          &find_dwo_cu, INSERT);
12818
12819   if (*slot != NULL)
12820     return (struct dwo_unit *) *slot;
12821
12822   /* Use a for loop so that we don't loop forever on bad debug info.  */
12823   for (i = 0; i < dwp_htab->nr_slots; ++i)
12824     {
12825       ULONGEST signature_in_table;
12826
12827       signature_in_table =
12828         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12829       if (signature_in_table == signature)
12830         {
12831           uint32_t unit_index =
12832             read_4_bytes (dbfd,
12833                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12834
12835           if (dwp_file->version == 1)
12836             {
12837               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12838                                                  dwp_file, unit_index,
12839                                                  comp_dir, signature,
12840                                                  is_debug_types);
12841             }
12842           else
12843             {
12844               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12845                                                  dwp_file, unit_index,
12846                                                  comp_dir, signature,
12847                                                  is_debug_types);
12848             }
12849           return (struct dwo_unit *) *slot;
12850         }
12851       if (signature_in_table == 0)
12852         return NULL;
12853       hash = (hash + hash2) & mask;
12854     }
12855
12856   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12857            " [in module %s]"),
12858          dwp_file->name);
12859 }
12860
12861 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12862    Open the file specified by FILE_NAME and hand it off to BFD for
12863    preliminary analysis.  Return a newly initialized bfd *, which
12864    includes a canonicalized copy of FILE_NAME.
12865    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12866    SEARCH_CWD is true if the current directory is to be searched.
12867    It will be searched before debug-file-directory.
12868    If successful, the file is added to the bfd include table of the
12869    objfile's bfd (see gdb_bfd_record_inclusion).
12870    If unable to find/open the file, return NULL.
12871    NOTE: This function is derived from symfile_bfd_open.  */
12872
12873 static gdb_bfd_ref_ptr
12874 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12875                     const char *file_name, int is_dwp, int search_cwd)
12876 {
12877   int desc, flags;
12878   char *absolute_name;
12879   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12880      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12881      to debug_file_directory.  */
12882   char *search_path;
12883   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12884
12885   if (search_cwd)
12886     {
12887       if (*debug_file_directory != '\0')
12888         search_path = concat (".", dirname_separator_string,
12889                               debug_file_directory, (char *) NULL);
12890       else
12891         search_path = xstrdup (".");
12892     }
12893   else
12894     search_path = xstrdup (debug_file_directory);
12895
12896   flags = OPF_RETURN_REALPATH;
12897   if (is_dwp)
12898     flags |= OPF_SEARCH_IN_PATH;
12899   desc = openp (search_path, flags, file_name,
12900                 O_RDONLY | O_BINARY, &absolute_name);
12901   xfree (search_path);
12902   if (desc < 0)
12903     return NULL;
12904
12905   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12906   xfree (absolute_name);
12907   if (sym_bfd == NULL)
12908     return NULL;
12909   bfd_set_cacheable (sym_bfd.get (), 1);
12910
12911   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12912     return NULL;
12913
12914   /* Success.  Record the bfd as having been included by the objfile's bfd.
12915      This is important because things like demangled_names_hash lives in the
12916      objfile's per_bfd space and may have references to things like symbol
12917      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12918   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12919
12920   return sym_bfd;
12921 }
12922
12923 /* Try to open DWO file FILE_NAME.
12924    COMP_DIR is the DW_AT_comp_dir attribute.
12925    The result is the bfd handle of the file.
12926    If there is a problem finding or opening the file, return NULL.
12927    Upon success, the canonicalized path of the file is stored in the bfd,
12928    same as symfile_bfd_open.  */
12929
12930 static gdb_bfd_ref_ptr
12931 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12932                const char *file_name, const char *comp_dir)
12933 {
12934   if (IS_ABSOLUTE_PATH (file_name))
12935     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12936                                0 /*is_dwp*/, 0 /*search_cwd*/);
12937
12938   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12939
12940   if (comp_dir != NULL)
12941     {
12942       char *path_to_try = concat (comp_dir, SLASH_STRING,
12943                                   file_name, (char *) NULL);
12944
12945       /* NOTE: If comp_dir is a relative path, this will also try the
12946          search path, which seems useful.  */
12947       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12948                                                 path_to_try,
12949                                                 0 /*is_dwp*/,
12950                                                 1 /*search_cwd*/));
12951       xfree (path_to_try);
12952       if (abfd != NULL)
12953         return abfd;
12954     }
12955
12956   /* That didn't work, try debug-file-directory, which, despite its name,
12957      is a list of paths.  */
12958
12959   if (*debug_file_directory == '\0')
12960     return NULL;
12961
12962   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12963                              0 /*is_dwp*/, 1 /*search_cwd*/);
12964 }
12965
12966 /* This function is mapped across the sections and remembers the offset and
12967    size of each of the DWO debugging sections we are interested in.  */
12968
12969 static void
12970 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12971 {
12972   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12973   const struct dwop_section_names *names = &dwop_section_names;
12974
12975   if (section_is_p (sectp->name, &names->abbrev_dwo))
12976     {
12977       dwo_sections->abbrev.s.section = sectp;
12978       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12979     }
12980   else if (section_is_p (sectp->name, &names->info_dwo))
12981     {
12982       dwo_sections->info.s.section = sectp;
12983       dwo_sections->info.size = bfd_get_section_size (sectp);
12984     }
12985   else if (section_is_p (sectp->name, &names->line_dwo))
12986     {
12987       dwo_sections->line.s.section = sectp;
12988       dwo_sections->line.size = bfd_get_section_size (sectp);
12989     }
12990   else if (section_is_p (sectp->name, &names->loc_dwo))
12991     {
12992       dwo_sections->loc.s.section = sectp;
12993       dwo_sections->loc.size = bfd_get_section_size (sectp);
12994     }
12995   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12996     {
12997       dwo_sections->macinfo.s.section = sectp;
12998       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12999     }
13000   else if (section_is_p (sectp->name, &names->macro_dwo))
13001     {
13002       dwo_sections->macro.s.section = sectp;
13003       dwo_sections->macro.size = bfd_get_section_size (sectp);
13004     }
13005   else if (section_is_p (sectp->name, &names->str_dwo))
13006     {
13007       dwo_sections->str.s.section = sectp;
13008       dwo_sections->str.size = bfd_get_section_size (sectp);
13009     }
13010   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13011     {
13012       dwo_sections->str_offsets.s.section = sectp;
13013       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13014     }
13015   else if (section_is_p (sectp->name, &names->types_dwo))
13016     {
13017       struct dwarf2_section_info type_section;
13018
13019       memset (&type_section, 0, sizeof (type_section));
13020       type_section.s.section = sectp;
13021       type_section.size = bfd_get_section_size (sectp);
13022       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13023                      &type_section);
13024     }
13025 }
13026
13027 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13028    by PER_CU.  This is for the non-DWP case.
13029    The result is NULL if DWO_NAME can't be found.  */
13030
13031 static struct dwo_file *
13032 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13033                         const char *dwo_name, const char *comp_dir)
13034 {
13035   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13036   struct objfile *objfile = dwarf2_per_objfile->objfile;
13037   struct dwo_file *dwo_file;
13038   struct cleanup *cleanups;
13039
13040   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13041   if (dbfd == NULL)
13042     {
13043       if (dwarf_read_debug)
13044         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13045       return NULL;
13046     }
13047   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13048   dwo_file->dwo_name = dwo_name;
13049   dwo_file->comp_dir = comp_dir;
13050   dwo_file->dbfd = dbfd.release ();
13051
13052   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13053   cleanup_data->dwo_file = dwo_file;
13054   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13055
13056   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13057
13058   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13059                          &dwo_file->sections);
13060
13061   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13062                          dwo_file->cus);
13063
13064   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13065                                  dwo_file->sections.types, dwo_file->tus);
13066
13067   discard_cleanups (cleanups);
13068
13069   if (dwarf_read_debug)
13070     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13071
13072   return dwo_file;
13073 }
13074
13075 /* This function is mapped across the sections and remembers the offset and
13076    size of each of the DWP debugging sections common to version 1 and 2 that
13077    we are interested in.  */
13078
13079 static void
13080 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13081                                    void *dwp_file_ptr)
13082 {
13083   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13084   const struct dwop_section_names *names = &dwop_section_names;
13085   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13086
13087   /* Record the ELF section number for later lookup: this is what the
13088      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13089   gdb_assert (elf_section_nr < dwp_file->num_sections);
13090   dwp_file->elf_sections[elf_section_nr] = sectp;
13091
13092   /* Look for specific sections that we need.  */
13093   if (section_is_p (sectp->name, &names->str_dwo))
13094     {
13095       dwp_file->sections.str.s.section = sectp;
13096       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13097     }
13098   else if (section_is_p (sectp->name, &names->cu_index))
13099     {
13100       dwp_file->sections.cu_index.s.section = sectp;
13101       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13102     }
13103   else if (section_is_p (sectp->name, &names->tu_index))
13104     {
13105       dwp_file->sections.tu_index.s.section = sectp;
13106       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13107     }
13108 }
13109
13110 /* This function is mapped across the sections and remembers the offset and
13111    size of each of the DWP version 2 debugging sections that we are interested
13112    in.  This is split into a separate function because we don't know if we
13113    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13114
13115 static void
13116 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13117 {
13118   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13119   const struct dwop_section_names *names = &dwop_section_names;
13120   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13121
13122   /* Record the ELF section number for later lookup: this is what the
13123      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13124   gdb_assert (elf_section_nr < dwp_file->num_sections);
13125   dwp_file->elf_sections[elf_section_nr] = sectp;
13126
13127   /* Look for specific sections that we need.  */
13128   if (section_is_p (sectp->name, &names->abbrev_dwo))
13129     {
13130       dwp_file->sections.abbrev.s.section = sectp;
13131       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13132     }
13133   else if (section_is_p (sectp->name, &names->info_dwo))
13134     {
13135       dwp_file->sections.info.s.section = sectp;
13136       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13137     }
13138   else if (section_is_p (sectp->name, &names->line_dwo))
13139     {
13140       dwp_file->sections.line.s.section = sectp;
13141       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13142     }
13143   else if (section_is_p (sectp->name, &names->loc_dwo))
13144     {
13145       dwp_file->sections.loc.s.section = sectp;
13146       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13147     }
13148   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13149     {
13150       dwp_file->sections.macinfo.s.section = sectp;
13151       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13152     }
13153   else if (section_is_p (sectp->name, &names->macro_dwo))
13154     {
13155       dwp_file->sections.macro.s.section = sectp;
13156       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13157     }
13158   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13159     {
13160       dwp_file->sections.str_offsets.s.section = sectp;
13161       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13162     }
13163   else if (section_is_p (sectp->name, &names->types_dwo))
13164     {
13165       dwp_file->sections.types.s.section = sectp;
13166       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13167     }
13168 }
13169
13170 /* Hash function for dwp_file loaded CUs/TUs.  */
13171
13172 static hashval_t
13173 hash_dwp_loaded_cutus (const void *item)
13174 {
13175   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13176
13177   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13178   return dwo_unit->signature;
13179 }
13180
13181 /* Equality function for dwp_file loaded CUs/TUs.  */
13182
13183 static int
13184 eq_dwp_loaded_cutus (const void *a, const void *b)
13185 {
13186   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13187   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13188
13189   return dua->signature == dub->signature;
13190 }
13191
13192 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13193
13194 static htab_t
13195 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13196 {
13197   return htab_create_alloc_ex (3,
13198                                hash_dwp_loaded_cutus,
13199                                eq_dwp_loaded_cutus,
13200                                NULL,
13201                                &objfile->objfile_obstack,
13202                                hashtab_obstack_allocate,
13203                                dummy_obstack_deallocate);
13204 }
13205
13206 /* Try to open DWP file FILE_NAME.
13207    The result is the bfd handle of the file.
13208    If there is a problem finding or opening the file, return NULL.
13209    Upon success, the canonicalized path of the file is stored in the bfd,
13210    same as symfile_bfd_open.  */
13211
13212 static gdb_bfd_ref_ptr
13213 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13214                const char *file_name)
13215 {
13216   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13217                                             1 /*is_dwp*/,
13218                                             1 /*search_cwd*/));
13219   if (abfd != NULL)
13220     return abfd;
13221
13222   /* Work around upstream bug 15652.
13223      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13224      [Whether that's a "bug" is debatable, but it is getting in our way.]
13225      We have no real idea where the dwp file is, because gdb's realpath-ing
13226      of the executable's path may have discarded the needed info.
13227      [IWBN if the dwp file name was recorded in the executable, akin to
13228      .gnu_debuglink, but that doesn't exist yet.]
13229      Strip the directory from FILE_NAME and search again.  */
13230   if (*debug_file_directory != '\0')
13231     {
13232       /* Don't implicitly search the current directory here.
13233          If the user wants to search "." to handle this case,
13234          it must be added to debug-file-directory.  */
13235       return try_open_dwop_file (dwarf2_per_objfile,
13236                                  lbasename (file_name), 1 /*is_dwp*/,
13237                                  0 /*search_cwd*/);
13238     }
13239
13240   return NULL;
13241 }
13242
13243 /* Initialize the use of the DWP file for the current objfile.
13244    By convention the name of the DWP file is ${objfile}.dwp.
13245    The result is NULL if it can't be found.  */
13246
13247 static struct dwp_file *
13248 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13249 {
13250   struct objfile *objfile = dwarf2_per_objfile->objfile;
13251   struct dwp_file *dwp_file;
13252
13253   /* Try to find first .dwp for the binary file before any symbolic links
13254      resolving.  */
13255
13256   /* If the objfile is a debug file, find the name of the real binary
13257      file and get the name of dwp file from there.  */
13258   std::string dwp_name;
13259   if (objfile->separate_debug_objfile_backlink != NULL)
13260     {
13261       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13262       const char *backlink_basename = lbasename (backlink->original_name);
13263
13264       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13265     }
13266   else
13267     dwp_name = objfile->original_name;
13268
13269   dwp_name += ".dwp";
13270
13271   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13272   if (dbfd == NULL
13273       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13274     {
13275       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13276       dwp_name = objfile_name (objfile);
13277       dwp_name += ".dwp";
13278       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13279     }
13280
13281   if (dbfd == NULL)
13282     {
13283       if (dwarf_read_debug)
13284         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13285       return NULL;
13286     }
13287   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13288   dwp_file->name = bfd_get_filename (dbfd.get ());
13289   dwp_file->dbfd = dbfd.release ();
13290
13291   /* +1: section 0 is unused */
13292   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13293   dwp_file->elf_sections =
13294     OBSTACK_CALLOC (&objfile->objfile_obstack,
13295                     dwp_file->num_sections, asection *);
13296
13297   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13298                          dwp_file);
13299
13300   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13301
13302   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13303
13304   /* The DWP file version is stored in the hash table.  Oh well.  */
13305   if (dwp_file->cus && dwp_file->tus
13306       && dwp_file->cus->version != dwp_file->tus->version)
13307     {
13308       /* Technically speaking, we should try to limp along, but this is
13309          pretty bizarre.  We use pulongest here because that's the established
13310          portability solution (e.g, we cannot use %u for uint32_t).  */
13311       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13312                " TU version %s [in DWP file %s]"),
13313              pulongest (dwp_file->cus->version),
13314              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13315     }
13316
13317   if (dwp_file->cus)
13318     dwp_file->version = dwp_file->cus->version;
13319   else if (dwp_file->tus)
13320     dwp_file->version = dwp_file->tus->version;
13321   else
13322     dwp_file->version = 2;
13323
13324   if (dwp_file->version == 2)
13325     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13326                            dwp_file);
13327
13328   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13329   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13330
13331   if (dwarf_read_debug)
13332     {
13333       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13334       fprintf_unfiltered (gdb_stdlog,
13335                           "    %s CUs, %s TUs\n",
13336                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13337                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13338     }
13339
13340   return dwp_file;
13341 }
13342
13343 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13344
13345 static struct dwp_file *
13346 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13347 {
13348   if (! dwarf2_per_objfile->dwp_checked)
13349     {
13350       dwarf2_per_objfile->dwp_file
13351         = open_and_init_dwp_file (dwarf2_per_objfile);
13352       dwarf2_per_objfile->dwp_checked = 1;
13353     }
13354   return dwarf2_per_objfile->dwp_file;
13355 }
13356
13357 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13358    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13359    or in the DWP file for the objfile, referenced by THIS_UNIT.
13360    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13361    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13362
13363    This is called, for example, when wanting to read a variable with a
13364    complex location.  Therefore we don't want to do file i/o for every call.
13365    Therefore we don't want to look for a DWO file on every call.
13366    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13367    then we check if we've already seen DWO_NAME, and only THEN do we check
13368    for a DWO file.
13369
13370    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13371    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13372
13373 static struct dwo_unit *
13374 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13375                  const char *dwo_name, const char *comp_dir,
13376                  ULONGEST signature, int is_debug_types)
13377 {
13378   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13379   struct objfile *objfile = dwarf2_per_objfile->objfile;
13380   const char *kind = is_debug_types ? "TU" : "CU";
13381   void **dwo_file_slot;
13382   struct dwo_file *dwo_file;
13383   struct dwp_file *dwp_file;
13384
13385   /* First see if there's a DWP file.
13386      If we have a DWP file but didn't find the DWO inside it, don't
13387      look for the original DWO file.  It makes gdb behave differently
13388      depending on whether one is debugging in the build tree.  */
13389
13390   dwp_file = get_dwp_file (dwarf2_per_objfile);
13391   if (dwp_file != NULL)
13392     {
13393       const struct dwp_hash_table *dwp_htab =
13394         is_debug_types ? dwp_file->tus : dwp_file->cus;
13395
13396       if (dwp_htab != NULL)
13397         {
13398           struct dwo_unit *dwo_cutu =
13399             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13400                                     signature, is_debug_types);
13401
13402           if (dwo_cutu != NULL)
13403             {
13404               if (dwarf_read_debug)
13405                 {
13406                   fprintf_unfiltered (gdb_stdlog,
13407                                       "Virtual DWO %s %s found: @%s\n",
13408                                       kind, hex_string (signature),
13409                                       host_address_to_string (dwo_cutu));
13410                 }
13411               return dwo_cutu;
13412             }
13413         }
13414     }
13415   else
13416     {
13417       /* No DWP file, look for the DWO file.  */
13418
13419       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13420                                             dwo_name, comp_dir);
13421       if (*dwo_file_slot == NULL)
13422         {
13423           /* Read in the file and build a table of the CUs/TUs it contains.  */
13424           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13425         }
13426       /* NOTE: This will be NULL if unable to open the file.  */
13427       dwo_file = (struct dwo_file *) *dwo_file_slot;
13428
13429       if (dwo_file != NULL)
13430         {
13431           struct dwo_unit *dwo_cutu = NULL;
13432
13433           if (is_debug_types && dwo_file->tus)
13434             {
13435               struct dwo_unit find_dwo_cutu;
13436
13437               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13438               find_dwo_cutu.signature = signature;
13439               dwo_cutu
13440                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13441             }
13442           else if (!is_debug_types && dwo_file->cus)
13443             {
13444               struct dwo_unit find_dwo_cutu;
13445
13446               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13447               find_dwo_cutu.signature = signature;
13448               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13449                                                        &find_dwo_cutu);
13450             }
13451
13452           if (dwo_cutu != NULL)
13453             {
13454               if (dwarf_read_debug)
13455                 {
13456                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13457                                       kind, dwo_name, hex_string (signature),
13458                                       host_address_to_string (dwo_cutu));
13459                 }
13460               return dwo_cutu;
13461             }
13462         }
13463     }
13464
13465   /* We didn't find it.  This could mean a dwo_id mismatch, or
13466      someone deleted the DWO/DWP file, or the search path isn't set up
13467      correctly to find the file.  */
13468
13469   if (dwarf_read_debug)
13470     {
13471       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13472                           kind, dwo_name, hex_string (signature));
13473     }
13474
13475   /* This is a warning and not a complaint because it can be caused by
13476      pilot error (e.g., user accidentally deleting the DWO).  */
13477   {
13478     /* Print the name of the DWP file if we looked there, helps the user
13479        better diagnose the problem.  */
13480     std::string dwp_text;
13481
13482     if (dwp_file != NULL)
13483       dwp_text = string_printf (" [in DWP file %s]",
13484                                 lbasename (dwp_file->name));
13485
13486     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13487                " [in module %s]"),
13488              kind, dwo_name, hex_string (signature),
13489              dwp_text.c_str (),
13490              this_unit->is_debug_types ? "TU" : "CU",
13491              to_underlying (this_unit->sect_off), objfile_name (objfile));
13492   }
13493   return NULL;
13494 }
13495
13496 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13497    See lookup_dwo_cutu_unit for details.  */
13498
13499 static struct dwo_unit *
13500 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13501                       const char *dwo_name, const char *comp_dir,
13502                       ULONGEST signature)
13503 {
13504   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13505 }
13506
13507 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13508    See lookup_dwo_cutu_unit for details.  */
13509
13510 static struct dwo_unit *
13511 lookup_dwo_type_unit (struct signatured_type *this_tu,
13512                       const char *dwo_name, const char *comp_dir)
13513 {
13514   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13515 }
13516
13517 /* Traversal function for queue_and_load_all_dwo_tus.  */
13518
13519 static int
13520 queue_and_load_dwo_tu (void **slot, void *info)
13521 {
13522   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13523   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13524   ULONGEST signature = dwo_unit->signature;
13525   struct signatured_type *sig_type =
13526     lookup_dwo_signatured_type (per_cu->cu, signature);
13527
13528   if (sig_type != NULL)
13529     {
13530       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13531
13532       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13533          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13534          while processing PER_CU.  */
13535       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13536         load_full_type_unit (sig_cu);
13537       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13538     }
13539
13540   return 1;
13541 }
13542
13543 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13544    The DWO may have the only definition of the type, though it may not be
13545    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13546    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13547
13548 static void
13549 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13550 {
13551   struct dwo_unit *dwo_unit;
13552   struct dwo_file *dwo_file;
13553
13554   gdb_assert (!per_cu->is_debug_types);
13555   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13556   gdb_assert (per_cu->cu != NULL);
13557
13558   dwo_unit = per_cu->cu->dwo_unit;
13559   gdb_assert (dwo_unit != NULL);
13560
13561   dwo_file = dwo_unit->dwo_file;
13562   if (dwo_file->tus != NULL)
13563     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13564 }
13565
13566 /* Free all resources associated with DWO_FILE.
13567    Close the DWO file and munmap the sections.
13568    All memory should be on the objfile obstack.  */
13569
13570 static void
13571 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13572 {
13573
13574   /* Note: dbfd is NULL for virtual DWO files.  */
13575   gdb_bfd_unref (dwo_file->dbfd);
13576
13577   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13578 }
13579
13580 /* Wrapper for free_dwo_file for use in cleanups.  */
13581
13582 static void
13583 free_dwo_file_cleanup (void *arg)
13584 {
13585   struct free_dwo_file_cleanup_data *data
13586     = (struct free_dwo_file_cleanup_data *) arg;
13587   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13588
13589   free_dwo_file (data->dwo_file, objfile);
13590
13591   xfree (data);
13592 }
13593
13594 /* Traversal function for free_dwo_files.  */
13595
13596 static int
13597 free_dwo_file_from_slot (void **slot, void *info)
13598 {
13599   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13600   struct objfile *objfile = (struct objfile *) info;
13601
13602   free_dwo_file (dwo_file, objfile);
13603
13604   return 1;
13605 }
13606
13607 /* Free all resources associated with DWO_FILES.  */
13608
13609 static void
13610 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13611 {
13612   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13613 }
13614 \f
13615 /* Read in various DIEs.  */
13616
13617 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13618    Inherit only the children of the DW_AT_abstract_origin DIE not being
13619    already referenced by DW_AT_abstract_origin from the children of the
13620    current DIE.  */
13621
13622 static void
13623 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13624 {
13625   struct die_info *child_die;
13626   sect_offset *offsetp;
13627   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13628   struct die_info *origin_die;
13629   /* Iterator of the ORIGIN_DIE children.  */
13630   struct die_info *origin_child_die;
13631   struct attribute *attr;
13632   struct dwarf2_cu *origin_cu;
13633   struct pending **origin_previous_list_in_scope;
13634
13635   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13636   if (!attr)
13637     return;
13638
13639   /* Note that following die references may follow to a die in a
13640      different cu.  */
13641
13642   origin_cu = cu;
13643   origin_die = follow_die_ref (die, attr, &origin_cu);
13644
13645   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13646      symbols in.  */
13647   origin_previous_list_in_scope = origin_cu->list_in_scope;
13648   origin_cu->list_in_scope = cu->list_in_scope;
13649
13650   if (die->tag != origin_die->tag
13651       && !(die->tag == DW_TAG_inlined_subroutine
13652            && origin_die->tag == DW_TAG_subprogram))
13653     complaint (&symfile_complaints,
13654                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13655                to_underlying (die->sect_off),
13656                to_underlying (origin_die->sect_off));
13657
13658   std::vector<sect_offset> offsets;
13659
13660   for (child_die = die->child;
13661        child_die && child_die->tag;
13662        child_die = sibling_die (child_die))
13663     {
13664       struct die_info *child_origin_die;
13665       struct dwarf2_cu *child_origin_cu;
13666
13667       /* We are trying to process concrete instance entries:
13668          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13669          it's not relevant to our analysis here. i.e. detecting DIEs that are
13670          present in the abstract instance but not referenced in the concrete
13671          one.  */
13672       if (child_die->tag == DW_TAG_call_site
13673           || child_die->tag == DW_TAG_GNU_call_site)
13674         continue;
13675
13676       /* For each CHILD_DIE, find the corresponding child of
13677          ORIGIN_DIE.  If there is more than one layer of
13678          DW_AT_abstract_origin, follow them all; there shouldn't be,
13679          but GCC versions at least through 4.4 generate this (GCC PR
13680          40573).  */
13681       child_origin_die = child_die;
13682       child_origin_cu = cu;
13683       while (1)
13684         {
13685           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13686                               child_origin_cu);
13687           if (attr == NULL)
13688             break;
13689           child_origin_die = follow_die_ref (child_origin_die, attr,
13690                                              &child_origin_cu);
13691         }
13692
13693       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13694          counterpart may exist.  */
13695       if (child_origin_die != child_die)
13696         {
13697           if (child_die->tag != child_origin_die->tag
13698               && !(child_die->tag == DW_TAG_inlined_subroutine
13699                    && child_origin_die->tag == DW_TAG_subprogram))
13700             complaint (&symfile_complaints,
13701                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13702                          "different tags"),
13703                        to_underlying (child_die->sect_off),
13704                        to_underlying (child_origin_die->sect_off));
13705           if (child_origin_die->parent != origin_die)
13706             complaint (&symfile_complaints,
13707                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13708                          "different parents"),
13709                        to_underlying (child_die->sect_off),
13710                        to_underlying (child_origin_die->sect_off));
13711           else
13712             offsets.push_back (child_origin_die->sect_off);
13713         }
13714     }
13715   std::sort (offsets.begin (), offsets.end ());
13716   sect_offset *offsets_end = offsets.data () + offsets.size ();
13717   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13718     if (offsetp[-1] == *offsetp)
13719       complaint (&symfile_complaints,
13720                  _("Multiple children of DIE 0x%x refer "
13721                    "to DIE 0x%x as their abstract origin"),
13722                  to_underlying (die->sect_off), to_underlying (*offsetp));
13723
13724   offsetp = offsets.data ();
13725   origin_child_die = origin_die->child;
13726   while (origin_child_die && origin_child_die->tag)
13727     {
13728       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13729       while (offsetp < offsets_end
13730              && *offsetp < origin_child_die->sect_off)
13731         offsetp++;
13732       if (offsetp >= offsets_end
13733           || *offsetp > origin_child_die->sect_off)
13734         {
13735           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13736              Check whether we're already processing ORIGIN_CHILD_DIE.
13737              This can happen with mutually referenced abstract_origins.
13738              PR 16581.  */
13739           if (!origin_child_die->in_process)
13740             process_die (origin_child_die, origin_cu);
13741         }
13742       origin_child_die = sibling_die (origin_child_die);
13743     }
13744   origin_cu->list_in_scope = origin_previous_list_in_scope;
13745 }
13746
13747 static void
13748 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13749 {
13750   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13751   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13752   struct context_stack *newobj;
13753   CORE_ADDR lowpc;
13754   CORE_ADDR highpc;
13755   struct die_info *child_die;
13756   struct attribute *attr, *call_line, *call_file;
13757   const char *name;
13758   CORE_ADDR baseaddr;
13759   struct block *block;
13760   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13761   std::vector<struct symbol *> template_args;
13762   struct template_symbol *templ_func = NULL;
13763
13764   if (inlined_func)
13765     {
13766       /* If we do not have call site information, we can't show the
13767          caller of this inlined function.  That's too confusing, so
13768          only use the scope for local variables.  */
13769       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13770       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13771       if (call_line == NULL || call_file == NULL)
13772         {
13773           read_lexical_block_scope (die, cu);
13774           return;
13775         }
13776     }
13777
13778   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13779
13780   name = dwarf2_name (die, cu);
13781
13782   /* Ignore functions with missing or empty names.  These are actually
13783      illegal according to the DWARF standard.  */
13784   if (name == NULL)
13785     {
13786       complaint (&symfile_complaints,
13787                  _("missing name for subprogram DIE at %d"),
13788                  to_underlying (die->sect_off));
13789       return;
13790     }
13791
13792   /* Ignore functions with missing or invalid low and high pc attributes.  */
13793   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13794       <= PC_BOUNDS_INVALID)
13795     {
13796       attr = dwarf2_attr (die, DW_AT_external, cu);
13797       if (!attr || !DW_UNSND (attr))
13798         complaint (&symfile_complaints,
13799                    _("cannot get low and high bounds "
13800                      "for subprogram DIE at %d"),
13801                    to_underlying (die->sect_off));
13802       return;
13803     }
13804
13805   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13806   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13807
13808   /* If we have any template arguments, then we must allocate a
13809      different sort of symbol.  */
13810   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13811     {
13812       if (child_die->tag == DW_TAG_template_type_param
13813           || child_die->tag == DW_TAG_template_value_param)
13814         {
13815           templ_func = allocate_template_symbol (objfile);
13816           templ_func->subclass = SYMBOL_TEMPLATE;
13817           break;
13818         }
13819     }
13820
13821   newobj = push_context (0, lowpc);
13822   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13823                              (struct symbol *) templ_func);
13824
13825   /* If there is a location expression for DW_AT_frame_base, record
13826      it.  */
13827   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13828   if (attr)
13829     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13830
13831   /* If there is a location for the static link, record it.  */
13832   newobj->static_link = NULL;
13833   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13834   if (attr)
13835     {
13836       newobj->static_link
13837         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13838       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13839     }
13840
13841   cu->list_in_scope = &local_symbols;
13842
13843   if (die->child != NULL)
13844     {
13845       child_die = die->child;
13846       while (child_die && child_die->tag)
13847         {
13848           if (child_die->tag == DW_TAG_template_type_param
13849               || child_die->tag == DW_TAG_template_value_param)
13850             {
13851               struct symbol *arg = new_symbol (child_die, NULL, cu);
13852
13853               if (arg != NULL)
13854                 template_args.push_back (arg);
13855             }
13856           else
13857             process_die (child_die, cu);
13858           child_die = sibling_die (child_die);
13859         }
13860     }
13861
13862   inherit_abstract_dies (die, cu);
13863
13864   /* If we have a DW_AT_specification, we might need to import using
13865      directives from the context of the specification DIE.  See the
13866      comment in determine_prefix.  */
13867   if (cu->language == language_cplus
13868       && dwarf2_attr (die, DW_AT_specification, cu))
13869     {
13870       struct dwarf2_cu *spec_cu = cu;
13871       struct die_info *spec_die = die_specification (die, &spec_cu);
13872
13873       while (spec_die)
13874         {
13875           child_die = spec_die->child;
13876           while (child_die && child_die->tag)
13877             {
13878               if (child_die->tag == DW_TAG_imported_module)
13879                 process_die (child_die, spec_cu);
13880               child_die = sibling_die (child_die);
13881             }
13882
13883           /* In some cases, GCC generates specification DIEs that
13884              themselves contain DW_AT_specification attributes.  */
13885           spec_die = die_specification (spec_die, &spec_cu);
13886         }
13887     }
13888
13889   newobj = pop_context ();
13890   /* Make a block for the local symbols within.  */
13891   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13892                         newobj->static_link, lowpc, highpc);
13893
13894   /* For C++, set the block's scope.  */
13895   if ((cu->language == language_cplus
13896        || cu->language == language_fortran
13897        || cu->language == language_d
13898        || cu->language == language_rust)
13899       && cu->processing_has_namespace_info)
13900     block_set_scope (block, determine_prefix (die, cu),
13901                      &objfile->objfile_obstack);
13902
13903   /* If we have address ranges, record them.  */
13904   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13905
13906   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13907
13908   /* Attach template arguments to function.  */
13909   if (!template_args.empty ())
13910     {
13911       gdb_assert (templ_func != NULL);
13912
13913       templ_func->n_template_arguments = template_args.size ();
13914       templ_func->template_arguments
13915         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13916                      templ_func->n_template_arguments);
13917       memcpy (templ_func->template_arguments,
13918               template_args.data (),
13919               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13920     }
13921
13922   /* In C++, we can have functions nested inside functions (e.g., when
13923      a function declares a class that has methods).  This means that
13924      when we finish processing a function scope, we may need to go
13925      back to building a containing block's symbol lists.  */
13926   local_symbols = newobj->locals;
13927   local_using_directives = newobj->local_using_directives;
13928
13929   /* If we've finished processing a top-level function, subsequent
13930      symbols go in the file symbol list.  */
13931   if (outermost_context_p ())
13932     cu->list_in_scope = &file_symbols;
13933 }
13934
13935 /* Process all the DIES contained within a lexical block scope.  Start
13936    a new scope, process the dies, and then close the scope.  */
13937
13938 static void
13939 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13940 {
13941   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13942   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13943   struct context_stack *newobj;
13944   CORE_ADDR lowpc, highpc;
13945   struct die_info *child_die;
13946   CORE_ADDR baseaddr;
13947
13948   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13949
13950   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13951   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13952      as multiple lexical blocks?  Handling children in a sane way would
13953      be nasty.  Might be easier to properly extend generic blocks to
13954      describe ranges.  */
13955   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13956     {
13957     case PC_BOUNDS_NOT_PRESENT:
13958       /* DW_TAG_lexical_block has no attributes, process its children as if
13959          there was no wrapping by that DW_TAG_lexical_block.
13960          GCC does no longer produces such DWARF since GCC r224161.  */
13961       for (child_die = die->child;
13962            child_die != NULL && child_die->tag;
13963            child_die = sibling_die (child_die))
13964         process_die (child_die, cu);
13965       return;
13966     case PC_BOUNDS_INVALID:
13967       return;
13968     }
13969   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13970   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13971
13972   push_context (0, lowpc);
13973   if (die->child != NULL)
13974     {
13975       child_die = die->child;
13976       while (child_die && child_die->tag)
13977         {
13978           process_die (child_die, cu);
13979           child_die = sibling_die (child_die);
13980         }
13981     }
13982   inherit_abstract_dies (die, cu);
13983   newobj = pop_context ();
13984
13985   if (local_symbols != NULL || local_using_directives != NULL)
13986     {
13987       struct block *block
13988         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13989                         newobj->start_addr, highpc);
13990
13991       /* Note that recording ranges after traversing children, as we
13992          do here, means that recording a parent's ranges entails
13993          walking across all its children's ranges as they appear in
13994          the address map, which is quadratic behavior.
13995
13996          It would be nicer to record the parent's ranges before
13997          traversing its children, simply overriding whatever you find
13998          there.  But since we don't even decide whether to create a
13999          block until after we've traversed its children, that's hard
14000          to do.  */
14001       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14002     }
14003   local_symbols = newobj->locals;
14004   local_using_directives = newobj->local_using_directives;
14005 }
14006
14007 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14008
14009 static void
14010 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14011 {
14012   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14013   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14014   CORE_ADDR pc, baseaddr;
14015   struct attribute *attr;
14016   struct call_site *call_site, call_site_local;
14017   void **slot;
14018   int nparams;
14019   struct die_info *child_die;
14020
14021   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14022
14023   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14024   if (attr == NULL)
14025     {
14026       /* This was a pre-DWARF-5 GNU extension alias
14027          for DW_AT_call_return_pc.  */
14028       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14029     }
14030   if (!attr)
14031     {
14032       complaint (&symfile_complaints,
14033                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14034                    "DIE 0x%x [in module %s]"),
14035                  to_underlying (die->sect_off), objfile_name (objfile));
14036       return;
14037     }
14038   pc = attr_value_as_address (attr) + baseaddr;
14039   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14040
14041   if (cu->call_site_htab == NULL)
14042     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14043                                                NULL, &objfile->objfile_obstack,
14044                                                hashtab_obstack_allocate, NULL);
14045   call_site_local.pc = pc;
14046   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14047   if (*slot != NULL)
14048     {
14049       complaint (&symfile_complaints,
14050                  _("Duplicate PC %s for DW_TAG_call_site "
14051                    "DIE 0x%x [in module %s]"),
14052                  paddress (gdbarch, pc), to_underlying (die->sect_off),
14053                  objfile_name (objfile));
14054       return;
14055     }
14056
14057   /* Count parameters at the caller.  */
14058
14059   nparams = 0;
14060   for (child_die = die->child; child_die && child_die->tag;
14061        child_die = sibling_die (child_die))
14062     {
14063       if (child_die->tag != DW_TAG_call_site_parameter
14064           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14065         {
14066           complaint (&symfile_complaints,
14067                      _("Tag %d is not DW_TAG_call_site_parameter in "
14068                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14069                      child_die->tag, to_underlying (child_die->sect_off),
14070                      objfile_name (objfile));
14071           continue;
14072         }
14073
14074       nparams++;
14075     }
14076
14077   call_site
14078     = ((struct call_site *)
14079        obstack_alloc (&objfile->objfile_obstack,
14080                       sizeof (*call_site)
14081                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14082   *slot = call_site;
14083   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14084   call_site->pc = pc;
14085
14086   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14087       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14088     {
14089       struct die_info *func_die;
14090
14091       /* Skip also over DW_TAG_inlined_subroutine.  */
14092       for (func_die = die->parent;
14093            func_die && func_die->tag != DW_TAG_subprogram
14094            && func_die->tag != DW_TAG_subroutine_type;
14095            func_die = func_die->parent);
14096
14097       /* DW_AT_call_all_calls is a superset
14098          of DW_AT_call_all_tail_calls.  */
14099       if (func_die
14100           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14101           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14102           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14103           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14104         {
14105           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14106              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14107              both the initial caller containing the real return address PC and
14108              the final callee containing the current PC of a chain of tail
14109              calls do not need to have the tail call list complete.  But any
14110              function candidate for a virtual tail call frame searched via
14111              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14112              determined unambiguously.  */
14113         }
14114       else
14115         {
14116           struct type *func_type = NULL;
14117
14118           if (func_die)
14119             func_type = get_die_type (func_die, cu);
14120           if (func_type != NULL)
14121             {
14122               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14123
14124               /* Enlist this call site to the function.  */
14125               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14126               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14127             }
14128           else
14129             complaint (&symfile_complaints,
14130                        _("Cannot find function owning DW_TAG_call_site "
14131                          "DIE 0x%x [in module %s]"),
14132                        to_underlying (die->sect_off), objfile_name (objfile));
14133         }
14134     }
14135
14136   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14137   if (attr == NULL)
14138     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14139   if (attr == NULL)
14140     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14141   if (attr == NULL)
14142     {
14143       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14144       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14145     }
14146   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14147   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14148     /* Keep NULL DWARF_BLOCK.  */;
14149   else if (attr_form_is_block (attr))
14150     {
14151       struct dwarf2_locexpr_baton *dlbaton;
14152
14153       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14154       dlbaton->data = DW_BLOCK (attr)->data;
14155       dlbaton->size = DW_BLOCK (attr)->size;
14156       dlbaton->per_cu = cu->per_cu;
14157
14158       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14159     }
14160   else if (attr_form_is_ref (attr))
14161     {
14162       struct dwarf2_cu *target_cu = cu;
14163       struct die_info *target_die;
14164
14165       target_die = follow_die_ref (die, attr, &target_cu);
14166       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14167       if (die_is_declaration (target_die, target_cu))
14168         {
14169           const char *target_physname;
14170
14171           /* Prefer the mangled name; otherwise compute the demangled one.  */
14172           target_physname = dw2_linkage_name (target_die, target_cu);
14173           if (target_physname == NULL)
14174             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14175           if (target_physname == NULL)
14176             complaint (&symfile_complaints,
14177                        _("DW_AT_call_target target DIE has invalid "
14178                          "physname, for referencing DIE 0x%x [in module %s]"),
14179                        to_underlying (die->sect_off), objfile_name (objfile));
14180           else
14181             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14182         }
14183       else
14184         {
14185           CORE_ADDR lowpc;
14186
14187           /* DW_AT_entry_pc should be preferred.  */
14188           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14189               <= PC_BOUNDS_INVALID)
14190             complaint (&symfile_complaints,
14191                        _("DW_AT_call_target target DIE has invalid "
14192                          "low pc, for referencing DIE 0x%x [in module %s]"),
14193                        to_underlying (die->sect_off), objfile_name (objfile));
14194           else
14195             {
14196               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14197               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14198             }
14199         }
14200     }
14201   else
14202     complaint (&symfile_complaints,
14203                _("DW_TAG_call_site DW_AT_call_target is neither "
14204                  "block nor reference, for DIE 0x%x [in module %s]"),
14205                to_underlying (die->sect_off), objfile_name (objfile));
14206
14207   call_site->per_cu = cu->per_cu;
14208
14209   for (child_die = die->child;
14210        child_die && child_die->tag;
14211        child_die = sibling_die (child_die))
14212     {
14213       struct call_site_parameter *parameter;
14214       struct attribute *loc, *origin;
14215
14216       if (child_die->tag != DW_TAG_call_site_parameter
14217           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14218         {
14219           /* Already printed the complaint above.  */
14220           continue;
14221         }
14222
14223       gdb_assert (call_site->parameter_count < nparams);
14224       parameter = &call_site->parameter[call_site->parameter_count];
14225
14226       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14227          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14228          register is contained in DW_AT_call_value.  */
14229
14230       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14231       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14232       if (origin == NULL)
14233         {
14234           /* This was a pre-DWARF-5 GNU extension alias
14235              for DW_AT_call_parameter.  */
14236           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14237         }
14238       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14239         {
14240           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14241
14242           sect_offset sect_off
14243             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14244           if (!offset_in_cu_p (&cu->header, sect_off))
14245             {
14246               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14247                  binding can be done only inside one CU.  Such referenced DIE
14248                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14249               complaint (&symfile_complaints,
14250                          _("DW_AT_call_parameter offset is not in CU for "
14251                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14252                          to_underlying (child_die->sect_off),
14253                          objfile_name (objfile));
14254               continue;
14255             }
14256           parameter->u.param_cu_off
14257             = (cu_offset) (sect_off - cu->header.sect_off);
14258         }
14259       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14260         {
14261           complaint (&symfile_complaints,
14262                      _("No DW_FORM_block* DW_AT_location for "
14263                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14264                      to_underlying (child_die->sect_off), objfile_name (objfile));
14265           continue;
14266         }
14267       else
14268         {
14269           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14270             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14271           if (parameter->u.dwarf_reg != -1)
14272             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14273           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14274                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14275                                              &parameter->u.fb_offset))
14276             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14277           else
14278             {
14279               complaint (&symfile_complaints,
14280                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14281                            "for DW_FORM_block* DW_AT_location is supported for "
14282                            "DW_TAG_call_site child DIE 0x%x "
14283                            "[in module %s]"),
14284                          to_underlying (child_die->sect_off),
14285                          objfile_name (objfile));
14286               continue;
14287             }
14288         }
14289
14290       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14291       if (attr == NULL)
14292         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14293       if (!attr_form_is_block (attr))
14294         {
14295           complaint (&symfile_complaints,
14296                      _("No DW_FORM_block* DW_AT_call_value for "
14297                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14298                      to_underlying (child_die->sect_off),
14299                      objfile_name (objfile));
14300           continue;
14301         }
14302       parameter->value = DW_BLOCK (attr)->data;
14303       parameter->value_size = DW_BLOCK (attr)->size;
14304
14305       /* Parameters are not pre-cleared by memset above.  */
14306       parameter->data_value = NULL;
14307       parameter->data_value_size = 0;
14308       call_site->parameter_count++;
14309
14310       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14311       if (attr == NULL)
14312         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14313       if (attr)
14314         {
14315           if (!attr_form_is_block (attr))
14316             complaint (&symfile_complaints,
14317                        _("No DW_FORM_block* DW_AT_call_data_value for "
14318                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14319                        to_underlying (child_die->sect_off),
14320                        objfile_name (objfile));
14321           else
14322             {
14323               parameter->data_value = DW_BLOCK (attr)->data;
14324               parameter->data_value_size = DW_BLOCK (attr)->size;
14325             }
14326         }
14327     }
14328 }
14329
14330 /* Helper function for read_variable.  If DIE represents a virtual
14331    table, then return the type of the concrete object that is
14332    associated with the virtual table.  Otherwise, return NULL.  */
14333
14334 static struct type *
14335 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14336 {
14337   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14338   if (attr == NULL)
14339     return NULL;
14340
14341   /* Find the type DIE.  */
14342   struct die_info *type_die = NULL;
14343   struct dwarf2_cu *type_cu = cu;
14344
14345   if (attr_form_is_ref (attr))
14346     type_die = follow_die_ref (die, attr, &type_cu);
14347   if (type_die == NULL)
14348     return NULL;
14349
14350   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14351     return NULL;
14352   return die_containing_type (type_die, type_cu);
14353 }
14354
14355 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14356
14357 static void
14358 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14359 {
14360   struct rust_vtable_symbol *storage = NULL;
14361
14362   if (cu->language == language_rust)
14363     {
14364       struct type *containing_type = rust_containing_type (die, cu);
14365
14366       if (containing_type != NULL)
14367         {
14368           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14369
14370           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14371                                     struct rust_vtable_symbol);
14372           initialize_objfile_symbol (storage);
14373           storage->concrete_type = containing_type;
14374           storage->subclass = SYMBOL_RUST_VTABLE;
14375         }
14376     }
14377
14378   new_symbol (die, NULL, cu, storage);
14379 }
14380
14381 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14382    reading .debug_rnglists.
14383    Callback's type should be:
14384     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14385    Return true if the attributes are present and valid, otherwise,
14386    return false.  */
14387
14388 template <typename Callback>
14389 static bool
14390 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14391                          Callback &&callback)
14392 {
14393   struct dwarf2_per_objfile *dwarf2_per_objfile
14394     = cu->per_cu->dwarf2_per_objfile;
14395   struct objfile *objfile = dwarf2_per_objfile->objfile;
14396   bfd *obfd = objfile->obfd;
14397   /* Base address selection entry.  */
14398   CORE_ADDR base;
14399   int found_base;
14400   const gdb_byte *buffer;
14401   CORE_ADDR baseaddr;
14402   bool overflow = false;
14403
14404   found_base = cu->base_known;
14405   base = cu->base_address;
14406
14407   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14408   if (offset >= dwarf2_per_objfile->rnglists.size)
14409     {
14410       complaint (&symfile_complaints,
14411                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14412                  offset);
14413       return false;
14414     }
14415   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14416
14417   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14418
14419   while (1)
14420     {
14421       /* Initialize it due to a false compiler warning.  */
14422       CORE_ADDR range_beginning = 0, range_end = 0;
14423       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14424                                  + dwarf2_per_objfile->rnglists.size);
14425       unsigned int bytes_read;
14426
14427       if (buffer == buf_end)
14428         {
14429           overflow = true;
14430           break;
14431         }
14432       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14433       switch (rlet)
14434         {
14435         case DW_RLE_end_of_list:
14436           break;
14437         case DW_RLE_base_address:
14438           if (buffer + cu->header.addr_size > buf_end)
14439             {
14440               overflow = true;
14441               break;
14442             }
14443           base = read_address (obfd, buffer, cu, &bytes_read);
14444           found_base = 1;
14445           buffer += bytes_read;
14446           break;
14447         case DW_RLE_start_length:
14448           if (buffer + cu->header.addr_size > buf_end)
14449             {
14450               overflow = true;
14451               break;
14452             }
14453           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14454           buffer += bytes_read;
14455           range_end = (range_beginning
14456                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14457           buffer += bytes_read;
14458           if (buffer > buf_end)
14459             {
14460               overflow = true;
14461               break;
14462             }
14463           break;
14464         case DW_RLE_offset_pair:
14465           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14466           buffer += bytes_read;
14467           if (buffer > buf_end)
14468             {
14469               overflow = true;
14470               break;
14471             }
14472           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14473           buffer += bytes_read;
14474           if (buffer > buf_end)
14475             {
14476               overflow = true;
14477               break;
14478             }
14479           break;
14480         case DW_RLE_start_end:
14481           if (buffer + 2 * cu->header.addr_size > buf_end)
14482             {
14483               overflow = true;
14484               break;
14485             }
14486           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14487           buffer += bytes_read;
14488           range_end = read_address (obfd, buffer, cu, &bytes_read);
14489           buffer += bytes_read;
14490           break;
14491         default:
14492           complaint (&symfile_complaints,
14493                      _("Invalid .debug_rnglists data (no base address)"));
14494           return false;
14495         }
14496       if (rlet == DW_RLE_end_of_list || overflow)
14497         break;
14498       if (rlet == DW_RLE_base_address)
14499         continue;
14500
14501       if (!found_base)
14502         {
14503           /* We have no valid base address for the ranges
14504              data.  */
14505           complaint (&symfile_complaints,
14506                      _("Invalid .debug_rnglists data (no base address)"));
14507           return false;
14508         }
14509
14510       if (range_beginning > range_end)
14511         {
14512           /* Inverted range entries are invalid.  */
14513           complaint (&symfile_complaints,
14514                      _("Invalid .debug_rnglists data (inverted range)"));
14515           return false;
14516         }
14517
14518       /* Empty range entries have no effect.  */
14519       if (range_beginning == range_end)
14520         continue;
14521
14522       range_beginning += base;
14523       range_end += base;
14524
14525       /* A not-uncommon case of bad debug info.
14526          Don't pollute the addrmap with bad data.  */
14527       if (range_beginning + baseaddr == 0
14528           && !dwarf2_per_objfile->has_section_at_zero)
14529         {
14530           complaint (&symfile_complaints,
14531                      _(".debug_rnglists entry has start address of zero"
14532                        " [in module %s]"), objfile_name (objfile));
14533           continue;
14534         }
14535
14536       callback (range_beginning, range_end);
14537     }
14538
14539   if (overflow)
14540     {
14541       complaint (&symfile_complaints,
14542                  _("Offset %d is not terminated "
14543                    "for DW_AT_ranges attribute"),
14544                  offset);
14545       return false;
14546     }
14547
14548   return true;
14549 }
14550
14551 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14552    Callback's type should be:
14553     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14554    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14555
14556 template <typename Callback>
14557 static int
14558 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14559                        Callback &&callback)
14560 {
14561   struct dwarf2_per_objfile *dwarf2_per_objfile
14562       = cu->per_cu->dwarf2_per_objfile;
14563   struct objfile *objfile = dwarf2_per_objfile->objfile;
14564   struct comp_unit_head *cu_header = &cu->header;
14565   bfd *obfd = objfile->obfd;
14566   unsigned int addr_size = cu_header->addr_size;
14567   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14568   /* Base address selection entry.  */
14569   CORE_ADDR base;
14570   int found_base;
14571   unsigned int dummy;
14572   const gdb_byte *buffer;
14573   CORE_ADDR baseaddr;
14574
14575   if (cu_header->version >= 5)
14576     return dwarf2_rnglists_process (offset, cu, callback);
14577
14578   found_base = cu->base_known;
14579   base = cu->base_address;
14580
14581   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14582   if (offset >= dwarf2_per_objfile->ranges.size)
14583     {
14584       complaint (&symfile_complaints,
14585                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14586                  offset);
14587       return 0;
14588     }
14589   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14590
14591   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14592
14593   while (1)
14594     {
14595       CORE_ADDR range_beginning, range_end;
14596
14597       range_beginning = read_address (obfd, buffer, cu, &dummy);
14598       buffer += addr_size;
14599       range_end = read_address (obfd, buffer, cu, &dummy);
14600       buffer += addr_size;
14601       offset += 2 * addr_size;
14602
14603       /* An end of list marker is a pair of zero addresses.  */
14604       if (range_beginning == 0 && range_end == 0)
14605         /* Found the end of list entry.  */
14606         break;
14607
14608       /* Each base address selection entry is a pair of 2 values.
14609          The first is the largest possible address, the second is
14610          the base address.  Check for a base address here.  */
14611       if ((range_beginning & mask) == mask)
14612         {
14613           /* If we found the largest possible address, then we already
14614              have the base address in range_end.  */
14615           base = range_end;
14616           found_base = 1;
14617           continue;
14618         }
14619
14620       if (!found_base)
14621         {
14622           /* We have no valid base address for the ranges
14623              data.  */
14624           complaint (&symfile_complaints,
14625                      _("Invalid .debug_ranges data (no base address)"));
14626           return 0;
14627         }
14628
14629       if (range_beginning > range_end)
14630         {
14631           /* Inverted range entries are invalid.  */
14632           complaint (&symfile_complaints,
14633                      _("Invalid .debug_ranges data (inverted range)"));
14634           return 0;
14635         }
14636
14637       /* Empty range entries have no effect.  */
14638       if (range_beginning == range_end)
14639         continue;
14640
14641       range_beginning += base;
14642       range_end += base;
14643
14644       /* A not-uncommon case of bad debug info.
14645          Don't pollute the addrmap with bad data.  */
14646       if (range_beginning + baseaddr == 0
14647           && !dwarf2_per_objfile->has_section_at_zero)
14648         {
14649           complaint (&symfile_complaints,
14650                      _(".debug_ranges entry has start address of zero"
14651                        " [in module %s]"), objfile_name (objfile));
14652           continue;
14653         }
14654
14655       callback (range_beginning, range_end);
14656     }
14657
14658   return 1;
14659 }
14660
14661 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14662    Return 1 if the attributes are present and valid, otherwise, return 0.
14663    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14664
14665 static int
14666 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14667                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14668                     struct partial_symtab *ranges_pst)
14669 {
14670   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14671   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14672   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14673                                        SECT_OFF_TEXT (objfile));
14674   int low_set = 0;
14675   CORE_ADDR low = 0;
14676   CORE_ADDR high = 0;
14677   int retval;
14678
14679   retval = dwarf2_ranges_process (offset, cu,
14680     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14681     {
14682       if (ranges_pst != NULL)
14683         {
14684           CORE_ADDR lowpc;
14685           CORE_ADDR highpc;
14686
14687           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14688                                               range_beginning + baseaddr);
14689           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14690                                                range_end + baseaddr);
14691           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14692                              ranges_pst);
14693         }
14694
14695       /* FIXME: This is recording everything as a low-high
14696          segment of consecutive addresses.  We should have a
14697          data structure for discontiguous block ranges
14698          instead.  */
14699       if (! low_set)
14700         {
14701           low = range_beginning;
14702           high = range_end;
14703           low_set = 1;
14704         }
14705       else
14706         {
14707           if (range_beginning < low)
14708             low = range_beginning;
14709           if (range_end > high)
14710             high = range_end;
14711         }
14712     });
14713   if (!retval)
14714     return 0;
14715
14716   if (! low_set)
14717     /* If the first entry is an end-of-list marker, the range
14718        describes an empty scope, i.e. no instructions.  */
14719     return 0;
14720
14721   if (low_return)
14722     *low_return = low;
14723   if (high_return)
14724     *high_return = high;
14725   return 1;
14726 }
14727
14728 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14729    definition for the return value.  *LOWPC and *HIGHPC are set iff
14730    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14731
14732 static enum pc_bounds_kind
14733 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14734                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14735                       struct partial_symtab *pst)
14736 {
14737   struct dwarf2_per_objfile *dwarf2_per_objfile
14738     = cu->per_cu->dwarf2_per_objfile;
14739   struct attribute *attr;
14740   struct attribute *attr_high;
14741   CORE_ADDR low = 0;
14742   CORE_ADDR high = 0;
14743   enum pc_bounds_kind ret;
14744
14745   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14746   if (attr_high)
14747     {
14748       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14749       if (attr)
14750         {
14751           low = attr_value_as_address (attr);
14752           high = attr_value_as_address (attr_high);
14753           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14754             high += low;
14755         }
14756       else
14757         /* Found high w/o low attribute.  */
14758         return PC_BOUNDS_INVALID;
14759
14760       /* Found consecutive range of addresses.  */
14761       ret = PC_BOUNDS_HIGH_LOW;
14762     }
14763   else
14764     {
14765       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14766       if (attr != NULL)
14767         {
14768           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14769              We take advantage of the fact that DW_AT_ranges does not appear
14770              in DW_TAG_compile_unit of DWO files.  */
14771           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14772           unsigned int ranges_offset = (DW_UNSND (attr)
14773                                         + (need_ranges_base
14774                                            ? cu->ranges_base
14775                                            : 0));
14776
14777           /* Value of the DW_AT_ranges attribute is the offset in the
14778              .debug_ranges section.  */
14779           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14780             return PC_BOUNDS_INVALID;
14781           /* Found discontinuous range of addresses.  */
14782           ret = PC_BOUNDS_RANGES;
14783         }
14784       else
14785         return PC_BOUNDS_NOT_PRESENT;
14786     }
14787
14788   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14789   if (high <= low)
14790     return PC_BOUNDS_INVALID;
14791
14792   /* When using the GNU linker, .gnu.linkonce. sections are used to
14793      eliminate duplicate copies of functions and vtables and such.
14794      The linker will arbitrarily choose one and discard the others.
14795      The AT_*_pc values for such functions refer to local labels in
14796      these sections.  If the section from that file was discarded, the
14797      labels are not in the output, so the relocs get a value of 0.
14798      If this is a discarded function, mark the pc bounds as invalid,
14799      so that GDB will ignore it.  */
14800   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14801     return PC_BOUNDS_INVALID;
14802
14803   *lowpc = low;
14804   if (highpc)
14805     *highpc = high;
14806   return ret;
14807 }
14808
14809 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14810    its low and high PC addresses.  Do nothing if these addresses could not
14811    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14812    and HIGHPC to the high address if greater than HIGHPC.  */
14813
14814 static void
14815 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14816                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14817                                  struct dwarf2_cu *cu)
14818 {
14819   CORE_ADDR low, high;
14820   struct die_info *child = die->child;
14821
14822   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14823     {
14824       *lowpc = std::min (*lowpc, low);
14825       *highpc = std::max (*highpc, high);
14826     }
14827
14828   /* If the language does not allow nested subprograms (either inside
14829      subprograms or lexical blocks), we're done.  */
14830   if (cu->language != language_ada)
14831     return;
14832
14833   /* Check all the children of the given DIE.  If it contains nested
14834      subprograms, then check their pc bounds.  Likewise, we need to
14835      check lexical blocks as well, as they may also contain subprogram
14836      definitions.  */
14837   while (child && child->tag)
14838     {
14839       if (child->tag == DW_TAG_subprogram
14840           || child->tag == DW_TAG_lexical_block)
14841         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14842       child = sibling_die (child);
14843     }
14844 }
14845
14846 /* Get the low and high pc's represented by the scope DIE, and store
14847    them in *LOWPC and *HIGHPC.  If the correct values can't be
14848    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14849
14850 static void
14851 get_scope_pc_bounds (struct die_info *die,
14852                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14853                      struct dwarf2_cu *cu)
14854 {
14855   CORE_ADDR best_low = (CORE_ADDR) -1;
14856   CORE_ADDR best_high = (CORE_ADDR) 0;
14857   CORE_ADDR current_low, current_high;
14858
14859   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14860       >= PC_BOUNDS_RANGES)
14861     {
14862       best_low = current_low;
14863       best_high = current_high;
14864     }
14865   else
14866     {
14867       struct die_info *child = die->child;
14868
14869       while (child && child->tag)
14870         {
14871           switch (child->tag) {
14872           case DW_TAG_subprogram:
14873             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14874             break;
14875           case DW_TAG_namespace:
14876           case DW_TAG_module:
14877             /* FIXME: carlton/2004-01-16: Should we do this for
14878                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14879                that current GCC's always emit the DIEs corresponding
14880                to definitions of methods of classes as children of a
14881                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14882                the DIEs giving the declarations, which could be
14883                anywhere).  But I don't see any reason why the
14884                standards says that they have to be there.  */
14885             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14886
14887             if (current_low != ((CORE_ADDR) -1))
14888               {
14889                 best_low = std::min (best_low, current_low);
14890                 best_high = std::max (best_high, current_high);
14891               }
14892             break;
14893           default:
14894             /* Ignore.  */
14895             break;
14896           }
14897
14898           child = sibling_die (child);
14899         }
14900     }
14901
14902   *lowpc = best_low;
14903   *highpc = best_high;
14904 }
14905
14906 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14907    in DIE.  */
14908
14909 static void
14910 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14911                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14912 {
14913   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14914   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14915   struct attribute *attr;
14916   struct attribute *attr_high;
14917
14918   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14919   if (attr_high)
14920     {
14921       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14922       if (attr)
14923         {
14924           CORE_ADDR low = attr_value_as_address (attr);
14925           CORE_ADDR high = attr_value_as_address (attr_high);
14926
14927           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14928             high += low;
14929
14930           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14931           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14932           record_block_range (block, low, high - 1);
14933         }
14934     }
14935
14936   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14937   if (attr)
14938     {
14939       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14940          We take advantage of the fact that DW_AT_ranges does not appear
14941          in DW_TAG_compile_unit of DWO files.  */
14942       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14943
14944       /* The value of the DW_AT_ranges attribute is the offset of the
14945          address range list in the .debug_ranges section.  */
14946       unsigned long offset = (DW_UNSND (attr)
14947                               + (need_ranges_base ? cu->ranges_base : 0));
14948       const gdb_byte *buffer;
14949
14950       /* For some target architectures, but not others, the
14951          read_address function sign-extends the addresses it returns.
14952          To recognize base address selection entries, we need a
14953          mask.  */
14954       unsigned int addr_size = cu->header.addr_size;
14955       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14956
14957       /* The base address, to which the next pair is relative.  Note
14958          that this 'base' is a DWARF concept: most entries in a range
14959          list are relative, to reduce the number of relocs against the
14960          debugging information.  This is separate from this function's
14961          'baseaddr' argument, which GDB uses to relocate debugging
14962          information from a shared library based on the address at
14963          which the library was loaded.  */
14964       CORE_ADDR base = cu->base_address;
14965       int base_known = cu->base_known;
14966
14967       dwarf2_ranges_process (offset, cu,
14968         [&] (CORE_ADDR start, CORE_ADDR end)
14969         {
14970           start += baseaddr;
14971           end += baseaddr;
14972           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14973           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14974           record_block_range (block, start, end - 1);
14975         });
14976     }
14977 }
14978
14979 /* Check whether the producer field indicates either of GCC < 4.6, or the
14980    Intel C/C++ compiler, and cache the result in CU.  */
14981
14982 static void
14983 check_producer (struct dwarf2_cu *cu)
14984 {
14985   int major, minor;
14986
14987   if (cu->producer == NULL)
14988     {
14989       /* For unknown compilers expect their behavior is DWARF version
14990          compliant.
14991
14992          GCC started to support .debug_types sections by -gdwarf-4 since
14993          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14994          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14995          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14996          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14997     }
14998   else if (producer_is_gcc (cu->producer, &major, &minor))
14999     {
15000       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15001       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15002     }
15003   else if (producer_is_icc (cu->producer, &major, &minor))
15004     cu->producer_is_icc_lt_14 = major < 14;
15005   else
15006     {
15007       /* For other non-GCC compilers, expect their behavior is DWARF version
15008          compliant.  */
15009     }
15010
15011   cu->checked_producer = 1;
15012 }
15013
15014 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15015    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15016    during 4.6.0 experimental.  */
15017
15018 static int
15019 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15020 {
15021   if (!cu->checked_producer)
15022     check_producer (cu);
15023
15024   return cu->producer_is_gxx_lt_4_6;
15025 }
15026
15027 /* Return the default accessibility type if it is not overriden by
15028    DW_AT_accessibility.  */
15029
15030 static enum dwarf_access_attribute
15031 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15032 {
15033   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15034     {
15035       /* The default DWARF 2 accessibility for members is public, the default
15036          accessibility for inheritance is private.  */
15037
15038       if (die->tag != DW_TAG_inheritance)
15039         return DW_ACCESS_public;
15040       else
15041         return DW_ACCESS_private;
15042     }
15043   else
15044     {
15045       /* DWARF 3+ defines the default accessibility a different way.  The same
15046          rules apply now for DW_TAG_inheritance as for the members and it only
15047          depends on the container kind.  */
15048
15049       if (die->parent->tag == DW_TAG_class_type)
15050         return DW_ACCESS_private;
15051       else
15052         return DW_ACCESS_public;
15053     }
15054 }
15055
15056 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15057    offset.  If the attribute was not found return 0, otherwise return
15058    1.  If it was found but could not properly be handled, set *OFFSET
15059    to 0.  */
15060
15061 static int
15062 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15063                              LONGEST *offset)
15064 {
15065   struct attribute *attr;
15066
15067   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15068   if (attr != NULL)
15069     {
15070       *offset = 0;
15071
15072       /* Note that we do not check for a section offset first here.
15073          This is because DW_AT_data_member_location is new in DWARF 4,
15074          so if we see it, we can assume that a constant form is really
15075          a constant and not a section offset.  */
15076       if (attr_form_is_constant (attr))
15077         *offset = dwarf2_get_attr_constant_value (attr, 0);
15078       else if (attr_form_is_section_offset (attr))
15079         dwarf2_complex_location_expr_complaint ();
15080       else if (attr_form_is_block (attr))
15081         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15082       else
15083         dwarf2_complex_location_expr_complaint ();
15084
15085       return 1;
15086     }
15087
15088   return 0;
15089 }
15090
15091 /* Add an aggregate field to the field list.  */
15092
15093 static void
15094 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15095                   struct dwarf2_cu *cu)
15096 {
15097   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15098   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15099   struct nextfield *new_field;
15100   struct attribute *attr;
15101   struct field *fp;
15102   const char *fieldname = "";
15103
15104   /* Allocate a new field list entry and link it in.  */
15105   new_field = XNEW (struct nextfield);
15106   make_cleanup (xfree, new_field);
15107   memset (new_field, 0, sizeof (struct nextfield));
15108
15109   if (die->tag == DW_TAG_inheritance)
15110     {
15111       new_field->next = fip->baseclasses;
15112       fip->baseclasses = new_field;
15113     }
15114   else
15115     {
15116       new_field->next = fip->fields;
15117       fip->fields = new_field;
15118     }
15119   fip->nfields++;
15120
15121   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15122   if (attr)
15123     new_field->accessibility = DW_UNSND (attr);
15124   else
15125     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15126   if (new_field->accessibility != DW_ACCESS_public)
15127     fip->non_public_fields = 1;
15128
15129   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15130   if (attr)
15131     new_field->virtuality = DW_UNSND (attr);
15132   else
15133     new_field->virtuality = DW_VIRTUALITY_none;
15134
15135   fp = &new_field->field;
15136
15137   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15138     {
15139       LONGEST offset;
15140
15141       /* Data member other than a C++ static data member.  */
15142
15143       /* Get type of field.  */
15144       fp->type = die_type (die, cu);
15145
15146       SET_FIELD_BITPOS (*fp, 0);
15147
15148       /* Get bit size of field (zero if none).  */
15149       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15150       if (attr)
15151         {
15152           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15153         }
15154       else
15155         {
15156           FIELD_BITSIZE (*fp) = 0;
15157         }
15158
15159       /* Get bit offset of field.  */
15160       if (handle_data_member_location (die, cu, &offset))
15161         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15162       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15163       if (attr)
15164         {
15165           if (gdbarch_bits_big_endian (gdbarch))
15166             {
15167               /* For big endian bits, the DW_AT_bit_offset gives the
15168                  additional bit offset from the MSB of the containing
15169                  anonymous object to the MSB of the field.  We don't
15170                  have to do anything special since we don't need to
15171                  know the size of the anonymous object.  */
15172               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15173             }
15174           else
15175             {
15176               /* For little endian bits, compute the bit offset to the
15177                  MSB of the anonymous object, subtract off the number of
15178                  bits from the MSB of the field to the MSB of the
15179                  object, and then subtract off the number of bits of
15180                  the field itself.  The result is the bit offset of
15181                  the LSB of the field.  */
15182               int anonymous_size;
15183               int bit_offset = DW_UNSND (attr);
15184
15185               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15186               if (attr)
15187                 {
15188                   /* The size of the anonymous object containing
15189                      the bit field is explicit, so use the
15190                      indicated size (in bytes).  */
15191                   anonymous_size = DW_UNSND (attr);
15192                 }
15193               else
15194                 {
15195                   /* The size of the anonymous object containing
15196                      the bit field must be inferred from the type
15197                      attribute of the data member containing the
15198                      bit field.  */
15199                   anonymous_size = TYPE_LENGTH (fp->type);
15200                 }
15201               SET_FIELD_BITPOS (*fp,
15202                                 (FIELD_BITPOS (*fp)
15203                                  + anonymous_size * bits_per_byte
15204                                  - bit_offset - FIELD_BITSIZE (*fp)));
15205             }
15206         }
15207       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15208       if (attr != NULL)
15209         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15210                                 + dwarf2_get_attr_constant_value (attr, 0)));
15211
15212       /* Get name of field.  */
15213       fieldname = dwarf2_name (die, cu);
15214       if (fieldname == NULL)
15215         fieldname = "";
15216
15217       /* The name is already allocated along with this objfile, so we don't
15218          need to duplicate it for the type.  */
15219       fp->name = fieldname;
15220
15221       /* Change accessibility for artificial fields (e.g. virtual table
15222          pointer or virtual base class pointer) to private.  */
15223       if (dwarf2_attr (die, DW_AT_artificial, cu))
15224         {
15225           FIELD_ARTIFICIAL (*fp) = 1;
15226           new_field->accessibility = DW_ACCESS_private;
15227           fip->non_public_fields = 1;
15228         }
15229     }
15230   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15231     {
15232       /* C++ static member.  */
15233
15234       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15235          is a declaration, but all versions of G++ as of this writing
15236          (so through at least 3.2.1) incorrectly generate
15237          DW_TAG_variable tags.  */
15238
15239       const char *physname;
15240
15241       /* Get name of field.  */
15242       fieldname = dwarf2_name (die, cu);
15243       if (fieldname == NULL)
15244         return;
15245
15246       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15247       if (attr
15248           /* Only create a symbol if this is an external value.
15249              new_symbol checks this and puts the value in the global symbol
15250              table, which we want.  If it is not external, new_symbol
15251              will try to put the value in cu->list_in_scope which is wrong.  */
15252           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15253         {
15254           /* A static const member, not much different than an enum as far as
15255              we're concerned, except that we can support more types.  */
15256           new_symbol (die, NULL, cu);
15257         }
15258
15259       /* Get physical name.  */
15260       physname = dwarf2_physname (fieldname, die, cu);
15261
15262       /* The name is already allocated along with this objfile, so we don't
15263          need to duplicate it for the type.  */
15264       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15265       FIELD_TYPE (*fp) = die_type (die, cu);
15266       FIELD_NAME (*fp) = fieldname;
15267     }
15268   else if (die->tag == DW_TAG_inheritance)
15269     {
15270       LONGEST offset;
15271
15272       /* C++ base class field.  */
15273       if (handle_data_member_location (die, cu, &offset))
15274         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15275       FIELD_BITSIZE (*fp) = 0;
15276       FIELD_TYPE (*fp) = die_type (die, cu);
15277       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15278       fip->nbaseclasses++;
15279     }
15280 }
15281
15282 /* Can the type given by DIE define another type?  */
15283
15284 static bool
15285 type_can_define_types (const struct die_info *die)
15286 {
15287   switch (die->tag)
15288     {
15289     case DW_TAG_typedef:
15290     case DW_TAG_class_type:
15291     case DW_TAG_structure_type:
15292     case DW_TAG_union_type:
15293     case DW_TAG_enumeration_type:
15294       return true;
15295
15296     default:
15297       return false;
15298     }
15299 }
15300
15301 /* Add a type definition defined in the scope of the FIP's class.  */
15302
15303 static void
15304 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15305                       struct dwarf2_cu *cu)
15306 {
15307   struct decl_field_list *new_field;
15308   struct decl_field *fp;
15309
15310   /* Allocate a new field list entry and link it in.  */
15311   new_field = XCNEW (struct decl_field_list);
15312   make_cleanup (xfree, new_field);
15313
15314   gdb_assert (type_can_define_types (die));
15315
15316   fp = &new_field->field;
15317
15318   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15319   fp->name = dwarf2_name (die, cu);
15320   fp->type = read_type_die (die, cu);
15321
15322   /* Save accessibility.  */
15323   enum dwarf_access_attribute accessibility;
15324   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15325   if (attr != NULL)
15326     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15327   else
15328     accessibility = dwarf2_default_access_attribute (die, cu);
15329   switch (accessibility)
15330     {
15331     case DW_ACCESS_public:
15332       /* The assumed value if neither private nor protected.  */
15333       break;
15334     case DW_ACCESS_private:
15335       fp->is_private = 1;
15336       break;
15337     case DW_ACCESS_protected:
15338       fp->is_protected = 1;
15339       break;
15340     default:
15341       complaint (&symfile_complaints,
15342                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15343     }
15344
15345   if (die->tag == DW_TAG_typedef)
15346     {
15347       new_field->next = fip->typedef_field_list;
15348       fip->typedef_field_list = new_field;
15349       fip->typedef_field_list_count++;
15350     }
15351   else
15352     {
15353       new_field->next = fip->nested_types_list;
15354       fip->nested_types_list = new_field;
15355       fip->nested_types_list_count++;
15356     }
15357 }
15358
15359 /* Create the vector of fields, and attach it to the type.  */
15360
15361 static void
15362 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15363                               struct dwarf2_cu *cu)
15364 {
15365   int nfields = fip->nfields;
15366
15367   /* Record the field count, allocate space for the array of fields,
15368      and create blank accessibility bitfields if necessary.  */
15369   TYPE_NFIELDS (type) = nfields;
15370   TYPE_FIELDS (type) = (struct field *)
15371     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15372   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15373
15374   if (fip->non_public_fields && cu->language != language_ada)
15375     {
15376       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15377
15378       TYPE_FIELD_PRIVATE_BITS (type) =
15379         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15380       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15381
15382       TYPE_FIELD_PROTECTED_BITS (type) =
15383         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15384       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15385
15386       TYPE_FIELD_IGNORE_BITS (type) =
15387         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15388       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15389     }
15390
15391   /* If the type has baseclasses, allocate and clear a bit vector for
15392      TYPE_FIELD_VIRTUAL_BITS.  */
15393   if (fip->nbaseclasses && cu->language != language_ada)
15394     {
15395       int num_bytes = B_BYTES (fip->nbaseclasses);
15396       unsigned char *pointer;
15397
15398       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15399       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15400       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15401       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15402       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15403     }
15404
15405   /* Copy the saved-up fields into the field vector.  Start from the head of
15406      the list, adding to the tail of the field array, so that they end up in
15407      the same order in the array in which they were added to the list.  */
15408   while (nfields-- > 0)
15409     {
15410       struct nextfield *fieldp;
15411
15412       if (fip->fields)
15413         {
15414           fieldp = fip->fields;
15415           fip->fields = fieldp->next;
15416         }
15417       else
15418         {
15419           fieldp = fip->baseclasses;
15420           fip->baseclasses = fieldp->next;
15421         }
15422
15423       TYPE_FIELD (type, nfields) = fieldp->field;
15424       switch (fieldp->accessibility)
15425         {
15426         case DW_ACCESS_private:
15427           if (cu->language != language_ada)
15428             SET_TYPE_FIELD_PRIVATE (type, nfields);
15429           break;
15430
15431         case DW_ACCESS_protected:
15432           if (cu->language != language_ada)
15433             SET_TYPE_FIELD_PROTECTED (type, nfields);
15434           break;
15435
15436         case DW_ACCESS_public:
15437           break;
15438
15439         default:
15440           /* Unknown accessibility.  Complain and treat it as public.  */
15441           {
15442             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15443                        fieldp->accessibility);
15444           }
15445           break;
15446         }
15447       if (nfields < fip->nbaseclasses)
15448         {
15449           switch (fieldp->virtuality)
15450             {
15451             case DW_VIRTUALITY_virtual:
15452             case DW_VIRTUALITY_pure_virtual:
15453               if (cu->language == language_ada)
15454                 error (_("unexpected virtuality in component of Ada type"));
15455               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15456               break;
15457             }
15458         }
15459     }
15460 }
15461
15462 /* Return true if this member function is a constructor, false
15463    otherwise.  */
15464
15465 static int
15466 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15467 {
15468   const char *fieldname;
15469   const char *type_name;
15470   int len;
15471
15472   if (die->parent == NULL)
15473     return 0;
15474
15475   if (die->parent->tag != DW_TAG_structure_type
15476       && die->parent->tag != DW_TAG_union_type
15477       && die->parent->tag != DW_TAG_class_type)
15478     return 0;
15479
15480   fieldname = dwarf2_name (die, cu);
15481   type_name = dwarf2_name (die->parent, cu);
15482   if (fieldname == NULL || type_name == NULL)
15483     return 0;
15484
15485   len = strlen (fieldname);
15486   return (strncmp (fieldname, type_name, len) == 0
15487           && (type_name[len] == '\0' || type_name[len] == '<'));
15488 }
15489
15490 /* Add a member function to the proper fieldlist.  */
15491
15492 static void
15493 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15494                       struct type *type, struct dwarf2_cu *cu)
15495 {
15496   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15497   struct attribute *attr;
15498   struct fnfieldlist *flp;
15499   int i;
15500   struct fn_field *fnp;
15501   const char *fieldname;
15502   struct nextfnfield *new_fnfield;
15503   struct type *this_type;
15504   enum dwarf_access_attribute accessibility;
15505
15506   if (cu->language == language_ada)
15507     error (_("unexpected member function in Ada type"));
15508
15509   /* Get name of member function.  */
15510   fieldname = dwarf2_name (die, cu);
15511   if (fieldname == NULL)
15512     return;
15513
15514   /* Look up member function name in fieldlist.  */
15515   for (i = 0; i < fip->nfnfields; i++)
15516     {
15517       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15518         break;
15519     }
15520
15521   /* Create new list element if necessary.  */
15522   if (i < fip->nfnfields)
15523     flp = &fip->fnfieldlists[i];
15524   else
15525     {
15526       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15527         {
15528           fip->fnfieldlists = (struct fnfieldlist *)
15529             xrealloc (fip->fnfieldlists,
15530                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15531                       * sizeof (struct fnfieldlist));
15532           if (fip->nfnfields == 0)
15533             make_cleanup (free_current_contents, &fip->fnfieldlists);
15534         }
15535       flp = &fip->fnfieldlists[fip->nfnfields];
15536       flp->name = fieldname;
15537       flp->length = 0;
15538       flp->head = NULL;
15539       i = fip->nfnfields++;
15540     }
15541
15542   /* Create a new member function field and chain it to the field list
15543      entry.  */
15544   new_fnfield = XNEW (struct nextfnfield);
15545   make_cleanup (xfree, new_fnfield);
15546   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15547   new_fnfield->next = flp->head;
15548   flp->head = new_fnfield;
15549   flp->length++;
15550
15551   /* Fill in the member function field info.  */
15552   fnp = &new_fnfield->fnfield;
15553
15554   /* Delay processing of the physname until later.  */
15555   if (cu->language == language_cplus)
15556     {
15557       add_to_method_list (type, i, flp->length - 1, fieldname,
15558                           die, cu);
15559     }
15560   else
15561     {
15562       const char *physname = dwarf2_physname (fieldname, die, cu);
15563       fnp->physname = physname ? physname : "";
15564     }
15565
15566   fnp->type = alloc_type (objfile);
15567   this_type = read_type_die (die, cu);
15568   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15569     {
15570       int nparams = TYPE_NFIELDS (this_type);
15571
15572       /* TYPE is the domain of this method, and THIS_TYPE is the type
15573            of the method itself (TYPE_CODE_METHOD).  */
15574       smash_to_method_type (fnp->type, type,
15575                             TYPE_TARGET_TYPE (this_type),
15576                             TYPE_FIELDS (this_type),
15577                             TYPE_NFIELDS (this_type),
15578                             TYPE_VARARGS (this_type));
15579
15580       /* Handle static member functions.
15581          Dwarf2 has no clean way to discern C++ static and non-static
15582          member functions.  G++ helps GDB by marking the first
15583          parameter for non-static member functions (which is the this
15584          pointer) as artificial.  We obtain this information from
15585          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15586       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15587         fnp->voffset = VOFFSET_STATIC;
15588     }
15589   else
15590     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15591                dwarf2_full_name (fieldname, die, cu));
15592
15593   /* Get fcontext from DW_AT_containing_type if present.  */
15594   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15595     fnp->fcontext = die_containing_type (die, cu);
15596
15597   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15598      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15599
15600   /* Get accessibility.  */
15601   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15602   if (attr)
15603     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15604   else
15605     accessibility = dwarf2_default_access_attribute (die, cu);
15606   switch (accessibility)
15607     {
15608     case DW_ACCESS_private:
15609       fnp->is_private = 1;
15610       break;
15611     case DW_ACCESS_protected:
15612       fnp->is_protected = 1;
15613       break;
15614     }
15615
15616   /* Check for artificial methods.  */
15617   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15618   if (attr && DW_UNSND (attr) != 0)
15619     fnp->is_artificial = 1;
15620
15621   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15622
15623   /* Get index in virtual function table if it is a virtual member
15624      function.  For older versions of GCC, this is an offset in the
15625      appropriate virtual table, as specified by DW_AT_containing_type.
15626      For everyone else, it is an expression to be evaluated relative
15627      to the object address.  */
15628
15629   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15630   if (attr)
15631     {
15632       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15633         {
15634           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15635             {
15636               /* Old-style GCC.  */
15637               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15638             }
15639           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15640                    || (DW_BLOCK (attr)->size > 1
15641                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15642                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15643             {
15644               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15645               if ((fnp->voffset % cu->header.addr_size) != 0)
15646                 dwarf2_complex_location_expr_complaint ();
15647               else
15648                 fnp->voffset /= cu->header.addr_size;
15649               fnp->voffset += 2;
15650             }
15651           else
15652             dwarf2_complex_location_expr_complaint ();
15653
15654           if (!fnp->fcontext)
15655             {
15656               /* If there is no `this' field and no DW_AT_containing_type,
15657                  we cannot actually find a base class context for the
15658                  vtable!  */
15659               if (TYPE_NFIELDS (this_type) == 0
15660                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15661                 {
15662                   complaint (&symfile_complaints,
15663                              _("cannot determine context for virtual member "
15664                                "function \"%s\" (offset %d)"),
15665                              fieldname, to_underlying (die->sect_off));
15666                 }
15667               else
15668                 {
15669                   fnp->fcontext
15670                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15671                 }
15672             }
15673         }
15674       else if (attr_form_is_section_offset (attr))
15675         {
15676           dwarf2_complex_location_expr_complaint ();
15677         }
15678       else
15679         {
15680           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15681                                                  fieldname);
15682         }
15683     }
15684   else
15685     {
15686       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15687       if (attr && DW_UNSND (attr))
15688         {
15689           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15690           complaint (&symfile_complaints,
15691                      _("Member function \"%s\" (offset %d) is virtual "
15692                        "but the vtable offset is not specified"),
15693                      fieldname, to_underlying (die->sect_off));
15694           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15695           TYPE_CPLUS_DYNAMIC (type) = 1;
15696         }
15697     }
15698 }
15699
15700 /* Create the vector of member function fields, and attach it to the type.  */
15701
15702 static void
15703 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15704                                  struct dwarf2_cu *cu)
15705 {
15706   struct fnfieldlist *flp;
15707   int i;
15708
15709   if (cu->language == language_ada)
15710     error (_("unexpected member functions in Ada type"));
15711
15712   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15713   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15714     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15715
15716   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15717     {
15718       struct nextfnfield *nfp = flp->head;
15719       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15720       int k;
15721
15722       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15723       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15724       fn_flp->fn_fields = (struct fn_field *)
15725         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15726       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15727         fn_flp->fn_fields[k] = nfp->fnfield;
15728     }
15729
15730   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15731 }
15732
15733 /* Returns non-zero if NAME is the name of a vtable member in CU's
15734    language, zero otherwise.  */
15735 static int
15736 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15737 {
15738   static const char vptr[] = "_vptr";
15739
15740   /* Look for the C++ form of the vtable.  */
15741   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15742     return 1;
15743
15744   return 0;
15745 }
15746
15747 /* GCC outputs unnamed structures that are really pointers to member
15748    functions, with the ABI-specified layout.  If TYPE describes
15749    such a structure, smash it into a member function type.
15750
15751    GCC shouldn't do this; it should just output pointer to member DIEs.
15752    This is GCC PR debug/28767.  */
15753
15754 static void
15755 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15756 {
15757   struct type *pfn_type, *self_type, *new_type;
15758
15759   /* Check for a structure with no name and two children.  */
15760   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15761     return;
15762
15763   /* Check for __pfn and __delta members.  */
15764   if (TYPE_FIELD_NAME (type, 0) == NULL
15765       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15766       || TYPE_FIELD_NAME (type, 1) == NULL
15767       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15768     return;
15769
15770   /* Find the type of the method.  */
15771   pfn_type = TYPE_FIELD_TYPE (type, 0);
15772   if (pfn_type == NULL
15773       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15774       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15775     return;
15776
15777   /* Look for the "this" argument.  */
15778   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15779   if (TYPE_NFIELDS (pfn_type) == 0
15780       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15781       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15782     return;
15783
15784   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15785   new_type = alloc_type (objfile);
15786   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15787                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15788                         TYPE_VARARGS (pfn_type));
15789   smash_to_methodptr_type (type, new_type);
15790 }
15791
15792
15793 /* Called when we find the DIE that starts a structure or union scope
15794    (definition) to create a type for the structure or union.  Fill in
15795    the type's name and general properties; the members will not be
15796    processed until process_structure_scope.  A symbol table entry for
15797    the type will also not be done until process_structure_scope (assuming
15798    the type has a name).
15799
15800    NOTE: we need to call these functions regardless of whether or not the
15801    DIE has a DW_AT_name attribute, since it might be an anonymous
15802    structure or union.  This gets the type entered into our set of
15803    user defined types.  */
15804
15805 static struct type *
15806 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15807 {
15808   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15809   struct type *type;
15810   struct attribute *attr;
15811   const char *name;
15812
15813   /* If the definition of this type lives in .debug_types, read that type.
15814      Don't follow DW_AT_specification though, that will take us back up
15815      the chain and we want to go down.  */
15816   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15817   if (attr)
15818     {
15819       type = get_DW_AT_signature_type (die, attr, cu);
15820
15821       /* The type's CU may not be the same as CU.
15822          Ensure TYPE is recorded with CU in die_type_hash.  */
15823       return set_die_type (die, type, cu);
15824     }
15825
15826   type = alloc_type (objfile);
15827   INIT_CPLUS_SPECIFIC (type);
15828
15829   name = dwarf2_name (die, cu);
15830   if (name != NULL)
15831     {
15832       if (cu->language == language_cplus
15833           || cu->language == language_d
15834           || cu->language == language_rust)
15835         {
15836           const char *full_name = dwarf2_full_name (name, die, cu);
15837
15838           /* dwarf2_full_name might have already finished building the DIE's
15839              type.  If so, there is no need to continue.  */
15840           if (get_die_type (die, cu) != NULL)
15841             return get_die_type (die, cu);
15842
15843           TYPE_TAG_NAME (type) = full_name;
15844           if (die->tag == DW_TAG_structure_type
15845               || die->tag == DW_TAG_class_type)
15846             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15847         }
15848       else
15849         {
15850           /* The name is already allocated along with this objfile, so
15851              we don't need to duplicate it for the type.  */
15852           TYPE_TAG_NAME (type) = name;
15853           if (die->tag == DW_TAG_class_type)
15854             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15855         }
15856     }
15857
15858   if (die->tag == DW_TAG_structure_type)
15859     {
15860       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15861     }
15862   else if (die->tag == DW_TAG_union_type)
15863     {
15864       TYPE_CODE (type) = TYPE_CODE_UNION;
15865     }
15866   else
15867     {
15868       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15869     }
15870
15871   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15872     TYPE_DECLARED_CLASS (type) = 1;
15873
15874   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15875   if (attr)
15876     {
15877       if (attr_form_is_constant (attr))
15878         TYPE_LENGTH (type) = DW_UNSND (attr);
15879       else
15880         {
15881           /* For the moment, dynamic type sizes are not supported
15882              by GDB's struct type.  The actual size is determined
15883              on-demand when resolving the type of a given object,
15884              so set the type's length to zero for now.  Otherwise,
15885              we record an expression as the length, and that expression
15886              could lead to a very large value, which could eventually
15887              lead to us trying to allocate that much memory when creating
15888              a value of that type.  */
15889           TYPE_LENGTH (type) = 0;
15890         }
15891     }
15892   else
15893     {
15894       TYPE_LENGTH (type) = 0;
15895     }
15896
15897   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15898     {
15899       /* ICC<14 does not output the required DW_AT_declaration on
15900          incomplete types, but gives them a size of zero.  */
15901       TYPE_STUB (type) = 1;
15902     }
15903   else
15904     TYPE_STUB_SUPPORTED (type) = 1;
15905
15906   if (die_is_declaration (die, cu))
15907     TYPE_STUB (type) = 1;
15908   else if (attr == NULL && die->child == NULL
15909            && producer_is_realview (cu->producer))
15910     /* RealView does not output the required DW_AT_declaration
15911        on incomplete types.  */
15912     TYPE_STUB (type) = 1;
15913
15914   /* We need to add the type field to the die immediately so we don't
15915      infinitely recurse when dealing with pointers to the structure
15916      type within the structure itself.  */
15917   set_die_type (die, type, cu);
15918
15919   /* set_die_type should be already done.  */
15920   set_descriptive_type (type, die, cu);
15921
15922   return type;
15923 }
15924
15925 /* Finish creating a structure or union type, including filling in
15926    its members and creating a symbol for it.  */
15927
15928 static void
15929 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15930 {
15931   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15932   struct die_info *child_die;
15933   struct type *type;
15934
15935   type = get_die_type (die, cu);
15936   if (type == NULL)
15937     type = read_structure_type (die, cu);
15938
15939   if (die->child != NULL && ! die_is_declaration (die, cu))
15940     {
15941       struct field_info fi;
15942       std::vector<struct symbol *> template_args;
15943       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15944
15945       memset (&fi, 0, sizeof (struct field_info));
15946
15947       child_die = die->child;
15948
15949       while (child_die && child_die->tag)
15950         {
15951           if (child_die->tag == DW_TAG_member
15952               || child_die->tag == DW_TAG_variable)
15953             {
15954               /* NOTE: carlton/2002-11-05: A C++ static data member
15955                  should be a DW_TAG_member that is a declaration, but
15956                  all versions of G++ as of this writing (so through at
15957                  least 3.2.1) incorrectly generate DW_TAG_variable
15958                  tags for them instead.  */
15959               dwarf2_add_field (&fi, child_die, cu);
15960             }
15961           else if (child_die->tag == DW_TAG_subprogram)
15962             {
15963               /* Rust doesn't have member functions in the C++ sense.
15964                  However, it does emit ordinary functions as children
15965                  of a struct DIE.  */
15966               if (cu->language == language_rust)
15967                 read_func_scope (child_die, cu);
15968               else
15969                 {
15970                   /* C++ member function.  */
15971                   dwarf2_add_member_fn (&fi, child_die, type, cu);
15972                 }
15973             }
15974           else if (child_die->tag == DW_TAG_inheritance)
15975             {
15976               /* C++ base class field.  */
15977               dwarf2_add_field (&fi, child_die, cu);
15978             }
15979           else if (type_can_define_types (child_die))
15980             dwarf2_add_type_defn (&fi, child_die, cu);
15981           else if (child_die->tag == DW_TAG_template_type_param
15982                    || child_die->tag == DW_TAG_template_value_param)
15983             {
15984               struct symbol *arg = new_symbol (child_die, NULL, cu);
15985
15986               if (arg != NULL)
15987                 template_args.push_back (arg);
15988             }
15989
15990           child_die = sibling_die (child_die);
15991         }
15992
15993       /* Attach template arguments to type.  */
15994       if (!template_args.empty ())
15995         {
15996           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15997           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15998           TYPE_TEMPLATE_ARGUMENTS (type)
15999             = XOBNEWVEC (&objfile->objfile_obstack,
16000                          struct symbol *,
16001                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16002           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16003                   template_args.data (),
16004                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16005                    * sizeof (struct symbol *)));
16006         }
16007
16008       /* Attach fields and member functions to the type.  */
16009       if (fi.nfields)
16010         dwarf2_attach_fields_to_type (&fi, type, cu);
16011       if (fi.nfnfields)
16012         {
16013           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16014
16015           /* Get the type which refers to the base class (possibly this
16016              class itself) which contains the vtable pointer for the current
16017              class from the DW_AT_containing_type attribute.  This use of
16018              DW_AT_containing_type is a GNU extension.  */
16019
16020           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16021             {
16022               struct type *t = die_containing_type (die, cu);
16023
16024               set_type_vptr_basetype (type, t);
16025               if (type == t)
16026                 {
16027                   int i;
16028
16029                   /* Our own class provides vtbl ptr.  */
16030                   for (i = TYPE_NFIELDS (t) - 1;
16031                        i >= TYPE_N_BASECLASSES (t);
16032                        --i)
16033                     {
16034                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16035
16036                       if (is_vtable_name (fieldname, cu))
16037                         {
16038                           set_type_vptr_fieldno (type, i);
16039                           break;
16040                         }
16041                     }
16042
16043                   /* Complain if virtual function table field not found.  */
16044                   if (i < TYPE_N_BASECLASSES (t))
16045                     complaint (&symfile_complaints,
16046                                _("virtual function table pointer "
16047                                  "not found when defining class '%s'"),
16048                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16049                                "");
16050                 }
16051               else
16052                 {
16053                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16054                 }
16055             }
16056           else if (cu->producer
16057                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16058             {
16059               /* The IBM XLC compiler does not provide direct indication
16060                  of the containing type, but the vtable pointer is
16061                  always named __vfp.  */
16062
16063               int i;
16064
16065               for (i = TYPE_NFIELDS (type) - 1;
16066                    i >= TYPE_N_BASECLASSES (type);
16067                    --i)
16068                 {
16069                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16070                     {
16071                       set_type_vptr_fieldno (type, i);
16072                       set_type_vptr_basetype (type, type);
16073                       break;
16074                     }
16075                 }
16076             }
16077         }
16078
16079       /* Copy fi.typedef_field_list linked list elements content into the
16080          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16081       if (fi.typedef_field_list)
16082         {
16083           int i = fi.typedef_field_list_count;
16084
16085           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16086           TYPE_TYPEDEF_FIELD_ARRAY (type)
16087             = ((struct decl_field *)
16088                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16089           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16090
16091           /* Reverse the list order to keep the debug info elements order.  */
16092           while (--i >= 0)
16093             {
16094               struct decl_field *dest, *src;
16095
16096               dest = &TYPE_TYPEDEF_FIELD (type, i);
16097               src = &fi.typedef_field_list->field;
16098               fi.typedef_field_list = fi.typedef_field_list->next;
16099               *dest = *src;
16100             }
16101         }
16102
16103       /* Copy fi.nested_types_list linked list elements content into the
16104          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16105       if (fi.nested_types_list != NULL && cu->language != language_ada)
16106         {
16107           int i = fi.nested_types_list_count;
16108
16109           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16110           TYPE_NESTED_TYPES_ARRAY (type)
16111             = ((struct decl_field *)
16112                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16113           TYPE_NESTED_TYPES_COUNT (type) = i;
16114
16115           /* Reverse the list order to keep the debug info elements order.  */
16116           while (--i >= 0)
16117             {
16118               struct decl_field *dest, *src;
16119
16120               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16121               src = &fi.nested_types_list->field;
16122               fi.nested_types_list = fi.nested_types_list->next;
16123               *dest = *src;
16124             }
16125         }
16126
16127       do_cleanups (back_to);
16128     }
16129
16130   quirk_gcc_member_function_pointer (type, objfile);
16131
16132   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16133      snapshots) has been known to create a die giving a declaration
16134      for a class that has, as a child, a die giving a definition for a
16135      nested class.  So we have to process our children even if the
16136      current die is a declaration.  Normally, of course, a declaration
16137      won't have any children at all.  */
16138
16139   child_die = die->child;
16140
16141   while (child_die != NULL && child_die->tag)
16142     {
16143       if (child_die->tag == DW_TAG_member
16144           || child_die->tag == DW_TAG_variable
16145           || child_die->tag == DW_TAG_inheritance
16146           || child_die->tag == DW_TAG_template_value_param
16147           || child_die->tag == DW_TAG_template_type_param)
16148         {
16149           /* Do nothing.  */
16150         }
16151       else
16152         process_die (child_die, cu);
16153
16154       child_die = sibling_die (child_die);
16155     }
16156
16157   /* Do not consider external references.  According to the DWARF standard,
16158      these DIEs are identified by the fact that they have no byte_size
16159      attribute, and a declaration attribute.  */
16160   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16161       || !die_is_declaration (die, cu))
16162     new_symbol (die, type, cu);
16163 }
16164
16165 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16166    update TYPE using some information only available in DIE's children.  */
16167
16168 static void
16169 update_enumeration_type_from_children (struct die_info *die,
16170                                        struct type *type,
16171                                        struct dwarf2_cu *cu)
16172 {
16173   struct die_info *child_die;
16174   int unsigned_enum = 1;
16175   int flag_enum = 1;
16176   ULONGEST mask = 0;
16177
16178   auto_obstack obstack;
16179
16180   for (child_die = die->child;
16181        child_die != NULL && child_die->tag;
16182        child_die = sibling_die (child_die))
16183     {
16184       struct attribute *attr;
16185       LONGEST value;
16186       const gdb_byte *bytes;
16187       struct dwarf2_locexpr_baton *baton;
16188       const char *name;
16189
16190       if (child_die->tag != DW_TAG_enumerator)
16191         continue;
16192
16193       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16194       if (attr == NULL)
16195         continue;
16196
16197       name = dwarf2_name (child_die, cu);
16198       if (name == NULL)
16199         name = "<anonymous enumerator>";
16200
16201       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16202                                &value, &bytes, &baton);
16203       if (value < 0)
16204         {
16205           unsigned_enum = 0;
16206           flag_enum = 0;
16207         }
16208       else if ((mask & value) != 0)
16209         flag_enum = 0;
16210       else
16211         mask |= value;
16212
16213       /* If we already know that the enum type is neither unsigned, nor
16214          a flag type, no need to look at the rest of the enumerates.  */
16215       if (!unsigned_enum && !flag_enum)
16216         break;
16217     }
16218
16219   if (unsigned_enum)
16220     TYPE_UNSIGNED (type) = 1;
16221   if (flag_enum)
16222     TYPE_FLAG_ENUM (type) = 1;
16223 }
16224
16225 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16226    complete the type's fields yet, or create any symbols.  */
16227
16228 static struct type *
16229 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16230 {
16231   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16232   struct type *type;
16233   struct attribute *attr;
16234   const char *name;
16235
16236   /* If the definition of this type lives in .debug_types, read that type.
16237      Don't follow DW_AT_specification though, that will take us back up
16238      the chain and we want to go down.  */
16239   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16240   if (attr)
16241     {
16242       type = get_DW_AT_signature_type (die, attr, cu);
16243
16244       /* The type's CU may not be the same as CU.
16245          Ensure TYPE is recorded with CU in die_type_hash.  */
16246       return set_die_type (die, type, cu);
16247     }
16248
16249   type = alloc_type (objfile);
16250
16251   TYPE_CODE (type) = TYPE_CODE_ENUM;
16252   name = dwarf2_full_name (NULL, die, cu);
16253   if (name != NULL)
16254     TYPE_TAG_NAME (type) = name;
16255
16256   attr = dwarf2_attr (die, DW_AT_type, cu);
16257   if (attr != NULL)
16258     {
16259       struct type *underlying_type = die_type (die, cu);
16260
16261       TYPE_TARGET_TYPE (type) = underlying_type;
16262     }
16263
16264   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16265   if (attr)
16266     {
16267       TYPE_LENGTH (type) = DW_UNSND (attr);
16268     }
16269   else
16270     {
16271       TYPE_LENGTH (type) = 0;
16272     }
16273
16274   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16275      declared as private in the package spec, and then defined only
16276      inside the package body.  Such types are known as Taft Amendment
16277      Types.  When another package uses such a type, an incomplete DIE
16278      may be generated by the compiler.  */
16279   if (die_is_declaration (die, cu))
16280     TYPE_STUB (type) = 1;
16281
16282   /* Finish the creation of this type by using the enum's children.
16283      We must call this even when the underlying type has been provided
16284      so that we can determine if we're looking at a "flag" enum.  */
16285   update_enumeration_type_from_children (die, type, cu);
16286
16287   /* If this type has an underlying type that is not a stub, then we
16288      may use its attributes.  We always use the "unsigned" attribute
16289      in this situation, because ordinarily we guess whether the type
16290      is unsigned -- but the guess can be wrong and the underlying type
16291      can tell us the reality.  However, we defer to a local size
16292      attribute if one exists, because this lets the compiler override
16293      the underlying type if needed.  */
16294   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16295     {
16296       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16297       if (TYPE_LENGTH (type) == 0)
16298         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16299     }
16300
16301   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16302
16303   return set_die_type (die, type, cu);
16304 }
16305
16306 /* Given a pointer to a die which begins an enumeration, process all
16307    the dies that define the members of the enumeration, and create the
16308    symbol for the enumeration type.
16309
16310    NOTE: We reverse the order of the element list.  */
16311
16312 static void
16313 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16314 {
16315   struct type *this_type;
16316
16317   this_type = get_die_type (die, cu);
16318   if (this_type == NULL)
16319     this_type = read_enumeration_type (die, cu);
16320
16321   if (die->child != NULL)
16322     {
16323       struct die_info *child_die;
16324       struct symbol *sym;
16325       struct field *fields = NULL;
16326       int num_fields = 0;
16327       const char *name;
16328
16329       child_die = die->child;
16330       while (child_die && child_die->tag)
16331         {
16332           if (child_die->tag != DW_TAG_enumerator)
16333             {
16334               process_die (child_die, cu);
16335             }
16336           else
16337             {
16338               name = dwarf2_name (child_die, cu);
16339               if (name)
16340                 {
16341                   sym = new_symbol (child_die, this_type, cu);
16342
16343                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16344                     {
16345                       fields = (struct field *)
16346                         xrealloc (fields,
16347                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16348                                   * sizeof (struct field));
16349                     }
16350
16351                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16352                   FIELD_TYPE (fields[num_fields]) = NULL;
16353                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16354                   FIELD_BITSIZE (fields[num_fields]) = 0;
16355
16356                   num_fields++;
16357                 }
16358             }
16359
16360           child_die = sibling_die (child_die);
16361         }
16362
16363       if (num_fields)
16364         {
16365           TYPE_NFIELDS (this_type) = num_fields;
16366           TYPE_FIELDS (this_type) = (struct field *)
16367             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16368           memcpy (TYPE_FIELDS (this_type), fields,
16369                   sizeof (struct field) * num_fields);
16370           xfree (fields);
16371         }
16372     }
16373
16374   /* If we are reading an enum from a .debug_types unit, and the enum
16375      is a declaration, and the enum is not the signatured type in the
16376      unit, then we do not want to add a symbol for it.  Adding a
16377      symbol would in some cases obscure the true definition of the
16378      enum, giving users an incomplete type when the definition is
16379      actually available.  Note that we do not want to do this for all
16380      enums which are just declarations, because C++0x allows forward
16381      enum declarations.  */
16382   if (cu->per_cu->is_debug_types
16383       && die_is_declaration (die, cu))
16384     {
16385       struct signatured_type *sig_type;
16386
16387       sig_type = (struct signatured_type *) cu->per_cu;
16388       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16389       if (sig_type->type_offset_in_section != die->sect_off)
16390         return;
16391     }
16392
16393   new_symbol (die, this_type, cu);
16394 }
16395
16396 /* Extract all information from a DW_TAG_array_type DIE and put it in
16397    the DIE's type field.  For now, this only handles one dimensional
16398    arrays.  */
16399
16400 static struct type *
16401 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16402 {
16403   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16404   struct die_info *child_die;
16405   struct type *type;
16406   struct type *element_type, *range_type, *index_type;
16407   struct attribute *attr;
16408   const char *name;
16409   struct dynamic_prop *byte_stride_prop = NULL;
16410   unsigned int bit_stride = 0;
16411
16412   element_type = die_type (die, cu);
16413
16414   /* The die_type call above may have already set the type for this DIE.  */
16415   type = get_die_type (die, cu);
16416   if (type)
16417     return type;
16418
16419   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16420   if (attr != NULL)
16421     {
16422       int stride_ok;
16423
16424       byte_stride_prop
16425         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16426       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16427       if (!stride_ok)
16428         {
16429           complaint (&symfile_complaints,
16430                      _("unable to read array DW_AT_byte_stride "
16431                        " - DIE at 0x%x [in module %s]"),
16432                      to_underlying (die->sect_off),
16433                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16434           /* Ignore this attribute.  We will likely not be able to print
16435              arrays of this type correctly, but there is little we can do
16436              to help if we cannot read the attribute's value.  */
16437           byte_stride_prop = NULL;
16438         }
16439     }
16440
16441   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16442   if (attr != NULL)
16443     bit_stride = DW_UNSND (attr);
16444
16445   /* Irix 6.2 native cc creates array types without children for
16446      arrays with unspecified length.  */
16447   if (die->child == NULL)
16448     {
16449       index_type = objfile_type (objfile)->builtin_int;
16450       range_type = create_static_range_type (NULL, index_type, 0, -1);
16451       type = create_array_type_with_stride (NULL, element_type, range_type,
16452                                             byte_stride_prop, bit_stride);
16453       return set_die_type (die, type, cu);
16454     }
16455
16456   std::vector<struct type *> range_types;
16457   child_die = die->child;
16458   while (child_die && child_die->tag)
16459     {
16460       if (child_die->tag == DW_TAG_subrange_type)
16461         {
16462           struct type *child_type = read_type_die (child_die, cu);
16463
16464           if (child_type != NULL)
16465             {
16466               /* The range type was succesfully read.  Save it for the
16467                  array type creation.  */
16468               range_types.push_back (child_type);
16469             }
16470         }
16471       child_die = sibling_die (child_die);
16472     }
16473
16474   /* Dwarf2 dimensions are output from left to right, create the
16475      necessary array types in backwards order.  */
16476
16477   type = element_type;
16478
16479   if (read_array_order (die, cu) == DW_ORD_col_major)
16480     {
16481       int i = 0;
16482
16483       while (i < range_types.size ())
16484         type = create_array_type_with_stride (NULL, type, range_types[i++],
16485                                               byte_stride_prop, bit_stride);
16486     }
16487   else
16488     {
16489       size_t ndim = range_types.size ();
16490       while (ndim-- > 0)
16491         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16492                                               byte_stride_prop, bit_stride);
16493     }
16494
16495   /* Understand Dwarf2 support for vector types (like they occur on
16496      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16497      array type.  This is not part of the Dwarf2/3 standard yet, but a
16498      custom vendor extension.  The main difference between a regular
16499      array and the vector variant is that vectors are passed by value
16500      to functions.  */
16501   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16502   if (attr)
16503     make_vector_type (type);
16504
16505   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16506      implementation may choose to implement triple vectors using this
16507      attribute.  */
16508   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16509   if (attr)
16510     {
16511       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16512         TYPE_LENGTH (type) = DW_UNSND (attr);
16513       else
16514         complaint (&symfile_complaints,
16515                    _("DW_AT_byte_size for array type smaller "
16516                      "than the total size of elements"));
16517     }
16518
16519   name = dwarf2_name (die, cu);
16520   if (name)
16521     TYPE_NAME (type) = name;
16522
16523   /* Install the type in the die.  */
16524   set_die_type (die, type, cu);
16525
16526   /* set_die_type should be already done.  */
16527   set_descriptive_type (type, die, cu);
16528
16529   return type;
16530 }
16531
16532 static enum dwarf_array_dim_ordering
16533 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16534 {
16535   struct attribute *attr;
16536
16537   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16538
16539   if (attr)
16540     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16541
16542   /* GNU F77 is a special case, as at 08/2004 array type info is the
16543      opposite order to the dwarf2 specification, but data is still
16544      laid out as per normal fortran.
16545
16546      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16547      version checking.  */
16548
16549   if (cu->language == language_fortran
16550       && cu->producer && strstr (cu->producer, "GNU F77"))
16551     {
16552       return DW_ORD_row_major;
16553     }
16554
16555   switch (cu->language_defn->la_array_ordering)
16556     {
16557     case array_column_major:
16558       return DW_ORD_col_major;
16559     case array_row_major:
16560     default:
16561       return DW_ORD_row_major;
16562     };
16563 }
16564
16565 /* Extract all information from a DW_TAG_set_type DIE and put it in
16566    the DIE's type field.  */
16567
16568 static struct type *
16569 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16570 {
16571   struct type *domain_type, *set_type;
16572   struct attribute *attr;
16573
16574   domain_type = die_type (die, cu);
16575
16576   /* The die_type call above may have already set the type for this DIE.  */
16577   set_type = get_die_type (die, cu);
16578   if (set_type)
16579     return set_type;
16580
16581   set_type = create_set_type (NULL, domain_type);
16582
16583   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16584   if (attr)
16585     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16586
16587   return set_die_type (die, set_type, cu);
16588 }
16589
16590 /* A helper for read_common_block that creates a locexpr baton.
16591    SYM is the symbol which we are marking as computed.
16592    COMMON_DIE is the DIE for the common block.
16593    COMMON_LOC is the location expression attribute for the common
16594    block itself.
16595    MEMBER_LOC is the location expression attribute for the particular
16596    member of the common block that we are processing.
16597    CU is the CU from which the above come.  */
16598
16599 static void
16600 mark_common_block_symbol_computed (struct symbol *sym,
16601                                    struct die_info *common_die,
16602                                    struct attribute *common_loc,
16603                                    struct attribute *member_loc,
16604                                    struct dwarf2_cu *cu)
16605 {
16606   struct dwarf2_per_objfile *dwarf2_per_objfile
16607     = cu->per_cu->dwarf2_per_objfile;
16608   struct objfile *objfile = dwarf2_per_objfile->objfile;
16609   struct dwarf2_locexpr_baton *baton;
16610   gdb_byte *ptr;
16611   unsigned int cu_off;
16612   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16613   LONGEST offset = 0;
16614
16615   gdb_assert (common_loc && member_loc);
16616   gdb_assert (attr_form_is_block (common_loc));
16617   gdb_assert (attr_form_is_block (member_loc)
16618               || attr_form_is_constant (member_loc));
16619
16620   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16621   baton->per_cu = cu->per_cu;
16622   gdb_assert (baton->per_cu);
16623
16624   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16625
16626   if (attr_form_is_constant (member_loc))
16627     {
16628       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16629       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16630     }
16631   else
16632     baton->size += DW_BLOCK (member_loc)->size;
16633
16634   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16635   baton->data = ptr;
16636
16637   *ptr++ = DW_OP_call4;
16638   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16639   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16640   ptr += 4;
16641
16642   if (attr_form_is_constant (member_loc))
16643     {
16644       *ptr++ = DW_OP_addr;
16645       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16646       ptr += cu->header.addr_size;
16647     }
16648   else
16649     {
16650       /* We have to copy the data here, because DW_OP_call4 will only
16651          use a DW_AT_location attribute.  */
16652       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16653       ptr += DW_BLOCK (member_loc)->size;
16654     }
16655
16656   *ptr++ = DW_OP_plus;
16657   gdb_assert (ptr - baton->data == baton->size);
16658
16659   SYMBOL_LOCATION_BATON (sym) = baton;
16660   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16661 }
16662
16663 /* Create appropriate locally-scoped variables for all the
16664    DW_TAG_common_block entries.  Also create a struct common_block
16665    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16666    is used to sepate the common blocks name namespace from regular
16667    variable names.  */
16668
16669 static void
16670 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16671 {
16672   struct attribute *attr;
16673
16674   attr = dwarf2_attr (die, DW_AT_location, cu);
16675   if (attr)
16676     {
16677       /* Support the .debug_loc offsets.  */
16678       if (attr_form_is_block (attr))
16679         {
16680           /* Ok.  */
16681         }
16682       else if (attr_form_is_section_offset (attr))
16683         {
16684           dwarf2_complex_location_expr_complaint ();
16685           attr = NULL;
16686         }
16687       else
16688         {
16689           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16690                                                  "common block member");
16691           attr = NULL;
16692         }
16693     }
16694
16695   if (die->child != NULL)
16696     {
16697       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16698       struct die_info *child_die;
16699       size_t n_entries = 0, size;
16700       struct common_block *common_block;
16701       struct symbol *sym;
16702
16703       for (child_die = die->child;
16704            child_die && child_die->tag;
16705            child_die = sibling_die (child_die))
16706         ++n_entries;
16707
16708       size = (sizeof (struct common_block)
16709               + (n_entries - 1) * sizeof (struct symbol *));
16710       common_block
16711         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16712                                                  size);
16713       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16714       common_block->n_entries = 0;
16715
16716       for (child_die = die->child;
16717            child_die && child_die->tag;
16718            child_die = sibling_die (child_die))
16719         {
16720           /* Create the symbol in the DW_TAG_common_block block in the current
16721              symbol scope.  */
16722           sym = new_symbol (child_die, NULL, cu);
16723           if (sym != NULL)
16724             {
16725               struct attribute *member_loc;
16726
16727               common_block->contents[common_block->n_entries++] = sym;
16728
16729               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16730                                         cu);
16731               if (member_loc)
16732                 {
16733                   /* GDB has handled this for a long time, but it is
16734                      not specified by DWARF.  It seems to have been
16735                      emitted by gfortran at least as recently as:
16736                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16737                   complaint (&symfile_complaints,
16738                              _("Variable in common block has "
16739                                "DW_AT_data_member_location "
16740                                "- DIE at 0x%x [in module %s]"),
16741                              to_underlying (child_die->sect_off),
16742                              objfile_name (objfile));
16743
16744                   if (attr_form_is_section_offset (member_loc))
16745                     dwarf2_complex_location_expr_complaint ();
16746                   else if (attr_form_is_constant (member_loc)
16747                            || attr_form_is_block (member_loc))
16748                     {
16749                       if (attr)
16750                         mark_common_block_symbol_computed (sym, die, attr,
16751                                                            member_loc, cu);
16752                     }
16753                   else
16754                     dwarf2_complex_location_expr_complaint ();
16755                 }
16756             }
16757         }
16758
16759       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16760       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16761     }
16762 }
16763
16764 /* Create a type for a C++ namespace.  */
16765
16766 static struct type *
16767 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16768 {
16769   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16770   const char *previous_prefix, *name;
16771   int is_anonymous;
16772   struct type *type;
16773
16774   /* For extensions, reuse the type of the original namespace.  */
16775   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16776     {
16777       struct die_info *ext_die;
16778       struct dwarf2_cu *ext_cu = cu;
16779
16780       ext_die = dwarf2_extension (die, &ext_cu);
16781       type = read_type_die (ext_die, ext_cu);
16782
16783       /* EXT_CU may not be the same as CU.
16784          Ensure TYPE is recorded with CU in die_type_hash.  */
16785       return set_die_type (die, type, cu);
16786     }
16787
16788   name = namespace_name (die, &is_anonymous, cu);
16789
16790   /* Now build the name of the current namespace.  */
16791
16792   previous_prefix = determine_prefix (die, cu);
16793   if (previous_prefix[0] != '\0')
16794     name = typename_concat (&objfile->objfile_obstack,
16795                             previous_prefix, name, 0, cu);
16796
16797   /* Create the type.  */
16798   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16799   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16800
16801   return set_die_type (die, type, cu);
16802 }
16803
16804 /* Read a namespace scope.  */
16805
16806 static void
16807 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16808 {
16809   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16810   int is_anonymous;
16811
16812   /* Add a symbol associated to this if we haven't seen the namespace
16813      before.  Also, add a using directive if it's an anonymous
16814      namespace.  */
16815
16816   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16817     {
16818       struct type *type;
16819
16820       type = read_type_die (die, cu);
16821       new_symbol (die, type, cu);
16822
16823       namespace_name (die, &is_anonymous, cu);
16824       if (is_anonymous)
16825         {
16826           const char *previous_prefix = determine_prefix (die, cu);
16827
16828           std::vector<const char *> excludes;
16829           add_using_directive (using_directives (cu->language),
16830                                previous_prefix, TYPE_NAME (type), NULL,
16831                                NULL, excludes, 0, &objfile->objfile_obstack);
16832         }
16833     }
16834
16835   if (die->child != NULL)
16836     {
16837       struct die_info *child_die = die->child;
16838
16839       while (child_die && child_die->tag)
16840         {
16841           process_die (child_die, cu);
16842           child_die = sibling_die (child_die);
16843         }
16844     }
16845 }
16846
16847 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16848    imported module.  Still we need that type as local Fortran "use ... only"
16849    declaration imports depend on the created type in determine_prefix.  */
16850
16851 static struct type *
16852 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16853 {
16854   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16855   const char *module_name;
16856   struct type *type;
16857
16858   module_name = dwarf2_name (die, cu);
16859   if (!module_name)
16860     complaint (&symfile_complaints,
16861                _("DW_TAG_module has no name, offset 0x%x"),
16862                to_underlying (die->sect_off));
16863   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16864
16865   /* determine_prefix uses TYPE_TAG_NAME.  */
16866   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16867
16868   return set_die_type (die, type, cu);
16869 }
16870
16871 /* Read a Fortran module.  */
16872
16873 static void
16874 read_module (struct die_info *die, struct dwarf2_cu *cu)
16875 {
16876   struct die_info *child_die = die->child;
16877   struct type *type;
16878
16879   type = read_type_die (die, cu);
16880   new_symbol (die, type, cu);
16881
16882   while (child_die && child_die->tag)
16883     {
16884       process_die (child_die, cu);
16885       child_die = sibling_die (child_die);
16886     }
16887 }
16888
16889 /* Return the name of the namespace represented by DIE.  Set
16890    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16891    namespace.  */
16892
16893 static const char *
16894 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16895 {
16896   struct die_info *current_die;
16897   const char *name = NULL;
16898
16899   /* Loop through the extensions until we find a name.  */
16900
16901   for (current_die = die;
16902        current_die != NULL;
16903        current_die = dwarf2_extension (die, &cu))
16904     {
16905       /* We don't use dwarf2_name here so that we can detect the absence
16906          of a name -> anonymous namespace.  */
16907       name = dwarf2_string_attr (die, DW_AT_name, cu);
16908
16909       if (name != NULL)
16910         break;
16911     }
16912
16913   /* Is it an anonymous namespace?  */
16914
16915   *is_anonymous = (name == NULL);
16916   if (*is_anonymous)
16917     name = CP_ANONYMOUS_NAMESPACE_STR;
16918
16919   return name;
16920 }
16921
16922 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16923    the user defined type vector.  */
16924
16925 static struct type *
16926 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16927 {
16928   struct gdbarch *gdbarch
16929     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16930   struct comp_unit_head *cu_header = &cu->header;
16931   struct type *type;
16932   struct attribute *attr_byte_size;
16933   struct attribute *attr_address_class;
16934   int byte_size, addr_class;
16935   struct type *target_type;
16936
16937   target_type = die_type (die, cu);
16938
16939   /* The die_type call above may have already set the type for this DIE.  */
16940   type = get_die_type (die, cu);
16941   if (type)
16942     return type;
16943
16944   type = lookup_pointer_type (target_type);
16945
16946   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16947   if (attr_byte_size)
16948     byte_size = DW_UNSND (attr_byte_size);
16949   else
16950     byte_size = cu_header->addr_size;
16951
16952   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16953   if (attr_address_class)
16954     addr_class = DW_UNSND (attr_address_class);
16955   else
16956     addr_class = DW_ADDR_none;
16957
16958   /* If the pointer size or address class is different than the
16959      default, create a type variant marked as such and set the
16960      length accordingly.  */
16961   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16962     {
16963       if (gdbarch_address_class_type_flags_p (gdbarch))
16964         {
16965           int type_flags;
16966
16967           type_flags = gdbarch_address_class_type_flags
16968                          (gdbarch, byte_size, addr_class);
16969           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16970                       == 0);
16971           type = make_type_with_address_space (type, type_flags);
16972         }
16973       else if (TYPE_LENGTH (type) != byte_size)
16974         {
16975           complaint (&symfile_complaints,
16976                      _("invalid pointer size %d"), byte_size);
16977         }
16978       else
16979         {
16980           /* Should we also complain about unhandled address classes?  */
16981         }
16982     }
16983
16984   TYPE_LENGTH (type) = byte_size;
16985   return set_die_type (die, type, cu);
16986 }
16987
16988 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16989    the user defined type vector.  */
16990
16991 static struct type *
16992 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16993 {
16994   struct type *type;
16995   struct type *to_type;
16996   struct type *domain;
16997
16998   to_type = die_type (die, cu);
16999   domain = die_containing_type (die, cu);
17000
17001   /* The calls above may have already set the type for this DIE.  */
17002   type = get_die_type (die, cu);
17003   if (type)
17004     return type;
17005
17006   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17007     type = lookup_methodptr_type (to_type);
17008   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17009     {
17010       struct type *new_type
17011         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17012
17013       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17014                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17015                             TYPE_VARARGS (to_type));
17016       type = lookup_methodptr_type (new_type);
17017     }
17018   else
17019     type = lookup_memberptr_type (to_type, domain);
17020
17021   return set_die_type (die, type, cu);
17022 }
17023
17024 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17025    the user defined type vector.  */
17026
17027 static struct type *
17028 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17029                           enum type_code refcode)
17030 {
17031   struct comp_unit_head *cu_header = &cu->header;
17032   struct type *type, *target_type;
17033   struct attribute *attr;
17034
17035   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17036
17037   target_type = die_type (die, cu);
17038
17039   /* The die_type call above may have already set the type for this DIE.  */
17040   type = get_die_type (die, cu);
17041   if (type)
17042     return type;
17043
17044   type = lookup_reference_type (target_type, refcode);
17045   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17046   if (attr)
17047     {
17048       TYPE_LENGTH (type) = DW_UNSND (attr);
17049     }
17050   else
17051     {
17052       TYPE_LENGTH (type) = cu_header->addr_size;
17053     }
17054   return set_die_type (die, type, cu);
17055 }
17056
17057 /* Add the given cv-qualifiers to the element type of the array.  GCC
17058    outputs DWARF type qualifiers that apply to an array, not the
17059    element type.  But GDB relies on the array element type to carry
17060    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17061    specification.  */
17062
17063 static struct type *
17064 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17065                    struct type *base_type, int cnst, int voltl)
17066 {
17067   struct type *el_type, *inner_array;
17068
17069   base_type = copy_type (base_type);
17070   inner_array = base_type;
17071
17072   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17073     {
17074       TYPE_TARGET_TYPE (inner_array) =
17075         copy_type (TYPE_TARGET_TYPE (inner_array));
17076       inner_array = TYPE_TARGET_TYPE (inner_array);
17077     }
17078
17079   el_type = TYPE_TARGET_TYPE (inner_array);
17080   cnst |= TYPE_CONST (el_type);
17081   voltl |= TYPE_VOLATILE (el_type);
17082   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17083
17084   return set_die_type (die, base_type, cu);
17085 }
17086
17087 static struct type *
17088 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17089 {
17090   struct type *base_type, *cv_type;
17091
17092   base_type = die_type (die, cu);
17093
17094   /* The die_type call above may have already set the type for this DIE.  */
17095   cv_type = get_die_type (die, cu);
17096   if (cv_type)
17097     return cv_type;
17098
17099   /* In case the const qualifier is applied to an array type, the element type
17100      is so qualified, not the array type (section 6.7.3 of C99).  */
17101   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17102     return add_array_cv_type (die, cu, base_type, 1, 0);
17103
17104   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17105   return set_die_type (die, cv_type, cu);
17106 }
17107
17108 static struct type *
17109 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17110 {
17111   struct type *base_type, *cv_type;
17112
17113   base_type = die_type (die, cu);
17114
17115   /* The die_type call above may have already set the type for this DIE.  */
17116   cv_type = get_die_type (die, cu);
17117   if (cv_type)
17118     return cv_type;
17119
17120   /* In case the volatile qualifier is applied to an array type, the
17121      element type is so qualified, not the array type (section 6.7.3
17122      of C99).  */
17123   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17124     return add_array_cv_type (die, cu, base_type, 0, 1);
17125
17126   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17127   return set_die_type (die, cv_type, cu);
17128 }
17129
17130 /* Handle DW_TAG_restrict_type.  */
17131
17132 static struct type *
17133 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17134 {
17135   struct type *base_type, *cv_type;
17136
17137   base_type = die_type (die, cu);
17138
17139   /* The die_type call above may have already set the type for this DIE.  */
17140   cv_type = get_die_type (die, cu);
17141   if (cv_type)
17142     return cv_type;
17143
17144   cv_type = make_restrict_type (base_type);
17145   return set_die_type (die, cv_type, cu);
17146 }
17147
17148 /* Handle DW_TAG_atomic_type.  */
17149
17150 static struct type *
17151 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17152 {
17153   struct type *base_type, *cv_type;
17154
17155   base_type = die_type (die, cu);
17156
17157   /* The die_type call above may have already set the type for this DIE.  */
17158   cv_type = get_die_type (die, cu);
17159   if (cv_type)
17160     return cv_type;
17161
17162   cv_type = make_atomic_type (base_type);
17163   return set_die_type (die, cv_type, cu);
17164 }
17165
17166 /* Extract all information from a DW_TAG_string_type DIE and add to
17167    the user defined type vector.  It isn't really a user defined type,
17168    but it behaves like one, with other DIE's using an AT_user_def_type
17169    attribute to reference it.  */
17170
17171 static struct type *
17172 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17173 {
17174   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17175   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17176   struct type *type, *range_type, *index_type, *char_type;
17177   struct attribute *attr;
17178   unsigned int length;
17179
17180   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17181   if (attr)
17182     {
17183       length = DW_UNSND (attr);
17184     }
17185   else
17186     {
17187       /* Check for the DW_AT_byte_size attribute.  */
17188       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17189       if (attr)
17190         {
17191           length = DW_UNSND (attr);
17192         }
17193       else
17194         {
17195           length = 1;
17196         }
17197     }
17198
17199   index_type = objfile_type (objfile)->builtin_int;
17200   range_type = create_static_range_type (NULL, index_type, 1, length);
17201   char_type = language_string_char_type (cu->language_defn, gdbarch);
17202   type = create_string_type (NULL, char_type, range_type);
17203
17204   return set_die_type (die, type, cu);
17205 }
17206
17207 /* Assuming that DIE corresponds to a function, returns nonzero
17208    if the function is prototyped.  */
17209
17210 static int
17211 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17212 {
17213   struct attribute *attr;
17214
17215   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17216   if (attr && (DW_UNSND (attr) != 0))
17217     return 1;
17218
17219   /* The DWARF standard implies that the DW_AT_prototyped attribute
17220      is only meaninful for C, but the concept also extends to other
17221      languages that allow unprototyped functions (Eg: Objective C).
17222      For all other languages, assume that functions are always
17223      prototyped.  */
17224   if (cu->language != language_c
17225       && cu->language != language_objc
17226       && cu->language != language_opencl)
17227     return 1;
17228
17229   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17230      prototyped and unprototyped functions; default to prototyped,
17231      since that is more common in modern code (and RealView warns
17232      about unprototyped functions).  */
17233   if (producer_is_realview (cu->producer))
17234     return 1;
17235
17236   return 0;
17237 }
17238
17239 /* Handle DIES due to C code like:
17240
17241    struct foo
17242    {
17243    int (*funcp)(int a, long l);
17244    int b;
17245    };
17246
17247    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17248
17249 static struct type *
17250 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17251 {
17252   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17253   struct type *type;            /* Type that this function returns.  */
17254   struct type *ftype;           /* Function that returns above type.  */
17255   struct attribute *attr;
17256
17257   type = die_type (die, cu);
17258
17259   /* The die_type call above may have already set the type for this DIE.  */
17260   ftype = get_die_type (die, cu);
17261   if (ftype)
17262     return ftype;
17263
17264   ftype = lookup_function_type (type);
17265
17266   if (prototyped_function_p (die, cu))
17267     TYPE_PROTOTYPED (ftype) = 1;
17268
17269   /* Store the calling convention in the type if it's available in
17270      the subroutine die.  Otherwise set the calling convention to
17271      the default value DW_CC_normal.  */
17272   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17273   if (attr)
17274     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17275   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17276     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17277   else
17278     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17279
17280   /* Record whether the function returns normally to its caller or not
17281      if the DWARF producer set that information.  */
17282   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17283   if (attr && (DW_UNSND (attr) != 0))
17284     TYPE_NO_RETURN (ftype) = 1;
17285
17286   /* We need to add the subroutine type to the die immediately so
17287      we don't infinitely recurse when dealing with parameters
17288      declared as the same subroutine type.  */
17289   set_die_type (die, ftype, cu);
17290
17291   if (die->child != NULL)
17292     {
17293       struct type *void_type = objfile_type (objfile)->builtin_void;
17294       struct die_info *child_die;
17295       int nparams, iparams;
17296
17297       /* Count the number of parameters.
17298          FIXME: GDB currently ignores vararg functions, but knows about
17299          vararg member functions.  */
17300       nparams = 0;
17301       child_die = die->child;
17302       while (child_die && child_die->tag)
17303         {
17304           if (child_die->tag == DW_TAG_formal_parameter)
17305             nparams++;
17306           else if (child_die->tag == DW_TAG_unspecified_parameters)
17307             TYPE_VARARGS (ftype) = 1;
17308           child_die = sibling_die (child_die);
17309         }
17310
17311       /* Allocate storage for parameters and fill them in.  */
17312       TYPE_NFIELDS (ftype) = nparams;
17313       TYPE_FIELDS (ftype) = (struct field *)
17314         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17315
17316       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17317          even if we error out during the parameters reading below.  */
17318       for (iparams = 0; iparams < nparams; iparams++)
17319         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17320
17321       iparams = 0;
17322       child_die = die->child;
17323       while (child_die && child_die->tag)
17324         {
17325           if (child_die->tag == DW_TAG_formal_parameter)
17326             {
17327               struct type *arg_type;
17328
17329               /* DWARF version 2 has no clean way to discern C++
17330                  static and non-static member functions.  G++ helps
17331                  GDB by marking the first parameter for non-static
17332                  member functions (which is the this pointer) as
17333                  artificial.  We pass this information to
17334                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17335
17336                  DWARF version 3 added DW_AT_object_pointer, which GCC
17337                  4.5 does not yet generate.  */
17338               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17339               if (attr)
17340                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17341               else
17342                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17343               arg_type = die_type (child_die, cu);
17344
17345               /* RealView does not mark THIS as const, which the testsuite
17346                  expects.  GCC marks THIS as const in method definitions,
17347                  but not in the class specifications (GCC PR 43053).  */
17348               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17349                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17350                 {
17351                   int is_this = 0;
17352                   struct dwarf2_cu *arg_cu = cu;
17353                   const char *name = dwarf2_name (child_die, cu);
17354
17355                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17356                   if (attr)
17357                     {
17358                       /* If the compiler emits this, use it.  */
17359                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17360                         is_this = 1;
17361                     }
17362                   else if (name && strcmp (name, "this") == 0)
17363                     /* Function definitions will have the argument names.  */
17364                     is_this = 1;
17365                   else if (name == NULL && iparams == 0)
17366                     /* Declarations may not have the names, so like
17367                        elsewhere in GDB, assume an artificial first
17368                        argument is "this".  */
17369                     is_this = 1;
17370
17371                   if (is_this)
17372                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17373                                              arg_type, 0);
17374                 }
17375
17376               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17377               iparams++;
17378             }
17379           child_die = sibling_die (child_die);
17380         }
17381     }
17382
17383   return ftype;
17384 }
17385
17386 static struct type *
17387 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17388 {
17389   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17390   const char *name = NULL;
17391   struct type *this_type, *target_type;
17392
17393   name = dwarf2_full_name (NULL, die, cu);
17394   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17395   TYPE_TARGET_STUB (this_type) = 1;
17396   set_die_type (die, this_type, cu);
17397   target_type = die_type (die, cu);
17398   if (target_type != this_type)
17399     TYPE_TARGET_TYPE (this_type) = target_type;
17400   else
17401     {
17402       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17403          spec and cause infinite loops in GDB.  */
17404       complaint (&symfile_complaints,
17405                  _("Self-referential DW_TAG_typedef "
17406                    "- DIE at 0x%x [in module %s]"),
17407                  to_underlying (die->sect_off), objfile_name (objfile));
17408       TYPE_TARGET_TYPE (this_type) = NULL;
17409     }
17410   return this_type;
17411 }
17412
17413 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17414    (which may be different from NAME) to the architecture back-end to allow
17415    it to guess the correct format if necessary.  */
17416
17417 static struct type *
17418 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17419                         const char *name_hint)
17420 {
17421   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17422   const struct floatformat **format;
17423   struct type *type;
17424
17425   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17426   if (format)
17427     type = init_float_type (objfile, bits, name, format);
17428   else
17429     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17430
17431   return type;
17432 }
17433
17434 /* Find a representation of a given base type and install
17435    it in the TYPE field of the die.  */
17436
17437 static struct type *
17438 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17439 {
17440   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17441   struct type *type;
17442   struct attribute *attr;
17443   int encoding = 0, bits = 0;
17444   const char *name;
17445
17446   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17447   if (attr)
17448     {
17449       encoding = DW_UNSND (attr);
17450     }
17451   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17452   if (attr)
17453     {
17454       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17455     }
17456   name = dwarf2_name (die, cu);
17457   if (!name)
17458     {
17459       complaint (&symfile_complaints,
17460                  _("DW_AT_name missing from DW_TAG_base_type"));
17461     }
17462
17463   switch (encoding)
17464     {
17465       case DW_ATE_address:
17466         /* Turn DW_ATE_address into a void * pointer.  */
17467         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17468         type = init_pointer_type (objfile, bits, name, type);
17469         break;
17470       case DW_ATE_boolean:
17471         type = init_boolean_type (objfile, bits, 1, name);
17472         break;
17473       case DW_ATE_complex_float:
17474         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17475         type = init_complex_type (objfile, name, type);
17476         break;
17477       case DW_ATE_decimal_float:
17478         type = init_decfloat_type (objfile, bits, name);
17479         break;
17480       case DW_ATE_float:
17481         type = dwarf2_init_float_type (objfile, bits, name, name);
17482         break;
17483       case DW_ATE_signed:
17484         type = init_integer_type (objfile, bits, 0, name);
17485         break;
17486       case DW_ATE_unsigned:
17487         if (cu->language == language_fortran
17488             && name
17489             && startswith (name, "character("))
17490           type = init_character_type (objfile, bits, 1, name);
17491         else
17492           type = init_integer_type (objfile, bits, 1, name);
17493         break;
17494       case DW_ATE_signed_char:
17495         if (cu->language == language_ada || cu->language == language_m2
17496             || cu->language == language_pascal
17497             || cu->language == language_fortran)
17498           type = init_character_type (objfile, bits, 0, name);
17499         else
17500           type = init_integer_type (objfile, bits, 0, name);
17501         break;
17502       case DW_ATE_unsigned_char:
17503         if (cu->language == language_ada || cu->language == language_m2
17504             || cu->language == language_pascal
17505             || cu->language == language_fortran
17506             || cu->language == language_rust)
17507           type = init_character_type (objfile, bits, 1, name);
17508         else
17509           type = init_integer_type (objfile, bits, 1, name);
17510         break;
17511       case DW_ATE_UTF:
17512         {
17513           gdbarch *arch = get_objfile_arch (objfile);
17514
17515           if (bits == 16)
17516             type = builtin_type (arch)->builtin_char16;
17517           else if (bits == 32)
17518             type = builtin_type (arch)->builtin_char32;
17519           else
17520             {
17521               complaint (&symfile_complaints,
17522                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17523                          bits);
17524               type = init_integer_type (objfile, bits, 1, name);
17525             }
17526           return set_die_type (die, type, cu);
17527         }
17528         break;
17529
17530       default:
17531         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17532                    dwarf_type_encoding_name (encoding));
17533         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17534         break;
17535     }
17536
17537   if (name && strcmp (name, "char") == 0)
17538     TYPE_NOSIGN (type) = 1;
17539
17540   return set_die_type (die, type, cu);
17541 }
17542
17543 /* Parse dwarf attribute if it's a block, reference or constant and put the
17544    resulting value of the attribute into struct bound_prop.
17545    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17546
17547 static int
17548 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17549                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17550 {
17551   struct dwarf2_property_baton *baton;
17552   struct obstack *obstack
17553     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17554
17555   if (attr == NULL || prop == NULL)
17556     return 0;
17557
17558   if (attr_form_is_block (attr))
17559     {
17560       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17561       baton->referenced_type = NULL;
17562       baton->locexpr.per_cu = cu->per_cu;
17563       baton->locexpr.size = DW_BLOCK (attr)->size;
17564       baton->locexpr.data = DW_BLOCK (attr)->data;
17565       prop->data.baton = baton;
17566       prop->kind = PROP_LOCEXPR;
17567       gdb_assert (prop->data.baton != NULL);
17568     }
17569   else if (attr_form_is_ref (attr))
17570     {
17571       struct dwarf2_cu *target_cu = cu;
17572       struct die_info *target_die;
17573       struct attribute *target_attr;
17574
17575       target_die = follow_die_ref (die, attr, &target_cu);
17576       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17577       if (target_attr == NULL)
17578         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17579                                    target_cu);
17580       if (target_attr == NULL)
17581         return 0;
17582
17583       switch (target_attr->name)
17584         {
17585           case DW_AT_location:
17586             if (attr_form_is_section_offset (target_attr))
17587               {
17588                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17589                 baton->referenced_type = die_type (target_die, target_cu);
17590                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17591                 prop->data.baton = baton;
17592                 prop->kind = PROP_LOCLIST;
17593                 gdb_assert (prop->data.baton != NULL);
17594               }
17595             else if (attr_form_is_block (target_attr))
17596               {
17597                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17598                 baton->referenced_type = die_type (target_die, target_cu);
17599                 baton->locexpr.per_cu = cu->per_cu;
17600                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17601                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17602                 prop->data.baton = baton;
17603                 prop->kind = PROP_LOCEXPR;
17604                 gdb_assert (prop->data.baton != NULL);
17605               }
17606             else
17607               {
17608                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17609                                                        "dynamic property");
17610                 return 0;
17611               }
17612             break;
17613           case DW_AT_data_member_location:
17614             {
17615               LONGEST offset;
17616
17617               if (!handle_data_member_location (target_die, target_cu,
17618                                                 &offset))
17619                 return 0;
17620
17621               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17622               baton->referenced_type = read_type_die (target_die->parent,
17623                                                       target_cu);
17624               baton->offset_info.offset = offset;
17625               baton->offset_info.type = die_type (target_die, target_cu);
17626               prop->data.baton = baton;
17627               prop->kind = PROP_ADDR_OFFSET;
17628               break;
17629             }
17630         }
17631     }
17632   else if (attr_form_is_constant (attr))
17633     {
17634       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17635       prop->kind = PROP_CONST;
17636     }
17637   else
17638     {
17639       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17640                                              dwarf2_name (die, cu));
17641       return 0;
17642     }
17643
17644   return 1;
17645 }
17646
17647 /* Read the given DW_AT_subrange DIE.  */
17648
17649 static struct type *
17650 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17651 {
17652   struct type *base_type, *orig_base_type;
17653   struct type *range_type;
17654   struct attribute *attr;
17655   struct dynamic_prop low, high;
17656   int low_default_is_valid;
17657   int high_bound_is_count = 0;
17658   const char *name;
17659   LONGEST negative_mask;
17660
17661   orig_base_type = die_type (die, cu);
17662   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17663      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17664      creating the range type, but we use the result of check_typedef
17665      when examining properties of the type.  */
17666   base_type = check_typedef (orig_base_type);
17667
17668   /* The die_type call above may have already set the type for this DIE.  */
17669   range_type = get_die_type (die, cu);
17670   if (range_type)
17671     return range_type;
17672
17673   low.kind = PROP_CONST;
17674   high.kind = PROP_CONST;
17675   high.data.const_val = 0;
17676
17677   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17678      omitting DW_AT_lower_bound.  */
17679   switch (cu->language)
17680     {
17681     case language_c:
17682     case language_cplus:
17683       low.data.const_val = 0;
17684       low_default_is_valid = 1;
17685       break;
17686     case language_fortran:
17687       low.data.const_val = 1;
17688       low_default_is_valid = 1;
17689       break;
17690     case language_d:
17691     case language_objc:
17692     case language_rust:
17693       low.data.const_val = 0;
17694       low_default_is_valid = (cu->header.version >= 4);
17695       break;
17696     case language_ada:
17697     case language_m2:
17698     case language_pascal:
17699       low.data.const_val = 1;
17700       low_default_is_valid = (cu->header.version >= 4);
17701       break;
17702     default:
17703       low.data.const_val = 0;
17704       low_default_is_valid = 0;
17705       break;
17706     }
17707
17708   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17709   if (attr)
17710     attr_to_dynamic_prop (attr, die, cu, &low);
17711   else if (!low_default_is_valid)
17712     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17713                                       "- DIE at 0x%x [in module %s]"),
17714                to_underlying (die->sect_off),
17715                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17716
17717   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17718   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17719     {
17720       attr = dwarf2_attr (die, DW_AT_count, cu);
17721       if (attr_to_dynamic_prop (attr, die, cu, &high))
17722         {
17723           /* If bounds are constant do the final calculation here.  */
17724           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17725             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17726           else
17727             high_bound_is_count = 1;
17728         }
17729     }
17730
17731   /* Dwarf-2 specifications explicitly allows to create subrange types
17732      without specifying a base type.
17733      In that case, the base type must be set to the type of
17734      the lower bound, upper bound or count, in that order, if any of these
17735      three attributes references an object that has a type.
17736      If no base type is found, the Dwarf-2 specifications say that
17737      a signed integer type of size equal to the size of an address should
17738      be used.
17739      For the following C code: `extern char gdb_int [];'
17740      GCC produces an empty range DIE.
17741      FIXME: muller/2010-05-28: Possible references to object for low bound,
17742      high bound or count are not yet handled by this code.  */
17743   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17744     {
17745       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17746       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17747       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17748       struct type *int_type = objfile_type (objfile)->builtin_int;
17749
17750       /* Test "int", "long int", and "long long int" objfile types,
17751          and select the first one having a size above or equal to the
17752          architecture address size.  */
17753       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17754         base_type = int_type;
17755       else
17756         {
17757           int_type = objfile_type (objfile)->builtin_long;
17758           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17759             base_type = int_type;
17760           else
17761             {
17762               int_type = objfile_type (objfile)->builtin_long_long;
17763               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17764                 base_type = int_type;
17765             }
17766         }
17767     }
17768
17769   /* Normally, the DWARF producers are expected to use a signed
17770      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17771      But this is unfortunately not always the case, as witnessed
17772      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17773      is used instead.  To work around that ambiguity, we treat
17774      the bounds as signed, and thus sign-extend their values, when
17775      the base type is signed.  */
17776   negative_mask =
17777     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17778   if (low.kind == PROP_CONST
17779       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17780     low.data.const_val |= negative_mask;
17781   if (high.kind == PROP_CONST
17782       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17783     high.data.const_val |= negative_mask;
17784
17785   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17786
17787   if (high_bound_is_count)
17788     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17789
17790   /* Ada expects an empty array on no boundary attributes.  */
17791   if (attr == NULL && cu->language != language_ada)
17792     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17793
17794   name = dwarf2_name (die, cu);
17795   if (name)
17796     TYPE_NAME (range_type) = name;
17797
17798   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17799   if (attr)
17800     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17801
17802   set_die_type (die, range_type, cu);
17803
17804   /* set_die_type should be already done.  */
17805   set_descriptive_type (range_type, die, cu);
17806
17807   return range_type;
17808 }
17809
17810 static struct type *
17811 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17812 {
17813   struct type *type;
17814
17815   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17816                     NULL);
17817   TYPE_NAME (type) = dwarf2_name (die, cu);
17818
17819   /* In Ada, an unspecified type is typically used when the description
17820      of the type is defered to a different unit.  When encountering
17821      such a type, we treat it as a stub, and try to resolve it later on,
17822      when needed.  */
17823   if (cu->language == language_ada)
17824     TYPE_STUB (type) = 1;
17825
17826   return set_die_type (die, type, cu);
17827 }
17828
17829 /* Read a single die and all its descendents.  Set the die's sibling
17830    field to NULL; set other fields in the die correctly, and set all
17831    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17832    location of the info_ptr after reading all of those dies.  PARENT
17833    is the parent of the die in question.  */
17834
17835 static struct die_info *
17836 read_die_and_children (const struct die_reader_specs *reader,
17837                        const gdb_byte *info_ptr,
17838                        const gdb_byte **new_info_ptr,
17839                        struct die_info *parent)
17840 {
17841   struct die_info *die;
17842   const gdb_byte *cur_ptr;
17843   int has_children;
17844
17845   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17846   if (die == NULL)
17847     {
17848       *new_info_ptr = cur_ptr;
17849       return NULL;
17850     }
17851   store_in_ref_table (die, reader->cu);
17852
17853   if (has_children)
17854     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17855   else
17856     {
17857       die->child = NULL;
17858       *new_info_ptr = cur_ptr;
17859     }
17860
17861   die->sibling = NULL;
17862   die->parent = parent;
17863   return die;
17864 }
17865
17866 /* Read a die, all of its descendents, and all of its siblings; set
17867    all of the fields of all of the dies correctly.  Arguments are as
17868    in read_die_and_children.  */
17869
17870 static struct die_info *
17871 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17872                          const gdb_byte *info_ptr,
17873                          const gdb_byte **new_info_ptr,
17874                          struct die_info *parent)
17875 {
17876   struct die_info *first_die, *last_sibling;
17877   const gdb_byte *cur_ptr;
17878
17879   cur_ptr = info_ptr;
17880   first_die = last_sibling = NULL;
17881
17882   while (1)
17883     {
17884       struct die_info *die
17885         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17886
17887       if (die == NULL)
17888         {
17889           *new_info_ptr = cur_ptr;
17890           return first_die;
17891         }
17892
17893       if (!first_die)
17894         first_die = die;
17895       else
17896         last_sibling->sibling = die;
17897
17898       last_sibling = die;
17899     }
17900 }
17901
17902 /* Read a die, all of its descendents, and all of its siblings; set
17903    all of the fields of all of the dies correctly.  Arguments are as
17904    in read_die_and_children.
17905    This the main entry point for reading a DIE and all its children.  */
17906
17907 static struct die_info *
17908 read_die_and_siblings (const struct die_reader_specs *reader,
17909                        const gdb_byte *info_ptr,
17910                        const gdb_byte **new_info_ptr,
17911                        struct die_info *parent)
17912 {
17913   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17914                                                   new_info_ptr, parent);
17915
17916   if (dwarf_die_debug)
17917     {
17918       fprintf_unfiltered (gdb_stdlog,
17919                           "Read die from %s@0x%x of %s:\n",
17920                           get_section_name (reader->die_section),
17921                           (unsigned) (info_ptr - reader->die_section->buffer),
17922                           bfd_get_filename (reader->abfd));
17923       dump_die (die, dwarf_die_debug);
17924     }
17925
17926   return die;
17927 }
17928
17929 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17930    attributes.
17931    The caller is responsible for filling in the extra attributes
17932    and updating (*DIEP)->num_attrs.
17933    Set DIEP to point to a newly allocated die with its information,
17934    except for its child, sibling, and parent fields.
17935    Set HAS_CHILDREN to tell whether the die has children or not.  */
17936
17937 static const gdb_byte *
17938 read_full_die_1 (const struct die_reader_specs *reader,
17939                  struct die_info **diep, const gdb_byte *info_ptr,
17940                  int *has_children, int num_extra_attrs)
17941 {
17942   unsigned int abbrev_number, bytes_read, i;
17943   struct abbrev_info *abbrev;
17944   struct die_info *die;
17945   struct dwarf2_cu *cu = reader->cu;
17946   bfd *abfd = reader->abfd;
17947
17948   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17949   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17950   info_ptr += bytes_read;
17951   if (!abbrev_number)
17952     {
17953       *diep = NULL;
17954       *has_children = 0;
17955       return info_ptr;
17956     }
17957
17958   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17959   if (!abbrev)
17960     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17961            abbrev_number,
17962            bfd_get_filename (abfd));
17963
17964   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17965   die->sect_off = sect_off;
17966   die->tag = abbrev->tag;
17967   die->abbrev = abbrev_number;
17968
17969   /* Make the result usable.
17970      The caller needs to update num_attrs after adding the extra
17971      attributes.  */
17972   die->num_attrs = abbrev->num_attrs;
17973
17974   for (i = 0; i < abbrev->num_attrs; ++i)
17975     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17976                                info_ptr);
17977
17978   *diep = die;
17979   *has_children = abbrev->has_children;
17980   return info_ptr;
17981 }
17982
17983 /* Read a die and all its attributes.
17984    Set DIEP to point to a newly allocated die with its information,
17985    except for its child, sibling, and parent fields.
17986    Set HAS_CHILDREN to tell whether the die has children or not.  */
17987
17988 static const gdb_byte *
17989 read_full_die (const struct die_reader_specs *reader,
17990                struct die_info **diep, const gdb_byte *info_ptr,
17991                int *has_children)
17992 {
17993   const gdb_byte *result;
17994
17995   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17996
17997   if (dwarf_die_debug)
17998     {
17999       fprintf_unfiltered (gdb_stdlog,
18000                           "Read die from %s@0x%x of %s:\n",
18001                           get_section_name (reader->die_section),
18002                           (unsigned) (info_ptr - reader->die_section->buffer),
18003                           bfd_get_filename (reader->abfd));
18004       dump_die (*diep, dwarf_die_debug);
18005     }
18006
18007   return result;
18008 }
18009 \f
18010 /* Abbreviation tables.
18011
18012    In DWARF version 2, the description of the debugging information is
18013    stored in a separate .debug_abbrev section.  Before we read any
18014    dies from a section we read in all abbreviations and install them
18015    in a hash table.  */
18016
18017 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18018
18019 struct abbrev_info *
18020 abbrev_table::alloc_abbrev ()
18021 {
18022   struct abbrev_info *abbrev;
18023
18024   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18025   memset (abbrev, 0, sizeof (struct abbrev_info));
18026
18027   return abbrev;
18028 }
18029
18030 /* Add an abbreviation to the table.  */
18031
18032 void
18033 abbrev_table::add_abbrev (unsigned int abbrev_number,
18034                           struct abbrev_info *abbrev)
18035 {
18036   unsigned int hash_number;
18037
18038   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18039   abbrev->next = m_abbrevs[hash_number];
18040   m_abbrevs[hash_number] = abbrev;
18041 }
18042
18043 /* Look up an abbrev in the table.
18044    Returns NULL if the abbrev is not found.  */
18045
18046 struct abbrev_info *
18047 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18048 {
18049   unsigned int hash_number;
18050   struct abbrev_info *abbrev;
18051
18052   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18053   abbrev = m_abbrevs[hash_number];
18054
18055   while (abbrev)
18056     {
18057       if (abbrev->number == abbrev_number)
18058         return abbrev;
18059       abbrev = abbrev->next;
18060     }
18061   return NULL;
18062 }
18063
18064 /* Read in an abbrev table.  */
18065
18066 static abbrev_table_up
18067 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18068                          struct dwarf2_section_info *section,
18069                          sect_offset sect_off)
18070 {
18071   struct objfile *objfile = dwarf2_per_objfile->objfile;
18072   bfd *abfd = get_section_bfd_owner (section);
18073   const gdb_byte *abbrev_ptr;
18074   struct abbrev_info *cur_abbrev;
18075   unsigned int abbrev_number, bytes_read, abbrev_name;
18076   unsigned int abbrev_form;
18077   struct attr_abbrev *cur_attrs;
18078   unsigned int allocated_attrs;
18079
18080   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18081
18082   dwarf2_read_section (objfile, section);
18083   abbrev_ptr = section->buffer + to_underlying (sect_off);
18084   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18085   abbrev_ptr += bytes_read;
18086
18087   allocated_attrs = ATTR_ALLOC_CHUNK;
18088   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18089
18090   /* Loop until we reach an abbrev number of 0.  */
18091   while (abbrev_number)
18092     {
18093       cur_abbrev = abbrev_table->alloc_abbrev ();
18094
18095       /* read in abbrev header */
18096       cur_abbrev->number = abbrev_number;
18097       cur_abbrev->tag
18098         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18099       abbrev_ptr += bytes_read;
18100       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18101       abbrev_ptr += 1;
18102
18103       /* now read in declarations */
18104       for (;;)
18105         {
18106           LONGEST implicit_const;
18107
18108           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18109           abbrev_ptr += bytes_read;
18110           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18111           abbrev_ptr += bytes_read;
18112           if (abbrev_form == DW_FORM_implicit_const)
18113             {
18114               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18115                                                    &bytes_read);
18116               abbrev_ptr += bytes_read;
18117             }
18118           else
18119             {
18120               /* Initialize it due to a false compiler warning.  */
18121               implicit_const = -1;
18122             }
18123
18124           if (abbrev_name == 0)
18125             break;
18126
18127           if (cur_abbrev->num_attrs == allocated_attrs)
18128             {
18129               allocated_attrs += ATTR_ALLOC_CHUNK;
18130               cur_attrs
18131                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18132             }
18133
18134           cur_attrs[cur_abbrev->num_attrs].name
18135             = (enum dwarf_attribute) abbrev_name;
18136           cur_attrs[cur_abbrev->num_attrs].form
18137             = (enum dwarf_form) abbrev_form;
18138           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18139           ++cur_abbrev->num_attrs;
18140         }
18141
18142       cur_abbrev->attrs =
18143         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18144                    cur_abbrev->num_attrs);
18145       memcpy (cur_abbrev->attrs, cur_attrs,
18146               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18147
18148       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18149
18150       /* Get next abbreviation.
18151          Under Irix6 the abbreviations for a compilation unit are not
18152          always properly terminated with an abbrev number of 0.
18153          Exit loop if we encounter an abbreviation which we have
18154          already read (which means we are about to read the abbreviations
18155          for the next compile unit) or if the end of the abbreviation
18156          table is reached.  */
18157       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18158         break;
18159       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18160       abbrev_ptr += bytes_read;
18161       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18162         break;
18163     }
18164
18165   xfree (cur_attrs);
18166   return abbrev_table;
18167 }
18168
18169 /* Returns nonzero if TAG represents a type that we might generate a partial
18170    symbol for.  */
18171
18172 static int
18173 is_type_tag_for_partial (int tag)
18174 {
18175   switch (tag)
18176     {
18177 #if 0
18178     /* Some types that would be reasonable to generate partial symbols for,
18179        that we don't at present.  */
18180     case DW_TAG_array_type:
18181     case DW_TAG_file_type:
18182     case DW_TAG_ptr_to_member_type:
18183     case DW_TAG_set_type:
18184     case DW_TAG_string_type:
18185     case DW_TAG_subroutine_type:
18186 #endif
18187     case DW_TAG_base_type:
18188     case DW_TAG_class_type:
18189     case DW_TAG_interface_type:
18190     case DW_TAG_enumeration_type:
18191     case DW_TAG_structure_type:
18192     case DW_TAG_subrange_type:
18193     case DW_TAG_typedef:
18194     case DW_TAG_union_type:
18195       return 1;
18196     default:
18197       return 0;
18198     }
18199 }
18200
18201 /* Load all DIEs that are interesting for partial symbols into memory.  */
18202
18203 static struct partial_die_info *
18204 load_partial_dies (const struct die_reader_specs *reader,
18205                    const gdb_byte *info_ptr, int building_psymtab)
18206 {
18207   struct dwarf2_cu *cu = reader->cu;
18208   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18209   struct partial_die_info *part_die;
18210   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18211   unsigned int bytes_read;
18212   unsigned int load_all = 0;
18213   int nesting_level = 1;
18214
18215   parent_die = NULL;
18216   last_die = NULL;
18217
18218   gdb_assert (cu->per_cu != NULL);
18219   if (cu->per_cu->load_all_dies)
18220     load_all = 1;
18221
18222   cu->partial_dies
18223     = htab_create_alloc_ex (cu->header.length / 12,
18224                             partial_die_hash,
18225                             partial_die_eq,
18226                             NULL,
18227                             &cu->comp_unit_obstack,
18228                             hashtab_obstack_allocate,
18229                             dummy_obstack_deallocate);
18230
18231   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18232
18233   while (1)
18234     {
18235       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18236
18237       /* A NULL abbrev means the end of a series of children.  */
18238       if (abbrev == NULL)
18239         {
18240           if (--nesting_level == 0)
18241             {
18242               /* PART_DIE was probably the last thing allocated on the
18243                  comp_unit_obstack, so we could call obstack_free
18244                  here.  We don't do that because the waste is small,
18245                  and will be cleaned up when we're done with this
18246                  compilation unit.  This way, we're also more robust
18247                  against other users of the comp_unit_obstack.  */
18248               return first_die;
18249             }
18250           info_ptr += bytes_read;
18251           last_die = parent_die;
18252           parent_die = parent_die->die_parent;
18253           continue;
18254         }
18255
18256       /* Check for template arguments.  We never save these; if
18257          they're seen, we just mark the parent, and go on our way.  */
18258       if (parent_die != NULL
18259           && cu->language == language_cplus
18260           && (abbrev->tag == DW_TAG_template_type_param
18261               || abbrev->tag == DW_TAG_template_value_param))
18262         {
18263           parent_die->has_template_arguments = 1;
18264
18265           if (!load_all)
18266             {
18267               /* We don't need a partial DIE for the template argument.  */
18268               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18269               continue;
18270             }
18271         }
18272
18273       /* We only recurse into c++ subprograms looking for template arguments.
18274          Skip their other children.  */
18275       if (!load_all
18276           && cu->language == language_cplus
18277           && parent_die != NULL
18278           && parent_die->tag == DW_TAG_subprogram)
18279         {
18280           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18281           continue;
18282         }
18283
18284       /* Check whether this DIE is interesting enough to save.  Normally
18285          we would not be interested in members here, but there may be
18286          later variables referencing them via DW_AT_specification (for
18287          static members).  */
18288       if (!load_all
18289           && !is_type_tag_for_partial (abbrev->tag)
18290           && abbrev->tag != DW_TAG_constant
18291           && abbrev->tag != DW_TAG_enumerator
18292           && abbrev->tag != DW_TAG_subprogram
18293           && abbrev->tag != DW_TAG_inlined_subroutine
18294           && abbrev->tag != DW_TAG_lexical_block
18295           && abbrev->tag != DW_TAG_variable
18296           && abbrev->tag != DW_TAG_namespace
18297           && abbrev->tag != DW_TAG_module
18298           && abbrev->tag != DW_TAG_member
18299           && abbrev->tag != DW_TAG_imported_unit
18300           && abbrev->tag != DW_TAG_imported_declaration)
18301         {
18302           /* Otherwise we skip to the next sibling, if any.  */
18303           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18304           continue;
18305         }
18306
18307       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18308                                    info_ptr);
18309
18310       /* This two-pass algorithm for processing partial symbols has a
18311          high cost in cache pressure.  Thus, handle some simple cases
18312          here which cover the majority of C partial symbols.  DIEs
18313          which neither have specification tags in them, nor could have
18314          specification tags elsewhere pointing at them, can simply be
18315          processed and discarded.
18316
18317          This segment is also optional; scan_partial_symbols and
18318          add_partial_symbol will handle these DIEs if we chain
18319          them in normally.  When compilers which do not emit large
18320          quantities of duplicate debug information are more common,
18321          this code can probably be removed.  */
18322
18323       /* Any complete simple types at the top level (pretty much all
18324          of them, for a language without namespaces), can be processed
18325          directly.  */
18326       if (parent_die == NULL
18327           && part_die->has_specification == 0
18328           && part_die->is_declaration == 0
18329           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18330               || part_die->tag == DW_TAG_base_type
18331               || part_die->tag == DW_TAG_subrange_type))
18332         {
18333           if (building_psymtab && part_die->name != NULL)
18334             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18335                                  VAR_DOMAIN, LOC_TYPEDEF,
18336                                  &objfile->static_psymbols,
18337                                  0, cu->language, objfile);
18338           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18339           continue;
18340         }
18341
18342       /* The exception for DW_TAG_typedef with has_children above is
18343          a workaround of GCC PR debug/47510.  In the case of this complaint
18344          type_name_no_tag_or_error will error on such types later.
18345
18346          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18347          it could not find the child DIEs referenced later, this is checked
18348          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18349
18350       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18351         complaint (&symfile_complaints,
18352                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18353                      "- DIE at 0x%x [in module %s]"),
18354                    to_underlying (part_die->sect_off), objfile_name (objfile));
18355
18356       /* If we're at the second level, and we're an enumerator, and
18357          our parent has no specification (meaning possibly lives in a
18358          namespace elsewhere), then we can add the partial symbol now
18359          instead of queueing it.  */
18360       if (part_die->tag == DW_TAG_enumerator
18361           && parent_die != NULL
18362           && parent_die->die_parent == NULL
18363           && parent_die->tag == DW_TAG_enumeration_type
18364           && parent_die->has_specification == 0)
18365         {
18366           if (part_die->name == NULL)
18367             complaint (&symfile_complaints,
18368                        _("malformed enumerator DIE ignored"));
18369           else if (building_psymtab)
18370             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18371                                  VAR_DOMAIN, LOC_CONST,
18372                                  cu->language == language_cplus
18373                                  ? &objfile->global_psymbols
18374                                  : &objfile->static_psymbols,
18375                                  0, cu->language, objfile);
18376
18377           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18378           continue;
18379         }
18380
18381       /* We'll save this DIE so link it in.  */
18382       part_die->die_parent = parent_die;
18383       part_die->die_sibling = NULL;
18384       part_die->die_child = NULL;
18385
18386       if (last_die && last_die == parent_die)
18387         last_die->die_child = part_die;
18388       else if (last_die)
18389         last_die->die_sibling = part_die;
18390
18391       last_die = part_die;
18392
18393       if (first_die == NULL)
18394         first_die = part_die;
18395
18396       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18397          find interesting need to be in the hash table, because we
18398          also have the parent/sibling/child chains; only those that we
18399          might refer to by offset later during partial symbol reading.
18400
18401          For now this means things that might have be the target of a
18402          DW_AT_specification, DW_AT_abstract_origin, or
18403          DW_AT_extension.  DW_AT_extension will refer only to
18404          namespaces; DW_AT_abstract_origin refers to functions (and
18405          many things under the function DIE, but we do not recurse
18406          into function DIEs during partial symbol reading) and
18407          possibly variables as well; DW_AT_specification refers to
18408          declarations.  Declarations ought to have the DW_AT_declaration
18409          flag.  It happens that GCC forgets to put it in sometimes, but
18410          only for functions, not for types.
18411
18412          Adding more things than necessary to the hash table is harmless
18413          except for the performance cost.  Adding too few will result in
18414          wasted time in find_partial_die, when we reread the compilation
18415          unit with load_all_dies set.  */
18416
18417       if (load_all
18418           || abbrev->tag == DW_TAG_constant
18419           || abbrev->tag == DW_TAG_subprogram
18420           || abbrev->tag == DW_TAG_variable
18421           || abbrev->tag == DW_TAG_namespace
18422           || part_die->is_declaration)
18423         {
18424           void **slot;
18425
18426           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18427                                            to_underlying (part_die->sect_off),
18428                                            INSERT);
18429           *slot = part_die;
18430         }
18431
18432       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18433
18434       /* For some DIEs we want to follow their children (if any).  For C
18435          we have no reason to follow the children of structures; for other
18436          languages we have to, so that we can get at method physnames
18437          to infer fully qualified class names, for DW_AT_specification,
18438          and for C++ template arguments.  For C++, we also look one level
18439          inside functions to find template arguments (if the name of the
18440          function does not already contain the template arguments).
18441
18442          For Ada, we need to scan the children of subprograms and lexical
18443          blocks as well because Ada allows the definition of nested
18444          entities that could be interesting for the debugger, such as
18445          nested subprograms for instance.  */
18446       if (last_die->has_children
18447           && (load_all
18448               || last_die->tag == DW_TAG_namespace
18449               || last_die->tag == DW_TAG_module
18450               || last_die->tag == DW_TAG_enumeration_type
18451               || (cu->language == language_cplus
18452                   && last_die->tag == DW_TAG_subprogram
18453                   && (last_die->name == NULL
18454                       || strchr (last_die->name, '<') == NULL))
18455               || (cu->language != language_c
18456                   && (last_die->tag == DW_TAG_class_type
18457                       || last_die->tag == DW_TAG_interface_type
18458                       || last_die->tag == DW_TAG_structure_type
18459                       || last_die->tag == DW_TAG_union_type))
18460               || (cu->language == language_ada
18461                   && (last_die->tag == DW_TAG_subprogram
18462                       || last_die->tag == DW_TAG_lexical_block))))
18463         {
18464           nesting_level++;
18465           parent_die = last_die;
18466           continue;
18467         }
18468
18469       /* Otherwise we skip to the next sibling, if any.  */
18470       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18471
18472       /* Back to the top, do it again.  */
18473     }
18474 }
18475
18476 /* Read a minimal amount of information into the minimal die structure.  */
18477
18478 static const gdb_byte *
18479 read_partial_die (const struct die_reader_specs *reader,
18480                   struct partial_die_info *part_die,
18481                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18482                   const gdb_byte *info_ptr)
18483 {
18484   struct dwarf2_cu *cu = reader->cu;
18485   struct dwarf2_per_objfile *dwarf2_per_objfile
18486     = cu->per_cu->dwarf2_per_objfile;
18487   struct objfile *objfile = dwarf2_per_objfile->objfile;
18488   const gdb_byte *buffer = reader->buffer;
18489   unsigned int i;
18490   struct attribute attr;
18491   int has_low_pc_attr = 0;
18492   int has_high_pc_attr = 0;
18493   int high_pc_relative = 0;
18494
18495   memset (part_die, 0, sizeof (struct partial_die_info));
18496
18497   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18498
18499   info_ptr += abbrev_len;
18500
18501   if (abbrev == NULL)
18502     return info_ptr;
18503
18504   part_die->tag = abbrev->tag;
18505   part_die->has_children = abbrev->has_children;
18506
18507   for (i = 0; i < abbrev->num_attrs; ++i)
18508     {
18509       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18510
18511       /* Store the data if it is of an attribute we want to keep in a
18512          partial symbol table.  */
18513       switch (attr.name)
18514         {
18515         case DW_AT_name:
18516           switch (part_die->tag)
18517             {
18518             case DW_TAG_compile_unit:
18519             case DW_TAG_partial_unit:
18520             case DW_TAG_type_unit:
18521               /* Compilation units have a DW_AT_name that is a filename, not
18522                  a source language identifier.  */
18523             case DW_TAG_enumeration_type:
18524             case DW_TAG_enumerator:
18525               /* These tags always have simple identifiers already; no need
18526                  to canonicalize them.  */
18527               part_die->name = DW_STRING (&attr);
18528               break;
18529             default:
18530               part_die->name
18531                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18532                                             &objfile->per_bfd->storage_obstack);
18533               break;
18534             }
18535           break;
18536         case DW_AT_linkage_name:
18537         case DW_AT_MIPS_linkage_name:
18538           /* Note that both forms of linkage name might appear.  We
18539              assume they will be the same, and we only store the last
18540              one we see.  */
18541           if (cu->language == language_ada)
18542             part_die->name = DW_STRING (&attr);
18543           part_die->linkage_name = DW_STRING (&attr);
18544           break;
18545         case DW_AT_low_pc:
18546           has_low_pc_attr = 1;
18547           part_die->lowpc = attr_value_as_address (&attr);
18548           break;
18549         case DW_AT_high_pc:
18550           has_high_pc_attr = 1;
18551           part_die->highpc = attr_value_as_address (&attr);
18552           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18553                 high_pc_relative = 1;
18554           break;
18555         case DW_AT_location:
18556           /* Support the .debug_loc offsets.  */
18557           if (attr_form_is_block (&attr))
18558             {
18559                part_die->d.locdesc = DW_BLOCK (&attr);
18560             }
18561           else if (attr_form_is_section_offset (&attr))
18562             {
18563               dwarf2_complex_location_expr_complaint ();
18564             }
18565           else
18566             {
18567               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18568                                                      "partial symbol information");
18569             }
18570           break;
18571         case DW_AT_external:
18572           part_die->is_external = DW_UNSND (&attr);
18573           break;
18574         case DW_AT_declaration:
18575           part_die->is_declaration = DW_UNSND (&attr);
18576           break;
18577         case DW_AT_type:
18578           part_die->has_type = 1;
18579           break;
18580         case DW_AT_abstract_origin:
18581         case DW_AT_specification:
18582         case DW_AT_extension:
18583           part_die->has_specification = 1;
18584           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18585           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18586                                    || cu->per_cu->is_dwz);
18587           break;
18588         case DW_AT_sibling:
18589           /* Ignore absolute siblings, they might point outside of
18590              the current compile unit.  */
18591           if (attr.form == DW_FORM_ref_addr)
18592             complaint (&symfile_complaints,
18593                        _("ignoring absolute DW_AT_sibling"));
18594           else
18595             {
18596               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18597               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18598
18599               if (sibling_ptr < info_ptr)
18600                 complaint (&symfile_complaints,
18601                            _("DW_AT_sibling points backwards"));
18602               else if (sibling_ptr > reader->buffer_end)
18603                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18604               else
18605                 part_die->sibling = sibling_ptr;
18606             }
18607           break;
18608         case DW_AT_byte_size:
18609           part_die->has_byte_size = 1;
18610           break;
18611         case DW_AT_const_value:
18612           part_die->has_const_value = 1;
18613           break;
18614         case DW_AT_calling_convention:
18615           /* DWARF doesn't provide a way to identify a program's source-level
18616              entry point.  DW_AT_calling_convention attributes are only meant
18617              to describe functions' calling conventions.
18618
18619              However, because it's a necessary piece of information in
18620              Fortran, and before DWARF 4 DW_CC_program was the only
18621              piece of debugging information whose definition refers to
18622              a 'main program' at all, several compilers marked Fortran
18623              main programs with DW_CC_program --- even when those
18624              functions use the standard calling conventions.
18625
18626              Although DWARF now specifies a way to provide this
18627              information, we support this practice for backward
18628              compatibility.  */
18629           if (DW_UNSND (&attr) == DW_CC_program
18630               && cu->language == language_fortran)
18631             part_die->main_subprogram = 1;
18632           break;
18633         case DW_AT_inline:
18634           if (DW_UNSND (&attr) == DW_INL_inlined
18635               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18636             part_die->may_be_inlined = 1;
18637           break;
18638
18639         case DW_AT_import:
18640           if (part_die->tag == DW_TAG_imported_unit)
18641             {
18642               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18643               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18644                                   || cu->per_cu->is_dwz);
18645             }
18646           break;
18647
18648         case DW_AT_main_subprogram:
18649           part_die->main_subprogram = DW_UNSND (&attr);
18650           break;
18651
18652         default:
18653           break;
18654         }
18655     }
18656
18657   if (high_pc_relative)
18658     part_die->highpc += part_die->lowpc;
18659
18660   if (has_low_pc_attr && has_high_pc_attr)
18661     {
18662       /* When using the GNU linker, .gnu.linkonce. sections are used to
18663          eliminate duplicate copies of functions and vtables and such.
18664          The linker will arbitrarily choose one and discard the others.
18665          The AT_*_pc values for such functions refer to local labels in
18666          these sections.  If the section from that file was discarded, the
18667          labels are not in the output, so the relocs get a value of 0.
18668          If this is a discarded function, mark the pc bounds as invalid,
18669          so that GDB will ignore it.  */
18670       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18671         {
18672           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18673
18674           complaint (&symfile_complaints,
18675                      _("DW_AT_low_pc %s is zero "
18676                        "for DIE at 0x%x [in module %s]"),
18677                      paddress (gdbarch, part_die->lowpc),
18678                      to_underlying (part_die->sect_off), objfile_name (objfile));
18679         }
18680       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18681       else if (part_die->lowpc >= part_die->highpc)
18682         {
18683           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18684
18685           complaint (&symfile_complaints,
18686                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18687                        "for DIE at 0x%x [in module %s]"),
18688                      paddress (gdbarch, part_die->lowpc),
18689                      paddress (gdbarch, part_die->highpc),
18690                      to_underlying (part_die->sect_off),
18691                      objfile_name (objfile));
18692         }
18693       else
18694         part_die->has_pc_info = 1;
18695     }
18696
18697   return info_ptr;
18698 }
18699
18700 /* Find a cached partial DIE at OFFSET in CU.  */
18701
18702 static struct partial_die_info *
18703 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18704 {
18705   struct partial_die_info *lookup_die = NULL;
18706   struct partial_die_info part_die;
18707
18708   part_die.sect_off = sect_off;
18709   lookup_die = ((struct partial_die_info *)
18710                 htab_find_with_hash (cu->partial_dies, &part_die,
18711                                      to_underlying (sect_off)));
18712
18713   return lookup_die;
18714 }
18715
18716 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18717    except in the case of .debug_types DIEs which do not reference
18718    outside their CU (they do however referencing other types via
18719    DW_FORM_ref_sig8).  */
18720
18721 static struct partial_die_info *
18722 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18723 {
18724   struct dwarf2_per_objfile *dwarf2_per_objfile
18725     = cu->per_cu->dwarf2_per_objfile;
18726   struct objfile *objfile = dwarf2_per_objfile->objfile;
18727   struct dwarf2_per_cu_data *per_cu = NULL;
18728   struct partial_die_info *pd = NULL;
18729
18730   if (offset_in_dwz == cu->per_cu->is_dwz
18731       && offset_in_cu_p (&cu->header, sect_off))
18732     {
18733       pd = find_partial_die_in_comp_unit (sect_off, cu);
18734       if (pd != NULL)
18735         return pd;
18736       /* We missed recording what we needed.
18737          Load all dies and try again.  */
18738       per_cu = cu->per_cu;
18739     }
18740   else
18741     {
18742       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18743       if (cu->per_cu->is_debug_types)
18744         {
18745           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18746                    " external reference to offset 0x%x [in module %s].\n"),
18747                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18748                  bfd_get_filename (objfile->obfd));
18749         }
18750       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18751                                                  dwarf2_per_objfile);
18752
18753       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18754         load_partial_comp_unit (per_cu);
18755
18756       per_cu->cu->last_used = 0;
18757       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18758     }
18759
18760   /* If we didn't find it, and not all dies have been loaded,
18761      load them all and try again.  */
18762
18763   if (pd == NULL && per_cu->load_all_dies == 0)
18764     {
18765       per_cu->load_all_dies = 1;
18766
18767       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18768          THIS_CU->cu may already be in use.  So we can't just free it and
18769          replace its DIEs with the ones we read in.  Instead, we leave those
18770          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18771          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18772          set.  */
18773       load_partial_comp_unit (per_cu);
18774
18775       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18776     }
18777
18778   if (pd == NULL)
18779     internal_error (__FILE__, __LINE__,
18780                     _("could not find partial DIE 0x%x "
18781                       "in cache [from module %s]\n"),
18782                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18783   return pd;
18784 }
18785
18786 /* See if we can figure out if the class lives in a namespace.  We do
18787    this by looking for a member function; its demangled name will
18788    contain namespace info, if there is any.  */
18789
18790 static void
18791 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18792                                   struct dwarf2_cu *cu)
18793 {
18794   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18795      what template types look like, because the demangler
18796      frequently doesn't give the same name as the debug info.  We
18797      could fix this by only using the demangled name to get the
18798      prefix (but see comment in read_structure_type).  */
18799
18800   struct partial_die_info *real_pdi;
18801   struct partial_die_info *child_pdi;
18802
18803   /* If this DIE (this DIE's specification, if any) has a parent, then
18804      we should not do this.  We'll prepend the parent's fully qualified
18805      name when we create the partial symbol.  */
18806
18807   real_pdi = struct_pdi;
18808   while (real_pdi->has_specification)
18809     real_pdi = find_partial_die (real_pdi->spec_offset,
18810                                  real_pdi->spec_is_dwz, cu);
18811
18812   if (real_pdi->die_parent != NULL)
18813     return;
18814
18815   for (child_pdi = struct_pdi->die_child;
18816        child_pdi != NULL;
18817        child_pdi = child_pdi->die_sibling)
18818     {
18819       if (child_pdi->tag == DW_TAG_subprogram
18820           && child_pdi->linkage_name != NULL)
18821         {
18822           char *actual_class_name
18823             = language_class_name_from_physname (cu->language_defn,
18824                                                  child_pdi->linkage_name);
18825           if (actual_class_name != NULL)
18826             {
18827               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18828               struct_pdi->name
18829                 = ((const char *)
18830                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18831                                   actual_class_name,
18832                                   strlen (actual_class_name)));
18833               xfree (actual_class_name);
18834             }
18835           break;
18836         }
18837     }
18838 }
18839
18840 /* Adjust PART_DIE before generating a symbol for it.  This function
18841    may set the is_external flag or change the DIE's name.  */
18842
18843 static void
18844 fixup_partial_die (struct partial_die_info *part_die,
18845                    struct dwarf2_cu *cu)
18846 {
18847   /* Once we've fixed up a die, there's no point in doing so again.
18848      This also avoids a memory leak if we were to call
18849      guess_partial_die_structure_name multiple times.  */
18850   if (part_die->fixup_called)
18851     return;
18852
18853   /* If we found a reference attribute and the DIE has no name, try
18854      to find a name in the referred to DIE.  */
18855
18856   if (part_die->name == NULL && part_die->has_specification)
18857     {
18858       struct partial_die_info *spec_die;
18859
18860       spec_die = find_partial_die (part_die->spec_offset,
18861                                    part_die->spec_is_dwz, cu);
18862
18863       fixup_partial_die (spec_die, cu);
18864
18865       if (spec_die->name)
18866         {
18867           part_die->name = spec_die->name;
18868
18869           /* Copy DW_AT_external attribute if it is set.  */
18870           if (spec_die->is_external)
18871             part_die->is_external = spec_die->is_external;
18872         }
18873     }
18874
18875   /* Set default names for some unnamed DIEs.  */
18876
18877   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18878     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18879
18880   /* If there is no parent die to provide a namespace, and there are
18881      children, see if we can determine the namespace from their linkage
18882      name.  */
18883   if (cu->language == language_cplus
18884       && !VEC_empty (dwarf2_section_info_def,
18885                      cu->per_cu->dwarf2_per_objfile->types)
18886       && part_die->die_parent == NULL
18887       && part_die->has_children
18888       && (part_die->tag == DW_TAG_class_type
18889           || part_die->tag == DW_TAG_structure_type
18890           || part_die->tag == DW_TAG_union_type))
18891     guess_partial_die_structure_name (part_die, cu);
18892
18893   /* GCC might emit a nameless struct or union that has a linkage
18894      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18895   if (part_die->name == NULL
18896       && (part_die->tag == DW_TAG_class_type
18897           || part_die->tag == DW_TAG_interface_type
18898           || part_die->tag == DW_TAG_structure_type
18899           || part_die->tag == DW_TAG_union_type)
18900       && part_die->linkage_name != NULL)
18901     {
18902       char *demangled;
18903
18904       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18905       if (demangled)
18906         {
18907           const char *base;
18908
18909           /* Strip any leading namespaces/classes, keep only the base name.
18910              DW_AT_name for named DIEs does not contain the prefixes.  */
18911           base = strrchr (demangled, ':');
18912           if (base && base > demangled && base[-1] == ':')
18913             base++;
18914           else
18915             base = demangled;
18916
18917           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18918           part_die->name
18919             = ((const char *)
18920                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18921                               base, strlen (base)));
18922           xfree (demangled);
18923         }
18924     }
18925
18926   part_die->fixup_called = 1;
18927 }
18928
18929 /* Read an attribute value described by an attribute form.  */
18930
18931 static const gdb_byte *
18932 read_attribute_value (const struct die_reader_specs *reader,
18933                       struct attribute *attr, unsigned form,
18934                       LONGEST implicit_const, const gdb_byte *info_ptr)
18935 {
18936   struct dwarf2_cu *cu = reader->cu;
18937   struct dwarf2_per_objfile *dwarf2_per_objfile
18938     = cu->per_cu->dwarf2_per_objfile;
18939   struct objfile *objfile = dwarf2_per_objfile->objfile;
18940   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18941   bfd *abfd = reader->abfd;
18942   struct comp_unit_head *cu_header = &cu->header;
18943   unsigned int bytes_read;
18944   struct dwarf_block *blk;
18945
18946   attr->form = (enum dwarf_form) form;
18947   switch (form)
18948     {
18949     case DW_FORM_ref_addr:
18950       if (cu->header.version == 2)
18951         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18952       else
18953         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18954                                        &cu->header, &bytes_read);
18955       info_ptr += bytes_read;
18956       break;
18957     case DW_FORM_GNU_ref_alt:
18958       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18959       info_ptr += bytes_read;
18960       break;
18961     case DW_FORM_addr:
18962       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18963       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18964       info_ptr += bytes_read;
18965       break;
18966     case DW_FORM_block2:
18967       blk = dwarf_alloc_block (cu);
18968       blk->size = read_2_bytes (abfd, info_ptr);
18969       info_ptr += 2;
18970       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18971       info_ptr += blk->size;
18972       DW_BLOCK (attr) = blk;
18973       break;
18974     case DW_FORM_block4:
18975       blk = dwarf_alloc_block (cu);
18976       blk->size = read_4_bytes (abfd, info_ptr);
18977       info_ptr += 4;
18978       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18979       info_ptr += blk->size;
18980       DW_BLOCK (attr) = blk;
18981       break;
18982     case DW_FORM_data2:
18983       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18984       info_ptr += 2;
18985       break;
18986     case DW_FORM_data4:
18987       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18988       info_ptr += 4;
18989       break;
18990     case DW_FORM_data8:
18991       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18992       info_ptr += 8;
18993       break;
18994     case DW_FORM_data16:
18995       blk = dwarf_alloc_block (cu);
18996       blk->size = 16;
18997       blk->data = read_n_bytes (abfd, info_ptr, 16);
18998       info_ptr += 16;
18999       DW_BLOCK (attr) = blk;
19000       break;
19001     case DW_FORM_sec_offset:
19002       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19003       info_ptr += bytes_read;
19004       break;
19005     case DW_FORM_string:
19006       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19007       DW_STRING_IS_CANONICAL (attr) = 0;
19008       info_ptr += bytes_read;
19009       break;
19010     case DW_FORM_strp:
19011       if (!cu->per_cu->is_dwz)
19012         {
19013           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19014                                                    abfd, info_ptr, cu_header,
19015                                                    &bytes_read);
19016           DW_STRING_IS_CANONICAL (attr) = 0;
19017           info_ptr += bytes_read;
19018           break;
19019         }
19020       /* FALLTHROUGH */
19021     case DW_FORM_line_strp:
19022       if (!cu->per_cu->is_dwz)
19023         {
19024           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19025                                                         abfd, info_ptr,
19026                                                         cu_header, &bytes_read);
19027           DW_STRING_IS_CANONICAL (attr) = 0;
19028           info_ptr += bytes_read;
19029           break;
19030         }
19031       /* FALLTHROUGH */
19032     case DW_FORM_GNU_strp_alt:
19033       {
19034         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19035         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19036                                           &bytes_read);
19037
19038         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19039                                                           dwz, str_offset);
19040         DW_STRING_IS_CANONICAL (attr) = 0;
19041         info_ptr += bytes_read;
19042       }
19043       break;
19044     case DW_FORM_exprloc:
19045     case DW_FORM_block:
19046       blk = dwarf_alloc_block (cu);
19047       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19048       info_ptr += bytes_read;
19049       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19050       info_ptr += blk->size;
19051       DW_BLOCK (attr) = blk;
19052       break;
19053     case DW_FORM_block1:
19054       blk = dwarf_alloc_block (cu);
19055       blk->size = read_1_byte (abfd, info_ptr);
19056       info_ptr += 1;
19057       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19058       info_ptr += blk->size;
19059       DW_BLOCK (attr) = blk;
19060       break;
19061     case DW_FORM_data1:
19062       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19063       info_ptr += 1;
19064       break;
19065     case DW_FORM_flag:
19066       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19067       info_ptr += 1;
19068       break;
19069     case DW_FORM_flag_present:
19070       DW_UNSND (attr) = 1;
19071       break;
19072     case DW_FORM_sdata:
19073       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19074       info_ptr += bytes_read;
19075       break;
19076     case DW_FORM_udata:
19077       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19078       info_ptr += bytes_read;
19079       break;
19080     case DW_FORM_ref1:
19081       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19082                          + read_1_byte (abfd, info_ptr));
19083       info_ptr += 1;
19084       break;
19085     case DW_FORM_ref2:
19086       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19087                          + read_2_bytes (abfd, info_ptr));
19088       info_ptr += 2;
19089       break;
19090     case DW_FORM_ref4:
19091       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19092                          + read_4_bytes (abfd, info_ptr));
19093       info_ptr += 4;
19094       break;
19095     case DW_FORM_ref8:
19096       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19097                          + read_8_bytes (abfd, info_ptr));
19098       info_ptr += 8;
19099       break;
19100     case DW_FORM_ref_sig8:
19101       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19102       info_ptr += 8;
19103       break;
19104     case DW_FORM_ref_udata:
19105       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19106                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19107       info_ptr += bytes_read;
19108       break;
19109     case DW_FORM_indirect:
19110       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19111       info_ptr += bytes_read;
19112       if (form == DW_FORM_implicit_const)
19113         {
19114           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19115           info_ptr += bytes_read;
19116         }
19117       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19118                                        info_ptr);
19119       break;
19120     case DW_FORM_implicit_const:
19121       DW_SND (attr) = implicit_const;
19122       break;
19123     case DW_FORM_GNU_addr_index:
19124       if (reader->dwo_file == NULL)
19125         {
19126           /* For now flag a hard error.
19127              Later we can turn this into a complaint.  */
19128           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19129                  dwarf_form_name (form),
19130                  bfd_get_filename (abfd));
19131         }
19132       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19133       info_ptr += bytes_read;
19134       break;
19135     case DW_FORM_GNU_str_index:
19136       if (reader->dwo_file == NULL)
19137         {
19138           /* For now flag a hard error.
19139              Later we can turn this into a complaint if warranted.  */
19140           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19141                  dwarf_form_name (form),
19142                  bfd_get_filename (abfd));
19143         }
19144       {
19145         ULONGEST str_index =
19146           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19147
19148         DW_STRING (attr) = read_str_index (reader, str_index);
19149         DW_STRING_IS_CANONICAL (attr) = 0;
19150         info_ptr += bytes_read;
19151       }
19152       break;
19153     default:
19154       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19155              dwarf_form_name (form),
19156              bfd_get_filename (abfd));
19157     }
19158
19159   /* Super hack.  */
19160   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19161     attr->form = DW_FORM_GNU_ref_alt;
19162
19163   /* We have seen instances where the compiler tried to emit a byte
19164      size attribute of -1 which ended up being encoded as an unsigned
19165      0xffffffff.  Although 0xffffffff is technically a valid size value,
19166      an object of this size seems pretty unlikely so we can relatively
19167      safely treat these cases as if the size attribute was invalid and
19168      treat them as zero by default.  */
19169   if (attr->name == DW_AT_byte_size
19170       && form == DW_FORM_data4
19171       && DW_UNSND (attr) >= 0xffffffff)
19172     {
19173       complaint
19174         (&symfile_complaints,
19175          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19176          hex_string (DW_UNSND (attr)));
19177       DW_UNSND (attr) = 0;
19178     }
19179
19180   return info_ptr;
19181 }
19182
19183 /* Read an attribute described by an abbreviated attribute.  */
19184
19185 static const gdb_byte *
19186 read_attribute (const struct die_reader_specs *reader,
19187                 struct attribute *attr, struct attr_abbrev *abbrev,
19188                 const gdb_byte *info_ptr)
19189 {
19190   attr->name = abbrev->name;
19191   return read_attribute_value (reader, attr, abbrev->form,
19192                                abbrev->implicit_const, info_ptr);
19193 }
19194
19195 /* Read dwarf information from a buffer.  */
19196
19197 static unsigned int
19198 read_1_byte (bfd *abfd, const gdb_byte *buf)
19199 {
19200   return bfd_get_8 (abfd, buf);
19201 }
19202
19203 static int
19204 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19205 {
19206   return bfd_get_signed_8 (abfd, buf);
19207 }
19208
19209 static unsigned int
19210 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19211 {
19212   return bfd_get_16 (abfd, buf);
19213 }
19214
19215 static int
19216 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19217 {
19218   return bfd_get_signed_16 (abfd, buf);
19219 }
19220
19221 static unsigned int
19222 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19223 {
19224   return bfd_get_32 (abfd, buf);
19225 }
19226
19227 static int
19228 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19229 {
19230   return bfd_get_signed_32 (abfd, buf);
19231 }
19232
19233 static ULONGEST
19234 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19235 {
19236   return bfd_get_64 (abfd, buf);
19237 }
19238
19239 static CORE_ADDR
19240 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19241               unsigned int *bytes_read)
19242 {
19243   struct comp_unit_head *cu_header = &cu->header;
19244   CORE_ADDR retval = 0;
19245
19246   if (cu_header->signed_addr_p)
19247     {
19248       switch (cu_header->addr_size)
19249         {
19250         case 2:
19251           retval = bfd_get_signed_16 (abfd, buf);
19252           break;
19253         case 4:
19254           retval = bfd_get_signed_32 (abfd, buf);
19255           break;
19256         case 8:
19257           retval = bfd_get_signed_64 (abfd, buf);
19258           break;
19259         default:
19260           internal_error (__FILE__, __LINE__,
19261                           _("read_address: bad switch, signed [in module %s]"),
19262                           bfd_get_filename (abfd));
19263         }
19264     }
19265   else
19266     {
19267       switch (cu_header->addr_size)
19268         {
19269         case 2:
19270           retval = bfd_get_16 (abfd, buf);
19271           break;
19272         case 4:
19273           retval = bfd_get_32 (abfd, buf);
19274           break;
19275         case 8:
19276           retval = bfd_get_64 (abfd, buf);
19277           break;
19278         default:
19279           internal_error (__FILE__, __LINE__,
19280                           _("read_address: bad switch, "
19281                             "unsigned [in module %s]"),
19282                           bfd_get_filename (abfd));
19283         }
19284     }
19285
19286   *bytes_read = cu_header->addr_size;
19287   return retval;
19288 }
19289
19290 /* Read the initial length from a section.  The (draft) DWARF 3
19291    specification allows the initial length to take up either 4 bytes
19292    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19293    bytes describe the length and all offsets will be 8 bytes in length
19294    instead of 4.
19295
19296    An older, non-standard 64-bit format is also handled by this
19297    function.  The older format in question stores the initial length
19298    as an 8-byte quantity without an escape value.  Lengths greater
19299    than 2^32 aren't very common which means that the initial 4 bytes
19300    is almost always zero.  Since a length value of zero doesn't make
19301    sense for the 32-bit format, this initial zero can be considered to
19302    be an escape value which indicates the presence of the older 64-bit
19303    format.  As written, the code can't detect (old format) lengths
19304    greater than 4GB.  If it becomes necessary to handle lengths
19305    somewhat larger than 4GB, we could allow other small values (such
19306    as the non-sensical values of 1, 2, and 3) to also be used as
19307    escape values indicating the presence of the old format.
19308
19309    The value returned via bytes_read should be used to increment the
19310    relevant pointer after calling read_initial_length().
19311
19312    [ Note:  read_initial_length() and read_offset() are based on the
19313      document entitled "DWARF Debugging Information Format", revision
19314      3, draft 8, dated November 19, 2001.  This document was obtained
19315      from:
19316
19317         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19318
19319      This document is only a draft and is subject to change.  (So beware.)
19320
19321      Details regarding the older, non-standard 64-bit format were
19322      determined empirically by examining 64-bit ELF files produced by
19323      the SGI toolchain on an IRIX 6.5 machine.
19324
19325      - Kevin, July 16, 2002
19326    ] */
19327
19328 static LONGEST
19329 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19330 {
19331   LONGEST length = bfd_get_32 (abfd, buf);
19332
19333   if (length == 0xffffffff)
19334     {
19335       length = bfd_get_64 (abfd, buf + 4);
19336       *bytes_read = 12;
19337     }
19338   else if (length == 0)
19339     {
19340       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19341       length = bfd_get_64 (abfd, buf);
19342       *bytes_read = 8;
19343     }
19344   else
19345     {
19346       *bytes_read = 4;
19347     }
19348
19349   return length;
19350 }
19351
19352 /* Cover function for read_initial_length.
19353    Returns the length of the object at BUF, and stores the size of the
19354    initial length in *BYTES_READ and stores the size that offsets will be in
19355    *OFFSET_SIZE.
19356    If the initial length size is not equivalent to that specified in
19357    CU_HEADER then issue a complaint.
19358    This is useful when reading non-comp-unit headers.  */
19359
19360 static LONGEST
19361 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19362                                         const struct comp_unit_head *cu_header,
19363                                         unsigned int *bytes_read,
19364                                         unsigned int *offset_size)
19365 {
19366   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19367
19368   gdb_assert (cu_header->initial_length_size == 4
19369               || cu_header->initial_length_size == 8
19370               || cu_header->initial_length_size == 12);
19371
19372   if (cu_header->initial_length_size != *bytes_read)
19373     complaint (&symfile_complaints,
19374                _("intermixed 32-bit and 64-bit DWARF sections"));
19375
19376   *offset_size = (*bytes_read == 4) ? 4 : 8;
19377   return length;
19378 }
19379
19380 /* Read an offset from the data stream.  The size of the offset is
19381    given by cu_header->offset_size.  */
19382
19383 static LONGEST
19384 read_offset (bfd *abfd, const gdb_byte *buf,
19385              const struct comp_unit_head *cu_header,
19386              unsigned int *bytes_read)
19387 {
19388   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19389
19390   *bytes_read = cu_header->offset_size;
19391   return offset;
19392 }
19393
19394 /* Read an offset from the data stream.  */
19395
19396 static LONGEST
19397 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19398 {
19399   LONGEST retval = 0;
19400
19401   switch (offset_size)
19402     {
19403     case 4:
19404       retval = bfd_get_32 (abfd, buf);
19405       break;
19406     case 8:
19407       retval = bfd_get_64 (abfd, buf);
19408       break;
19409     default:
19410       internal_error (__FILE__, __LINE__,
19411                       _("read_offset_1: bad switch [in module %s]"),
19412                       bfd_get_filename (abfd));
19413     }
19414
19415   return retval;
19416 }
19417
19418 static const gdb_byte *
19419 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19420 {
19421   /* If the size of a host char is 8 bits, we can return a pointer
19422      to the buffer, otherwise we have to copy the data to a buffer
19423      allocated on the temporary obstack.  */
19424   gdb_assert (HOST_CHAR_BIT == 8);
19425   return buf;
19426 }
19427
19428 static const char *
19429 read_direct_string (bfd *abfd, const gdb_byte *buf,
19430                     unsigned int *bytes_read_ptr)
19431 {
19432   /* If the size of a host char is 8 bits, we can return a pointer
19433      to the string, otherwise we have to copy the string to a buffer
19434      allocated on the temporary obstack.  */
19435   gdb_assert (HOST_CHAR_BIT == 8);
19436   if (*buf == '\0')
19437     {
19438       *bytes_read_ptr = 1;
19439       return NULL;
19440     }
19441   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19442   return (const char *) buf;
19443 }
19444
19445 /* Return pointer to string at section SECT offset STR_OFFSET with error
19446    reporting strings FORM_NAME and SECT_NAME.  */
19447
19448 static const char *
19449 read_indirect_string_at_offset_from (struct objfile *objfile,
19450                                      bfd *abfd, LONGEST str_offset,
19451                                      struct dwarf2_section_info *sect,
19452                                      const char *form_name,
19453                                      const char *sect_name)
19454 {
19455   dwarf2_read_section (objfile, sect);
19456   if (sect->buffer == NULL)
19457     error (_("%s used without %s section [in module %s]"),
19458            form_name, sect_name, bfd_get_filename (abfd));
19459   if (str_offset >= sect->size)
19460     error (_("%s pointing outside of %s section [in module %s]"),
19461            form_name, sect_name, bfd_get_filename (abfd));
19462   gdb_assert (HOST_CHAR_BIT == 8);
19463   if (sect->buffer[str_offset] == '\0')
19464     return NULL;
19465   return (const char *) (sect->buffer + str_offset);
19466 }
19467
19468 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19469
19470 static const char *
19471 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19472                                 bfd *abfd, LONGEST str_offset)
19473 {
19474   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19475                                               abfd, str_offset,
19476                                               &dwarf2_per_objfile->str,
19477                                               "DW_FORM_strp", ".debug_str");
19478 }
19479
19480 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19481
19482 static const char *
19483 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19484                                      bfd *abfd, LONGEST str_offset)
19485 {
19486   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19487                                               abfd, str_offset,
19488                                               &dwarf2_per_objfile->line_str,
19489                                               "DW_FORM_line_strp",
19490                                               ".debug_line_str");
19491 }
19492
19493 /* Read a string at offset STR_OFFSET in the .debug_str section from
19494    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19495    the string consists of a single NUL byte, return NULL; otherwise
19496    return a pointer to the string.  */
19497
19498 static const char *
19499 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19500                                LONGEST str_offset)
19501 {
19502   dwarf2_read_section (objfile, &dwz->str);
19503
19504   if (dwz->str.buffer == NULL)
19505     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19506              "section [in module %s]"),
19507            bfd_get_filename (dwz->dwz_bfd));
19508   if (str_offset >= dwz->str.size)
19509     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19510              ".debug_str section [in module %s]"),
19511            bfd_get_filename (dwz->dwz_bfd));
19512   gdb_assert (HOST_CHAR_BIT == 8);
19513   if (dwz->str.buffer[str_offset] == '\0')
19514     return NULL;
19515   return (const char *) (dwz->str.buffer + str_offset);
19516 }
19517
19518 /* Return pointer to string at .debug_str offset as read from BUF.
19519    BUF is assumed to be in a compilation unit described by CU_HEADER.
19520    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19521
19522 static const char *
19523 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19524                       const gdb_byte *buf,
19525                       const struct comp_unit_head *cu_header,
19526                       unsigned int *bytes_read_ptr)
19527 {
19528   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19529
19530   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19531 }
19532
19533 /* Return pointer to string at .debug_line_str offset as read from BUF.
19534    BUF is assumed to be in a compilation unit described by CU_HEADER.
19535    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19536
19537 static const char *
19538 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19539                            bfd *abfd, const gdb_byte *buf,
19540                            const struct comp_unit_head *cu_header,
19541                            unsigned int *bytes_read_ptr)
19542 {
19543   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19544
19545   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19546                                               str_offset);
19547 }
19548
19549 ULONGEST
19550 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19551                           unsigned int *bytes_read_ptr)
19552 {
19553   ULONGEST result;
19554   unsigned int num_read;
19555   int shift;
19556   unsigned char byte;
19557
19558   result = 0;
19559   shift = 0;
19560   num_read = 0;
19561   while (1)
19562     {
19563       byte = bfd_get_8 (abfd, buf);
19564       buf++;
19565       num_read++;
19566       result |= ((ULONGEST) (byte & 127) << shift);
19567       if ((byte & 128) == 0)
19568         {
19569           break;
19570         }
19571       shift += 7;
19572     }
19573   *bytes_read_ptr = num_read;
19574   return result;
19575 }
19576
19577 static LONGEST
19578 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19579                     unsigned int *bytes_read_ptr)
19580 {
19581   LONGEST result;
19582   int shift, num_read;
19583   unsigned char byte;
19584
19585   result = 0;
19586   shift = 0;
19587   num_read = 0;
19588   while (1)
19589     {
19590       byte = bfd_get_8 (abfd, buf);
19591       buf++;
19592       num_read++;
19593       result |= ((LONGEST) (byte & 127) << shift);
19594       shift += 7;
19595       if ((byte & 128) == 0)
19596         {
19597           break;
19598         }
19599     }
19600   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19601     result |= -(((LONGEST) 1) << shift);
19602   *bytes_read_ptr = num_read;
19603   return result;
19604 }
19605
19606 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19607    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19608    ADDR_SIZE is the size of addresses from the CU header.  */
19609
19610 static CORE_ADDR
19611 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19612                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19613 {
19614   struct objfile *objfile = dwarf2_per_objfile->objfile;
19615   bfd *abfd = objfile->obfd;
19616   const gdb_byte *info_ptr;
19617
19618   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19619   if (dwarf2_per_objfile->addr.buffer == NULL)
19620     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19621            objfile_name (objfile));
19622   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19623     error (_("DW_FORM_addr_index pointing outside of "
19624              ".debug_addr section [in module %s]"),
19625            objfile_name (objfile));
19626   info_ptr = (dwarf2_per_objfile->addr.buffer
19627               + addr_base + addr_index * addr_size);
19628   if (addr_size == 4)
19629     return bfd_get_32 (abfd, info_ptr);
19630   else
19631     return bfd_get_64 (abfd, info_ptr);
19632 }
19633
19634 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19635
19636 static CORE_ADDR
19637 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19638 {
19639   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19640                             cu->addr_base, cu->header.addr_size);
19641 }
19642
19643 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19644
19645 static CORE_ADDR
19646 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19647                              unsigned int *bytes_read)
19648 {
19649   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19650   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19651
19652   return read_addr_index (cu, addr_index);
19653 }
19654
19655 /* Data structure to pass results from dwarf2_read_addr_index_reader
19656    back to dwarf2_read_addr_index.  */
19657
19658 struct dwarf2_read_addr_index_data
19659 {
19660   ULONGEST addr_base;
19661   int addr_size;
19662 };
19663
19664 /* die_reader_func for dwarf2_read_addr_index.  */
19665
19666 static void
19667 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19668                                const gdb_byte *info_ptr,
19669                                struct die_info *comp_unit_die,
19670                                int has_children,
19671                                void *data)
19672 {
19673   struct dwarf2_cu *cu = reader->cu;
19674   struct dwarf2_read_addr_index_data *aidata =
19675     (struct dwarf2_read_addr_index_data *) data;
19676
19677   aidata->addr_base = cu->addr_base;
19678   aidata->addr_size = cu->header.addr_size;
19679 }
19680
19681 /* Given an index in .debug_addr, fetch the value.
19682    NOTE: This can be called during dwarf expression evaluation,
19683    long after the debug information has been read, and thus per_cu->cu
19684    may no longer exist.  */
19685
19686 CORE_ADDR
19687 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19688                         unsigned int addr_index)
19689 {
19690   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19691   struct objfile *objfile = dwarf2_per_objfile->objfile;
19692   struct dwarf2_cu *cu = per_cu->cu;
19693   ULONGEST addr_base;
19694   int addr_size;
19695
19696   /* We need addr_base and addr_size.
19697      If we don't have PER_CU->cu, we have to get it.
19698      Nasty, but the alternative is storing the needed info in PER_CU,
19699      which at this point doesn't seem justified: it's not clear how frequently
19700      it would get used and it would increase the size of every PER_CU.
19701      Entry points like dwarf2_per_cu_addr_size do a similar thing
19702      so we're not in uncharted territory here.
19703      Alas we need to be a bit more complicated as addr_base is contained
19704      in the DIE.
19705
19706      We don't need to read the entire CU(/TU).
19707      We just need the header and top level die.
19708
19709      IWBN to use the aging mechanism to let us lazily later discard the CU.
19710      For now we skip this optimization.  */
19711
19712   if (cu != NULL)
19713     {
19714       addr_base = cu->addr_base;
19715       addr_size = cu->header.addr_size;
19716     }
19717   else
19718     {
19719       struct dwarf2_read_addr_index_data aidata;
19720
19721       /* Note: We can't use init_cutu_and_read_dies_simple here,
19722          we need addr_base.  */
19723       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19724                                dwarf2_read_addr_index_reader, &aidata);
19725       addr_base = aidata.addr_base;
19726       addr_size = aidata.addr_size;
19727     }
19728
19729   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19730                             addr_size);
19731 }
19732
19733 /* Given a DW_FORM_GNU_str_index, fetch the string.
19734    This is only used by the Fission support.  */
19735
19736 static const char *
19737 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19738 {
19739   struct dwarf2_cu *cu = reader->cu;
19740   struct dwarf2_per_objfile *dwarf2_per_objfile
19741     = cu->per_cu->dwarf2_per_objfile;
19742   struct objfile *objfile = dwarf2_per_objfile->objfile;
19743   const char *objf_name = objfile_name (objfile);
19744   bfd *abfd = objfile->obfd;
19745   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19746   struct dwarf2_section_info *str_offsets_section =
19747     &reader->dwo_file->sections.str_offsets;
19748   const gdb_byte *info_ptr;
19749   ULONGEST str_offset;
19750   static const char form_name[] = "DW_FORM_GNU_str_index";
19751
19752   dwarf2_read_section (objfile, str_section);
19753   dwarf2_read_section (objfile, str_offsets_section);
19754   if (str_section->buffer == NULL)
19755     error (_("%s used without .debug_str.dwo section"
19756              " in CU at offset 0x%x [in module %s]"),
19757            form_name, to_underlying (cu->header.sect_off), objf_name);
19758   if (str_offsets_section->buffer == NULL)
19759     error (_("%s used without .debug_str_offsets.dwo section"
19760              " in CU at offset 0x%x [in module %s]"),
19761            form_name, to_underlying (cu->header.sect_off), objf_name);
19762   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19763     error (_("%s pointing outside of .debug_str_offsets.dwo"
19764              " section in CU at offset 0x%x [in module %s]"),
19765            form_name, to_underlying (cu->header.sect_off), objf_name);
19766   info_ptr = (str_offsets_section->buffer
19767               + str_index * cu->header.offset_size);
19768   if (cu->header.offset_size == 4)
19769     str_offset = bfd_get_32 (abfd, info_ptr);
19770   else
19771     str_offset = bfd_get_64 (abfd, info_ptr);
19772   if (str_offset >= str_section->size)
19773     error (_("Offset from %s pointing outside of"
19774              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19775            form_name, to_underlying (cu->header.sect_off), objf_name);
19776   return (const char *) (str_section->buffer + str_offset);
19777 }
19778
19779 /* Return the length of an LEB128 number in BUF.  */
19780
19781 static int
19782 leb128_size (const gdb_byte *buf)
19783 {
19784   const gdb_byte *begin = buf;
19785   gdb_byte byte;
19786
19787   while (1)
19788     {
19789       byte = *buf++;
19790       if ((byte & 128) == 0)
19791         return buf - begin;
19792     }
19793 }
19794
19795 static void
19796 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19797 {
19798   switch (lang)
19799     {
19800     case DW_LANG_C89:
19801     case DW_LANG_C99:
19802     case DW_LANG_C11:
19803     case DW_LANG_C:
19804     case DW_LANG_UPC:
19805       cu->language = language_c;
19806       break;
19807     case DW_LANG_Java:
19808     case DW_LANG_C_plus_plus:
19809     case DW_LANG_C_plus_plus_11:
19810     case DW_LANG_C_plus_plus_14:
19811       cu->language = language_cplus;
19812       break;
19813     case DW_LANG_D:
19814       cu->language = language_d;
19815       break;
19816     case DW_LANG_Fortran77:
19817     case DW_LANG_Fortran90:
19818     case DW_LANG_Fortran95:
19819     case DW_LANG_Fortran03:
19820     case DW_LANG_Fortran08:
19821       cu->language = language_fortran;
19822       break;
19823     case DW_LANG_Go:
19824       cu->language = language_go;
19825       break;
19826     case DW_LANG_Mips_Assembler:
19827       cu->language = language_asm;
19828       break;
19829     case DW_LANG_Ada83:
19830     case DW_LANG_Ada95:
19831       cu->language = language_ada;
19832       break;
19833     case DW_LANG_Modula2:
19834       cu->language = language_m2;
19835       break;
19836     case DW_LANG_Pascal83:
19837       cu->language = language_pascal;
19838       break;
19839     case DW_LANG_ObjC:
19840       cu->language = language_objc;
19841       break;
19842     case DW_LANG_Rust:
19843     case DW_LANG_Rust_old:
19844       cu->language = language_rust;
19845       break;
19846     case DW_LANG_Cobol74:
19847     case DW_LANG_Cobol85:
19848     default:
19849       cu->language = language_minimal;
19850       break;
19851     }
19852   cu->language_defn = language_def (cu->language);
19853 }
19854
19855 /* Return the named attribute or NULL if not there.  */
19856
19857 static struct attribute *
19858 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19859 {
19860   for (;;)
19861     {
19862       unsigned int i;
19863       struct attribute *spec = NULL;
19864
19865       for (i = 0; i < die->num_attrs; ++i)
19866         {
19867           if (die->attrs[i].name == name)
19868             return &die->attrs[i];
19869           if (die->attrs[i].name == DW_AT_specification
19870               || die->attrs[i].name == DW_AT_abstract_origin)
19871             spec = &die->attrs[i];
19872         }
19873
19874       if (!spec)
19875         break;
19876
19877       die = follow_die_ref (die, spec, &cu);
19878     }
19879
19880   return NULL;
19881 }
19882
19883 /* Return the named attribute or NULL if not there,
19884    but do not follow DW_AT_specification, etc.
19885    This is for use in contexts where we're reading .debug_types dies.
19886    Following DW_AT_specification, DW_AT_abstract_origin will take us
19887    back up the chain, and we want to go down.  */
19888
19889 static struct attribute *
19890 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19891 {
19892   unsigned int i;
19893
19894   for (i = 0; i < die->num_attrs; ++i)
19895     if (die->attrs[i].name == name)
19896       return &die->attrs[i];
19897
19898   return NULL;
19899 }
19900
19901 /* Return the string associated with a string-typed attribute, or NULL if it
19902    is either not found or is of an incorrect type.  */
19903
19904 static const char *
19905 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19906 {
19907   struct attribute *attr;
19908   const char *str = NULL;
19909
19910   attr = dwarf2_attr (die, name, cu);
19911
19912   if (attr != NULL)
19913     {
19914       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19915           || attr->form == DW_FORM_string
19916           || attr->form == DW_FORM_GNU_str_index
19917           || attr->form == DW_FORM_GNU_strp_alt)
19918         str = DW_STRING (attr);
19919       else
19920         complaint (&symfile_complaints,
19921                    _("string type expected for attribute %s for "
19922                      "DIE at 0x%x in module %s"),
19923                    dwarf_attr_name (name), to_underlying (die->sect_off),
19924                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19925     }
19926
19927   return str;
19928 }
19929
19930 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19931    and holds a non-zero value.  This function should only be used for
19932    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19933
19934 static int
19935 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19936 {
19937   struct attribute *attr = dwarf2_attr (die, name, cu);
19938
19939   return (attr && DW_UNSND (attr));
19940 }
19941
19942 static int
19943 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19944 {
19945   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19946      which value is non-zero.  However, we have to be careful with
19947      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19948      (via dwarf2_flag_true_p) follows this attribute.  So we may
19949      end up accidently finding a declaration attribute that belongs
19950      to a different DIE referenced by the specification attribute,
19951      even though the given DIE does not have a declaration attribute.  */
19952   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19953           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19954 }
19955
19956 /* Return the die giving the specification for DIE, if there is
19957    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19958    containing the return value on output.  If there is no
19959    specification, but there is an abstract origin, that is
19960    returned.  */
19961
19962 static struct die_info *
19963 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19964 {
19965   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19966                                              *spec_cu);
19967
19968   if (spec_attr == NULL)
19969     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19970
19971   if (spec_attr == NULL)
19972     return NULL;
19973   else
19974     return follow_die_ref (die, spec_attr, spec_cu);
19975 }
19976
19977 /* Stub for free_line_header to match void * callback types.  */
19978
19979 static void
19980 free_line_header_voidp (void *arg)
19981 {
19982   struct line_header *lh = (struct line_header *) arg;
19983
19984   delete lh;
19985 }
19986
19987 void
19988 line_header::add_include_dir (const char *include_dir)
19989 {
19990   if (dwarf_line_debug >= 2)
19991     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19992                         include_dirs.size () + 1, include_dir);
19993
19994   include_dirs.push_back (include_dir);
19995 }
19996
19997 void
19998 line_header::add_file_name (const char *name,
19999                             dir_index d_index,
20000                             unsigned int mod_time,
20001                             unsigned int length)
20002 {
20003   if (dwarf_line_debug >= 2)
20004     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20005                         (unsigned) file_names.size () + 1, name);
20006
20007   file_names.emplace_back (name, d_index, mod_time, length);
20008 }
20009
20010 /* A convenience function to find the proper .debug_line section for a CU.  */
20011
20012 static struct dwarf2_section_info *
20013 get_debug_line_section (struct dwarf2_cu *cu)
20014 {
20015   struct dwarf2_section_info *section;
20016   struct dwarf2_per_objfile *dwarf2_per_objfile
20017     = cu->per_cu->dwarf2_per_objfile;
20018
20019   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20020      DWO file.  */
20021   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20022     section = &cu->dwo_unit->dwo_file->sections.line;
20023   else if (cu->per_cu->is_dwz)
20024     {
20025       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20026
20027       section = &dwz->line;
20028     }
20029   else
20030     section = &dwarf2_per_objfile->line;
20031
20032   return section;
20033 }
20034
20035 /* Read directory or file name entry format, starting with byte of
20036    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20037    entries count and the entries themselves in the described entry
20038    format.  */
20039
20040 static void
20041 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20042                         bfd *abfd, const gdb_byte **bufp,
20043                         struct line_header *lh,
20044                         const struct comp_unit_head *cu_header,
20045                         void (*callback) (struct line_header *lh,
20046                                           const char *name,
20047                                           dir_index d_index,
20048                                           unsigned int mod_time,
20049                                           unsigned int length))
20050 {
20051   gdb_byte format_count, formati;
20052   ULONGEST data_count, datai;
20053   const gdb_byte *buf = *bufp;
20054   const gdb_byte *format_header_data;
20055   unsigned int bytes_read;
20056
20057   format_count = read_1_byte (abfd, buf);
20058   buf += 1;
20059   format_header_data = buf;
20060   for (formati = 0; formati < format_count; formati++)
20061     {
20062       read_unsigned_leb128 (abfd, buf, &bytes_read);
20063       buf += bytes_read;
20064       read_unsigned_leb128 (abfd, buf, &bytes_read);
20065       buf += bytes_read;
20066     }
20067
20068   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20069   buf += bytes_read;
20070   for (datai = 0; datai < data_count; datai++)
20071     {
20072       const gdb_byte *format = format_header_data;
20073       struct file_entry fe;
20074
20075       for (formati = 0; formati < format_count; formati++)
20076         {
20077           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20078           format += bytes_read;
20079
20080           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20081           format += bytes_read;
20082
20083           gdb::optional<const char *> string;
20084           gdb::optional<unsigned int> uint;
20085
20086           switch (form)
20087             {
20088             case DW_FORM_string:
20089               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20090               buf += bytes_read;
20091               break;
20092
20093             case DW_FORM_line_strp:
20094               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20095                                                          abfd, buf,
20096                                                          cu_header,
20097                                                          &bytes_read));
20098               buf += bytes_read;
20099               break;
20100
20101             case DW_FORM_data1:
20102               uint.emplace (read_1_byte (abfd, buf));
20103               buf += 1;
20104               break;
20105
20106             case DW_FORM_data2:
20107               uint.emplace (read_2_bytes (abfd, buf));
20108               buf += 2;
20109               break;
20110
20111             case DW_FORM_data4:
20112               uint.emplace (read_4_bytes (abfd, buf));
20113               buf += 4;
20114               break;
20115
20116             case DW_FORM_data8:
20117               uint.emplace (read_8_bytes (abfd, buf));
20118               buf += 8;
20119               break;
20120
20121             case DW_FORM_udata:
20122               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20123               buf += bytes_read;
20124               break;
20125
20126             case DW_FORM_block:
20127               /* It is valid only for DW_LNCT_timestamp which is ignored by
20128                  current GDB.  */
20129               break;
20130             }
20131
20132           switch (content_type)
20133             {
20134             case DW_LNCT_path:
20135               if (string.has_value ())
20136                 fe.name = *string;
20137               break;
20138             case DW_LNCT_directory_index:
20139               if (uint.has_value ())
20140                 fe.d_index = (dir_index) *uint;
20141               break;
20142             case DW_LNCT_timestamp:
20143               if (uint.has_value ())
20144                 fe.mod_time = *uint;
20145               break;
20146             case DW_LNCT_size:
20147               if (uint.has_value ())
20148                 fe.length = *uint;
20149               break;
20150             case DW_LNCT_MD5:
20151               break;
20152             default:
20153               complaint (&symfile_complaints,
20154                          _("Unknown format content type %s"),
20155                          pulongest (content_type));
20156             }
20157         }
20158
20159       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20160     }
20161
20162   *bufp = buf;
20163 }
20164
20165 /* Read the statement program header starting at OFFSET in
20166    .debug_line, or .debug_line.dwo.  Return a pointer
20167    to a struct line_header, allocated using xmalloc.
20168    Returns NULL if there is a problem reading the header, e.g., if it
20169    has a version we don't understand.
20170
20171    NOTE: the strings in the include directory and file name tables of
20172    the returned object point into the dwarf line section buffer,
20173    and must not be freed.  */
20174
20175 static line_header_up
20176 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20177 {
20178   const gdb_byte *line_ptr;
20179   unsigned int bytes_read, offset_size;
20180   int i;
20181   const char *cur_dir, *cur_file;
20182   struct dwarf2_section_info *section;
20183   bfd *abfd;
20184   struct dwarf2_per_objfile *dwarf2_per_objfile
20185     = cu->per_cu->dwarf2_per_objfile;
20186
20187   section = get_debug_line_section (cu);
20188   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20189   if (section->buffer == NULL)
20190     {
20191       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20192         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20193       else
20194         complaint (&symfile_complaints, _("missing .debug_line section"));
20195       return 0;
20196     }
20197
20198   /* We can't do this until we know the section is non-empty.
20199      Only then do we know we have such a section.  */
20200   abfd = get_section_bfd_owner (section);
20201
20202   /* Make sure that at least there's room for the total_length field.
20203      That could be 12 bytes long, but we're just going to fudge that.  */
20204   if (to_underlying (sect_off) + 4 >= section->size)
20205     {
20206       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20207       return 0;
20208     }
20209
20210   line_header_up lh (new line_header ());
20211
20212   lh->sect_off = sect_off;
20213   lh->offset_in_dwz = cu->per_cu->is_dwz;
20214
20215   line_ptr = section->buffer + to_underlying (sect_off);
20216
20217   /* Read in the header.  */
20218   lh->total_length =
20219     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20220                                             &bytes_read, &offset_size);
20221   line_ptr += bytes_read;
20222   if (line_ptr + lh->total_length > (section->buffer + section->size))
20223     {
20224       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20225       return 0;
20226     }
20227   lh->statement_program_end = line_ptr + lh->total_length;
20228   lh->version = read_2_bytes (abfd, line_ptr);
20229   line_ptr += 2;
20230   if (lh->version > 5)
20231     {
20232       /* This is a version we don't understand.  The format could have
20233          changed in ways we don't handle properly so just punt.  */
20234       complaint (&symfile_complaints,
20235                  _("unsupported version in .debug_line section"));
20236       return NULL;
20237     }
20238   if (lh->version >= 5)
20239     {
20240       gdb_byte segment_selector_size;
20241
20242       /* Skip address size.  */
20243       read_1_byte (abfd, line_ptr);
20244       line_ptr += 1;
20245
20246       segment_selector_size = read_1_byte (abfd, line_ptr);
20247       line_ptr += 1;
20248       if (segment_selector_size != 0)
20249         {
20250           complaint (&symfile_complaints,
20251                      _("unsupported segment selector size %u "
20252                        "in .debug_line section"),
20253                      segment_selector_size);
20254           return NULL;
20255         }
20256     }
20257   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20258   line_ptr += offset_size;
20259   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20260   line_ptr += 1;
20261   if (lh->version >= 4)
20262     {
20263       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20264       line_ptr += 1;
20265     }
20266   else
20267     lh->maximum_ops_per_instruction = 1;
20268
20269   if (lh->maximum_ops_per_instruction == 0)
20270     {
20271       lh->maximum_ops_per_instruction = 1;
20272       complaint (&symfile_complaints,
20273                  _("invalid maximum_ops_per_instruction "
20274                    "in `.debug_line' section"));
20275     }
20276
20277   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20278   line_ptr += 1;
20279   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20280   line_ptr += 1;
20281   lh->line_range = read_1_byte (abfd, line_ptr);
20282   line_ptr += 1;
20283   lh->opcode_base = read_1_byte (abfd, line_ptr);
20284   line_ptr += 1;
20285   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20286
20287   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20288   for (i = 1; i < lh->opcode_base; ++i)
20289     {
20290       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20291       line_ptr += 1;
20292     }
20293
20294   if (lh->version >= 5)
20295     {
20296       /* Read directory table.  */
20297       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20298                               &cu->header,
20299                               [] (struct line_header *lh, const char *name,
20300                                   dir_index d_index, unsigned int mod_time,
20301                                   unsigned int length)
20302         {
20303           lh->add_include_dir (name);
20304         });
20305
20306       /* Read file name table.  */
20307       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20308                               &cu->header,
20309                               [] (struct line_header *lh, const char *name,
20310                                   dir_index d_index, unsigned int mod_time,
20311                                   unsigned int length)
20312         {
20313           lh->add_file_name (name, d_index, mod_time, length);
20314         });
20315     }
20316   else
20317     {
20318       /* Read directory table.  */
20319       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20320         {
20321           line_ptr += bytes_read;
20322           lh->add_include_dir (cur_dir);
20323         }
20324       line_ptr += bytes_read;
20325
20326       /* Read file name table.  */
20327       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20328         {
20329           unsigned int mod_time, length;
20330           dir_index d_index;
20331
20332           line_ptr += bytes_read;
20333           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20334           line_ptr += bytes_read;
20335           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20336           line_ptr += bytes_read;
20337           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20338           line_ptr += bytes_read;
20339
20340           lh->add_file_name (cur_file, d_index, mod_time, length);
20341         }
20342       line_ptr += bytes_read;
20343     }
20344   lh->statement_program_start = line_ptr;
20345
20346   if (line_ptr > (section->buffer + section->size))
20347     complaint (&symfile_complaints,
20348                _("line number info header doesn't "
20349                  "fit in `.debug_line' section"));
20350
20351   return lh;
20352 }
20353
20354 /* Subroutine of dwarf_decode_lines to simplify it.
20355    Return the file name of the psymtab for included file FILE_INDEX
20356    in line header LH of PST.
20357    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20358    If space for the result is malloc'd, *NAME_HOLDER will be set.
20359    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20360
20361 static const char *
20362 psymtab_include_file_name (const struct line_header *lh, int file_index,
20363                            const struct partial_symtab *pst,
20364                            const char *comp_dir,
20365                            gdb::unique_xmalloc_ptr<char> *name_holder)
20366 {
20367   const file_entry &fe = lh->file_names[file_index];
20368   const char *include_name = fe.name;
20369   const char *include_name_to_compare = include_name;
20370   const char *pst_filename;
20371   int file_is_pst;
20372
20373   const char *dir_name = fe.include_dir (lh);
20374
20375   gdb::unique_xmalloc_ptr<char> hold_compare;
20376   if (!IS_ABSOLUTE_PATH (include_name)
20377       && (dir_name != NULL || comp_dir != NULL))
20378     {
20379       /* Avoid creating a duplicate psymtab for PST.
20380          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20381          Before we do the comparison, however, we need to account
20382          for DIR_NAME and COMP_DIR.
20383          First prepend dir_name (if non-NULL).  If we still don't
20384          have an absolute path prepend comp_dir (if non-NULL).
20385          However, the directory we record in the include-file's
20386          psymtab does not contain COMP_DIR (to match the
20387          corresponding symtab(s)).
20388
20389          Example:
20390
20391          bash$ cd /tmp
20392          bash$ gcc -g ./hello.c
20393          include_name = "hello.c"
20394          dir_name = "."
20395          DW_AT_comp_dir = comp_dir = "/tmp"
20396          DW_AT_name = "./hello.c"
20397
20398       */
20399
20400       if (dir_name != NULL)
20401         {
20402           name_holder->reset (concat (dir_name, SLASH_STRING,
20403                                       include_name, (char *) NULL));
20404           include_name = name_holder->get ();
20405           include_name_to_compare = include_name;
20406         }
20407       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20408         {
20409           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20410                                       include_name, (char *) NULL));
20411           include_name_to_compare = hold_compare.get ();
20412         }
20413     }
20414
20415   pst_filename = pst->filename;
20416   gdb::unique_xmalloc_ptr<char> copied_name;
20417   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20418     {
20419       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20420                                  pst_filename, (char *) NULL));
20421       pst_filename = copied_name.get ();
20422     }
20423
20424   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20425
20426   if (file_is_pst)
20427     return NULL;
20428   return include_name;
20429 }
20430
20431 /* State machine to track the state of the line number program.  */
20432
20433 class lnp_state_machine
20434 {
20435 public:
20436   /* Initialize a machine state for the start of a line number
20437      program.  */
20438   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20439
20440   file_entry *current_file ()
20441   {
20442     /* lh->file_names is 0-based, but the file name numbers in the
20443        statement program are 1-based.  */
20444     return m_line_header->file_name_at (m_file);
20445   }
20446
20447   /* Record the line in the state machine.  END_SEQUENCE is true if
20448      we're processing the end of a sequence.  */
20449   void record_line (bool end_sequence);
20450
20451   /* Check address and if invalid nop-out the rest of the lines in this
20452      sequence.  */
20453   void check_line_address (struct dwarf2_cu *cu,
20454                            const gdb_byte *line_ptr,
20455                            CORE_ADDR lowpc, CORE_ADDR address);
20456
20457   void handle_set_discriminator (unsigned int discriminator)
20458   {
20459     m_discriminator = discriminator;
20460     m_line_has_non_zero_discriminator |= discriminator != 0;
20461   }
20462
20463   /* Handle DW_LNE_set_address.  */
20464   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20465   {
20466     m_op_index = 0;
20467     address += baseaddr;
20468     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20469   }
20470
20471   /* Handle DW_LNS_advance_pc.  */
20472   void handle_advance_pc (CORE_ADDR adjust);
20473
20474   /* Handle a special opcode.  */
20475   void handle_special_opcode (unsigned char op_code);
20476
20477   /* Handle DW_LNS_advance_line.  */
20478   void handle_advance_line (int line_delta)
20479   {
20480     advance_line (line_delta);
20481   }
20482
20483   /* Handle DW_LNS_set_file.  */
20484   void handle_set_file (file_name_index file);
20485
20486   /* Handle DW_LNS_negate_stmt.  */
20487   void handle_negate_stmt ()
20488   {
20489     m_is_stmt = !m_is_stmt;
20490   }
20491
20492   /* Handle DW_LNS_const_add_pc.  */
20493   void handle_const_add_pc ();
20494
20495   /* Handle DW_LNS_fixed_advance_pc.  */
20496   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20497   {
20498     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20499     m_op_index = 0;
20500   }
20501
20502   /* Handle DW_LNS_copy.  */
20503   void handle_copy ()
20504   {
20505     record_line (false);
20506     m_discriminator = 0;
20507   }
20508
20509   /* Handle DW_LNE_end_sequence.  */
20510   void handle_end_sequence ()
20511   {
20512     m_record_line_callback = ::record_line;
20513   }
20514
20515 private:
20516   /* Advance the line by LINE_DELTA.  */
20517   void advance_line (int line_delta)
20518   {
20519     m_line += line_delta;
20520
20521     if (line_delta != 0)
20522       m_line_has_non_zero_discriminator = m_discriminator != 0;
20523   }
20524
20525   gdbarch *m_gdbarch;
20526
20527   /* True if we're recording lines.
20528      Otherwise we're building partial symtabs and are just interested in
20529      finding include files mentioned by the line number program.  */
20530   bool m_record_lines_p;
20531
20532   /* The line number header.  */
20533   line_header *m_line_header;
20534
20535   /* These are part of the standard DWARF line number state machine,
20536      and initialized according to the DWARF spec.  */
20537
20538   unsigned char m_op_index = 0;
20539   /* The line table index (1-based) of the current file.  */
20540   file_name_index m_file = (file_name_index) 1;
20541   unsigned int m_line = 1;
20542
20543   /* These are initialized in the constructor.  */
20544
20545   CORE_ADDR m_address;
20546   bool m_is_stmt;
20547   unsigned int m_discriminator;
20548
20549   /* Additional bits of state we need to track.  */
20550
20551   /* The last file that we called dwarf2_start_subfile for.
20552      This is only used for TLLs.  */
20553   unsigned int m_last_file = 0;
20554   /* The last file a line number was recorded for.  */
20555   struct subfile *m_last_subfile = NULL;
20556
20557   /* The function to call to record a line.  */
20558   record_line_ftype *m_record_line_callback = NULL;
20559
20560   /* The last line number that was recorded, used to coalesce
20561      consecutive entries for the same line.  This can happen, for
20562      example, when discriminators are present.  PR 17276.  */
20563   unsigned int m_last_line = 0;
20564   bool m_line_has_non_zero_discriminator = false;
20565 };
20566
20567 void
20568 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20569 {
20570   CORE_ADDR addr_adj = (((m_op_index + adjust)
20571                          / m_line_header->maximum_ops_per_instruction)
20572                         * m_line_header->minimum_instruction_length);
20573   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20574   m_op_index = ((m_op_index + adjust)
20575                 % m_line_header->maximum_ops_per_instruction);
20576 }
20577
20578 void
20579 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20580 {
20581   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20582   CORE_ADDR addr_adj = (((m_op_index
20583                           + (adj_opcode / m_line_header->line_range))
20584                          / m_line_header->maximum_ops_per_instruction)
20585                         * m_line_header->minimum_instruction_length);
20586   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20587   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20588                 % m_line_header->maximum_ops_per_instruction);
20589
20590   int line_delta = (m_line_header->line_base
20591                     + (adj_opcode % m_line_header->line_range));
20592   advance_line (line_delta);
20593   record_line (false);
20594   m_discriminator = 0;
20595 }
20596
20597 void
20598 lnp_state_machine::handle_set_file (file_name_index file)
20599 {
20600   m_file = file;
20601
20602   const file_entry *fe = current_file ();
20603   if (fe == NULL)
20604     dwarf2_debug_line_missing_file_complaint ();
20605   else if (m_record_lines_p)
20606     {
20607       const char *dir = fe->include_dir (m_line_header);
20608
20609       m_last_subfile = current_subfile;
20610       m_line_has_non_zero_discriminator = m_discriminator != 0;
20611       dwarf2_start_subfile (fe->name, dir);
20612     }
20613 }
20614
20615 void
20616 lnp_state_machine::handle_const_add_pc ()
20617 {
20618   CORE_ADDR adjust
20619     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20620
20621   CORE_ADDR addr_adj
20622     = (((m_op_index + adjust)
20623         / m_line_header->maximum_ops_per_instruction)
20624        * m_line_header->minimum_instruction_length);
20625
20626   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20627   m_op_index = ((m_op_index + adjust)
20628                 % m_line_header->maximum_ops_per_instruction);
20629 }
20630
20631 /* Ignore this record_line request.  */
20632
20633 static void
20634 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20635 {
20636   return;
20637 }
20638
20639 /* Return non-zero if we should add LINE to the line number table.
20640    LINE is the line to add, LAST_LINE is the last line that was added,
20641    LAST_SUBFILE is the subfile for LAST_LINE.
20642    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20643    had a non-zero discriminator.
20644
20645    We have to be careful in the presence of discriminators.
20646    E.g., for this line:
20647
20648      for (i = 0; i < 100000; i++);
20649
20650    clang can emit four line number entries for that one line,
20651    each with a different discriminator.
20652    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20653
20654    However, we want gdb to coalesce all four entries into one.
20655    Otherwise the user could stepi into the middle of the line and
20656    gdb would get confused about whether the pc really was in the
20657    middle of the line.
20658
20659    Things are further complicated by the fact that two consecutive
20660    line number entries for the same line is a heuristic used by gcc
20661    to denote the end of the prologue.  So we can't just discard duplicate
20662    entries, we have to be selective about it.  The heuristic we use is
20663    that we only collapse consecutive entries for the same line if at least
20664    one of those entries has a non-zero discriminator.  PR 17276.
20665
20666    Note: Addresses in the line number state machine can never go backwards
20667    within one sequence, thus this coalescing is ok.  */
20668
20669 static int
20670 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20671                      int line_has_non_zero_discriminator,
20672                      struct subfile *last_subfile)
20673 {
20674   if (current_subfile != last_subfile)
20675     return 1;
20676   if (line != last_line)
20677     return 1;
20678   /* Same line for the same file that we've seen already.
20679      As a last check, for pr 17276, only record the line if the line
20680      has never had a non-zero discriminator.  */
20681   if (!line_has_non_zero_discriminator)
20682     return 1;
20683   return 0;
20684 }
20685
20686 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20687    in the line table of subfile SUBFILE.  */
20688
20689 static void
20690 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20691                      unsigned int line, CORE_ADDR address,
20692                      record_line_ftype p_record_line)
20693 {
20694   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20695
20696   if (dwarf_line_debug)
20697     {
20698       fprintf_unfiltered (gdb_stdlog,
20699                           "Recording line %u, file %s, address %s\n",
20700                           line, lbasename (subfile->name),
20701                           paddress (gdbarch, address));
20702     }
20703
20704   (*p_record_line) (subfile, line, addr);
20705 }
20706
20707 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20708    Mark the end of a set of line number records.
20709    The arguments are the same as for dwarf_record_line_1.
20710    If SUBFILE is NULL the request is ignored.  */
20711
20712 static void
20713 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20714                    CORE_ADDR address, record_line_ftype p_record_line)
20715 {
20716   if (subfile == NULL)
20717     return;
20718
20719   if (dwarf_line_debug)
20720     {
20721       fprintf_unfiltered (gdb_stdlog,
20722                           "Finishing current line, file %s, address %s\n",
20723                           lbasename (subfile->name),
20724                           paddress (gdbarch, address));
20725     }
20726
20727   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20728 }
20729
20730 void
20731 lnp_state_machine::record_line (bool end_sequence)
20732 {
20733   if (dwarf_line_debug)
20734     {
20735       fprintf_unfiltered (gdb_stdlog,
20736                           "Processing actual line %u: file %u,"
20737                           " address %s, is_stmt %u, discrim %u\n",
20738                           m_line, to_underlying (m_file),
20739                           paddress (m_gdbarch, m_address),
20740                           m_is_stmt, m_discriminator);
20741     }
20742
20743   file_entry *fe = current_file ();
20744
20745   if (fe == NULL)
20746     dwarf2_debug_line_missing_file_complaint ();
20747   /* For now we ignore lines not starting on an instruction boundary.
20748      But not when processing end_sequence for compatibility with the
20749      previous version of the code.  */
20750   else if (m_op_index == 0 || end_sequence)
20751     {
20752       fe->included_p = 1;
20753       if (m_record_lines_p && m_is_stmt)
20754         {
20755           if (m_last_subfile != current_subfile || end_sequence)
20756             {
20757               dwarf_finish_line (m_gdbarch, m_last_subfile,
20758                                  m_address, m_record_line_callback);
20759             }
20760
20761           if (!end_sequence)
20762             {
20763               if (dwarf_record_line_p (m_line, m_last_line,
20764                                        m_line_has_non_zero_discriminator,
20765                                        m_last_subfile))
20766                 {
20767                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20768                                        m_line, m_address,
20769                                        m_record_line_callback);
20770                 }
20771               m_last_subfile = current_subfile;
20772               m_last_line = m_line;
20773             }
20774         }
20775     }
20776 }
20777
20778 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20779                                       bool record_lines_p)
20780 {
20781   m_gdbarch = arch;
20782   m_record_lines_p = record_lines_p;
20783   m_line_header = lh;
20784
20785   m_record_line_callback = ::record_line;
20786
20787   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20788      was a line entry for it so that the backend has a chance to adjust it
20789      and also record it in case it needs it.  This is currently used by MIPS
20790      code, cf. `mips_adjust_dwarf2_line'.  */
20791   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20792   m_is_stmt = lh->default_is_stmt;
20793   m_discriminator = 0;
20794 }
20795
20796 void
20797 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20798                                        const gdb_byte *line_ptr,
20799                                        CORE_ADDR lowpc, CORE_ADDR address)
20800 {
20801   /* If address < lowpc then it's not a usable value, it's outside the
20802      pc range of the CU.  However, we restrict the test to only address
20803      values of zero to preserve GDB's previous behaviour which is to
20804      handle the specific case of a function being GC'd by the linker.  */
20805
20806   if (address == 0 && address < lowpc)
20807     {
20808       /* This line table is for a function which has been
20809          GCd by the linker.  Ignore it.  PR gdb/12528 */
20810
20811       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20812       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20813
20814       complaint (&symfile_complaints,
20815                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20816                  line_offset, objfile_name (objfile));
20817       m_record_line_callback = noop_record_line;
20818       /* Note: record_line_callback is left as noop_record_line until
20819          we see DW_LNE_end_sequence.  */
20820     }
20821 }
20822
20823 /* Subroutine of dwarf_decode_lines to simplify it.
20824    Process the line number information in LH.
20825    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20826    program in order to set included_p for every referenced header.  */
20827
20828 static void
20829 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20830                       const int decode_for_pst_p, CORE_ADDR lowpc)
20831 {
20832   const gdb_byte *line_ptr, *extended_end;
20833   const gdb_byte *line_end;
20834   unsigned int bytes_read, extended_len;
20835   unsigned char op_code, extended_op;
20836   CORE_ADDR baseaddr;
20837   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20838   bfd *abfd = objfile->obfd;
20839   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20840   /* True if we're recording line info (as opposed to building partial
20841      symtabs and just interested in finding include files mentioned by
20842      the line number program).  */
20843   bool record_lines_p = !decode_for_pst_p;
20844
20845   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20846
20847   line_ptr = lh->statement_program_start;
20848   line_end = lh->statement_program_end;
20849
20850   /* Read the statement sequences until there's nothing left.  */
20851   while (line_ptr < line_end)
20852     {
20853       /* The DWARF line number program state machine.  Reset the state
20854          machine at the start of each sequence.  */
20855       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20856       bool end_sequence = false;
20857
20858       if (record_lines_p)
20859         {
20860           /* Start a subfile for the current file of the state
20861              machine.  */
20862           const file_entry *fe = state_machine.current_file ();
20863
20864           if (fe != NULL)
20865             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20866         }
20867
20868       /* Decode the table.  */
20869       while (line_ptr < line_end && !end_sequence)
20870         {
20871           op_code = read_1_byte (abfd, line_ptr);
20872           line_ptr += 1;
20873
20874           if (op_code >= lh->opcode_base)
20875             {
20876               /* Special opcode.  */
20877               state_machine.handle_special_opcode (op_code);
20878             }
20879           else switch (op_code)
20880             {
20881             case DW_LNS_extended_op:
20882               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20883                                                    &bytes_read);
20884               line_ptr += bytes_read;
20885               extended_end = line_ptr + extended_len;
20886               extended_op = read_1_byte (abfd, line_ptr);
20887               line_ptr += 1;
20888               switch (extended_op)
20889                 {
20890                 case DW_LNE_end_sequence:
20891                   state_machine.handle_end_sequence ();
20892                   end_sequence = true;
20893                   break;
20894                 case DW_LNE_set_address:
20895                   {
20896                     CORE_ADDR address
20897                       = read_address (abfd, line_ptr, cu, &bytes_read);
20898                     line_ptr += bytes_read;
20899
20900                     state_machine.check_line_address (cu, line_ptr,
20901                                                       lowpc, address);
20902                     state_machine.handle_set_address (baseaddr, address);
20903                   }
20904                   break;
20905                 case DW_LNE_define_file:
20906                   {
20907                     const char *cur_file;
20908                     unsigned int mod_time, length;
20909                     dir_index dindex;
20910
20911                     cur_file = read_direct_string (abfd, line_ptr,
20912                                                    &bytes_read);
20913                     line_ptr += bytes_read;
20914                     dindex = (dir_index)
20915                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20916                     line_ptr += bytes_read;
20917                     mod_time =
20918                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20919                     line_ptr += bytes_read;
20920                     length =
20921                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20922                     line_ptr += bytes_read;
20923                     lh->add_file_name (cur_file, dindex, mod_time, length);
20924                   }
20925                   break;
20926                 case DW_LNE_set_discriminator:
20927                   {
20928                     /* The discriminator is not interesting to the
20929                        debugger; just ignore it.  We still need to
20930                        check its value though:
20931                        if there are consecutive entries for the same
20932                        (non-prologue) line we want to coalesce them.
20933                        PR 17276.  */
20934                     unsigned int discr
20935                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20936                     line_ptr += bytes_read;
20937
20938                     state_machine.handle_set_discriminator (discr);
20939                   }
20940                   break;
20941                 default:
20942                   complaint (&symfile_complaints,
20943                              _("mangled .debug_line section"));
20944                   return;
20945                 }
20946               /* Make sure that we parsed the extended op correctly.  If e.g.
20947                  we expected a different address size than the producer used,
20948                  we may have read the wrong number of bytes.  */
20949               if (line_ptr != extended_end)
20950                 {
20951                   complaint (&symfile_complaints,
20952                              _("mangled .debug_line section"));
20953                   return;
20954                 }
20955               break;
20956             case DW_LNS_copy:
20957               state_machine.handle_copy ();
20958               break;
20959             case DW_LNS_advance_pc:
20960               {
20961                 CORE_ADDR adjust
20962                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20963                 line_ptr += bytes_read;
20964
20965                 state_machine.handle_advance_pc (adjust);
20966               }
20967               break;
20968             case DW_LNS_advance_line:
20969               {
20970                 int line_delta
20971                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20972                 line_ptr += bytes_read;
20973
20974                 state_machine.handle_advance_line (line_delta);
20975               }
20976               break;
20977             case DW_LNS_set_file:
20978               {
20979                 file_name_index file
20980                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20981                                                             &bytes_read);
20982                 line_ptr += bytes_read;
20983
20984                 state_machine.handle_set_file (file);
20985               }
20986               break;
20987             case DW_LNS_set_column:
20988               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20989               line_ptr += bytes_read;
20990               break;
20991             case DW_LNS_negate_stmt:
20992               state_machine.handle_negate_stmt ();
20993               break;
20994             case DW_LNS_set_basic_block:
20995               break;
20996             /* Add to the address register of the state machine the
20997                address increment value corresponding to special opcode
20998                255.  I.e., this value is scaled by the minimum
20999                instruction length since special opcode 255 would have
21000                scaled the increment.  */
21001             case DW_LNS_const_add_pc:
21002               state_machine.handle_const_add_pc ();
21003               break;
21004             case DW_LNS_fixed_advance_pc:
21005               {
21006                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21007                 line_ptr += 2;
21008
21009                 state_machine.handle_fixed_advance_pc (addr_adj);
21010               }
21011               break;
21012             default:
21013               {
21014                 /* Unknown standard opcode, ignore it.  */
21015                 int i;
21016
21017                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21018                   {
21019                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21020                     line_ptr += bytes_read;
21021                   }
21022               }
21023             }
21024         }
21025
21026       if (!end_sequence)
21027         dwarf2_debug_line_missing_end_sequence_complaint ();
21028
21029       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21030          in which case we still finish recording the last line).  */
21031       state_machine.record_line (true);
21032     }
21033 }
21034
21035 /* Decode the Line Number Program (LNP) for the given line_header
21036    structure and CU.  The actual information extracted and the type
21037    of structures created from the LNP depends on the value of PST.
21038
21039    1. If PST is NULL, then this procedure uses the data from the program
21040       to create all necessary symbol tables, and their linetables.
21041
21042    2. If PST is not NULL, this procedure reads the program to determine
21043       the list of files included by the unit represented by PST, and
21044       builds all the associated partial symbol tables.
21045
21046    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21047    It is used for relative paths in the line table.
21048    NOTE: When processing partial symtabs (pst != NULL),
21049    comp_dir == pst->dirname.
21050
21051    NOTE: It is important that psymtabs have the same file name (via strcmp)
21052    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21053    symtab we don't use it in the name of the psymtabs we create.
21054    E.g. expand_line_sal requires this when finding psymtabs to expand.
21055    A good testcase for this is mb-inline.exp.
21056
21057    LOWPC is the lowest address in CU (or 0 if not known).
21058
21059    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21060    for its PC<->lines mapping information.  Otherwise only the filename
21061    table is read in.  */
21062
21063 static void
21064 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21065                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21066                     CORE_ADDR lowpc, int decode_mapping)
21067 {
21068   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21069   const int decode_for_pst_p = (pst != NULL);
21070
21071   if (decode_mapping)
21072     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21073
21074   if (decode_for_pst_p)
21075     {
21076       int file_index;
21077
21078       /* Now that we're done scanning the Line Header Program, we can
21079          create the psymtab of each included file.  */
21080       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21081         if (lh->file_names[file_index].included_p == 1)
21082           {
21083             gdb::unique_xmalloc_ptr<char> name_holder;
21084             const char *include_name =
21085               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21086                                          &name_holder);
21087             if (include_name != NULL)
21088               dwarf2_create_include_psymtab (include_name, pst, objfile);
21089           }
21090     }
21091   else
21092     {
21093       /* Make sure a symtab is created for every file, even files
21094          which contain only variables (i.e. no code with associated
21095          line numbers).  */
21096       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21097       int i;
21098
21099       for (i = 0; i < lh->file_names.size (); i++)
21100         {
21101           file_entry &fe = lh->file_names[i];
21102
21103           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21104
21105           if (current_subfile->symtab == NULL)
21106             {
21107               current_subfile->symtab
21108                 = allocate_symtab (cust, current_subfile->name);
21109             }
21110           fe.symtab = current_subfile->symtab;
21111         }
21112     }
21113 }
21114
21115 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21116    DIRNAME the name of the source directory which contains FILENAME
21117    or NULL if not known.
21118    This routine tries to keep line numbers from identical absolute and
21119    relative file names in a common subfile.
21120
21121    Using the `list' example from the GDB testsuite, which resides in
21122    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21123    of /srcdir/list0.c yields the following debugging information for list0.c:
21124
21125    DW_AT_name:          /srcdir/list0.c
21126    DW_AT_comp_dir:      /compdir
21127    files.files[0].name: list0.h
21128    files.files[0].dir:  /srcdir
21129    files.files[1].name: list0.c
21130    files.files[1].dir:  /srcdir
21131
21132    The line number information for list0.c has to end up in a single
21133    subfile, so that `break /srcdir/list0.c:1' works as expected.
21134    start_subfile will ensure that this happens provided that we pass the
21135    concatenation of files.files[1].dir and files.files[1].name as the
21136    subfile's name.  */
21137
21138 static void
21139 dwarf2_start_subfile (const char *filename, const char *dirname)
21140 {
21141   char *copy = NULL;
21142
21143   /* In order not to lose the line information directory,
21144      we concatenate it to the filename when it makes sense.
21145      Note that the Dwarf3 standard says (speaking of filenames in line
21146      information): ``The directory index is ignored for file names
21147      that represent full path names''.  Thus ignoring dirname in the
21148      `else' branch below isn't an issue.  */
21149
21150   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21151     {
21152       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21153       filename = copy;
21154     }
21155
21156   start_subfile (filename);
21157
21158   if (copy != NULL)
21159     xfree (copy);
21160 }
21161
21162 /* Start a symtab for DWARF.
21163    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21164
21165 static struct compunit_symtab *
21166 dwarf2_start_symtab (struct dwarf2_cu *cu,
21167                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21168 {
21169   struct compunit_symtab *cust
21170     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21171                     low_pc, cu->language);
21172
21173   record_debugformat ("DWARF 2");
21174   record_producer (cu->producer);
21175
21176   /* We assume that we're processing GCC output.  */
21177   processing_gcc_compilation = 2;
21178
21179   cu->processing_has_namespace_info = 0;
21180
21181   return cust;
21182 }
21183
21184 static void
21185 var_decode_location (struct attribute *attr, struct symbol *sym,
21186                      struct dwarf2_cu *cu)
21187 {
21188   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21189   struct comp_unit_head *cu_header = &cu->header;
21190
21191   /* NOTE drow/2003-01-30: There used to be a comment and some special
21192      code here to turn a symbol with DW_AT_external and a
21193      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21194      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21195      with some versions of binutils) where shared libraries could have
21196      relocations against symbols in their debug information - the
21197      minimal symbol would have the right address, but the debug info
21198      would not.  It's no longer necessary, because we will explicitly
21199      apply relocations when we read in the debug information now.  */
21200
21201   /* A DW_AT_location attribute with no contents indicates that a
21202      variable has been optimized away.  */
21203   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21204     {
21205       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21206       return;
21207     }
21208
21209   /* Handle one degenerate form of location expression specially, to
21210      preserve GDB's previous behavior when section offsets are
21211      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21212      then mark this symbol as LOC_STATIC.  */
21213
21214   if (attr_form_is_block (attr)
21215       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21216            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21217           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21218               && (DW_BLOCK (attr)->size
21219                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21220     {
21221       unsigned int dummy;
21222
21223       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21224         SYMBOL_VALUE_ADDRESS (sym) =
21225           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21226       else
21227         SYMBOL_VALUE_ADDRESS (sym) =
21228           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21229       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21230       fixup_symbol_section (sym, objfile);
21231       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21232                                               SYMBOL_SECTION (sym));
21233       return;
21234     }
21235
21236   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21237      expression evaluator, and use LOC_COMPUTED only when necessary
21238      (i.e. when the value of a register or memory location is
21239      referenced, or a thread-local block, etc.).  Then again, it might
21240      not be worthwhile.  I'm assuming that it isn't unless performance
21241      or memory numbers show me otherwise.  */
21242
21243   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21244
21245   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21246     cu->has_loclist = 1;
21247 }
21248
21249 /* Given a pointer to a DWARF information entry, figure out if we need
21250    to make a symbol table entry for it, and if so, create a new entry
21251    and return a pointer to it.
21252    If TYPE is NULL, determine symbol type from the die, otherwise
21253    used the passed type.
21254    If SPACE is not NULL, use it to hold the new symbol.  If it is
21255    NULL, allocate a new symbol on the objfile's obstack.  */
21256
21257 static struct symbol *
21258 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21259             struct symbol *space)
21260 {
21261   struct dwarf2_per_objfile *dwarf2_per_objfile
21262     = cu->per_cu->dwarf2_per_objfile;
21263   struct objfile *objfile = dwarf2_per_objfile->objfile;
21264   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21265   struct symbol *sym = NULL;
21266   const char *name;
21267   struct attribute *attr = NULL;
21268   struct attribute *attr2 = NULL;
21269   CORE_ADDR baseaddr;
21270   struct pending **list_to_add = NULL;
21271
21272   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21273
21274   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21275
21276   name = dwarf2_name (die, cu);
21277   if (name)
21278     {
21279       const char *linkagename;
21280       int suppress_add = 0;
21281
21282       if (space)
21283         sym = space;
21284       else
21285         sym = allocate_symbol (objfile);
21286       OBJSTAT (objfile, n_syms++);
21287
21288       /* Cache this symbol's name and the name's demangled form (if any).  */
21289       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21290       linkagename = dwarf2_physname (name, die, cu);
21291       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21292
21293       /* Fortran does not have mangling standard and the mangling does differ
21294          between gfortran, iFort etc.  */
21295       if (cu->language == language_fortran
21296           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21297         symbol_set_demangled_name (&(sym->ginfo),
21298                                    dwarf2_full_name (name, die, cu),
21299                                    NULL);
21300
21301       /* Default assumptions.
21302          Use the passed type or decode it from the die.  */
21303       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21304       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21305       if (type != NULL)
21306         SYMBOL_TYPE (sym) = type;
21307       else
21308         SYMBOL_TYPE (sym) = die_type (die, cu);
21309       attr = dwarf2_attr (die,
21310                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21311                           cu);
21312       if (attr)
21313         {
21314           SYMBOL_LINE (sym) = DW_UNSND (attr);
21315         }
21316
21317       attr = dwarf2_attr (die,
21318                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21319                           cu);
21320       if (attr)
21321         {
21322           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21323           struct file_entry *fe;
21324
21325           if (cu->line_header != NULL)
21326             fe = cu->line_header->file_name_at (file_index);
21327           else
21328             fe = NULL;
21329
21330           if (fe == NULL)
21331             complaint (&symfile_complaints,
21332                        _("file index out of range"));
21333           else
21334             symbol_set_symtab (sym, fe->symtab);
21335         }
21336
21337       switch (die->tag)
21338         {
21339         case DW_TAG_label:
21340           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21341           if (attr)
21342             {
21343               CORE_ADDR addr;
21344
21345               addr = attr_value_as_address (attr);
21346               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21347               SYMBOL_VALUE_ADDRESS (sym) = addr;
21348             }
21349           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21350           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21351           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21352           add_symbol_to_list (sym, cu->list_in_scope);
21353           break;
21354         case DW_TAG_subprogram:
21355           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21356              finish_block.  */
21357           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21358           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21359           if ((attr2 && (DW_UNSND (attr2) != 0))
21360               || cu->language == language_ada)
21361             {
21362               /* Subprograms marked external are stored as a global symbol.
21363                  Ada subprograms, whether marked external or not, are always
21364                  stored as a global symbol, because we want to be able to
21365                  access them globally.  For instance, we want to be able
21366                  to break on a nested subprogram without having to
21367                  specify the context.  */
21368               list_to_add = &global_symbols;
21369             }
21370           else
21371             {
21372               list_to_add = cu->list_in_scope;
21373             }
21374           break;
21375         case DW_TAG_inlined_subroutine:
21376           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21377              finish_block.  */
21378           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21379           SYMBOL_INLINED (sym) = 1;
21380           list_to_add = cu->list_in_scope;
21381           break;
21382         case DW_TAG_template_value_param:
21383           suppress_add = 1;
21384           /* Fall through.  */
21385         case DW_TAG_constant:
21386         case DW_TAG_variable:
21387         case DW_TAG_member:
21388           /* Compilation with minimal debug info may result in
21389              variables with missing type entries.  Change the
21390              misleading `void' type to something sensible.  */
21391           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21392             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21393
21394           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21395           /* In the case of DW_TAG_member, we should only be called for
21396              static const members.  */
21397           if (die->tag == DW_TAG_member)
21398             {
21399               /* dwarf2_add_field uses die_is_declaration,
21400                  so we do the same.  */
21401               gdb_assert (die_is_declaration (die, cu));
21402               gdb_assert (attr);
21403             }
21404           if (attr)
21405             {
21406               dwarf2_const_value (attr, sym, cu);
21407               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21408               if (!suppress_add)
21409                 {
21410                   if (attr2 && (DW_UNSND (attr2) != 0))
21411                     list_to_add = &global_symbols;
21412                   else
21413                     list_to_add = cu->list_in_scope;
21414                 }
21415               break;
21416             }
21417           attr = dwarf2_attr (die, DW_AT_location, cu);
21418           if (attr)
21419             {
21420               var_decode_location (attr, sym, cu);
21421               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21422
21423               /* Fortran explicitly imports any global symbols to the local
21424                  scope by DW_TAG_common_block.  */
21425               if (cu->language == language_fortran && die->parent
21426                   && die->parent->tag == DW_TAG_common_block)
21427                 attr2 = NULL;
21428
21429               if (SYMBOL_CLASS (sym) == LOC_STATIC
21430                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21431                   && !dwarf2_per_objfile->has_section_at_zero)
21432                 {
21433                   /* When a static variable is eliminated by the linker,
21434                      the corresponding debug information is not stripped
21435                      out, but the variable address is set to null;
21436                      do not add such variables into symbol table.  */
21437                 }
21438               else if (attr2 && (DW_UNSND (attr2) != 0))
21439                 {
21440                   /* Workaround gfortran PR debug/40040 - it uses
21441                      DW_AT_location for variables in -fPIC libraries which may
21442                      get overriden by other libraries/executable and get
21443                      a different address.  Resolve it by the minimal symbol
21444                      which may come from inferior's executable using copy
21445                      relocation.  Make this workaround only for gfortran as for
21446                      other compilers GDB cannot guess the minimal symbol
21447                      Fortran mangling kind.  */
21448                   if (cu->language == language_fortran && die->parent
21449                       && die->parent->tag == DW_TAG_module
21450                       && cu->producer
21451                       && startswith (cu->producer, "GNU Fortran"))
21452                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21453
21454                   /* A variable with DW_AT_external is never static,
21455                      but it may be block-scoped.  */
21456                   list_to_add = (cu->list_in_scope == &file_symbols
21457                                  ? &global_symbols : cu->list_in_scope);
21458                 }
21459               else
21460                 list_to_add = cu->list_in_scope;
21461             }
21462           else
21463             {
21464               /* We do not know the address of this symbol.
21465                  If it is an external symbol and we have type information
21466                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21467                  The address of the variable will then be determined from
21468                  the minimal symbol table whenever the variable is
21469                  referenced.  */
21470               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21471
21472               /* Fortran explicitly imports any global symbols to the local
21473                  scope by DW_TAG_common_block.  */
21474               if (cu->language == language_fortran && die->parent
21475                   && die->parent->tag == DW_TAG_common_block)
21476                 {
21477                   /* SYMBOL_CLASS doesn't matter here because
21478                      read_common_block is going to reset it.  */
21479                   if (!suppress_add)
21480                     list_to_add = cu->list_in_scope;
21481                 }
21482               else if (attr2 && (DW_UNSND (attr2) != 0)
21483                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21484                 {
21485                   /* A variable with DW_AT_external is never static, but it
21486                      may be block-scoped.  */
21487                   list_to_add = (cu->list_in_scope == &file_symbols
21488                                  ? &global_symbols : cu->list_in_scope);
21489
21490                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21491                 }
21492               else if (!die_is_declaration (die, cu))
21493                 {
21494                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21495                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21496                   if (!suppress_add)
21497                     list_to_add = cu->list_in_scope;
21498                 }
21499             }
21500           break;
21501         case DW_TAG_formal_parameter:
21502           /* If we are inside a function, mark this as an argument.  If
21503              not, we might be looking at an argument to an inlined function
21504              when we do not have enough information to show inlined frames;
21505              pretend it's a local variable in that case so that the user can
21506              still see it.  */
21507           if (context_stack_depth > 0
21508               && context_stack[context_stack_depth - 1].name != NULL)
21509             SYMBOL_IS_ARGUMENT (sym) = 1;
21510           attr = dwarf2_attr (die, DW_AT_location, cu);
21511           if (attr)
21512             {
21513               var_decode_location (attr, sym, cu);
21514             }
21515           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21516           if (attr)
21517             {
21518               dwarf2_const_value (attr, sym, cu);
21519             }
21520
21521           list_to_add = cu->list_in_scope;
21522           break;
21523         case DW_TAG_unspecified_parameters:
21524           /* From varargs functions; gdb doesn't seem to have any
21525              interest in this information, so just ignore it for now.
21526              (FIXME?) */
21527           break;
21528         case DW_TAG_template_type_param:
21529           suppress_add = 1;
21530           /* Fall through.  */
21531         case DW_TAG_class_type:
21532         case DW_TAG_interface_type:
21533         case DW_TAG_structure_type:
21534         case DW_TAG_union_type:
21535         case DW_TAG_set_type:
21536         case DW_TAG_enumeration_type:
21537           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21538           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21539
21540           {
21541             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21542                really ever be static objects: otherwise, if you try
21543                to, say, break of a class's method and you're in a file
21544                which doesn't mention that class, it won't work unless
21545                the check for all static symbols in lookup_symbol_aux
21546                saves you.  See the OtherFileClass tests in
21547                gdb.c++/namespace.exp.  */
21548
21549             if (!suppress_add)
21550               {
21551                 list_to_add = (cu->list_in_scope == &file_symbols
21552                                && cu->language == language_cplus
21553                                ? &global_symbols : cu->list_in_scope);
21554
21555                 /* The semantics of C++ state that "struct foo {
21556                    ... }" also defines a typedef for "foo".  */
21557                 if (cu->language == language_cplus
21558                     || cu->language == language_ada
21559                     || cu->language == language_d
21560                     || cu->language == language_rust)
21561                   {
21562                     /* The symbol's name is already allocated along
21563                        with this objfile, so we don't need to
21564                        duplicate it for the type.  */
21565                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21566                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21567                   }
21568               }
21569           }
21570           break;
21571         case DW_TAG_typedef:
21572           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21573           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21574           list_to_add = cu->list_in_scope;
21575           break;
21576         case DW_TAG_base_type:
21577         case DW_TAG_subrange_type:
21578           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21579           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21580           list_to_add = cu->list_in_scope;
21581           break;
21582         case DW_TAG_enumerator:
21583           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21584           if (attr)
21585             {
21586               dwarf2_const_value (attr, sym, cu);
21587             }
21588           {
21589             /* NOTE: carlton/2003-11-10: See comment above in the
21590                DW_TAG_class_type, etc. block.  */
21591
21592             list_to_add = (cu->list_in_scope == &file_symbols
21593                            && cu->language == language_cplus
21594                            ? &global_symbols : cu->list_in_scope);
21595           }
21596           break;
21597         case DW_TAG_imported_declaration:
21598         case DW_TAG_namespace:
21599           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21600           list_to_add = &global_symbols;
21601           break;
21602         case DW_TAG_module:
21603           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21604           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21605           list_to_add = &global_symbols;
21606           break;
21607         case DW_TAG_common_block:
21608           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21609           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21610           add_symbol_to_list (sym, cu->list_in_scope);
21611           break;
21612         default:
21613           /* Not a tag we recognize.  Hopefully we aren't processing
21614              trash data, but since we must specifically ignore things
21615              we don't recognize, there is nothing else we should do at
21616              this point.  */
21617           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21618                      dwarf_tag_name (die->tag));
21619           break;
21620         }
21621
21622       if (suppress_add)
21623         {
21624           sym->hash_next = objfile->template_symbols;
21625           objfile->template_symbols = sym;
21626           list_to_add = NULL;
21627         }
21628
21629       if (list_to_add != NULL)
21630         add_symbol_to_list (sym, list_to_add);
21631
21632       /* For the benefit of old versions of GCC, check for anonymous
21633          namespaces based on the demangled name.  */
21634       if (!cu->processing_has_namespace_info
21635           && cu->language == language_cplus)
21636         cp_scan_for_anonymous_namespaces (sym, objfile);
21637     }
21638   return (sym);
21639 }
21640
21641 /* Given an attr with a DW_FORM_dataN value in host byte order,
21642    zero-extend it as appropriate for the symbol's type.  The DWARF
21643    standard (v4) is not entirely clear about the meaning of using
21644    DW_FORM_dataN for a constant with a signed type, where the type is
21645    wider than the data.  The conclusion of a discussion on the DWARF
21646    list was that this is unspecified.  We choose to always zero-extend
21647    because that is the interpretation long in use by GCC.  */
21648
21649 static gdb_byte *
21650 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21651                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21652 {
21653   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21654   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21655                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21656   LONGEST l = DW_UNSND (attr);
21657
21658   if (bits < sizeof (*value) * 8)
21659     {
21660       l &= ((LONGEST) 1 << bits) - 1;
21661       *value = l;
21662     }
21663   else if (bits == sizeof (*value) * 8)
21664     *value = l;
21665   else
21666     {
21667       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21668       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21669       return bytes;
21670     }
21671
21672   return NULL;
21673 }
21674
21675 /* Read a constant value from an attribute.  Either set *VALUE, or if
21676    the value does not fit in *VALUE, set *BYTES - either already
21677    allocated on the objfile obstack, or newly allocated on OBSTACK,
21678    or, set *BATON, if we translated the constant to a location
21679    expression.  */
21680
21681 static void
21682 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21683                          const char *name, struct obstack *obstack,
21684                          struct dwarf2_cu *cu,
21685                          LONGEST *value, const gdb_byte **bytes,
21686                          struct dwarf2_locexpr_baton **baton)
21687 {
21688   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21689   struct comp_unit_head *cu_header = &cu->header;
21690   struct dwarf_block *blk;
21691   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21692                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21693
21694   *value = 0;
21695   *bytes = NULL;
21696   *baton = NULL;
21697
21698   switch (attr->form)
21699     {
21700     case DW_FORM_addr:
21701     case DW_FORM_GNU_addr_index:
21702       {
21703         gdb_byte *data;
21704
21705         if (TYPE_LENGTH (type) != cu_header->addr_size)
21706           dwarf2_const_value_length_mismatch_complaint (name,
21707                                                         cu_header->addr_size,
21708                                                         TYPE_LENGTH (type));
21709         /* Symbols of this form are reasonably rare, so we just
21710            piggyback on the existing location code rather than writing
21711            a new implementation of symbol_computed_ops.  */
21712         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21713         (*baton)->per_cu = cu->per_cu;
21714         gdb_assert ((*baton)->per_cu);
21715
21716         (*baton)->size = 2 + cu_header->addr_size;
21717         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21718         (*baton)->data = data;
21719
21720         data[0] = DW_OP_addr;
21721         store_unsigned_integer (&data[1], cu_header->addr_size,
21722                                 byte_order, DW_ADDR (attr));
21723         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21724       }
21725       break;
21726     case DW_FORM_string:
21727     case DW_FORM_strp:
21728     case DW_FORM_GNU_str_index:
21729     case DW_FORM_GNU_strp_alt:
21730       /* DW_STRING is already allocated on the objfile obstack, point
21731          directly to it.  */
21732       *bytes = (const gdb_byte *) DW_STRING (attr);
21733       break;
21734     case DW_FORM_block1:
21735     case DW_FORM_block2:
21736     case DW_FORM_block4:
21737     case DW_FORM_block:
21738     case DW_FORM_exprloc:
21739     case DW_FORM_data16:
21740       blk = DW_BLOCK (attr);
21741       if (TYPE_LENGTH (type) != blk->size)
21742         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21743                                                       TYPE_LENGTH (type));
21744       *bytes = blk->data;
21745       break;
21746
21747       /* The DW_AT_const_value attributes are supposed to carry the
21748          symbol's value "represented as it would be on the target
21749          architecture."  By the time we get here, it's already been
21750          converted to host endianness, so we just need to sign- or
21751          zero-extend it as appropriate.  */
21752     case DW_FORM_data1:
21753       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21754       break;
21755     case DW_FORM_data2:
21756       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21757       break;
21758     case DW_FORM_data4:
21759       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21760       break;
21761     case DW_FORM_data8:
21762       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21763       break;
21764
21765     case DW_FORM_sdata:
21766     case DW_FORM_implicit_const:
21767       *value = DW_SND (attr);
21768       break;
21769
21770     case DW_FORM_udata:
21771       *value = DW_UNSND (attr);
21772       break;
21773
21774     default:
21775       complaint (&symfile_complaints,
21776                  _("unsupported const value attribute form: '%s'"),
21777                  dwarf_form_name (attr->form));
21778       *value = 0;
21779       break;
21780     }
21781 }
21782
21783
21784 /* Copy constant value from an attribute to a symbol.  */
21785
21786 static void
21787 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21788                     struct dwarf2_cu *cu)
21789 {
21790   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21791   LONGEST value;
21792   const gdb_byte *bytes;
21793   struct dwarf2_locexpr_baton *baton;
21794
21795   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21796                            SYMBOL_PRINT_NAME (sym),
21797                            &objfile->objfile_obstack, cu,
21798                            &value, &bytes, &baton);
21799
21800   if (baton != NULL)
21801     {
21802       SYMBOL_LOCATION_BATON (sym) = baton;
21803       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21804     }
21805   else if (bytes != NULL)
21806      {
21807       SYMBOL_VALUE_BYTES (sym) = bytes;
21808       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21809     }
21810   else
21811     {
21812       SYMBOL_VALUE (sym) = value;
21813       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21814     }
21815 }
21816
21817 /* Return the type of the die in question using its DW_AT_type attribute.  */
21818
21819 static struct type *
21820 die_type (struct die_info *die, struct dwarf2_cu *cu)
21821 {
21822   struct attribute *type_attr;
21823
21824   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21825   if (!type_attr)
21826     {
21827       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21828       /* A missing DW_AT_type represents a void type.  */
21829       return objfile_type (objfile)->builtin_void;
21830     }
21831
21832   return lookup_die_type (die, type_attr, cu);
21833 }
21834
21835 /* True iff CU's producer generates GNAT Ada auxiliary information
21836    that allows to find parallel types through that information instead
21837    of having to do expensive parallel lookups by type name.  */
21838
21839 static int
21840 need_gnat_info (struct dwarf2_cu *cu)
21841 {
21842   /* Assume that the Ada compiler was GNAT, which always produces
21843      the auxiliary information.  */
21844   return (cu->language == language_ada);
21845 }
21846
21847 /* Return the auxiliary type of the die in question using its
21848    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21849    attribute is not present.  */
21850
21851 static struct type *
21852 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21853 {
21854   struct attribute *type_attr;
21855
21856   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21857   if (!type_attr)
21858     return NULL;
21859
21860   return lookup_die_type (die, type_attr, cu);
21861 }
21862
21863 /* If DIE has a descriptive_type attribute, then set the TYPE's
21864    descriptive type accordingly.  */
21865
21866 static void
21867 set_descriptive_type (struct type *type, struct die_info *die,
21868                       struct dwarf2_cu *cu)
21869 {
21870   struct type *descriptive_type = die_descriptive_type (die, cu);
21871
21872   if (descriptive_type)
21873     {
21874       ALLOCATE_GNAT_AUX_TYPE (type);
21875       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21876     }
21877 }
21878
21879 /* Return the containing type of the die in question using its
21880    DW_AT_containing_type attribute.  */
21881
21882 static struct type *
21883 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21884 {
21885   struct attribute *type_attr;
21886   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21887
21888   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21889   if (!type_attr)
21890     error (_("Dwarf Error: Problem turning containing type into gdb type "
21891              "[in module %s]"), objfile_name (objfile));
21892
21893   return lookup_die_type (die, type_attr, cu);
21894 }
21895
21896 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21897
21898 static struct type *
21899 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21900 {
21901   struct dwarf2_per_objfile *dwarf2_per_objfile
21902     = cu->per_cu->dwarf2_per_objfile;
21903   struct objfile *objfile = dwarf2_per_objfile->objfile;
21904   char *message, *saved;
21905
21906   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
21907                         objfile_name (objfile),
21908                         to_underlying (cu->header.sect_off),
21909                         to_underlying (die->sect_off));
21910   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21911                                   message, strlen (message));
21912   xfree (message);
21913
21914   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21915 }
21916
21917 /* Look up the type of DIE in CU using its type attribute ATTR.
21918    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21919    DW_AT_containing_type.
21920    If there is no type substitute an error marker.  */
21921
21922 static struct type *
21923 lookup_die_type (struct die_info *die, const struct attribute *attr,
21924                  struct dwarf2_cu *cu)
21925 {
21926   struct dwarf2_per_objfile *dwarf2_per_objfile
21927     = cu->per_cu->dwarf2_per_objfile;
21928   struct objfile *objfile = dwarf2_per_objfile->objfile;
21929   struct type *this_type;
21930
21931   gdb_assert (attr->name == DW_AT_type
21932               || attr->name == DW_AT_GNAT_descriptive_type
21933               || attr->name == DW_AT_containing_type);
21934
21935   /* First see if we have it cached.  */
21936
21937   if (attr->form == DW_FORM_GNU_ref_alt)
21938     {
21939       struct dwarf2_per_cu_data *per_cu;
21940       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21941
21942       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21943                                                  dwarf2_per_objfile);
21944       this_type = get_die_type_at_offset (sect_off, per_cu);
21945     }
21946   else if (attr_form_is_ref (attr))
21947     {
21948       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21949
21950       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21951     }
21952   else if (attr->form == DW_FORM_ref_sig8)
21953     {
21954       ULONGEST signature = DW_SIGNATURE (attr);
21955
21956       return get_signatured_type (die, signature, cu);
21957     }
21958   else
21959     {
21960       complaint (&symfile_complaints,
21961                  _("Dwarf Error: Bad type attribute %s in DIE"
21962                    " at 0x%x [in module %s]"),
21963                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
21964                  objfile_name (objfile));
21965       return build_error_marker_type (cu, die);
21966     }
21967
21968   /* If not cached we need to read it in.  */
21969
21970   if (this_type == NULL)
21971     {
21972       struct die_info *type_die = NULL;
21973       struct dwarf2_cu *type_cu = cu;
21974
21975       if (attr_form_is_ref (attr))
21976         type_die = follow_die_ref (die, attr, &type_cu);
21977       if (type_die == NULL)
21978         return build_error_marker_type (cu, die);
21979       /* If we find the type now, it's probably because the type came
21980          from an inter-CU reference and the type's CU got expanded before
21981          ours.  */
21982       this_type = read_type_die (type_die, type_cu);
21983     }
21984
21985   /* If we still don't have a type use an error marker.  */
21986
21987   if (this_type == NULL)
21988     return build_error_marker_type (cu, die);
21989
21990   return this_type;
21991 }
21992
21993 /* Return the type in DIE, CU.
21994    Returns NULL for invalid types.
21995
21996    This first does a lookup in die_type_hash,
21997    and only reads the die in if necessary.
21998
21999    NOTE: This can be called when reading in partial or full symbols.  */
22000
22001 static struct type *
22002 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22003 {
22004   struct type *this_type;
22005
22006   this_type = get_die_type (die, cu);
22007   if (this_type)
22008     return this_type;
22009
22010   return read_type_die_1 (die, cu);
22011 }
22012
22013 /* Read the type in DIE, CU.
22014    Returns NULL for invalid types.  */
22015
22016 static struct type *
22017 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22018 {
22019   struct type *this_type = NULL;
22020
22021   switch (die->tag)
22022     {
22023     case DW_TAG_class_type:
22024     case DW_TAG_interface_type:
22025     case DW_TAG_structure_type:
22026     case DW_TAG_union_type:
22027       this_type = read_structure_type (die, cu);
22028       break;
22029     case DW_TAG_enumeration_type:
22030       this_type = read_enumeration_type (die, cu);
22031       break;
22032     case DW_TAG_subprogram:
22033     case DW_TAG_subroutine_type:
22034     case DW_TAG_inlined_subroutine:
22035       this_type = read_subroutine_type (die, cu);
22036       break;
22037     case DW_TAG_array_type:
22038       this_type = read_array_type (die, cu);
22039       break;
22040     case DW_TAG_set_type:
22041       this_type = read_set_type (die, cu);
22042       break;
22043     case DW_TAG_pointer_type:
22044       this_type = read_tag_pointer_type (die, cu);
22045       break;
22046     case DW_TAG_ptr_to_member_type:
22047       this_type = read_tag_ptr_to_member_type (die, cu);
22048       break;
22049     case DW_TAG_reference_type:
22050       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22051       break;
22052     case DW_TAG_rvalue_reference_type:
22053       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22054       break;
22055     case DW_TAG_const_type:
22056       this_type = read_tag_const_type (die, cu);
22057       break;
22058     case DW_TAG_volatile_type:
22059       this_type = read_tag_volatile_type (die, cu);
22060       break;
22061     case DW_TAG_restrict_type:
22062       this_type = read_tag_restrict_type (die, cu);
22063       break;
22064     case DW_TAG_string_type:
22065       this_type = read_tag_string_type (die, cu);
22066       break;
22067     case DW_TAG_typedef:
22068       this_type = read_typedef (die, cu);
22069       break;
22070     case DW_TAG_subrange_type:
22071       this_type = read_subrange_type (die, cu);
22072       break;
22073     case DW_TAG_base_type:
22074       this_type = read_base_type (die, cu);
22075       break;
22076     case DW_TAG_unspecified_type:
22077       this_type = read_unspecified_type (die, cu);
22078       break;
22079     case DW_TAG_namespace:
22080       this_type = read_namespace_type (die, cu);
22081       break;
22082     case DW_TAG_module:
22083       this_type = read_module_type (die, cu);
22084       break;
22085     case DW_TAG_atomic_type:
22086       this_type = read_tag_atomic_type (die, cu);
22087       break;
22088     default:
22089       complaint (&symfile_complaints,
22090                  _("unexpected tag in read_type_die: '%s'"),
22091                  dwarf_tag_name (die->tag));
22092       break;
22093     }
22094
22095   return this_type;
22096 }
22097
22098 /* See if we can figure out if the class lives in a namespace.  We do
22099    this by looking for a member function; its demangled name will
22100    contain namespace info, if there is any.
22101    Return the computed name or NULL.
22102    Space for the result is allocated on the objfile's obstack.
22103    This is the full-die version of guess_partial_die_structure_name.
22104    In this case we know DIE has no useful parent.  */
22105
22106 static char *
22107 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22108 {
22109   struct die_info *spec_die;
22110   struct dwarf2_cu *spec_cu;
22111   struct die_info *child;
22112   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22113
22114   spec_cu = cu;
22115   spec_die = die_specification (die, &spec_cu);
22116   if (spec_die != NULL)
22117     {
22118       die = spec_die;
22119       cu = spec_cu;
22120     }
22121
22122   for (child = die->child;
22123        child != NULL;
22124        child = child->sibling)
22125     {
22126       if (child->tag == DW_TAG_subprogram)
22127         {
22128           const char *linkage_name = dw2_linkage_name (child, cu);
22129
22130           if (linkage_name != NULL)
22131             {
22132               char *actual_name
22133                 = language_class_name_from_physname (cu->language_defn,
22134                                                      linkage_name);
22135               char *name = NULL;
22136
22137               if (actual_name != NULL)
22138                 {
22139                   const char *die_name = dwarf2_name (die, cu);
22140
22141                   if (die_name != NULL
22142                       && strcmp (die_name, actual_name) != 0)
22143                     {
22144                       /* Strip off the class name from the full name.
22145                          We want the prefix.  */
22146                       int die_name_len = strlen (die_name);
22147                       int actual_name_len = strlen (actual_name);
22148
22149                       /* Test for '::' as a sanity check.  */
22150                       if (actual_name_len > die_name_len + 2
22151                           && actual_name[actual_name_len
22152                                          - die_name_len - 1] == ':')
22153                         name = (char *) obstack_copy0 (
22154                           &objfile->per_bfd->storage_obstack,
22155                           actual_name, actual_name_len - die_name_len - 2);
22156                     }
22157                 }
22158               xfree (actual_name);
22159               return name;
22160             }
22161         }
22162     }
22163
22164   return NULL;
22165 }
22166
22167 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22168    prefix part in such case.  See
22169    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22170
22171 static const char *
22172 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22173 {
22174   struct attribute *attr;
22175   const char *base;
22176
22177   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22178       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22179     return NULL;
22180
22181   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22182     return NULL;
22183
22184   attr = dw2_linkage_name_attr (die, cu);
22185   if (attr == NULL || DW_STRING (attr) == NULL)
22186     return NULL;
22187
22188   /* dwarf2_name had to be already called.  */
22189   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22190
22191   /* Strip the base name, keep any leading namespaces/classes.  */
22192   base = strrchr (DW_STRING (attr), ':');
22193   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22194     return "";
22195
22196   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22197   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22198                                  DW_STRING (attr),
22199                                  &base[-1] - DW_STRING (attr));
22200 }
22201
22202 /* Return the name of the namespace/class that DIE is defined within,
22203    or "" if we can't tell.  The caller should not xfree the result.
22204
22205    For example, if we're within the method foo() in the following
22206    code:
22207
22208    namespace N {
22209      class C {
22210        void foo () {
22211        }
22212      };
22213    }
22214
22215    then determine_prefix on foo's die will return "N::C".  */
22216
22217 static const char *
22218 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22219 {
22220   struct dwarf2_per_objfile *dwarf2_per_objfile
22221     = cu->per_cu->dwarf2_per_objfile;
22222   struct die_info *parent, *spec_die;
22223   struct dwarf2_cu *spec_cu;
22224   struct type *parent_type;
22225   const char *retval;
22226
22227   if (cu->language != language_cplus
22228       && cu->language != language_fortran && cu->language != language_d
22229       && cu->language != language_rust)
22230     return "";
22231
22232   retval = anonymous_struct_prefix (die, cu);
22233   if (retval)
22234     return retval;
22235
22236   /* We have to be careful in the presence of DW_AT_specification.
22237      For example, with GCC 3.4, given the code
22238
22239      namespace N {
22240        void foo() {
22241          // Definition of N::foo.
22242        }
22243      }
22244
22245      then we'll have a tree of DIEs like this:
22246
22247      1: DW_TAG_compile_unit
22248        2: DW_TAG_namespace        // N
22249          3: DW_TAG_subprogram     // declaration of N::foo
22250        4: DW_TAG_subprogram       // definition of N::foo
22251             DW_AT_specification   // refers to die #3
22252
22253      Thus, when processing die #4, we have to pretend that we're in
22254      the context of its DW_AT_specification, namely the contex of die
22255      #3.  */
22256   spec_cu = cu;
22257   spec_die = die_specification (die, &spec_cu);
22258   if (spec_die == NULL)
22259     parent = die->parent;
22260   else
22261     {
22262       parent = spec_die->parent;
22263       cu = spec_cu;
22264     }
22265
22266   if (parent == NULL)
22267     return "";
22268   else if (parent->building_fullname)
22269     {
22270       const char *name;
22271       const char *parent_name;
22272
22273       /* It has been seen on RealView 2.2 built binaries,
22274          DW_TAG_template_type_param types actually _defined_ as
22275          children of the parent class:
22276
22277          enum E {};
22278          template class <class Enum> Class{};
22279          Class<enum E> class_e;
22280
22281          1: DW_TAG_class_type (Class)
22282            2: DW_TAG_enumeration_type (E)
22283              3: DW_TAG_enumerator (enum1:0)
22284              3: DW_TAG_enumerator (enum2:1)
22285              ...
22286            2: DW_TAG_template_type_param
22287               DW_AT_type  DW_FORM_ref_udata (E)
22288
22289          Besides being broken debug info, it can put GDB into an
22290          infinite loop.  Consider:
22291
22292          When we're building the full name for Class<E>, we'll start
22293          at Class, and go look over its template type parameters,
22294          finding E.  We'll then try to build the full name of E, and
22295          reach here.  We're now trying to build the full name of E,
22296          and look over the parent DIE for containing scope.  In the
22297          broken case, if we followed the parent DIE of E, we'd again
22298          find Class, and once again go look at its template type
22299          arguments, etc., etc.  Simply don't consider such parent die
22300          as source-level parent of this die (it can't be, the language
22301          doesn't allow it), and break the loop here.  */
22302       name = dwarf2_name (die, cu);
22303       parent_name = dwarf2_name (parent, cu);
22304       complaint (&symfile_complaints,
22305                  _("template param type '%s' defined within parent '%s'"),
22306                  name ? name : "<unknown>",
22307                  parent_name ? parent_name : "<unknown>");
22308       return "";
22309     }
22310   else
22311     switch (parent->tag)
22312       {
22313       case DW_TAG_namespace:
22314         parent_type = read_type_die (parent, cu);
22315         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22316            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22317            Work around this problem here.  */
22318         if (cu->language == language_cplus
22319             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22320           return "";
22321         /* We give a name to even anonymous namespaces.  */
22322         return TYPE_TAG_NAME (parent_type);
22323       case DW_TAG_class_type:
22324       case DW_TAG_interface_type:
22325       case DW_TAG_structure_type:
22326       case DW_TAG_union_type:
22327       case DW_TAG_module:
22328         parent_type = read_type_die (parent, cu);
22329         if (TYPE_TAG_NAME (parent_type) != NULL)
22330           return TYPE_TAG_NAME (parent_type);
22331         else
22332           /* An anonymous structure is only allowed non-static data
22333              members; no typedefs, no member functions, et cetera.
22334              So it does not need a prefix.  */
22335           return "";
22336       case DW_TAG_compile_unit:
22337       case DW_TAG_partial_unit:
22338         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22339         if (cu->language == language_cplus
22340             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22341             && die->child != NULL
22342             && (die->tag == DW_TAG_class_type
22343                 || die->tag == DW_TAG_structure_type
22344                 || die->tag == DW_TAG_union_type))
22345           {
22346             char *name = guess_full_die_structure_name (die, cu);
22347             if (name != NULL)
22348               return name;
22349           }
22350         return "";
22351       case DW_TAG_enumeration_type:
22352         parent_type = read_type_die (parent, cu);
22353         if (TYPE_DECLARED_CLASS (parent_type))
22354           {
22355             if (TYPE_TAG_NAME (parent_type) != NULL)
22356               return TYPE_TAG_NAME (parent_type);
22357             return "";
22358           }
22359         /* Fall through.  */
22360       default:
22361         return determine_prefix (parent, cu);
22362       }
22363 }
22364
22365 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22366    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22367    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22368    an obconcat, otherwise allocate storage for the result.  The CU argument is
22369    used to determine the language and hence, the appropriate separator.  */
22370
22371 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22372
22373 static char *
22374 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22375                  int physname, struct dwarf2_cu *cu)
22376 {
22377   const char *lead = "";
22378   const char *sep;
22379
22380   if (suffix == NULL || suffix[0] == '\0'
22381       || prefix == NULL || prefix[0] == '\0')
22382     sep = "";
22383   else if (cu->language == language_d)
22384     {
22385       /* For D, the 'main' function could be defined in any module, but it
22386          should never be prefixed.  */
22387       if (strcmp (suffix, "D main") == 0)
22388         {
22389           prefix = "";
22390           sep = "";
22391         }
22392       else
22393         sep = ".";
22394     }
22395   else if (cu->language == language_fortran && physname)
22396     {
22397       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22398          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22399
22400       lead = "__";
22401       sep = "_MOD_";
22402     }
22403   else
22404     sep = "::";
22405
22406   if (prefix == NULL)
22407     prefix = "";
22408   if (suffix == NULL)
22409     suffix = "";
22410
22411   if (obs == NULL)
22412     {
22413       char *retval
22414         = ((char *)
22415            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22416
22417       strcpy (retval, lead);
22418       strcat (retval, prefix);
22419       strcat (retval, sep);
22420       strcat (retval, suffix);
22421       return retval;
22422     }
22423   else
22424     {
22425       /* We have an obstack.  */
22426       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22427     }
22428 }
22429
22430 /* Return sibling of die, NULL if no sibling.  */
22431
22432 static struct die_info *
22433 sibling_die (struct die_info *die)
22434 {
22435   return die->sibling;
22436 }
22437
22438 /* Get name of a die, return NULL if not found.  */
22439
22440 static const char *
22441 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22442                           struct obstack *obstack)
22443 {
22444   if (name && cu->language == language_cplus)
22445     {
22446       std::string canon_name = cp_canonicalize_string (name);
22447
22448       if (!canon_name.empty ())
22449         {
22450           if (canon_name != name)
22451             name = (const char *) obstack_copy0 (obstack,
22452                                                  canon_name.c_str (),
22453                                                  canon_name.length ());
22454         }
22455     }
22456
22457   return name;
22458 }
22459
22460 /* Get name of a die, return NULL if not found.
22461    Anonymous namespaces are converted to their magic string.  */
22462
22463 static const char *
22464 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22465 {
22466   struct attribute *attr;
22467   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22468
22469   attr = dwarf2_attr (die, DW_AT_name, cu);
22470   if ((!attr || !DW_STRING (attr))
22471       && die->tag != DW_TAG_namespace
22472       && die->tag != DW_TAG_class_type
22473       && die->tag != DW_TAG_interface_type
22474       && die->tag != DW_TAG_structure_type
22475       && die->tag != DW_TAG_union_type)
22476     return NULL;
22477
22478   switch (die->tag)
22479     {
22480     case DW_TAG_compile_unit:
22481     case DW_TAG_partial_unit:
22482       /* Compilation units have a DW_AT_name that is a filename, not
22483          a source language identifier.  */
22484     case DW_TAG_enumeration_type:
22485     case DW_TAG_enumerator:
22486       /* These tags always have simple identifiers already; no need
22487          to canonicalize them.  */
22488       return DW_STRING (attr);
22489
22490     case DW_TAG_namespace:
22491       if (attr != NULL && DW_STRING (attr) != NULL)
22492         return DW_STRING (attr);
22493       return CP_ANONYMOUS_NAMESPACE_STR;
22494
22495     case DW_TAG_class_type:
22496     case DW_TAG_interface_type:
22497     case DW_TAG_structure_type:
22498     case DW_TAG_union_type:
22499       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22500          structures or unions.  These were of the form "._%d" in GCC 4.1,
22501          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22502          and GCC 4.4.  We work around this problem by ignoring these.  */
22503       if (attr && DW_STRING (attr)
22504           && (startswith (DW_STRING (attr), "._")
22505               || startswith (DW_STRING (attr), "<anonymous")))
22506         return NULL;
22507
22508       /* GCC might emit a nameless typedef that has a linkage name.  See
22509          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22510       if (!attr || DW_STRING (attr) == NULL)
22511         {
22512           char *demangled = NULL;
22513
22514           attr = dw2_linkage_name_attr (die, cu);
22515           if (attr == NULL || DW_STRING (attr) == NULL)
22516             return NULL;
22517
22518           /* Avoid demangling DW_STRING (attr) the second time on a second
22519              call for the same DIE.  */
22520           if (!DW_STRING_IS_CANONICAL (attr))
22521             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22522
22523           if (demangled)
22524             {
22525               const char *base;
22526
22527               /* FIXME: we already did this for the partial symbol... */
22528               DW_STRING (attr)
22529                 = ((const char *)
22530                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22531                                   demangled, strlen (demangled)));
22532               DW_STRING_IS_CANONICAL (attr) = 1;
22533               xfree (demangled);
22534
22535               /* Strip any leading namespaces/classes, keep only the base name.
22536                  DW_AT_name for named DIEs does not contain the prefixes.  */
22537               base = strrchr (DW_STRING (attr), ':');
22538               if (base && base > DW_STRING (attr) && base[-1] == ':')
22539                 return &base[1];
22540               else
22541                 return DW_STRING (attr);
22542             }
22543         }
22544       break;
22545
22546     default:
22547       break;
22548     }
22549
22550   if (!DW_STRING_IS_CANONICAL (attr))
22551     {
22552       DW_STRING (attr)
22553         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22554                                     &objfile->per_bfd->storage_obstack);
22555       DW_STRING_IS_CANONICAL (attr) = 1;
22556     }
22557   return DW_STRING (attr);
22558 }
22559
22560 /* Return the die that this die in an extension of, or NULL if there
22561    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22562    containing the return value on output.  */
22563
22564 static struct die_info *
22565 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22566 {
22567   struct attribute *attr;
22568
22569   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22570   if (attr == NULL)
22571     return NULL;
22572
22573   return follow_die_ref (die, attr, ext_cu);
22574 }
22575
22576 /* Convert a DIE tag into its string name.  */
22577
22578 static const char *
22579 dwarf_tag_name (unsigned tag)
22580 {
22581   const char *name = get_DW_TAG_name (tag);
22582
22583   if (name == NULL)
22584     return "DW_TAG_<unknown>";
22585
22586   return name;
22587 }
22588
22589 /* Convert a DWARF attribute code into its string name.  */
22590
22591 static const char *
22592 dwarf_attr_name (unsigned attr)
22593 {
22594   const char *name;
22595
22596 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22597   if (attr == DW_AT_MIPS_fde)
22598     return "DW_AT_MIPS_fde";
22599 #else
22600   if (attr == DW_AT_HP_block_index)
22601     return "DW_AT_HP_block_index";
22602 #endif
22603
22604   name = get_DW_AT_name (attr);
22605
22606   if (name == NULL)
22607     return "DW_AT_<unknown>";
22608
22609   return name;
22610 }
22611
22612 /* Convert a DWARF value form code into its string name.  */
22613
22614 static const char *
22615 dwarf_form_name (unsigned form)
22616 {
22617   const char *name = get_DW_FORM_name (form);
22618
22619   if (name == NULL)
22620     return "DW_FORM_<unknown>";
22621
22622   return name;
22623 }
22624
22625 static const char *
22626 dwarf_bool_name (unsigned mybool)
22627 {
22628   if (mybool)
22629     return "TRUE";
22630   else
22631     return "FALSE";
22632 }
22633
22634 /* Convert a DWARF type code into its string name.  */
22635
22636 static const char *
22637 dwarf_type_encoding_name (unsigned enc)
22638 {
22639   const char *name = get_DW_ATE_name (enc);
22640
22641   if (name == NULL)
22642     return "DW_ATE_<unknown>";
22643
22644   return name;
22645 }
22646
22647 static void
22648 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22649 {
22650   unsigned int i;
22651
22652   print_spaces (indent, f);
22653   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22654                       dwarf_tag_name (die->tag), die->abbrev,
22655                       to_underlying (die->sect_off));
22656
22657   if (die->parent != NULL)
22658     {
22659       print_spaces (indent, f);
22660       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22661                           to_underlying (die->parent->sect_off));
22662     }
22663
22664   print_spaces (indent, f);
22665   fprintf_unfiltered (f, "  has children: %s\n",
22666            dwarf_bool_name (die->child != NULL));
22667
22668   print_spaces (indent, f);
22669   fprintf_unfiltered (f, "  attributes:\n");
22670
22671   for (i = 0; i < die->num_attrs; ++i)
22672     {
22673       print_spaces (indent, f);
22674       fprintf_unfiltered (f, "    %s (%s) ",
22675                dwarf_attr_name (die->attrs[i].name),
22676                dwarf_form_name (die->attrs[i].form));
22677
22678       switch (die->attrs[i].form)
22679         {
22680         case DW_FORM_addr:
22681         case DW_FORM_GNU_addr_index:
22682           fprintf_unfiltered (f, "address: ");
22683           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22684           break;
22685         case DW_FORM_block2:
22686         case DW_FORM_block4:
22687         case DW_FORM_block:
22688         case DW_FORM_block1:
22689           fprintf_unfiltered (f, "block: size %s",
22690                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22691           break;
22692         case DW_FORM_exprloc:
22693           fprintf_unfiltered (f, "expression: size %s",
22694                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22695           break;
22696         case DW_FORM_data16:
22697           fprintf_unfiltered (f, "constant of 16 bytes");
22698           break;
22699         case DW_FORM_ref_addr:
22700           fprintf_unfiltered (f, "ref address: ");
22701           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22702           break;
22703         case DW_FORM_GNU_ref_alt:
22704           fprintf_unfiltered (f, "alt ref address: ");
22705           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22706           break;
22707         case DW_FORM_ref1:
22708         case DW_FORM_ref2:
22709         case DW_FORM_ref4:
22710         case DW_FORM_ref8:
22711         case DW_FORM_ref_udata:
22712           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22713                               (long) (DW_UNSND (&die->attrs[i])));
22714           break;
22715         case DW_FORM_data1:
22716         case DW_FORM_data2:
22717         case DW_FORM_data4:
22718         case DW_FORM_data8:
22719         case DW_FORM_udata:
22720         case DW_FORM_sdata:
22721           fprintf_unfiltered (f, "constant: %s",
22722                               pulongest (DW_UNSND (&die->attrs[i])));
22723           break;
22724         case DW_FORM_sec_offset:
22725           fprintf_unfiltered (f, "section offset: %s",
22726                               pulongest (DW_UNSND (&die->attrs[i])));
22727           break;
22728         case DW_FORM_ref_sig8:
22729           fprintf_unfiltered (f, "signature: %s",
22730                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22731           break;
22732         case DW_FORM_string:
22733         case DW_FORM_strp:
22734         case DW_FORM_line_strp:
22735         case DW_FORM_GNU_str_index:
22736         case DW_FORM_GNU_strp_alt:
22737           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22738                    DW_STRING (&die->attrs[i])
22739                    ? DW_STRING (&die->attrs[i]) : "",
22740                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22741           break;
22742         case DW_FORM_flag:
22743           if (DW_UNSND (&die->attrs[i]))
22744             fprintf_unfiltered (f, "flag: TRUE");
22745           else
22746             fprintf_unfiltered (f, "flag: FALSE");
22747           break;
22748         case DW_FORM_flag_present:
22749           fprintf_unfiltered (f, "flag: TRUE");
22750           break;
22751         case DW_FORM_indirect:
22752           /* The reader will have reduced the indirect form to
22753              the "base form" so this form should not occur.  */
22754           fprintf_unfiltered (f, 
22755                               "unexpected attribute form: DW_FORM_indirect");
22756           break;
22757         case DW_FORM_implicit_const:
22758           fprintf_unfiltered (f, "constant: %s",
22759                               plongest (DW_SND (&die->attrs[i])));
22760           break;
22761         default:
22762           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22763                    die->attrs[i].form);
22764           break;
22765         }
22766       fprintf_unfiltered (f, "\n");
22767     }
22768 }
22769
22770 static void
22771 dump_die_for_error (struct die_info *die)
22772 {
22773   dump_die_shallow (gdb_stderr, 0, die);
22774 }
22775
22776 static void
22777 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22778 {
22779   int indent = level * 4;
22780
22781   gdb_assert (die != NULL);
22782
22783   if (level >= max_level)
22784     return;
22785
22786   dump_die_shallow (f, indent, die);
22787
22788   if (die->child != NULL)
22789     {
22790       print_spaces (indent, f);
22791       fprintf_unfiltered (f, "  Children:");
22792       if (level + 1 < max_level)
22793         {
22794           fprintf_unfiltered (f, "\n");
22795           dump_die_1 (f, level + 1, max_level, die->child);
22796         }
22797       else
22798         {
22799           fprintf_unfiltered (f,
22800                               " [not printed, max nesting level reached]\n");
22801         }
22802     }
22803
22804   if (die->sibling != NULL && level > 0)
22805     {
22806       dump_die_1 (f, level, max_level, die->sibling);
22807     }
22808 }
22809
22810 /* This is called from the pdie macro in gdbinit.in.
22811    It's not static so gcc will keep a copy callable from gdb.  */
22812
22813 void
22814 dump_die (struct die_info *die, int max_level)
22815 {
22816   dump_die_1 (gdb_stdlog, 0, max_level, die);
22817 }
22818
22819 static void
22820 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22821 {
22822   void **slot;
22823
22824   slot = htab_find_slot_with_hash (cu->die_hash, die,
22825                                    to_underlying (die->sect_off),
22826                                    INSERT);
22827
22828   *slot = die;
22829 }
22830
22831 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22832    required kind.  */
22833
22834 static sect_offset
22835 dwarf2_get_ref_die_offset (const struct attribute *attr)
22836 {
22837   if (attr_form_is_ref (attr))
22838     return (sect_offset) DW_UNSND (attr);
22839
22840   complaint (&symfile_complaints,
22841              _("unsupported die ref attribute form: '%s'"),
22842              dwarf_form_name (attr->form));
22843   return {};
22844 }
22845
22846 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22847  * the value held by the attribute is not constant.  */
22848
22849 static LONGEST
22850 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22851 {
22852   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22853     return DW_SND (attr);
22854   else if (attr->form == DW_FORM_udata
22855            || attr->form == DW_FORM_data1
22856            || attr->form == DW_FORM_data2
22857            || attr->form == DW_FORM_data4
22858            || attr->form == DW_FORM_data8)
22859     return DW_UNSND (attr);
22860   else
22861     {
22862       /* For DW_FORM_data16 see attr_form_is_constant.  */
22863       complaint (&symfile_complaints,
22864                  _("Attribute value is not a constant (%s)"),
22865                  dwarf_form_name (attr->form));
22866       return default_value;
22867     }
22868 }
22869
22870 /* Follow reference or signature attribute ATTR of SRC_DIE.
22871    On entry *REF_CU is the CU of SRC_DIE.
22872    On exit *REF_CU is the CU of the result.  */
22873
22874 static struct die_info *
22875 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22876                        struct dwarf2_cu **ref_cu)
22877 {
22878   struct die_info *die;
22879
22880   if (attr_form_is_ref (attr))
22881     die = follow_die_ref (src_die, attr, ref_cu);
22882   else if (attr->form == DW_FORM_ref_sig8)
22883     die = follow_die_sig (src_die, attr, ref_cu);
22884   else
22885     {
22886       dump_die_for_error (src_die);
22887       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22888              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22889     }
22890
22891   return die;
22892 }
22893
22894 /* Follow reference OFFSET.
22895    On entry *REF_CU is the CU of the source die referencing OFFSET.
22896    On exit *REF_CU is the CU of the result.
22897    Returns NULL if OFFSET is invalid.  */
22898
22899 static struct die_info *
22900 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22901                    struct dwarf2_cu **ref_cu)
22902 {
22903   struct die_info temp_die;
22904   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22905   struct dwarf2_per_objfile *dwarf2_per_objfile
22906     = cu->per_cu->dwarf2_per_objfile;
22907   struct objfile *objfile = dwarf2_per_objfile->objfile;
22908
22909   gdb_assert (cu->per_cu != NULL);
22910
22911   target_cu = cu;
22912
22913   if (cu->per_cu->is_debug_types)
22914     {
22915       /* .debug_types CUs cannot reference anything outside their CU.
22916          If they need to, they have to reference a signatured type via
22917          DW_FORM_ref_sig8.  */
22918       if (!offset_in_cu_p (&cu->header, sect_off))
22919         return NULL;
22920     }
22921   else if (offset_in_dwz != cu->per_cu->is_dwz
22922            || !offset_in_cu_p (&cu->header, sect_off))
22923     {
22924       struct dwarf2_per_cu_data *per_cu;
22925
22926       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22927                                                  dwarf2_per_objfile);
22928
22929       /* If necessary, add it to the queue and load its DIEs.  */
22930       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22931         load_full_comp_unit (per_cu, cu->language);
22932
22933       target_cu = per_cu->cu;
22934     }
22935   else if (cu->dies == NULL)
22936     {
22937       /* We're loading full DIEs during partial symbol reading.  */
22938       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22939       load_full_comp_unit (cu->per_cu, language_minimal);
22940     }
22941
22942   *ref_cu = target_cu;
22943   temp_die.sect_off = sect_off;
22944   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22945                                                   &temp_die,
22946                                                   to_underlying (sect_off));
22947 }
22948
22949 /* Follow reference attribute ATTR of SRC_DIE.
22950    On entry *REF_CU is the CU of SRC_DIE.
22951    On exit *REF_CU is the CU of the result.  */
22952
22953 static struct die_info *
22954 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22955                 struct dwarf2_cu **ref_cu)
22956 {
22957   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22958   struct dwarf2_cu *cu = *ref_cu;
22959   struct die_info *die;
22960
22961   die = follow_die_offset (sect_off,
22962                            (attr->form == DW_FORM_GNU_ref_alt
22963                             || cu->per_cu->is_dwz),
22964                            ref_cu);
22965   if (!die)
22966     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
22967            "at 0x%x [in module %s]"),
22968            to_underlying (sect_off), to_underlying (src_die->sect_off),
22969            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22970
22971   return die;
22972 }
22973
22974 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22975    Returned value is intended for DW_OP_call*.  Returned
22976    dwarf2_locexpr_baton->data has lifetime of
22977    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22978
22979 struct dwarf2_locexpr_baton
22980 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22981                                struct dwarf2_per_cu_data *per_cu,
22982                                CORE_ADDR (*get_frame_pc) (void *baton),
22983                                void *baton)
22984 {
22985   struct dwarf2_cu *cu;
22986   struct die_info *die;
22987   struct attribute *attr;
22988   struct dwarf2_locexpr_baton retval;
22989   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22990   struct dwarf2_per_objfile *dwarf2_per_objfile
22991     = get_dwarf2_per_objfile (objfile);
22992
22993   if (per_cu->cu == NULL)
22994     load_cu (per_cu);
22995   cu = per_cu->cu;
22996   if (cu == NULL)
22997     {
22998       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22999          Instead just throw an error, not much else we can do.  */
23000       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23001              to_underlying (sect_off), objfile_name (objfile));
23002     }
23003
23004   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23005   if (!die)
23006     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23007            to_underlying (sect_off), objfile_name (objfile));
23008
23009   attr = dwarf2_attr (die, DW_AT_location, cu);
23010   if (!attr)
23011     {
23012       /* DWARF: "If there is no such attribute, then there is no effect.".
23013          DATA is ignored if SIZE is 0.  */
23014
23015       retval.data = NULL;
23016       retval.size = 0;
23017     }
23018   else if (attr_form_is_section_offset (attr))
23019     {
23020       struct dwarf2_loclist_baton loclist_baton;
23021       CORE_ADDR pc = (*get_frame_pc) (baton);
23022       size_t size;
23023
23024       fill_in_loclist_baton (cu, &loclist_baton, attr);
23025
23026       retval.data = dwarf2_find_location_expression (&loclist_baton,
23027                                                      &size, pc);
23028       retval.size = size;
23029     }
23030   else
23031     {
23032       if (!attr_form_is_block (attr))
23033         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
23034                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23035                to_underlying (sect_off), objfile_name (objfile));
23036
23037       retval.data = DW_BLOCK (attr)->data;
23038       retval.size = DW_BLOCK (attr)->size;
23039     }
23040   retval.per_cu = cu->per_cu;
23041
23042   age_cached_comp_units (dwarf2_per_objfile);
23043
23044   return retval;
23045 }
23046
23047 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23048    offset.  */
23049
23050 struct dwarf2_locexpr_baton
23051 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23052                              struct dwarf2_per_cu_data *per_cu,
23053                              CORE_ADDR (*get_frame_pc) (void *baton),
23054                              void *baton)
23055 {
23056   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23057
23058   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23059 }
23060
23061 /* Write a constant of a given type as target-ordered bytes into
23062    OBSTACK.  */
23063
23064 static const gdb_byte *
23065 write_constant_as_bytes (struct obstack *obstack,
23066                          enum bfd_endian byte_order,
23067                          struct type *type,
23068                          ULONGEST value,
23069                          LONGEST *len)
23070 {
23071   gdb_byte *result;
23072
23073   *len = TYPE_LENGTH (type);
23074   result = (gdb_byte *) obstack_alloc (obstack, *len);
23075   store_unsigned_integer (result, *len, byte_order, value);
23076
23077   return result;
23078 }
23079
23080 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23081    pointer to the constant bytes and set LEN to the length of the
23082    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23083    does not have a DW_AT_const_value, return NULL.  */
23084
23085 const gdb_byte *
23086 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23087                              struct dwarf2_per_cu_data *per_cu,
23088                              struct obstack *obstack,
23089                              LONGEST *len)
23090 {
23091   struct dwarf2_cu *cu;
23092   struct die_info *die;
23093   struct attribute *attr;
23094   const gdb_byte *result = NULL;
23095   struct type *type;
23096   LONGEST value;
23097   enum bfd_endian byte_order;
23098   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23099
23100   if (per_cu->cu == NULL)
23101     load_cu (per_cu);
23102   cu = per_cu->cu;
23103   if (cu == NULL)
23104     {
23105       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23106          Instead just throw an error, not much else we can do.  */
23107       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23108              to_underlying (sect_off), objfile_name (objfile));
23109     }
23110
23111   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23112   if (!die)
23113     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23114            to_underlying (sect_off), objfile_name (objfile));
23115
23116
23117   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23118   if (attr == NULL)
23119     return NULL;
23120
23121   byte_order = (bfd_big_endian (objfile->obfd)
23122                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23123
23124   switch (attr->form)
23125     {
23126     case DW_FORM_addr:
23127     case DW_FORM_GNU_addr_index:
23128       {
23129         gdb_byte *tem;
23130
23131         *len = cu->header.addr_size;
23132         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23133         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23134         result = tem;
23135       }
23136       break;
23137     case DW_FORM_string:
23138     case DW_FORM_strp:
23139     case DW_FORM_GNU_str_index:
23140     case DW_FORM_GNU_strp_alt:
23141       /* DW_STRING is already allocated on the objfile obstack, point
23142          directly to it.  */
23143       result = (const gdb_byte *) DW_STRING (attr);
23144       *len = strlen (DW_STRING (attr));
23145       break;
23146     case DW_FORM_block1:
23147     case DW_FORM_block2:
23148     case DW_FORM_block4:
23149     case DW_FORM_block:
23150     case DW_FORM_exprloc:
23151     case DW_FORM_data16:
23152       result = DW_BLOCK (attr)->data;
23153       *len = DW_BLOCK (attr)->size;
23154       break;
23155
23156       /* The DW_AT_const_value attributes are supposed to carry the
23157          symbol's value "represented as it would be on the target
23158          architecture."  By the time we get here, it's already been
23159          converted to host endianness, so we just need to sign- or
23160          zero-extend it as appropriate.  */
23161     case DW_FORM_data1:
23162       type = die_type (die, cu);
23163       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23164       if (result == NULL)
23165         result = write_constant_as_bytes (obstack, byte_order,
23166                                           type, value, len);
23167       break;
23168     case DW_FORM_data2:
23169       type = die_type (die, cu);
23170       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23171       if (result == NULL)
23172         result = write_constant_as_bytes (obstack, byte_order,
23173                                           type, value, len);
23174       break;
23175     case DW_FORM_data4:
23176       type = die_type (die, cu);
23177       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23178       if (result == NULL)
23179         result = write_constant_as_bytes (obstack, byte_order,
23180                                           type, value, len);
23181       break;
23182     case DW_FORM_data8:
23183       type = die_type (die, cu);
23184       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23185       if (result == NULL)
23186         result = write_constant_as_bytes (obstack, byte_order,
23187                                           type, value, len);
23188       break;
23189
23190     case DW_FORM_sdata:
23191     case DW_FORM_implicit_const:
23192       type = die_type (die, cu);
23193       result = write_constant_as_bytes (obstack, byte_order,
23194                                         type, DW_SND (attr), len);
23195       break;
23196
23197     case DW_FORM_udata:
23198       type = die_type (die, cu);
23199       result = write_constant_as_bytes (obstack, byte_order,
23200                                         type, DW_UNSND (attr), len);
23201       break;
23202
23203     default:
23204       complaint (&symfile_complaints,
23205                  _("unsupported const value attribute form: '%s'"),
23206                  dwarf_form_name (attr->form));
23207       break;
23208     }
23209
23210   return result;
23211 }
23212
23213 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23214    valid type for this die is found.  */
23215
23216 struct type *
23217 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23218                                 struct dwarf2_per_cu_data *per_cu)
23219 {
23220   struct dwarf2_cu *cu;
23221   struct die_info *die;
23222
23223   if (per_cu->cu == NULL)
23224     load_cu (per_cu);
23225   cu = per_cu->cu;
23226   if (!cu)
23227     return NULL;
23228
23229   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23230   if (!die)
23231     return NULL;
23232
23233   return die_type (die, cu);
23234 }
23235
23236 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23237    PER_CU.  */
23238
23239 struct type *
23240 dwarf2_get_die_type (cu_offset die_offset,
23241                      struct dwarf2_per_cu_data *per_cu)
23242 {
23243   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23244   return get_die_type_at_offset (die_offset_sect, per_cu);
23245 }
23246
23247 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23248    On entry *REF_CU is the CU of SRC_DIE.
23249    On exit *REF_CU is the CU of the result.
23250    Returns NULL if the referenced DIE isn't found.  */
23251
23252 static struct die_info *
23253 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23254                   struct dwarf2_cu **ref_cu)
23255 {
23256   struct die_info temp_die;
23257   struct dwarf2_cu *sig_cu;
23258   struct die_info *die;
23259
23260   /* While it might be nice to assert sig_type->type == NULL here,
23261      we can get here for DW_AT_imported_declaration where we need
23262      the DIE not the type.  */
23263
23264   /* If necessary, add it to the queue and load its DIEs.  */
23265
23266   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23267     read_signatured_type (sig_type);
23268
23269   sig_cu = sig_type->per_cu.cu;
23270   gdb_assert (sig_cu != NULL);
23271   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23272   temp_die.sect_off = sig_type->type_offset_in_section;
23273   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23274                                                  to_underlying (temp_die.sect_off));
23275   if (die)
23276     {
23277       struct dwarf2_per_objfile *dwarf2_per_objfile
23278         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23279
23280       /* For .gdb_index version 7 keep track of included TUs.
23281          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23282       if (dwarf2_per_objfile->index_table != NULL
23283           && dwarf2_per_objfile->index_table->version <= 7)
23284         {
23285           VEC_safe_push (dwarf2_per_cu_ptr,
23286                          (*ref_cu)->per_cu->imported_symtabs,
23287                          sig_cu->per_cu);
23288         }
23289
23290       *ref_cu = sig_cu;
23291       return die;
23292     }
23293
23294   return NULL;
23295 }
23296
23297 /* Follow signatured type referenced by ATTR in SRC_DIE.
23298    On entry *REF_CU is the CU of SRC_DIE.
23299    On exit *REF_CU is the CU of the result.
23300    The result is the DIE of the type.
23301    If the referenced type cannot be found an error is thrown.  */
23302
23303 static struct die_info *
23304 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23305                 struct dwarf2_cu **ref_cu)
23306 {
23307   ULONGEST signature = DW_SIGNATURE (attr);
23308   struct signatured_type *sig_type;
23309   struct die_info *die;
23310
23311   gdb_assert (attr->form == DW_FORM_ref_sig8);
23312
23313   sig_type = lookup_signatured_type (*ref_cu, signature);
23314   /* sig_type will be NULL if the signatured type is missing from
23315      the debug info.  */
23316   if (sig_type == NULL)
23317     {
23318       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23319                " from DIE at 0x%x [in module %s]"),
23320              hex_string (signature), to_underlying (src_die->sect_off),
23321              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23322     }
23323
23324   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23325   if (die == NULL)
23326     {
23327       dump_die_for_error (src_die);
23328       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23329                " from DIE at 0x%x [in module %s]"),
23330              hex_string (signature), to_underlying (src_die->sect_off),
23331              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23332     }
23333
23334   return die;
23335 }
23336
23337 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23338    reading in and processing the type unit if necessary.  */
23339
23340 static struct type *
23341 get_signatured_type (struct die_info *die, ULONGEST signature,
23342                      struct dwarf2_cu *cu)
23343 {
23344   struct dwarf2_per_objfile *dwarf2_per_objfile
23345     = cu->per_cu->dwarf2_per_objfile;
23346   struct signatured_type *sig_type;
23347   struct dwarf2_cu *type_cu;
23348   struct die_info *type_die;
23349   struct type *type;
23350
23351   sig_type = lookup_signatured_type (cu, signature);
23352   /* sig_type will be NULL if the signatured type is missing from
23353      the debug info.  */
23354   if (sig_type == NULL)
23355     {
23356       complaint (&symfile_complaints,
23357                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23358                    " from DIE at 0x%x [in module %s]"),
23359                  hex_string (signature), to_underlying (die->sect_off),
23360                  objfile_name (dwarf2_per_objfile->objfile));
23361       return build_error_marker_type (cu, die);
23362     }
23363
23364   /* If we already know the type we're done.  */
23365   if (sig_type->type != NULL)
23366     return sig_type->type;
23367
23368   type_cu = cu;
23369   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23370   if (type_die != NULL)
23371     {
23372       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23373          is created.  This is important, for example, because for c++ classes
23374          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23375       type = read_type_die (type_die, type_cu);
23376       if (type == NULL)
23377         {
23378           complaint (&symfile_complaints,
23379                      _("Dwarf Error: Cannot build signatured type %s"
23380                        " referenced from DIE at 0x%x [in module %s]"),
23381                      hex_string (signature), to_underlying (die->sect_off),
23382                      objfile_name (dwarf2_per_objfile->objfile));
23383           type = build_error_marker_type (cu, die);
23384         }
23385     }
23386   else
23387     {
23388       complaint (&symfile_complaints,
23389                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23390                    " from DIE at 0x%x [in module %s]"),
23391                  hex_string (signature), to_underlying (die->sect_off),
23392                  objfile_name (dwarf2_per_objfile->objfile));
23393       type = build_error_marker_type (cu, die);
23394     }
23395   sig_type->type = type;
23396
23397   return type;
23398 }
23399
23400 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23401    reading in and processing the type unit if necessary.  */
23402
23403 static struct type *
23404 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23405                           struct dwarf2_cu *cu) /* ARI: editCase function */
23406 {
23407   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23408   if (attr_form_is_ref (attr))
23409     {
23410       struct dwarf2_cu *type_cu = cu;
23411       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23412
23413       return read_type_die (type_die, type_cu);
23414     }
23415   else if (attr->form == DW_FORM_ref_sig8)
23416     {
23417       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23418     }
23419   else
23420     {
23421       struct dwarf2_per_objfile *dwarf2_per_objfile
23422         = cu->per_cu->dwarf2_per_objfile;
23423
23424       complaint (&symfile_complaints,
23425                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23426                    " at 0x%x [in module %s]"),
23427                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23428                  objfile_name (dwarf2_per_objfile->objfile));
23429       return build_error_marker_type (cu, die);
23430     }
23431 }
23432
23433 /* Load the DIEs associated with type unit PER_CU into memory.  */
23434
23435 static void
23436 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23437 {
23438   struct signatured_type *sig_type;
23439
23440   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23441   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23442
23443   /* We have the per_cu, but we need the signatured_type.
23444      Fortunately this is an easy translation.  */
23445   gdb_assert (per_cu->is_debug_types);
23446   sig_type = (struct signatured_type *) per_cu;
23447
23448   gdb_assert (per_cu->cu == NULL);
23449
23450   read_signatured_type (sig_type);
23451
23452   gdb_assert (per_cu->cu != NULL);
23453 }
23454
23455 /* die_reader_func for read_signatured_type.
23456    This is identical to load_full_comp_unit_reader,
23457    but is kept separate for now.  */
23458
23459 static void
23460 read_signatured_type_reader (const struct die_reader_specs *reader,
23461                              const gdb_byte *info_ptr,
23462                              struct die_info *comp_unit_die,
23463                              int has_children,
23464                              void *data)
23465 {
23466   struct dwarf2_cu *cu = reader->cu;
23467
23468   gdb_assert (cu->die_hash == NULL);
23469   cu->die_hash =
23470     htab_create_alloc_ex (cu->header.length / 12,
23471                           die_hash,
23472                           die_eq,
23473                           NULL,
23474                           &cu->comp_unit_obstack,
23475                           hashtab_obstack_allocate,
23476                           dummy_obstack_deallocate);
23477
23478   if (has_children)
23479     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23480                                                   &info_ptr, comp_unit_die);
23481   cu->dies = comp_unit_die;
23482   /* comp_unit_die is not stored in die_hash, no need.  */
23483
23484   /* We try not to read any attributes in this function, because not
23485      all CUs needed for references have been loaded yet, and symbol
23486      table processing isn't initialized.  But we have to set the CU language,
23487      or we won't be able to build types correctly.
23488      Similarly, if we do not read the producer, we can not apply
23489      producer-specific interpretation.  */
23490   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23491 }
23492
23493 /* Read in a signatured type and build its CU and DIEs.
23494    If the type is a stub for the real type in a DWO file,
23495    read in the real type from the DWO file as well.  */
23496
23497 static void
23498 read_signatured_type (struct signatured_type *sig_type)
23499 {
23500   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23501
23502   gdb_assert (per_cu->is_debug_types);
23503   gdb_assert (per_cu->cu == NULL);
23504
23505   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23506                            read_signatured_type_reader, NULL);
23507   sig_type->per_cu.tu_read = 1;
23508 }
23509
23510 /* Decode simple location descriptions.
23511    Given a pointer to a dwarf block that defines a location, compute
23512    the location and return the value.
23513
23514    NOTE drow/2003-11-18: This function is called in two situations
23515    now: for the address of static or global variables (partial symbols
23516    only) and for offsets into structures which are expected to be
23517    (more or less) constant.  The partial symbol case should go away,
23518    and only the constant case should remain.  That will let this
23519    function complain more accurately.  A few special modes are allowed
23520    without complaint for global variables (for instance, global
23521    register values and thread-local values).
23522
23523    A location description containing no operations indicates that the
23524    object is optimized out.  The return value is 0 for that case.
23525    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23526    callers will only want a very basic result and this can become a
23527    complaint.
23528
23529    Note that stack[0] is unused except as a default error return.  */
23530
23531 static CORE_ADDR
23532 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23533 {
23534   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23535   size_t i;
23536   size_t size = blk->size;
23537   const gdb_byte *data = blk->data;
23538   CORE_ADDR stack[64];
23539   int stacki;
23540   unsigned int bytes_read, unsnd;
23541   gdb_byte op;
23542
23543   i = 0;
23544   stacki = 0;
23545   stack[stacki] = 0;
23546   stack[++stacki] = 0;
23547
23548   while (i < size)
23549     {
23550       op = data[i++];
23551       switch (op)
23552         {
23553         case DW_OP_lit0:
23554         case DW_OP_lit1:
23555         case DW_OP_lit2:
23556         case DW_OP_lit3:
23557         case DW_OP_lit4:
23558         case DW_OP_lit5:
23559         case DW_OP_lit6:
23560         case DW_OP_lit7:
23561         case DW_OP_lit8:
23562         case DW_OP_lit9:
23563         case DW_OP_lit10:
23564         case DW_OP_lit11:
23565         case DW_OP_lit12:
23566         case DW_OP_lit13:
23567         case DW_OP_lit14:
23568         case DW_OP_lit15:
23569         case DW_OP_lit16:
23570         case DW_OP_lit17:
23571         case DW_OP_lit18:
23572         case DW_OP_lit19:
23573         case DW_OP_lit20:
23574         case DW_OP_lit21:
23575         case DW_OP_lit22:
23576         case DW_OP_lit23:
23577         case DW_OP_lit24:
23578         case DW_OP_lit25:
23579         case DW_OP_lit26:
23580         case DW_OP_lit27:
23581         case DW_OP_lit28:
23582         case DW_OP_lit29:
23583         case DW_OP_lit30:
23584         case DW_OP_lit31:
23585           stack[++stacki] = op - DW_OP_lit0;
23586           break;
23587
23588         case DW_OP_reg0:
23589         case DW_OP_reg1:
23590         case DW_OP_reg2:
23591         case DW_OP_reg3:
23592         case DW_OP_reg4:
23593         case DW_OP_reg5:
23594         case DW_OP_reg6:
23595         case DW_OP_reg7:
23596         case DW_OP_reg8:
23597         case DW_OP_reg9:
23598         case DW_OP_reg10:
23599         case DW_OP_reg11:
23600         case DW_OP_reg12:
23601         case DW_OP_reg13:
23602         case DW_OP_reg14:
23603         case DW_OP_reg15:
23604         case DW_OP_reg16:
23605         case DW_OP_reg17:
23606         case DW_OP_reg18:
23607         case DW_OP_reg19:
23608         case DW_OP_reg20:
23609         case DW_OP_reg21:
23610         case DW_OP_reg22:
23611         case DW_OP_reg23:
23612         case DW_OP_reg24:
23613         case DW_OP_reg25:
23614         case DW_OP_reg26:
23615         case DW_OP_reg27:
23616         case DW_OP_reg28:
23617         case DW_OP_reg29:
23618         case DW_OP_reg30:
23619         case DW_OP_reg31:
23620           stack[++stacki] = op - DW_OP_reg0;
23621           if (i < size)
23622             dwarf2_complex_location_expr_complaint ();
23623           break;
23624
23625         case DW_OP_regx:
23626           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23627           i += bytes_read;
23628           stack[++stacki] = unsnd;
23629           if (i < size)
23630             dwarf2_complex_location_expr_complaint ();
23631           break;
23632
23633         case DW_OP_addr:
23634           stack[++stacki] = read_address (objfile->obfd, &data[i],
23635                                           cu, &bytes_read);
23636           i += bytes_read;
23637           break;
23638
23639         case DW_OP_const1u:
23640           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23641           i += 1;
23642           break;
23643
23644         case DW_OP_const1s:
23645           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23646           i += 1;
23647           break;
23648
23649         case DW_OP_const2u:
23650           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23651           i += 2;
23652           break;
23653
23654         case DW_OP_const2s:
23655           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23656           i += 2;
23657           break;
23658
23659         case DW_OP_const4u:
23660           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23661           i += 4;
23662           break;
23663
23664         case DW_OP_const4s:
23665           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23666           i += 4;
23667           break;
23668
23669         case DW_OP_const8u:
23670           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23671           i += 8;
23672           break;
23673
23674         case DW_OP_constu:
23675           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23676                                                   &bytes_read);
23677           i += bytes_read;
23678           break;
23679
23680         case DW_OP_consts:
23681           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23682           i += bytes_read;
23683           break;
23684
23685         case DW_OP_dup:
23686           stack[stacki + 1] = stack[stacki];
23687           stacki++;
23688           break;
23689
23690         case DW_OP_plus:
23691           stack[stacki - 1] += stack[stacki];
23692           stacki--;
23693           break;
23694
23695         case DW_OP_plus_uconst:
23696           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23697                                                  &bytes_read);
23698           i += bytes_read;
23699           break;
23700
23701         case DW_OP_minus:
23702           stack[stacki - 1] -= stack[stacki];
23703           stacki--;
23704           break;
23705
23706         case DW_OP_deref:
23707           /* If we're not the last op, then we definitely can't encode
23708              this using GDB's address_class enum.  This is valid for partial
23709              global symbols, although the variable's address will be bogus
23710              in the psymtab.  */
23711           if (i < size)
23712             dwarf2_complex_location_expr_complaint ();
23713           break;
23714
23715         case DW_OP_GNU_push_tls_address:
23716         case DW_OP_form_tls_address:
23717           /* The top of the stack has the offset from the beginning
23718              of the thread control block at which the variable is located.  */
23719           /* Nothing should follow this operator, so the top of stack would
23720              be returned.  */
23721           /* This is valid for partial global symbols, but the variable's
23722              address will be bogus in the psymtab.  Make it always at least
23723              non-zero to not look as a variable garbage collected by linker
23724              which have DW_OP_addr 0.  */
23725           if (i < size)
23726             dwarf2_complex_location_expr_complaint ();
23727           stack[stacki]++;
23728           break;
23729
23730         case DW_OP_GNU_uninit:
23731           break;
23732
23733         case DW_OP_GNU_addr_index:
23734         case DW_OP_GNU_const_index:
23735           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23736                                                          &bytes_read);
23737           i += bytes_read;
23738           break;
23739
23740         default:
23741           {
23742             const char *name = get_DW_OP_name (op);
23743
23744             if (name)
23745               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23746                          name);
23747             else
23748               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23749                          op);
23750           }
23751
23752           return (stack[stacki]);
23753         }
23754
23755       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23756          outside of the allocated space.  Also enforce minimum>0.  */
23757       if (stacki >= ARRAY_SIZE (stack) - 1)
23758         {
23759           complaint (&symfile_complaints,
23760                      _("location description stack overflow"));
23761           return 0;
23762         }
23763
23764       if (stacki <= 0)
23765         {
23766           complaint (&symfile_complaints,
23767                      _("location description stack underflow"));
23768           return 0;
23769         }
23770     }
23771   return (stack[stacki]);
23772 }
23773
23774 /* memory allocation interface */
23775
23776 static struct dwarf_block *
23777 dwarf_alloc_block (struct dwarf2_cu *cu)
23778 {
23779   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23780 }
23781
23782 static struct die_info *
23783 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23784 {
23785   struct die_info *die;
23786   size_t size = sizeof (struct die_info);
23787
23788   if (num_attrs > 1)
23789     size += (num_attrs - 1) * sizeof (struct attribute);
23790
23791   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23792   memset (die, 0, sizeof (struct die_info));
23793   return (die);
23794 }
23795
23796 \f
23797 /* Macro support.  */
23798
23799 /* Return file name relative to the compilation directory of file number I in
23800    *LH's file name table.  The result is allocated using xmalloc; the caller is
23801    responsible for freeing it.  */
23802
23803 static char *
23804 file_file_name (int file, struct line_header *lh)
23805 {
23806   /* Is the file number a valid index into the line header's file name
23807      table?  Remember that file numbers start with one, not zero.  */
23808   if (1 <= file && file <= lh->file_names.size ())
23809     {
23810       const file_entry &fe = lh->file_names[file - 1];
23811
23812       if (!IS_ABSOLUTE_PATH (fe.name))
23813         {
23814           const char *dir = fe.include_dir (lh);
23815           if (dir != NULL)
23816             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23817         }
23818       return xstrdup (fe.name);
23819     }
23820   else
23821     {
23822       /* The compiler produced a bogus file number.  We can at least
23823          record the macro definitions made in the file, even if we
23824          won't be able to find the file by name.  */
23825       char fake_name[80];
23826
23827       xsnprintf (fake_name, sizeof (fake_name),
23828                  "<bad macro file number %d>", file);
23829
23830       complaint (&symfile_complaints,
23831                  _("bad file number in macro information (%d)"),
23832                  file);
23833
23834       return xstrdup (fake_name);
23835     }
23836 }
23837
23838 /* Return the full name of file number I in *LH's file name table.
23839    Use COMP_DIR as the name of the current directory of the
23840    compilation.  The result is allocated using xmalloc; the caller is
23841    responsible for freeing it.  */
23842 static char *
23843 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23844 {
23845   /* Is the file number a valid index into the line header's file name
23846      table?  Remember that file numbers start with one, not zero.  */
23847   if (1 <= file && file <= lh->file_names.size ())
23848     {
23849       char *relative = file_file_name (file, lh);
23850
23851       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23852         return relative;
23853       return reconcat (relative, comp_dir, SLASH_STRING,
23854                        relative, (char *) NULL);
23855     }
23856   else
23857     return file_file_name (file, lh);
23858 }
23859
23860
23861 static struct macro_source_file *
23862 macro_start_file (int file, int line,
23863                   struct macro_source_file *current_file,
23864                   struct line_header *lh)
23865 {
23866   /* File name relative to the compilation directory of this source file.  */
23867   char *file_name = file_file_name (file, lh);
23868
23869   if (! current_file)
23870     {
23871       /* Note: We don't create a macro table for this compilation unit
23872          at all until we actually get a filename.  */
23873       struct macro_table *macro_table = get_macro_table ();
23874
23875       /* If we have no current file, then this must be the start_file
23876          directive for the compilation unit's main source file.  */
23877       current_file = macro_set_main (macro_table, file_name);
23878       macro_define_special (macro_table);
23879     }
23880   else
23881     current_file = macro_include (current_file, line, file_name);
23882
23883   xfree (file_name);
23884
23885   return current_file;
23886 }
23887
23888 static const char *
23889 consume_improper_spaces (const char *p, const char *body)
23890 {
23891   if (*p == ' ')
23892     {
23893       complaint (&symfile_complaints,
23894                  _("macro definition contains spaces "
23895                    "in formal argument list:\n`%s'"),
23896                  body);
23897
23898       while (*p == ' ')
23899         p++;
23900     }
23901
23902   return p;
23903 }
23904
23905
23906 static void
23907 parse_macro_definition (struct macro_source_file *file, int line,
23908                         const char *body)
23909 {
23910   const char *p;
23911
23912   /* The body string takes one of two forms.  For object-like macro
23913      definitions, it should be:
23914
23915         <macro name> " " <definition>
23916
23917      For function-like macro definitions, it should be:
23918
23919         <macro name> "() " <definition>
23920      or
23921         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23922
23923      Spaces may appear only where explicitly indicated, and in the
23924      <definition>.
23925
23926      The Dwarf 2 spec says that an object-like macro's name is always
23927      followed by a space, but versions of GCC around March 2002 omit
23928      the space when the macro's definition is the empty string.
23929
23930      The Dwarf 2 spec says that there should be no spaces between the
23931      formal arguments in a function-like macro's formal argument list,
23932      but versions of GCC around March 2002 include spaces after the
23933      commas.  */
23934
23935
23936   /* Find the extent of the macro name.  The macro name is terminated
23937      by either a space or null character (for an object-like macro) or
23938      an opening paren (for a function-like macro).  */
23939   for (p = body; *p; p++)
23940     if (*p == ' ' || *p == '(')
23941       break;
23942
23943   if (*p == ' ' || *p == '\0')
23944     {
23945       /* It's an object-like macro.  */
23946       int name_len = p - body;
23947       char *name = savestring (body, name_len);
23948       const char *replacement;
23949
23950       if (*p == ' ')
23951         replacement = body + name_len + 1;
23952       else
23953         {
23954           dwarf2_macro_malformed_definition_complaint (body);
23955           replacement = body + name_len;
23956         }
23957
23958       macro_define_object (file, line, name, replacement);
23959
23960       xfree (name);
23961     }
23962   else if (*p == '(')
23963     {
23964       /* It's a function-like macro.  */
23965       char *name = savestring (body, p - body);
23966       int argc = 0;
23967       int argv_size = 1;
23968       char **argv = XNEWVEC (char *, argv_size);
23969
23970       p++;
23971
23972       p = consume_improper_spaces (p, body);
23973
23974       /* Parse the formal argument list.  */
23975       while (*p && *p != ')')
23976         {
23977           /* Find the extent of the current argument name.  */
23978           const char *arg_start = p;
23979
23980           while (*p && *p != ',' && *p != ')' && *p != ' ')
23981             p++;
23982
23983           if (! *p || p == arg_start)
23984             dwarf2_macro_malformed_definition_complaint (body);
23985           else
23986             {
23987               /* Make sure argv has room for the new argument.  */
23988               if (argc >= argv_size)
23989                 {
23990                   argv_size *= 2;
23991                   argv = XRESIZEVEC (char *, argv, argv_size);
23992                 }
23993
23994               argv[argc++] = savestring (arg_start, p - arg_start);
23995             }
23996
23997           p = consume_improper_spaces (p, body);
23998
23999           /* Consume the comma, if present.  */
24000           if (*p == ',')
24001             {
24002               p++;
24003
24004               p = consume_improper_spaces (p, body);
24005             }
24006         }
24007
24008       if (*p == ')')
24009         {
24010           p++;
24011
24012           if (*p == ' ')
24013             /* Perfectly formed definition, no complaints.  */
24014             macro_define_function (file, line, name,
24015                                    argc, (const char **) argv,
24016                                    p + 1);
24017           else if (*p == '\0')
24018             {
24019               /* Complain, but do define it.  */
24020               dwarf2_macro_malformed_definition_complaint (body);
24021               macro_define_function (file, line, name,
24022                                      argc, (const char **) argv,
24023                                      p);
24024             }
24025           else
24026             /* Just complain.  */
24027             dwarf2_macro_malformed_definition_complaint (body);
24028         }
24029       else
24030         /* Just complain.  */
24031         dwarf2_macro_malformed_definition_complaint (body);
24032
24033       xfree (name);
24034       {
24035         int i;
24036
24037         for (i = 0; i < argc; i++)
24038           xfree (argv[i]);
24039       }
24040       xfree (argv);
24041     }
24042   else
24043     dwarf2_macro_malformed_definition_complaint (body);
24044 }
24045
24046 /* Skip some bytes from BYTES according to the form given in FORM.
24047    Returns the new pointer.  */
24048
24049 static const gdb_byte *
24050 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24051                  enum dwarf_form form,
24052                  unsigned int offset_size,
24053                  struct dwarf2_section_info *section)
24054 {
24055   unsigned int bytes_read;
24056
24057   switch (form)
24058     {
24059     case DW_FORM_data1:
24060     case DW_FORM_flag:
24061       ++bytes;
24062       break;
24063
24064     case DW_FORM_data2:
24065       bytes += 2;
24066       break;
24067
24068     case DW_FORM_data4:
24069       bytes += 4;
24070       break;
24071
24072     case DW_FORM_data8:
24073       bytes += 8;
24074       break;
24075
24076     case DW_FORM_data16:
24077       bytes += 16;
24078       break;
24079
24080     case DW_FORM_string:
24081       read_direct_string (abfd, bytes, &bytes_read);
24082       bytes += bytes_read;
24083       break;
24084
24085     case DW_FORM_sec_offset:
24086     case DW_FORM_strp:
24087     case DW_FORM_GNU_strp_alt:
24088       bytes += offset_size;
24089       break;
24090
24091     case DW_FORM_block:
24092       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24093       bytes += bytes_read;
24094       break;
24095
24096     case DW_FORM_block1:
24097       bytes += 1 + read_1_byte (abfd, bytes);
24098       break;
24099     case DW_FORM_block2:
24100       bytes += 2 + read_2_bytes (abfd, bytes);
24101       break;
24102     case DW_FORM_block4:
24103       bytes += 4 + read_4_bytes (abfd, bytes);
24104       break;
24105
24106     case DW_FORM_sdata:
24107     case DW_FORM_udata:
24108     case DW_FORM_GNU_addr_index:
24109     case DW_FORM_GNU_str_index:
24110       bytes = gdb_skip_leb128 (bytes, buffer_end);
24111       if (bytes == NULL)
24112         {
24113           dwarf2_section_buffer_overflow_complaint (section);
24114           return NULL;
24115         }
24116       break;
24117
24118     case DW_FORM_implicit_const:
24119       break;
24120
24121     default:
24122       {
24123         complaint (&symfile_complaints,
24124                    _("invalid form 0x%x in `%s'"),
24125                    form, get_section_name (section));
24126         return NULL;
24127       }
24128     }
24129
24130   return bytes;
24131 }
24132
24133 /* A helper for dwarf_decode_macros that handles skipping an unknown
24134    opcode.  Returns an updated pointer to the macro data buffer; or,
24135    on error, issues a complaint and returns NULL.  */
24136
24137 static const gdb_byte *
24138 skip_unknown_opcode (unsigned int opcode,
24139                      const gdb_byte **opcode_definitions,
24140                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24141                      bfd *abfd,
24142                      unsigned int offset_size,
24143                      struct dwarf2_section_info *section)
24144 {
24145   unsigned int bytes_read, i;
24146   unsigned long arg;
24147   const gdb_byte *defn;
24148
24149   if (opcode_definitions[opcode] == NULL)
24150     {
24151       complaint (&symfile_complaints,
24152                  _("unrecognized DW_MACFINO opcode 0x%x"),
24153                  opcode);
24154       return NULL;
24155     }
24156
24157   defn = opcode_definitions[opcode];
24158   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24159   defn += bytes_read;
24160
24161   for (i = 0; i < arg; ++i)
24162     {
24163       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24164                                  (enum dwarf_form) defn[i], offset_size,
24165                                  section);
24166       if (mac_ptr == NULL)
24167         {
24168           /* skip_form_bytes already issued the complaint.  */
24169           return NULL;
24170         }
24171     }
24172
24173   return mac_ptr;
24174 }
24175
24176 /* A helper function which parses the header of a macro section.
24177    If the macro section is the extended (for now called "GNU") type,
24178    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24179    the header, or issues a complaint and returns NULL on error.  */
24180
24181 static const gdb_byte *
24182 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24183                           bfd *abfd,
24184                           const gdb_byte *mac_ptr,
24185                           unsigned int *offset_size,
24186                           int section_is_gnu)
24187 {
24188   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24189
24190   if (section_is_gnu)
24191     {
24192       unsigned int version, flags;
24193
24194       version = read_2_bytes (abfd, mac_ptr);
24195       if (version != 4 && version != 5)
24196         {
24197           complaint (&symfile_complaints,
24198                      _("unrecognized version `%d' in .debug_macro section"),
24199                      version);
24200           return NULL;
24201         }
24202       mac_ptr += 2;
24203
24204       flags = read_1_byte (abfd, mac_ptr);
24205       ++mac_ptr;
24206       *offset_size = (flags & 1) ? 8 : 4;
24207
24208       if ((flags & 2) != 0)
24209         /* We don't need the line table offset.  */
24210         mac_ptr += *offset_size;
24211
24212       /* Vendor opcode descriptions.  */
24213       if ((flags & 4) != 0)
24214         {
24215           unsigned int i, count;
24216
24217           count = read_1_byte (abfd, mac_ptr);
24218           ++mac_ptr;
24219           for (i = 0; i < count; ++i)
24220             {
24221               unsigned int opcode, bytes_read;
24222               unsigned long arg;
24223
24224               opcode = read_1_byte (abfd, mac_ptr);
24225               ++mac_ptr;
24226               opcode_definitions[opcode] = mac_ptr;
24227               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24228               mac_ptr += bytes_read;
24229               mac_ptr += arg;
24230             }
24231         }
24232     }
24233
24234   return mac_ptr;
24235 }
24236
24237 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24238    including DW_MACRO_import.  */
24239
24240 static void
24241 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24242                           bfd *abfd,
24243                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24244                           struct macro_source_file *current_file,
24245                           struct line_header *lh,
24246                           struct dwarf2_section_info *section,
24247                           int section_is_gnu, int section_is_dwz,
24248                           unsigned int offset_size,
24249                           htab_t include_hash)
24250 {
24251   struct objfile *objfile = dwarf2_per_objfile->objfile;
24252   enum dwarf_macro_record_type macinfo_type;
24253   int at_commandline;
24254   const gdb_byte *opcode_definitions[256];
24255
24256   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24257                                       &offset_size, section_is_gnu);
24258   if (mac_ptr == NULL)
24259     {
24260       /* We already issued a complaint.  */
24261       return;
24262     }
24263
24264   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24265      GDB is still reading the definitions from command line.  First
24266      DW_MACINFO_start_file will need to be ignored as it was already executed
24267      to create CURRENT_FILE for the main source holding also the command line
24268      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24269      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24270
24271   at_commandline = 1;
24272
24273   do
24274     {
24275       /* Do we at least have room for a macinfo type byte?  */
24276       if (mac_ptr >= mac_end)
24277         {
24278           dwarf2_section_buffer_overflow_complaint (section);
24279           break;
24280         }
24281
24282       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24283       mac_ptr++;
24284
24285       /* Note that we rely on the fact that the corresponding GNU and
24286          DWARF constants are the same.  */
24287       DIAGNOSTIC_PUSH
24288       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24289       switch (macinfo_type)
24290         {
24291           /* A zero macinfo type indicates the end of the macro
24292              information.  */
24293         case 0:
24294           break;
24295
24296         case DW_MACRO_define:
24297         case DW_MACRO_undef:
24298         case DW_MACRO_define_strp:
24299         case DW_MACRO_undef_strp:
24300         case DW_MACRO_define_sup:
24301         case DW_MACRO_undef_sup:
24302           {
24303             unsigned int bytes_read;
24304             int line;
24305             const char *body;
24306             int is_define;
24307
24308             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24309             mac_ptr += bytes_read;
24310
24311             if (macinfo_type == DW_MACRO_define
24312                 || macinfo_type == DW_MACRO_undef)
24313               {
24314                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24315                 mac_ptr += bytes_read;
24316               }
24317             else
24318               {
24319                 LONGEST str_offset;
24320
24321                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24322                 mac_ptr += offset_size;
24323
24324                 if (macinfo_type == DW_MACRO_define_sup
24325                     || macinfo_type == DW_MACRO_undef_sup
24326                     || section_is_dwz)
24327                   {
24328                     struct dwz_file *dwz
24329                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24330
24331                     body = read_indirect_string_from_dwz (objfile,
24332                                                           dwz, str_offset);
24333                   }
24334                 else
24335                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24336                                                          abfd, str_offset);
24337               }
24338
24339             is_define = (macinfo_type == DW_MACRO_define
24340                          || macinfo_type == DW_MACRO_define_strp
24341                          || macinfo_type == DW_MACRO_define_sup);
24342             if (! current_file)
24343               {
24344                 /* DWARF violation as no main source is present.  */
24345                 complaint (&symfile_complaints,
24346                            _("debug info with no main source gives macro %s "
24347                              "on line %d: %s"),
24348                            is_define ? _("definition") : _("undefinition"),
24349                            line, body);
24350                 break;
24351               }
24352             if ((line == 0 && !at_commandline)
24353                 || (line != 0 && at_commandline))
24354               complaint (&symfile_complaints,
24355                          _("debug info gives %s macro %s with %s line %d: %s"),
24356                          at_commandline ? _("command-line") : _("in-file"),
24357                          is_define ? _("definition") : _("undefinition"),
24358                          line == 0 ? _("zero") : _("non-zero"), line, body);
24359
24360             if (is_define)
24361               parse_macro_definition (current_file, line, body);
24362             else
24363               {
24364                 gdb_assert (macinfo_type == DW_MACRO_undef
24365                             || macinfo_type == DW_MACRO_undef_strp
24366                             || macinfo_type == DW_MACRO_undef_sup);
24367                 macro_undef (current_file, line, body);
24368               }
24369           }
24370           break;
24371
24372         case DW_MACRO_start_file:
24373           {
24374             unsigned int bytes_read;
24375             int line, file;
24376
24377             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24378             mac_ptr += bytes_read;
24379             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24380             mac_ptr += bytes_read;
24381
24382             if ((line == 0 && !at_commandline)
24383                 || (line != 0 && at_commandline))
24384               complaint (&symfile_complaints,
24385                          _("debug info gives source %d included "
24386                            "from %s at %s line %d"),
24387                          file, at_commandline ? _("command-line") : _("file"),
24388                          line == 0 ? _("zero") : _("non-zero"), line);
24389
24390             if (at_commandline)
24391               {
24392                 /* This DW_MACRO_start_file was executed in the
24393                    pass one.  */
24394                 at_commandline = 0;
24395               }
24396             else
24397               current_file = macro_start_file (file, line, current_file, lh);
24398           }
24399           break;
24400
24401         case DW_MACRO_end_file:
24402           if (! current_file)
24403             complaint (&symfile_complaints,
24404                        _("macro debug info has an unmatched "
24405                          "`close_file' directive"));
24406           else
24407             {
24408               current_file = current_file->included_by;
24409               if (! current_file)
24410                 {
24411                   enum dwarf_macro_record_type next_type;
24412
24413                   /* GCC circa March 2002 doesn't produce the zero
24414                      type byte marking the end of the compilation
24415                      unit.  Complain if it's not there, but exit no
24416                      matter what.  */
24417
24418                   /* Do we at least have room for a macinfo type byte?  */
24419                   if (mac_ptr >= mac_end)
24420                     {
24421                       dwarf2_section_buffer_overflow_complaint (section);
24422                       return;
24423                     }
24424
24425                   /* We don't increment mac_ptr here, so this is just
24426                      a look-ahead.  */
24427                   next_type
24428                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24429                                                                   mac_ptr);
24430                   if (next_type != 0)
24431                     complaint (&symfile_complaints,
24432                                _("no terminating 0-type entry for "
24433                                  "macros in `.debug_macinfo' section"));
24434
24435                   return;
24436                 }
24437             }
24438           break;
24439
24440         case DW_MACRO_import:
24441         case DW_MACRO_import_sup:
24442           {
24443             LONGEST offset;
24444             void **slot;
24445             bfd *include_bfd = abfd;
24446             struct dwarf2_section_info *include_section = section;
24447             const gdb_byte *include_mac_end = mac_end;
24448             int is_dwz = section_is_dwz;
24449             const gdb_byte *new_mac_ptr;
24450
24451             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24452             mac_ptr += offset_size;
24453
24454             if (macinfo_type == DW_MACRO_import_sup)
24455               {
24456                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24457
24458                 dwarf2_read_section (objfile, &dwz->macro);
24459
24460                 include_section = &dwz->macro;
24461                 include_bfd = get_section_bfd_owner (include_section);
24462                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24463                 is_dwz = 1;
24464               }
24465
24466             new_mac_ptr = include_section->buffer + offset;
24467             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24468
24469             if (*slot != NULL)
24470               {
24471                 /* This has actually happened; see
24472                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24473                 complaint (&symfile_complaints,
24474                            _("recursive DW_MACRO_import in "
24475                              ".debug_macro section"));
24476               }
24477             else
24478               {
24479                 *slot = (void *) new_mac_ptr;
24480
24481                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24482                                           include_bfd, new_mac_ptr,
24483                                           include_mac_end, current_file, lh,
24484                                           section, section_is_gnu, is_dwz,
24485                                           offset_size, include_hash);
24486
24487                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24488               }
24489           }
24490           break;
24491
24492         case DW_MACINFO_vendor_ext:
24493           if (!section_is_gnu)
24494             {
24495               unsigned int bytes_read;
24496
24497               /* This reads the constant, but since we don't recognize
24498                  any vendor extensions, we ignore it.  */
24499               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24500               mac_ptr += bytes_read;
24501               read_direct_string (abfd, mac_ptr, &bytes_read);
24502               mac_ptr += bytes_read;
24503
24504               /* We don't recognize any vendor extensions.  */
24505               break;
24506             }
24507           /* FALLTHROUGH */
24508
24509         default:
24510           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24511                                          mac_ptr, mac_end, abfd, offset_size,
24512                                          section);
24513           if (mac_ptr == NULL)
24514             return;
24515           break;
24516         }
24517       DIAGNOSTIC_POP
24518     } while (macinfo_type != 0);
24519 }
24520
24521 static void
24522 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24523                      int section_is_gnu)
24524 {
24525   struct dwarf2_per_objfile *dwarf2_per_objfile
24526     = cu->per_cu->dwarf2_per_objfile;
24527   struct objfile *objfile = dwarf2_per_objfile->objfile;
24528   struct line_header *lh = cu->line_header;
24529   bfd *abfd;
24530   const gdb_byte *mac_ptr, *mac_end;
24531   struct macro_source_file *current_file = 0;
24532   enum dwarf_macro_record_type macinfo_type;
24533   unsigned int offset_size = cu->header.offset_size;
24534   const gdb_byte *opcode_definitions[256];
24535   void **slot;
24536   struct dwarf2_section_info *section;
24537   const char *section_name;
24538
24539   if (cu->dwo_unit != NULL)
24540     {
24541       if (section_is_gnu)
24542         {
24543           section = &cu->dwo_unit->dwo_file->sections.macro;
24544           section_name = ".debug_macro.dwo";
24545         }
24546       else
24547         {
24548           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24549           section_name = ".debug_macinfo.dwo";
24550         }
24551     }
24552   else
24553     {
24554       if (section_is_gnu)
24555         {
24556           section = &dwarf2_per_objfile->macro;
24557           section_name = ".debug_macro";
24558         }
24559       else
24560         {
24561           section = &dwarf2_per_objfile->macinfo;
24562           section_name = ".debug_macinfo";
24563         }
24564     }
24565
24566   dwarf2_read_section (objfile, section);
24567   if (section->buffer == NULL)
24568     {
24569       complaint (&symfile_complaints, _("missing %s section"), section_name);
24570       return;
24571     }
24572   abfd = get_section_bfd_owner (section);
24573
24574   /* First pass: Find the name of the base filename.
24575      This filename is needed in order to process all macros whose definition
24576      (or undefinition) comes from the command line.  These macros are defined
24577      before the first DW_MACINFO_start_file entry, and yet still need to be
24578      associated to the base file.
24579
24580      To determine the base file name, we scan the macro definitions until we
24581      reach the first DW_MACINFO_start_file entry.  We then initialize
24582      CURRENT_FILE accordingly so that any macro definition found before the
24583      first DW_MACINFO_start_file can still be associated to the base file.  */
24584
24585   mac_ptr = section->buffer + offset;
24586   mac_end = section->buffer + section->size;
24587
24588   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24589                                       &offset_size, section_is_gnu);
24590   if (mac_ptr == NULL)
24591     {
24592       /* We already issued a complaint.  */
24593       return;
24594     }
24595
24596   do
24597     {
24598       /* Do we at least have room for a macinfo type byte?  */
24599       if (mac_ptr >= mac_end)
24600         {
24601           /* Complaint is printed during the second pass as GDB will probably
24602              stop the first pass earlier upon finding
24603              DW_MACINFO_start_file.  */
24604           break;
24605         }
24606
24607       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24608       mac_ptr++;
24609
24610       /* Note that we rely on the fact that the corresponding GNU and
24611          DWARF constants are the same.  */
24612       DIAGNOSTIC_PUSH
24613       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24614       switch (macinfo_type)
24615         {
24616           /* A zero macinfo type indicates the end of the macro
24617              information.  */
24618         case 0:
24619           break;
24620
24621         case DW_MACRO_define:
24622         case DW_MACRO_undef:
24623           /* Only skip the data by MAC_PTR.  */
24624           {
24625             unsigned int bytes_read;
24626
24627             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24628             mac_ptr += bytes_read;
24629             read_direct_string (abfd, mac_ptr, &bytes_read);
24630             mac_ptr += bytes_read;
24631           }
24632           break;
24633
24634         case DW_MACRO_start_file:
24635           {
24636             unsigned int bytes_read;
24637             int line, file;
24638
24639             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24640             mac_ptr += bytes_read;
24641             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24642             mac_ptr += bytes_read;
24643
24644             current_file = macro_start_file (file, line, current_file, lh);
24645           }
24646           break;
24647
24648         case DW_MACRO_end_file:
24649           /* No data to skip by MAC_PTR.  */
24650           break;
24651
24652         case DW_MACRO_define_strp:
24653         case DW_MACRO_undef_strp:
24654         case DW_MACRO_define_sup:
24655         case DW_MACRO_undef_sup:
24656           {
24657             unsigned int bytes_read;
24658
24659             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24660             mac_ptr += bytes_read;
24661             mac_ptr += offset_size;
24662           }
24663           break;
24664
24665         case DW_MACRO_import:
24666         case DW_MACRO_import_sup:
24667           /* Note that, according to the spec, a transparent include
24668              chain cannot call DW_MACRO_start_file.  So, we can just
24669              skip this opcode.  */
24670           mac_ptr += offset_size;
24671           break;
24672
24673         case DW_MACINFO_vendor_ext:
24674           /* Only skip the data by MAC_PTR.  */
24675           if (!section_is_gnu)
24676             {
24677               unsigned int bytes_read;
24678
24679               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24680               mac_ptr += bytes_read;
24681               read_direct_string (abfd, mac_ptr, &bytes_read);
24682               mac_ptr += bytes_read;
24683             }
24684           /* FALLTHROUGH */
24685
24686         default:
24687           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24688                                          mac_ptr, mac_end, abfd, offset_size,
24689                                          section);
24690           if (mac_ptr == NULL)
24691             return;
24692           break;
24693         }
24694       DIAGNOSTIC_POP
24695     } while (macinfo_type != 0 && current_file == NULL);
24696
24697   /* Second pass: Process all entries.
24698
24699      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24700      command-line macro definitions/undefinitions.  This flag is unset when we
24701      reach the first DW_MACINFO_start_file entry.  */
24702
24703   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24704                                            htab_eq_pointer,
24705                                            NULL, xcalloc, xfree));
24706   mac_ptr = section->buffer + offset;
24707   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24708   *slot = (void *) mac_ptr;
24709   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24710                             abfd, mac_ptr, mac_end,
24711                             current_file, lh, section,
24712                             section_is_gnu, 0, offset_size,
24713                             include_hash.get ());
24714 }
24715
24716 /* Check if the attribute's form is a DW_FORM_block*
24717    if so return true else false.  */
24718
24719 static int
24720 attr_form_is_block (const struct attribute *attr)
24721 {
24722   return (attr == NULL ? 0 :
24723       attr->form == DW_FORM_block1
24724       || attr->form == DW_FORM_block2
24725       || attr->form == DW_FORM_block4
24726       || attr->form == DW_FORM_block
24727       || attr->form == DW_FORM_exprloc);
24728 }
24729
24730 /* Return non-zero if ATTR's value is a section offset --- classes
24731    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24732    You may use DW_UNSND (attr) to retrieve such offsets.
24733
24734    Section 7.5.4, "Attribute Encodings", explains that no attribute
24735    may have a value that belongs to more than one of these classes; it
24736    would be ambiguous if we did, because we use the same forms for all
24737    of them.  */
24738
24739 static int
24740 attr_form_is_section_offset (const struct attribute *attr)
24741 {
24742   return (attr->form == DW_FORM_data4
24743           || attr->form == DW_FORM_data8
24744           || attr->form == DW_FORM_sec_offset);
24745 }
24746
24747 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24748    zero otherwise.  When this function returns true, you can apply
24749    dwarf2_get_attr_constant_value to it.
24750
24751    However, note that for some attributes you must check
24752    attr_form_is_section_offset before using this test.  DW_FORM_data4
24753    and DW_FORM_data8 are members of both the constant class, and of
24754    the classes that contain offsets into other debug sections
24755    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24756    that, if an attribute's can be either a constant or one of the
24757    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24758    taken as section offsets, not constants.
24759
24760    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24761    cannot handle that.  */
24762
24763 static int
24764 attr_form_is_constant (const struct attribute *attr)
24765 {
24766   switch (attr->form)
24767     {
24768     case DW_FORM_sdata:
24769     case DW_FORM_udata:
24770     case DW_FORM_data1:
24771     case DW_FORM_data2:
24772     case DW_FORM_data4:
24773     case DW_FORM_data8:
24774     case DW_FORM_implicit_const:
24775       return 1;
24776     default:
24777       return 0;
24778     }
24779 }
24780
24781
24782 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24783    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24784
24785 static int
24786 attr_form_is_ref (const struct attribute *attr)
24787 {
24788   switch (attr->form)
24789     {
24790     case DW_FORM_ref_addr:
24791     case DW_FORM_ref1:
24792     case DW_FORM_ref2:
24793     case DW_FORM_ref4:
24794     case DW_FORM_ref8:
24795     case DW_FORM_ref_udata:
24796     case DW_FORM_GNU_ref_alt:
24797       return 1;
24798     default:
24799       return 0;
24800     }
24801 }
24802
24803 /* Return the .debug_loc section to use for CU.
24804    For DWO files use .debug_loc.dwo.  */
24805
24806 static struct dwarf2_section_info *
24807 cu_debug_loc_section (struct dwarf2_cu *cu)
24808 {
24809   struct dwarf2_per_objfile *dwarf2_per_objfile
24810     = cu->per_cu->dwarf2_per_objfile;
24811
24812   if (cu->dwo_unit)
24813     {
24814       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24815       
24816       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24817     }
24818   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24819                                   : &dwarf2_per_objfile->loc);
24820 }
24821
24822 /* A helper function that fills in a dwarf2_loclist_baton.  */
24823
24824 static void
24825 fill_in_loclist_baton (struct dwarf2_cu *cu,
24826                        struct dwarf2_loclist_baton *baton,
24827                        const struct attribute *attr)
24828 {
24829   struct dwarf2_per_objfile *dwarf2_per_objfile
24830     = cu->per_cu->dwarf2_per_objfile;
24831   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24832
24833   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24834
24835   baton->per_cu = cu->per_cu;
24836   gdb_assert (baton->per_cu);
24837   /* We don't know how long the location list is, but make sure we
24838      don't run off the edge of the section.  */
24839   baton->size = section->size - DW_UNSND (attr);
24840   baton->data = section->buffer + DW_UNSND (attr);
24841   baton->base_address = cu->base_address;
24842   baton->from_dwo = cu->dwo_unit != NULL;
24843 }
24844
24845 static void
24846 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24847                              struct dwarf2_cu *cu, int is_block)
24848 {
24849   struct dwarf2_per_objfile *dwarf2_per_objfile
24850     = cu->per_cu->dwarf2_per_objfile;
24851   struct objfile *objfile = dwarf2_per_objfile->objfile;
24852   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24853
24854   if (attr_form_is_section_offset (attr)
24855       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24856          the section.  If so, fall through to the complaint in the
24857          other branch.  */
24858       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24859     {
24860       struct dwarf2_loclist_baton *baton;
24861
24862       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24863
24864       fill_in_loclist_baton (cu, baton, attr);
24865
24866       if (cu->base_known == 0)
24867         complaint (&symfile_complaints,
24868                    _("Location list used without "
24869                      "specifying the CU base address."));
24870
24871       SYMBOL_ACLASS_INDEX (sym) = (is_block
24872                                    ? dwarf2_loclist_block_index
24873                                    : dwarf2_loclist_index);
24874       SYMBOL_LOCATION_BATON (sym) = baton;
24875     }
24876   else
24877     {
24878       struct dwarf2_locexpr_baton *baton;
24879
24880       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24881       baton->per_cu = cu->per_cu;
24882       gdb_assert (baton->per_cu);
24883
24884       if (attr_form_is_block (attr))
24885         {
24886           /* Note that we're just copying the block's data pointer
24887              here, not the actual data.  We're still pointing into the
24888              info_buffer for SYM's objfile; right now we never release
24889              that buffer, but when we do clean up properly this may
24890              need to change.  */
24891           baton->size = DW_BLOCK (attr)->size;
24892           baton->data = DW_BLOCK (attr)->data;
24893         }
24894       else
24895         {
24896           dwarf2_invalid_attrib_class_complaint ("location description",
24897                                                  SYMBOL_NATURAL_NAME (sym));
24898           baton->size = 0;
24899         }
24900
24901       SYMBOL_ACLASS_INDEX (sym) = (is_block
24902                                    ? dwarf2_locexpr_block_index
24903                                    : dwarf2_locexpr_index);
24904       SYMBOL_LOCATION_BATON (sym) = baton;
24905     }
24906 }
24907
24908 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24909    came from a separate debuginfo file, then the master objfile is
24910    returned.  */
24911
24912 struct objfile *
24913 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24914 {
24915   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24916
24917   /* Return the master objfile, so that we can report and look up the
24918      correct file containing this variable.  */
24919   if (objfile->separate_debug_objfile_backlink)
24920     objfile = objfile->separate_debug_objfile_backlink;
24921
24922   return objfile;
24923 }
24924
24925 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24926    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24927    CU_HEADERP first.  */
24928
24929 static const struct comp_unit_head *
24930 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24931                        struct dwarf2_per_cu_data *per_cu)
24932 {
24933   const gdb_byte *info_ptr;
24934
24935   if (per_cu->cu)
24936     return &per_cu->cu->header;
24937
24938   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24939
24940   memset (cu_headerp, 0, sizeof (*cu_headerp));
24941   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24942                        rcuh_kind::COMPILE);
24943
24944   return cu_headerp;
24945 }
24946
24947 /* Return the address size given in the compilation unit header for CU.  */
24948
24949 int
24950 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24951 {
24952   struct comp_unit_head cu_header_local;
24953   const struct comp_unit_head *cu_headerp;
24954
24955   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24956
24957   return cu_headerp->addr_size;
24958 }
24959
24960 /* Return the offset size given in the compilation unit header for CU.  */
24961
24962 int
24963 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24964 {
24965   struct comp_unit_head cu_header_local;
24966   const struct comp_unit_head *cu_headerp;
24967
24968   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24969
24970   return cu_headerp->offset_size;
24971 }
24972
24973 /* See its dwarf2loc.h declaration.  */
24974
24975 int
24976 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24977 {
24978   struct comp_unit_head cu_header_local;
24979   const struct comp_unit_head *cu_headerp;
24980
24981   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24982
24983   if (cu_headerp->version == 2)
24984     return cu_headerp->addr_size;
24985   else
24986     return cu_headerp->offset_size;
24987 }
24988
24989 /* Return the text offset of the CU.  The returned offset comes from
24990    this CU's objfile.  If this objfile came from a separate debuginfo
24991    file, then the offset may be different from the corresponding
24992    offset in the parent objfile.  */
24993
24994 CORE_ADDR
24995 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24996 {
24997   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24998
24999   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25000 }
25001
25002 /* Return DWARF version number of PER_CU.  */
25003
25004 short
25005 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25006 {
25007   return per_cu->dwarf_version;
25008 }
25009
25010 /* Locate the .debug_info compilation unit from CU's objfile which contains
25011    the DIE at OFFSET.  Raises an error on failure.  */
25012
25013 static struct dwarf2_per_cu_data *
25014 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25015                                   unsigned int offset_in_dwz,
25016                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25017 {
25018   struct dwarf2_per_cu_data *this_cu;
25019   int low, high;
25020   const sect_offset *cu_off;
25021
25022   low = 0;
25023   high = dwarf2_per_objfile->n_comp_units - 1;
25024   while (high > low)
25025     {
25026       struct dwarf2_per_cu_data *mid_cu;
25027       int mid = low + (high - low) / 2;
25028
25029       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25030       cu_off = &mid_cu->sect_off;
25031       if (mid_cu->is_dwz > offset_in_dwz
25032           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25033         high = mid;
25034       else
25035         low = mid + 1;
25036     }
25037   gdb_assert (low == high);
25038   this_cu = dwarf2_per_objfile->all_comp_units[low];
25039   cu_off = &this_cu->sect_off;
25040   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25041     {
25042       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25043         error (_("Dwarf Error: could not find partial DIE containing "
25044                "offset 0x%x [in module %s]"),
25045                to_underlying (sect_off),
25046                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25047
25048       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25049                   <= sect_off);
25050       return dwarf2_per_objfile->all_comp_units[low-1];
25051     }
25052   else
25053     {
25054       this_cu = dwarf2_per_objfile->all_comp_units[low];
25055       if (low == dwarf2_per_objfile->n_comp_units - 1
25056           && sect_off >= this_cu->sect_off + this_cu->length)
25057         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
25058       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25059       return this_cu;
25060     }
25061 }
25062
25063 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25064
25065 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25066   : per_cu (per_cu_),
25067     mark (0),
25068     has_loclist (0),
25069     checked_producer (0),
25070     producer_is_gxx_lt_4_6 (0),
25071     producer_is_gcc_lt_4_3 (0),
25072     producer_is_icc_lt_14 (0),
25073     processing_has_namespace_info (0)
25074 {
25075   per_cu->cu = this;
25076 }
25077
25078 /* Destroy a dwarf2_cu.  */
25079
25080 dwarf2_cu::~dwarf2_cu ()
25081 {
25082   per_cu->cu = NULL;
25083 }
25084
25085 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25086
25087 static void
25088 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25089                        enum language pretend_language)
25090 {
25091   struct attribute *attr;
25092
25093   /* Set the language we're debugging.  */
25094   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25095   if (attr)
25096     set_cu_language (DW_UNSND (attr), cu);
25097   else
25098     {
25099       cu->language = pretend_language;
25100       cu->language_defn = language_def (cu->language);
25101     }
25102
25103   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25104 }
25105
25106 /* Free all cached compilation units.  */
25107
25108 static void
25109 free_cached_comp_units (void *data)
25110 {
25111   struct dwarf2_per_objfile *dwarf2_per_objfile
25112     = (struct dwarf2_per_objfile *) data;
25113
25114   dwarf2_per_objfile->free_cached_comp_units ();
25115 }
25116
25117 /* Increase the age counter on each cached compilation unit, and free
25118    any that are too old.  */
25119
25120 static void
25121 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25122 {
25123   struct dwarf2_per_cu_data *per_cu, **last_chain;
25124
25125   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25126   per_cu = dwarf2_per_objfile->read_in_chain;
25127   while (per_cu != NULL)
25128     {
25129       per_cu->cu->last_used ++;
25130       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25131         dwarf2_mark (per_cu->cu);
25132       per_cu = per_cu->cu->read_in_chain;
25133     }
25134
25135   per_cu = dwarf2_per_objfile->read_in_chain;
25136   last_chain = &dwarf2_per_objfile->read_in_chain;
25137   while (per_cu != NULL)
25138     {
25139       struct dwarf2_per_cu_data *next_cu;
25140
25141       next_cu = per_cu->cu->read_in_chain;
25142
25143       if (!per_cu->cu->mark)
25144         {
25145           delete per_cu->cu;
25146           *last_chain = next_cu;
25147         }
25148       else
25149         last_chain = &per_cu->cu->read_in_chain;
25150
25151       per_cu = next_cu;
25152     }
25153 }
25154
25155 /* Remove a single compilation unit from the cache.  */
25156
25157 static void
25158 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25159 {
25160   struct dwarf2_per_cu_data *per_cu, **last_chain;
25161   struct dwarf2_per_objfile *dwarf2_per_objfile
25162     = target_per_cu->dwarf2_per_objfile;
25163
25164   per_cu = dwarf2_per_objfile->read_in_chain;
25165   last_chain = &dwarf2_per_objfile->read_in_chain;
25166   while (per_cu != NULL)
25167     {
25168       struct dwarf2_per_cu_data *next_cu;
25169
25170       next_cu = per_cu->cu->read_in_chain;
25171
25172       if (per_cu == target_per_cu)
25173         {
25174           delete per_cu->cu;
25175           per_cu->cu = NULL;
25176           *last_chain = next_cu;
25177           break;
25178         }
25179       else
25180         last_chain = &per_cu->cu->read_in_chain;
25181
25182       per_cu = next_cu;
25183     }
25184 }
25185
25186 /* Release all extra memory associated with OBJFILE.  */
25187
25188 void
25189 dwarf2_free_objfile (struct objfile *objfile)
25190 {
25191   struct dwarf2_per_objfile *dwarf2_per_objfile
25192     = get_dwarf2_per_objfile (objfile);
25193
25194   if (dwarf2_per_objfile == NULL)
25195     return;
25196
25197   dwarf2_per_objfile->~dwarf2_per_objfile ();
25198 }
25199
25200 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25201    We store these in a hash table separate from the DIEs, and preserve them
25202    when the DIEs are flushed out of cache.
25203
25204    The CU "per_cu" pointer is needed because offset alone is not enough to
25205    uniquely identify the type.  A file may have multiple .debug_types sections,
25206    or the type may come from a DWO file.  Furthermore, while it's more logical
25207    to use per_cu->section+offset, with Fission the section with the data is in
25208    the DWO file but we don't know that section at the point we need it.
25209    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25210    because we can enter the lookup routine, get_die_type_at_offset, from
25211    outside this file, and thus won't necessarily have PER_CU->cu.
25212    Fortunately, PER_CU is stable for the life of the objfile.  */
25213
25214 struct dwarf2_per_cu_offset_and_type
25215 {
25216   const struct dwarf2_per_cu_data *per_cu;
25217   sect_offset sect_off;
25218   struct type *type;
25219 };
25220
25221 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25222
25223 static hashval_t
25224 per_cu_offset_and_type_hash (const void *item)
25225 {
25226   const struct dwarf2_per_cu_offset_and_type *ofs
25227     = (const struct dwarf2_per_cu_offset_and_type *) item;
25228
25229   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25230 }
25231
25232 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25233
25234 static int
25235 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25236 {
25237   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25238     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25239   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25240     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25241
25242   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25243           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25244 }
25245
25246 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25247    table if necessary.  For convenience, return TYPE.
25248
25249    The DIEs reading must have careful ordering to:
25250     * Not cause infite loops trying to read in DIEs as a prerequisite for
25251       reading current DIE.
25252     * Not trying to dereference contents of still incompletely read in types
25253       while reading in other DIEs.
25254     * Enable referencing still incompletely read in types just by a pointer to
25255       the type without accessing its fields.
25256
25257    Therefore caller should follow these rules:
25258      * Try to fetch any prerequisite types we may need to build this DIE type
25259        before building the type and calling set_die_type.
25260      * After building type call set_die_type for current DIE as soon as
25261        possible before fetching more types to complete the current type.
25262      * Make the type as complete as possible before fetching more types.  */
25263
25264 static struct type *
25265 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25266 {
25267   struct dwarf2_per_objfile *dwarf2_per_objfile
25268     = cu->per_cu->dwarf2_per_objfile;
25269   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25270   struct objfile *objfile = dwarf2_per_objfile->objfile;
25271   struct attribute *attr;
25272   struct dynamic_prop prop;
25273
25274   /* For Ada types, make sure that the gnat-specific data is always
25275      initialized (if not already set).  There are a few types where
25276      we should not be doing so, because the type-specific area is
25277      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25278      where the type-specific area is used to store the floatformat).
25279      But this is not a problem, because the gnat-specific information
25280      is actually not needed for these types.  */
25281   if (need_gnat_info (cu)
25282       && TYPE_CODE (type) != TYPE_CODE_FUNC
25283       && TYPE_CODE (type) != TYPE_CODE_FLT
25284       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25285       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25286       && TYPE_CODE (type) != TYPE_CODE_METHOD
25287       && !HAVE_GNAT_AUX_INFO (type))
25288     INIT_GNAT_SPECIFIC (type);
25289
25290   /* Read DW_AT_allocated and set in type.  */
25291   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25292   if (attr_form_is_block (attr))
25293     {
25294       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25295         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25296     }
25297   else if (attr != NULL)
25298     {
25299       complaint (&symfile_complaints,
25300                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25301                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25302                  to_underlying (die->sect_off));
25303     }
25304
25305   /* Read DW_AT_associated and set in type.  */
25306   attr = dwarf2_attr (die, DW_AT_associated, cu);
25307   if (attr_form_is_block (attr))
25308     {
25309       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25310         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25311     }
25312   else if (attr != NULL)
25313     {
25314       complaint (&symfile_complaints,
25315                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25316                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25317                  to_underlying (die->sect_off));
25318     }
25319
25320   /* Read DW_AT_data_location and set in type.  */
25321   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25322   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25323     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25324
25325   if (dwarf2_per_objfile->die_type_hash == NULL)
25326     {
25327       dwarf2_per_objfile->die_type_hash =
25328         htab_create_alloc_ex (127,
25329                               per_cu_offset_and_type_hash,
25330                               per_cu_offset_and_type_eq,
25331                               NULL,
25332                               &objfile->objfile_obstack,
25333                               hashtab_obstack_allocate,
25334                               dummy_obstack_deallocate);
25335     }
25336
25337   ofs.per_cu = cu->per_cu;
25338   ofs.sect_off = die->sect_off;
25339   ofs.type = type;
25340   slot = (struct dwarf2_per_cu_offset_and_type **)
25341     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25342   if (*slot)
25343     complaint (&symfile_complaints,
25344                _("A problem internal to GDB: DIE 0x%x has type already set"),
25345                to_underlying (die->sect_off));
25346   *slot = XOBNEW (&objfile->objfile_obstack,
25347                   struct dwarf2_per_cu_offset_and_type);
25348   **slot = ofs;
25349   return type;
25350 }
25351
25352 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25353    or return NULL if the die does not have a saved type.  */
25354
25355 static struct type *
25356 get_die_type_at_offset (sect_offset sect_off,
25357                         struct dwarf2_per_cu_data *per_cu)
25358 {
25359   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25360   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25361
25362   if (dwarf2_per_objfile->die_type_hash == NULL)
25363     return NULL;
25364
25365   ofs.per_cu = per_cu;
25366   ofs.sect_off = sect_off;
25367   slot = ((struct dwarf2_per_cu_offset_and_type *)
25368           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25369   if (slot)
25370     return slot->type;
25371   else
25372     return NULL;
25373 }
25374
25375 /* Look up the type for DIE in CU in die_type_hash,
25376    or return NULL if DIE does not have a saved type.  */
25377
25378 static struct type *
25379 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25380 {
25381   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25382 }
25383
25384 /* Add a dependence relationship from CU to REF_PER_CU.  */
25385
25386 static void
25387 dwarf2_add_dependence (struct dwarf2_cu *cu,
25388                        struct dwarf2_per_cu_data *ref_per_cu)
25389 {
25390   void **slot;
25391
25392   if (cu->dependencies == NULL)
25393     cu->dependencies
25394       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25395                               NULL, &cu->comp_unit_obstack,
25396                               hashtab_obstack_allocate,
25397                               dummy_obstack_deallocate);
25398
25399   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25400   if (*slot == NULL)
25401     *slot = ref_per_cu;
25402 }
25403
25404 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25405    Set the mark field in every compilation unit in the
25406    cache that we must keep because we are keeping CU.  */
25407
25408 static int
25409 dwarf2_mark_helper (void **slot, void *data)
25410 {
25411   struct dwarf2_per_cu_data *per_cu;
25412
25413   per_cu = (struct dwarf2_per_cu_data *) *slot;
25414
25415   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25416      reading of the chain.  As such dependencies remain valid it is not much
25417      useful to track and undo them during QUIT cleanups.  */
25418   if (per_cu->cu == NULL)
25419     return 1;
25420
25421   if (per_cu->cu->mark)
25422     return 1;
25423   per_cu->cu->mark = 1;
25424
25425   if (per_cu->cu->dependencies != NULL)
25426     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25427
25428   return 1;
25429 }
25430
25431 /* Set the mark field in CU and in every other compilation unit in the
25432    cache that we must keep because we are keeping CU.  */
25433
25434 static void
25435 dwarf2_mark (struct dwarf2_cu *cu)
25436 {
25437   if (cu->mark)
25438     return;
25439   cu->mark = 1;
25440   if (cu->dependencies != NULL)
25441     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25442 }
25443
25444 static void
25445 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25446 {
25447   while (per_cu)
25448     {
25449       per_cu->cu->mark = 0;
25450       per_cu = per_cu->cu->read_in_chain;
25451     }
25452 }
25453
25454 /* Trivial hash function for partial_die_info: the hash value of a DIE
25455    is its offset in .debug_info for this objfile.  */
25456
25457 static hashval_t
25458 partial_die_hash (const void *item)
25459 {
25460   const struct partial_die_info *part_die
25461     = (const struct partial_die_info *) item;
25462
25463   return to_underlying (part_die->sect_off);
25464 }
25465
25466 /* Trivial comparison function for partial_die_info structures: two DIEs
25467    are equal if they have the same offset.  */
25468
25469 static int
25470 partial_die_eq (const void *item_lhs, const void *item_rhs)
25471 {
25472   const struct partial_die_info *part_die_lhs
25473     = (const struct partial_die_info *) item_lhs;
25474   const struct partial_die_info *part_die_rhs
25475     = (const struct partial_die_info *) item_rhs;
25476
25477   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25478 }
25479
25480 static struct cmd_list_element *set_dwarf_cmdlist;
25481 static struct cmd_list_element *show_dwarf_cmdlist;
25482
25483 static void
25484 set_dwarf_cmd (const char *args, int from_tty)
25485 {
25486   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25487              gdb_stdout);
25488 }
25489
25490 static void
25491 show_dwarf_cmd (const char *args, int from_tty)
25492 {
25493   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25494 }
25495
25496 /* The "save gdb-index" command.  */
25497
25498 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25499    error checking.  */
25500
25501 static void
25502 file_write (FILE *file, const void *data, size_t size)
25503 {
25504   if (fwrite (data, 1, size, file) != size)
25505     error (_("couldn't data write to file"));
25506 }
25507
25508 /* Write the contents of VEC to FILE, with error checking.  */
25509
25510 template<typename Elem, typename Alloc>
25511 static void
25512 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25513 {
25514   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25515 }
25516
25517 /* In-memory buffer to prepare data to be written later to a file.  */
25518 class data_buf
25519 {
25520 public:
25521   /* Copy DATA to the end of the buffer.  */
25522   template<typename T>
25523   void append_data (const T &data)
25524   {
25525     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25526                reinterpret_cast<const gdb_byte *> (&data + 1),
25527                grow (sizeof (data)));
25528   }
25529
25530   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25531      terminating zero is appended too.  */
25532   void append_cstr0 (const char *cstr)
25533   {
25534     const size_t size = strlen (cstr) + 1;
25535     std::copy (cstr, cstr + size, grow (size));
25536   }
25537
25538   /* Store INPUT as ULEB128 to the end of buffer.  */
25539   void append_unsigned_leb128 (ULONGEST input)
25540   {
25541     for (;;)
25542       {
25543         gdb_byte output = input & 0x7f;
25544         input >>= 7;
25545         if (input)
25546           output |= 0x80;
25547         append_data (output);
25548         if (input == 0)
25549           break;
25550       }
25551   }
25552
25553   /* Accept a host-format integer in VAL and append it to the buffer
25554      as a target-format integer which is LEN bytes long.  */
25555   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25556   {
25557     ::store_unsigned_integer (grow (len), len, byte_order, val);
25558   }
25559
25560   /* Return the size of the buffer.  */
25561   size_t size () const
25562   {
25563     return m_vec.size ();
25564   }
25565
25566   /* Return true iff the buffer is empty.  */
25567   bool empty () const
25568   {
25569     return m_vec.empty ();
25570   }
25571
25572   /* Write the buffer to FILE.  */
25573   void file_write (FILE *file) const
25574   {
25575     ::file_write (file, m_vec);
25576   }
25577
25578 private:
25579   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25580      the start of the new block.  */
25581   gdb_byte *grow (size_t size)
25582   {
25583     m_vec.resize (m_vec.size () + size);
25584     return &*m_vec.end () - size;
25585   }
25586
25587   gdb::byte_vector m_vec;
25588 };
25589
25590 /* An entry in the symbol table.  */
25591 struct symtab_index_entry
25592 {
25593   /* The name of the symbol.  */
25594   const char *name;
25595   /* The offset of the name in the constant pool.  */
25596   offset_type index_offset;
25597   /* A sorted vector of the indices of all the CUs that hold an object
25598      of this name.  */
25599   std::vector<offset_type> cu_indices;
25600 };
25601
25602 /* The symbol table.  This is a power-of-2-sized hash table.  */
25603 struct mapped_symtab
25604 {
25605   mapped_symtab ()
25606   {
25607     data.resize (1024);
25608   }
25609
25610   offset_type n_elements = 0;
25611   std::vector<symtab_index_entry> data;
25612 };
25613
25614 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25615    the slot.
25616    
25617    Function is used only during write_hash_table so no index format backward
25618    compatibility is needed.  */
25619
25620 static symtab_index_entry &
25621 find_slot (struct mapped_symtab *symtab, const char *name)
25622 {
25623   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25624
25625   index = hash & (symtab->data.size () - 1);
25626   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25627
25628   for (;;)
25629     {
25630       if (symtab->data[index].name == NULL
25631           || strcmp (name, symtab->data[index].name) == 0)
25632         return symtab->data[index];
25633       index = (index + step) & (symtab->data.size () - 1);
25634     }
25635 }
25636
25637 /* Expand SYMTAB's hash table.  */
25638
25639 static void
25640 hash_expand (struct mapped_symtab *symtab)
25641 {
25642   auto old_entries = std::move (symtab->data);
25643
25644   symtab->data.clear ();
25645   symtab->data.resize (old_entries.size () * 2);
25646
25647   for (auto &it : old_entries)
25648     if (it.name != NULL)
25649       {
25650         auto &ref = find_slot (symtab, it.name);
25651         ref = std::move (it);
25652       }
25653 }
25654
25655 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25656    CU_INDEX is the index of the CU in which the symbol appears.
25657    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25658
25659 static void
25660 add_index_entry (struct mapped_symtab *symtab, const char *name,
25661                  int is_static, gdb_index_symbol_kind kind,
25662                  offset_type cu_index)
25663 {
25664   offset_type cu_index_and_attrs;
25665
25666   ++symtab->n_elements;
25667   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25668     hash_expand (symtab);
25669
25670   symtab_index_entry &slot = find_slot (symtab, name);
25671   if (slot.name == NULL)
25672     {
25673       slot.name = name;
25674       /* index_offset is set later.  */
25675     }
25676
25677   cu_index_and_attrs = 0;
25678   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25679   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25680   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25681
25682   /* We don't want to record an index value twice as we want to avoid the
25683      duplication.
25684      We process all global symbols and then all static symbols
25685      (which would allow us to avoid the duplication by only having to check
25686      the last entry pushed), but a symbol could have multiple kinds in one CU.
25687      To keep things simple we don't worry about the duplication here and
25688      sort and uniqufy the list after we've processed all symbols.  */
25689   slot.cu_indices.push_back (cu_index_and_attrs);
25690 }
25691
25692 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25693
25694 static void
25695 uniquify_cu_indices (struct mapped_symtab *symtab)
25696 {
25697   for (auto &entry : symtab->data)
25698     {
25699       if (entry.name != NULL && !entry.cu_indices.empty ())
25700         {
25701           auto &cu_indices = entry.cu_indices;
25702           std::sort (cu_indices.begin (), cu_indices.end ());
25703           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25704           cu_indices.erase (from, cu_indices.end ());
25705         }
25706     }
25707 }
25708
25709 /* A form of 'const char *' suitable for container keys.  Only the
25710    pointer is stored.  The strings themselves are compared, not the
25711    pointers.  */
25712 class c_str_view
25713 {
25714 public:
25715   c_str_view (const char *cstr)
25716     : m_cstr (cstr)
25717   {}
25718
25719   bool operator== (const c_str_view &other) const
25720   {
25721     return strcmp (m_cstr, other.m_cstr) == 0;
25722   }
25723
25724   /* Return the underlying C string.  Note, the returned string is
25725      only a reference with lifetime of this object.  */
25726   const char *c_str () const
25727   {
25728     return m_cstr;
25729   }
25730
25731 private:
25732   friend class c_str_view_hasher;
25733   const char *const m_cstr;
25734 };
25735
25736 /* A std::unordered_map::hasher for c_str_view that uses the right
25737    hash function for strings in a mapped index.  */
25738 class c_str_view_hasher
25739 {
25740 public:
25741   size_t operator () (const c_str_view &x) const
25742   {
25743     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25744   }
25745 };
25746
25747 /* A std::unordered_map::hasher for std::vector<>.  */
25748 template<typename T>
25749 class vector_hasher
25750 {
25751 public:
25752   size_t operator () (const std::vector<T> &key) const
25753   {
25754     return iterative_hash (key.data (),
25755                            sizeof (key.front ()) * key.size (), 0);
25756   }
25757 };
25758
25759 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25760    constant pool entries going into the data buffer CPOOL.  */
25761
25762 static void
25763 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25764 {
25765   {
25766     /* Elements are sorted vectors of the indices of all the CUs that
25767        hold an object of this name.  */
25768     std::unordered_map<std::vector<offset_type>, offset_type,
25769                        vector_hasher<offset_type>>
25770       symbol_hash_table;
25771
25772     /* We add all the index vectors to the constant pool first, to
25773        ensure alignment is ok.  */
25774     for (symtab_index_entry &entry : symtab->data)
25775       {
25776         if (entry.name == NULL)
25777           continue;
25778         gdb_assert (entry.index_offset == 0);
25779
25780         /* Finding before inserting is faster than always trying to
25781            insert, because inserting always allocates a node, does the
25782            lookup, and then destroys the new node if another node
25783            already had the same key.  C++17 try_emplace will avoid
25784            this.  */
25785         const auto found
25786           = symbol_hash_table.find (entry.cu_indices);
25787         if (found != symbol_hash_table.end ())
25788           {
25789             entry.index_offset = found->second;
25790             continue;
25791           }
25792
25793         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25794         entry.index_offset = cpool.size ();
25795         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25796         for (const auto index : entry.cu_indices)
25797           cpool.append_data (MAYBE_SWAP (index));
25798       }
25799   }
25800
25801   /* Now write out the hash table.  */
25802   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25803   for (const auto &entry : symtab->data)
25804     {
25805       offset_type str_off, vec_off;
25806
25807       if (entry.name != NULL)
25808         {
25809           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25810           if (insertpair.second)
25811             cpool.append_cstr0 (entry.name);
25812           str_off = insertpair.first->second;
25813           vec_off = entry.index_offset;
25814         }
25815       else
25816         {
25817           /* While 0 is a valid constant pool index, it is not valid
25818              to have 0 for both offsets.  */
25819           str_off = 0;
25820           vec_off = 0;
25821         }
25822
25823       output.append_data (MAYBE_SWAP (str_off));
25824       output.append_data (MAYBE_SWAP (vec_off));
25825     }
25826 }
25827
25828 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25829
25830 /* Helper struct for building the address table.  */
25831 struct addrmap_index_data
25832 {
25833   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25834     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25835   {}
25836
25837   struct objfile *objfile;
25838   data_buf &addr_vec;
25839   psym_index_map &cu_index_htab;
25840
25841   /* Non-zero if the previous_* fields are valid.
25842      We can't write an entry until we see the next entry (since it is only then
25843      that we know the end of the entry).  */
25844   int previous_valid;
25845   /* Index of the CU in the table of all CUs in the index file.  */
25846   unsigned int previous_cu_index;
25847   /* Start address of the CU.  */
25848   CORE_ADDR previous_cu_start;
25849 };
25850
25851 /* Write an address entry to ADDR_VEC.  */
25852
25853 static void
25854 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25855                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25856 {
25857   CORE_ADDR baseaddr;
25858
25859   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25860
25861   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25862   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25863   addr_vec.append_data (MAYBE_SWAP (cu_index));
25864 }
25865
25866 /* Worker function for traversing an addrmap to build the address table.  */
25867
25868 static int
25869 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25870 {
25871   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25872   struct partial_symtab *pst = (struct partial_symtab *) obj;
25873
25874   if (data->previous_valid)
25875     add_address_entry (data->objfile, data->addr_vec,
25876                        data->previous_cu_start, start_addr,
25877                        data->previous_cu_index);
25878
25879   data->previous_cu_start = start_addr;
25880   if (pst != NULL)
25881     {
25882       const auto it = data->cu_index_htab.find (pst);
25883       gdb_assert (it != data->cu_index_htab.cend ());
25884       data->previous_cu_index = it->second;
25885       data->previous_valid = 1;
25886     }
25887   else
25888     data->previous_valid = 0;
25889
25890   return 0;
25891 }
25892
25893 /* Write OBJFILE's address map to ADDR_VEC.
25894    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25895    in the index file.  */
25896
25897 static void
25898 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25899                    psym_index_map &cu_index_htab)
25900 {
25901   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25902
25903   /* When writing the address table, we have to cope with the fact that
25904      the addrmap iterator only provides the start of a region; we have to
25905      wait until the next invocation to get the start of the next region.  */
25906
25907   addrmap_index_data.objfile = objfile;
25908   addrmap_index_data.previous_valid = 0;
25909
25910   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25911                    &addrmap_index_data);
25912
25913   /* It's highly unlikely the last entry (end address = 0xff...ff)
25914      is valid, but we should still handle it.
25915      The end address is recorded as the start of the next region, but that
25916      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25917      anyway.  */
25918   if (addrmap_index_data.previous_valid)
25919     add_address_entry (objfile, addr_vec,
25920                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25921                        addrmap_index_data.previous_cu_index);
25922 }
25923
25924 /* Return the symbol kind of PSYM.  */
25925
25926 static gdb_index_symbol_kind
25927 symbol_kind (struct partial_symbol *psym)
25928 {
25929   domain_enum domain = PSYMBOL_DOMAIN (psym);
25930   enum address_class aclass = PSYMBOL_CLASS (psym);
25931
25932   switch (domain)
25933     {
25934     case VAR_DOMAIN:
25935       switch (aclass)
25936         {
25937         case LOC_BLOCK:
25938           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25939         case LOC_TYPEDEF:
25940           return GDB_INDEX_SYMBOL_KIND_TYPE;
25941         case LOC_COMPUTED:
25942         case LOC_CONST_BYTES:
25943         case LOC_OPTIMIZED_OUT:
25944         case LOC_STATIC:
25945           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25946         case LOC_CONST:
25947           /* Note: It's currently impossible to recognize psyms as enum values
25948              short of reading the type info.  For now punt.  */
25949           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25950         default:
25951           /* There are other LOC_FOO values that one might want to classify
25952              as variables, but dwarf2read.c doesn't currently use them.  */
25953           return GDB_INDEX_SYMBOL_KIND_OTHER;
25954         }
25955     case STRUCT_DOMAIN:
25956       return GDB_INDEX_SYMBOL_KIND_TYPE;
25957     default:
25958       return GDB_INDEX_SYMBOL_KIND_OTHER;
25959     }
25960 }
25961
25962 /* Add a list of partial symbols to SYMTAB.  */
25963
25964 static void
25965 write_psymbols (struct mapped_symtab *symtab,
25966                 std::unordered_set<partial_symbol *> &psyms_seen,
25967                 struct partial_symbol **psymp,
25968                 int count,
25969                 offset_type cu_index,
25970                 int is_static)
25971 {
25972   for (; count-- > 0; ++psymp)
25973     {
25974       struct partial_symbol *psym = *psymp;
25975
25976       if (SYMBOL_LANGUAGE (psym) == language_ada)
25977         error (_("Ada is not currently supported by the index"));
25978
25979       /* Only add a given psymbol once.  */
25980       if (psyms_seen.insert (psym).second)
25981         {
25982           gdb_index_symbol_kind kind = symbol_kind (psym);
25983
25984           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
25985                            is_static, kind, cu_index);
25986         }
25987     }
25988 }
25989
25990 /* A helper struct used when iterating over debug_types.  */
25991 struct signatured_type_index_data
25992 {
25993   signatured_type_index_data (data_buf &types_list_,
25994                               std::unordered_set<partial_symbol *> &psyms_seen_)
25995     : types_list (types_list_), psyms_seen (psyms_seen_)
25996   {}
25997
25998   struct objfile *objfile;
25999   struct mapped_symtab *symtab;
26000   data_buf &types_list;
26001   std::unordered_set<partial_symbol *> &psyms_seen;
26002   int cu_index;
26003 };
26004
26005 /* A helper function that writes a single signatured_type to an
26006    obstack.  */
26007
26008 static int
26009 write_one_signatured_type (void **slot, void *d)
26010 {
26011   struct signatured_type_index_data *info
26012     = (struct signatured_type_index_data *) d;
26013   struct signatured_type *entry = (struct signatured_type *) *slot;
26014   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26015
26016   write_psymbols (info->symtab,
26017                   info->psyms_seen,
26018                   &info->objfile->global_psymbols[psymtab->globals_offset],
26019                   psymtab->n_global_syms, info->cu_index,
26020                   0);
26021   write_psymbols (info->symtab,
26022                   info->psyms_seen,
26023                   &info->objfile->static_psymbols[psymtab->statics_offset],
26024                   psymtab->n_static_syms, info->cu_index,
26025                   1);
26026
26027   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26028                                 to_underlying (entry->per_cu.sect_off));
26029   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26030                                 to_underlying (entry->type_offset_in_tu));
26031   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26032
26033   ++info->cu_index;
26034
26035   return 1;
26036 }
26037
26038 /* Recurse into all "included" dependencies and count their symbols as
26039    if they appeared in this psymtab.  */
26040
26041 static void
26042 recursively_count_psymbols (struct partial_symtab *psymtab,
26043                             size_t &psyms_seen)
26044 {
26045   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26046     if (psymtab->dependencies[i]->user != NULL)
26047       recursively_count_psymbols (psymtab->dependencies[i],
26048                                   psyms_seen);
26049
26050   psyms_seen += psymtab->n_global_syms;
26051   psyms_seen += psymtab->n_static_syms;
26052 }
26053
26054 /* Recurse into all "included" dependencies and write their symbols as
26055    if they appeared in this psymtab.  */
26056
26057 static void
26058 recursively_write_psymbols (struct objfile *objfile,
26059                             struct partial_symtab *psymtab,
26060                             struct mapped_symtab *symtab,
26061                             std::unordered_set<partial_symbol *> &psyms_seen,
26062                             offset_type cu_index)
26063 {
26064   int i;
26065
26066   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26067     if (psymtab->dependencies[i]->user != NULL)
26068       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26069                                   symtab, psyms_seen, cu_index);
26070
26071   write_psymbols (symtab,
26072                   psyms_seen,
26073                   &objfile->global_psymbols[psymtab->globals_offset],
26074                   psymtab->n_global_syms, cu_index,
26075                   0);
26076   write_psymbols (symtab,
26077                   psyms_seen,
26078                   &objfile->static_psymbols[psymtab->statics_offset],
26079                   psymtab->n_static_syms, cu_index,
26080                   1);
26081 }
26082
26083 /* DWARF-5 .debug_names builder.  */
26084 class debug_names
26085 {
26086 public:
26087   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26088                bfd_endian dwarf5_byte_order)
26089     : m_dwarf5_byte_order (dwarf5_byte_order),
26090       m_dwarf32 (dwarf5_byte_order),
26091       m_dwarf64 (dwarf5_byte_order),
26092       m_dwarf (is_dwarf64
26093                ? static_cast<dwarf &> (m_dwarf64)
26094                : static_cast<dwarf &> (m_dwarf32)),
26095       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26096       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26097       m_debugstrlookup (dwarf2_per_objfile)
26098   {}
26099
26100   int dwarf5_offset_size () const
26101   {
26102     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26103     return dwarf5_is_dwarf64 ? 8 : 4;
26104   }
26105
26106   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26107   enum class unit_kind { cu, tu };
26108
26109   /* Insert one symbol.  */
26110   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26111                unit_kind kind)
26112   {
26113     const int dwarf_tag = psymbol_tag (psym);
26114     if (dwarf_tag == 0)
26115       return;
26116     const char *const name = SYMBOL_SEARCH_NAME (psym);
26117     const auto insertpair
26118       = m_name_to_value_set.emplace (c_str_view (name),
26119                                      std::set<symbol_value> ());
26120     std::set<symbol_value> &value_set = insertpair.first->second;
26121     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26122   }
26123
26124   /* Build all the tables.  All symbols must be already inserted.
26125      This function does not call file_write, caller has to do it
26126      afterwards.  */
26127   void build ()
26128   {
26129     /* Verify the build method has not be called twice.  */
26130     gdb_assert (m_abbrev_table.empty ());
26131     const size_t name_count = m_name_to_value_set.size ();
26132     m_bucket_table.resize
26133       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26134     m_hash_table.reserve (name_count);
26135     m_name_table_string_offs.reserve (name_count);
26136     m_name_table_entry_offs.reserve (name_count);
26137
26138     /* Map each hash of symbol to its name and value.  */
26139     struct hash_it_pair
26140     {
26141       uint32_t hash;
26142       decltype (m_name_to_value_set)::const_iterator it;
26143     };
26144     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26145     bucket_hash.resize (m_bucket_table.size ());
26146     for (decltype (m_name_to_value_set)::const_iterator it
26147            = m_name_to_value_set.cbegin ();
26148          it != m_name_to_value_set.cend ();
26149          ++it)
26150       {
26151         const char *const name = it->first.c_str ();
26152         const uint32_t hash = dwarf5_djb_hash (name);
26153         hash_it_pair hashitpair;
26154         hashitpair.hash = hash;
26155         hashitpair.it = it;
26156         auto &slot = bucket_hash[hash % bucket_hash.size()];
26157         slot.push_front (std::move (hashitpair));
26158       }
26159     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26160       {
26161         const std::forward_list<hash_it_pair> &hashitlist
26162           = bucket_hash[bucket_ix];
26163         if (hashitlist.empty ())
26164           continue;
26165         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26166         /* The hashes array is indexed starting at 1.  */
26167         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26168                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26169                                 m_hash_table.size () + 1);
26170         for (const hash_it_pair &hashitpair : hashitlist)
26171           {
26172             m_hash_table.push_back (0);
26173             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26174                                                         (&m_hash_table.back ()),
26175                                     sizeof (m_hash_table.back ()),
26176                                     m_dwarf5_byte_order, hashitpair.hash);
26177             const c_str_view &name = hashitpair.it->first;
26178             const std::set<symbol_value> &value_set = hashitpair.it->second;
26179             m_name_table_string_offs.push_back_reorder
26180               (m_debugstrlookup.lookup (name.c_str ()));
26181             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26182             gdb_assert (!value_set.empty ());
26183             for (const symbol_value &value : value_set)
26184               {
26185                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26186                                                         value.is_static,
26187                                                         value.kind)];
26188                 if (idx == 0)
26189                   {
26190                     idx = m_idx_next++;
26191                     m_abbrev_table.append_unsigned_leb128 (idx);
26192                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26193                     m_abbrev_table.append_unsigned_leb128
26194                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26195                                                            : DW_IDX_type_unit);
26196                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26197                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26198                                                            ? DW_IDX_GNU_internal
26199                                                            : DW_IDX_GNU_external);
26200                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26201
26202                     /* Terminate attributes list.  */
26203                     m_abbrev_table.append_unsigned_leb128 (0);
26204                     m_abbrev_table.append_unsigned_leb128 (0);
26205                   }
26206
26207                 m_entry_pool.append_unsigned_leb128 (idx);
26208                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26209               }
26210
26211             /* Terminate the list of CUs.  */
26212             m_entry_pool.append_unsigned_leb128 (0);
26213           }
26214       }
26215     gdb_assert (m_hash_table.size () == name_count);
26216
26217     /* Terminate tags list.  */
26218     m_abbrev_table.append_unsigned_leb128 (0);
26219   }
26220
26221   /* Return .debug_names bucket count.  This must be called only after
26222      calling the build method.  */
26223   uint32_t bucket_count () const
26224   {
26225     /* Verify the build method has been already called.  */
26226     gdb_assert (!m_abbrev_table.empty ());
26227     const uint32_t retval = m_bucket_table.size ();
26228
26229     /* Check for overflow.  */
26230     gdb_assert (retval == m_bucket_table.size ());
26231     return retval;
26232   }
26233
26234   /* Return .debug_names names count.  This must be called only after
26235      calling the build method.  */
26236   uint32_t name_count () const
26237   {
26238     /* Verify the build method has been already called.  */
26239     gdb_assert (!m_abbrev_table.empty ());
26240     const uint32_t retval = m_hash_table.size ();
26241
26242     /* Check for overflow.  */
26243     gdb_assert (retval == m_hash_table.size ());
26244     return retval;
26245   }
26246
26247   /* Return number of bytes of .debug_names abbreviation table.  This
26248      must be called only after calling the build method.  */
26249   uint32_t abbrev_table_bytes () const
26250   {
26251     gdb_assert (!m_abbrev_table.empty ());
26252     return m_abbrev_table.size ();
26253   }
26254
26255   /* Recurse into all "included" dependencies and store their symbols
26256      as if they appeared in this psymtab.  */
26257   void recursively_write_psymbols
26258     (struct objfile *objfile,
26259      struct partial_symtab *psymtab,
26260      std::unordered_set<partial_symbol *> &psyms_seen,
26261      int cu_index)
26262   {
26263     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26264       if (psymtab->dependencies[i]->user != NULL)
26265         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26266                                     psyms_seen, cu_index);
26267
26268     write_psymbols (psyms_seen,
26269                     &objfile->global_psymbols[psymtab->globals_offset],
26270                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26271     write_psymbols (psyms_seen,
26272                     &objfile->static_psymbols[psymtab->statics_offset],
26273                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26274   }
26275
26276   /* Return number of bytes the .debug_names section will have.  This
26277      must be called only after calling the build method.  */
26278   size_t bytes () const
26279   {
26280     /* Verify the build method has been already called.  */
26281     gdb_assert (!m_abbrev_table.empty ());
26282     size_t expected_bytes = 0;
26283     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26284     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26285     expected_bytes += m_name_table_string_offs.bytes ();
26286     expected_bytes += m_name_table_entry_offs.bytes ();
26287     expected_bytes += m_abbrev_table.size ();
26288     expected_bytes += m_entry_pool.size ();
26289     return expected_bytes;
26290   }
26291
26292   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26293      FILE_STR.  This must be called only after calling the build
26294      method.  */
26295   void file_write (FILE *file_names, FILE *file_str) const
26296   {
26297     /* Verify the build method has been already called.  */
26298     gdb_assert (!m_abbrev_table.empty ());
26299     ::file_write (file_names, m_bucket_table);
26300     ::file_write (file_names, m_hash_table);
26301     m_name_table_string_offs.file_write (file_names);
26302     m_name_table_entry_offs.file_write (file_names);
26303     m_abbrev_table.file_write (file_names);
26304     m_entry_pool.file_write (file_names);
26305     m_debugstrlookup.file_write (file_str);
26306   }
26307
26308   /* A helper user data for write_one_signatured_type.  */
26309   class write_one_signatured_type_data
26310   {
26311   public:
26312     write_one_signatured_type_data (debug_names &nametable_,
26313                                     signatured_type_index_data &&info_)
26314     : nametable (nametable_), info (std::move (info_))
26315     {}
26316     debug_names &nametable;
26317     struct signatured_type_index_data info;
26318   };
26319
26320   /* A helper function to pass write_one_signatured_type to
26321      htab_traverse_noresize.  */
26322   static int
26323   write_one_signatured_type (void **slot, void *d)
26324   {
26325     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26326     struct signatured_type_index_data *info = &data->info;
26327     struct signatured_type *entry = (struct signatured_type *) *slot;
26328
26329     data->nametable.write_one_signatured_type (entry, info);
26330
26331     return 1;
26332   }
26333
26334 private:
26335
26336   /* Storage for symbol names mapping them to their .debug_str section
26337      offsets.  */
26338   class debug_str_lookup
26339   {
26340   public:
26341
26342     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26343        All .debug_str section strings are automatically stored.  */
26344     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26345       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26346         m_dwarf2_per_objfile (dwarf2_per_objfile)
26347     {
26348       dwarf2_read_section (dwarf2_per_objfile->objfile,
26349                            &dwarf2_per_objfile->str);
26350       if (dwarf2_per_objfile->str.buffer == NULL)
26351         return;
26352       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26353            data < (dwarf2_per_objfile->str.buffer
26354                    + dwarf2_per_objfile->str.size);)
26355         {
26356           const char *const s = reinterpret_cast<const char *> (data);
26357           const auto insertpair
26358             = m_str_table.emplace (c_str_view (s),
26359                                    data - dwarf2_per_objfile->str.buffer);
26360           if (!insertpair.second)
26361             complaint (&symfile_complaints,
26362                        _("Duplicate string \"%s\" in "
26363                          ".debug_str section [in module %s]"),
26364                        s, bfd_get_filename (m_abfd));
26365           data += strlen (s) + 1;
26366         }
26367     }
26368
26369     /* Return offset of symbol name S in the .debug_str section.  Add
26370        such symbol to the section's end if it does not exist there
26371        yet.  */
26372     size_t lookup (const char *s)
26373     {
26374       const auto it = m_str_table.find (c_str_view (s));
26375       if (it != m_str_table.end ())
26376         return it->second;
26377       const size_t offset = (m_dwarf2_per_objfile->str.size
26378                              + m_str_add_buf.size ());
26379       m_str_table.emplace (c_str_view (s), offset);
26380       m_str_add_buf.append_cstr0 (s);
26381       return offset;
26382     }
26383
26384     /* Append the end of the .debug_str section to FILE.  */
26385     void file_write (FILE *file) const
26386     {
26387       m_str_add_buf.file_write (file);
26388     }
26389
26390   private:
26391     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26392     bfd *const m_abfd;
26393     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26394
26395     /* Data to add at the end of .debug_str for new needed symbol names.  */
26396     data_buf m_str_add_buf;
26397   };
26398
26399   /* Container to map used DWARF tags to their .debug_names abbreviation
26400      tags.  */
26401   class index_key
26402   {
26403   public:
26404     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26405       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26406     {
26407     }
26408
26409     bool
26410     operator== (const index_key &other) const
26411     {
26412       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26413               && kind == other.kind);
26414     }
26415
26416     const int dwarf_tag;
26417     const bool is_static;
26418     const unit_kind kind;
26419   };
26420
26421   /* Provide std::unordered_map::hasher for index_key.  */
26422   class index_key_hasher
26423   {
26424   public:
26425     size_t
26426     operator () (const index_key &key) const
26427     {
26428       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26429     }
26430   };
26431
26432   /* Parameters of one symbol entry.  */
26433   class symbol_value
26434   {
26435   public:
26436     const int dwarf_tag, cu_index;
26437     const bool is_static;
26438     const unit_kind kind;
26439
26440     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26441                   unit_kind kind_)
26442       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26443         kind (kind_)
26444     {}
26445
26446     bool
26447     operator< (const symbol_value &other) const
26448     {
26449 #define X(n) \
26450   do \
26451     { \
26452       if (n < other.n) \
26453         return true; \
26454       if (n > other.n) \
26455         return false; \
26456     } \
26457   while (0)
26458       X (dwarf_tag);
26459       X (is_static);
26460       X (kind);
26461       X (cu_index);
26462 #undef X
26463       return false;
26464     }
26465   };
26466
26467   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26468      output.  */
26469   class offset_vec
26470   {
26471   protected:
26472     const bfd_endian dwarf5_byte_order;
26473   public:
26474     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26475       : dwarf5_byte_order (dwarf5_byte_order_)
26476     {}
26477
26478     /* Call std::vector::reserve for NELEM elements.  */
26479     virtual void reserve (size_t nelem) = 0;
26480
26481     /* Call std::vector::push_back with store_unsigned_integer byte
26482        reordering for ELEM.  */
26483     virtual void push_back_reorder (size_t elem) = 0;
26484
26485     /* Return expected output size in bytes.  */
26486     virtual size_t bytes () const = 0;
26487
26488     /* Write name table to FILE.  */
26489     virtual void file_write (FILE *file) const = 0;
26490   };
26491
26492   /* Template to unify DWARF-32 and DWARF-64 output.  */
26493   template<typename OffsetSize>
26494   class offset_vec_tmpl : public offset_vec
26495   {
26496   public:
26497     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26498       : offset_vec (dwarf5_byte_order_)
26499     {}
26500
26501     /* Implement offset_vec::reserve.  */
26502     void reserve (size_t nelem) override
26503     {
26504       m_vec.reserve (nelem);
26505     }
26506
26507     /* Implement offset_vec::push_back_reorder.  */
26508     void push_back_reorder (size_t elem) override
26509     {
26510       m_vec.push_back (elem);
26511       /* Check for overflow.  */
26512       gdb_assert (m_vec.back () == elem);
26513       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26514                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26515     }
26516
26517     /* Implement offset_vec::bytes.  */
26518     size_t bytes () const override
26519     {
26520       return m_vec.size () * sizeof (m_vec[0]);
26521     }
26522
26523     /* Implement offset_vec::file_write.  */
26524     void file_write (FILE *file) const override
26525     {
26526       ::file_write (file, m_vec);
26527     }
26528
26529   private:
26530     std::vector<OffsetSize> m_vec;
26531   };
26532
26533   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26534      respecting name table width.  */
26535   class dwarf
26536   {
26537   public:
26538     offset_vec &name_table_string_offs, &name_table_entry_offs;
26539
26540     dwarf (offset_vec &name_table_string_offs_,
26541            offset_vec &name_table_entry_offs_)
26542       : name_table_string_offs (name_table_string_offs_),
26543         name_table_entry_offs (name_table_entry_offs_)
26544     {
26545     }
26546   };
26547
26548   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26549      respecting name table width.  */
26550   template<typename OffsetSize>
26551   class dwarf_tmpl : public dwarf
26552   {
26553   public:
26554     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26555       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26556         m_name_table_string_offs (dwarf5_byte_order_),
26557         m_name_table_entry_offs (dwarf5_byte_order_)
26558     {}
26559
26560   private:
26561     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26562     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26563   };
26564
26565   /* Try to reconstruct original DWARF tag for given partial_symbol.
26566      This function is not DWARF-5 compliant but it is sufficient for
26567      GDB as a DWARF-5 index consumer.  */
26568   static int psymbol_tag (const struct partial_symbol *psym)
26569   {
26570     domain_enum domain = PSYMBOL_DOMAIN (psym);
26571     enum address_class aclass = PSYMBOL_CLASS (psym);
26572
26573     switch (domain)
26574       {
26575       case VAR_DOMAIN:
26576         switch (aclass)
26577           {
26578           case LOC_BLOCK:
26579             return DW_TAG_subprogram;
26580           case LOC_TYPEDEF:
26581             return DW_TAG_typedef;
26582           case LOC_COMPUTED:
26583           case LOC_CONST_BYTES:
26584           case LOC_OPTIMIZED_OUT:
26585           case LOC_STATIC:
26586             return DW_TAG_variable;
26587           case LOC_CONST:
26588             /* Note: It's currently impossible to recognize psyms as enum values
26589                short of reading the type info.  For now punt.  */
26590             return DW_TAG_variable;
26591           default:
26592             /* There are other LOC_FOO values that one might want to classify
26593                as variables, but dwarf2read.c doesn't currently use them.  */
26594             return DW_TAG_variable;
26595           }
26596       case STRUCT_DOMAIN:
26597         return DW_TAG_structure_type;
26598       default:
26599         return 0;
26600       }
26601   }
26602
26603   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26604   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26605                        struct partial_symbol **psymp, int count, int cu_index,
26606                        bool is_static, unit_kind kind)
26607   {
26608     for (; count-- > 0; ++psymp)
26609       {
26610         struct partial_symbol *psym = *psymp;
26611
26612         if (SYMBOL_LANGUAGE (psym) == language_ada)
26613           error (_("Ada is not currently supported by the index"));
26614
26615         /* Only add a given psymbol once.  */
26616         if (psyms_seen.insert (psym).second)
26617           insert (psym, cu_index, is_static, kind);
26618       }
26619   }
26620
26621   /* A helper function that writes a single signatured_type
26622      to a debug_names.  */
26623   void
26624   write_one_signatured_type (struct signatured_type *entry,
26625                              struct signatured_type_index_data *info)
26626   {
26627     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26628
26629     write_psymbols (info->psyms_seen,
26630                     &info->objfile->global_psymbols[psymtab->globals_offset],
26631                     psymtab->n_global_syms, info->cu_index, false,
26632                     unit_kind::tu);
26633     write_psymbols (info->psyms_seen,
26634                     &info->objfile->static_psymbols[psymtab->statics_offset],
26635                     psymtab->n_static_syms, info->cu_index, true,
26636                     unit_kind::tu);
26637
26638     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26639                                   to_underlying (entry->per_cu.sect_off));
26640
26641     ++info->cu_index;
26642   }
26643
26644   /* Store value of each symbol.  */
26645   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26646     m_name_to_value_set;
26647
26648   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26649      order.  */
26650   std::vector<uint32_t> m_bucket_table;
26651   std::vector<uint32_t> m_hash_table;
26652
26653   const bfd_endian m_dwarf5_byte_order;
26654   dwarf_tmpl<uint32_t> m_dwarf32;
26655   dwarf_tmpl<uint64_t> m_dwarf64;
26656   dwarf &m_dwarf;
26657   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26658   debug_str_lookup m_debugstrlookup;
26659
26660   /* Map each used .debug_names abbreviation tag parameter to its
26661      index value.  */
26662   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26663
26664   /* Next unused .debug_names abbreviation tag for
26665      m_indexkey_to_idx.  */
26666   int m_idx_next = 1;
26667
26668   /* .debug_names abbreviation table.  */
26669   data_buf m_abbrev_table;
26670
26671   /* .debug_names entry pool.  */
26672   data_buf m_entry_pool;
26673 };
26674
26675 /* Return iff any of the needed offsets does not fit into 32-bit
26676    .debug_names section.  */
26677
26678 static bool
26679 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26680 {
26681   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26682     {
26683       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26684
26685       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26686         return true;
26687     }
26688   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26689     {
26690       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26691       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26692
26693       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26694         return true;
26695     }
26696   return false;
26697 }
26698
26699 /* The psyms_seen set is potentially going to be largish (~40k
26700    elements when indexing a -g3 build of GDB itself).  Estimate the
26701    number of elements in order to avoid too many rehashes, which
26702    require rebuilding buckets and thus many trips to
26703    malloc/free.  */
26704
26705 static size_t
26706 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26707 {
26708   size_t psyms_count = 0;
26709   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26710     {
26711       struct dwarf2_per_cu_data *per_cu
26712         = dwarf2_per_objfile->all_comp_units[i];
26713       struct partial_symtab *psymtab = per_cu->v.psymtab;
26714
26715       if (psymtab != NULL && psymtab->user == NULL)
26716         recursively_count_psymbols (psymtab, psyms_count);
26717     }
26718   /* Generating an index for gdb itself shows a ratio of
26719      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26720   return psyms_count / 4;
26721 }
26722
26723 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26724    Return how many bytes were expected to be written into OUT_FILE.  */
26725
26726 static size_t
26727 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26728 {
26729   struct objfile *objfile = dwarf2_per_objfile->objfile;
26730   mapped_symtab symtab;
26731   data_buf cu_list;
26732
26733   /* While we're scanning CU's create a table that maps a psymtab pointer
26734      (which is what addrmap records) to its index (which is what is recorded
26735      in the index file).  This will later be needed to write the address
26736      table.  */
26737   psym_index_map cu_index_htab;
26738   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26739
26740   /* The CU list is already sorted, so we don't need to do additional
26741      work here.  Also, the debug_types entries do not appear in
26742      all_comp_units, but only in their own hash table.  */
26743
26744   std::unordered_set<partial_symbol *> psyms_seen
26745     (psyms_seen_size (dwarf2_per_objfile));
26746   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26747     {
26748       struct dwarf2_per_cu_data *per_cu
26749         = dwarf2_per_objfile->all_comp_units[i];
26750       struct partial_symtab *psymtab = per_cu->v.psymtab;
26751
26752       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26753          It may be referenced from a local scope but in such case it does not
26754          need to be present in .gdb_index.  */
26755       if (psymtab == NULL)
26756         continue;
26757
26758       if (psymtab->user == NULL)
26759         recursively_write_psymbols (objfile, psymtab, &symtab,
26760                                     psyms_seen, i);
26761
26762       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26763       gdb_assert (insertpair.second);
26764
26765       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26766                            to_underlying (per_cu->sect_off));
26767       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26768     }
26769
26770   /* Dump the address map.  */
26771   data_buf addr_vec;
26772   write_address_map (objfile, addr_vec, cu_index_htab);
26773
26774   /* Write out the .debug_type entries, if any.  */
26775   data_buf types_cu_list;
26776   if (dwarf2_per_objfile->signatured_types)
26777     {
26778       signatured_type_index_data sig_data (types_cu_list,
26779                                            psyms_seen);
26780
26781       sig_data.objfile = objfile;
26782       sig_data.symtab = &symtab;
26783       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26784       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26785                               write_one_signatured_type, &sig_data);
26786     }
26787
26788   /* Now that we've processed all symbols we can shrink their cu_indices
26789      lists.  */
26790   uniquify_cu_indices (&symtab);
26791
26792   data_buf symtab_vec, constant_pool;
26793   write_hash_table (&symtab, symtab_vec, constant_pool);
26794
26795   data_buf contents;
26796   const offset_type size_of_contents = 6 * sizeof (offset_type);
26797   offset_type total_len = size_of_contents;
26798
26799   /* The version number.  */
26800   contents.append_data (MAYBE_SWAP (8));
26801
26802   /* The offset of the CU list from the start of the file.  */
26803   contents.append_data (MAYBE_SWAP (total_len));
26804   total_len += cu_list.size ();
26805
26806   /* The offset of the types CU list from the start of the file.  */
26807   contents.append_data (MAYBE_SWAP (total_len));
26808   total_len += types_cu_list.size ();
26809
26810   /* The offset of the address table from the start of the file.  */
26811   contents.append_data (MAYBE_SWAP (total_len));
26812   total_len += addr_vec.size ();
26813
26814   /* The offset of the symbol table from the start of the file.  */
26815   contents.append_data (MAYBE_SWAP (total_len));
26816   total_len += symtab_vec.size ();
26817
26818   /* The offset of the constant pool from the start of the file.  */
26819   contents.append_data (MAYBE_SWAP (total_len));
26820   total_len += constant_pool.size ();
26821
26822   gdb_assert (contents.size () == size_of_contents);
26823
26824   contents.file_write (out_file);
26825   cu_list.file_write (out_file);
26826   types_cu_list.file_write (out_file);
26827   addr_vec.file_write (out_file);
26828   symtab_vec.file_write (out_file);
26829   constant_pool.file_write (out_file);
26830
26831   return total_len;
26832 }
26833
26834 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26835 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26836
26837 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26838    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26839    many bytes were expected to be written into OUT_FILE.  */
26840
26841 static size_t
26842 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
26843                    FILE *out_file, FILE *out_file_str)
26844 {
26845   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
26846   struct objfile *objfile = dwarf2_per_objfile->objfile;
26847   const enum bfd_endian dwarf5_byte_order
26848     = gdbarch_byte_order (get_objfile_arch (objfile));
26849
26850   /* The CU list is already sorted, so we don't need to do additional
26851      work here.  Also, the debug_types entries do not appear in
26852      all_comp_units, but only in their own hash table.  */
26853   data_buf cu_list;
26854   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
26855                          dwarf5_byte_order);
26856   std::unordered_set<partial_symbol *>
26857     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
26858   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26859     {
26860       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26861       partial_symtab *psymtab = per_cu->v.psymtab;
26862
26863       /* CU of a shared file from 'dwz -m' may be unused by this main
26864          file.  It may be referenced from a local scope but in such
26865          case it does not need to be present in .debug_names.  */
26866       if (psymtab == NULL)
26867         continue;
26868
26869       if (psymtab->user == NULL)
26870         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26871
26872       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
26873                            to_underlying (per_cu->sect_off));
26874     }
26875
26876   /* Write out the .debug_type entries, if any.  */
26877   data_buf types_cu_list;
26878   if (dwarf2_per_objfile->signatured_types)
26879     {
26880       debug_names::write_one_signatured_type_data sig_data (nametable,
26881                         signatured_type_index_data (types_cu_list, psyms_seen));
26882
26883       sig_data.info.objfile = objfile;
26884       /* It is used only for gdb_index.  */
26885       sig_data.info.symtab = nullptr;
26886       sig_data.info.cu_index = 0;
26887       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26888                               debug_names::write_one_signatured_type,
26889                               &sig_data);
26890     }
26891
26892   nametable.build ();
26893
26894   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26895
26896   const offset_type bytes_of_header
26897     = ((dwarf5_is_dwarf64 ? 12 : 4)
26898        + 2 + 2 + 7 * 4
26899        + sizeof (dwarf5_gdb_augmentation));
26900   size_t expected_bytes = 0;
26901   expected_bytes += bytes_of_header;
26902   expected_bytes += cu_list.size ();
26903   expected_bytes += types_cu_list.size ();
26904   expected_bytes += nametable.bytes ();
26905   data_buf header;
26906
26907   if (!dwarf5_is_dwarf64)
26908     {
26909       const uint64_t size64 = expected_bytes - 4;
26910       gdb_assert (size64 < 0xfffffff0);
26911       header.append_uint (4, dwarf5_byte_order, size64);
26912     }
26913   else
26914     {
26915       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26916       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26917     }
26918
26919   /* The version number.  */
26920   header.append_uint (2, dwarf5_byte_order, 5);
26921
26922   /* Padding.  */
26923   header.append_uint (2, dwarf5_byte_order, 0);
26924
26925   /* comp_unit_count - The number of CUs in the CU list.  */
26926   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26927
26928   /* local_type_unit_count - The number of TUs in the local TU
26929      list.  */
26930   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26931
26932   /* foreign_type_unit_count - The number of TUs in the foreign TU
26933      list.  */
26934   header.append_uint (4, dwarf5_byte_order, 0);
26935
26936   /* bucket_count - The number of hash buckets in the hash lookup
26937      table.  */
26938   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26939
26940   /* name_count - The number of unique names in the index.  */
26941   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26942
26943   /* abbrev_table_size - The size in bytes of the abbreviations
26944      table.  */
26945   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26946
26947   /* augmentation_string_size - The size in bytes of the augmentation
26948      string.  This value is rounded up to a multiple of 4.  */
26949   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26950   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26951   header.append_data (dwarf5_gdb_augmentation);
26952
26953   gdb_assert (header.size () == bytes_of_header);
26954
26955   header.file_write (out_file);
26956   cu_list.file_write (out_file);
26957   types_cu_list.file_write (out_file);
26958   nametable.file_write (out_file, out_file_str);
26959
26960   return expected_bytes;
26961 }
26962
26963 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26964    position is at the end of the file.  */
26965
26966 static void
26967 assert_file_size (FILE *file, const char *filename, size_t expected_size)
26968 {
26969   const auto file_size = ftell (file);
26970   if (file_size == -1)
26971     error (_("Can't get `%s' size"), filename);
26972   gdb_assert (file_size == expected_size);
26973 }
26974
26975 /* Create an index file for OBJFILE in the directory DIR.  */
26976
26977 static void
26978 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
26979                          const char *dir,
26980                          dw_index_kind index_kind)
26981 {
26982   struct objfile *objfile = dwarf2_per_objfile->objfile;
26983
26984   if (dwarf2_per_objfile->using_index)
26985     error (_("Cannot use an index to create the index"));
26986
26987   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
26988     error (_("Cannot make an index when the file has multiple .debug_types sections"));
26989
26990   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
26991     return;
26992
26993   struct stat st;
26994   if (stat (objfile_name (objfile), &st) < 0)
26995     perror_with_name (objfile_name (objfile));
26996
26997   std::string filename (std::string (dir) + SLASH_STRING
26998                         + lbasename (objfile_name (objfile))
26999                         + (index_kind == dw_index_kind::DEBUG_NAMES
27000                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27001
27002   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27003   if (!out_file)
27004     error (_("Can't open `%s' for writing"), filename.c_str ());
27005
27006   /* Order matters here; we want FILE to be closed before FILENAME is
27007      unlinked, because on MS-Windows one cannot delete a file that is
27008      still open.  (Don't call anything here that might throw until
27009      file_closer is created.)  */
27010   gdb::unlinker unlink_file (filename.c_str ());
27011   gdb_file_up close_out_file (out_file);
27012
27013   if (index_kind == dw_index_kind::DEBUG_NAMES)
27014     {
27015       std::string filename_str (std::string (dir) + SLASH_STRING
27016                                 + lbasename (objfile_name (objfile))
27017                                 + DEBUG_STR_SUFFIX);
27018       FILE *out_file_str
27019         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27020       if (!out_file_str)
27021         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27022       gdb::unlinker unlink_file_str (filename_str.c_str ());
27023       gdb_file_up close_out_file_str (out_file_str);
27024
27025       const size_t total_len
27026         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27027       assert_file_size (out_file, filename.c_str (), total_len);
27028
27029       /* We want to keep the file .debug_str file too.  */
27030       unlink_file_str.keep ();
27031     }
27032   else
27033     {
27034       const size_t total_len
27035         = write_gdbindex (dwarf2_per_objfile, out_file);
27036       assert_file_size (out_file, filename.c_str (), total_len);
27037     }
27038
27039   /* We want to keep the file.  */
27040   unlink_file.keep ();
27041 }
27042
27043 /* Implementation of the `save gdb-index' command.
27044    
27045    Note that the .gdb_index file format used by this command is
27046    documented in the GDB manual.  Any changes here must be documented
27047    there.  */
27048
27049 static void
27050 save_gdb_index_command (const char *arg, int from_tty)
27051 {
27052   struct objfile *objfile;
27053   const char dwarf5space[] = "-dwarf-5 ";
27054   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27055
27056   if (!arg)
27057     arg = "";
27058
27059   arg = skip_spaces (arg);
27060   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27061     {
27062       index_kind = dw_index_kind::DEBUG_NAMES;
27063       arg += strlen (dwarf5space);
27064       arg = skip_spaces (arg);
27065     }
27066
27067   if (!*arg)
27068     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27069
27070   ALL_OBJFILES (objfile)
27071   {
27072     struct stat st;
27073
27074     /* If the objfile does not correspond to an actual file, skip it.  */
27075     if (stat (objfile_name (objfile), &st) < 0)
27076       continue;
27077
27078     struct dwarf2_per_objfile *dwarf2_per_objfile
27079       = get_dwarf2_per_objfile (objfile);
27080
27081     if (dwarf2_per_objfile != NULL)
27082       {
27083         TRY
27084           {
27085             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27086           }
27087         CATCH (except, RETURN_MASK_ERROR)
27088           {
27089             exception_fprintf (gdb_stderr, except,
27090                                _("Error while writing index for `%s': "),
27091                                objfile_name (objfile));
27092           }
27093         END_CATCH
27094       }
27095
27096   }
27097 }
27098
27099 \f
27100
27101 int dwarf_always_disassemble;
27102
27103 static void
27104 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27105                                struct cmd_list_element *c, const char *value)
27106 {
27107   fprintf_filtered (file,
27108                     _("Whether to always disassemble "
27109                       "DWARF expressions is %s.\n"),
27110                     value);
27111 }
27112
27113 static void
27114 show_check_physname (struct ui_file *file, int from_tty,
27115                      struct cmd_list_element *c, const char *value)
27116 {
27117   fprintf_filtered (file,
27118                     _("Whether to check \"physname\" is %s.\n"),
27119                     value);
27120 }
27121
27122 void
27123 _initialize_dwarf2_read (void)
27124 {
27125   struct cmd_list_element *c;
27126
27127   dwarf2_objfile_data_key = register_objfile_data ();
27128
27129   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27130 Set DWARF specific variables.\n\
27131 Configure DWARF variables such as the cache size"),
27132                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27133                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27134
27135   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27136 Show DWARF specific variables\n\
27137 Show DWARF variables such as the cache size"),
27138                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27139                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27140
27141   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27142                             &dwarf_max_cache_age, _("\
27143 Set the upper bound on the age of cached DWARF compilation units."), _("\
27144 Show the upper bound on the age of cached DWARF compilation units."), _("\
27145 A higher limit means that cached compilation units will be stored\n\
27146 in memory longer, and more total memory will be used.  Zero disables\n\
27147 caching, which can slow down startup."),
27148                             NULL,
27149                             show_dwarf_max_cache_age,
27150                             &set_dwarf_cmdlist,
27151                             &show_dwarf_cmdlist);
27152
27153   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27154                            &dwarf_always_disassemble, _("\
27155 Set whether `info address' always disassembles DWARF expressions."), _("\
27156 Show whether `info address' always disassembles DWARF expressions."), _("\
27157 When enabled, DWARF expressions are always printed in an assembly-like\n\
27158 syntax.  When disabled, expressions will be printed in a more\n\
27159 conversational style, when possible."),
27160                            NULL,
27161                            show_dwarf_always_disassemble,
27162                            &set_dwarf_cmdlist,
27163                            &show_dwarf_cmdlist);
27164
27165   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27166 Set debugging of the DWARF reader."), _("\
27167 Show debugging of the DWARF reader."), _("\
27168 When enabled (non-zero), debugging messages are printed during DWARF\n\
27169 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27170 information.  A value greater than 1 provides more verbose information."),
27171                             NULL,
27172                             NULL,
27173                             &setdebuglist, &showdebuglist);
27174
27175   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27176 Set debugging of the DWARF DIE reader."), _("\
27177 Show debugging of the DWARF DIE reader."), _("\
27178 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27179 The value is the maximum depth to print."),
27180                              NULL,
27181                              NULL,
27182                              &setdebuglist, &showdebuglist);
27183
27184   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27185 Set debugging of the dwarf line reader."), _("\
27186 Show debugging of the dwarf line reader."), _("\
27187 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27188 A value of 1 (one) provides basic information.\n\
27189 A value greater than 1 provides more verbose information."),
27190                              NULL,
27191                              NULL,
27192                              &setdebuglist, &showdebuglist);
27193
27194   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27195 Set cross-checking of \"physname\" code against demangler."), _("\
27196 Show cross-checking of \"physname\" code against demangler."), _("\
27197 When enabled, GDB's internal \"physname\" code is checked against\n\
27198 the demangler."),
27199                            NULL, show_check_physname,
27200                            &setdebuglist, &showdebuglist);
27201
27202   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27203                            no_class, &use_deprecated_index_sections, _("\
27204 Set whether to use deprecated gdb_index sections."), _("\
27205 Show whether to use deprecated gdb_index sections."), _("\
27206 When enabled, deprecated .gdb_index sections are used anyway.\n\
27207 Normally they are ignored either because of a missing feature or\n\
27208 performance issue.\n\
27209 Warning: This option must be enabled before gdb reads the file."),
27210                            NULL,
27211                            NULL,
27212                            &setlist, &showlist);
27213
27214   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27215                _("\
27216 Save a gdb-index file.\n\
27217 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27218 \n\
27219 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27220 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27221 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27222                &save_cmdlist);
27223   set_cmd_completer (c, filename_completer);
27224
27225   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27226                                                         &dwarf2_locexpr_funcs);
27227   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27228                                                         &dwarf2_loclist_funcs);
27229
27230   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27231                                         &dwarf2_block_frame_base_locexpr_funcs);
27232   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27233                                         &dwarf2_block_frame_base_loclist_funcs);
27234
27235 #if GDB_SELF_TEST
27236   selftests::register_test ("dw2_expand_symtabs_matching",
27237                             selftests::dw2_expand_symtabs_matching::run_test);
27238 #endif
27239 }