Unbreak build for non-ELF ports
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2017 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 typedef struct symbol *symbolp;
91 DEF_VEC_P (symbolp);
92
93 /* When == 1, print basic high level tracing messages.
94    When > 1, be more verbose.
95    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
96 static unsigned int dwarf_read_debug = 0;
97
98 /* When non-zero, dump DIEs after they are read in.  */
99 static unsigned int dwarf_die_debug = 0;
100
101 /* When non-zero, dump line number entries as they are read in.  */
102 static unsigned int dwarf_line_debug = 0;
103
104 /* When non-zero, cross-check physname against demangler.  */
105 static int check_physname = 0;
106
107 /* When non-zero, do not reject deprecated .gdb_index sections.  */
108 static int use_deprecated_index_sections = 0;
109
110 static const struct objfile_data *dwarf2_objfile_data_key;
111
112 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
113
114 static int dwarf2_locexpr_index;
115 static int dwarf2_loclist_index;
116 static int dwarf2_locexpr_block_index;
117 static int dwarf2_loclist_block_index;
118
119 /* A descriptor for dwarf sections.
120
121    S.ASECTION, SIZE are typically initialized when the objfile is first
122    scanned.  BUFFER, READIN are filled in later when the section is read.
123    If the section contained compressed data then SIZE is updated to record
124    the uncompressed size of the section.
125
126    DWP file format V2 introduces a wrinkle that is easiest to handle by
127    creating the concept of virtual sections contained within a real section.
128    In DWP V2 the sections of the input DWO files are concatenated together
129    into one section, but section offsets are kept relative to the original
130    input section.
131    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
132    the real section this "virtual" section is contained in, and BUFFER,SIZE
133    describe the virtual section.  */
134
135 struct dwarf2_section_info
136 {
137   union
138   {
139     /* If this is a real section, the bfd section.  */
140     asection *section;
141     /* If this is a virtual section, pointer to the containing ("real")
142        section.  */
143     struct dwarf2_section_info *containing_section;
144   } s;
145   /* Pointer to section data, only valid if readin.  */
146   const gdb_byte *buffer;
147   /* The size of the section, real or virtual.  */
148   bfd_size_type size;
149   /* If this is a virtual section, the offset in the real section.
150      Only valid if is_virtual.  */
151   bfd_size_type virtual_offset;
152   /* True if we have tried to read this section.  */
153   char readin;
154   /* True if this is a virtual section, False otherwise.
155      This specifies which of s.section and s.containing_section to use.  */
156   char is_virtual;
157 };
158
159 typedef struct dwarf2_section_info dwarf2_section_info_def;
160 DEF_VEC_O (dwarf2_section_info_def);
161
162 /* All offsets in the index are of this type.  It must be
163    architecture-independent.  */
164 typedef uint32_t offset_type;
165
166 DEF_VEC_I (offset_type);
167
168 /* Ensure only legit values are used.  */
169 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
170   do { \
171     gdb_assert ((unsigned int) (value) <= 1); \
172     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
173   } while (0)
174
175 /* Ensure only legit values are used.  */
176 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
177   do { \
178     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
179                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
180     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
181   } while (0)
182
183 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
184 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
185   do { \
186     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
187     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
188   } while (0)
189
190 #if WORDS_BIGENDIAN
191
192 /* Convert VALUE between big- and little-endian.  */
193
194 static offset_type
195 byte_swap (offset_type value)
196 {
197   offset_type result;
198
199   result = (value & 0xff) << 24;
200   result |= (value & 0xff00) << 8;
201   result |= (value & 0xff0000) >> 8;
202   result |= (value & 0xff000000) >> 24;
203   return result;
204 }
205
206 #define MAYBE_SWAP(V)  byte_swap (V)
207
208 #else
209 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
210 #endif /* WORDS_BIGENDIAN */
211
212 /* An index into a (C++) symbol name component in a symbol name as
213    recorded in the mapped_index's symbol table.  For each C++ symbol
214    in the symbol table, we record one entry for the start of each
215    component in the symbol in a table of name components, and then
216    sort the table, in order to be able to binary search symbol names,
217    ignoring leading namespaces, both completion and regular look up.
218    For example, for symbol "A::B::C", we'll have an entry that points
219    to "A::B::C", another that points to "B::C", and another for "C".
220    Note that function symbols in GDB index have no parameter
221    information, just the function/method names.  You can convert a
222    name_component to a "const char *" using the
223    'mapped_index::symbol_name_at(offset_type)' method.  */
224
225 struct name_component
226 {
227   /* Offset in the symbol name where the component starts.  Stored as
228      a (32-bit) offset instead of a pointer to save memory and improve
229      locality on 64-bit architectures.  */
230   offset_type name_offset;
231
232   /* The symbol's index in the symbol and constant pool tables of a
233      mapped_index.  */
234   offset_type idx;
235 };
236
237 /* Base class containing bits shared by both .gdb_index and
238    .debug_name indexes.  */
239
240 struct mapped_index_base
241 {
242   /* The name_component table (a sorted vector).  See name_component's
243      description above.  */
244   std::vector<name_component> name_components;
245
246   /* How NAME_COMPONENTS is sorted.  */
247   enum case_sensitivity name_components_casing;
248
249   /* Return the number of names in the symbol table.  */
250   virtual size_t symbol_name_count () const = 0;
251
252   /* Get the name of the symbol at IDX in the symbol table.  */
253   virtual const char *symbol_name_at (offset_type idx) const = 0;
254
255   /* Return whether the name at IDX in the symbol table should be
256      ignored.  */
257   virtual bool symbol_name_slot_invalid (offset_type idx) const
258   {
259     return false;
260   }
261
262   /* Build the symbol name component sorted vector, if we haven't
263      yet.  */
264   void build_name_components ();
265
266   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
267      possible matches for LN_NO_PARAMS in the name component
268      vector.  */
269   std::pair<std::vector<name_component>::const_iterator,
270             std::vector<name_component>::const_iterator>
271     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
272
273   /* Prevent deleting/destroying via a base class pointer.  */
274 protected:
275   ~mapped_index_base() = default;
276 };
277
278 /* A description of the mapped index.  The file format is described in
279    a comment by the code that writes the index.  */
280 struct mapped_index : public mapped_index_base
281 {
282   /* A slot/bucket in the symbol table hash.  */
283   struct symbol_table_slot
284   {
285     const offset_type name;
286     const offset_type vec;
287   };
288
289   /* Index data format version.  */
290   int version;
291
292   /* The total length of the buffer.  */
293   off_t total_size;
294
295   /* The address table data.  */
296   gdb::array_view<const gdb_byte> address_table;
297
298   /* The symbol table, implemented as a hash table.  */
299   gdb::array_view<symbol_table_slot> symbol_table;
300
301   /* A pointer to the constant pool.  */
302   const char *constant_pool;
303
304   bool symbol_name_slot_invalid (offset_type idx) const override
305   {
306     const auto &bucket = this->symbol_table[idx];
307     return bucket.name == 0 && bucket.vec;
308   }
309
310   /* Convenience method to get at the name of the symbol at IDX in the
311      symbol table.  */
312   const char *symbol_name_at (offset_type idx) const override
313   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
314
315   size_t symbol_name_count () const override
316   { return this->symbol_table.size (); }
317 };
318
319 /* A description of the mapped .debug_names.
320    Uninitialized map has CU_COUNT 0.  */
321 struct mapped_debug_names : public mapped_index_base
322 {
323   bfd_endian dwarf5_byte_order;
324   bool dwarf5_is_dwarf64;
325   bool augmentation_is_gdb;
326   uint8_t offset_size;
327   uint32_t cu_count = 0;
328   uint32_t tu_count, bucket_count, name_count;
329   const gdb_byte *cu_table_reordered, *tu_table_reordered;
330   const uint32_t *bucket_table_reordered, *hash_table_reordered;
331   const gdb_byte *name_table_string_offs_reordered;
332   const gdb_byte *name_table_entry_offs_reordered;
333   const gdb_byte *entry_pool;
334
335   struct index_val
336   {
337     ULONGEST dwarf_tag;
338     struct attr
339     {
340       /* Attribute name DW_IDX_*.  */
341       ULONGEST dw_idx;
342
343       /* Attribute form DW_FORM_*.  */
344       ULONGEST form;
345
346       /* Value if FORM is DW_FORM_implicit_const.  */
347       LONGEST implicit_const;
348     };
349     std::vector<attr> attr_vec;
350   };
351
352   std::unordered_map<ULONGEST, index_val> abbrev_map;
353
354   const char *namei_to_name (uint32_t namei) const;
355
356   /* Implementation of the mapped_index_base virtual interface, for
357      the name_components cache.  */
358
359   const char *symbol_name_at (offset_type idx) const override
360   { return namei_to_name (idx); }
361
362   size_t symbol_name_count () const override
363   { return this->name_count; }
364 };
365
366 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
367 DEF_VEC_P (dwarf2_per_cu_ptr);
368
369 struct tu_stats
370 {
371   int nr_uniq_abbrev_tables;
372   int nr_symtabs;
373   int nr_symtab_sharers;
374   int nr_stmt_less_type_units;
375   int nr_all_type_units_reallocs;
376 };
377
378 /* Collection of data recorded per objfile.
379    This hangs off of dwarf2_objfile_data_key.  */
380
381 struct dwarf2_per_objfile
382 {
383   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
384      dwarf2 section names, or is NULL if the standard ELF names are
385      used.  */
386   dwarf2_per_objfile (struct objfile *objfile,
387                       const dwarf2_debug_sections *names);
388
389   ~dwarf2_per_objfile ();
390
391   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
392
393   /* Free all cached compilation units.  */
394   void free_cached_comp_units ();
395 private:
396   /* This function is mapped across the sections and remembers the
397      offset and size of each of the debugging sections we are
398      interested in.  */
399   void locate_sections (bfd *abfd, asection *sectp,
400                         const dwarf2_debug_sections &names);
401
402 public:
403   dwarf2_section_info info {};
404   dwarf2_section_info abbrev {};
405   dwarf2_section_info line {};
406   dwarf2_section_info loc {};
407   dwarf2_section_info loclists {};
408   dwarf2_section_info macinfo {};
409   dwarf2_section_info macro {};
410   dwarf2_section_info str {};
411   dwarf2_section_info line_str {};
412   dwarf2_section_info ranges {};
413   dwarf2_section_info rnglists {};
414   dwarf2_section_info addr {};
415   dwarf2_section_info frame {};
416   dwarf2_section_info eh_frame {};
417   dwarf2_section_info gdb_index {};
418   dwarf2_section_info debug_names {};
419   dwarf2_section_info debug_aranges {};
420
421   VEC (dwarf2_section_info_def) *types = NULL;
422
423   /* Back link.  */
424   struct objfile *objfile = NULL;
425
426   /* Table of all the compilation units.  This is used to locate
427      the target compilation unit of a particular reference.  */
428   struct dwarf2_per_cu_data **all_comp_units = NULL;
429
430   /* The number of compilation units in ALL_COMP_UNITS.  */
431   int n_comp_units = 0;
432
433   /* The number of .debug_types-related CUs.  */
434   int n_type_units = 0;
435
436   /* The number of elements allocated in all_type_units.
437      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
438   int n_allocated_type_units = 0;
439
440   /* The .debug_types-related CUs (TUs).
441      This is stored in malloc space because we may realloc it.  */
442   struct signatured_type **all_type_units = NULL;
443
444   /* Table of struct type_unit_group objects.
445      The hash key is the DW_AT_stmt_list value.  */
446   htab_t type_unit_groups {};
447
448   /* A table mapping .debug_types signatures to its signatured_type entry.
449      This is NULL if the .debug_types section hasn't been read in yet.  */
450   htab_t signatured_types {};
451
452   /* Type unit statistics, to see how well the scaling improvements
453      are doing.  */
454   struct tu_stats tu_stats {};
455
456   /* A chain of compilation units that are currently read in, so that
457      they can be freed later.  */
458   dwarf2_per_cu_data *read_in_chain = NULL;
459
460   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
461      This is NULL if the table hasn't been allocated yet.  */
462   htab_t dwo_files {};
463
464   /* True if we've checked for whether there is a DWP file.  */
465   bool dwp_checked = false;
466
467   /* The DWP file if there is one, or NULL.  */
468   struct dwp_file *dwp_file = NULL;
469
470   /* The shared '.dwz' file, if one exists.  This is used when the
471      original data was compressed using 'dwz -m'.  */
472   struct dwz_file *dwz_file = NULL;
473
474   /* A flag indicating whether this objfile has a section loaded at a
475      VMA of 0.  */
476   bool has_section_at_zero = false;
477
478   /* True if we are using the mapped index,
479      or we are faking it for OBJF_READNOW's sake.  */
480   bool using_index = false;
481
482   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
483   mapped_index *index_table = NULL;
484
485   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
486   std::unique_ptr<mapped_debug_names> debug_names_table;
487
488   /* When using index_table, this keeps track of all quick_file_names entries.
489      TUs typically share line table entries with a CU, so we maintain a
490      separate table of all line table entries to support the sharing.
491      Note that while there can be way more TUs than CUs, we've already
492      sorted all the TUs into "type unit groups", grouped by their
493      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
494      CU and its associated TU group if there is one.  */
495   htab_t quick_file_names_table {};
496
497   /* Set during partial symbol reading, to prevent queueing of full
498      symbols.  */
499   bool reading_partial_symbols = false;
500
501   /* Table mapping type DIEs to their struct type *.
502      This is NULL if not allocated yet.
503      The mapping is done via (CU/TU + DIE offset) -> type.  */
504   htab_t die_type_hash {};
505
506   /* The CUs we recently read.  */
507   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
508
509   /* Table containing line_header indexed by offset and offset_in_dwz.  */
510   htab_t line_header_hash {};
511
512   /* Table containing all filenames.  This is an optional because the
513      table is lazily constructed on first access.  */
514   gdb::optional<filename_seen_cache> filenames_cache;
515 };
516
517 static struct dwarf2_per_objfile *dwarf2_per_objfile;
518
519 /* Default names of the debugging sections.  */
520
521 /* Note that if the debugging section has been compressed, it might
522    have a name like .zdebug_info.  */
523
524 static const struct dwarf2_debug_sections dwarf2_elf_names =
525 {
526   { ".debug_info", ".zdebug_info" },
527   { ".debug_abbrev", ".zdebug_abbrev" },
528   { ".debug_line", ".zdebug_line" },
529   { ".debug_loc", ".zdebug_loc" },
530   { ".debug_loclists", ".zdebug_loclists" },
531   { ".debug_macinfo", ".zdebug_macinfo" },
532   { ".debug_macro", ".zdebug_macro" },
533   { ".debug_str", ".zdebug_str" },
534   { ".debug_line_str", ".zdebug_line_str" },
535   { ".debug_ranges", ".zdebug_ranges" },
536   { ".debug_rnglists", ".zdebug_rnglists" },
537   { ".debug_types", ".zdebug_types" },
538   { ".debug_addr", ".zdebug_addr" },
539   { ".debug_frame", ".zdebug_frame" },
540   { ".eh_frame", NULL },
541   { ".gdb_index", ".zgdb_index" },
542   { ".debug_names", ".zdebug_names" },
543   { ".debug_aranges", ".zdebug_aranges" },
544   23
545 };
546
547 /* List of DWO/DWP sections.  */
548
549 static const struct dwop_section_names
550 {
551   struct dwarf2_section_names abbrev_dwo;
552   struct dwarf2_section_names info_dwo;
553   struct dwarf2_section_names line_dwo;
554   struct dwarf2_section_names loc_dwo;
555   struct dwarf2_section_names loclists_dwo;
556   struct dwarf2_section_names macinfo_dwo;
557   struct dwarf2_section_names macro_dwo;
558   struct dwarf2_section_names str_dwo;
559   struct dwarf2_section_names str_offsets_dwo;
560   struct dwarf2_section_names types_dwo;
561   struct dwarf2_section_names cu_index;
562   struct dwarf2_section_names tu_index;
563 }
564 dwop_section_names =
565 {
566   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
567   { ".debug_info.dwo", ".zdebug_info.dwo" },
568   { ".debug_line.dwo", ".zdebug_line.dwo" },
569   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
570   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
571   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
572   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
573   { ".debug_str.dwo", ".zdebug_str.dwo" },
574   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
575   { ".debug_types.dwo", ".zdebug_types.dwo" },
576   { ".debug_cu_index", ".zdebug_cu_index" },
577   { ".debug_tu_index", ".zdebug_tu_index" },
578 };
579
580 /* local data types */
581
582 /* The data in a compilation unit header, after target2host
583    translation, looks like this.  */
584 struct comp_unit_head
585 {
586   unsigned int length;
587   short version;
588   unsigned char addr_size;
589   unsigned char signed_addr_p;
590   sect_offset abbrev_sect_off;
591
592   /* Size of file offsets; either 4 or 8.  */
593   unsigned int offset_size;
594
595   /* Size of the length field; either 4 or 12.  */
596   unsigned int initial_length_size;
597
598   enum dwarf_unit_type unit_type;
599
600   /* Offset to the first byte of this compilation unit header in the
601      .debug_info section, for resolving relative reference dies.  */
602   sect_offset sect_off;
603
604   /* Offset to first die in this cu from the start of the cu.
605      This will be the first byte following the compilation unit header.  */
606   cu_offset first_die_cu_offset;
607
608   /* 64-bit signature of this type unit - it is valid only for
609      UNIT_TYPE DW_UT_type.  */
610   ULONGEST signature;
611
612   /* For types, offset in the type's DIE of the type defined by this TU.  */
613   cu_offset type_cu_offset_in_tu;
614 };
615
616 /* Type used for delaying computation of method physnames.
617    See comments for compute_delayed_physnames.  */
618 struct delayed_method_info
619 {
620   /* The type to which the method is attached, i.e., its parent class.  */
621   struct type *type;
622
623   /* The index of the method in the type's function fieldlists.  */
624   int fnfield_index;
625
626   /* The index of the method in the fieldlist.  */
627   int index;
628
629   /* The name of the DIE.  */
630   const char *name;
631
632   /*  The DIE associated with this method.  */
633   struct die_info *die;
634 };
635
636 typedef struct delayed_method_info delayed_method_info;
637 DEF_VEC_O (delayed_method_info);
638
639 /* Internal state when decoding a particular compilation unit.  */
640 struct dwarf2_cu
641 {
642   /* The objfile containing this compilation unit.  */
643   struct objfile *objfile;
644
645   /* The header of the compilation unit.  */
646   struct comp_unit_head header;
647
648   /* Base address of this compilation unit.  */
649   CORE_ADDR base_address;
650
651   /* Non-zero if base_address has been set.  */
652   int base_known;
653
654   /* The language we are debugging.  */
655   enum language language;
656   const struct language_defn *language_defn;
657
658   const char *producer;
659
660   /* The generic symbol table building routines have separate lists for
661      file scope symbols and all all other scopes (local scopes).  So
662      we need to select the right one to pass to add_symbol_to_list().
663      We do it by keeping a pointer to the correct list in list_in_scope.
664
665      FIXME: The original dwarf code just treated the file scope as the
666      first local scope, and all other local scopes as nested local
667      scopes, and worked fine.  Check to see if we really need to
668      distinguish these in buildsym.c.  */
669   struct pending **list_in_scope;
670
671   /* The abbrev table for this CU.
672      Normally this points to the abbrev table in the objfile.
673      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
674   struct abbrev_table *abbrev_table;
675
676   /* Hash table holding all the loaded partial DIEs
677      with partial_die->offset.SECT_OFF as hash.  */
678   htab_t partial_dies;
679
680   /* Storage for things with the same lifetime as this read-in compilation
681      unit, including partial DIEs.  */
682   struct obstack comp_unit_obstack;
683
684   /* When multiple dwarf2_cu structures are living in memory, this field
685      chains them all together, so that they can be released efficiently.
686      We will probably also want a generation counter so that most-recently-used
687      compilation units are cached...  */
688   struct dwarf2_per_cu_data *read_in_chain;
689
690   /* Backlink to our per_cu entry.  */
691   struct dwarf2_per_cu_data *per_cu;
692
693   /* How many compilation units ago was this CU last referenced?  */
694   int last_used;
695
696   /* A hash table of DIE cu_offset for following references with
697      die_info->offset.sect_off as hash.  */
698   htab_t die_hash;
699
700   /* Full DIEs if read in.  */
701   struct die_info *dies;
702
703   /* A set of pointers to dwarf2_per_cu_data objects for compilation
704      units referenced by this one.  Only set during full symbol processing;
705      partial symbol tables do not have dependencies.  */
706   htab_t dependencies;
707
708   /* Header data from the line table, during full symbol processing.  */
709   struct line_header *line_header;
710   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
711      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
712      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
713      to the line header as long as this DIE is being processed.  See
714      process_die_scope.  */
715   die_info *line_header_die_owner;
716
717   /* A list of methods which need to have physnames computed
718      after all type information has been read.  */
719   VEC (delayed_method_info) *method_list;
720
721   /* To be copied to symtab->call_site_htab.  */
722   htab_t call_site_htab;
723
724   /* Non-NULL if this CU came from a DWO file.
725      There is an invariant here that is important to remember:
726      Except for attributes copied from the top level DIE in the "main"
727      (or "stub") file in preparation for reading the DWO file
728      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
729      Either there isn't a DWO file (in which case this is NULL and the point
730      is moot), or there is and either we're not going to read it (in which
731      case this is NULL) or there is and we are reading it (in which case this
732      is non-NULL).  */
733   struct dwo_unit *dwo_unit;
734
735   /* The DW_AT_addr_base attribute if present, zero otherwise
736      (zero is a valid value though).
737      Note this value comes from the Fission stub CU/TU's DIE.  */
738   ULONGEST addr_base;
739
740   /* The DW_AT_ranges_base attribute if present, zero otherwise
741      (zero is a valid value though).
742      Note this value comes from the Fission stub CU/TU's DIE.
743      Also note that the value is zero in the non-DWO case so this value can
744      be used without needing to know whether DWO files are in use or not.
745      N.B. This does not apply to DW_AT_ranges appearing in
746      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
747      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
748      DW_AT_ranges_base *would* have to be applied, and we'd have to care
749      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
750   ULONGEST ranges_base;
751
752   /* Mark used when releasing cached dies.  */
753   unsigned int mark : 1;
754
755   /* This CU references .debug_loc.  See the symtab->locations_valid field.
756      This test is imperfect as there may exist optimized debug code not using
757      any location list and still facing inlining issues if handled as
758      unoptimized code.  For a future better test see GCC PR other/32998.  */
759   unsigned int has_loclist : 1;
760
761   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
762      if all the producer_is_* fields are valid.  This information is cached
763      because profiling CU expansion showed excessive time spent in
764      producer_is_gxx_lt_4_6.  */
765   unsigned int checked_producer : 1;
766   unsigned int producer_is_gxx_lt_4_6 : 1;
767   unsigned int producer_is_gcc_lt_4_3 : 1;
768   unsigned int producer_is_icc_lt_14 : 1;
769
770   /* When set, the file that we're processing is known to have
771      debugging info for C++ namespaces.  GCC 3.3.x did not produce
772      this information, but later versions do.  */
773
774   unsigned int processing_has_namespace_info : 1;
775 };
776
777 /* Persistent data held for a compilation unit, even when not
778    processing it.  We put a pointer to this structure in the
779    read_symtab_private field of the psymtab.  */
780
781 struct dwarf2_per_cu_data
782 {
783   /* The start offset and length of this compilation unit.
784      NOTE: Unlike comp_unit_head.length, this length includes
785      initial_length_size.
786      If the DIE refers to a DWO file, this is always of the original die,
787      not the DWO file.  */
788   sect_offset sect_off;
789   unsigned int length;
790
791   /* DWARF standard version this data has been read from (such as 4 or 5).  */
792   short dwarf_version;
793
794   /* Flag indicating this compilation unit will be read in before
795      any of the current compilation units are processed.  */
796   unsigned int queued : 1;
797
798   /* This flag will be set when reading partial DIEs if we need to load
799      absolutely all DIEs for this compilation unit, instead of just the ones
800      we think are interesting.  It gets set if we look for a DIE in the
801      hash table and don't find it.  */
802   unsigned int load_all_dies : 1;
803
804   /* Non-zero if this CU is from .debug_types.
805      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
806      this is non-zero.  */
807   unsigned int is_debug_types : 1;
808
809   /* Non-zero if this CU is from the .dwz file.  */
810   unsigned int is_dwz : 1;
811
812   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
813      This flag is only valid if is_debug_types is true.
814      We can't read a CU directly from a DWO file: There are required
815      attributes in the stub.  */
816   unsigned int reading_dwo_directly : 1;
817
818   /* Non-zero if the TU has been read.
819      This is used to assist the "Stay in DWO Optimization" for Fission:
820      When reading a DWO, it's faster to read TUs from the DWO instead of
821      fetching them from random other DWOs (due to comdat folding).
822      If the TU has already been read, the optimization is unnecessary
823      (and unwise - we don't want to change where gdb thinks the TU lives
824      "midflight").
825      This flag is only valid if is_debug_types is true.  */
826   unsigned int tu_read : 1;
827
828   /* The section this CU/TU lives in.
829      If the DIE refers to a DWO file, this is always the original die,
830      not the DWO file.  */
831   struct dwarf2_section_info *section;
832
833   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
834      of the CU cache it gets reset to NULL again.  This is left as NULL for
835      dummy CUs (a CU header, but nothing else).  */
836   struct dwarf2_cu *cu;
837
838   /* The corresponding objfile.
839      Normally we can get the objfile from dwarf2_per_objfile.
840      However we can enter this file with just a "per_cu" handle.  */
841   struct objfile *objfile;
842
843   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
844      is active.  Otherwise, the 'psymtab' field is active.  */
845   union
846   {
847     /* The partial symbol table associated with this compilation unit,
848        or NULL for unread partial units.  */
849     struct partial_symtab *psymtab;
850
851     /* Data needed by the "quick" functions.  */
852     struct dwarf2_per_cu_quick_data *quick;
853   } v;
854
855   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
856      while reading psymtabs, used to compute the psymtab dependencies,
857      and then cleared.  Then it is filled in again while reading full
858      symbols, and only deleted when the objfile is destroyed.
859
860      This is also used to work around a difference between the way gold
861      generates .gdb_index version <=7 and the way gdb does.  Arguably this
862      is a gold bug.  For symbols coming from TUs, gold records in the index
863      the CU that includes the TU instead of the TU itself.  This breaks
864      dw2_lookup_symbol: It assumes that if the index says symbol X lives
865      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
866      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
867      we need to look in TU Z to find X.  Fortunately, this is akin to
868      DW_TAG_imported_unit, so we just use the same mechanism: For
869      .gdb_index version <=7 this also records the TUs that the CU referred
870      to.  Concurrently with this change gdb was modified to emit version 8
871      indices so we only pay a price for gold generated indices.
872      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
873   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
874 };
875
876 /* Entry in the signatured_types hash table.  */
877
878 struct signatured_type
879 {
880   /* The "per_cu" object of this type.
881      This struct is used iff per_cu.is_debug_types.
882      N.B.: This is the first member so that it's easy to convert pointers
883      between them.  */
884   struct dwarf2_per_cu_data per_cu;
885
886   /* The type's signature.  */
887   ULONGEST signature;
888
889   /* Offset in the TU of the type's DIE, as read from the TU header.
890      If this TU is a DWO stub and the definition lives in a DWO file
891      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
892   cu_offset type_offset_in_tu;
893
894   /* Offset in the section of the type's DIE.
895      If the definition lives in a DWO file, this is the offset in the
896      .debug_types.dwo section.
897      The value is zero until the actual value is known.
898      Zero is otherwise not a valid section offset.  */
899   sect_offset type_offset_in_section;
900
901   /* Type units are grouped by their DW_AT_stmt_list entry so that they
902      can share them.  This points to the containing symtab.  */
903   struct type_unit_group *type_unit_group;
904
905   /* The type.
906      The first time we encounter this type we fully read it in and install it
907      in the symbol tables.  Subsequent times we only need the type.  */
908   struct type *type;
909
910   /* Containing DWO unit.
911      This field is valid iff per_cu.reading_dwo_directly.  */
912   struct dwo_unit *dwo_unit;
913 };
914
915 typedef struct signatured_type *sig_type_ptr;
916 DEF_VEC_P (sig_type_ptr);
917
918 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
919    This includes type_unit_group and quick_file_names.  */
920
921 struct stmt_list_hash
922 {
923   /* The DWO unit this table is from or NULL if there is none.  */
924   struct dwo_unit *dwo_unit;
925
926   /* Offset in .debug_line or .debug_line.dwo.  */
927   sect_offset line_sect_off;
928 };
929
930 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
931    an object of this type.  */
932
933 struct type_unit_group
934 {
935   /* dwarf2read.c's main "handle" on a TU symtab.
936      To simplify things we create an artificial CU that "includes" all the
937      type units using this stmt_list so that the rest of the code still has
938      a "per_cu" handle on the symtab.
939      This PER_CU is recognized by having no section.  */
940 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
941   struct dwarf2_per_cu_data per_cu;
942
943   /* The TUs that share this DW_AT_stmt_list entry.
944      This is added to while parsing type units to build partial symtabs,
945      and is deleted afterwards and not used again.  */
946   VEC (sig_type_ptr) *tus;
947
948   /* The compunit symtab.
949      Type units in a group needn't all be defined in the same source file,
950      so we create an essentially anonymous symtab as the compunit symtab.  */
951   struct compunit_symtab *compunit_symtab;
952
953   /* The data used to construct the hash key.  */
954   struct stmt_list_hash hash;
955
956   /* The number of symtabs from the line header.
957      The value here must match line_header.num_file_names.  */
958   unsigned int num_symtabs;
959
960   /* The symbol tables for this TU (obtained from the files listed in
961      DW_AT_stmt_list).
962      WARNING: The order of entries here must match the order of entries
963      in the line header.  After the first TU using this type_unit_group, the
964      line header for the subsequent TUs is recreated from this.  This is done
965      because we need to use the same symtabs for each TU using the same
966      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
967      there's no guarantee the line header doesn't have duplicate entries.  */
968   struct symtab **symtabs;
969 };
970
971 /* These sections are what may appear in a (real or virtual) DWO file.  */
972
973 struct dwo_sections
974 {
975   struct dwarf2_section_info abbrev;
976   struct dwarf2_section_info line;
977   struct dwarf2_section_info loc;
978   struct dwarf2_section_info loclists;
979   struct dwarf2_section_info macinfo;
980   struct dwarf2_section_info macro;
981   struct dwarf2_section_info str;
982   struct dwarf2_section_info str_offsets;
983   /* In the case of a virtual DWO file, these two are unused.  */
984   struct dwarf2_section_info info;
985   VEC (dwarf2_section_info_def) *types;
986 };
987
988 /* CUs/TUs in DWP/DWO files.  */
989
990 struct dwo_unit
991 {
992   /* Backlink to the containing struct dwo_file.  */
993   struct dwo_file *dwo_file;
994
995   /* The "id" that distinguishes this CU/TU.
996      .debug_info calls this "dwo_id", .debug_types calls this "signature".
997      Since signatures came first, we stick with it for consistency.  */
998   ULONGEST signature;
999
1000   /* The section this CU/TU lives in, in the DWO file.  */
1001   struct dwarf2_section_info *section;
1002
1003   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1004   sect_offset sect_off;
1005   unsigned int length;
1006
1007   /* For types, offset in the type's DIE of the type defined by this TU.  */
1008   cu_offset type_offset_in_tu;
1009 };
1010
1011 /* include/dwarf2.h defines the DWP section codes.
1012    It defines a max value but it doesn't define a min value, which we
1013    use for error checking, so provide one.  */
1014
1015 enum dwp_v2_section_ids
1016 {
1017   DW_SECT_MIN = 1
1018 };
1019
1020 /* Data for one DWO file.
1021
1022    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1023    appears in a DWP file).  DWP files don't really have DWO files per se -
1024    comdat folding of types "loses" the DWO file they came from, and from
1025    a high level view DWP files appear to contain a mass of random types.
1026    However, to maintain consistency with the non-DWP case we pretend DWP
1027    files contain virtual DWO files, and we assign each TU with one virtual
1028    DWO file (generally based on the line and abbrev section offsets -
1029    a heuristic that seems to work in practice).  */
1030
1031 struct dwo_file
1032 {
1033   /* The DW_AT_GNU_dwo_name attribute.
1034      For virtual DWO files the name is constructed from the section offsets
1035      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1036      from related CU+TUs.  */
1037   const char *dwo_name;
1038
1039   /* The DW_AT_comp_dir attribute.  */
1040   const char *comp_dir;
1041
1042   /* The bfd, when the file is open.  Otherwise this is NULL.
1043      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1044   bfd *dbfd;
1045
1046   /* The sections that make up this DWO file.
1047      Remember that for virtual DWO files in DWP V2, these are virtual
1048      sections (for lack of a better name).  */
1049   struct dwo_sections sections;
1050
1051   /* The CUs in the file.
1052      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1053      an extension to handle LLVM's Link Time Optimization output (where
1054      multiple source files may be compiled into a single object/dwo pair). */
1055   htab_t cus;
1056
1057   /* Table of TUs in the file.
1058      Each element is a struct dwo_unit.  */
1059   htab_t tus;
1060 };
1061
1062 /* These sections are what may appear in a DWP file.  */
1063
1064 struct dwp_sections
1065 {
1066   /* These are used by both DWP version 1 and 2.  */
1067   struct dwarf2_section_info str;
1068   struct dwarf2_section_info cu_index;
1069   struct dwarf2_section_info tu_index;
1070
1071   /* These are only used by DWP version 2 files.
1072      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1073      sections are referenced by section number, and are not recorded here.
1074      In DWP version 2 there is at most one copy of all these sections, each
1075      section being (effectively) comprised of the concatenation of all of the
1076      individual sections that exist in the version 1 format.
1077      To keep the code simple we treat each of these concatenated pieces as a
1078      section itself (a virtual section?).  */
1079   struct dwarf2_section_info abbrev;
1080   struct dwarf2_section_info info;
1081   struct dwarf2_section_info line;
1082   struct dwarf2_section_info loc;
1083   struct dwarf2_section_info macinfo;
1084   struct dwarf2_section_info macro;
1085   struct dwarf2_section_info str_offsets;
1086   struct dwarf2_section_info types;
1087 };
1088
1089 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1090    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1091
1092 struct virtual_v1_dwo_sections
1093 {
1094   struct dwarf2_section_info abbrev;
1095   struct dwarf2_section_info line;
1096   struct dwarf2_section_info loc;
1097   struct dwarf2_section_info macinfo;
1098   struct dwarf2_section_info macro;
1099   struct dwarf2_section_info str_offsets;
1100   /* Each DWP hash table entry records one CU or one TU.
1101      That is recorded here, and copied to dwo_unit.section.  */
1102   struct dwarf2_section_info info_or_types;
1103 };
1104
1105 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1106    In version 2, the sections of the DWO files are concatenated together
1107    and stored in one section of that name.  Thus each ELF section contains
1108    several "virtual" sections.  */
1109
1110 struct virtual_v2_dwo_sections
1111 {
1112   bfd_size_type abbrev_offset;
1113   bfd_size_type abbrev_size;
1114
1115   bfd_size_type line_offset;
1116   bfd_size_type line_size;
1117
1118   bfd_size_type loc_offset;
1119   bfd_size_type loc_size;
1120
1121   bfd_size_type macinfo_offset;
1122   bfd_size_type macinfo_size;
1123
1124   bfd_size_type macro_offset;
1125   bfd_size_type macro_size;
1126
1127   bfd_size_type str_offsets_offset;
1128   bfd_size_type str_offsets_size;
1129
1130   /* Each DWP hash table entry records one CU or one TU.
1131      That is recorded here, and copied to dwo_unit.section.  */
1132   bfd_size_type info_or_types_offset;
1133   bfd_size_type info_or_types_size;
1134 };
1135
1136 /* Contents of DWP hash tables.  */
1137
1138 struct dwp_hash_table
1139 {
1140   uint32_t version, nr_columns;
1141   uint32_t nr_units, nr_slots;
1142   const gdb_byte *hash_table, *unit_table;
1143   union
1144   {
1145     struct
1146     {
1147       const gdb_byte *indices;
1148     } v1;
1149     struct
1150     {
1151       /* This is indexed by column number and gives the id of the section
1152          in that column.  */
1153 #define MAX_NR_V2_DWO_SECTIONS \
1154   (1 /* .debug_info or .debug_types */ \
1155    + 1 /* .debug_abbrev */ \
1156    + 1 /* .debug_line */ \
1157    + 1 /* .debug_loc */ \
1158    + 1 /* .debug_str_offsets */ \
1159    + 1 /* .debug_macro or .debug_macinfo */)
1160       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1161       const gdb_byte *offsets;
1162       const gdb_byte *sizes;
1163     } v2;
1164   } section_pool;
1165 };
1166
1167 /* Data for one DWP file.  */
1168
1169 struct dwp_file
1170 {
1171   /* Name of the file.  */
1172   const char *name;
1173
1174   /* File format version.  */
1175   int version;
1176
1177   /* The bfd.  */
1178   bfd *dbfd;
1179
1180   /* Section info for this file.  */
1181   struct dwp_sections sections;
1182
1183   /* Table of CUs in the file.  */
1184   const struct dwp_hash_table *cus;
1185
1186   /* Table of TUs in the file.  */
1187   const struct dwp_hash_table *tus;
1188
1189   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1190   htab_t loaded_cus;
1191   htab_t loaded_tus;
1192
1193   /* Table to map ELF section numbers to their sections.
1194      This is only needed for the DWP V1 file format.  */
1195   unsigned int num_sections;
1196   asection **elf_sections;
1197 };
1198
1199 /* This represents a '.dwz' file.  */
1200
1201 struct dwz_file
1202 {
1203   /* A dwz file can only contain a few sections.  */
1204   struct dwarf2_section_info abbrev;
1205   struct dwarf2_section_info info;
1206   struct dwarf2_section_info str;
1207   struct dwarf2_section_info line;
1208   struct dwarf2_section_info macro;
1209   struct dwarf2_section_info gdb_index;
1210   struct dwarf2_section_info debug_names;
1211
1212   /* The dwz's BFD.  */
1213   bfd *dwz_bfd;
1214 };
1215
1216 /* Struct used to pass misc. parameters to read_die_and_children, et
1217    al.  which are used for both .debug_info and .debug_types dies.
1218    All parameters here are unchanging for the life of the call.  This
1219    struct exists to abstract away the constant parameters of die reading.  */
1220
1221 struct die_reader_specs
1222 {
1223   /* The bfd of die_section.  */
1224   bfd* abfd;
1225
1226   /* The CU of the DIE we are parsing.  */
1227   struct dwarf2_cu *cu;
1228
1229   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1230   struct dwo_file *dwo_file;
1231
1232   /* The section the die comes from.
1233      This is either .debug_info or .debug_types, or the .dwo variants.  */
1234   struct dwarf2_section_info *die_section;
1235
1236   /* die_section->buffer.  */
1237   const gdb_byte *buffer;
1238
1239   /* The end of the buffer.  */
1240   const gdb_byte *buffer_end;
1241
1242   /* The value of the DW_AT_comp_dir attribute.  */
1243   const char *comp_dir;
1244 };
1245
1246 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1247 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1248                                       const gdb_byte *info_ptr,
1249                                       struct die_info *comp_unit_die,
1250                                       int has_children,
1251                                       void *data);
1252
1253 /* A 1-based directory index.  This is a strong typedef to prevent
1254    accidentally using a directory index as a 0-based index into an
1255    array/vector.  */
1256 enum class dir_index : unsigned int {};
1257
1258 /* Likewise, a 1-based file name index.  */
1259 enum class file_name_index : unsigned int {};
1260
1261 struct file_entry
1262 {
1263   file_entry () = default;
1264
1265   file_entry (const char *name_, dir_index d_index_,
1266               unsigned int mod_time_, unsigned int length_)
1267     : name (name_),
1268       d_index (d_index_),
1269       mod_time (mod_time_),
1270       length (length_)
1271   {}
1272
1273   /* Return the include directory at D_INDEX stored in LH.  Returns
1274      NULL if D_INDEX is out of bounds.  */
1275   const char *include_dir (const line_header *lh) const;
1276
1277   /* The file name.  Note this is an observing pointer.  The memory is
1278      owned by debug_line_buffer.  */
1279   const char *name {};
1280
1281   /* The directory index (1-based).  */
1282   dir_index d_index {};
1283
1284   unsigned int mod_time {};
1285
1286   unsigned int length {};
1287
1288   /* True if referenced by the Line Number Program.  */
1289   bool included_p {};
1290
1291   /* The associated symbol table, if any.  */
1292   struct symtab *symtab {};
1293 };
1294
1295 /* The line number information for a compilation unit (found in the
1296    .debug_line section) begins with a "statement program header",
1297    which contains the following information.  */
1298 struct line_header
1299 {
1300   line_header ()
1301     : offset_in_dwz {}
1302   {}
1303
1304   /* Add an entry to the include directory table.  */
1305   void add_include_dir (const char *include_dir);
1306
1307   /* Add an entry to the file name table.  */
1308   void add_file_name (const char *name, dir_index d_index,
1309                       unsigned int mod_time, unsigned int length);
1310
1311   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1312      is out of bounds.  */
1313   const char *include_dir_at (dir_index index) const
1314   {
1315     /* Convert directory index number (1-based) to vector index
1316        (0-based).  */
1317     size_t vec_index = to_underlying (index) - 1;
1318
1319     if (vec_index >= include_dirs.size ())
1320       return NULL;
1321     return include_dirs[vec_index];
1322   }
1323
1324   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1325      is out of bounds.  */
1326   file_entry *file_name_at (file_name_index index)
1327   {
1328     /* Convert file name index number (1-based) to vector index
1329        (0-based).  */
1330     size_t vec_index = to_underlying (index) - 1;
1331
1332     if (vec_index >= file_names.size ())
1333       return NULL;
1334     return &file_names[vec_index];
1335   }
1336
1337   /* Const version of the above.  */
1338   const file_entry *file_name_at (unsigned int index) const
1339   {
1340     if (index >= file_names.size ())
1341       return NULL;
1342     return &file_names[index];
1343   }
1344
1345   /* Offset of line number information in .debug_line section.  */
1346   sect_offset sect_off {};
1347
1348   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1349   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1350
1351   unsigned int total_length {};
1352   unsigned short version {};
1353   unsigned int header_length {};
1354   unsigned char minimum_instruction_length {};
1355   unsigned char maximum_ops_per_instruction {};
1356   unsigned char default_is_stmt {};
1357   int line_base {};
1358   unsigned char line_range {};
1359   unsigned char opcode_base {};
1360
1361   /* standard_opcode_lengths[i] is the number of operands for the
1362      standard opcode whose value is i.  This means that
1363      standard_opcode_lengths[0] is unused, and the last meaningful
1364      element is standard_opcode_lengths[opcode_base - 1].  */
1365   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1366
1367   /* The include_directories table.  Note these are observing
1368      pointers.  The memory is owned by debug_line_buffer.  */
1369   std::vector<const char *> include_dirs;
1370
1371   /* The file_names table.  */
1372   std::vector<file_entry> file_names;
1373
1374   /* The start and end of the statement program following this
1375      header.  These point into dwarf2_per_objfile->line_buffer.  */
1376   const gdb_byte *statement_program_start {}, *statement_program_end {};
1377 };
1378
1379 typedef std::unique_ptr<line_header> line_header_up;
1380
1381 const char *
1382 file_entry::include_dir (const line_header *lh) const
1383 {
1384   return lh->include_dir_at (d_index);
1385 }
1386
1387 /* When we construct a partial symbol table entry we only
1388    need this much information.  */
1389 struct partial_die_info
1390   {
1391     /* Offset of this DIE.  */
1392     sect_offset sect_off;
1393
1394     /* DWARF-2 tag for this DIE.  */
1395     ENUM_BITFIELD(dwarf_tag) tag : 16;
1396
1397     /* Assorted flags describing the data found in this DIE.  */
1398     unsigned int has_children : 1;
1399     unsigned int is_external : 1;
1400     unsigned int is_declaration : 1;
1401     unsigned int has_type : 1;
1402     unsigned int has_specification : 1;
1403     unsigned int has_pc_info : 1;
1404     unsigned int may_be_inlined : 1;
1405
1406     /* This DIE has been marked DW_AT_main_subprogram.  */
1407     unsigned int main_subprogram : 1;
1408
1409     /* Flag set if the SCOPE field of this structure has been
1410        computed.  */
1411     unsigned int scope_set : 1;
1412
1413     /* Flag set if the DIE has a byte_size attribute.  */
1414     unsigned int has_byte_size : 1;
1415
1416     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1417     unsigned int has_const_value : 1;
1418
1419     /* Flag set if any of the DIE's children are template arguments.  */
1420     unsigned int has_template_arguments : 1;
1421
1422     /* Flag set if fixup_partial_die has been called on this die.  */
1423     unsigned int fixup_called : 1;
1424
1425     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1426     unsigned int is_dwz : 1;
1427
1428     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1429     unsigned int spec_is_dwz : 1;
1430
1431     /* The name of this DIE.  Normally the value of DW_AT_name, but
1432        sometimes a default name for unnamed DIEs.  */
1433     const char *name;
1434
1435     /* The linkage name, if present.  */
1436     const char *linkage_name;
1437
1438     /* The scope to prepend to our children.  This is generally
1439        allocated on the comp_unit_obstack, so will disappear
1440        when this compilation unit leaves the cache.  */
1441     const char *scope;
1442
1443     /* Some data associated with the partial DIE.  The tag determines
1444        which field is live.  */
1445     union
1446     {
1447       /* The location description associated with this DIE, if any.  */
1448       struct dwarf_block *locdesc;
1449       /* The offset of an import, for DW_TAG_imported_unit.  */
1450       sect_offset sect_off;
1451     } d;
1452
1453     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1454     CORE_ADDR lowpc;
1455     CORE_ADDR highpc;
1456
1457     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1458        DW_AT_sibling, if any.  */
1459     /* NOTE: This member isn't strictly necessary, read_partial_die could
1460        return DW_AT_sibling values to its caller load_partial_dies.  */
1461     const gdb_byte *sibling;
1462
1463     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1464        DW_AT_specification (or DW_AT_abstract_origin or
1465        DW_AT_extension).  */
1466     sect_offset spec_offset;
1467
1468     /* Pointers to this DIE's parent, first child, and next sibling,
1469        if any.  */
1470     struct partial_die_info *die_parent, *die_child, *die_sibling;
1471   };
1472
1473 /* This data structure holds the information of an abbrev.  */
1474 struct abbrev_info
1475   {
1476     unsigned int number;        /* number identifying abbrev */
1477     enum dwarf_tag tag;         /* dwarf tag */
1478     unsigned short has_children;                /* boolean */
1479     unsigned short num_attrs;   /* number of attributes */
1480     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1481     struct abbrev_info *next;   /* next in chain */
1482   };
1483
1484 struct attr_abbrev
1485   {
1486     ENUM_BITFIELD(dwarf_attribute) name : 16;
1487     ENUM_BITFIELD(dwarf_form) form : 16;
1488
1489     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1490     LONGEST implicit_const;
1491   };
1492
1493 /* Size of abbrev_table.abbrev_hash_table.  */
1494 #define ABBREV_HASH_SIZE 121
1495
1496 /* Top level data structure to contain an abbreviation table.  */
1497
1498 struct abbrev_table
1499 {
1500   /* Where the abbrev table came from.
1501      This is used as a sanity check when the table is used.  */
1502   sect_offset sect_off;
1503
1504   /* Storage for the abbrev table.  */
1505   struct obstack abbrev_obstack;
1506
1507   /* Hash table of abbrevs.
1508      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1509      It could be statically allocated, but the previous code didn't so we
1510      don't either.  */
1511   struct abbrev_info **abbrevs;
1512 };
1513
1514 /* Attributes have a name and a value.  */
1515 struct attribute
1516   {
1517     ENUM_BITFIELD(dwarf_attribute) name : 16;
1518     ENUM_BITFIELD(dwarf_form) form : 15;
1519
1520     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1521        field should be in u.str (existing only for DW_STRING) but it is kept
1522        here for better struct attribute alignment.  */
1523     unsigned int string_is_canonical : 1;
1524
1525     union
1526       {
1527         const char *str;
1528         struct dwarf_block *blk;
1529         ULONGEST unsnd;
1530         LONGEST snd;
1531         CORE_ADDR addr;
1532         ULONGEST signature;
1533       }
1534     u;
1535   };
1536
1537 /* This data structure holds a complete die structure.  */
1538 struct die_info
1539   {
1540     /* DWARF-2 tag for this DIE.  */
1541     ENUM_BITFIELD(dwarf_tag) tag : 16;
1542
1543     /* Number of attributes */
1544     unsigned char num_attrs;
1545
1546     /* True if we're presently building the full type name for the
1547        type derived from this DIE.  */
1548     unsigned char building_fullname : 1;
1549
1550     /* True if this die is in process.  PR 16581.  */
1551     unsigned char in_process : 1;
1552
1553     /* Abbrev number */
1554     unsigned int abbrev;
1555
1556     /* Offset in .debug_info or .debug_types section.  */
1557     sect_offset sect_off;
1558
1559     /* The dies in a compilation unit form an n-ary tree.  PARENT
1560        points to this die's parent; CHILD points to the first child of
1561        this node; and all the children of a given node are chained
1562        together via their SIBLING fields.  */
1563     struct die_info *child;     /* Its first child, if any.  */
1564     struct die_info *sibling;   /* Its next sibling, if any.  */
1565     struct die_info *parent;    /* Its parent, if any.  */
1566
1567     /* An array of attributes, with NUM_ATTRS elements.  There may be
1568        zero, but it's not common and zero-sized arrays are not
1569        sufficiently portable C.  */
1570     struct attribute attrs[1];
1571   };
1572
1573 /* Get at parts of an attribute structure.  */
1574
1575 #define DW_STRING(attr)    ((attr)->u.str)
1576 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1577 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1578 #define DW_BLOCK(attr)     ((attr)->u.blk)
1579 #define DW_SND(attr)       ((attr)->u.snd)
1580 #define DW_ADDR(attr)      ((attr)->u.addr)
1581 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1582
1583 /* Blocks are a bunch of untyped bytes.  */
1584 struct dwarf_block
1585   {
1586     size_t size;
1587
1588     /* Valid only if SIZE is not zero.  */
1589     const gdb_byte *data;
1590   };
1591
1592 #ifndef ATTR_ALLOC_CHUNK
1593 #define ATTR_ALLOC_CHUNK 4
1594 #endif
1595
1596 /* Allocate fields for structs, unions and enums in this size.  */
1597 #ifndef DW_FIELD_ALLOC_CHUNK
1598 #define DW_FIELD_ALLOC_CHUNK 4
1599 #endif
1600
1601 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1602    but this would require a corresponding change in unpack_field_as_long
1603    and friends.  */
1604 static int bits_per_byte = 8;
1605
1606 struct nextfield
1607 {
1608   struct nextfield *next;
1609   int accessibility;
1610   int virtuality;
1611   struct field field;
1612 };
1613
1614 struct nextfnfield
1615 {
1616   struct nextfnfield *next;
1617   struct fn_field fnfield;
1618 };
1619
1620 struct fnfieldlist
1621 {
1622   const char *name;
1623   int length;
1624   struct nextfnfield *head;
1625 };
1626
1627 struct decl_field_list
1628 {
1629   struct decl_field field;
1630   struct decl_field_list *next;
1631 };
1632
1633 /* The routines that read and process dies for a C struct or C++ class
1634    pass lists of data member fields and lists of member function fields
1635    in an instance of a field_info structure, as defined below.  */
1636 struct field_info
1637   {
1638     /* List of data member and baseclasses fields.  */
1639     struct nextfield *fields, *baseclasses;
1640
1641     /* Number of fields (including baseclasses).  */
1642     int nfields;
1643
1644     /* Number of baseclasses.  */
1645     int nbaseclasses;
1646
1647     /* Set if the accesibility of one of the fields is not public.  */
1648     int non_public_fields;
1649
1650     /* Member function fieldlist array, contains name of possibly overloaded
1651        member function, number of overloaded member functions and a pointer
1652        to the head of the member function field chain.  */
1653     struct fnfieldlist *fnfieldlists;
1654
1655     /* Number of entries in the fnfieldlists array.  */
1656     int nfnfields;
1657
1658     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1659        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1660     struct decl_field_list *typedef_field_list;
1661     unsigned typedef_field_list_count;
1662
1663     /* Nested types defined by this class and the number of elements in this
1664        list.  */
1665     struct decl_field_list *nested_types_list;
1666     unsigned nested_types_list_count;
1667   };
1668
1669 /* One item on the queue of compilation units to read in full symbols
1670    for.  */
1671 struct dwarf2_queue_item
1672 {
1673   struct dwarf2_per_cu_data *per_cu;
1674   enum language pretend_language;
1675   struct dwarf2_queue_item *next;
1676 };
1677
1678 /* The current queue.  */
1679 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1680
1681 /* Loaded secondary compilation units are kept in memory until they
1682    have not been referenced for the processing of this many
1683    compilation units.  Set this to zero to disable caching.  Cache
1684    sizes of up to at least twenty will improve startup time for
1685    typical inter-CU-reference binaries, at an obvious memory cost.  */
1686 static int dwarf_max_cache_age = 5;
1687 static void
1688 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1689                           struct cmd_list_element *c, const char *value)
1690 {
1691   fprintf_filtered (file, _("The upper bound on the age of cached "
1692                             "DWARF compilation units is %s.\n"),
1693                     value);
1694 }
1695 \f
1696 /* local function prototypes */
1697
1698 static const char *get_section_name (const struct dwarf2_section_info *);
1699
1700 static const char *get_section_file_name (const struct dwarf2_section_info *);
1701
1702 static void dwarf2_find_base_address (struct die_info *die,
1703                                       struct dwarf2_cu *cu);
1704
1705 static struct partial_symtab *create_partial_symtab
1706   (struct dwarf2_per_cu_data *per_cu, const char *name);
1707
1708 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1709                                         const gdb_byte *info_ptr,
1710                                         struct die_info *type_unit_die,
1711                                         int has_children, void *data);
1712
1713 static void dwarf2_build_psymtabs_hard (struct objfile *);
1714
1715 static void scan_partial_symbols (struct partial_die_info *,
1716                                   CORE_ADDR *, CORE_ADDR *,
1717                                   int, struct dwarf2_cu *);
1718
1719 static void add_partial_symbol (struct partial_die_info *,
1720                                 struct dwarf2_cu *);
1721
1722 static void add_partial_namespace (struct partial_die_info *pdi,
1723                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1724                                    int set_addrmap, struct dwarf2_cu *cu);
1725
1726 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1727                                 CORE_ADDR *highpc, int set_addrmap,
1728                                 struct dwarf2_cu *cu);
1729
1730 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1731                                      struct dwarf2_cu *cu);
1732
1733 static void add_partial_subprogram (struct partial_die_info *pdi,
1734                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1735                                     int need_pc, struct dwarf2_cu *cu);
1736
1737 static void dwarf2_read_symtab (struct partial_symtab *,
1738                                 struct objfile *);
1739
1740 static void psymtab_to_symtab_1 (struct partial_symtab *);
1741
1742 static struct abbrev_info *abbrev_table_lookup_abbrev
1743   (const struct abbrev_table *, unsigned int);
1744
1745 static struct abbrev_table *abbrev_table_read_table
1746   (struct dwarf2_section_info *, sect_offset);
1747
1748 static void abbrev_table_free (struct abbrev_table *);
1749
1750 static void abbrev_table_free_cleanup (void *);
1751
1752 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1753                                  struct dwarf2_section_info *);
1754
1755 static void dwarf2_free_abbrev_table (void *);
1756
1757 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1758
1759 static struct partial_die_info *load_partial_dies
1760   (const struct die_reader_specs *, const gdb_byte *, int);
1761
1762 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1763                                          struct partial_die_info *,
1764                                          struct abbrev_info *,
1765                                          unsigned int,
1766                                          const gdb_byte *);
1767
1768 static struct partial_die_info *find_partial_die (sect_offset, int,
1769                                                   struct dwarf2_cu *);
1770
1771 static void fixup_partial_die (struct partial_die_info *,
1772                                struct dwarf2_cu *);
1773
1774 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1775                                        struct attribute *, struct attr_abbrev *,
1776                                        const gdb_byte *);
1777
1778 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1779
1780 static int read_1_signed_byte (bfd *, const gdb_byte *);
1781
1782 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1783
1784 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1785
1786 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1787
1788 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1789                                unsigned int *);
1790
1791 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1792
1793 static LONGEST read_checked_initial_length_and_offset
1794   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1795    unsigned int *, unsigned int *);
1796
1797 static LONGEST read_offset (bfd *, const gdb_byte *,
1798                             const struct comp_unit_head *,
1799                             unsigned int *);
1800
1801 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1802
1803 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1804                                        sect_offset);
1805
1806 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1807
1808 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1809
1810 static const char *read_indirect_string (bfd *, const gdb_byte *,
1811                                          const struct comp_unit_head *,
1812                                          unsigned int *);
1813
1814 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1815                                               const struct comp_unit_head *,
1816                                               unsigned int *);
1817
1818 static const char *read_indirect_string_at_offset (bfd *abfd,
1819                                                    LONGEST str_offset);
1820
1821 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1822
1823 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1824
1825 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1826                                               const gdb_byte *,
1827                                               unsigned int *);
1828
1829 static const char *read_str_index (const struct die_reader_specs *reader,
1830                                    ULONGEST str_index);
1831
1832 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1833
1834 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1835                                       struct dwarf2_cu *);
1836
1837 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1838                                                 unsigned int);
1839
1840 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1841                                        struct dwarf2_cu *cu);
1842
1843 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1844                                struct dwarf2_cu *cu);
1845
1846 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1847
1848 static struct die_info *die_specification (struct die_info *die,
1849                                            struct dwarf2_cu **);
1850
1851 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1852                                                 struct dwarf2_cu *cu);
1853
1854 static void dwarf_decode_lines (struct line_header *, const char *,
1855                                 struct dwarf2_cu *, struct partial_symtab *,
1856                                 CORE_ADDR, int decode_mapping);
1857
1858 static void dwarf2_start_subfile (const char *, const char *);
1859
1860 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1861                                                     const char *, const char *,
1862                                                     CORE_ADDR);
1863
1864 static struct symbol *new_symbol (struct die_info *, struct type *,
1865                                   struct dwarf2_cu *);
1866
1867 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1868                                        struct dwarf2_cu *, struct symbol *);
1869
1870 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1871                                 struct dwarf2_cu *);
1872
1873 static void dwarf2_const_value_attr (const struct attribute *attr,
1874                                      struct type *type,
1875                                      const char *name,
1876                                      struct obstack *obstack,
1877                                      struct dwarf2_cu *cu, LONGEST *value,
1878                                      const gdb_byte **bytes,
1879                                      struct dwarf2_locexpr_baton **baton);
1880
1881 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1882
1883 static int need_gnat_info (struct dwarf2_cu *);
1884
1885 static struct type *die_descriptive_type (struct die_info *,
1886                                           struct dwarf2_cu *);
1887
1888 static void set_descriptive_type (struct type *, struct die_info *,
1889                                   struct dwarf2_cu *);
1890
1891 static struct type *die_containing_type (struct die_info *,
1892                                          struct dwarf2_cu *);
1893
1894 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1895                                      struct dwarf2_cu *);
1896
1897 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1898
1899 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1900
1901 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1902
1903 static char *typename_concat (struct obstack *obs, const char *prefix,
1904                               const char *suffix, int physname,
1905                               struct dwarf2_cu *cu);
1906
1907 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1908
1909 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1910
1911 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1912
1913 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1914
1915 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1916
1917 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1918
1919 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1920                                struct dwarf2_cu *, struct partial_symtab *);
1921
1922 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1923    values.  Keep the items ordered with increasing constraints compliance.  */
1924 enum pc_bounds_kind
1925 {
1926   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1927   PC_BOUNDS_NOT_PRESENT,
1928
1929   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1930      were present but they do not form a valid range of PC addresses.  */
1931   PC_BOUNDS_INVALID,
1932
1933   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1934   PC_BOUNDS_RANGES,
1935
1936   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1937   PC_BOUNDS_HIGH_LOW,
1938 };
1939
1940 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1941                                                  CORE_ADDR *, CORE_ADDR *,
1942                                                  struct dwarf2_cu *,
1943                                                  struct partial_symtab *);
1944
1945 static void get_scope_pc_bounds (struct die_info *,
1946                                  CORE_ADDR *, CORE_ADDR *,
1947                                  struct dwarf2_cu *);
1948
1949 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1950                                         CORE_ADDR, struct dwarf2_cu *);
1951
1952 static void dwarf2_add_field (struct field_info *, struct die_info *,
1953                               struct dwarf2_cu *);
1954
1955 static void dwarf2_attach_fields_to_type (struct field_info *,
1956                                           struct type *, struct dwarf2_cu *);
1957
1958 static void dwarf2_add_member_fn (struct field_info *,
1959                                   struct die_info *, struct type *,
1960                                   struct dwarf2_cu *);
1961
1962 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1963                                              struct type *,
1964                                              struct dwarf2_cu *);
1965
1966 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1967
1968 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1969
1970 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1971
1972 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1973
1974 static struct using_direct **using_directives (enum language);
1975
1976 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1977
1978 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1979
1980 static struct type *read_module_type (struct die_info *die,
1981                                       struct dwarf2_cu *cu);
1982
1983 static const char *namespace_name (struct die_info *die,
1984                                    int *is_anonymous, struct dwarf2_cu *);
1985
1986 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1987
1988 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1989
1990 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1991                                                        struct dwarf2_cu *);
1992
1993 static struct die_info *read_die_and_siblings_1
1994   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1995    struct die_info *);
1996
1997 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1998                                                const gdb_byte *info_ptr,
1999                                                const gdb_byte **new_info_ptr,
2000                                                struct die_info *parent);
2001
2002 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2003                                         struct die_info **, const gdb_byte *,
2004                                         int *, int);
2005
2006 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2007                                       struct die_info **, const gdb_byte *,
2008                                       int *);
2009
2010 static void process_die (struct die_info *, struct dwarf2_cu *);
2011
2012 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2013                                              struct obstack *);
2014
2015 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2016
2017 static const char *dwarf2_full_name (const char *name,
2018                                      struct die_info *die,
2019                                      struct dwarf2_cu *cu);
2020
2021 static const char *dwarf2_physname (const char *name, struct die_info *die,
2022                                     struct dwarf2_cu *cu);
2023
2024 static struct die_info *dwarf2_extension (struct die_info *die,
2025                                           struct dwarf2_cu **);
2026
2027 static const char *dwarf_tag_name (unsigned int);
2028
2029 static const char *dwarf_attr_name (unsigned int);
2030
2031 static const char *dwarf_form_name (unsigned int);
2032
2033 static const char *dwarf_bool_name (unsigned int);
2034
2035 static const char *dwarf_type_encoding_name (unsigned int);
2036
2037 static struct die_info *sibling_die (struct die_info *);
2038
2039 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2040
2041 static void dump_die_for_error (struct die_info *);
2042
2043 static void dump_die_1 (struct ui_file *, int level, int max_level,
2044                         struct die_info *);
2045
2046 /*static*/ void dump_die (struct die_info *, int max_level);
2047
2048 static void store_in_ref_table (struct die_info *,
2049                                 struct dwarf2_cu *);
2050
2051 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2052
2053 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2054
2055 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2056                                                const struct attribute *,
2057                                                struct dwarf2_cu **);
2058
2059 static struct die_info *follow_die_ref (struct die_info *,
2060                                         const struct attribute *,
2061                                         struct dwarf2_cu **);
2062
2063 static struct die_info *follow_die_sig (struct die_info *,
2064                                         const struct attribute *,
2065                                         struct dwarf2_cu **);
2066
2067 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2068                                          struct dwarf2_cu *);
2069
2070 static struct type *get_DW_AT_signature_type (struct die_info *,
2071                                               const struct attribute *,
2072                                               struct dwarf2_cu *);
2073
2074 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2075
2076 static void read_signatured_type (struct signatured_type *);
2077
2078 static int attr_to_dynamic_prop (const struct attribute *attr,
2079                                  struct die_info *die, struct dwarf2_cu *cu,
2080                                  struct dynamic_prop *prop);
2081
2082 /* memory allocation interface */
2083
2084 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2085
2086 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2087
2088 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2089
2090 static int attr_form_is_block (const struct attribute *);
2091
2092 static int attr_form_is_section_offset (const struct attribute *);
2093
2094 static int attr_form_is_constant (const struct attribute *);
2095
2096 static int attr_form_is_ref (const struct attribute *);
2097
2098 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2099                                    struct dwarf2_loclist_baton *baton,
2100                                    const struct attribute *attr);
2101
2102 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2103                                          struct symbol *sym,
2104                                          struct dwarf2_cu *cu,
2105                                          int is_block);
2106
2107 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2108                                      const gdb_byte *info_ptr,
2109                                      struct abbrev_info *abbrev);
2110
2111 static void free_stack_comp_unit (void *);
2112
2113 static hashval_t partial_die_hash (const void *item);
2114
2115 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2116
2117 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2118   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2119
2120 static void init_one_comp_unit (struct dwarf2_cu *cu,
2121                                 struct dwarf2_per_cu_data *per_cu);
2122
2123 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2124                                    struct die_info *comp_unit_die,
2125                                    enum language pretend_language);
2126
2127 static void free_heap_comp_unit (void *);
2128
2129 static void free_cached_comp_units (void *);
2130
2131 static void age_cached_comp_units (void);
2132
2133 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2134
2135 static struct type *set_die_type (struct die_info *, struct type *,
2136                                   struct dwarf2_cu *);
2137
2138 static void create_all_comp_units (struct objfile *);
2139
2140 static int create_all_type_units (struct objfile *);
2141
2142 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2143                                  enum language);
2144
2145 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2146                                     enum language);
2147
2148 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2149                                     enum language);
2150
2151 static void dwarf2_add_dependence (struct dwarf2_cu *,
2152                                    struct dwarf2_per_cu_data *);
2153
2154 static void dwarf2_mark (struct dwarf2_cu *);
2155
2156 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2157
2158 static struct type *get_die_type_at_offset (sect_offset,
2159                                             struct dwarf2_per_cu_data *);
2160
2161 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2162
2163 static void dwarf2_release_queue (void *dummy);
2164
2165 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2166                              enum language pretend_language);
2167
2168 static void process_queue (void);
2169
2170 /* The return type of find_file_and_directory.  Note, the enclosed
2171    string pointers are only valid while this object is valid.  */
2172
2173 struct file_and_directory
2174 {
2175   /* The filename.  This is never NULL.  */
2176   const char *name;
2177
2178   /* The compilation directory.  NULL if not known.  If we needed to
2179      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2180      points directly to the DW_AT_comp_dir string attribute owned by
2181      the obstack that owns the DIE.  */
2182   const char *comp_dir;
2183
2184   /* If we needed to build a new string for comp_dir, this is what
2185      owns the storage.  */
2186   std::string comp_dir_storage;
2187 };
2188
2189 static file_and_directory find_file_and_directory (struct die_info *die,
2190                                                    struct dwarf2_cu *cu);
2191
2192 static char *file_full_name (int file, struct line_header *lh,
2193                              const char *comp_dir);
2194
2195 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2196 enum class rcuh_kind { COMPILE, TYPE };
2197
2198 static const gdb_byte *read_and_check_comp_unit_head
2199   (struct comp_unit_head *header,
2200    struct dwarf2_section_info *section,
2201    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2202    rcuh_kind section_kind);
2203
2204 static void init_cutu_and_read_dies
2205   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2206    int use_existing_cu, int keep,
2207    die_reader_func_ftype *die_reader_func, void *data);
2208
2209 static void init_cutu_and_read_dies_simple
2210   (struct dwarf2_per_cu_data *this_cu,
2211    die_reader_func_ftype *die_reader_func, void *data);
2212
2213 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2214
2215 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2216
2217 static struct dwo_unit *lookup_dwo_unit_in_dwp
2218   (struct dwp_file *dwp_file, const char *comp_dir,
2219    ULONGEST signature, int is_debug_types);
2220
2221 static struct dwp_file *get_dwp_file (void);
2222
2223 static struct dwo_unit *lookup_dwo_comp_unit
2224   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2225
2226 static struct dwo_unit *lookup_dwo_type_unit
2227   (struct signatured_type *, const char *, const char *);
2228
2229 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2230
2231 static void free_dwo_file_cleanup (void *);
2232
2233 static void process_cu_includes (void);
2234
2235 static void check_producer (struct dwarf2_cu *cu);
2236
2237 static void free_line_header_voidp (void *arg);
2238 \f
2239 /* Various complaints about symbol reading that don't abort the process.  */
2240
2241 static void
2242 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2243 {
2244   complaint (&symfile_complaints,
2245              _("statement list doesn't fit in .debug_line section"));
2246 }
2247
2248 static void
2249 dwarf2_debug_line_missing_file_complaint (void)
2250 {
2251   complaint (&symfile_complaints,
2252              _(".debug_line section has line data without a file"));
2253 }
2254
2255 static void
2256 dwarf2_debug_line_missing_end_sequence_complaint (void)
2257 {
2258   complaint (&symfile_complaints,
2259              _(".debug_line section has line "
2260                "program sequence without an end"));
2261 }
2262
2263 static void
2264 dwarf2_complex_location_expr_complaint (void)
2265 {
2266   complaint (&symfile_complaints, _("location expression too complex"));
2267 }
2268
2269 static void
2270 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2271                                               int arg3)
2272 {
2273   complaint (&symfile_complaints,
2274              _("const value length mismatch for '%s', got %d, expected %d"),
2275              arg1, arg2, arg3);
2276 }
2277
2278 static void
2279 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2280 {
2281   complaint (&symfile_complaints,
2282              _("debug info runs off end of %s section"
2283                " [in module %s]"),
2284              get_section_name (section),
2285              get_section_file_name (section));
2286 }
2287
2288 static void
2289 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2290 {
2291   complaint (&symfile_complaints,
2292              _("macro debug info contains a "
2293                "malformed macro definition:\n`%s'"),
2294              arg1);
2295 }
2296
2297 static void
2298 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2299 {
2300   complaint (&symfile_complaints,
2301              _("invalid attribute class or form for '%s' in '%s'"),
2302              arg1, arg2);
2303 }
2304
2305 /* Hash function for line_header_hash.  */
2306
2307 static hashval_t
2308 line_header_hash (const struct line_header *ofs)
2309 {
2310   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2311 }
2312
2313 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2314
2315 static hashval_t
2316 line_header_hash_voidp (const void *item)
2317 {
2318   const struct line_header *ofs = (const struct line_header *) item;
2319
2320   return line_header_hash (ofs);
2321 }
2322
2323 /* Equality function for line_header_hash.  */
2324
2325 static int
2326 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2327 {
2328   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2329   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2330
2331   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2332           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2333 }
2334
2335 \f
2336
2337 /* Read the given attribute value as an address, taking the attribute's
2338    form into account.  */
2339
2340 static CORE_ADDR
2341 attr_value_as_address (struct attribute *attr)
2342 {
2343   CORE_ADDR addr;
2344
2345   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2346     {
2347       /* Aside from a few clearly defined exceptions, attributes that
2348          contain an address must always be in DW_FORM_addr form.
2349          Unfortunately, some compilers happen to be violating this
2350          requirement by encoding addresses using other forms, such
2351          as DW_FORM_data4 for example.  For those broken compilers,
2352          we try to do our best, without any guarantee of success,
2353          to interpret the address correctly.  It would also be nice
2354          to generate a complaint, but that would require us to maintain
2355          a list of legitimate cases where a non-address form is allowed,
2356          as well as update callers to pass in at least the CU's DWARF
2357          version.  This is more overhead than what we're willing to
2358          expand for a pretty rare case.  */
2359       addr = DW_UNSND (attr);
2360     }
2361   else
2362     addr = DW_ADDR (attr);
2363
2364   return addr;
2365 }
2366
2367 /* The suffix for an index file.  */
2368 #define INDEX4_SUFFIX ".gdb-index"
2369 #define INDEX5_SUFFIX ".debug_names"
2370 #define DEBUG_STR_SUFFIX ".debug_str"
2371
2372 /* See declaration.  */
2373
2374 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2375                                         const dwarf2_debug_sections *names)
2376   : objfile (objfile_)
2377 {
2378   if (names == NULL)
2379     names = &dwarf2_elf_names;
2380
2381   bfd *obfd = objfile->obfd;
2382
2383   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2384     locate_sections (obfd, sec, *names);
2385 }
2386
2387 dwarf2_per_objfile::~dwarf2_per_objfile ()
2388 {
2389   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2390   free_cached_comp_units ();
2391
2392   if (quick_file_names_table)
2393     htab_delete (quick_file_names_table);
2394
2395   if (line_header_hash)
2396     htab_delete (line_header_hash);
2397
2398   /* Everything else should be on the objfile obstack.  */
2399 }
2400
2401 /* See declaration.  */
2402
2403 void
2404 dwarf2_per_objfile::free_cached_comp_units ()
2405 {
2406   dwarf2_per_cu_data *per_cu = read_in_chain;
2407   dwarf2_per_cu_data **last_chain = &read_in_chain;
2408   while (per_cu != NULL)
2409     {
2410       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2411
2412       free_heap_comp_unit (per_cu->cu);
2413       *last_chain = next_cu;
2414       per_cu = next_cu;
2415     }
2416 }
2417
2418 /* Try to locate the sections we need for DWARF 2 debugging
2419    information and return true if we have enough to do something.
2420    NAMES points to the dwarf2 section names, or is NULL if the standard
2421    ELF names are used.  */
2422
2423 int
2424 dwarf2_has_info (struct objfile *objfile,
2425                  const struct dwarf2_debug_sections *names)
2426 {
2427   if (objfile->flags & OBJF_READNEVER)
2428     return 0;
2429
2430   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2431                         objfile_data (objfile, dwarf2_objfile_data_key));
2432   if (!dwarf2_per_objfile)
2433     {
2434       /* Initialize per-objfile state.  */
2435       struct dwarf2_per_objfile *data
2436         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2437
2438       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2439       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2440     }
2441   return (!dwarf2_per_objfile->info.is_virtual
2442           && dwarf2_per_objfile->info.s.section != NULL
2443           && !dwarf2_per_objfile->abbrev.is_virtual
2444           && dwarf2_per_objfile->abbrev.s.section != NULL);
2445 }
2446
2447 /* Return the containing section of virtual section SECTION.  */
2448
2449 static struct dwarf2_section_info *
2450 get_containing_section (const struct dwarf2_section_info *section)
2451 {
2452   gdb_assert (section->is_virtual);
2453   return section->s.containing_section;
2454 }
2455
2456 /* Return the bfd owner of SECTION.  */
2457
2458 static struct bfd *
2459 get_section_bfd_owner (const struct dwarf2_section_info *section)
2460 {
2461   if (section->is_virtual)
2462     {
2463       section = get_containing_section (section);
2464       gdb_assert (!section->is_virtual);
2465     }
2466   return section->s.section->owner;
2467 }
2468
2469 /* Return the bfd section of SECTION.
2470    Returns NULL if the section is not present.  */
2471
2472 static asection *
2473 get_section_bfd_section (const struct dwarf2_section_info *section)
2474 {
2475   if (section->is_virtual)
2476     {
2477       section = get_containing_section (section);
2478       gdb_assert (!section->is_virtual);
2479     }
2480   return section->s.section;
2481 }
2482
2483 /* Return the name of SECTION.  */
2484
2485 static const char *
2486 get_section_name (const struct dwarf2_section_info *section)
2487 {
2488   asection *sectp = get_section_bfd_section (section);
2489
2490   gdb_assert (sectp != NULL);
2491   return bfd_section_name (get_section_bfd_owner (section), sectp);
2492 }
2493
2494 /* Return the name of the file SECTION is in.  */
2495
2496 static const char *
2497 get_section_file_name (const struct dwarf2_section_info *section)
2498 {
2499   bfd *abfd = get_section_bfd_owner (section);
2500
2501   return bfd_get_filename (abfd);
2502 }
2503
2504 /* Return the id of SECTION.
2505    Returns 0 if SECTION doesn't exist.  */
2506
2507 static int
2508 get_section_id (const struct dwarf2_section_info *section)
2509 {
2510   asection *sectp = get_section_bfd_section (section);
2511
2512   if (sectp == NULL)
2513     return 0;
2514   return sectp->id;
2515 }
2516
2517 /* Return the flags of SECTION.
2518    SECTION (or containing section if this is a virtual section) must exist.  */
2519
2520 static int
2521 get_section_flags (const struct dwarf2_section_info *section)
2522 {
2523   asection *sectp = get_section_bfd_section (section);
2524
2525   gdb_assert (sectp != NULL);
2526   return bfd_get_section_flags (sectp->owner, sectp);
2527 }
2528
2529 /* When loading sections, we look either for uncompressed section or for
2530    compressed section names.  */
2531
2532 static int
2533 section_is_p (const char *section_name,
2534               const struct dwarf2_section_names *names)
2535 {
2536   if (names->normal != NULL
2537       && strcmp (section_name, names->normal) == 0)
2538     return 1;
2539   if (names->compressed != NULL
2540       && strcmp (section_name, names->compressed) == 0)
2541     return 1;
2542   return 0;
2543 }
2544
2545 /* See declaration.  */
2546
2547 void
2548 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2549                                      const dwarf2_debug_sections &names)
2550 {
2551   flagword aflag = bfd_get_section_flags (abfd, sectp);
2552
2553   if ((aflag & SEC_HAS_CONTENTS) == 0)
2554     {
2555     }
2556   else if (section_is_p (sectp->name, &names.info))
2557     {
2558       this->info.s.section = sectp;
2559       this->info.size = bfd_get_section_size (sectp);
2560     }
2561   else if (section_is_p (sectp->name, &names.abbrev))
2562     {
2563       this->abbrev.s.section = sectp;
2564       this->abbrev.size = bfd_get_section_size (sectp);
2565     }
2566   else if (section_is_p (sectp->name, &names.line))
2567     {
2568       this->line.s.section = sectp;
2569       this->line.size = bfd_get_section_size (sectp);
2570     }
2571   else if (section_is_p (sectp->name, &names.loc))
2572     {
2573       this->loc.s.section = sectp;
2574       this->loc.size = bfd_get_section_size (sectp);
2575     }
2576   else if (section_is_p (sectp->name, &names.loclists))
2577     {
2578       this->loclists.s.section = sectp;
2579       this->loclists.size = bfd_get_section_size (sectp);
2580     }
2581   else if (section_is_p (sectp->name, &names.macinfo))
2582     {
2583       this->macinfo.s.section = sectp;
2584       this->macinfo.size = bfd_get_section_size (sectp);
2585     }
2586   else if (section_is_p (sectp->name, &names.macro))
2587     {
2588       this->macro.s.section = sectp;
2589       this->macro.size = bfd_get_section_size (sectp);
2590     }
2591   else if (section_is_p (sectp->name, &names.str))
2592     {
2593       this->str.s.section = sectp;
2594       this->str.size = bfd_get_section_size (sectp);
2595     }
2596   else if (section_is_p (sectp->name, &names.line_str))
2597     {
2598       this->line_str.s.section = sectp;
2599       this->line_str.size = bfd_get_section_size (sectp);
2600     }
2601   else if (section_is_p (sectp->name, &names.addr))
2602     {
2603       this->addr.s.section = sectp;
2604       this->addr.size = bfd_get_section_size (sectp);
2605     }
2606   else if (section_is_p (sectp->name, &names.frame))
2607     {
2608       this->frame.s.section = sectp;
2609       this->frame.size = bfd_get_section_size (sectp);
2610     }
2611   else if (section_is_p (sectp->name, &names.eh_frame))
2612     {
2613       this->eh_frame.s.section = sectp;
2614       this->eh_frame.size = bfd_get_section_size (sectp);
2615     }
2616   else if (section_is_p (sectp->name, &names.ranges))
2617     {
2618       this->ranges.s.section = sectp;
2619       this->ranges.size = bfd_get_section_size (sectp);
2620     }
2621   else if (section_is_p (sectp->name, &names.rnglists))
2622     {
2623       this->rnglists.s.section = sectp;
2624       this->rnglists.size = bfd_get_section_size (sectp);
2625     }
2626   else if (section_is_p (sectp->name, &names.types))
2627     {
2628       struct dwarf2_section_info type_section;
2629
2630       memset (&type_section, 0, sizeof (type_section));
2631       type_section.s.section = sectp;
2632       type_section.size = bfd_get_section_size (sectp);
2633
2634       VEC_safe_push (dwarf2_section_info_def, this->types,
2635                      &type_section);
2636     }
2637   else if (section_is_p (sectp->name, &names.gdb_index))
2638     {
2639       this->gdb_index.s.section = sectp;
2640       this->gdb_index.size = bfd_get_section_size (sectp);
2641     }
2642   else if (section_is_p (sectp->name, &names.debug_names))
2643     {
2644       this->debug_names.s.section = sectp;
2645       this->debug_names.size = bfd_get_section_size (sectp);
2646     }
2647   else if (section_is_p (sectp->name, &names.debug_aranges))
2648     {
2649       this->debug_aranges.s.section = sectp;
2650       this->debug_aranges.size = bfd_get_section_size (sectp);
2651     }
2652
2653   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2654       && bfd_section_vma (abfd, sectp) == 0)
2655     this->has_section_at_zero = true;
2656 }
2657
2658 /* A helper function that decides whether a section is empty,
2659    or not present.  */
2660
2661 static int
2662 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2663 {
2664   if (section->is_virtual)
2665     return section->size == 0;
2666   return section->s.section == NULL || section->size == 0;
2667 }
2668
2669 /* Read the contents of the section INFO.
2670    OBJFILE is the main object file, but not necessarily the file where
2671    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2672    of the DWO file.
2673    If the section is compressed, uncompress it before returning.  */
2674
2675 static void
2676 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2677 {
2678   asection *sectp;
2679   bfd *abfd;
2680   gdb_byte *buf, *retbuf;
2681
2682   if (info->readin)
2683     return;
2684   info->buffer = NULL;
2685   info->readin = 1;
2686
2687   if (dwarf2_section_empty_p (info))
2688     return;
2689
2690   sectp = get_section_bfd_section (info);
2691
2692   /* If this is a virtual section we need to read in the real one first.  */
2693   if (info->is_virtual)
2694     {
2695       struct dwarf2_section_info *containing_section =
2696         get_containing_section (info);
2697
2698       gdb_assert (sectp != NULL);
2699       if ((sectp->flags & SEC_RELOC) != 0)
2700         {
2701           error (_("Dwarf Error: DWP format V2 with relocations is not"
2702                    " supported in section %s [in module %s]"),
2703                  get_section_name (info), get_section_file_name (info));
2704         }
2705       dwarf2_read_section (objfile, containing_section);
2706       /* Other code should have already caught virtual sections that don't
2707          fit.  */
2708       gdb_assert (info->virtual_offset + info->size
2709                   <= containing_section->size);
2710       /* If the real section is empty or there was a problem reading the
2711          section we shouldn't get here.  */
2712       gdb_assert (containing_section->buffer != NULL);
2713       info->buffer = containing_section->buffer + info->virtual_offset;
2714       return;
2715     }
2716
2717   /* If the section has relocations, we must read it ourselves.
2718      Otherwise we attach it to the BFD.  */
2719   if ((sectp->flags & SEC_RELOC) == 0)
2720     {
2721       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2722       return;
2723     }
2724
2725   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2726   info->buffer = buf;
2727
2728   /* When debugging .o files, we may need to apply relocations; see
2729      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2730      We never compress sections in .o files, so we only need to
2731      try this when the section is not compressed.  */
2732   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2733   if (retbuf != NULL)
2734     {
2735       info->buffer = retbuf;
2736       return;
2737     }
2738
2739   abfd = get_section_bfd_owner (info);
2740   gdb_assert (abfd != NULL);
2741
2742   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2743       || bfd_bread (buf, info->size, abfd) != info->size)
2744     {
2745       error (_("Dwarf Error: Can't read DWARF data"
2746                " in section %s [in module %s]"),
2747              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2748     }
2749 }
2750
2751 /* A helper function that returns the size of a section in a safe way.
2752    If you are positive that the section has been read before using the
2753    size, then it is safe to refer to the dwarf2_section_info object's
2754    "size" field directly.  In other cases, you must call this
2755    function, because for compressed sections the size field is not set
2756    correctly until the section has been read.  */
2757
2758 static bfd_size_type
2759 dwarf2_section_size (struct objfile *objfile,
2760                      struct dwarf2_section_info *info)
2761 {
2762   if (!info->readin)
2763     dwarf2_read_section (objfile, info);
2764   return info->size;
2765 }
2766
2767 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2768    SECTION_NAME.  */
2769
2770 void
2771 dwarf2_get_section_info (struct objfile *objfile,
2772                          enum dwarf2_section_enum sect,
2773                          asection **sectp, const gdb_byte **bufp,
2774                          bfd_size_type *sizep)
2775 {
2776   struct dwarf2_per_objfile *data
2777     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2778                                                   dwarf2_objfile_data_key);
2779   struct dwarf2_section_info *info;
2780
2781   /* We may see an objfile without any DWARF, in which case we just
2782      return nothing.  */
2783   if (data == NULL)
2784     {
2785       *sectp = NULL;
2786       *bufp = NULL;
2787       *sizep = 0;
2788       return;
2789     }
2790   switch (sect)
2791     {
2792     case DWARF2_DEBUG_FRAME:
2793       info = &data->frame;
2794       break;
2795     case DWARF2_EH_FRAME:
2796       info = &data->eh_frame;
2797       break;
2798     default:
2799       gdb_assert_not_reached ("unexpected section");
2800     }
2801
2802   dwarf2_read_section (objfile, info);
2803
2804   *sectp = get_section_bfd_section (info);
2805   *bufp = info->buffer;
2806   *sizep = info->size;
2807 }
2808
2809 /* A helper function to find the sections for a .dwz file.  */
2810
2811 static void
2812 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2813 {
2814   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2815
2816   /* Note that we only support the standard ELF names, because .dwz
2817      is ELF-only (at the time of writing).  */
2818   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2819     {
2820       dwz_file->abbrev.s.section = sectp;
2821       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2822     }
2823   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2824     {
2825       dwz_file->info.s.section = sectp;
2826       dwz_file->info.size = bfd_get_section_size (sectp);
2827     }
2828   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2829     {
2830       dwz_file->str.s.section = sectp;
2831       dwz_file->str.size = bfd_get_section_size (sectp);
2832     }
2833   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2834     {
2835       dwz_file->line.s.section = sectp;
2836       dwz_file->line.size = bfd_get_section_size (sectp);
2837     }
2838   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2839     {
2840       dwz_file->macro.s.section = sectp;
2841       dwz_file->macro.size = bfd_get_section_size (sectp);
2842     }
2843   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2844     {
2845       dwz_file->gdb_index.s.section = sectp;
2846       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2847     }
2848   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2849     {
2850       dwz_file->debug_names.s.section = sectp;
2851       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2852     }
2853 }
2854
2855 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2856    there is no .gnu_debugaltlink section in the file.  Error if there
2857    is such a section but the file cannot be found.  */
2858
2859 static struct dwz_file *
2860 dwarf2_get_dwz_file (void)
2861 {
2862   const char *filename;
2863   struct dwz_file *result;
2864   bfd_size_type buildid_len_arg;
2865   size_t buildid_len;
2866   bfd_byte *buildid;
2867
2868   if (dwarf2_per_objfile->dwz_file != NULL)
2869     return dwarf2_per_objfile->dwz_file;
2870
2871   bfd_set_error (bfd_error_no_error);
2872   gdb::unique_xmalloc_ptr<char> data
2873     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2874                                   &buildid_len_arg, &buildid));
2875   if (data == NULL)
2876     {
2877       if (bfd_get_error () == bfd_error_no_error)
2878         return NULL;
2879       error (_("could not read '.gnu_debugaltlink' section: %s"),
2880              bfd_errmsg (bfd_get_error ()));
2881     }
2882
2883   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2884
2885   buildid_len = (size_t) buildid_len_arg;
2886
2887   filename = data.get ();
2888
2889   std::string abs_storage;
2890   if (!IS_ABSOLUTE_PATH (filename))
2891     {
2892       gdb::unique_xmalloc_ptr<char> abs
2893         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2894
2895       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2896       filename = abs_storage.c_str ();
2897     }
2898
2899   /* First try the file name given in the section.  If that doesn't
2900      work, try to use the build-id instead.  */
2901   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2902   if (dwz_bfd != NULL)
2903     {
2904       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2905         dwz_bfd.release ();
2906     }
2907
2908   if (dwz_bfd == NULL)
2909     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2910
2911   if (dwz_bfd == NULL)
2912     error (_("could not find '.gnu_debugaltlink' file for %s"),
2913            objfile_name (dwarf2_per_objfile->objfile));
2914
2915   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2916                            struct dwz_file);
2917   result->dwz_bfd = dwz_bfd.release ();
2918
2919   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2920
2921   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2922   dwarf2_per_objfile->dwz_file = result;
2923   return result;
2924 }
2925 \f
2926 /* DWARF quick_symbols_functions support.  */
2927
2928 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2929    unique line tables, so we maintain a separate table of all .debug_line
2930    derived entries to support the sharing.
2931    All the quick functions need is the list of file names.  We discard the
2932    line_header when we're done and don't need to record it here.  */
2933 struct quick_file_names
2934 {
2935   /* The data used to construct the hash key.  */
2936   struct stmt_list_hash hash;
2937
2938   /* The number of entries in file_names, real_names.  */
2939   unsigned int num_file_names;
2940
2941   /* The file names from the line table, after being run through
2942      file_full_name.  */
2943   const char **file_names;
2944
2945   /* The file names from the line table after being run through
2946      gdb_realpath.  These are computed lazily.  */
2947   const char **real_names;
2948 };
2949
2950 /* When using the index (and thus not using psymtabs), each CU has an
2951    object of this type.  This is used to hold information needed by
2952    the various "quick" methods.  */
2953 struct dwarf2_per_cu_quick_data
2954 {
2955   /* The file table.  This can be NULL if there was no file table
2956      or it's currently not read in.
2957      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2958   struct quick_file_names *file_names;
2959
2960   /* The corresponding symbol table.  This is NULL if symbols for this
2961      CU have not yet been read.  */
2962   struct compunit_symtab *compunit_symtab;
2963
2964   /* A temporary mark bit used when iterating over all CUs in
2965      expand_symtabs_matching.  */
2966   unsigned int mark : 1;
2967
2968   /* True if we've tried to read the file table and found there isn't one.
2969      There will be no point in trying to read it again next time.  */
2970   unsigned int no_file_data : 1;
2971 };
2972
2973 /* Utility hash function for a stmt_list_hash.  */
2974
2975 static hashval_t
2976 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2977 {
2978   hashval_t v = 0;
2979
2980   if (stmt_list_hash->dwo_unit != NULL)
2981     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2982   v += to_underlying (stmt_list_hash->line_sect_off);
2983   return v;
2984 }
2985
2986 /* Utility equality function for a stmt_list_hash.  */
2987
2988 static int
2989 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2990                     const struct stmt_list_hash *rhs)
2991 {
2992   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2993     return 0;
2994   if (lhs->dwo_unit != NULL
2995       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2996     return 0;
2997
2998   return lhs->line_sect_off == rhs->line_sect_off;
2999 }
3000
3001 /* Hash function for a quick_file_names.  */
3002
3003 static hashval_t
3004 hash_file_name_entry (const void *e)
3005 {
3006   const struct quick_file_names *file_data
3007     = (const struct quick_file_names *) e;
3008
3009   return hash_stmt_list_entry (&file_data->hash);
3010 }
3011
3012 /* Equality function for a quick_file_names.  */
3013
3014 static int
3015 eq_file_name_entry (const void *a, const void *b)
3016 {
3017   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3018   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3019
3020   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3021 }
3022
3023 /* Delete function for a quick_file_names.  */
3024
3025 static void
3026 delete_file_name_entry (void *e)
3027 {
3028   struct quick_file_names *file_data = (struct quick_file_names *) e;
3029   int i;
3030
3031   for (i = 0; i < file_data->num_file_names; ++i)
3032     {
3033       xfree ((void*) file_data->file_names[i]);
3034       if (file_data->real_names)
3035         xfree ((void*) file_data->real_names[i]);
3036     }
3037
3038   /* The space for the struct itself lives on objfile_obstack,
3039      so we don't free it here.  */
3040 }
3041
3042 /* Create a quick_file_names hash table.  */
3043
3044 static htab_t
3045 create_quick_file_names_table (unsigned int nr_initial_entries)
3046 {
3047   return htab_create_alloc (nr_initial_entries,
3048                             hash_file_name_entry, eq_file_name_entry,
3049                             delete_file_name_entry, xcalloc, xfree);
3050 }
3051
3052 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3053    have to be created afterwards.  You should call age_cached_comp_units after
3054    processing PER_CU->CU.  dw2_setup must have been already called.  */
3055
3056 static void
3057 load_cu (struct dwarf2_per_cu_data *per_cu)
3058 {
3059   if (per_cu->is_debug_types)
3060     load_full_type_unit (per_cu);
3061   else
3062     load_full_comp_unit (per_cu, language_minimal);
3063
3064   if (per_cu->cu == NULL)
3065     return;  /* Dummy CU.  */
3066
3067   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3068 }
3069
3070 /* Read in the symbols for PER_CU.  */
3071
3072 static void
3073 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3074 {
3075   struct cleanup *back_to;
3076
3077   /* Skip type_unit_groups, reading the type units they contain
3078      is handled elsewhere.  */
3079   if (IS_TYPE_UNIT_GROUP (per_cu))
3080     return;
3081
3082   back_to = make_cleanup (dwarf2_release_queue, NULL);
3083
3084   if (dwarf2_per_objfile->using_index
3085       ? per_cu->v.quick->compunit_symtab == NULL
3086       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3087     {
3088       queue_comp_unit (per_cu, language_minimal);
3089       load_cu (per_cu);
3090
3091       /* If we just loaded a CU from a DWO, and we're working with an index
3092          that may badly handle TUs, load all the TUs in that DWO as well.
3093          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3094       if (!per_cu->is_debug_types
3095           && per_cu->cu != NULL
3096           && per_cu->cu->dwo_unit != NULL
3097           && dwarf2_per_objfile->index_table != NULL
3098           && dwarf2_per_objfile->index_table->version <= 7
3099           /* DWP files aren't supported yet.  */
3100           && get_dwp_file () == NULL)
3101         queue_and_load_all_dwo_tus (per_cu);
3102     }
3103
3104   process_queue ();
3105
3106   /* Age the cache, releasing compilation units that have not
3107      been used recently.  */
3108   age_cached_comp_units ();
3109
3110   do_cleanups (back_to);
3111 }
3112
3113 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3114    the objfile from which this CU came.  Returns the resulting symbol
3115    table.  */
3116
3117 static struct compunit_symtab *
3118 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3119 {
3120   gdb_assert (dwarf2_per_objfile->using_index);
3121   if (!per_cu->v.quick->compunit_symtab)
3122     {
3123       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
3124       scoped_restore decrementer = increment_reading_symtab ();
3125       dw2_do_instantiate_symtab (per_cu);
3126       process_cu_includes ();
3127       do_cleanups (back_to);
3128     }
3129
3130   return per_cu->v.quick->compunit_symtab;
3131 }
3132
3133 /* Return the CU/TU given its index.
3134
3135    This is intended for loops like:
3136
3137    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3138                     + dwarf2_per_objfile->n_type_units); ++i)
3139      {
3140        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3141
3142        ...;
3143      }
3144 */
3145
3146 static struct dwarf2_per_cu_data *
3147 dw2_get_cutu (int index)
3148 {
3149   if (index >= dwarf2_per_objfile->n_comp_units)
3150     {
3151       index -= dwarf2_per_objfile->n_comp_units;
3152       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3153       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3154     }
3155
3156   return dwarf2_per_objfile->all_comp_units[index];
3157 }
3158
3159 /* Return the CU given its index.
3160    This differs from dw2_get_cutu in that it's for when you know INDEX
3161    refers to a CU.  */
3162
3163 static struct dwarf2_per_cu_data *
3164 dw2_get_cu (int index)
3165 {
3166   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3167
3168   return dwarf2_per_objfile->all_comp_units[index];
3169 }
3170
3171 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3172    objfile_obstack, and constructed with the specified field
3173    values.  */
3174
3175 static dwarf2_per_cu_data *
3176 create_cu_from_index_list (struct objfile *objfile,
3177                           struct dwarf2_section_info *section,
3178                           int is_dwz,
3179                           sect_offset sect_off, ULONGEST length)
3180 {
3181   dwarf2_per_cu_data *the_cu
3182     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3183                      struct dwarf2_per_cu_data);
3184   the_cu->sect_off = sect_off;
3185   the_cu->length = length;
3186   the_cu->objfile = objfile;
3187   the_cu->section = section;
3188   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3189                                    struct dwarf2_per_cu_quick_data);
3190   the_cu->is_dwz = is_dwz;
3191   return the_cu;
3192 }
3193
3194 /* A helper for create_cus_from_index that handles a given list of
3195    CUs.  */
3196
3197 static void
3198 create_cus_from_index_list (struct objfile *objfile,
3199                             const gdb_byte *cu_list, offset_type n_elements,
3200                             struct dwarf2_section_info *section,
3201                             int is_dwz,
3202                             int base_offset)
3203 {
3204   offset_type i;
3205
3206   for (i = 0; i < n_elements; i += 2)
3207     {
3208       gdb_static_assert (sizeof (ULONGEST) >= 8);
3209
3210       sect_offset sect_off
3211         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3212       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3213       cu_list += 2 * 8;
3214
3215       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3216         = create_cu_from_index_list (objfile, section, is_dwz, sect_off, length);
3217     }
3218 }
3219
3220 /* Read the CU list from the mapped index, and use it to create all
3221    the CU objects for this objfile.  */
3222
3223 static void
3224 create_cus_from_index (struct objfile *objfile,
3225                        const gdb_byte *cu_list, offset_type cu_list_elements,
3226                        const gdb_byte *dwz_list, offset_type dwz_elements)
3227 {
3228   struct dwz_file *dwz;
3229
3230   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3231   dwarf2_per_objfile->all_comp_units =
3232     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3233                dwarf2_per_objfile->n_comp_units);
3234
3235   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3236                               &dwarf2_per_objfile->info, 0, 0);
3237
3238   if (dwz_elements == 0)
3239     return;
3240
3241   dwz = dwarf2_get_dwz_file ();
3242   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3243                               cu_list_elements / 2);
3244 }
3245
3246 /* Create the signatured type hash table from the index.  */
3247
3248 static void
3249 create_signatured_type_table_from_index (struct objfile *objfile,
3250                                          struct dwarf2_section_info *section,
3251                                          const gdb_byte *bytes,
3252                                          offset_type elements)
3253 {
3254   offset_type i;
3255   htab_t sig_types_hash;
3256
3257   dwarf2_per_objfile->n_type_units
3258     = dwarf2_per_objfile->n_allocated_type_units
3259     = elements / 3;
3260   dwarf2_per_objfile->all_type_units =
3261     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3262
3263   sig_types_hash = allocate_signatured_type_table (objfile);
3264
3265   for (i = 0; i < elements; i += 3)
3266     {
3267       struct signatured_type *sig_type;
3268       ULONGEST signature;
3269       void **slot;
3270       cu_offset type_offset_in_tu;
3271
3272       gdb_static_assert (sizeof (ULONGEST) >= 8);
3273       sect_offset sect_off
3274         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3275       type_offset_in_tu
3276         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3277                                                 BFD_ENDIAN_LITTLE);
3278       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3279       bytes += 3 * 8;
3280
3281       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3282                                  struct signatured_type);
3283       sig_type->signature = signature;
3284       sig_type->type_offset_in_tu = type_offset_in_tu;
3285       sig_type->per_cu.is_debug_types = 1;
3286       sig_type->per_cu.section = section;
3287       sig_type->per_cu.sect_off = sect_off;
3288       sig_type->per_cu.objfile = objfile;
3289       sig_type->per_cu.v.quick
3290         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3291                           struct dwarf2_per_cu_quick_data);
3292
3293       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3294       *slot = sig_type;
3295
3296       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3297     }
3298
3299   dwarf2_per_objfile->signatured_types = sig_types_hash;
3300 }
3301
3302 /* Create the signatured type hash table from .debug_names.  */
3303
3304 static void
3305 create_signatured_type_table_from_debug_names
3306   (struct objfile *objfile,
3307    const mapped_debug_names &map,
3308    struct dwarf2_section_info *section,
3309    struct dwarf2_section_info *abbrev_section)
3310 {
3311   dwarf2_read_section (objfile, section);
3312   dwarf2_read_section (objfile, abbrev_section);
3313
3314   dwarf2_per_objfile->n_type_units
3315     = dwarf2_per_objfile->n_allocated_type_units
3316     = map.tu_count;
3317   dwarf2_per_objfile->all_type_units
3318     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3319
3320   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3321
3322   for (uint32_t i = 0; i < map.tu_count; ++i)
3323     {
3324       struct signatured_type *sig_type;
3325       ULONGEST signature;
3326       void **slot;
3327       cu_offset type_offset_in_tu;
3328
3329       sect_offset sect_off
3330         = (sect_offset) (extract_unsigned_integer
3331                          (map.tu_table_reordered + i * map.offset_size,
3332                           map.offset_size,
3333                           map.dwarf5_byte_order));
3334
3335       comp_unit_head cu_header;
3336       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
3337                                      section->buffer + to_underlying (sect_off),
3338                                      rcuh_kind::TYPE);
3339
3340       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3341                                  struct signatured_type);
3342       sig_type->signature = cu_header.signature;
3343       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3344       sig_type->per_cu.is_debug_types = 1;
3345       sig_type->per_cu.section = section;
3346       sig_type->per_cu.sect_off = sect_off;
3347       sig_type->per_cu.objfile = objfile;
3348       sig_type->per_cu.v.quick
3349         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3350                           struct dwarf2_per_cu_quick_data);
3351
3352       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3353       *slot = sig_type;
3354
3355       dwarf2_per_objfile->all_type_units[i] = sig_type;
3356     }
3357
3358   dwarf2_per_objfile->signatured_types = sig_types_hash;
3359 }
3360
3361 /* Read the address map data from the mapped index, and use it to
3362    populate the objfile's psymtabs_addrmap.  */
3363
3364 static void
3365 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3366 {
3367   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3368   const gdb_byte *iter, *end;
3369   struct addrmap *mutable_map;
3370   CORE_ADDR baseaddr;
3371
3372   auto_obstack temp_obstack;
3373
3374   mutable_map = addrmap_create_mutable (&temp_obstack);
3375
3376   iter = index->address_table.data ();
3377   end = iter + index->address_table.size ();
3378
3379   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3380
3381   while (iter < end)
3382     {
3383       ULONGEST hi, lo, cu_index;
3384       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3385       iter += 8;
3386       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3387       iter += 8;
3388       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3389       iter += 4;
3390
3391       if (lo > hi)
3392         {
3393           complaint (&symfile_complaints,
3394                      _(".gdb_index address table has invalid range (%s - %s)"),
3395                      hex_string (lo), hex_string (hi));
3396           continue;
3397         }
3398
3399       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3400         {
3401           complaint (&symfile_complaints,
3402                      _(".gdb_index address table has invalid CU number %u"),
3403                      (unsigned) cu_index);
3404           continue;
3405         }
3406
3407       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3408       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3409       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3410     }
3411
3412   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3413                                                     &objfile->objfile_obstack);
3414 }
3415
3416 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3417    populate the objfile's psymtabs_addrmap.  */
3418
3419 static void
3420 create_addrmap_from_aranges (struct objfile *objfile,
3421                              struct dwarf2_section_info *section)
3422 {
3423   bfd *abfd = objfile->obfd;
3424   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3425   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3426                                        SECT_OFF_TEXT (objfile));
3427
3428   auto_obstack temp_obstack;
3429   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3430
3431   std::unordered_map<sect_offset,
3432                      dwarf2_per_cu_data *,
3433                      gdb::hash_enum<sect_offset>>
3434     debug_info_offset_to_per_cu;
3435   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3436     {
3437       dwarf2_per_cu_data *per_cu = dw2_get_cutu (cui);
3438       const auto insertpair
3439         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3440       if (!insertpair.second)
3441         {
3442           warning (_("Section .debug_aranges in %s has duplicate "
3443                      "debug_info_offset %u, ignoring .debug_aranges."),
3444                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3445           return;
3446         }
3447     }
3448
3449   dwarf2_read_section (objfile, section);
3450
3451   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3452
3453   const gdb_byte *addr = section->buffer;
3454
3455   while (addr < section->buffer + section->size)
3456     {
3457       const gdb_byte *const entry_addr = addr;
3458       unsigned int bytes_read;
3459
3460       const LONGEST entry_length = read_initial_length (abfd, addr,
3461                                                         &bytes_read);
3462       addr += bytes_read;
3463
3464       const gdb_byte *const entry_end = addr + entry_length;
3465       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3466       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3467       if (addr + entry_length > section->buffer + section->size)
3468         {
3469           warning (_("Section .debug_aranges in %s entry at offset %zu "
3470                      "length %s exceeds section length %s, "
3471                      "ignoring .debug_aranges."),
3472                    objfile_name (objfile), entry_addr - section->buffer,
3473                    plongest (bytes_read + entry_length),
3474                    pulongest (section->size));
3475           return;
3476         }
3477
3478       /* The version number.  */
3479       const uint16_t version = read_2_bytes (abfd, addr);
3480       addr += 2;
3481       if (version != 2)
3482         {
3483           warning (_("Section .debug_aranges in %s entry at offset %zu "
3484                      "has unsupported version %d, ignoring .debug_aranges."),
3485                    objfile_name (objfile), entry_addr - section->buffer,
3486                    version);
3487           return;
3488         }
3489
3490       const uint64_t debug_info_offset
3491         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3492       addr += offset_size;
3493       const auto per_cu_it
3494         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3495       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3496         {
3497           warning (_("Section .debug_aranges in %s entry at offset %zu "
3498                      "debug_info_offset %s does not exists, "
3499                      "ignoring .debug_aranges."),
3500                    objfile_name (objfile), entry_addr - section->buffer,
3501                    pulongest (debug_info_offset));
3502           return;
3503         }
3504       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3505
3506       const uint8_t address_size = *addr++;
3507       if (address_size < 1 || address_size > 8)
3508         {
3509           warning (_("Section .debug_aranges in %s entry at offset %zu "
3510                      "address_size %u is invalid, ignoring .debug_aranges."),
3511                    objfile_name (objfile), entry_addr - section->buffer,
3512                    address_size);
3513           return;
3514         }
3515
3516       const uint8_t segment_selector_size = *addr++;
3517       if (segment_selector_size != 0)
3518         {
3519           warning (_("Section .debug_aranges in %s entry at offset %zu "
3520                      "segment_selector_size %u is not supported, "
3521                      "ignoring .debug_aranges."),
3522                    objfile_name (objfile), entry_addr - section->buffer,
3523                    segment_selector_size);
3524           return;
3525         }
3526
3527       /* Must pad to an alignment boundary that is twice the address
3528          size.  It is undocumented by the DWARF standard but GCC does
3529          use it.  */
3530       for (size_t padding = ((-(addr - section->buffer))
3531                              & (2 * address_size - 1));
3532            padding > 0; padding--)
3533         if (*addr++ != 0)
3534           {
3535             warning (_("Section .debug_aranges in %s entry at offset %zu "
3536                        "padding is not zero, ignoring .debug_aranges."),
3537                      objfile_name (objfile), entry_addr - section->buffer);
3538             return;
3539           }
3540
3541       for (;;)
3542         {
3543           if (addr + 2 * address_size > entry_end)
3544             {
3545               warning (_("Section .debug_aranges in %s entry at offset %zu "
3546                          "address list is not properly terminated, "
3547                          "ignoring .debug_aranges."),
3548                        objfile_name (objfile), entry_addr - section->buffer);
3549               return;
3550             }
3551           ULONGEST start = extract_unsigned_integer (addr, address_size,
3552                                                      dwarf5_byte_order);
3553           addr += address_size;
3554           ULONGEST length = extract_unsigned_integer (addr, address_size,
3555                                                       dwarf5_byte_order);
3556           addr += address_size;
3557           if (start == 0 && length == 0)
3558             break;
3559           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3560             {
3561               /* Symbol was eliminated due to a COMDAT group.  */
3562               continue;
3563             }
3564           ULONGEST end = start + length;
3565           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3566           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3567           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3568         }
3569     }
3570
3571   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3572                                                     &objfile->objfile_obstack);
3573 }
3574
3575 /* The hash function for strings in the mapped index.  This is the same as
3576    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3577    implementation.  This is necessary because the hash function is tied to the
3578    format of the mapped index file.  The hash values do not have to match with
3579    SYMBOL_HASH_NEXT.
3580    
3581    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3582
3583 static hashval_t
3584 mapped_index_string_hash (int index_version, const void *p)
3585 {
3586   const unsigned char *str = (const unsigned char *) p;
3587   hashval_t r = 0;
3588   unsigned char c;
3589
3590   while ((c = *str++) != 0)
3591     {
3592       if (index_version >= 5)
3593         c = tolower (c);
3594       r = r * 67 + c - 113;
3595     }
3596
3597   return r;
3598 }
3599
3600 /* Find a slot in the mapped index INDEX for the object named NAME.
3601    If NAME is found, set *VEC_OUT to point to the CU vector in the
3602    constant pool and return true.  If NAME cannot be found, return
3603    false.  */
3604
3605 static bool
3606 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3607                           offset_type **vec_out)
3608 {
3609   offset_type hash;
3610   offset_type slot, step;
3611   int (*cmp) (const char *, const char *);
3612
3613   gdb::unique_xmalloc_ptr<char> without_params;
3614   if (current_language->la_language == language_cplus
3615       || current_language->la_language == language_fortran
3616       || current_language->la_language == language_d)
3617     {
3618       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3619          not contain any.  */
3620
3621       if (strchr (name, '(') != NULL)
3622         {
3623           without_params = cp_remove_params (name);
3624
3625           if (without_params != NULL)
3626             name = without_params.get ();
3627         }
3628     }
3629
3630   /* Index version 4 did not support case insensitive searches.  But the
3631      indices for case insensitive languages are built in lowercase, therefore
3632      simulate our NAME being searched is also lowercased.  */
3633   hash = mapped_index_string_hash ((index->version == 4
3634                                     && case_sensitivity == case_sensitive_off
3635                                     ? 5 : index->version),
3636                                    name);
3637
3638   slot = hash & (index->symbol_table.size () - 1);
3639   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3640   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3641
3642   for (;;)
3643     {
3644       const char *str;
3645
3646       const auto &bucket = index->symbol_table[slot];
3647       if (bucket.name == 0 && bucket.vec == 0)
3648         return false;
3649
3650       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3651       if (!cmp (name, str))
3652         {
3653           *vec_out = (offset_type *) (index->constant_pool
3654                                       + MAYBE_SWAP (bucket.vec));
3655           return true;
3656         }
3657
3658       slot = (slot + step) & (index->symbol_table.size () - 1);
3659     }
3660 }
3661
3662 /* A helper function that reads the .gdb_index from SECTION and fills
3663    in MAP.  FILENAME is the name of the file containing the section;
3664    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3665    ok to use deprecated sections.
3666
3667    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3668    out parameters that are filled in with information about the CU and
3669    TU lists in the section.
3670
3671    Returns 1 if all went well, 0 otherwise.  */
3672
3673 static int
3674 read_index_from_section (struct objfile *objfile,
3675                          const char *filename,
3676                          int deprecated_ok,
3677                          struct dwarf2_section_info *section,
3678                          struct mapped_index *map,
3679                          const gdb_byte **cu_list,
3680                          offset_type *cu_list_elements,
3681                          const gdb_byte **types_list,
3682                          offset_type *types_list_elements)
3683 {
3684   const gdb_byte *addr;
3685   offset_type version;
3686   offset_type *metadata;
3687   int i;
3688
3689   if (dwarf2_section_empty_p (section))
3690     return 0;
3691
3692   /* Older elfutils strip versions could keep the section in the main
3693      executable while splitting it for the separate debug info file.  */
3694   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3695     return 0;
3696
3697   dwarf2_read_section (objfile, section);
3698
3699   addr = section->buffer;
3700   /* Version check.  */
3701   version = MAYBE_SWAP (*(offset_type *) addr);
3702   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3703      causes the index to behave very poorly for certain requests.  Version 3
3704      contained incomplete addrmap.  So, it seems better to just ignore such
3705      indices.  */
3706   if (version < 4)
3707     {
3708       static int warning_printed = 0;
3709       if (!warning_printed)
3710         {
3711           warning (_("Skipping obsolete .gdb_index section in %s."),
3712                    filename);
3713           warning_printed = 1;
3714         }
3715       return 0;
3716     }
3717   /* Index version 4 uses a different hash function than index version
3718      5 and later.
3719
3720      Versions earlier than 6 did not emit psymbols for inlined
3721      functions.  Using these files will cause GDB not to be able to
3722      set breakpoints on inlined functions by name, so we ignore these
3723      indices unless the user has done
3724      "set use-deprecated-index-sections on".  */
3725   if (version < 6 && !deprecated_ok)
3726     {
3727       static int warning_printed = 0;
3728       if (!warning_printed)
3729         {
3730           warning (_("\
3731 Skipping deprecated .gdb_index section in %s.\n\
3732 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3733 to use the section anyway."),
3734                    filename);
3735           warning_printed = 1;
3736         }
3737       return 0;
3738     }
3739   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3740      of the TU (for symbols coming from TUs),
3741      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3742      Plus gold-generated indices can have duplicate entries for global symbols,
3743      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3744      These are just performance bugs, and we can't distinguish gdb-generated
3745      indices from gold-generated ones, so issue no warning here.  */
3746
3747   /* Indexes with higher version than the one supported by GDB may be no
3748      longer backward compatible.  */
3749   if (version > 8)
3750     return 0;
3751
3752   map->version = version;
3753   map->total_size = section->size;
3754
3755   metadata = (offset_type *) (addr + sizeof (offset_type));
3756
3757   i = 0;
3758   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3759   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3760                        / 8);
3761   ++i;
3762
3763   *types_list = addr + MAYBE_SWAP (metadata[i]);
3764   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3765                            - MAYBE_SWAP (metadata[i]))
3766                           / 8);
3767   ++i;
3768
3769   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3770   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3771   map->address_table
3772     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3773   ++i;
3774
3775   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3776   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3777   map->symbol_table
3778     = gdb::array_view<mapped_index::symbol_table_slot>
3779        ((mapped_index::symbol_table_slot *) symbol_table,
3780         (mapped_index::symbol_table_slot *) symbol_table_end);
3781
3782   ++i;
3783   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3784
3785   return 1;
3786 }
3787
3788 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3789    elements of all the CUs and return 1.  Otherwise, return 0.  */
3790
3791 static int
3792 dwarf2_read_index (struct objfile *objfile)
3793 {
3794   struct mapped_index local_map, *map;
3795   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3796   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3797   struct dwz_file *dwz;
3798
3799   if (!read_index_from_section (objfile, objfile_name (objfile),
3800                                 use_deprecated_index_sections,
3801                                 &dwarf2_per_objfile->gdb_index, &local_map,
3802                                 &cu_list, &cu_list_elements,
3803                                 &types_list, &types_list_elements))
3804     return 0;
3805
3806   /* Don't use the index if it's empty.  */
3807   if (local_map.symbol_table.empty ())
3808     return 0;
3809
3810   /* If there is a .dwz file, read it so we can get its CU list as
3811      well.  */
3812   dwz = dwarf2_get_dwz_file ();
3813   if (dwz != NULL)
3814     {
3815       struct mapped_index dwz_map;
3816       const gdb_byte *dwz_types_ignore;
3817       offset_type dwz_types_elements_ignore;
3818
3819       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3820                                     1,
3821                                     &dwz->gdb_index, &dwz_map,
3822                                     &dwz_list, &dwz_list_elements,
3823                                     &dwz_types_ignore,
3824                                     &dwz_types_elements_ignore))
3825         {
3826           warning (_("could not read '.gdb_index' section from %s; skipping"),
3827                    bfd_get_filename (dwz->dwz_bfd));
3828           return 0;
3829         }
3830     }
3831
3832   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3833                          dwz_list_elements);
3834
3835   if (types_list_elements)
3836     {
3837       struct dwarf2_section_info *section;
3838
3839       /* We can only handle a single .debug_types when we have an
3840          index.  */
3841       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3842         return 0;
3843
3844       section = VEC_index (dwarf2_section_info_def,
3845                            dwarf2_per_objfile->types, 0);
3846
3847       create_signatured_type_table_from_index (objfile, section, types_list,
3848                                                types_list_elements);
3849     }
3850
3851   create_addrmap_from_index (objfile, &local_map);
3852
3853   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3854   map = new (map) mapped_index ();
3855   *map = local_map;
3856
3857   dwarf2_per_objfile->index_table = map;
3858   dwarf2_per_objfile->using_index = 1;
3859   dwarf2_per_objfile->quick_file_names_table =
3860     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3861
3862   return 1;
3863 }
3864
3865 /* A helper for the "quick" functions which sets the global
3866    dwarf2_per_objfile according to OBJFILE.  */
3867
3868 static void
3869 dw2_setup (struct objfile *objfile)
3870 {
3871   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3872                         objfile_data (objfile, dwarf2_objfile_data_key));
3873   gdb_assert (dwarf2_per_objfile);
3874 }
3875
3876 /* die_reader_func for dw2_get_file_names.  */
3877
3878 static void
3879 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3880                            const gdb_byte *info_ptr,
3881                            struct die_info *comp_unit_die,
3882                            int has_children,
3883                            void *data)
3884 {
3885   struct dwarf2_cu *cu = reader->cu;
3886   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3887   struct objfile *objfile = dwarf2_per_objfile->objfile;
3888   struct dwarf2_per_cu_data *lh_cu;
3889   struct attribute *attr;
3890   int i;
3891   void **slot;
3892   struct quick_file_names *qfn;
3893
3894   gdb_assert (! this_cu->is_debug_types);
3895
3896   /* Our callers never want to match partial units -- instead they
3897      will match the enclosing full CU.  */
3898   if (comp_unit_die->tag == DW_TAG_partial_unit)
3899     {
3900       this_cu->v.quick->no_file_data = 1;
3901       return;
3902     }
3903
3904   lh_cu = this_cu;
3905   slot = NULL;
3906
3907   line_header_up lh;
3908   sect_offset line_offset {};
3909
3910   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3911   if (attr)
3912     {
3913       struct quick_file_names find_entry;
3914
3915       line_offset = (sect_offset) DW_UNSND (attr);
3916
3917       /* We may have already read in this line header (TU line header sharing).
3918          If we have we're done.  */
3919       find_entry.hash.dwo_unit = cu->dwo_unit;
3920       find_entry.hash.line_sect_off = line_offset;
3921       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3922                              &find_entry, INSERT);
3923       if (*slot != NULL)
3924         {
3925           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3926           return;
3927         }
3928
3929       lh = dwarf_decode_line_header (line_offset, cu);
3930     }
3931   if (lh == NULL)
3932     {
3933       lh_cu->v.quick->no_file_data = 1;
3934       return;
3935     }
3936
3937   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3938   qfn->hash.dwo_unit = cu->dwo_unit;
3939   qfn->hash.line_sect_off = line_offset;
3940   gdb_assert (slot != NULL);
3941   *slot = qfn;
3942
3943   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3944
3945   qfn->num_file_names = lh->file_names.size ();
3946   qfn->file_names =
3947     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3948   for (i = 0; i < lh->file_names.size (); ++i)
3949     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3950   qfn->real_names = NULL;
3951
3952   lh_cu->v.quick->file_names = qfn;
3953 }
3954
3955 /* A helper for the "quick" functions which attempts to read the line
3956    table for THIS_CU.  */
3957
3958 static struct quick_file_names *
3959 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3960 {
3961   /* This should never be called for TUs.  */
3962   gdb_assert (! this_cu->is_debug_types);
3963   /* Nor type unit groups.  */
3964   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3965
3966   if (this_cu->v.quick->file_names != NULL)
3967     return this_cu->v.quick->file_names;
3968   /* If we know there is no line data, no point in looking again.  */
3969   if (this_cu->v.quick->no_file_data)
3970     return NULL;
3971
3972   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3973
3974   if (this_cu->v.quick->no_file_data)
3975     return NULL;
3976   return this_cu->v.quick->file_names;
3977 }
3978
3979 /* A helper for the "quick" functions which computes and caches the
3980    real path for a given file name from the line table.  */
3981
3982 static const char *
3983 dw2_get_real_path (struct objfile *objfile,
3984                    struct quick_file_names *qfn, int index)
3985 {
3986   if (qfn->real_names == NULL)
3987     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3988                                       qfn->num_file_names, const char *);
3989
3990   if (qfn->real_names[index] == NULL)
3991     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3992
3993   return qfn->real_names[index];
3994 }
3995
3996 static struct symtab *
3997 dw2_find_last_source_symtab (struct objfile *objfile)
3998 {
3999   struct compunit_symtab *cust;
4000   int index;
4001
4002   dw2_setup (objfile);
4003   index = dwarf2_per_objfile->n_comp_units - 1;
4004   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
4005   if (cust == NULL)
4006     return NULL;
4007   return compunit_primary_filetab (cust);
4008 }
4009
4010 /* Traversal function for dw2_forget_cached_source_info.  */
4011
4012 static int
4013 dw2_free_cached_file_names (void **slot, void *info)
4014 {
4015   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4016
4017   if (file_data->real_names)
4018     {
4019       int i;
4020
4021       for (i = 0; i < file_data->num_file_names; ++i)
4022         {
4023           xfree ((void*) file_data->real_names[i]);
4024           file_data->real_names[i] = NULL;
4025         }
4026     }
4027
4028   return 1;
4029 }
4030
4031 static void
4032 dw2_forget_cached_source_info (struct objfile *objfile)
4033 {
4034   dw2_setup (objfile);
4035
4036   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4037                           dw2_free_cached_file_names, NULL);
4038 }
4039
4040 /* Helper function for dw2_map_symtabs_matching_filename that expands
4041    the symtabs and calls the iterator.  */
4042
4043 static int
4044 dw2_map_expand_apply (struct objfile *objfile,
4045                       struct dwarf2_per_cu_data *per_cu,
4046                       const char *name, const char *real_path,
4047                       gdb::function_view<bool (symtab *)> callback)
4048 {
4049   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4050
4051   /* Don't visit already-expanded CUs.  */
4052   if (per_cu->v.quick->compunit_symtab)
4053     return 0;
4054
4055   /* This may expand more than one symtab, and we want to iterate over
4056      all of them.  */
4057   dw2_instantiate_symtab (per_cu);
4058
4059   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4060                                     last_made, callback);
4061 }
4062
4063 /* Implementation of the map_symtabs_matching_filename method.  */
4064
4065 static bool
4066 dw2_map_symtabs_matching_filename
4067   (struct objfile *objfile, const char *name, const char *real_path,
4068    gdb::function_view<bool (symtab *)> callback)
4069 {
4070   int i;
4071   const char *name_basename = lbasename (name);
4072
4073   dw2_setup (objfile);
4074
4075   /* The rule is CUs specify all the files, including those used by
4076      any TU, so there's no need to scan TUs here.  */
4077
4078   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4079     {
4080       int j;
4081       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4082       struct quick_file_names *file_data;
4083
4084       /* We only need to look at symtabs not already expanded.  */
4085       if (per_cu->v.quick->compunit_symtab)
4086         continue;
4087
4088       file_data = dw2_get_file_names (per_cu);
4089       if (file_data == NULL)
4090         continue;
4091
4092       for (j = 0; j < file_data->num_file_names; ++j)
4093         {
4094           const char *this_name = file_data->file_names[j];
4095           const char *this_real_name;
4096
4097           if (compare_filenames_for_search (this_name, name))
4098             {
4099               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4100                                         callback))
4101                 return true;
4102               continue;
4103             }
4104
4105           /* Before we invoke realpath, which can get expensive when many
4106              files are involved, do a quick comparison of the basenames.  */
4107           if (! basenames_may_differ
4108               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4109             continue;
4110
4111           this_real_name = dw2_get_real_path (objfile, file_data, j);
4112           if (compare_filenames_for_search (this_real_name, name))
4113             {
4114               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4115                                         callback))
4116                 return true;
4117               continue;
4118             }
4119
4120           if (real_path != NULL)
4121             {
4122               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4123               gdb_assert (IS_ABSOLUTE_PATH (name));
4124               if (this_real_name != NULL
4125                   && FILENAME_CMP (real_path, this_real_name) == 0)
4126                 {
4127                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4128                                             callback))
4129                     return true;
4130                   continue;
4131                 }
4132             }
4133         }
4134     }
4135
4136   return false;
4137 }
4138
4139 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4140
4141 struct dw2_symtab_iterator
4142 {
4143   /* The internalized form of .gdb_index.  */
4144   struct mapped_index *index;
4145   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4146   int want_specific_block;
4147   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4148      Unused if !WANT_SPECIFIC_BLOCK.  */
4149   int block_index;
4150   /* The kind of symbol we're looking for.  */
4151   domain_enum domain;
4152   /* The list of CUs from the index entry of the symbol,
4153      or NULL if not found.  */
4154   offset_type *vec;
4155   /* The next element in VEC to look at.  */
4156   int next;
4157   /* The number of elements in VEC, or zero if there is no match.  */
4158   int length;
4159   /* Have we seen a global version of the symbol?
4160      If so we can ignore all further global instances.
4161      This is to work around gold/15646, inefficient gold-generated
4162      indices.  */
4163   int global_seen;
4164 };
4165
4166 /* Initialize the index symtab iterator ITER.
4167    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4168    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4169
4170 static void
4171 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4172                       struct mapped_index *index,
4173                       int want_specific_block,
4174                       int block_index,
4175                       domain_enum domain,
4176                       const char *name)
4177 {
4178   iter->index = index;
4179   iter->want_specific_block = want_specific_block;
4180   iter->block_index = block_index;
4181   iter->domain = domain;
4182   iter->next = 0;
4183   iter->global_seen = 0;
4184
4185   if (find_slot_in_mapped_hash (index, name, &iter->vec))
4186     iter->length = MAYBE_SWAP (*iter->vec);
4187   else
4188     {
4189       iter->vec = NULL;
4190       iter->length = 0;
4191     }
4192 }
4193
4194 /* Return the next matching CU or NULL if there are no more.  */
4195
4196 static struct dwarf2_per_cu_data *
4197 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4198 {
4199   for ( ; iter->next < iter->length; ++iter->next)
4200     {
4201       offset_type cu_index_and_attrs =
4202         MAYBE_SWAP (iter->vec[iter->next + 1]);
4203       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4204       struct dwarf2_per_cu_data *per_cu;
4205       int want_static = iter->block_index != GLOBAL_BLOCK;
4206       /* This value is only valid for index versions >= 7.  */
4207       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4208       gdb_index_symbol_kind symbol_kind =
4209         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4210       /* Only check the symbol attributes if they're present.
4211          Indices prior to version 7 don't record them,
4212          and indices >= 7 may elide them for certain symbols
4213          (gold does this).  */
4214       int attrs_valid =
4215         (iter->index->version >= 7
4216          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4217
4218       /* Don't crash on bad data.  */
4219       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4220                        + dwarf2_per_objfile->n_type_units))
4221         {
4222           complaint (&symfile_complaints,
4223                      _(".gdb_index entry has bad CU index"
4224                        " [in module %s]"),
4225                      objfile_name (dwarf2_per_objfile->objfile));
4226           continue;
4227         }
4228
4229       per_cu = dw2_get_cutu (cu_index);
4230
4231       /* Skip if already read in.  */
4232       if (per_cu->v.quick->compunit_symtab)
4233         continue;
4234
4235       /* Check static vs global.  */
4236       if (attrs_valid)
4237         {
4238           if (iter->want_specific_block
4239               && want_static != is_static)
4240             continue;
4241           /* Work around gold/15646.  */
4242           if (!is_static && iter->global_seen)
4243             continue;
4244           if (!is_static)
4245             iter->global_seen = 1;
4246         }
4247
4248       /* Only check the symbol's kind if it has one.  */
4249       if (attrs_valid)
4250         {
4251           switch (iter->domain)
4252             {
4253             case VAR_DOMAIN:
4254               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4255                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4256                   /* Some types are also in VAR_DOMAIN.  */
4257                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4258                 continue;
4259               break;
4260             case STRUCT_DOMAIN:
4261               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4262                 continue;
4263               break;
4264             case LABEL_DOMAIN:
4265               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4266                 continue;
4267               break;
4268             default:
4269               break;
4270             }
4271         }
4272
4273       ++iter->next;
4274       return per_cu;
4275     }
4276
4277   return NULL;
4278 }
4279
4280 static struct compunit_symtab *
4281 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4282                    const char *name, domain_enum domain)
4283 {
4284   struct compunit_symtab *stab_best = NULL;
4285   struct mapped_index *index;
4286
4287   dw2_setup (objfile);
4288
4289   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4290
4291   index = dwarf2_per_objfile->index_table;
4292
4293   /* index is NULL if OBJF_READNOW.  */
4294   if (index)
4295     {
4296       struct dw2_symtab_iterator iter;
4297       struct dwarf2_per_cu_data *per_cu;
4298
4299       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
4300
4301       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4302         {
4303           struct symbol *sym, *with_opaque = NULL;
4304           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4305           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4306           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4307
4308           sym = block_find_symbol (block, name, domain,
4309                                    block_find_non_opaque_type_preferred,
4310                                    &with_opaque);
4311
4312           /* Some caution must be observed with overloaded functions
4313              and methods, since the index will not contain any overload
4314              information (but NAME might contain it).  */
4315
4316           if (sym != NULL
4317               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4318             return stab;
4319           if (with_opaque != NULL
4320               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4321             stab_best = stab;
4322
4323           /* Keep looking through other CUs.  */
4324         }
4325     }
4326
4327   return stab_best;
4328 }
4329
4330 static void
4331 dw2_print_stats (struct objfile *objfile)
4332 {
4333   int i, total, count;
4334
4335   dw2_setup (objfile);
4336   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4337   count = 0;
4338   for (i = 0; i < total; ++i)
4339     {
4340       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4341
4342       if (!per_cu->v.quick->compunit_symtab)
4343         ++count;
4344     }
4345   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4346   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4347 }
4348
4349 /* This dumps minimal information about the index.
4350    It is called via "mt print objfiles".
4351    One use is to verify .gdb_index has been loaded by the
4352    gdb.dwarf2/gdb-index.exp testcase.  */
4353
4354 static void
4355 dw2_dump (struct objfile *objfile)
4356 {
4357   dw2_setup (objfile);
4358   gdb_assert (dwarf2_per_objfile->using_index);
4359   printf_filtered (".gdb_index:");
4360   if (dwarf2_per_objfile->index_table != NULL)
4361     {
4362       printf_filtered (" version %d\n",
4363                        dwarf2_per_objfile->index_table->version);
4364     }
4365   else
4366     printf_filtered (" faked for \"readnow\"\n");
4367   printf_filtered ("\n");
4368 }
4369
4370 static void
4371 dw2_relocate (struct objfile *objfile,
4372               const struct section_offsets *new_offsets,
4373               const struct section_offsets *delta)
4374 {
4375   /* There's nothing to relocate here.  */
4376 }
4377
4378 static void
4379 dw2_expand_symtabs_for_function (struct objfile *objfile,
4380                                  const char *func_name)
4381 {
4382   struct mapped_index *index;
4383
4384   dw2_setup (objfile);
4385
4386   index = dwarf2_per_objfile->index_table;
4387
4388   /* index is NULL if OBJF_READNOW.  */
4389   if (index)
4390     {
4391       struct dw2_symtab_iterator iter;
4392       struct dwarf2_per_cu_data *per_cu;
4393
4394       /* Note: It doesn't matter what we pass for block_index here.  */
4395       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4396                             func_name);
4397
4398       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4399         dw2_instantiate_symtab (per_cu);
4400     }
4401 }
4402
4403 static void
4404 dw2_expand_all_symtabs (struct objfile *objfile)
4405 {
4406   int i;
4407
4408   dw2_setup (objfile);
4409
4410   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4411                    + dwarf2_per_objfile->n_type_units); ++i)
4412     {
4413       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4414
4415       dw2_instantiate_symtab (per_cu);
4416     }
4417 }
4418
4419 static void
4420 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4421                                   const char *fullname)
4422 {
4423   int i;
4424
4425   dw2_setup (objfile);
4426
4427   /* We don't need to consider type units here.
4428      This is only called for examining code, e.g. expand_line_sal.
4429      There can be an order of magnitude (or more) more type units
4430      than comp units, and we avoid them if we can.  */
4431
4432   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4433     {
4434       int j;
4435       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4436       struct quick_file_names *file_data;
4437
4438       /* We only need to look at symtabs not already expanded.  */
4439       if (per_cu->v.quick->compunit_symtab)
4440         continue;
4441
4442       file_data = dw2_get_file_names (per_cu);
4443       if (file_data == NULL)
4444         continue;
4445
4446       for (j = 0; j < file_data->num_file_names; ++j)
4447         {
4448           const char *this_fullname = file_data->file_names[j];
4449
4450           if (filename_cmp (this_fullname, fullname) == 0)
4451             {
4452               dw2_instantiate_symtab (per_cu);
4453               break;
4454             }
4455         }
4456     }
4457 }
4458
4459 static void
4460 dw2_map_matching_symbols (struct objfile *objfile,
4461                           const char * name, domain_enum domain,
4462                           int global,
4463                           int (*callback) (struct block *,
4464                                            struct symbol *, void *),
4465                           void *data, symbol_name_match_type match,
4466                           symbol_compare_ftype *ordered_compare)
4467 {
4468   /* Currently unimplemented; used for Ada.  The function can be called if the
4469      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4470      does not look for non-Ada symbols this function should just return.  */
4471 }
4472
4473 /* Symbol name matcher for .gdb_index names.
4474
4475    Symbol names in .gdb_index have a few particularities:
4476
4477    - There's no indication of which is the language of each symbol.
4478
4479      Since each language has its own symbol name matching algorithm,
4480      and we don't know which language is the right one, we must match
4481      each symbol against all languages.  This would be a potential
4482      performance problem if it were not mitigated by the
4483      mapped_index::name_components lookup table, which significantly
4484      reduces the number of times we need to call into this matcher,
4485      making it a non-issue.
4486
4487    - Symbol names in the index have no overload (parameter)
4488      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4489      appear as "foo" in the index, for example.
4490
4491      This means that the lookup names passed to the symbol name
4492      matcher functions must have no parameter information either
4493      because (e.g.) symbol search name "foo" does not match
4494      lookup-name "foo(int)" [while swapping search name for lookup
4495      name would match].
4496 */
4497 class gdb_index_symbol_name_matcher
4498 {
4499 public:
4500   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4501   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4502
4503   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4504      Returns true if any matcher matches.  */
4505   bool matches (const char *symbol_name);
4506
4507 private:
4508   /* A reference to the lookup name we're matching against.  */
4509   const lookup_name_info &m_lookup_name;
4510
4511   /* A vector holding all the different symbol name matchers, for all
4512      languages.  */
4513   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4514 };
4515
4516 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4517   (const lookup_name_info &lookup_name)
4518     : m_lookup_name (lookup_name)
4519 {
4520   /* Prepare the vector of comparison functions upfront, to avoid
4521      doing the same work for each symbol.  Care is taken to avoid
4522      matching with the same matcher more than once if/when multiple
4523      languages use the same matcher function.  */
4524   auto &matchers = m_symbol_name_matcher_funcs;
4525   matchers.reserve (nr_languages);
4526
4527   matchers.push_back (default_symbol_name_matcher);
4528
4529   for (int i = 0; i < nr_languages; i++)
4530     {
4531       const language_defn *lang = language_def ((enum language) i);
4532       if (lang->la_get_symbol_name_matcher != NULL)
4533         {
4534           symbol_name_matcher_ftype *name_matcher
4535             = lang->la_get_symbol_name_matcher (m_lookup_name);
4536
4537           /* Don't insert the same comparison routine more than once.
4538              Note that we do this linear walk instead of a cheaper
4539              sorted insert, or use a std::set or something like that,
4540              because relative order of function addresses is not
4541              stable.  This is not a problem in practice because the
4542              number of supported languages is low, and the cost here
4543              is tiny compared to the number of searches we'll do
4544              afterwards using this object.  */
4545           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4546               == matchers.end ())
4547             matchers.push_back (name_matcher);
4548         }
4549     }
4550 }
4551
4552 bool
4553 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4554 {
4555   for (auto matches_name : m_symbol_name_matcher_funcs)
4556     if (matches_name (symbol_name, m_lookup_name, NULL))
4557       return true;
4558
4559   return false;
4560 }
4561
4562 /* Starting from a search name, return the string that finds the upper
4563    bound of all strings that start with SEARCH_NAME in a sorted name
4564    list.  Returns the empty string to indicate that the upper bound is
4565    the end of the list.  */
4566
4567 static std::string
4568 make_sort_after_prefix_name (const char *search_name)
4569 {
4570   /* When looking to complete "func", we find the upper bound of all
4571      symbols that start with "func" by looking for where we'd insert
4572      the closest string that would follow "func" in lexicographical
4573      order.  Usually, that's "func"-with-last-character-incremented,
4574      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4575      will be UTF-8 multi-byte sequences, but we can't be certain.
4576      Especially mind the 0xff character, which is a valid character in
4577      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4578      rule out compilers allowing it in identifiers.  Note that
4579      conveniently, strcmp/strcasecmp are specified to compare
4580      characters interpreted as unsigned char.  So what we do is treat
4581      the whole string as a base 256 number composed of a sequence of
4582      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4583      to 0, and carries 1 to the following more-significant position.
4584      If the very first character in SEARCH_NAME ends up incremented
4585      and carries/overflows, then the upper bound is the end of the
4586      list.  The string after the empty string is also the empty
4587      string.
4588
4589      Some examples of this operation:
4590
4591        SEARCH_NAME  => "+1" RESULT
4592
4593        "abc"              => "abd"
4594        "ab\xff"           => "ac"
4595        "\xff" "a" "\xff"  => "\xff" "b"
4596        "\xff"             => ""
4597        "\xff\xff"         => ""
4598        ""                 => ""
4599
4600      Then, with these symbols for example:
4601
4602       func
4603       func1
4604       fund
4605
4606      completing "func" looks for symbols between "func" and
4607      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4608      which finds "func" and "func1", but not "fund".
4609
4610      And with:
4611
4612       funcÿ     (Latin1 'ÿ' [0xff])
4613       funcÿ1
4614       fund
4615
4616      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4617      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4618
4619      And with:
4620
4621       ÿÿ        (Latin1 'ÿ' [0xff])
4622       ÿÿ1
4623
4624      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4625      the end of the list.
4626   */
4627   std::string after = search_name;
4628   while (!after.empty () && (unsigned char) after.back () == 0xff)
4629     after.pop_back ();
4630   if (!after.empty ())
4631     after.back () = (unsigned char) after.back () + 1;
4632   return after;
4633 }
4634
4635 /* See declaration.  */
4636
4637 std::pair<std::vector<name_component>::const_iterator,
4638           std::vector<name_component>::const_iterator>
4639 mapped_index_base::find_name_components_bounds
4640   (const lookup_name_info &lookup_name_without_params) const
4641 {
4642   auto *name_cmp
4643     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4644
4645   const char *cplus
4646     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4647
4648   /* Comparison function object for lower_bound that matches against a
4649      given symbol name.  */
4650   auto lookup_compare_lower = [&] (const name_component &elem,
4651                                    const char *name)
4652     {
4653       const char *elem_qualified = this->symbol_name_at (elem.idx);
4654       const char *elem_name = elem_qualified + elem.name_offset;
4655       return name_cmp (elem_name, name) < 0;
4656     };
4657
4658   /* Comparison function object for upper_bound that matches against a
4659      given symbol name.  */
4660   auto lookup_compare_upper = [&] (const char *name,
4661                                    const name_component &elem)
4662     {
4663       const char *elem_qualified = this->symbol_name_at (elem.idx);
4664       const char *elem_name = elem_qualified + elem.name_offset;
4665       return name_cmp (name, elem_name) < 0;
4666     };
4667
4668   auto begin = this->name_components.begin ();
4669   auto end = this->name_components.end ();
4670
4671   /* Find the lower bound.  */
4672   auto lower = [&] ()
4673     {
4674       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4675         return begin;
4676       else
4677         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4678     } ();
4679
4680   /* Find the upper bound.  */
4681   auto upper = [&] ()
4682     {
4683       if (lookup_name_without_params.completion_mode ())
4684         {
4685           /* In completion mode, we want UPPER to point past all
4686              symbols names that have the same prefix.  I.e., with
4687              these symbols, and completing "func":
4688
4689               function        << lower bound
4690               function1
4691               other_function  << upper bound
4692
4693              We find the upper bound by looking for the insertion
4694              point of "func"-with-last-character-incremented,
4695              i.e. "fund".  */
4696           std::string after = make_sort_after_prefix_name (cplus);
4697           if (after.empty ())
4698             return end;
4699           return std::lower_bound (lower, end, after.c_str (),
4700                                    lookup_compare_lower);
4701         }
4702       else
4703         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4704     } ();
4705
4706   return {lower, upper};
4707 }
4708
4709 /* See declaration.  */
4710
4711 void
4712 mapped_index_base::build_name_components ()
4713 {
4714   if (!this->name_components.empty ())
4715     return;
4716
4717   this->name_components_casing = case_sensitivity;
4718   auto *name_cmp
4719     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4720
4721   /* The code below only knows how to break apart components of C++
4722      symbol names (and other languages that use '::' as
4723      namespace/module separator).  If we add support for wild matching
4724      to some language that uses some other operator (E.g., Ada, Go and
4725      D use '.'), then we'll need to try splitting the symbol name
4726      according to that language too.  Note that Ada does support wild
4727      matching, but doesn't currently support .gdb_index.  */
4728   auto count = this->symbol_name_count ();
4729   for (offset_type idx = 0; idx < count; idx++)
4730     {
4731       if (this->symbol_name_slot_invalid (idx))
4732         continue;
4733
4734       const char *name = this->symbol_name_at (idx);
4735
4736       /* Add each name component to the name component table.  */
4737       unsigned int previous_len = 0;
4738       for (unsigned int current_len = cp_find_first_component (name);
4739            name[current_len] != '\0';
4740            current_len += cp_find_first_component (name + current_len))
4741         {
4742           gdb_assert (name[current_len] == ':');
4743           this->name_components.push_back ({previous_len, idx});
4744           /* Skip the '::'.  */
4745           current_len += 2;
4746           previous_len = current_len;
4747         }
4748       this->name_components.push_back ({previous_len, idx});
4749     }
4750
4751   /* Sort name_components elements by name.  */
4752   auto name_comp_compare = [&] (const name_component &left,
4753                                 const name_component &right)
4754     {
4755       const char *left_qualified = this->symbol_name_at (left.idx);
4756       const char *right_qualified = this->symbol_name_at (right.idx);
4757
4758       const char *left_name = left_qualified + left.name_offset;
4759       const char *right_name = right_qualified + right.name_offset;
4760
4761       return name_cmp (left_name, right_name) < 0;
4762     };
4763
4764   std::sort (this->name_components.begin (),
4765              this->name_components.end (),
4766              name_comp_compare);
4767 }
4768
4769 /* Helper for dw2_expand_symtabs_matching that works with a
4770    mapped_index_base instead of the containing objfile.  This is split
4771    to a separate function in order to be able to unit test the
4772    name_components matching using a mock mapped_index_base.  For each
4773    symbol name that matches, calls MATCH_CALLBACK, passing it the
4774    symbol's index in the mapped_index_base symbol table.  */
4775
4776 static void
4777 dw2_expand_symtabs_matching_symbol
4778   (mapped_index_base &index,
4779    const lookup_name_info &lookup_name_in,
4780    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4781    enum search_domain kind,
4782    gdb::function_view<void (offset_type)> match_callback)
4783 {
4784   lookup_name_info lookup_name_without_params
4785     = lookup_name_in.make_ignore_params ();
4786   gdb_index_symbol_name_matcher lookup_name_matcher
4787     (lookup_name_without_params);
4788
4789   /* Build the symbol name component sorted vector, if we haven't
4790      yet.  */
4791   index.build_name_components ();
4792
4793   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4794
4795   /* Now for each symbol name in range, check to see if we have a name
4796      match, and if so, call the MATCH_CALLBACK callback.  */
4797
4798   /* The same symbol may appear more than once in the range though.
4799      E.g., if we're looking for symbols that complete "w", and we have
4800      a symbol named "w1::w2", we'll find the two name components for
4801      that same symbol in the range.  To be sure we only call the
4802      callback once per symbol, we first collect the symbol name
4803      indexes that matched in a temporary vector and ignore
4804      duplicates.  */
4805   std::vector<offset_type> matches;
4806   matches.reserve (std::distance (bounds.first, bounds.second));
4807
4808   for (; bounds.first != bounds.second; ++bounds.first)
4809     {
4810       const char *qualified = index.symbol_name_at (bounds.first->idx);
4811
4812       if (!lookup_name_matcher.matches (qualified)
4813           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4814         continue;
4815
4816       matches.push_back (bounds.first->idx);
4817     }
4818
4819   std::sort (matches.begin (), matches.end ());
4820
4821   /* Finally call the callback, once per match.  */
4822   ULONGEST prev = -1;
4823   for (offset_type idx : matches)
4824     {
4825       if (prev != idx)
4826         {
4827           match_callback (idx);
4828           prev = idx;
4829         }
4830     }
4831
4832   /* Above we use a type wider than idx's for 'prev', since 0 and
4833      (offset_type)-1 are both possible values.  */
4834   static_assert (sizeof (prev) > sizeof (offset_type), "");
4835 }
4836
4837 #if GDB_SELF_TEST
4838
4839 namespace selftests { namespace dw2_expand_symtabs_matching {
4840
4841 /* A mock .gdb_index/.debug_names-like name index table, enough to
4842    exercise dw2_expand_symtabs_matching_symbol, which works with the
4843    mapped_index_base interface.  Builds an index from the symbol list
4844    passed as parameter to the constructor.  */
4845 class mock_mapped_index : public mapped_index_base
4846 {
4847 public:
4848   mock_mapped_index (gdb::array_view<const char *> symbols)
4849     : m_symbol_table (symbols)
4850   {}
4851
4852   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4853
4854   /* Return the number of names in the symbol table.  */
4855   virtual size_t symbol_name_count () const
4856   {
4857     return m_symbol_table.size ();
4858   }
4859
4860   /* Get the name of the symbol at IDX in the symbol table.  */
4861   virtual const char *symbol_name_at (offset_type idx) const
4862   {
4863     return m_symbol_table[idx];
4864   }
4865
4866 private:
4867   gdb::array_view<const char *> m_symbol_table;
4868 };
4869
4870 /* Convenience function that converts a NULL pointer to a "<null>"
4871    string, to pass to print routines.  */
4872
4873 static const char *
4874 string_or_null (const char *str)
4875 {
4876   return str != NULL ? str : "<null>";
4877 }
4878
4879 /* Check if a lookup_name_info built from
4880    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4881    index.  EXPECTED_LIST is the list of expected matches, in expected
4882    matching order.  If no match expected, then an empty list is
4883    specified.  Returns true on success.  On failure prints a warning
4884    indicating the file:line that failed, and returns false.  */
4885
4886 static bool
4887 check_match (const char *file, int line,
4888              mock_mapped_index &mock_index,
4889              const char *name, symbol_name_match_type match_type,
4890              bool completion_mode,
4891              std::initializer_list<const char *> expected_list)
4892 {
4893   lookup_name_info lookup_name (name, match_type, completion_mode);
4894
4895   bool matched = true;
4896
4897   auto mismatch = [&] (const char *expected_str,
4898                        const char *got)
4899   {
4900     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4901                "expected=\"%s\", got=\"%s\"\n"),
4902              file, line,
4903              (match_type == symbol_name_match_type::FULL
4904               ? "FULL" : "WILD"),
4905              name, string_or_null (expected_str), string_or_null (got));
4906     matched = false;
4907   };
4908
4909   auto expected_it = expected_list.begin ();
4910   auto expected_end = expected_list.end ();
4911
4912   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4913                                       NULL, ALL_DOMAIN,
4914                                       [&] (offset_type idx)
4915   {
4916     const char *matched_name = mock_index.symbol_name_at (idx);
4917     const char *expected_str
4918       = expected_it == expected_end ? NULL : *expected_it++;
4919
4920     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4921       mismatch (expected_str, matched_name);
4922   });
4923
4924   const char *expected_str
4925   = expected_it == expected_end ? NULL : *expected_it++;
4926   if (expected_str != NULL)
4927     mismatch (expected_str, NULL);
4928
4929   return matched;
4930 }
4931
4932 /* The symbols added to the mock mapped_index for testing (in
4933    canonical form).  */
4934 static const char *test_symbols[] = {
4935   "function",
4936   "std::bar",
4937   "std::zfunction",
4938   "std::zfunction2",
4939   "w1::w2",
4940   "ns::foo<char*>",
4941   "ns::foo<int>",
4942   "ns::foo<long>",
4943   "ns2::tmpl<int>::foo2",
4944   "(anonymous namespace)::A::B::C",
4945
4946   /* These are used to check that the increment-last-char in the
4947      matching algorithm for completion doesn't match "t1_fund" when
4948      completing "t1_func".  */
4949   "t1_func",
4950   "t1_func1",
4951   "t1_fund",
4952   "t1_fund1",
4953
4954   /* A UTF-8 name with multi-byte sequences to make sure that
4955      cp-name-parser understands this as a single identifier ("função"
4956      is "function" in PT).  */
4957   u8"u8função",
4958
4959   /* \377 (0xff) is Latin1 'ÿ'.  */
4960   "yfunc\377",
4961
4962   /* \377 (0xff) is Latin1 'ÿ'.  */
4963   "\377",
4964   "\377\377123",
4965
4966   /* A name with all sorts of complications.  Starts with "z" to make
4967      it easier for the completion tests below.  */
4968 #define Z_SYM_NAME \
4969   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4970     "::tuple<(anonymous namespace)::ui*, " \
4971     "std::default_delete<(anonymous namespace)::ui>, void>"
4972
4973   Z_SYM_NAME
4974 };
4975
4976 /* Returns true if the mapped_index_base::find_name_component_bounds
4977    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4978    in completion mode.  */
4979
4980 static bool
4981 check_find_bounds_finds (mapped_index_base &index,
4982                          const char *search_name,
4983                          gdb::array_view<const char *> expected_syms)
4984 {
4985   lookup_name_info lookup_name (search_name,
4986                                 symbol_name_match_type::FULL, true);
4987
4988   auto bounds = index.find_name_components_bounds (lookup_name);
4989
4990   size_t distance = std::distance (bounds.first, bounds.second);
4991   if (distance != expected_syms.size ())
4992     return false;
4993
4994   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4995     {
4996       auto nc_elem = bounds.first + exp_elem;
4997       const char *qualified = index.symbol_name_at (nc_elem->idx);
4998       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4999         return false;
5000     }
5001
5002   return true;
5003 }
5004
5005 /* Test the lower-level mapped_index::find_name_component_bounds
5006    method.  */
5007
5008 static void
5009 test_mapped_index_find_name_component_bounds ()
5010 {
5011   mock_mapped_index mock_index (test_symbols);
5012
5013   mock_index.build_name_components ();
5014
5015   /* Test the lower-level mapped_index::find_name_component_bounds
5016      method in completion mode.  */
5017   {
5018     static const char *expected_syms[] = {
5019       "t1_func",
5020       "t1_func1",
5021     };
5022
5023     SELF_CHECK (check_find_bounds_finds (mock_index,
5024                                          "t1_func", expected_syms));
5025   }
5026
5027   /* Check that the increment-last-char in the name matching algorithm
5028      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5029   {
5030     static const char *expected_syms1[] = {
5031       "\377",
5032       "\377\377123",
5033     };
5034     SELF_CHECK (check_find_bounds_finds (mock_index,
5035                                          "\377", expected_syms1));
5036
5037     static const char *expected_syms2[] = {
5038       "\377\377123",
5039     };
5040     SELF_CHECK (check_find_bounds_finds (mock_index,
5041                                          "\377\377", expected_syms2));
5042   }
5043 }
5044
5045 /* Test dw2_expand_symtabs_matching_symbol.  */
5046
5047 static void
5048 test_dw2_expand_symtabs_matching_symbol ()
5049 {
5050   mock_mapped_index mock_index (test_symbols);
5051
5052   /* We let all tests run until the end even if some fails, for debug
5053      convenience.  */
5054   bool any_mismatch = false;
5055
5056   /* Create the expected symbols list (an initializer_list).  Needed
5057      because lists have commas, and we need to pass them to CHECK,
5058      which is a macro.  */
5059 #define EXPECT(...) { __VA_ARGS__ }
5060
5061   /* Wrapper for check_match that passes down the current
5062      __FILE__/__LINE__.  */
5063 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5064   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5065                                 mock_index,                             \
5066                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5067                                 EXPECTED_LIST)
5068
5069   /* Identity checks.  */
5070   for (const char *sym : test_symbols)
5071     {
5072       /* Should be able to match all existing symbols.  */
5073       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5074                    EXPECT (sym));
5075
5076       /* Should be able to match all existing symbols with
5077          parameters.  */
5078       std::string with_params = std::string (sym) + "(int)";
5079       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5080                    EXPECT (sym));
5081
5082       /* Should be able to match all existing symbols with
5083          parameters and qualifiers.  */
5084       with_params = std::string (sym) + " ( int ) const";
5085       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5086                    EXPECT (sym));
5087
5088       /* This should really find sym, but cp-name-parser.y doesn't
5089          know about lvalue/rvalue qualifiers yet.  */
5090       with_params = std::string (sym) + " ( int ) &&";
5091       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5092                    {});
5093     }
5094
5095   /* Check that the name matching algorithm for completion doesn't get
5096      confused with Latin1 'ÿ' / 0xff.  */
5097   {
5098     static const char str[] = "\377";
5099     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5100                  EXPECT ("\377", "\377\377123"));
5101   }
5102
5103   /* Check that the increment-last-char in the matching algorithm for
5104      completion doesn't match "t1_fund" when completing "t1_func".  */
5105   {
5106     static const char str[] = "t1_func";
5107     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5108                  EXPECT ("t1_func", "t1_func1"));
5109   }
5110
5111   /* Check that completion mode works at each prefix of the expected
5112      symbol name.  */
5113   {
5114     static const char str[] = "function(int)";
5115     size_t len = strlen (str);
5116     std::string lookup;
5117
5118     for (size_t i = 1; i < len; i++)
5119       {
5120         lookup.assign (str, i);
5121         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5122                      EXPECT ("function"));
5123       }
5124   }
5125
5126   /* While "w" is a prefix of both components, the match function
5127      should still only be called once.  */
5128   {
5129     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5130                  EXPECT ("w1::w2"));
5131     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5132                  EXPECT ("w1::w2"));
5133   }
5134
5135   /* Same, with a "complicated" symbol.  */
5136   {
5137     static const char str[] = Z_SYM_NAME;
5138     size_t len = strlen (str);
5139     std::string lookup;
5140
5141     for (size_t i = 1; i < len; i++)
5142       {
5143         lookup.assign (str, i);
5144         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5145                      EXPECT (Z_SYM_NAME));
5146       }
5147   }
5148
5149   /* In FULL mode, an incomplete symbol doesn't match.  */
5150   {
5151     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5152                  {});
5153   }
5154
5155   /* A complete symbol with parameters matches any overload, since the
5156      index has no overload info.  */
5157   {
5158     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5159                  EXPECT ("std::zfunction", "std::zfunction2"));
5160     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5161                  EXPECT ("std::zfunction", "std::zfunction2"));
5162     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5163                  EXPECT ("std::zfunction", "std::zfunction2"));
5164   }
5165
5166   /* Check that whitespace is ignored appropriately.  A symbol with a
5167      template argument list. */
5168   {
5169     static const char expected[] = "ns::foo<int>";
5170     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5171                  EXPECT (expected));
5172     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5173                  EXPECT (expected));
5174   }
5175
5176   /* Check that whitespace is ignored appropriately.  A symbol with a
5177      template argument list that includes a pointer.  */
5178   {
5179     static const char expected[] = "ns::foo<char*>";
5180     /* Try both completion and non-completion modes.  */
5181     static const bool completion_mode[2] = {false, true};
5182     for (size_t i = 0; i < 2; i++)
5183       {
5184         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5185                      completion_mode[i], EXPECT (expected));
5186         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5187                      completion_mode[i], EXPECT (expected));
5188
5189         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5190                      completion_mode[i], EXPECT (expected));
5191         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5192                      completion_mode[i], EXPECT (expected));
5193       }
5194   }
5195
5196   {
5197     /* Check method qualifiers are ignored.  */
5198     static const char expected[] = "ns::foo<char*>";
5199     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5200                  symbol_name_match_type::FULL, true, EXPECT (expected));
5201     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5202                  symbol_name_match_type::FULL, true, EXPECT (expected));
5203     CHECK_MATCH ("foo < char * >  ( int ) const",
5204                  symbol_name_match_type::WILD, true, EXPECT (expected));
5205     CHECK_MATCH ("foo < char * >  ( int ) &&",
5206                  symbol_name_match_type::WILD, true, EXPECT (expected));
5207   }
5208
5209   /* Test lookup names that don't match anything.  */
5210   {
5211     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5212                  {});
5213
5214     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5215                  {});
5216   }
5217
5218   /* Some wild matching tests, exercising "(anonymous namespace)",
5219      which should not be confused with a parameter list.  */
5220   {
5221     static const char *syms[] = {
5222       "A::B::C",
5223       "B::C",
5224       "C",
5225       "A :: B :: C ( int )",
5226       "B :: C ( int )",
5227       "C ( int )",
5228     };
5229
5230     for (const char *s : syms)
5231       {
5232         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5233                      EXPECT ("(anonymous namespace)::A::B::C"));
5234       }
5235   }
5236
5237   {
5238     static const char expected[] = "ns2::tmpl<int>::foo2";
5239     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5240                  EXPECT (expected));
5241     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5242                  EXPECT (expected));
5243   }
5244
5245   SELF_CHECK (!any_mismatch);
5246
5247 #undef EXPECT
5248 #undef CHECK_MATCH
5249 }
5250
5251 static void
5252 run_test ()
5253 {
5254   test_mapped_index_find_name_component_bounds ();
5255   test_dw2_expand_symtabs_matching_symbol ();
5256 }
5257
5258 }} // namespace selftests::dw2_expand_symtabs_matching
5259
5260 #endif /* GDB_SELF_TEST */
5261
5262 /* If FILE_MATCHER is NULL or if PER_CU has
5263    dwarf2_per_cu_quick_data::MARK set (see
5264    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5265    EXPANSION_NOTIFY on it.  */
5266
5267 static void
5268 dw2_expand_symtabs_matching_one
5269   (struct dwarf2_per_cu_data *per_cu,
5270    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5271    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5272 {
5273   if (file_matcher == NULL || per_cu->v.quick->mark)
5274     {
5275       bool symtab_was_null
5276         = (per_cu->v.quick->compunit_symtab == NULL);
5277
5278       dw2_instantiate_symtab (per_cu);
5279
5280       if (expansion_notify != NULL
5281           && symtab_was_null
5282           && per_cu->v.quick->compunit_symtab != NULL)
5283         expansion_notify (per_cu->v.quick->compunit_symtab);
5284     }
5285 }
5286
5287 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5288    matched, to expand corresponding CUs that were marked.  IDX is the
5289    index of the symbol name that matched.  */
5290
5291 static void
5292 dw2_expand_marked_cus
5293   (mapped_index &index, offset_type idx,
5294    struct objfile *objfile,
5295    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5296    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5297    search_domain kind)
5298 {
5299   offset_type *vec, vec_len, vec_idx;
5300   bool global_seen = false;
5301
5302   vec = (offset_type *) (index.constant_pool
5303                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5304   vec_len = MAYBE_SWAP (vec[0]);
5305   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5306     {
5307       struct dwarf2_per_cu_data *per_cu;
5308       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5309       /* This value is only valid for index versions >= 7.  */
5310       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5311       gdb_index_symbol_kind symbol_kind =
5312         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5313       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5314       /* Only check the symbol attributes if they're present.
5315          Indices prior to version 7 don't record them,
5316          and indices >= 7 may elide them for certain symbols
5317          (gold does this).  */
5318       int attrs_valid =
5319         (index.version >= 7
5320          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5321
5322       /* Work around gold/15646.  */
5323       if (attrs_valid)
5324         {
5325           if (!is_static && global_seen)
5326             continue;
5327           if (!is_static)
5328             global_seen = true;
5329         }
5330
5331       /* Only check the symbol's kind if it has one.  */
5332       if (attrs_valid)
5333         {
5334           switch (kind)
5335             {
5336             case VARIABLES_DOMAIN:
5337               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5338                 continue;
5339               break;
5340             case FUNCTIONS_DOMAIN:
5341               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5342                 continue;
5343               break;
5344             case TYPES_DOMAIN:
5345               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5346                 continue;
5347               break;
5348             default:
5349               break;
5350             }
5351         }
5352
5353       /* Don't crash on bad data.  */
5354       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5355                        + dwarf2_per_objfile->n_type_units))
5356         {
5357           complaint (&symfile_complaints,
5358                      _(".gdb_index entry has bad CU index"
5359                        " [in module %s]"), objfile_name (objfile));
5360           continue;
5361         }
5362
5363       per_cu = dw2_get_cutu (cu_index);
5364       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5365                                        expansion_notify);
5366     }
5367 }
5368
5369 /* If FILE_MATCHER is non-NULL, set all the
5370    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5371    that match FILE_MATCHER.  */
5372
5373 static void
5374 dw_expand_symtabs_matching_file_matcher
5375   (gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5376 {
5377   if (file_matcher == NULL)
5378     return;
5379
5380   objfile *const objfile = dwarf2_per_objfile->objfile;
5381
5382   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5383                                             htab_eq_pointer,
5384                                             NULL, xcalloc, xfree));
5385   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5386                                                 htab_eq_pointer,
5387                                                 NULL, xcalloc, xfree));
5388
5389   /* The rule is CUs specify all the files, including those used by
5390      any TU, so there's no need to scan TUs here.  */
5391
5392   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5393     {
5394       int j;
5395       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5396       struct quick_file_names *file_data;
5397       void **slot;
5398
5399       QUIT;
5400
5401       per_cu->v.quick->mark = 0;
5402
5403       /* We only need to look at symtabs not already expanded.  */
5404       if (per_cu->v.quick->compunit_symtab)
5405         continue;
5406
5407       file_data = dw2_get_file_names (per_cu);
5408       if (file_data == NULL)
5409         continue;
5410
5411       if (htab_find (visited_not_found.get (), file_data) != NULL)
5412         continue;
5413       else if (htab_find (visited_found.get (), file_data) != NULL)
5414         {
5415           per_cu->v.quick->mark = 1;
5416           continue;
5417         }
5418
5419       for (j = 0; j < file_data->num_file_names; ++j)
5420         {
5421           const char *this_real_name;
5422
5423           if (file_matcher (file_data->file_names[j], false))
5424             {
5425               per_cu->v.quick->mark = 1;
5426               break;
5427             }
5428
5429           /* Before we invoke realpath, which can get expensive when many
5430              files are involved, do a quick comparison of the basenames.  */
5431           if (!basenames_may_differ
5432               && !file_matcher (lbasename (file_data->file_names[j]),
5433                                 true))
5434             continue;
5435
5436           this_real_name = dw2_get_real_path (objfile, file_data, j);
5437           if (file_matcher (this_real_name, false))
5438             {
5439               per_cu->v.quick->mark = 1;
5440               break;
5441             }
5442         }
5443
5444       slot = htab_find_slot (per_cu->v.quick->mark
5445                              ? visited_found.get ()
5446                              : visited_not_found.get (),
5447                              file_data, INSERT);
5448       *slot = file_data;
5449     }
5450 }
5451
5452 static void
5453 dw2_expand_symtabs_matching
5454   (struct objfile *objfile,
5455    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5456    const lookup_name_info &lookup_name,
5457    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5458    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5459    enum search_domain kind)
5460 {
5461   dw2_setup (objfile);
5462
5463   /* index_table is NULL if OBJF_READNOW.  */
5464   if (!dwarf2_per_objfile->index_table)
5465     return;
5466
5467   dw_expand_symtabs_matching_file_matcher (file_matcher);
5468
5469   mapped_index &index = *dwarf2_per_objfile->index_table;
5470
5471   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5472                                       symbol_matcher,
5473                                       kind, [&] (offset_type idx)
5474     {
5475       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
5476                              expansion_notify, kind);
5477     });
5478 }
5479
5480 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5481    symtab.  */
5482
5483 static struct compunit_symtab *
5484 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5485                                           CORE_ADDR pc)
5486 {
5487   int i;
5488
5489   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5490       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5491     return cust;
5492
5493   if (cust->includes == NULL)
5494     return NULL;
5495
5496   for (i = 0; cust->includes[i]; ++i)
5497     {
5498       struct compunit_symtab *s = cust->includes[i];
5499
5500       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5501       if (s != NULL)
5502         return s;
5503     }
5504
5505   return NULL;
5506 }
5507
5508 static struct compunit_symtab *
5509 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5510                                   struct bound_minimal_symbol msymbol,
5511                                   CORE_ADDR pc,
5512                                   struct obj_section *section,
5513                                   int warn_if_readin)
5514 {
5515   struct dwarf2_per_cu_data *data;
5516   struct compunit_symtab *result;
5517
5518   dw2_setup (objfile);
5519
5520   if (!objfile->psymtabs_addrmap)
5521     return NULL;
5522
5523   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5524                                                      pc);
5525   if (!data)
5526     return NULL;
5527
5528   if (warn_if_readin && data->v.quick->compunit_symtab)
5529     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5530              paddress (get_objfile_arch (objfile), pc));
5531
5532   result
5533     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5534                                                 pc);
5535   gdb_assert (result != NULL);
5536   return result;
5537 }
5538
5539 static void
5540 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5541                           void *data, int need_fullname)
5542 {
5543   dw2_setup (objfile);
5544
5545   if (!dwarf2_per_objfile->filenames_cache)
5546     {
5547       dwarf2_per_objfile->filenames_cache.emplace ();
5548
5549       htab_up visited (htab_create_alloc (10,
5550                                           htab_hash_pointer, htab_eq_pointer,
5551                                           NULL, xcalloc, xfree));
5552
5553       /* The rule is CUs specify all the files, including those used
5554          by any TU, so there's no need to scan TUs here.  We can
5555          ignore file names coming from already-expanded CUs.  */
5556
5557       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5558         {
5559           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5560
5561           if (per_cu->v.quick->compunit_symtab)
5562             {
5563               void **slot = htab_find_slot (visited.get (),
5564                                             per_cu->v.quick->file_names,
5565                                             INSERT);
5566
5567               *slot = per_cu->v.quick->file_names;
5568             }
5569         }
5570
5571       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5572         {
5573           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5574           struct quick_file_names *file_data;
5575           void **slot;
5576
5577           /* We only need to look at symtabs not already expanded.  */
5578           if (per_cu->v.quick->compunit_symtab)
5579             continue;
5580
5581           file_data = dw2_get_file_names (per_cu);
5582           if (file_data == NULL)
5583             continue;
5584
5585           slot = htab_find_slot (visited.get (), file_data, INSERT);
5586           if (*slot)
5587             {
5588               /* Already visited.  */
5589               continue;
5590             }
5591           *slot = file_data;
5592
5593           for (int j = 0; j < file_data->num_file_names; ++j)
5594             {
5595               const char *filename = file_data->file_names[j];
5596               dwarf2_per_objfile->filenames_cache->seen (filename);
5597             }
5598         }
5599     }
5600
5601   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5602     {
5603       gdb::unique_xmalloc_ptr<char> this_real_name;
5604
5605       if (need_fullname)
5606         this_real_name = gdb_realpath (filename);
5607       (*fun) (filename, this_real_name.get (), data);
5608     });
5609 }
5610
5611 static int
5612 dw2_has_symbols (struct objfile *objfile)
5613 {
5614   return 1;
5615 }
5616
5617 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5618 {
5619   dw2_has_symbols,
5620   dw2_find_last_source_symtab,
5621   dw2_forget_cached_source_info,
5622   dw2_map_symtabs_matching_filename,
5623   dw2_lookup_symbol,
5624   dw2_print_stats,
5625   dw2_dump,
5626   dw2_relocate,
5627   dw2_expand_symtabs_for_function,
5628   dw2_expand_all_symtabs,
5629   dw2_expand_symtabs_with_fullname,
5630   dw2_map_matching_symbols,
5631   dw2_expand_symtabs_matching,
5632   dw2_find_pc_sect_compunit_symtab,
5633   NULL,
5634   dw2_map_symbol_filenames
5635 };
5636
5637 /* DWARF-5 debug_names reader.  */
5638
5639 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5640 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5641
5642 /* A helper function that reads the .debug_names section in SECTION
5643    and fills in MAP.  FILENAME is the name of the file containing the
5644    section; it is used for error reporting.
5645
5646    Returns true if all went well, false otherwise.  */
5647
5648 static bool
5649 read_debug_names_from_section (struct objfile *objfile,
5650                                const char *filename,
5651                                struct dwarf2_section_info *section,
5652                                mapped_debug_names &map)
5653 {
5654   if (dwarf2_section_empty_p (section))
5655     return false;
5656
5657   /* Older elfutils strip versions could keep the section in the main
5658      executable while splitting it for the separate debug info file.  */
5659   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5660     return false;
5661
5662   dwarf2_read_section (objfile, section);
5663
5664   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5665
5666   const gdb_byte *addr = section->buffer;
5667
5668   bfd *const abfd = get_section_bfd_owner (section);
5669
5670   unsigned int bytes_read;
5671   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5672   addr += bytes_read;
5673
5674   map.dwarf5_is_dwarf64 = bytes_read != 4;
5675   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5676   if (bytes_read + length != section->size)
5677     {
5678       /* There may be multiple per-CU indices.  */
5679       warning (_("Section .debug_names in %s length %s does not match "
5680                  "section length %s, ignoring .debug_names."),
5681                filename, plongest (bytes_read + length),
5682                pulongest (section->size));
5683       return false;
5684     }
5685
5686   /* The version number.  */
5687   uint16_t version = read_2_bytes (abfd, addr);
5688   addr += 2;
5689   if (version != 5)
5690     {
5691       warning (_("Section .debug_names in %s has unsupported version %d, "
5692                  "ignoring .debug_names."),
5693                filename, version);
5694       return false;
5695     }
5696
5697   /* Padding.  */
5698   uint16_t padding = read_2_bytes (abfd, addr);
5699   addr += 2;
5700   if (padding != 0)
5701     {
5702       warning (_("Section .debug_names in %s has unsupported padding %d, "
5703                  "ignoring .debug_names."),
5704                filename, padding);
5705       return false;
5706     }
5707
5708   /* comp_unit_count - The number of CUs in the CU list.  */
5709   map.cu_count = read_4_bytes (abfd, addr);
5710   addr += 4;
5711
5712   /* local_type_unit_count - The number of TUs in the local TU
5713      list.  */
5714   map.tu_count = read_4_bytes (abfd, addr);
5715   addr += 4;
5716
5717   /* foreign_type_unit_count - The number of TUs in the foreign TU
5718      list.  */
5719   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5720   addr += 4;
5721   if (foreign_tu_count != 0)
5722     {
5723       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5724                  "ignoring .debug_names."),
5725                filename, static_cast<unsigned long> (foreign_tu_count));
5726       return false;
5727     }
5728
5729   /* bucket_count - The number of hash buckets in the hash lookup
5730      table.  */
5731   map.bucket_count = read_4_bytes (abfd, addr);
5732   addr += 4;
5733
5734   /* name_count - The number of unique names in the index.  */
5735   map.name_count = read_4_bytes (abfd, addr);
5736   addr += 4;
5737
5738   /* abbrev_table_size - The size in bytes of the abbreviations
5739      table.  */
5740   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5741   addr += 4;
5742
5743   /* augmentation_string_size - The size in bytes of the augmentation
5744      string.  This value is rounded up to a multiple of 4.  */
5745   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5746   addr += 4;
5747   map.augmentation_is_gdb = ((augmentation_string_size
5748                               == sizeof (dwarf5_augmentation))
5749                              && memcmp (addr, dwarf5_augmentation,
5750                                         sizeof (dwarf5_augmentation)) == 0);
5751   augmentation_string_size += (-augmentation_string_size) & 3;
5752   addr += augmentation_string_size;
5753
5754   /* List of CUs */
5755   map.cu_table_reordered = addr;
5756   addr += map.cu_count * map.offset_size;
5757
5758   /* List of Local TUs */
5759   map.tu_table_reordered = addr;
5760   addr += map.tu_count * map.offset_size;
5761
5762   /* Hash Lookup Table */
5763   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5764   addr += map.bucket_count * 4;
5765   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5766   addr += map.name_count * 4;
5767
5768   /* Name Table */
5769   map.name_table_string_offs_reordered = addr;
5770   addr += map.name_count * map.offset_size;
5771   map.name_table_entry_offs_reordered = addr;
5772   addr += map.name_count * map.offset_size;
5773
5774   const gdb_byte *abbrev_table_start = addr;
5775   for (;;)
5776     {
5777       unsigned int bytes_read;
5778       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5779       addr += bytes_read;
5780       if (index_num == 0)
5781         break;
5782
5783       const auto insertpair
5784         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5785       if (!insertpair.second)
5786         {
5787           warning (_("Section .debug_names in %s has duplicate index %s, "
5788                      "ignoring .debug_names."),
5789                    filename, pulongest (index_num));
5790           return false;
5791         }
5792       mapped_debug_names::index_val &indexval = insertpair.first->second;
5793       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5794       addr += bytes_read;
5795
5796       for (;;)
5797         {
5798           mapped_debug_names::index_val::attr attr;
5799           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5800           addr += bytes_read;
5801           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5802           addr += bytes_read;
5803           if (attr.form == DW_FORM_implicit_const)
5804             {
5805               attr.implicit_const = read_signed_leb128 (abfd, addr,
5806                                                         &bytes_read);
5807               addr += bytes_read;
5808             }
5809           if (attr.dw_idx == 0 && attr.form == 0)
5810             break;
5811           indexval.attr_vec.push_back (std::move (attr));
5812         }
5813     }
5814   if (addr != abbrev_table_start + abbrev_table_size)
5815     {
5816       warning (_("Section .debug_names in %s has abbreviation_table "
5817                  "of size %zu vs. written as %u, ignoring .debug_names."),
5818                filename, addr - abbrev_table_start, abbrev_table_size);
5819       return false;
5820     }
5821   map.entry_pool = addr;
5822
5823   return true;
5824 }
5825
5826 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5827    list.  */
5828
5829 static void
5830 create_cus_from_debug_names_list (struct objfile *objfile,
5831                                   const mapped_debug_names &map,
5832                                   dwarf2_section_info &section,
5833                                   bool is_dwz, int base_offset)
5834 {
5835   sect_offset sect_off_prev;
5836   for (uint32_t i = 0; i <= map.cu_count; ++i)
5837     {
5838       sect_offset sect_off_next;
5839       if (i < map.cu_count)
5840         {
5841           sect_off_next
5842             = (sect_offset) (extract_unsigned_integer
5843                              (map.cu_table_reordered + i * map.offset_size,
5844                               map.offset_size,
5845                               map.dwarf5_byte_order));
5846         }
5847       else
5848         sect_off_next = (sect_offset) section.size;
5849       if (i >= 1)
5850         {
5851           const ULONGEST length = sect_off_next - sect_off_prev;
5852           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5853             = create_cu_from_index_list (objfile, &section, is_dwz,
5854                                          sect_off_prev, length);
5855         }
5856       sect_off_prev = sect_off_next;
5857     }
5858 }
5859
5860 /* Read the CU list from the mapped index, and use it to create all
5861    the CU objects for this objfile.  */
5862
5863 static void
5864 create_cus_from_debug_names (struct objfile *objfile,
5865                              const mapped_debug_names &map,
5866                              const mapped_debug_names &dwz_map)
5867 {
5868
5869   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5870   dwarf2_per_objfile->all_comp_units
5871     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5872                  dwarf2_per_objfile->n_comp_units);
5873
5874   create_cus_from_debug_names_list (objfile, map, dwarf2_per_objfile->info,
5875                                     false /* is_dwz */,
5876                                     0 /* base_offset */);
5877
5878   if (dwz_map.cu_count == 0)
5879     return;
5880
5881   dwz_file *dwz = dwarf2_get_dwz_file ();
5882   create_cus_from_debug_names_list (objfile, dwz_map, dwz->info,
5883                                     true /* is_dwz */,
5884                                     map.cu_count /* base_offset */);
5885 }
5886
5887 /* Read .debug_names.  If everything went ok, initialize the "quick"
5888    elements of all the CUs and return true.  Otherwise, return false.  */
5889
5890 static bool
5891 dwarf2_read_debug_names (struct objfile *objfile)
5892 {
5893   mapped_debug_names local_map, dwz_map;
5894
5895   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5896                                       &dwarf2_per_objfile->debug_names,
5897                                       local_map))
5898     return false;
5899
5900   /* Don't use the index if it's empty.  */
5901   if (local_map.name_count == 0)
5902     return false;
5903
5904   /* If there is a .dwz file, read it so we can get its CU list as
5905      well.  */
5906   dwz_file *dwz = dwarf2_get_dwz_file ();
5907   if (dwz != NULL)
5908     {
5909       if (!read_debug_names_from_section (objfile,
5910                                           bfd_get_filename (dwz->dwz_bfd),
5911                                           &dwz->debug_names, dwz_map))
5912         {
5913           warning (_("could not read '.debug_names' section from %s; skipping"),
5914                    bfd_get_filename (dwz->dwz_bfd));
5915           return false;
5916         }
5917     }
5918
5919   create_cus_from_debug_names (objfile, local_map, dwz_map);
5920
5921   if (local_map.tu_count != 0)
5922     {
5923       /* We can only handle a single .debug_types when we have an
5924          index.  */
5925       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5926         return false;
5927
5928       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5929                                                 dwarf2_per_objfile->types, 0);
5930
5931       create_signatured_type_table_from_debug_names
5932         (objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5933     }
5934
5935   create_addrmap_from_aranges (objfile, &dwarf2_per_objfile->debug_aranges);
5936
5937   dwarf2_per_objfile->debug_names_table.reset (new mapped_debug_names);
5938   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5939   dwarf2_per_objfile->using_index = 1;
5940   dwarf2_per_objfile->quick_file_names_table =
5941     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5942
5943   return true;
5944 }
5945
5946 /* Symbol name hashing function as specified by DWARF-5.  */
5947
5948 static uint32_t
5949 dwarf5_djb_hash (const char *str_)
5950 {
5951   const unsigned char *str = (const unsigned char *) str_;
5952
5953   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
5954      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
5955
5956   uint32_t hash = 5381;
5957   while (int c = *str++)
5958     hash = hash * 33 + tolower (c);
5959   return hash;
5960 }
5961
5962 /* Type used to manage iterating over all CUs looking for a symbol for
5963    .debug_names.  */
5964
5965 class dw2_debug_names_iterator
5966 {
5967 public:
5968   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5969      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5970   dw2_debug_names_iterator (const mapped_debug_names &map,
5971                             bool want_specific_block,
5972                             block_enum block_index, domain_enum domain,
5973                             const char *name)
5974     : m_map (map), m_want_specific_block (want_specific_block),
5975       m_block_index (block_index), m_domain (domain),
5976       m_addr (find_vec_in_debug_names (map, name))
5977   {}
5978
5979   dw2_debug_names_iterator (const mapped_debug_names &map,
5980                             search_domain search, uint32_t namei)
5981     : m_map (map),
5982       m_search (search),
5983       m_addr (find_vec_in_debug_names (map, namei))
5984   {}
5985
5986   /* Return the next matching CU or NULL if there are no more.  */
5987   dwarf2_per_cu_data *next ();
5988
5989 private:
5990   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5991                                                   const char *name);
5992   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5993                                                   uint32_t namei);
5994
5995   /* The internalized form of .debug_names.  */
5996   const mapped_debug_names &m_map;
5997
5998   /* If true, only look for symbols that match BLOCK_INDEX.  */
5999   const bool m_want_specific_block = false;
6000
6001   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6002      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6003      value.  */
6004   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6005
6006   /* The kind of symbol we're looking for.  */
6007   const domain_enum m_domain = UNDEF_DOMAIN;
6008   const search_domain m_search = ALL_DOMAIN;
6009
6010   /* The list of CUs from the index entry of the symbol, or NULL if
6011      not found.  */
6012   const gdb_byte *m_addr;
6013 };
6014
6015 const char *
6016 mapped_debug_names::namei_to_name (uint32_t namei) const
6017 {
6018   const ULONGEST namei_string_offs
6019     = extract_unsigned_integer ((name_table_string_offs_reordered
6020                                  + namei * offset_size),
6021                                 offset_size,
6022                                 dwarf5_byte_order);
6023   return read_indirect_string_at_offset
6024     (dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6025 }
6026
6027 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6028    found, return pointer to its pool data.  If NAME cannot be found,
6029    return NULL.  */
6030
6031 const gdb_byte *
6032 dw2_debug_names_iterator::find_vec_in_debug_names
6033   (const mapped_debug_names &map, const char *name)
6034 {
6035   int (*cmp) (const char *, const char *);
6036
6037   if (current_language->la_language == language_cplus
6038       || current_language->la_language == language_fortran
6039       || current_language->la_language == language_d)
6040     {
6041       /* NAME is already canonical.  Drop any qualifiers as
6042          .debug_names does not contain any.  */
6043
6044       if (strchr (name, '(') != NULL)
6045         {
6046           gdb::unique_xmalloc_ptr<char> without_params
6047             = cp_remove_params (name);
6048
6049           if (without_params != NULL)
6050             {
6051               name = without_params.get();
6052             }
6053         }
6054     }
6055
6056   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6057
6058   const uint32_t full_hash = dwarf5_djb_hash (name);
6059   uint32_t namei
6060     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6061                                 (map.bucket_table_reordered
6062                                  + (full_hash % map.bucket_count)), 4,
6063                                 map.dwarf5_byte_order);
6064   if (namei == 0)
6065     return NULL;
6066   --namei;
6067   if (namei >= map.name_count)
6068     {
6069       complaint (&symfile_complaints,
6070                  _("Wrong .debug_names with name index %u but name_count=%u "
6071                    "[in module %s]"),
6072                  namei, map.name_count,
6073                  objfile_name (dwarf2_per_objfile->objfile));
6074       return NULL;
6075     }
6076
6077   for (;;)
6078     {
6079       const uint32_t namei_full_hash
6080         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6081                                     (map.hash_table_reordered + namei), 4,
6082                                     map.dwarf5_byte_order);
6083       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6084         return NULL;
6085
6086       if (full_hash == namei_full_hash)
6087         {
6088           const char *const namei_string = map.namei_to_name (namei);
6089
6090 #if 0 /* An expensive sanity check.  */
6091           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6092             {
6093               complaint (&symfile_complaints,
6094                          _("Wrong .debug_names hash for string at index %u "
6095                            "[in module %s]"),
6096                          namei, objfile_name (dwarf2_per_objfile->objfile));
6097               return NULL;
6098             }
6099 #endif
6100
6101           if (cmp (namei_string, name) == 0)
6102             {
6103               const ULONGEST namei_entry_offs
6104                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6105                                              + namei * map.offset_size),
6106                                             map.offset_size, map.dwarf5_byte_order);
6107               return map.entry_pool + namei_entry_offs;
6108             }
6109         }
6110
6111       ++namei;
6112       if (namei >= map.name_count)
6113         return NULL;
6114     }
6115 }
6116
6117 const gdb_byte *
6118 dw2_debug_names_iterator::find_vec_in_debug_names
6119   (const mapped_debug_names &map, uint32_t namei)
6120 {
6121   if (namei >= map.name_count)
6122     {
6123       complaint (&symfile_complaints,
6124                  _("Wrong .debug_names with name index %u but name_count=%u "
6125                    "[in module %s]"),
6126                  namei, map.name_count,
6127                  objfile_name (dwarf2_per_objfile->objfile));
6128       return NULL;
6129     }
6130
6131   const ULONGEST namei_entry_offs
6132     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6133                                  + namei * map.offset_size),
6134                                 map.offset_size, map.dwarf5_byte_order);
6135   return map.entry_pool + namei_entry_offs;
6136 }
6137
6138 /* See dw2_debug_names_iterator.  */
6139
6140 dwarf2_per_cu_data *
6141 dw2_debug_names_iterator::next ()
6142 {
6143   if (m_addr == NULL)
6144     return NULL;
6145
6146   bfd *const abfd = dwarf2_per_objfile->objfile->obfd;
6147
6148  again:
6149
6150   unsigned int bytes_read;
6151   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6152   m_addr += bytes_read;
6153   if (abbrev == 0)
6154     return NULL;
6155
6156   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6157   if (indexval_it == m_map.abbrev_map.cend ())
6158     {
6159       complaint (&symfile_complaints,
6160                  _("Wrong .debug_names undefined abbrev code %s "
6161                    "[in module %s]"),
6162                  pulongest (abbrev), objfile_name (dwarf2_per_objfile->objfile));
6163       return NULL;
6164     }
6165   const mapped_debug_names::index_val &indexval = indexval_it->second;
6166   bool have_is_static = false;
6167   bool is_static;
6168   dwarf2_per_cu_data *per_cu = NULL;
6169   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6170     {
6171       ULONGEST ull;
6172       switch (attr.form)
6173         {
6174         case DW_FORM_implicit_const:
6175           ull = attr.implicit_const;
6176           break;
6177         case DW_FORM_flag_present:
6178           ull = 1;
6179           break;
6180         case DW_FORM_udata:
6181           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6182           m_addr += bytes_read;
6183           break;
6184         default:
6185           complaint (&symfile_complaints,
6186                      _("Unsupported .debug_names form %s [in module %s]"),
6187                      dwarf_form_name (attr.form),
6188                      objfile_name (dwarf2_per_objfile->objfile));
6189           return NULL;
6190         }
6191       switch (attr.dw_idx)
6192         {
6193         case DW_IDX_compile_unit:
6194           /* Don't crash on bad data.  */
6195           if (ull >= (dwarf2_per_objfile->n_comp_units
6196                       + dwarf2_per_objfile->n_type_units))
6197             {
6198               complaint (&symfile_complaints,
6199                          _(".debug_names entry has bad CU index %s"
6200                            " [in module %s]"),
6201                          pulongest (ull),
6202                          objfile_name (dwarf2_per_objfile->objfile));
6203               continue;
6204             }
6205           per_cu = dw2_get_cutu (ull);
6206           break;
6207         case DW_IDX_GNU_internal:
6208           if (!m_map.augmentation_is_gdb)
6209             break;
6210           have_is_static = true;
6211           is_static = true;
6212           break;
6213         case DW_IDX_GNU_external:
6214           if (!m_map.augmentation_is_gdb)
6215             break;
6216           have_is_static = true;
6217           is_static = false;
6218           break;
6219         }
6220     }
6221
6222   /* Skip if already read in.  */
6223   if (per_cu->v.quick->compunit_symtab)
6224     goto again;
6225
6226   /* Check static vs global.  */
6227   if (have_is_static)
6228     {
6229       const bool want_static = m_block_index != GLOBAL_BLOCK;
6230       if (m_want_specific_block && want_static != is_static)
6231         goto again;
6232     }
6233
6234   /* Match dw2_symtab_iter_next, symbol_kind
6235      and debug_names::psymbol_tag.  */
6236   switch (m_domain)
6237     {
6238     case VAR_DOMAIN:
6239       switch (indexval.dwarf_tag)
6240         {
6241         case DW_TAG_variable:
6242         case DW_TAG_subprogram:
6243         /* Some types are also in VAR_DOMAIN.  */
6244         case DW_TAG_typedef:
6245         case DW_TAG_structure_type:
6246           break;
6247         default:
6248           goto again;
6249         }
6250       break;
6251     case STRUCT_DOMAIN:
6252       switch (indexval.dwarf_tag)
6253         {
6254         case DW_TAG_typedef:
6255         case DW_TAG_structure_type:
6256           break;
6257         default:
6258           goto again;
6259         }
6260       break;
6261     case LABEL_DOMAIN:
6262       switch (indexval.dwarf_tag)
6263         {
6264         case 0:
6265         case DW_TAG_variable:
6266           break;
6267         default:
6268           goto again;
6269         }
6270       break;
6271     default:
6272       break;
6273     }
6274
6275   /* Match dw2_expand_symtabs_matching, symbol_kind and
6276      debug_names::psymbol_tag.  */
6277   switch (m_search)
6278     {
6279     case VARIABLES_DOMAIN:
6280       switch (indexval.dwarf_tag)
6281         {
6282         case DW_TAG_variable:
6283           break;
6284         default:
6285           goto again;
6286         }
6287       break;
6288     case FUNCTIONS_DOMAIN:
6289       switch (indexval.dwarf_tag)
6290         {
6291         case DW_TAG_subprogram:
6292           break;
6293         default:
6294           goto again;
6295         }
6296       break;
6297     case TYPES_DOMAIN:
6298       switch (indexval.dwarf_tag)
6299         {
6300         case DW_TAG_typedef:
6301         case DW_TAG_structure_type:
6302           break;
6303         default:
6304           goto again;
6305         }
6306       break;
6307     default:
6308       break;
6309     }
6310
6311   return per_cu;
6312 }
6313
6314 static struct compunit_symtab *
6315 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6316                                const char *name, domain_enum domain)
6317 {
6318   const block_enum block_index = static_cast<block_enum> (block_index_int);
6319   dw2_setup (objfile);
6320
6321   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6322   if (!mapp)
6323     {
6324       /* index is NULL if OBJF_READNOW.  */
6325       return NULL;
6326     }
6327   const auto &map = *mapp;
6328
6329   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6330                                  block_index, domain, name);
6331
6332   struct compunit_symtab *stab_best = NULL;
6333   struct dwarf2_per_cu_data *per_cu;
6334   while ((per_cu = iter.next ()) != NULL)
6335     {
6336       struct symbol *sym, *with_opaque = NULL;
6337       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6338       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6339       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6340
6341       sym = block_find_symbol (block, name, domain,
6342                                block_find_non_opaque_type_preferred,
6343                                &with_opaque);
6344
6345       /* Some caution must be observed with overloaded functions and
6346          methods, since the index will not contain any overload
6347          information (but NAME might contain it).  */
6348
6349       if (sym != NULL
6350           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6351         return stab;
6352       if (with_opaque != NULL
6353           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6354         stab_best = stab;
6355
6356       /* Keep looking through other CUs.  */
6357     }
6358
6359   return stab_best;
6360 }
6361
6362 /* This dumps minimal information about .debug_names.  It is called
6363    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6364    uses this to verify that .debug_names has been loaded.  */
6365
6366 static void
6367 dw2_debug_names_dump (struct objfile *objfile)
6368 {
6369   dw2_setup (objfile);
6370   gdb_assert (dwarf2_per_objfile->using_index);
6371   printf_filtered (".debug_names:");
6372   if (dwarf2_per_objfile->debug_names_table)
6373     printf_filtered (" exists\n");
6374   else
6375     printf_filtered (" faked for \"readnow\"\n");
6376   printf_filtered ("\n");
6377 }
6378
6379 static void
6380 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6381                                              const char *func_name)
6382 {
6383   dw2_setup (objfile);
6384
6385   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6386   if (dwarf2_per_objfile->debug_names_table)
6387     {
6388       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6389
6390       /* Note: It doesn't matter what we pass for block_index here.  */
6391       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6392                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6393
6394       struct dwarf2_per_cu_data *per_cu;
6395       while ((per_cu = iter.next ()) != NULL)
6396         dw2_instantiate_symtab (per_cu);
6397     }
6398 }
6399
6400 static void
6401 dw2_debug_names_expand_symtabs_matching
6402   (struct objfile *objfile,
6403    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6404    const lookup_name_info &lookup_name,
6405    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6406    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6407    enum search_domain kind)
6408 {
6409   dw2_setup (objfile);
6410
6411   /* debug_names_table is NULL if OBJF_READNOW.  */
6412   if (!dwarf2_per_objfile->debug_names_table)
6413     return;
6414
6415   dw_expand_symtabs_matching_file_matcher (file_matcher);
6416
6417   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6418
6419   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6420                                       symbol_matcher,
6421                                       kind, [&] (offset_type namei)
6422     {
6423       /* The name was matched, now expand corresponding CUs that were
6424          marked.  */
6425       dw2_debug_names_iterator iter (map, kind, namei);
6426
6427       struct dwarf2_per_cu_data *per_cu;
6428       while ((per_cu = iter.next ()) != NULL)
6429         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6430                                          expansion_notify);
6431     });
6432 }
6433
6434 const struct quick_symbol_functions dwarf2_debug_names_functions =
6435 {
6436   dw2_has_symbols,
6437   dw2_find_last_source_symtab,
6438   dw2_forget_cached_source_info,
6439   dw2_map_symtabs_matching_filename,
6440   dw2_debug_names_lookup_symbol,
6441   dw2_print_stats,
6442   dw2_debug_names_dump,
6443   dw2_relocate,
6444   dw2_debug_names_expand_symtabs_for_function,
6445   dw2_expand_all_symtabs,
6446   dw2_expand_symtabs_with_fullname,
6447   dw2_map_matching_symbols,
6448   dw2_debug_names_expand_symtabs_matching,
6449   dw2_find_pc_sect_compunit_symtab,
6450   NULL,
6451   dw2_map_symbol_filenames
6452 };
6453
6454 /* See symfile.h.  */
6455
6456 bool
6457 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6458 {
6459   /* If we're about to read full symbols, don't bother with the
6460      indices.  In this case we also don't care if some other debug
6461      format is making psymtabs, because they are all about to be
6462      expanded anyway.  */
6463   if ((objfile->flags & OBJF_READNOW))
6464     {
6465       int i;
6466
6467       dwarf2_per_objfile->using_index = 1;
6468       create_all_comp_units (objfile);
6469       create_all_type_units (objfile);
6470       dwarf2_per_objfile->quick_file_names_table =
6471         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6472
6473       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6474                        + dwarf2_per_objfile->n_type_units); ++i)
6475         {
6476           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6477
6478           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6479                                             struct dwarf2_per_cu_quick_data);
6480         }
6481
6482       /* Return 1 so that gdb sees the "quick" functions.  However,
6483          these functions will be no-ops because we will have expanded
6484          all symtabs.  */
6485       *index_kind = dw_index_kind::GDB_INDEX;
6486       return true;
6487     }
6488
6489   if (dwarf2_read_debug_names (objfile))
6490     {
6491       *index_kind = dw_index_kind::DEBUG_NAMES;
6492       return true;
6493     }
6494
6495   if (dwarf2_read_index (objfile))
6496     {
6497       *index_kind = dw_index_kind::GDB_INDEX;
6498       return true;
6499     }
6500
6501   return false;
6502 }
6503
6504 \f
6505
6506 /* Build a partial symbol table.  */
6507
6508 void
6509 dwarf2_build_psymtabs (struct objfile *objfile)
6510 {
6511
6512   if (objfile->global_psymbols.capacity () == 0
6513       && objfile->static_psymbols.capacity () == 0)
6514     init_psymbol_list (objfile, 1024);
6515
6516   TRY
6517     {
6518       /* This isn't really ideal: all the data we allocate on the
6519          objfile's obstack is still uselessly kept around.  However,
6520          freeing it seems unsafe.  */
6521       psymtab_discarder psymtabs (objfile);
6522       dwarf2_build_psymtabs_hard (objfile);
6523       psymtabs.keep ();
6524     }
6525   CATCH (except, RETURN_MASK_ERROR)
6526     {
6527       exception_print (gdb_stderr, except);
6528     }
6529   END_CATCH
6530 }
6531
6532 /* Return the total length of the CU described by HEADER.  */
6533
6534 static unsigned int
6535 get_cu_length (const struct comp_unit_head *header)
6536 {
6537   return header->initial_length_size + header->length;
6538 }
6539
6540 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6541
6542 static inline bool
6543 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6544 {
6545   sect_offset bottom = cu_header->sect_off;
6546   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6547
6548   return sect_off >= bottom && sect_off < top;
6549 }
6550
6551 /* Find the base address of the compilation unit for range lists and
6552    location lists.  It will normally be specified by DW_AT_low_pc.
6553    In DWARF-3 draft 4, the base address could be overridden by
6554    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6555    compilation units with discontinuous ranges.  */
6556
6557 static void
6558 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6559 {
6560   struct attribute *attr;
6561
6562   cu->base_known = 0;
6563   cu->base_address = 0;
6564
6565   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6566   if (attr)
6567     {
6568       cu->base_address = attr_value_as_address (attr);
6569       cu->base_known = 1;
6570     }
6571   else
6572     {
6573       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6574       if (attr)
6575         {
6576           cu->base_address = attr_value_as_address (attr);
6577           cu->base_known = 1;
6578         }
6579     }
6580 }
6581
6582 /* Read in the comp unit header information from the debug_info at info_ptr.
6583    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6584    NOTE: This leaves members offset, first_die_offset to be filled in
6585    by the caller.  */
6586
6587 static const gdb_byte *
6588 read_comp_unit_head (struct comp_unit_head *cu_header,
6589                      const gdb_byte *info_ptr,
6590                      struct dwarf2_section_info *section,
6591                      rcuh_kind section_kind)
6592 {
6593   int signed_addr;
6594   unsigned int bytes_read;
6595   const char *filename = get_section_file_name (section);
6596   bfd *abfd = get_section_bfd_owner (section);
6597
6598   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6599   cu_header->initial_length_size = bytes_read;
6600   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6601   info_ptr += bytes_read;
6602   cu_header->version = read_2_bytes (abfd, info_ptr);
6603   info_ptr += 2;
6604   if (cu_header->version < 5)
6605     switch (section_kind)
6606       {
6607       case rcuh_kind::COMPILE:
6608         cu_header->unit_type = DW_UT_compile;
6609         break;
6610       case rcuh_kind::TYPE:
6611         cu_header->unit_type = DW_UT_type;
6612         break;
6613       default:
6614         internal_error (__FILE__, __LINE__,
6615                         _("read_comp_unit_head: invalid section_kind"));
6616       }
6617   else
6618     {
6619       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6620                                                  (read_1_byte (abfd, info_ptr));
6621       info_ptr += 1;
6622       switch (cu_header->unit_type)
6623         {
6624         case DW_UT_compile:
6625           if (section_kind != rcuh_kind::COMPILE)
6626             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6627                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6628                    filename);
6629           break;
6630         case DW_UT_type:
6631           section_kind = rcuh_kind::TYPE;
6632           break;
6633         default:
6634           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6635                  "(is %d, should be %d or %d) [in module %s]"),
6636                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6637         }
6638
6639       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6640       info_ptr += 1;
6641     }
6642   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6643                                                           cu_header,
6644                                                           &bytes_read);
6645   info_ptr += bytes_read;
6646   if (cu_header->version < 5)
6647     {
6648       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6649       info_ptr += 1;
6650     }
6651   signed_addr = bfd_get_sign_extend_vma (abfd);
6652   if (signed_addr < 0)
6653     internal_error (__FILE__, __LINE__,
6654                     _("read_comp_unit_head: dwarf from non elf file"));
6655   cu_header->signed_addr_p = signed_addr;
6656
6657   if (section_kind == rcuh_kind::TYPE)
6658     {
6659       LONGEST type_offset;
6660
6661       cu_header->signature = read_8_bytes (abfd, info_ptr);
6662       info_ptr += 8;
6663
6664       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6665       info_ptr += bytes_read;
6666       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6667       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6668         error (_("Dwarf Error: Too big type_offset in compilation unit "
6669                "header (is %s) [in module %s]"), plongest (type_offset),
6670                filename);
6671     }
6672
6673   return info_ptr;
6674 }
6675
6676 /* Helper function that returns the proper abbrev section for
6677    THIS_CU.  */
6678
6679 static struct dwarf2_section_info *
6680 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6681 {
6682   struct dwarf2_section_info *abbrev;
6683
6684   if (this_cu->is_dwz)
6685     abbrev = &dwarf2_get_dwz_file ()->abbrev;
6686   else
6687     abbrev = &dwarf2_per_objfile->abbrev;
6688
6689   return abbrev;
6690 }
6691
6692 /* Subroutine of read_and_check_comp_unit_head and
6693    read_and_check_type_unit_head to simplify them.
6694    Perform various error checking on the header.  */
6695
6696 static void
6697 error_check_comp_unit_head (struct comp_unit_head *header,
6698                             struct dwarf2_section_info *section,
6699                             struct dwarf2_section_info *abbrev_section)
6700 {
6701   const char *filename = get_section_file_name (section);
6702
6703   if (header->version < 2 || header->version > 5)
6704     error (_("Dwarf Error: wrong version in compilation unit header "
6705            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6706            filename);
6707
6708   if (to_underlying (header->abbrev_sect_off)
6709       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6710     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6711            "(offset 0x%x + 6) [in module %s]"),
6712            to_underlying (header->abbrev_sect_off),
6713            to_underlying (header->sect_off),
6714            filename);
6715
6716   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6717      avoid potential 32-bit overflow.  */
6718   if (((ULONGEST) header->sect_off + get_cu_length (header))
6719       > section->size)
6720     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6721            "(offset 0x%x + 0) [in module %s]"),
6722            header->length, to_underlying (header->sect_off),
6723            filename);
6724 }
6725
6726 /* Read in a CU/TU header and perform some basic error checking.
6727    The contents of the header are stored in HEADER.
6728    The result is a pointer to the start of the first DIE.  */
6729
6730 static const gdb_byte *
6731 read_and_check_comp_unit_head (struct comp_unit_head *header,
6732                                struct dwarf2_section_info *section,
6733                                struct dwarf2_section_info *abbrev_section,
6734                                const gdb_byte *info_ptr,
6735                                rcuh_kind section_kind)
6736 {
6737   const gdb_byte *beg_of_comp_unit = info_ptr;
6738
6739   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6740
6741   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6742
6743   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6744
6745   error_check_comp_unit_head (header, section, abbrev_section);
6746
6747   return info_ptr;
6748 }
6749
6750 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6751
6752 static sect_offset
6753 read_abbrev_offset (struct dwarf2_section_info *section,
6754                     sect_offset sect_off)
6755 {
6756   bfd *abfd = get_section_bfd_owner (section);
6757   const gdb_byte *info_ptr;
6758   unsigned int initial_length_size, offset_size;
6759   uint16_t version;
6760
6761   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6762   info_ptr = section->buffer + to_underlying (sect_off);
6763   read_initial_length (abfd, info_ptr, &initial_length_size);
6764   offset_size = initial_length_size == 4 ? 4 : 8;
6765   info_ptr += initial_length_size;
6766
6767   version = read_2_bytes (abfd, info_ptr);
6768   info_ptr += 2;
6769   if (version >= 5)
6770     {
6771       /* Skip unit type and address size.  */
6772       info_ptr += 2;
6773     }
6774
6775   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6776 }
6777
6778 /* Allocate a new partial symtab for file named NAME and mark this new
6779    partial symtab as being an include of PST.  */
6780
6781 static void
6782 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6783                                struct objfile *objfile)
6784 {
6785   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6786
6787   if (!IS_ABSOLUTE_PATH (subpst->filename))
6788     {
6789       /* It shares objfile->objfile_obstack.  */
6790       subpst->dirname = pst->dirname;
6791     }
6792
6793   subpst->textlow = 0;
6794   subpst->texthigh = 0;
6795
6796   subpst->dependencies
6797     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6798   subpst->dependencies[0] = pst;
6799   subpst->number_of_dependencies = 1;
6800
6801   subpst->globals_offset = 0;
6802   subpst->n_global_syms = 0;
6803   subpst->statics_offset = 0;
6804   subpst->n_static_syms = 0;
6805   subpst->compunit_symtab = NULL;
6806   subpst->read_symtab = pst->read_symtab;
6807   subpst->readin = 0;
6808
6809   /* No private part is necessary for include psymtabs.  This property
6810      can be used to differentiate between such include psymtabs and
6811      the regular ones.  */
6812   subpst->read_symtab_private = NULL;
6813 }
6814
6815 /* Read the Line Number Program data and extract the list of files
6816    included by the source file represented by PST.  Build an include
6817    partial symtab for each of these included files.  */
6818
6819 static void
6820 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6821                                struct die_info *die,
6822                                struct partial_symtab *pst)
6823 {
6824   line_header_up lh;
6825   struct attribute *attr;
6826
6827   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6828   if (attr)
6829     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6830   if (lh == NULL)
6831     return;  /* No linetable, so no includes.  */
6832
6833   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6834   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6835 }
6836
6837 static hashval_t
6838 hash_signatured_type (const void *item)
6839 {
6840   const struct signatured_type *sig_type
6841     = (const struct signatured_type *) item;
6842
6843   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6844   return sig_type->signature;
6845 }
6846
6847 static int
6848 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6849 {
6850   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6851   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6852
6853   return lhs->signature == rhs->signature;
6854 }
6855
6856 /* Allocate a hash table for signatured types.  */
6857
6858 static htab_t
6859 allocate_signatured_type_table (struct objfile *objfile)
6860 {
6861   return htab_create_alloc_ex (41,
6862                                hash_signatured_type,
6863                                eq_signatured_type,
6864                                NULL,
6865                                &objfile->objfile_obstack,
6866                                hashtab_obstack_allocate,
6867                                dummy_obstack_deallocate);
6868 }
6869
6870 /* A helper function to add a signatured type CU to a table.  */
6871
6872 static int
6873 add_signatured_type_cu_to_table (void **slot, void *datum)
6874 {
6875   struct signatured_type *sigt = (struct signatured_type *) *slot;
6876   struct signatured_type ***datap = (struct signatured_type ***) datum;
6877
6878   **datap = sigt;
6879   ++*datap;
6880
6881   return 1;
6882 }
6883
6884 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6885    and fill them into TYPES_HTAB.  It will process only type units,
6886    therefore DW_UT_type.  */
6887
6888 static void
6889 create_debug_type_hash_table (struct dwo_file *dwo_file,
6890                               dwarf2_section_info *section, htab_t &types_htab,
6891                               rcuh_kind section_kind)
6892 {
6893   struct objfile *objfile = dwarf2_per_objfile->objfile;
6894   struct dwarf2_section_info *abbrev_section;
6895   bfd *abfd;
6896   const gdb_byte *info_ptr, *end_ptr;
6897
6898   abbrev_section = (dwo_file != NULL
6899                     ? &dwo_file->sections.abbrev
6900                     : &dwarf2_per_objfile->abbrev);
6901
6902   if (dwarf_read_debug)
6903     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6904                         get_section_name (section),
6905                         get_section_file_name (abbrev_section));
6906
6907   dwarf2_read_section (objfile, section);
6908   info_ptr = section->buffer;
6909
6910   if (info_ptr == NULL)
6911     return;
6912
6913   /* We can't set abfd until now because the section may be empty or
6914      not present, in which case the bfd is unknown.  */
6915   abfd = get_section_bfd_owner (section);
6916
6917   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6918      because we don't need to read any dies: the signature is in the
6919      header.  */
6920
6921   end_ptr = info_ptr + section->size;
6922   while (info_ptr < end_ptr)
6923     {
6924       struct signatured_type *sig_type;
6925       struct dwo_unit *dwo_tu;
6926       void **slot;
6927       const gdb_byte *ptr = info_ptr;
6928       struct comp_unit_head header;
6929       unsigned int length;
6930
6931       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6932
6933       /* Initialize it due to a false compiler warning.  */
6934       header.signature = -1;
6935       header.type_cu_offset_in_tu = (cu_offset) -1;
6936
6937       /* We need to read the type's signature in order to build the hash
6938          table, but we don't need anything else just yet.  */
6939
6940       ptr = read_and_check_comp_unit_head (&header, section,
6941                                            abbrev_section, ptr, section_kind);
6942
6943       length = get_cu_length (&header);
6944
6945       /* Skip dummy type units.  */
6946       if (ptr >= info_ptr + length
6947           || peek_abbrev_code (abfd, ptr) == 0
6948           || header.unit_type != DW_UT_type)
6949         {
6950           info_ptr += length;
6951           continue;
6952         }
6953
6954       if (types_htab == NULL)
6955         {
6956           if (dwo_file)
6957             types_htab = allocate_dwo_unit_table (objfile);
6958           else
6959             types_htab = allocate_signatured_type_table (objfile);
6960         }
6961
6962       if (dwo_file)
6963         {
6964           sig_type = NULL;
6965           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6966                                    struct dwo_unit);
6967           dwo_tu->dwo_file = dwo_file;
6968           dwo_tu->signature = header.signature;
6969           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6970           dwo_tu->section = section;
6971           dwo_tu->sect_off = sect_off;
6972           dwo_tu->length = length;
6973         }
6974       else
6975         {
6976           /* N.B.: type_offset is not usable if this type uses a DWO file.
6977              The real type_offset is in the DWO file.  */
6978           dwo_tu = NULL;
6979           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6980                                      struct signatured_type);
6981           sig_type->signature = header.signature;
6982           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6983           sig_type->per_cu.objfile = objfile;
6984           sig_type->per_cu.is_debug_types = 1;
6985           sig_type->per_cu.section = section;
6986           sig_type->per_cu.sect_off = sect_off;
6987           sig_type->per_cu.length = length;
6988         }
6989
6990       slot = htab_find_slot (types_htab,
6991                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6992                              INSERT);
6993       gdb_assert (slot != NULL);
6994       if (*slot != NULL)
6995         {
6996           sect_offset dup_sect_off;
6997
6998           if (dwo_file)
6999             {
7000               const struct dwo_unit *dup_tu
7001                 = (const struct dwo_unit *) *slot;
7002
7003               dup_sect_off = dup_tu->sect_off;
7004             }
7005           else
7006             {
7007               const struct signatured_type *dup_tu
7008                 = (const struct signatured_type *) *slot;
7009
7010               dup_sect_off = dup_tu->per_cu.sect_off;
7011             }
7012
7013           complaint (&symfile_complaints,
7014                      _("debug type entry at offset 0x%x is duplicate to"
7015                        " the entry at offset 0x%x, signature %s"),
7016                      to_underlying (sect_off), to_underlying (dup_sect_off),
7017                      hex_string (header.signature));
7018         }
7019       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7020
7021       if (dwarf_read_debug > 1)
7022         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7023                             to_underlying (sect_off),
7024                             hex_string (header.signature));
7025
7026       info_ptr += length;
7027     }
7028 }
7029
7030 /* Create the hash table of all entries in the .debug_types
7031    (or .debug_types.dwo) section(s).
7032    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7033    otherwise it is NULL.
7034
7035    The result is a pointer to the hash table or NULL if there are no types.
7036
7037    Note: This function processes DWO files only, not DWP files.  */
7038
7039 static void
7040 create_debug_types_hash_table (struct dwo_file *dwo_file,
7041                                VEC (dwarf2_section_info_def) *types,
7042                                htab_t &types_htab)
7043 {
7044   int ix;
7045   struct dwarf2_section_info *section;
7046
7047   if (VEC_empty (dwarf2_section_info_def, types))
7048     return;
7049
7050   for (ix = 0;
7051        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7052        ++ix)
7053     create_debug_type_hash_table (dwo_file, section, types_htab,
7054                                   rcuh_kind::TYPE);
7055 }
7056
7057 /* Create the hash table of all entries in the .debug_types section,
7058    and initialize all_type_units.
7059    The result is zero if there is an error (e.g. missing .debug_types section),
7060    otherwise non-zero.  */
7061
7062 static int
7063 create_all_type_units (struct objfile *objfile)
7064 {
7065   htab_t types_htab = NULL;
7066   struct signatured_type **iter;
7067
7068   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
7069                                 rcuh_kind::COMPILE);
7070   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
7071   if (types_htab == NULL)
7072     {
7073       dwarf2_per_objfile->signatured_types = NULL;
7074       return 0;
7075     }
7076
7077   dwarf2_per_objfile->signatured_types = types_htab;
7078
7079   dwarf2_per_objfile->n_type_units
7080     = dwarf2_per_objfile->n_allocated_type_units
7081     = htab_elements (types_htab);
7082   dwarf2_per_objfile->all_type_units =
7083     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7084   iter = &dwarf2_per_objfile->all_type_units[0];
7085   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7086   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7087               == dwarf2_per_objfile->n_type_units);
7088
7089   return 1;
7090 }
7091
7092 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7093    If SLOT is non-NULL, it is the entry to use in the hash table.
7094    Otherwise we find one.  */
7095
7096 static struct signatured_type *
7097 add_type_unit (ULONGEST sig, void **slot)
7098 {
7099   struct objfile *objfile = dwarf2_per_objfile->objfile;
7100   int n_type_units = dwarf2_per_objfile->n_type_units;
7101   struct signatured_type *sig_type;
7102
7103   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7104   ++n_type_units;
7105   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7106     {
7107       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7108         dwarf2_per_objfile->n_allocated_type_units = 1;
7109       dwarf2_per_objfile->n_allocated_type_units *= 2;
7110       dwarf2_per_objfile->all_type_units
7111         = XRESIZEVEC (struct signatured_type *,
7112                       dwarf2_per_objfile->all_type_units,
7113                       dwarf2_per_objfile->n_allocated_type_units);
7114       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7115     }
7116   dwarf2_per_objfile->n_type_units = n_type_units;
7117
7118   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7119                              struct signatured_type);
7120   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7121   sig_type->signature = sig;
7122   sig_type->per_cu.is_debug_types = 1;
7123   if (dwarf2_per_objfile->using_index)
7124     {
7125       sig_type->per_cu.v.quick =
7126         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7127                         struct dwarf2_per_cu_quick_data);
7128     }
7129
7130   if (slot == NULL)
7131     {
7132       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7133                              sig_type, INSERT);
7134     }
7135   gdb_assert (*slot == NULL);
7136   *slot = sig_type;
7137   /* The rest of sig_type must be filled in by the caller.  */
7138   return sig_type;
7139 }
7140
7141 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7142    Fill in SIG_ENTRY with DWO_ENTRY.  */
7143
7144 static void
7145 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
7146                                   struct signatured_type *sig_entry,
7147                                   struct dwo_unit *dwo_entry)
7148 {
7149   /* Make sure we're not clobbering something we don't expect to.  */
7150   gdb_assert (! sig_entry->per_cu.queued);
7151   gdb_assert (sig_entry->per_cu.cu == NULL);
7152   if (dwarf2_per_objfile->using_index)
7153     {
7154       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7155       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7156     }
7157   else
7158       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7159   gdb_assert (sig_entry->signature == dwo_entry->signature);
7160   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7161   gdb_assert (sig_entry->type_unit_group == NULL);
7162   gdb_assert (sig_entry->dwo_unit == NULL);
7163
7164   sig_entry->per_cu.section = dwo_entry->section;
7165   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7166   sig_entry->per_cu.length = dwo_entry->length;
7167   sig_entry->per_cu.reading_dwo_directly = 1;
7168   sig_entry->per_cu.objfile = objfile;
7169   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7170   sig_entry->dwo_unit = dwo_entry;
7171 }
7172
7173 /* Subroutine of lookup_signatured_type.
7174    If we haven't read the TU yet, create the signatured_type data structure
7175    for a TU to be read in directly from a DWO file, bypassing the stub.
7176    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7177    using .gdb_index, then when reading a CU we want to stay in the DWO file
7178    containing that CU.  Otherwise we could end up reading several other DWO
7179    files (due to comdat folding) to process the transitive closure of all the
7180    mentioned TUs, and that can be slow.  The current DWO file will have every
7181    type signature that it needs.
7182    We only do this for .gdb_index because in the psymtab case we already have
7183    to read all the DWOs to build the type unit groups.  */
7184
7185 static struct signatured_type *
7186 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7187 {
7188   struct objfile *objfile = dwarf2_per_objfile->objfile;
7189   struct dwo_file *dwo_file;
7190   struct dwo_unit find_dwo_entry, *dwo_entry;
7191   struct signatured_type find_sig_entry, *sig_entry;
7192   void **slot;
7193
7194   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7195
7196   /* If TU skeletons have been removed then we may not have read in any
7197      TUs yet.  */
7198   if (dwarf2_per_objfile->signatured_types == NULL)
7199     {
7200       dwarf2_per_objfile->signatured_types
7201         = allocate_signatured_type_table (objfile);
7202     }
7203
7204   /* We only ever need to read in one copy of a signatured type.
7205      Use the global signatured_types array to do our own comdat-folding
7206      of types.  If this is the first time we're reading this TU, and
7207      the TU has an entry in .gdb_index, replace the recorded data from
7208      .gdb_index with this TU.  */
7209
7210   find_sig_entry.signature = sig;
7211   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7212                          &find_sig_entry, INSERT);
7213   sig_entry = (struct signatured_type *) *slot;
7214
7215   /* We can get here with the TU already read, *or* in the process of being
7216      read.  Don't reassign the global entry to point to this DWO if that's
7217      the case.  Also note that if the TU is already being read, it may not
7218      have come from a DWO, the program may be a mix of Fission-compiled
7219      code and non-Fission-compiled code.  */
7220
7221   /* Have we already tried to read this TU?
7222      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7223      needn't exist in the global table yet).  */
7224   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7225     return sig_entry;
7226
7227   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7228      dwo_unit of the TU itself.  */
7229   dwo_file = cu->dwo_unit->dwo_file;
7230
7231   /* Ok, this is the first time we're reading this TU.  */
7232   if (dwo_file->tus == NULL)
7233     return NULL;
7234   find_dwo_entry.signature = sig;
7235   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7236   if (dwo_entry == NULL)
7237     return NULL;
7238
7239   /* If the global table doesn't have an entry for this TU, add one.  */
7240   if (sig_entry == NULL)
7241     sig_entry = add_type_unit (sig, slot);
7242
7243   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
7244   sig_entry->per_cu.tu_read = 1;
7245   return sig_entry;
7246 }
7247
7248 /* Subroutine of lookup_signatured_type.
7249    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7250    then try the DWP file.  If the TU stub (skeleton) has been removed then
7251    it won't be in .gdb_index.  */
7252
7253 static struct signatured_type *
7254 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7255 {
7256   struct objfile *objfile = dwarf2_per_objfile->objfile;
7257   struct dwp_file *dwp_file = get_dwp_file ();
7258   struct dwo_unit *dwo_entry;
7259   struct signatured_type find_sig_entry, *sig_entry;
7260   void **slot;
7261
7262   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7263   gdb_assert (dwp_file != NULL);
7264
7265   /* If TU skeletons have been removed then we may not have read in any
7266      TUs yet.  */
7267   if (dwarf2_per_objfile->signatured_types == NULL)
7268     {
7269       dwarf2_per_objfile->signatured_types
7270         = allocate_signatured_type_table (objfile);
7271     }
7272
7273   find_sig_entry.signature = sig;
7274   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7275                          &find_sig_entry, INSERT);
7276   sig_entry = (struct signatured_type *) *slot;
7277
7278   /* Have we already tried to read this TU?
7279      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7280      needn't exist in the global table yet).  */
7281   if (sig_entry != NULL)
7282     return sig_entry;
7283
7284   if (dwp_file->tus == NULL)
7285     return NULL;
7286   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
7287                                       sig, 1 /* is_debug_types */);
7288   if (dwo_entry == NULL)
7289     return NULL;
7290
7291   sig_entry = add_type_unit (sig, slot);
7292   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
7293
7294   return sig_entry;
7295 }
7296
7297 /* Lookup a signature based type for DW_FORM_ref_sig8.
7298    Returns NULL if signature SIG is not present in the table.
7299    It is up to the caller to complain about this.  */
7300
7301 static struct signatured_type *
7302 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7303 {
7304   if (cu->dwo_unit
7305       && dwarf2_per_objfile->using_index)
7306     {
7307       /* We're in a DWO/DWP file, and we're using .gdb_index.
7308          These cases require special processing.  */
7309       if (get_dwp_file () == NULL)
7310         return lookup_dwo_signatured_type (cu, sig);
7311       else
7312         return lookup_dwp_signatured_type (cu, sig);
7313     }
7314   else
7315     {
7316       struct signatured_type find_entry, *entry;
7317
7318       if (dwarf2_per_objfile->signatured_types == NULL)
7319         return NULL;
7320       find_entry.signature = sig;
7321       entry = ((struct signatured_type *)
7322                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7323       return entry;
7324     }
7325 }
7326 \f
7327 /* Low level DIE reading support.  */
7328
7329 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7330
7331 static void
7332 init_cu_die_reader (struct die_reader_specs *reader,
7333                     struct dwarf2_cu *cu,
7334                     struct dwarf2_section_info *section,
7335                     struct dwo_file *dwo_file)
7336 {
7337   gdb_assert (section->readin && section->buffer != NULL);
7338   reader->abfd = get_section_bfd_owner (section);
7339   reader->cu = cu;
7340   reader->dwo_file = dwo_file;
7341   reader->die_section = section;
7342   reader->buffer = section->buffer;
7343   reader->buffer_end = section->buffer + section->size;
7344   reader->comp_dir = NULL;
7345 }
7346
7347 /* Subroutine of init_cutu_and_read_dies to simplify it.
7348    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7349    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7350    already.
7351
7352    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7353    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7354    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7355    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7356    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7357    STUB_COMP_DIR may be non-NULL.
7358    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7359    are filled in with the info of the DIE from the DWO file.
7360    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
7361    provided an abbrev table to use.
7362    The result is non-zero if a valid (non-dummy) DIE was found.  */
7363
7364 static int
7365 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7366                         struct dwo_unit *dwo_unit,
7367                         int abbrev_table_provided,
7368                         struct die_info *stub_comp_unit_die,
7369                         const char *stub_comp_dir,
7370                         struct die_reader_specs *result_reader,
7371                         const gdb_byte **result_info_ptr,
7372                         struct die_info **result_comp_unit_die,
7373                         int *result_has_children)
7374 {
7375   struct objfile *objfile = dwarf2_per_objfile->objfile;
7376   struct dwarf2_cu *cu = this_cu->cu;
7377   struct dwarf2_section_info *section;
7378   bfd *abfd;
7379   const gdb_byte *begin_info_ptr, *info_ptr;
7380   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7381   int i,num_extra_attrs;
7382   struct dwarf2_section_info *dwo_abbrev_section;
7383   struct attribute *attr;
7384   struct die_info *comp_unit_die;
7385
7386   /* At most one of these may be provided.  */
7387   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7388
7389   /* These attributes aren't processed until later:
7390      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7391      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7392      referenced later.  However, these attributes are found in the stub
7393      which we won't have later.  In order to not impose this complication
7394      on the rest of the code, we read them here and copy them to the
7395      DWO CU/TU die.  */
7396
7397   stmt_list = NULL;
7398   low_pc = NULL;
7399   high_pc = NULL;
7400   ranges = NULL;
7401   comp_dir = NULL;
7402
7403   if (stub_comp_unit_die != NULL)
7404     {
7405       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7406          DWO file.  */
7407       if (! this_cu->is_debug_types)
7408         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7409       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7410       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7411       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7412       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7413
7414       /* There should be a DW_AT_addr_base attribute here (if needed).
7415          We need the value before we can process DW_FORM_GNU_addr_index.  */
7416       cu->addr_base = 0;
7417       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7418       if (attr)
7419         cu->addr_base = DW_UNSND (attr);
7420
7421       /* There should be a DW_AT_ranges_base attribute here (if needed).
7422          We need the value before we can process DW_AT_ranges.  */
7423       cu->ranges_base = 0;
7424       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7425       if (attr)
7426         cu->ranges_base = DW_UNSND (attr);
7427     }
7428   else if (stub_comp_dir != NULL)
7429     {
7430       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7431       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7432       comp_dir->name = DW_AT_comp_dir;
7433       comp_dir->form = DW_FORM_string;
7434       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7435       DW_STRING (comp_dir) = stub_comp_dir;
7436     }
7437
7438   /* Set up for reading the DWO CU/TU.  */
7439   cu->dwo_unit = dwo_unit;
7440   section = dwo_unit->section;
7441   dwarf2_read_section (objfile, section);
7442   abfd = get_section_bfd_owner (section);
7443   begin_info_ptr = info_ptr = (section->buffer
7444                                + to_underlying (dwo_unit->sect_off));
7445   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7446   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
7447
7448   if (this_cu->is_debug_types)
7449     {
7450       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7451
7452       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7453                                                 dwo_abbrev_section,
7454                                                 info_ptr, rcuh_kind::TYPE);
7455       /* This is not an assert because it can be caused by bad debug info.  */
7456       if (sig_type->signature != cu->header.signature)
7457         {
7458           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7459                    " TU at offset 0x%x [in module %s]"),
7460                  hex_string (sig_type->signature),
7461                  hex_string (cu->header.signature),
7462                  to_underlying (dwo_unit->sect_off),
7463                  bfd_get_filename (abfd));
7464         }
7465       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7466       /* For DWOs coming from DWP files, we don't know the CU length
7467          nor the type's offset in the TU until now.  */
7468       dwo_unit->length = get_cu_length (&cu->header);
7469       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7470
7471       /* Establish the type offset that can be used to lookup the type.
7472          For DWO files, we don't know it until now.  */
7473       sig_type->type_offset_in_section
7474         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7475     }
7476   else
7477     {
7478       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7479                                                 dwo_abbrev_section,
7480                                                 info_ptr, rcuh_kind::COMPILE);
7481       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7482       /* For DWOs coming from DWP files, we don't know the CU length
7483          until now.  */
7484       dwo_unit->length = get_cu_length (&cu->header);
7485     }
7486
7487   /* Replace the CU's original abbrev table with the DWO's.
7488      Reminder: We can't read the abbrev table until we've read the header.  */
7489   if (abbrev_table_provided)
7490     {
7491       /* Don't free the provided abbrev table, the caller of
7492          init_cutu_and_read_dies owns it.  */
7493       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7494       /* Ensure the DWO abbrev table gets freed.  */
7495       make_cleanup (dwarf2_free_abbrev_table, cu);
7496     }
7497   else
7498     {
7499       dwarf2_free_abbrev_table (cu);
7500       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7501       /* Leave any existing abbrev table cleanup as is.  */
7502     }
7503
7504   /* Read in the die, but leave space to copy over the attributes
7505      from the stub.  This has the benefit of simplifying the rest of
7506      the code - all the work to maintain the illusion of a single
7507      DW_TAG_{compile,type}_unit DIE is done here.  */
7508   num_extra_attrs = ((stmt_list != NULL)
7509                      + (low_pc != NULL)
7510                      + (high_pc != NULL)
7511                      + (ranges != NULL)
7512                      + (comp_dir != NULL));
7513   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7514                               result_has_children, num_extra_attrs);
7515
7516   /* Copy over the attributes from the stub to the DIE we just read in.  */
7517   comp_unit_die = *result_comp_unit_die;
7518   i = comp_unit_die->num_attrs;
7519   if (stmt_list != NULL)
7520     comp_unit_die->attrs[i++] = *stmt_list;
7521   if (low_pc != NULL)
7522     comp_unit_die->attrs[i++] = *low_pc;
7523   if (high_pc != NULL)
7524     comp_unit_die->attrs[i++] = *high_pc;
7525   if (ranges != NULL)
7526     comp_unit_die->attrs[i++] = *ranges;
7527   if (comp_dir != NULL)
7528     comp_unit_die->attrs[i++] = *comp_dir;
7529   comp_unit_die->num_attrs += num_extra_attrs;
7530
7531   if (dwarf_die_debug)
7532     {
7533       fprintf_unfiltered (gdb_stdlog,
7534                           "Read die from %s@0x%x of %s:\n",
7535                           get_section_name (section),
7536                           (unsigned) (begin_info_ptr - section->buffer),
7537                           bfd_get_filename (abfd));
7538       dump_die (comp_unit_die, dwarf_die_debug);
7539     }
7540
7541   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7542      TUs by skipping the stub and going directly to the entry in the DWO file.
7543      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7544      to get it via circuitous means.  Blech.  */
7545   if (comp_dir != NULL)
7546     result_reader->comp_dir = DW_STRING (comp_dir);
7547
7548   /* Skip dummy compilation units.  */
7549   if (info_ptr >= begin_info_ptr + dwo_unit->length
7550       || peek_abbrev_code (abfd, info_ptr) == 0)
7551     return 0;
7552
7553   *result_info_ptr = info_ptr;
7554   return 1;
7555 }
7556
7557 /* Subroutine of init_cutu_and_read_dies to simplify it.
7558    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7559    Returns NULL if the specified DWO unit cannot be found.  */
7560
7561 static struct dwo_unit *
7562 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7563                  struct die_info *comp_unit_die)
7564 {
7565   struct dwarf2_cu *cu = this_cu->cu;
7566   ULONGEST signature;
7567   struct dwo_unit *dwo_unit;
7568   const char *comp_dir, *dwo_name;
7569
7570   gdb_assert (cu != NULL);
7571
7572   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7573   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7574   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7575
7576   if (this_cu->is_debug_types)
7577     {
7578       struct signatured_type *sig_type;
7579
7580       /* Since this_cu is the first member of struct signatured_type,
7581          we can go from a pointer to one to a pointer to the other.  */
7582       sig_type = (struct signatured_type *) this_cu;
7583       signature = sig_type->signature;
7584       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7585     }
7586   else
7587     {
7588       struct attribute *attr;
7589
7590       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7591       if (! attr)
7592         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7593                  " [in module %s]"),
7594                dwo_name, objfile_name (this_cu->objfile));
7595       signature = DW_UNSND (attr);
7596       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7597                                        signature);
7598     }
7599
7600   return dwo_unit;
7601 }
7602
7603 /* Subroutine of init_cutu_and_read_dies to simplify it.
7604    See it for a description of the parameters.
7605    Read a TU directly from a DWO file, bypassing the stub.
7606
7607    Note: This function could be a little bit simpler if we shared cleanups
7608    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
7609    to do, so we keep this function self-contained.  Or we could move this
7610    into our caller, but it's complex enough already.  */
7611
7612 static void
7613 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7614                            int use_existing_cu, int keep,
7615                            die_reader_func_ftype *die_reader_func,
7616                            void *data)
7617 {
7618   struct dwarf2_cu *cu;
7619   struct signatured_type *sig_type;
7620   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7621   struct die_reader_specs reader;
7622   const gdb_byte *info_ptr;
7623   struct die_info *comp_unit_die;
7624   int has_children;
7625
7626   /* Verify we can do the following downcast, and that we have the
7627      data we need.  */
7628   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7629   sig_type = (struct signatured_type *) this_cu;
7630   gdb_assert (sig_type->dwo_unit != NULL);
7631
7632   cleanups = make_cleanup (null_cleanup, NULL);
7633
7634   if (use_existing_cu && this_cu->cu != NULL)
7635     {
7636       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7637       cu = this_cu->cu;
7638       /* There's no need to do the rereading_dwo_cu handling that
7639          init_cutu_and_read_dies does since we don't read the stub.  */
7640     }
7641   else
7642     {
7643       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7644       gdb_assert (this_cu->cu == NULL);
7645       cu = XNEW (struct dwarf2_cu);
7646       init_one_comp_unit (cu, this_cu);
7647       /* If an error occurs while loading, release our storage.  */
7648       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7649     }
7650
7651   /* A future optimization, if needed, would be to use an existing
7652      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7653      could share abbrev tables.  */
7654
7655   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7656                               0 /* abbrev_table_provided */,
7657                               NULL /* stub_comp_unit_die */,
7658                               sig_type->dwo_unit->dwo_file->comp_dir,
7659                               &reader, &info_ptr,
7660                               &comp_unit_die, &has_children) == 0)
7661     {
7662       /* Dummy die.  */
7663       do_cleanups (cleanups);
7664       return;
7665     }
7666
7667   /* All the "real" work is done here.  */
7668   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7669
7670   /* This duplicates the code in init_cutu_and_read_dies,
7671      but the alternative is making the latter more complex.
7672      This function is only for the special case of using DWO files directly:
7673      no point in overly complicating the general case just to handle this.  */
7674   if (free_cu_cleanup != NULL)
7675     {
7676       if (keep)
7677         {
7678           /* We've successfully allocated this compilation unit.  Let our
7679              caller clean it up when finished with it.  */
7680           discard_cleanups (free_cu_cleanup);
7681
7682           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7683              So we have to manually free the abbrev table.  */
7684           dwarf2_free_abbrev_table (cu);
7685
7686           /* Link this CU into read_in_chain.  */
7687           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7688           dwarf2_per_objfile->read_in_chain = this_cu;
7689         }
7690       else
7691         do_cleanups (free_cu_cleanup);
7692     }
7693
7694   do_cleanups (cleanups);
7695 }
7696
7697 /* Initialize a CU (or TU) and read its DIEs.
7698    If the CU defers to a DWO file, read the DWO file as well.
7699
7700    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7701    Otherwise the table specified in the comp unit header is read in and used.
7702    This is an optimization for when we already have the abbrev table.
7703
7704    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7705    Otherwise, a new CU is allocated with xmalloc.
7706
7707    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7708    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7709
7710    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7711    linker) then DIE_READER_FUNC will not get called.  */
7712
7713 static void
7714 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7715                          struct abbrev_table *abbrev_table,
7716                          int use_existing_cu, int keep,
7717                          die_reader_func_ftype *die_reader_func,
7718                          void *data)
7719 {
7720   struct objfile *objfile = dwarf2_per_objfile->objfile;
7721   struct dwarf2_section_info *section = this_cu->section;
7722   bfd *abfd = get_section_bfd_owner (section);
7723   struct dwarf2_cu *cu;
7724   const gdb_byte *begin_info_ptr, *info_ptr;
7725   struct die_reader_specs reader;
7726   struct die_info *comp_unit_die;
7727   int has_children;
7728   struct attribute *attr;
7729   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7730   struct signatured_type *sig_type = NULL;
7731   struct dwarf2_section_info *abbrev_section;
7732   /* Non-zero if CU currently points to a DWO file and we need to
7733      reread it.  When this happens we need to reread the skeleton die
7734      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7735   int rereading_dwo_cu = 0;
7736
7737   if (dwarf_die_debug)
7738     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7739                         this_cu->is_debug_types ? "type" : "comp",
7740                         to_underlying (this_cu->sect_off));
7741
7742   if (use_existing_cu)
7743     gdb_assert (keep);
7744
7745   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7746      file (instead of going through the stub), short-circuit all of this.  */
7747   if (this_cu->reading_dwo_directly)
7748     {
7749       /* Narrow down the scope of possibilities to have to understand.  */
7750       gdb_assert (this_cu->is_debug_types);
7751       gdb_assert (abbrev_table == NULL);
7752       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7753                                  die_reader_func, data);
7754       return;
7755     }
7756
7757   cleanups = make_cleanup (null_cleanup, NULL);
7758
7759   /* This is cheap if the section is already read in.  */
7760   dwarf2_read_section (objfile, section);
7761
7762   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7763
7764   abbrev_section = get_abbrev_section_for_cu (this_cu);
7765
7766   if (use_existing_cu && this_cu->cu != NULL)
7767     {
7768       cu = this_cu->cu;
7769       /* If this CU is from a DWO file we need to start over, we need to
7770          refetch the attributes from the skeleton CU.
7771          This could be optimized by retrieving those attributes from when we
7772          were here the first time: the previous comp_unit_die was stored in
7773          comp_unit_obstack.  But there's no data yet that we need this
7774          optimization.  */
7775       if (cu->dwo_unit != NULL)
7776         rereading_dwo_cu = 1;
7777     }
7778   else
7779     {
7780       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7781       gdb_assert (this_cu->cu == NULL);
7782       cu = XNEW (struct dwarf2_cu);
7783       init_one_comp_unit (cu, this_cu);
7784       /* If an error occurs while loading, release our storage.  */
7785       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7786     }
7787
7788   /* Get the header.  */
7789   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7790     {
7791       /* We already have the header, there's no need to read it in again.  */
7792       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7793     }
7794   else
7795     {
7796       if (this_cu->is_debug_types)
7797         {
7798           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7799                                                     abbrev_section, info_ptr,
7800                                                     rcuh_kind::TYPE);
7801
7802           /* Since per_cu is the first member of struct signatured_type,
7803              we can go from a pointer to one to a pointer to the other.  */
7804           sig_type = (struct signatured_type *) this_cu;
7805           gdb_assert (sig_type->signature == cu->header.signature);
7806           gdb_assert (sig_type->type_offset_in_tu
7807                       == cu->header.type_cu_offset_in_tu);
7808           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7809
7810           /* LENGTH has not been set yet for type units if we're
7811              using .gdb_index.  */
7812           this_cu->length = get_cu_length (&cu->header);
7813
7814           /* Establish the type offset that can be used to lookup the type.  */
7815           sig_type->type_offset_in_section =
7816             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7817
7818           this_cu->dwarf_version = cu->header.version;
7819         }
7820       else
7821         {
7822           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7823                                                     abbrev_section,
7824                                                     info_ptr,
7825                                                     rcuh_kind::COMPILE);
7826
7827           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7828           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7829           this_cu->dwarf_version = cu->header.version;
7830         }
7831     }
7832
7833   /* Skip dummy compilation units.  */
7834   if (info_ptr >= begin_info_ptr + this_cu->length
7835       || peek_abbrev_code (abfd, info_ptr) == 0)
7836     {
7837       do_cleanups (cleanups);
7838       return;
7839     }
7840
7841   /* If we don't have them yet, read the abbrevs for this compilation unit.
7842      And if we need to read them now, make sure they're freed when we're
7843      done.  Note that it's important that if the CU had an abbrev table
7844      on entry we don't free it when we're done: Somewhere up the call stack
7845      it may be in use.  */
7846   if (abbrev_table != NULL)
7847     {
7848       gdb_assert (cu->abbrev_table == NULL);
7849       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7850       cu->abbrev_table = abbrev_table;
7851     }
7852   else if (cu->abbrev_table == NULL)
7853     {
7854       dwarf2_read_abbrevs (cu, abbrev_section);
7855       make_cleanup (dwarf2_free_abbrev_table, cu);
7856     }
7857   else if (rereading_dwo_cu)
7858     {
7859       dwarf2_free_abbrev_table (cu);
7860       dwarf2_read_abbrevs (cu, abbrev_section);
7861     }
7862
7863   /* Read the top level CU/TU die.  */
7864   init_cu_die_reader (&reader, cu, section, NULL);
7865   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7866
7867   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7868      from the DWO file.
7869      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7870      DWO CU, that this test will fail (the attribute will not be present).  */
7871   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7872   if (attr)
7873     {
7874       struct dwo_unit *dwo_unit;
7875       struct die_info *dwo_comp_unit_die;
7876
7877       if (has_children)
7878         {
7879           complaint (&symfile_complaints,
7880                      _("compilation unit with DW_AT_GNU_dwo_name"
7881                        " has children (offset 0x%x) [in module %s]"),
7882                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7883         }
7884       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7885       if (dwo_unit != NULL)
7886         {
7887           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7888                                       abbrev_table != NULL,
7889                                       comp_unit_die, NULL,
7890                                       &reader, &info_ptr,
7891                                       &dwo_comp_unit_die, &has_children) == 0)
7892             {
7893               /* Dummy die.  */
7894               do_cleanups (cleanups);
7895               return;
7896             }
7897           comp_unit_die = dwo_comp_unit_die;
7898         }
7899       else
7900         {
7901           /* Yikes, we couldn't find the rest of the DIE, we only have
7902              the stub.  A complaint has already been logged.  There's
7903              not much more we can do except pass on the stub DIE to
7904              die_reader_func.  We don't want to throw an error on bad
7905              debug info.  */
7906         }
7907     }
7908
7909   /* All of the above is setup for this call.  Yikes.  */
7910   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7911
7912   /* Done, clean up.  */
7913   if (free_cu_cleanup != NULL)
7914     {
7915       if (keep)
7916         {
7917           /* We've successfully allocated this compilation unit.  Let our
7918              caller clean it up when finished with it.  */
7919           discard_cleanups (free_cu_cleanup);
7920
7921           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7922              So we have to manually free the abbrev table.  */
7923           dwarf2_free_abbrev_table (cu);
7924
7925           /* Link this CU into read_in_chain.  */
7926           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7927           dwarf2_per_objfile->read_in_chain = this_cu;
7928         }
7929       else
7930         do_cleanups (free_cu_cleanup);
7931     }
7932
7933   do_cleanups (cleanups);
7934 }
7935
7936 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7937    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7938    to have already done the lookup to find the DWO file).
7939
7940    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7941    THIS_CU->is_debug_types, but nothing else.
7942
7943    We fill in THIS_CU->length.
7944
7945    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7946    linker) then DIE_READER_FUNC will not get called.
7947
7948    THIS_CU->cu is always freed when done.
7949    This is done in order to not leave THIS_CU->cu in a state where we have
7950    to care whether it refers to the "main" CU or the DWO CU.  */
7951
7952 static void
7953 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7954                                    struct dwo_file *dwo_file,
7955                                    die_reader_func_ftype *die_reader_func,
7956                                    void *data)
7957 {
7958   struct objfile *objfile = dwarf2_per_objfile->objfile;
7959   struct dwarf2_section_info *section = this_cu->section;
7960   bfd *abfd = get_section_bfd_owner (section);
7961   struct dwarf2_section_info *abbrev_section;
7962   struct dwarf2_cu cu;
7963   const gdb_byte *begin_info_ptr, *info_ptr;
7964   struct die_reader_specs reader;
7965   struct cleanup *cleanups;
7966   struct die_info *comp_unit_die;
7967   int has_children;
7968
7969   if (dwarf_die_debug)
7970     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7971                         this_cu->is_debug_types ? "type" : "comp",
7972                         to_underlying (this_cu->sect_off));
7973
7974   gdb_assert (this_cu->cu == NULL);
7975
7976   abbrev_section = (dwo_file != NULL
7977                     ? &dwo_file->sections.abbrev
7978                     : get_abbrev_section_for_cu (this_cu));
7979
7980   /* This is cheap if the section is already read in.  */
7981   dwarf2_read_section (objfile, section);
7982
7983   init_one_comp_unit (&cu, this_cu);
7984
7985   cleanups = make_cleanup (free_stack_comp_unit, &cu);
7986
7987   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7988   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
7989                                             abbrev_section, info_ptr,
7990                                             (this_cu->is_debug_types
7991                                              ? rcuh_kind::TYPE
7992                                              : rcuh_kind::COMPILE));
7993
7994   this_cu->length = get_cu_length (&cu.header);
7995
7996   /* Skip dummy compilation units.  */
7997   if (info_ptr >= begin_info_ptr + this_cu->length
7998       || peek_abbrev_code (abfd, info_ptr) == 0)
7999     {
8000       do_cleanups (cleanups);
8001       return;
8002     }
8003
8004   dwarf2_read_abbrevs (&cu, abbrev_section);
8005   make_cleanup (dwarf2_free_abbrev_table, &cu);
8006
8007   init_cu_die_reader (&reader, &cu, section, dwo_file);
8008   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8009
8010   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8011
8012   do_cleanups (cleanups);
8013 }
8014
8015 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8016    does not lookup the specified DWO file.
8017    This cannot be used to read DWO files.
8018
8019    THIS_CU->cu is always freed when done.
8020    This is done in order to not leave THIS_CU->cu in a state where we have
8021    to care whether it refers to the "main" CU or the DWO CU.
8022    We can revisit this if the data shows there's a performance issue.  */
8023
8024 static void
8025 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8026                                 die_reader_func_ftype *die_reader_func,
8027                                 void *data)
8028 {
8029   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8030 }
8031 \f
8032 /* Type Unit Groups.
8033
8034    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8035    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8036    so that all types coming from the same compilation (.o file) are grouped
8037    together.  A future step could be to put the types in the same symtab as
8038    the CU the types ultimately came from.  */
8039
8040 static hashval_t
8041 hash_type_unit_group (const void *item)
8042 {
8043   const struct type_unit_group *tu_group
8044     = (const struct type_unit_group *) item;
8045
8046   return hash_stmt_list_entry (&tu_group->hash);
8047 }
8048
8049 static int
8050 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8051 {
8052   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8053   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8054
8055   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8056 }
8057
8058 /* Allocate a hash table for type unit groups.  */
8059
8060 static htab_t
8061 allocate_type_unit_groups_table (void)
8062 {
8063   return htab_create_alloc_ex (3,
8064                                hash_type_unit_group,
8065                                eq_type_unit_group,
8066                                NULL,
8067                                &dwarf2_per_objfile->objfile->objfile_obstack,
8068                                hashtab_obstack_allocate,
8069                                dummy_obstack_deallocate);
8070 }
8071
8072 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8073    partial symtabs.  We combine several TUs per psymtab to not let the size
8074    of any one psymtab grow too big.  */
8075 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8076 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8077
8078 /* Helper routine for get_type_unit_group.
8079    Create the type_unit_group object used to hold one or more TUs.  */
8080
8081 static struct type_unit_group *
8082 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8083 {
8084   struct objfile *objfile = dwarf2_per_objfile->objfile;
8085   struct dwarf2_per_cu_data *per_cu;
8086   struct type_unit_group *tu_group;
8087
8088   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8089                              struct type_unit_group);
8090   per_cu = &tu_group->per_cu;
8091   per_cu->objfile = objfile;
8092
8093   if (dwarf2_per_objfile->using_index)
8094     {
8095       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8096                                         struct dwarf2_per_cu_quick_data);
8097     }
8098   else
8099     {
8100       unsigned int line_offset = to_underlying (line_offset_struct);
8101       struct partial_symtab *pst;
8102       char *name;
8103
8104       /* Give the symtab a useful name for debug purposes.  */
8105       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8106         name = xstrprintf ("<type_units_%d>",
8107                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8108       else
8109         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8110
8111       pst = create_partial_symtab (per_cu, name);
8112       pst->anonymous = 1;
8113
8114       xfree (name);
8115     }
8116
8117   tu_group->hash.dwo_unit = cu->dwo_unit;
8118   tu_group->hash.line_sect_off = line_offset_struct;
8119
8120   return tu_group;
8121 }
8122
8123 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8124    STMT_LIST is a DW_AT_stmt_list attribute.  */
8125
8126 static struct type_unit_group *
8127 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8128 {
8129   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8130   struct type_unit_group *tu_group;
8131   void **slot;
8132   unsigned int line_offset;
8133   struct type_unit_group type_unit_group_for_lookup;
8134
8135   if (dwarf2_per_objfile->type_unit_groups == NULL)
8136     {
8137       dwarf2_per_objfile->type_unit_groups =
8138         allocate_type_unit_groups_table ();
8139     }
8140
8141   /* Do we need to create a new group, or can we use an existing one?  */
8142
8143   if (stmt_list)
8144     {
8145       line_offset = DW_UNSND (stmt_list);
8146       ++tu_stats->nr_symtab_sharers;
8147     }
8148   else
8149     {
8150       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8151          We can do various things here like create one group per TU or
8152          spread them over multiple groups to split up the expansion work.
8153          To avoid worst case scenarios (too many groups or too large groups)
8154          we, umm, group them in bunches.  */
8155       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8156                      | (tu_stats->nr_stmt_less_type_units
8157                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8158       ++tu_stats->nr_stmt_less_type_units;
8159     }
8160
8161   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8162   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8163   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8164                          &type_unit_group_for_lookup, INSERT);
8165   if (*slot != NULL)
8166     {
8167       tu_group = (struct type_unit_group *) *slot;
8168       gdb_assert (tu_group != NULL);
8169     }
8170   else
8171     {
8172       sect_offset line_offset_struct = (sect_offset) line_offset;
8173       tu_group = create_type_unit_group (cu, line_offset_struct);
8174       *slot = tu_group;
8175       ++tu_stats->nr_symtabs;
8176     }
8177
8178   return tu_group;
8179 }
8180 \f
8181 /* Partial symbol tables.  */
8182
8183 /* Create a psymtab named NAME and assign it to PER_CU.
8184
8185    The caller must fill in the following details:
8186    dirname, textlow, texthigh.  */
8187
8188 static struct partial_symtab *
8189 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8190 {
8191   struct objfile *objfile = per_cu->objfile;
8192   struct partial_symtab *pst;
8193
8194   pst = start_psymtab_common (objfile, name, 0,
8195                               objfile->global_psymbols,
8196                               objfile->static_psymbols);
8197
8198   pst->psymtabs_addrmap_supported = 1;
8199
8200   /* This is the glue that links PST into GDB's symbol API.  */
8201   pst->read_symtab_private = per_cu;
8202   pst->read_symtab = dwarf2_read_symtab;
8203   per_cu->v.psymtab = pst;
8204
8205   return pst;
8206 }
8207
8208 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8209    type.  */
8210
8211 struct process_psymtab_comp_unit_data
8212 {
8213   /* True if we are reading a DW_TAG_partial_unit.  */
8214
8215   int want_partial_unit;
8216
8217   /* The "pretend" language that is used if the CU doesn't declare a
8218      language.  */
8219
8220   enum language pretend_language;
8221 };
8222
8223 /* die_reader_func for process_psymtab_comp_unit.  */
8224
8225 static void
8226 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8227                                   const gdb_byte *info_ptr,
8228                                   struct die_info *comp_unit_die,
8229                                   int has_children,
8230                                   void *data)
8231 {
8232   struct dwarf2_cu *cu = reader->cu;
8233   struct objfile *objfile = cu->objfile;
8234   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8235   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8236   CORE_ADDR baseaddr;
8237   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8238   struct partial_symtab *pst;
8239   enum pc_bounds_kind cu_bounds_kind;
8240   const char *filename;
8241   struct process_psymtab_comp_unit_data *info
8242     = (struct process_psymtab_comp_unit_data *) data;
8243
8244   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8245     return;
8246
8247   gdb_assert (! per_cu->is_debug_types);
8248
8249   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8250
8251   cu->list_in_scope = &file_symbols;
8252
8253   /* Allocate a new partial symbol table structure.  */
8254   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8255   if (filename == NULL)
8256     filename = "";
8257
8258   pst = create_partial_symtab (per_cu, filename);
8259
8260   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8261   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8262
8263   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8264
8265   dwarf2_find_base_address (comp_unit_die, cu);
8266
8267   /* Possibly set the default values of LOWPC and HIGHPC from
8268      `DW_AT_ranges'.  */
8269   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8270                                          &best_highpc, cu, pst);
8271   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8272     /* Store the contiguous range if it is not empty; it can be empty for
8273        CUs with no code.  */
8274     addrmap_set_empty (objfile->psymtabs_addrmap,
8275                        gdbarch_adjust_dwarf2_addr (gdbarch,
8276                                                    best_lowpc + baseaddr),
8277                        gdbarch_adjust_dwarf2_addr (gdbarch,
8278                                                    best_highpc + baseaddr) - 1,
8279                        pst);
8280
8281   /* Check if comp unit has_children.
8282      If so, read the rest of the partial symbols from this comp unit.
8283      If not, there's no more debug_info for this comp unit.  */
8284   if (has_children)
8285     {
8286       struct partial_die_info *first_die;
8287       CORE_ADDR lowpc, highpc;
8288
8289       lowpc = ((CORE_ADDR) -1);
8290       highpc = ((CORE_ADDR) 0);
8291
8292       first_die = load_partial_dies (reader, info_ptr, 1);
8293
8294       scan_partial_symbols (first_die, &lowpc, &highpc,
8295                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8296
8297       /* If we didn't find a lowpc, set it to highpc to avoid
8298          complaints from `maint check'.  */
8299       if (lowpc == ((CORE_ADDR) -1))
8300         lowpc = highpc;
8301
8302       /* If the compilation unit didn't have an explicit address range,
8303          then use the information extracted from its child dies.  */
8304       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8305         {
8306           best_lowpc = lowpc;
8307           best_highpc = highpc;
8308         }
8309     }
8310   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8311   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8312
8313   end_psymtab_common (objfile, pst);
8314
8315   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8316     {
8317       int i;
8318       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8319       struct dwarf2_per_cu_data *iter;
8320
8321       /* Fill in 'dependencies' here; we fill in 'users' in a
8322          post-pass.  */
8323       pst->number_of_dependencies = len;
8324       pst->dependencies =
8325         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8326       for (i = 0;
8327            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8328                         i, iter);
8329            ++i)
8330         pst->dependencies[i] = iter->v.psymtab;
8331
8332       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8333     }
8334
8335   /* Get the list of files included in the current compilation unit,
8336      and build a psymtab for each of them.  */
8337   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8338
8339   if (dwarf_read_debug)
8340     {
8341       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8342
8343       fprintf_unfiltered (gdb_stdlog,
8344                           "Psymtab for %s unit @0x%x: %s - %s"
8345                           ", %d global, %d static syms\n",
8346                           per_cu->is_debug_types ? "type" : "comp",
8347                           to_underlying (per_cu->sect_off),
8348                           paddress (gdbarch, pst->textlow),
8349                           paddress (gdbarch, pst->texthigh),
8350                           pst->n_global_syms, pst->n_static_syms);
8351     }
8352 }
8353
8354 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8355    Process compilation unit THIS_CU for a psymtab.  */
8356
8357 static void
8358 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8359                            int want_partial_unit,
8360                            enum language pretend_language)
8361 {
8362   /* If this compilation unit was already read in, free the
8363      cached copy in order to read it in again.  This is
8364      necessary because we skipped some symbols when we first
8365      read in the compilation unit (see load_partial_dies).
8366      This problem could be avoided, but the benefit is unclear.  */
8367   if (this_cu->cu != NULL)
8368     free_one_cached_comp_unit (this_cu);
8369
8370   if (this_cu->is_debug_types)
8371     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8372                              NULL);
8373   else
8374     {
8375       process_psymtab_comp_unit_data info;
8376       info.want_partial_unit = want_partial_unit;
8377       info.pretend_language = pretend_language;
8378       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8379                                process_psymtab_comp_unit_reader, &info);
8380     }
8381
8382   /* Age out any secondary CUs.  */
8383   age_cached_comp_units ();
8384 }
8385
8386 /* Reader function for build_type_psymtabs.  */
8387
8388 static void
8389 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8390                             const gdb_byte *info_ptr,
8391                             struct die_info *type_unit_die,
8392                             int has_children,
8393                             void *data)
8394 {
8395   struct objfile *objfile = dwarf2_per_objfile->objfile;
8396   struct dwarf2_cu *cu = reader->cu;
8397   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8398   struct signatured_type *sig_type;
8399   struct type_unit_group *tu_group;
8400   struct attribute *attr;
8401   struct partial_die_info *first_die;
8402   CORE_ADDR lowpc, highpc;
8403   struct partial_symtab *pst;
8404
8405   gdb_assert (data == NULL);
8406   gdb_assert (per_cu->is_debug_types);
8407   sig_type = (struct signatured_type *) per_cu;
8408
8409   if (! has_children)
8410     return;
8411
8412   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8413   tu_group = get_type_unit_group (cu, attr);
8414
8415   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8416
8417   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8418   cu->list_in_scope = &file_symbols;
8419   pst = create_partial_symtab (per_cu, "");
8420   pst->anonymous = 1;
8421
8422   first_die = load_partial_dies (reader, info_ptr, 1);
8423
8424   lowpc = (CORE_ADDR) -1;
8425   highpc = (CORE_ADDR) 0;
8426   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8427
8428   end_psymtab_common (objfile, pst);
8429 }
8430
8431 /* Struct used to sort TUs by their abbreviation table offset.  */
8432
8433 struct tu_abbrev_offset
8434 {
8435   struct signatured_type *sig_type;
8436   sect_offset abbrev_offset;
8437 };
8438
8439 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8440
8441 static int
8442 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8443 {
8444   const struct tu_abbrev_offset * const *a
8445     = (const struct tu_abbrev_offset * const*) ap;
8446   const struct tu_abbrev_offset * const *b
8447     = (const struct tu_abbrev_offset * const*) bp;
8448   sect_offset aoff = (*a)->abbrev_offset;
8449   sect_offset boff = (*b)->abbrev_offset;
8450
8451   return (aoff > boff) - (aoff < boff);
8452 }
8453
8454 /* Efficiently read all the type units.
8455    This does the bulk of the work for build_type_psymtabs.
8456
8457    The efficiency is because we sort TUs by the abbrev table they use and
8458    only read each abbrev table once.  In one program there are 200K TUs
8459    sharing 8K abbrev tables.
8460
8461    The main purpose of this function is to support building the
8462    dwarf2_per_objfile->type_unit_groups table.
8463    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8464    can collapse the search space by grouping them by stmt_list.
8465    The savings can be significant, in the same program from above the 200K TUs
8466    share 8K stmt_list tables.
8467
8468    FUNC is expected to call get_type_unit_group, which will create the
8469    struct type_unit_group if necessary and add it to
8470    dwarf2_per_objfile->type_unit_groups.  */
8471
8472 static void
8473 build_type_psymtabs_1 (void)
8474 {
8475   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8476   struct cleanup *cleanups;
8477   struct abbrev_table *abbrev_table;
8478   sect_offset abbrev_offset;
8479   struct tu_abbrev_offset *sorted_by_abbrev;
8480   int i;
8481
8482   /* It's up to the caller to not call us multiple times.  */
8483   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8484
8485   if (dwarf2_per_objfile->n_type_units == 0)
8486     return;
8487
8488   /* TUs typically share abbrev tables, and there can be way more TUs than
8489      abbrev tables.  Sort by abbrev table to reduce the number of times we
8490      read each abbrev table in.
8491      Alternatives are to punt or to maintain a cache of abbrev tables.
8492      This is simpler and efficient enough for now.
8493
8494      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8495      symtab to use).  Typically TUs with the same abbrev offset have the same
8496      stmt_list value too so in practice this should work well.
8497
8498      The basic algorithm here is:
8499
8500       sort TUs by abbrev table
8501       for each TU with same abbrev table:
8502         read abbrev table if first user
8503         read TU top level DIE
8504           [IWBN if DWO skeletons had DW_AT_stmt_list]
8505         call FUNC  */
8506
8507   if (dwarf_read_debug)
8508     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8509
8510   /* Sort in a separate table to maintain the order of all_type_units
8511      for .gdb_index: TU indices directly index all_type_units.  */
8512   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8513                               dwarf2_per_objfile->n_type_units);
8514   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8515     {
8516       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8517
8518       sorted_by_abbrev[i].sig_type = sig_type;
8519       sorted_by_abbrev[i].abbrev_offset =
8520         read_abbrev_offset (sig_type->per_cu.section,
8521                             sig_type->per_cu.sect_off);
8522     }
8523   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8524   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8525          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8526
8527   abbrev_offset = (sect_offset) ~(unsigned) 0;
8528   abbrev_table = NULL;
8529   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
8530
8531   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8532     {
8533       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8534
8535       /* Switch to the next abbrev table if necessary.  */
8536       if (abbrev_table == NULL
8537           || tu->abbrev_offset != abbrev_offset)
8538         {
8539           if (abbrev_table != NULL)
8540             {
8541               abbrev_table_free (abbrev_table);
8542               /* Reset to NULL in case abbrev_table_read_table throws
8543                  an error: abbrev_table_free_cleanup will get called.  */
8544               abbrev_table = NULL;
8545             }
8546           abbrev_offset = tu->abbrev_offset;
8547           abbrev_table =
8548             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
8549                                      abbrev_offset);
8550           ++tu_stats->nr_uniq_abbrev_tables;
8551         }
8552
8553       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
8554                                build_type_psymtabs_reader, NULL);
8555     }
8556
8557   do_cleanups (cleanups);
8558 }
8559
8560 /* Print collected type unit statistics.  */
8561
8562 static void
8563 print_tu_stats (void)
8564 {
8565   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8566
8567   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8568   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8569                       dwarf2_per_objfile->n_type_units);
8570   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8571                       tu_stats->nr_uniq_abbrev_tables);
8572   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8573                       tu_stats->nr_symtabs);
8574   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8575                       tu_stats->nr_symtab_sharers);
8576   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8577                       tu_stats->nr_stmt_less_type_units);
8578   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8579                       tu_stats->nr_all_type_units_reallocs);
8580 }
8581
8582 /* Traversal function for build_type_psymtabs.  */
8583
8584 static int
8585 build_type_psymtab_dependencies (void **slot, void *info)
8586 {
8587   struct objfile *objfile = dwarf2_per_objfile->objfile;
8588   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8589   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8590   struct partial_symtab *pst = per_cu->v.psymtab;
8591   int len = VEC_length (sig_type_ptr, tu_group->tus);
8592   struct signatured_type *iter;
8593   int i;
8594
8595   gdb_assert (len > 0);
8596   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8597
8598   pst->number_of_dependencies = len;
8599   pst->dependencies =
8600     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8601   for (i = 0;
8602        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8603        ++i)
8604     {
8605       gdb_assert (iter->per_cu.is_debug_types);
8606       pst->dependencies[i] = iter->per_cu.v.psymtab;
8607       iter->type_unit_group = tu_group;
8608     }
8609
8610   VEC_free (sig_type_ptr, tu_group->tus);
8611
8612   return 1;
8613 }
8614
8615 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8616    Build partial symbol tables for the .debug_types comp-units.  */
8617
8618 static void
8619 build_type_psymtabs (struct objfile *objfile)
8620 {
8621   if (! create_all_type_units (objfile))
8622     return;
8623
8624   build_type_psymtabs_1 ();
8625 }
8626
8627 /* Traversal function for process_skeletonless_type_unit.
8628    Read a TU in a DWO file and build partial symbols for it.  */
8629
8630 static int
8631 process_skeletonless_type_unit (void **slot, void *info)
8632 {
8633   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8634   struct objfile *objfile = (struct objfile *) info;
8635   struct signatured_type find_entry, *entry;
8636
8637   /* If this TU doesn't exist in the global table, add it and read it in.  */
8638
8639   if (dwarf2_per_objfile->signatured_types == NULL)
8640     {
8641       dwarf2_per_objfile->signatured_types
8642         = allocate_signatured_type_table (objfile);
8643     }
8644
8645   find_entry.signature = dwo_unit->signature;
8646   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8647                          INSERT);
8648   /* If we've already seen this type there's nothing to do.  What's happening
8649      is we're doing our own version of comdat-folding here.  */
8650   if (*slot != NULL)
8651     return 1;
8652
8653   /* This does the job that create_all_type_units would have done for
8654      this TU.  */
8655   entry = add_type_unit (dwo_unit->signature, slot);
8656   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
8657   *slot = entry;
8658
8659   /* This does the job that build_type_psymtabs_1 would have done.  */
8660   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8661                            build_type_psymtabs_reader, NULL);
8662
8663   return 1;
8664 }
8665
8666 /* Traversal function for process_skeletonless_type_units.  */
8667
8668 static int
8669 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8670 {
8671   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8672
8673   if (dwo_file->tus != NULL)
8674     {
8675       htab_traverse_noresize (dwo_file->tus,
8676                               process_skeletonless_type_unit, info);
8677     }
8678
8679   return 1;
8680 }
8681
8682 /* Scan all TUs of DWO files, verifying we've processed them.
8683    This is needed in case a TU was emitted without its skeleton.
8684    Note: This can't be done until we know what all the DWO files are.  */
8685
8686 static void
8687 process_skeletonless_type_units (struct objfile *objfile)
8688 {
8689   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8690   if (get_dwp_file () == NULL
8691       && dwarf2_per_objfile->dwo_files != NULL)
8692     {
8693       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8694                               process_dwo_file_for_skeletonless_type_units,
8695                               objfile);
8696     }
8697 }
8698
8699 /* Compute the 'user' field for each psymtab in OBJFILE.  */
8700
8701 static void
8702 set_partial_user (struct objfile *objfile)
8703 {
8704   int i;
8705
8706   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8707     {
8708       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
8709       struct partial_symtab *pst = per_cu->v.psymtab;
8710       int j;
8711
8712       if (pst == NULL)
8713         continue;
8714
8715       for (j = 0; j < pst->number_of_dependencies; ++j)
8716         {
8717           /* Set the 'user' field only if it is not already set.  */
8718           if (pst->dependencies[j]->user == NULL)
8719             pst->dependencies[j]->user = pst;
8720         }
8721     }
8722 }
8723
8724 /* Build the partial symbol table by doing a quick pass through the
8725    .debug_info and .debug_abbrev sections.  */
8726
8727 static void
8728 dwarf2_build_psymtabs_hard (struct objfile *objfile)
8729 {
8730   struct cleanup *back_to;
8731   int i;
8732
8733   if (dwarf_read_debug)
8734     {
8735       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8736                           objfile_name (objfile));
8737     }
8738
8739   dwarf2_per_objfile->reading_partial_symbols = 1;
8740
8741   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8742
8743   /* Any cached compilation units will be linked by the per-objfile
8744      read_in_chain.  Make sure to free them when we're done.  */
8745   back_to = make_cleanup (free_cached_comp_units, NULL);
8746
8747   build_type_psymtabs (objfile);
8748
8749   create_all_comp_units (objfile);
8750
8751   /* Create a temporary address map on a temporary obstack.  We later
8752      copy this to the final obstack.  */
8753   auto_obstack temp_obstack;
8754
8755   scoped_restore save_psymtabs_addrmap
8756     = make_scoped_restore (&objfile->psymtabs_addrmap,
8757                            addrmap_create_mutable (&temp_obstack));
8758
8759   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8760     {
8761       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
8762
8763       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8764     }
8765
8766   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8767   process_skeletonless_type_units (objfile);
8768
8769   /* Now that all TUs have been processed we can fill in the dependencies.  */
8770   if (dwarf2_per_objfile->type_unit_groups != NULL)
8771     {
8772       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8773                               build_type_psymtab_dependencies, NULL);
8774     }
8775
8776   if (dwarf_read_debug)
8777     print_tu_stats ();
8778
8779   set_partial_user (objfile);
8780
8781   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8782                                                     &objfile->objfile_obstack);
8783   /* At this point we want to keep the address map.  */
8784   save_psymtabs_addrmap.release ();
8785
8786   do_cleanups (back_to);
8787
8788   if (dwarf_read_debug)
8789     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8790                         objfile_name (objfile));
8791 }
8792
8793 /* die_reader_func for load_partial_comp_unit.  */
8794
8795 static void
8796 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8797                                const gdb_byte *info_ptr,
8798                                struct die_info *comp_unit_die,
8799                                int has_children,
8800                                void *data)
8801 {
8802   struct dwarf2_cu *cu = reader->cu;
8803
8804   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8805
8806   /* Check if comp unit has_children.
8807      If so, read the rest of the partial symbols from this comp unit.
8808      If not, there's no more debug_info for this comp unit.  */
8809   if (has_children)
8810     load_partial_dies (reader, info_ptr, 0);
8811 }
8812
8813 /* Load the partial DIEs for a secondary CU into memory.
8814    This is also used when rereading a primary CU with load_all_dies.  */
8815
8816 static void
8817 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8818 {
8819   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8820                            load_partial_comp_unit_reader, NULL);
8821 }
8822
8823 static void
8824 read_comp_units_from_section (struct objfile *objfile,
8825                               struct dwarf2_section_info *section,
8826                               struct dwarf2_section_info *abbrev_section,
8827                               unsigned int is_dwz,
8828                               int *n_allocated,
8829                               int *n_comp_units,
8830                               struct dwarf2_per_cu_data ***all_comp_units)
8831 {
8832   const gdb_byte *info_ptr;
8833
8834   if (dwarf_read_debug)
8835     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8836                         get_section_name (section),
8837                         get_section_file_name (section));
8838
8839   dwarf2_read_section (objfile, section);
8840
8841   info_ptr = section->buffer;
8842
8843   while (info_ptr < section->buffer + section->size)
8844     {
8845       struct dwarf2_per_cu_data *this_cu;
8846
8847       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8848
8849       comp_unit_head cu_header;
8850       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
8851                                      info_ptr, rcuh_kind::COMPILE);
8852
8853       /* Save the compilation unit for later lookup.  */
8854       if (cu_header.unit_type != DW_UT_type)
8855         {
8856           this_cu = XOBNEW (&objfile->objfile_obstack,
8857                             struct dwarf2_per_cu_data);
8858           memset (this_cu, 0, sizeof (*this_cu));
8859         }
8860       else
8861         {
8862           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8863                                   struct signatured_type);
8864           memset (sig_type, 0, sizeof (*sig_type));
8865           sig_type->signature = cu_header.signature;
8866           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8867           this_cu = &sig_type->per_cu;
8868         }
8869       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8870       this_cu->sect_off = sect_off;
8871       this_cu->length = cu_header.length + cu_header.initial_length_size;
8872       this_cu->is_dwz = is_dwz;
8873       this_cu->objfile = objfile;
8874       this_cu->section = section;
8875
8876       if (*n_comp_units == *n_allocated)
8877         {
8878           *n_allocated *= 2;
8879           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8880                                         *all_comp_units, *n_allocated);
8881         }
8882       (*all_comp_units)[*n_comp_units] = this_cu;
8883       ++*n_comp_units;
8884
8885       info_ptr = info_ptr + this_cu->length;
8886     }
8887 }
8888
8889 /* Create a list of all compilation units in OBJFILE.
8890    This is only done for -readnow and building partial symtabs.  */
8891
8892 static void
8893 create_all_comp_units (struct objfile *objfile)
8894 {
8895   int n_allocated;
8896   int n_comp_units;
8897   struct dwarf2_per_cu_data **all_comp_units;
8898   struct dwz_file *dwz;
8899
8900   n_comp_units = 0;
8901   n_allocated = 10;
8902   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
8903
8904   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
8905                                 &dwarf2_per_objfile->abbrev, 0,
8906                                 &n_allocated, &n_comp_units, &all_comp_units);
8907
8908   dwz = dwarf2_get_dwz_file ();
8909   if (dwz != NULL)
8910     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
8911                                   &n_allocated, &n_comp_units,
8912                                   &all_comp_units);
8913
8914   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
8915                                                   struct dwarf2_per_cu_data *,
8916                                                   n_comp_units);
8917   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
8918           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
8919   xfree (all_comp_units);
8920   dwarf2_per_objfile->n_comp_units = n_comp_units;
8921 }
8922
8923 /* Process all loaded DIEs for compilation unit CU, starting at
8924    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8925    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8926    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8927    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8928
8929 static void
8930 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8931                       CORE_ADDR *highpc, int set_addrmap,
8932                       struct dwarf2_cu *cu)
8933 {
8934   struct partial_die_info *pdi;
8935
8936   /* Now, march along the PDI's, descending into ones which have
8937      interesting children but skipping the children of the other ones,
8938      until we reach the end of the compilation unit.  */
8939
8940   pdi = first_die;
8941
8942   while (pdi != NULL)
8943     {
8944       fixup_partial_die (pdi, cu);
8945
8946       /* Anonymous namespaces or modules have no name but have interesting
8947          children, so we need to look at them.  Ditto for anonymous
8948          enums.  */
8949
8950       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8951           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8952           || pdi->tag == DW_TAG_imported_unit)
8953         {
8954           switch (pdi->tag)
8955             {
8956             case DW_TAG_subprogram:
8957               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8958               break;
8959             case DW_TAG_constant:
8960             case DW_TAG_variable:
8961             case DW_TAG_typedef:
8962             case DW_TAG_union_type:
8963               if (!pdi->is_declaration)
8964                 {
8965                   add_partial_symbol (pdi, cu);
8966                 }
8967               break;
8968             case DW_TAG_class_type:
8969             case DW_TAG_interface_type:
8970             case DW_TAG_structure_type:
8971               if (!pdi->is_declaration)
8972                 {
8973                   add_partial_symbol (pdi, cu);
8974                 }
8975               if (cu->language == language_rust && pdi->has_children)
8976                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8977                                       set_addrmap, cu);
8978               break;
8979             case DW_TAG_enumeration_type:
8980               if (!pdi->is_declaration)
8981                 add_partial_enumeration (pdi, cu);
8982               break;
8983             case DW_TAG_base_type:
8984             case DW_TAG_subrange_type:
8985               /* File scope base type definitions are added to the partial
8986                  symbol table.  */
8987               add_partial_symbol (pdi, cu);
8988               break;
8989             case DW_TAG_namespace:
8990               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8991               break;
8992             case DW_TAG_module:
8993               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8994               break;
8995             case DW_TAG_imported_unit:
8996               {
8997                 struct dwarf2_per_cu_data *per_cu;
8998
8999                 /* For now we don't handle imported units in type units.  */
9000                 if (cu->per_cu->is_debug_types)
9001                   {
9002                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9003                              " supported in type units [in module %s]"),
9004                            objfile_name (cu->objfile));
9005                   }
9006
9007                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
9008                                                            pdi->is_dwz,
9009                                                            cu->objfile);
9010
9011                 /* Go read the partial unit, if needed.  */
9012                 if (per_cu->v.psymtab == NULL)
9013                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9014
9015                 VEC_safe_push (dwarf2_per_cu_ptr,
9016                                cu->per_cu->imported_symtabs, per_cu);
9017               }
9018               break;
9019             case DW_TAG_imported_declaration:
9020               add_partial_symbol (pdi, cu);
9021               break;
9022             default:
9023               break;
9024             }
9025         }
9026
9027       /* If the die has a sibling, skip to the sibling.  */
9028
9029       pdi = pdi->die_sibling;
9030     }
9031 }
9032
9033 /* Functions used to compute the fully scoped name of a partial DIE.
9034
9035    Normally, this is simple.  For C++, the parent DIE's fully scoped
9036    name is concatenated with "::" and the partial DIE's name.
9037    Enumerators are an exception; they use the scope of their parent
9038    enumeration type, i.e. the name of the enumeration type is not
9039    prepended to the enumerator.
9040
9041    There are two complexities.  One is DW_AT_specification; in this
9042    case "parent" means the parent of the target of the specification,
9043    instead of the direct parent of the DIE.  The other is compilers
9044    which do not emit DW_TAG_namespace; in this case we try to guess
9045    the fully qualified name of structure types from their members'
9046    linkage names.  This must be done using the DIE's children rather
9047    than the children of any DW_AT_specification target.  We only need
9048    to do this for structures at the top level, i.e. if the target of
9049    any DW_AT_specification (if any; otherwise the DIE itself) does not
9050    have a parent.  */
9051
9052 /* Compute the scope prefix associated with PDI's parent, in
9053    compilation unit CU.  The result will be allocated on CU's
9054    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9055    field.  NULL is returned if no prefix is necessary.  */
9056 static const char *
9057 partial_die_parent_scope (struct partial_die_info *pdi,
9058                           struct dwarf2_cu *cu)
9059 {
9060   const char *grandparent_scope;
9061   struct partial_die_info *parent, *real_pdi;
9062
9063   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9064      then this means the parent of the specification DIE.  */
9065
9066   real_pdi = pdi;
9067   while (real_pdi->has_specification)
9068     real_pdi = find_partial_die (real_pdi->spec_offset,
9069                                  real_pdi->spec_is_dwz, cu);
9070
9071   parent = real_pdi->die_parent;
9072   if (parent == NULL)
9073     return NULL;
9074
9075   if (parent->scope_set)
9076     return parent->scope;
9077
9078   fixup_partial_die (parent, cu);
9079
9080   grandparent_scope = partial_die_parent_scope (parent, cu);
9081
9082   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9083      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9084      Work around this problem here.  */
9085   if (cu->language == language_cplus
9086       && parent->tag == DW_TAG_namespace
9087       && strcmp (parent->name, "::") == 0
9088       && grandparent_scope == NULL)
9089     {
9090       parent->scope = NULL;
9091       parent->scope_set = 1;
9092       return NULL;
9093     }
9094
9095   if (pdi->tag == DW_TAG_enumerator)
9096     /* Enumerators should not get the name of the enumeration as a prefix.  */
9097     parent->scope = grandparent_scope;
9098   else if (parent->tag == DW_TAG_namespace
9099       || parent->tag == DW_TAG_module
9100       || parent->tag == DW_TAG_structure_type
9101       || parent->tag == DW_TAG_class_type
9102       || parent->tag == DW_TAG_interface_type
9103       || parent->tag == DW_TAG_union_type
9104       || parent->tag == DW_TAG_enumeration_type)
9105     {
9106       if (grandparent_scope == NULL)
9107         parent->scope = parent->name;
9108       else
9109         parent->scope = typename_concat (&cu->comp_unit_obstack,
9110                                          grandparent_scope,
9111                                          parent->name, 0, cu);
9112     }
9113   else
9114     {
9115       /* FIXME drow/2004-04-01: What should we be doing with
9116          function-local names?  For partial symbols, we should probably be
9117          ignoring them.  */
9118       complaint (&symfile_complaints,
9119                  _("unhandled containing DIE tag %d for DIE at %d"),
9120                  parent->tag, to_underlying (pdi->sect_off));
9121       parent->scope = grandparent_scope;
9122     }
9123
9124   parent->scope_set = 1;
9125   return parent->scope;
9126 }
9127
9128 /* Return the fully scoped name associated with PDI, from compilation unit
9129    CU.  The result will be allocated with malloc.  */
9130
9131 static char *
9132 partial_die_full_name (struct partial_die_info *pdi,
9133                        struct dwarf2_cu *cu)
9134 {
9135   const char *parent_scope;
9136
9137   /* If this is a template instantiation, we can not work out the
9138      template arguments from partial DIEs.  So, unfortunately, we have
9139      to go through the full DIEs.  At least any work we do building
9140      types here will be reused if full symbols are loaded later.  */
9141   if (pdi->has_template_arguments)
9142     {
9143       fixup_partial_die (pdi, cu);
9144
9145       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9146         {
9147           struct die_info *die;
9148           struct attribute attr;
9149           struct dwarf2_cu *ref_cu = cu;
9150
9151           /* DW_FORM_ref_addr is using section offset.  */
9152           attr.name = (enum dwarf_attribute) 0;
9153           attr.form = DW_FORM_ref_addr;
9154           attr.u.unsnd = to_underlying (pdi->sect_off);
9155           die = follow_die_ref (NULL, &attr, &ref_cu);
9156
9157           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9158         }
9159     }
9160
9161   parent_scope = partial_die_parent_scope (pdi, cu);
9162   if (parent_scope == NULL)
9163     return NULL;
9164   else
9165     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9166 }
9167
9168 static void
9169 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9170 {
9171   struct objfile *objfile = cu->objfile;
9172   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9173   CORE_ADDR addr = 0;
9174   const char *actual_name = NULL;
9175   CORE_ADDR baseaddr;
9176   char *built_actual_name;
9177
9178   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9179
9180   built_actual_name = partial_die_full_name (pdi, cu);
9181   if (built_actual_name != NULL)
9182     actual_name = built_actual_name;
9183
9184   if (actual_name == NULL)
9185     actual_name = pdi->name;
9186
9187   switch (pdi->tag)
9188     {
9189     case DW_TAG_subprogram:
9190       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9191       if (pdi->is_external || cu->language == language_ada)
9192         {
9193           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9194              of the global scope.  But in Ada, we want to be able to access
9195              nested procedures globally.  So all Ada subprograms are stored
9196              in the global scope.  */
9197           add_psymbol_to_list (actual_name, strlen (actual_name),
9198                                built_actual_name != NULL,
9199                                VAR_DOMAIN, LOC_BLOCK,
9200                                &objfile->global_psymbols,
9201                                addr, cu->language, objfile);
9202         }
9203       else
9204         {
9205           add_psymbol_to_list (actual_name, strlen (actual_name),
9206                                built_actual_name != NULL,
9207                                VAR_DOMAIN, LOC_BLOCK,
9208                                &objfile->static_psymbols,
9209                                addr, cu->language, objfile);
9210         }
9211
9212       if (pdi->main_subprogram && actual_name != NULL)
9213         set_objfile_main_name (objfile, actual_name, cu->language);
9214       break;
9215     case DW_TAG_constant:
9216       {
9217         std::vector<partial_symbol *> *list;
9218
9219         if (pdi->is_external)
9220           list = &objfile->global_psymbols;
9221         else
9222           list = &objfile->static_psymbols;
9223         add_psymbol_to_list (actual_name, strlen (actual_name),
9224                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9225                              list, 0, cu->language, objfile);
9226       }
9227       break;
9228     case DW_TAG_variable:
9229       if (pdi->d.locdesc)
9230         addr = decode_locdesc (pdi->d.locdesc, cu);
9231
9232       if (pdi->d.locdesc
9233           && addr == 0
9234           && !dwarf2_per_objfile->has_section_at_zero)
9235         {
9236           /* A global or static variable may also have been stripped
9237              out by the linker if unused, in which case its address
9238              will be nullified; do not add such variables into partial
9239              symbol table then.  */
9240         }
9241       else if (pdi->is_external)
9242         {
9243           /* Global Variable.
9244              Don't enter into the minimal symbol tables as there is
9245              a minimal symbol table entry from the ELF symbols already.
9246              Enter into partial symbol table if it has a location
9247              descriptor or a type.
9248              If the location descriptor is missing, new_symbol will create
9249              a LOC_UNRESOLVED symbol, the address of the variable will then
9250              be determined from the minimal symbol table whenever the variable
9251              is referenced.
9252              The address for the partial symbol table entry is not
9253              used by GDB, but it comes in handy for debugging partial symbol
9254              table building.  */
9255
9256           if (pdi->d.locdesc || pdi->has_type)
9257             add_psymbol_to_list (actual_name, strlen (actual_name),
9258                                  built_actual_name != NULL,
9259                                  VAR_DOMAIN, LOC_STATIC,
9260                                  &objfile->global_psymbols,
9261                                  addr + baseaddr,
9262                                  cu->language, objfile);
9263         }
9264       else
9265         {
9266           int has_loc = pdi->d.locdesc != NULL;
9267
9268           /* Static Variable.  Skip symbols whose value we cannot know (those
9269              without location descriptors or constant values).  */
9270           if (!has_loc && !pdi->has_const_value)
9271             {
9272               xfree (built_actual_name);
9273               return;
9274             }
9275
9276           add_psymbol_to_list (actual_name, strlen (actual_name),
9277                                built_actual_name != NULL,
9278                                VAR_DOMAIN, LOC_STATIC,
9279                                &objfile->static_psymbols,
9280                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9281                                cu->language, objfile);
9282         }
9283       break;
9284     case DW_TAG_typedef:
9285     case DW_TAG_base_type:
9286     case DW_TAG_subrange_type:
9287       add_psymbol_to_list (actual_name, strlen (actual_name),
9288                            built_actual_name != NULL,
9289                            VAR_DOMAIN, LOC_TYPEDEF,
9290                            &objfile->static_psymbols,
9291                            0, cu->language, objfile);
9292       break;
9293     case DW_TAG_imported_declaration:
9294     case DW_TAG_namespace:
9295       add_psymbol_to_list (actual_name, strlen (actual_name),
9296                            built_actual_name != NULL,
9297                            VAR_DOMAIN, LOC_TYPEDEF,
9298                            &objfile->global_psymbols,
9299                            0, cu->language, objfile);
9300       break;
9301     case DW_TAG_module:
9302       add_psymbol_to_list (actual_name, strlen (actual_name),
9303                            built_actual_name != NULL,
9304                            MODULE_DOMAIN, LOC_TYPEDEF,
9305                            &objfile->global_psymbols,
9306                            0, cu->language, objfile);
9307       break;
9308     case DW_TAG_class_type:
9309     case DW_TAG_interface_type:
9310     case DW_TAG_structure_type:
9311     case DW_TAG_union_type:
9312     case DW_TAG_enumeration_type:
9313       /* Skip external references.  The DWARF standard says in the section
9314          about "Structure, Union, and Class Type Entries": "An incomplete
9315          structure, union or class type is represented by a structure,
9316          union or class entry that does not have a byte size attribute
9317          and that has a DW_AT_declaration attribute."  */
9318       if (!pdi->has_byte_size && pdi->is_declaration)
9319         {
9320           xfree (built_actual_name);
9321           return;
9322         }
9323
9324       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9325          static vs. global.  */
9326       add_psymbol_to_list (actual_name, strlen (actual_name),
9327                            built_actual_name != NULL,
9328                            STRUCT_DOMAIN, LOC_TYPEDEF,
9329                            cu->language == language_cplus
9330                            ? &objfile->global_psymbols
9331                            : &objfile->static_psymbols,
9332                            0, cu->language, objfile);
9333
9334       break;
9335     case DW_TAG_enumerator:
9336       add_psymbol_to_list (actual_name, strlen (actual_name),
9337                            built_actual_name != NULL,
9338                            VAR_DOMAIN, LOC_CONST,
9339                            cu->language == language_cplus
9340                            ? &objfile->global_psymbols
9341                            : &objfile->static_psymbols,
9342                            0, cu->language, objfile);
9343       break;
9344     default:
9345       break;
9346     }
9347
9348   xfree (built_actual_name);
9349 }
9350
9351 /* Read a partial die corresponding to a namespace; also, add a symbol
9352    corresponding to that namespace to the symbol table.  NAMESPACE is
9353    the name of the enclosing namespace.  */
9354
9355 static void
9356 add_partial_namespace (struct partial_die_info *pdi,
9357                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9358                        int set_addrmap, struct dwarf2_cu *cu)
9359 {
9360   /* Add a symbol for the namespace.  */
9361
9362   add_partial_symbol (pdi, cu);
9363
9364   /* Now scan partial symbols in that namespace.  */
9365
9366   if (pdi->has_children)
9367     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9368 }
9369
9370 /* Read a partial die corresponding to a Fortran module.  */
9371
9372 static void
9373 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9374                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9375 {
9376   /* Add a symbol for the namespace.  */
9377
9378   add_partial_symbol (pdi, cu);
9379
9380   /* Now scan partial symbols in that module.  */
9381
9382   if (pdi->has_children)
9383     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9384 }
9385
9386 /* Read a partial die corresponding to a subprogram and create a partial
9387    symbol for that subprogram.  When the CU language allows it, this
9388    routine also defines a partial symbol for each nested subprogram
9389    that this subprogram contains.  If SET_ADDRMAP is true, record the
9390    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
9391    and highest PC values found in PDI.
9392
9393    PDI may also be a lexical block, in which case we simply search
9394    recursively for subprograms defined inside that lexical block.
9395    Again, this is only performed when the CU language allows this
9396    type of definitions.  */
9397
9398 static void
9399 add_partial_subprogram (struct partial_die_info *pdi,
9400                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9401                         int set_addrmap, struct dwarf2_cu *cu)
9402 {
9403   if (pdi->tag == DW_TAG_subprogram)
9404     {
9405       if (pdi->has_pc_info)
9406         {
9407           if (pdi->lowpc < *lowpc)
9408             *lowpc = pdi->lowpc;
9409           if (pdi->highpc > *highpc)
9410             *highpc = pdi->highpc;
9411           if (set_addrmap)
9412             {
9413               struct objfile *objfile = cu->objfile;
9414               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9415               CORE_ADDR baseaddr;
9416               CORE_ADDR highpc;
9417               CORE_ADDR lowpc;
9418
9419               baseaddr = ANOFFSET (objfile->section_offsets,
9420                                    SECT_OFF_TEXT (objfile));
9421               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9422                                                   pdi->lowpc + baseaddr);
9423               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9424                                                    pdi->highpc + baseaddr);
9425               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9426                                  cu->per_cu->v.psymtab);
9427             }
9428         }
9429
9430       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9431         {
9432           if (!pdi->is_declaration)
9433             /* Ignore subprogram DIEs that do not have a name, they are
9434                illegal.  Do not emit a complaint at this point, we will
9435                do so when we convert this psymtab into a symtab.  */
9436             if (pdi->name)
9437               add_partial_symbol (pdi, cu);
9438         }
9439     }
9440
9441   if (! pdi->has_children)
9442     return;
9443
9444   if (cu->language == language_ada)
9445     {
9446       pdi = pdi->die_child;
9447       while (pdi != NULL)
9448         {
9449           fixup_partial_die (pdi, cu);
9450           if (pdi->tag == DW_TAG_subprogram
9451               || pdi->tag == DW_TAG_lexical_block)
9452             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9453           pdi = pdi->die_sibling;
9454         }
9455     }
9456 }
9457
9458 /* Read a partial die corresponding to an enumeration type.  */
9459
9460 static void
9461 add_partial_enumeration (struct partial_die_info *enum_pdi,
9462                          struct dwarf2_cu *cu)
9463 {
9464   struct partial_die_info *pdi;
9465
9466   if (enum_pdi->name != NULL)
9467     add_partial_symbol (enum_pdi, cu);
9468
9469   pdi = enum_pdi->die_child;
9470   while (pdi)
9471     {
9472       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9473         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9474       else
9475         add_partial_symbol (pdi, cu);
9476       pdi = pdi->die_sibling;
9477     }
9478 }
9479
9480 /* Return the initial uleb128 in the die at INFO_PTR.  */
9481
9482 static unsigned int
9483 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9484 {
9485   unsigned int bytes_read;
9486
9487   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9488 }
9489
9490 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
9491    Return the corresponding abbrev, or NULL if the number is zero (indicating
9492    an empty DIE).  In either case *BYTES_READ will be set to the length of
9493    the initial number.  */
9494
9495 static struct abbrev_info *
9496 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
9497                  struct dwarf2_cu *cu)
9498 {
9499   bfd *abfd = cu->objfile->obfd;
9500   unsigned int abbrev_number;
9501   struct abbrev_info *abbrev;
9502
9503   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9504
9505   if (abbrev_number == 0)
9506     return NULL;
9507
9508   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
9509   if (!abbrev)
9510     {
9511       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9512                " at offset 0x%x [in module %s]"),
9513              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9514              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9515     }
9516
9517   return abbrev;
9518 }
9519
9520 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9521    Returns a pointer to the end of a series of DIEs, terminated by an empty
9522    DIE.  Any children of the skipped DIEs will also be skipped.  */
9523
9524 static const gdb_byte *
9525 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9526 {
9527   struct dwarf2_cu *cu = reader->cu;
9528   struct abbrev_info *abbrev;
9529   unsigned int bytes_read;
9530
9531   while (1)
9532     {
9533       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
9534       if (abbrev == NULL)
9535         return info_ptr + bytes_read;
9536       else
9537         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9538     }
9539 }
9540
9541 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9542    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9543    abbrev corresponding to that skipped uleb128 should be passed in
9544    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9545    children.  */
9546
9547 static const gdb_byte *
9548 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9549               struct abbrev_info *abbrev)
9550 {
9551   unsigned int bytes_read;
9552   struct attribute attr;
9553   bfd *abfd = reader->abfd;
9554   struct dwarf2_cu *cu = reader->cu;
9555   const gdb_byte *buffer = reader->buffer;
9556   const gdb_byte *buffer_end = reader->buffer_end;
9557   unsigned int form, i;
9558
9559   for (i = 0; i < abbrev->num_attrs; i++)
9560     {
9561       /* The only abbrev we care about is DW_AT_sibling.  */
9562       if (abbrev->attrs[i].name == DW_AT_sibling)
9563         {
9564           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9565           if (attr.form == DW_FORM_ref_addr)
9566             complaint (&symfile_complaints,
9567                        _("ignoring absolute DW_AT_sibling"));
9568           else
9569             {
9570               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9571               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9572
9573               if (sibling_ptr < info_ptr)
9574                 complaint (&symfile_complaints,
9575                            _("DW_AT_sibling points backwards"));
9576               else if (sibling_ptr > reader->buffer_end)
9577                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9578               else
9579                 return sibling_ptr;
9580             }
9581         }
9582
9583       /* If it isn't DW_AT_sibling, skip this attribute.  */
9584       form = abbrev->attrs[i].form;
9585     skip_attribute:
9586       switch (form)
9587         {
9588         case DW_FORM_ref_addr:
9589           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9590              and later it is offset sized.  */
9591           if (cu->header.version == 2)
9592             info_ptr += cu->header.addr_size;
9593           else
9594             info_ptr += cu->header.offset_size;
9595           break;
9596         case DW_FORM_GNU_ref_alt:
9597           info_ptr += cu->header.offset_size;
9598           break;
9599         case DW_FORM_addr:
9600           info_ptr += cu->header.addr_size;
9601           break;
9602         case DW_FORM_data1:
9603         case DW_FORM_ref1:
9604         case DW_FORM_flag:
9605           info_ptr += 1;
9606           break;
9607         case DW_FORM_flag_present:
9608         case DW_FORM_implicit_const:
9609           break;
9610         case DW_FORM_data2:
9611         case DW_FORM_ref2:
9612           info_ptr += 2;
9613           break;
9614         case DW_FORM_data4:
9615         case DW_FORM_ref4:
9616           info_ptr += 4;
9617           break;
9618         case DW_FORM_data8:
9619         case DW_FORM_ref8:
9620         case DW_FORM_ref_sig8:
9621           info_ptr += 8;
9622           break;
9623         case DW_FORM_data16:
9624           info_ptr += 16;
9625           break;
9626         case DW_FORM_string:
9627           read_direct_string (abfd, info_ptr, &bytes_read);
9628           info_ptr += bytes_read;
9629           break;
9630         case DW_FORM_sec_offset:
9631         case DW_FORM_strp:
9632         case DW_FORM_GNU_strp_alt:
9633           info_ptr += cu->header.offset_size;
9634           break;
9635         case DW_FORM_exprloc:
9636         case DW_FORM_block:
9637           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9638           info_ptr += bytes_read;
9639           break;
9640         case DW_FORM_block1:
9641           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9642           break;
9643         case DW_FORM_block2:
9644           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9645           break;
9646         case DW_FORM_block4:
9647           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9648           break;
9649         case DW_FORM_sdata:
9650         case DW_FORM_udata:
9651         case DW_FORM_ref_udata:
9652         case DW_FORM_GNU_addr_index:
9653         case DW_FORM_GNU_str_index:
9654           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9655           break;
9656         case DW_FORM_indirect:
9657           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9658           info_ptr += bytes_read;
9659           /* We need to continue parsing from here, so just go back to
9660              the top.  */
9661           goto skip_attribute;
9662
9663         default:
9664           error (_("Dwarf Error: Cannot handle %s "
9665                    "in DWARF reader [in module %s]"),
9666                  dwarf_form_name (form),
9667                  bfd_get_filename (abfd));
9668         }
9669     }
9670
9671   if (abbrev->has_children)
9672     return skip_children (reader, info_ptr);
9673   else
9674     return info_ptr;
9675 }
9676
9677 /* Locate ORIG_PDI's sibling.
9678    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9679
9680 static const gdb_byte *
9681 locate_pdi_sibling (const struct die_reader_specs *reader,
9682                     struct partial_die_info *orig_pdi,
9683                     const gdb_byte *info_ptr)
9684 {
9685   /* Do we know the sibling already?  */
9686
9687   if (orig_pdi->sibling)
9688     return orig_pdi->sibling;
9689
9690   /* Are there any children to deal with?  */
9691
9692   if (!orig_pdi->has_children)
9693     return info_ptr;
9694
9695   /* Skip the children the long way.  */
9696
9697   return skip_children (reader, info_ptr);
9698 }
9699
9700 /* Expand this partial symbol table into a full symbol table.  SELF is
9701    not NULL.  */
9702
9703 static void
9704 dwarf2_read_symtab (struct partial_symtab *self,
9705                     struct objfile *objfile)
9706 {
9707   if (self->readin)
9708     {
9709       warning (_("bug: psymtab for %s is already read in."),
9710                self->filename);
9711     }
9712   else
9713     {
9714       if (info_verbose)
9715         {
9716           printf_filtered (_("Reading in symbols for %s..."),
9717                            self->filename);
9718           gdb_flush (gdb_stdout);
9719         }
9720
9721       /* Restore our global data.  */
9722       dwarf2_per_objfile
9723         = (struct dwarf2_per_objfile *) objfile_data (objfile,
9724                                                       dwarf2_objfile_data_key);
9725
9726       /* If this psymtab is constructed from a debug-only objfile, the
9727          has_section_at_zero flag will not necessarily be correct.  We
9728          can get the correct value for this flag by looking at the data
9729          associated with the (presumably stripped) associated objfile.  */
9730       if (objfile->separate_debug_objfile_backlink)
9731         {
9732           struct dwarf2_per_objfile *dpo_backlink
9733             = ((struct dwarf2_per_objfile *)
9734                objfile_data (objfile->separate_debug_objfile_backlink,
9735                              dwarf2_objfile_data_key));
9736
9737           dwarf2_per_objfile->has_section_at_zero
9738             = dpo_backlink->has_section_at_zero;
9739         }
9740
9741       dwarf2_per_objfile->reading_partial_symbols = 0;
9742
9743       psymtab_to_symtab_1 (self);
9744
9745       /* Finish up the debug error message.  */
9746       if (info_verbose)
9747         printf_filtered (_("done.\n"));
9748     }
9749
9750   process_cu_includes ();
9751 }
9752 \f
9753 /* Reading in full CUs.  */
9754
9755 /* Add PER_CU to the queue.  */
9756
9757 static void
9758 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9759                  enum language pretend_language)
9760 {
9761   struct dwarf2_queue_item *item;
9762
9763   per_cu->queued = 1;
9764   item = XNEW (struct dwarf2_queue_item);
9765   item->per_cu = per_cu;
9766   item->pretend_language = pretend_language;
9767   item->next = NULL;
9768
9769   if (dwarf2_queue == NULL)
9770     dwarf2_queue = item;
9771   else
9772     dwarf2_queue_tail->next = item;
9773
9774   dwarf2_queue_tail = item;
9775 }
9776
9777 /* If PER_CU is not yet queued, add it to the queue.
9778    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9779    dependency.
9780    The result is non-zero if PER_CU was queued, otherwise the result is zero
9781    meaning either PER_CU is already queued or it is already loaded.
9782
9783    N.B. There is an invariant here that if a CU is queued then it is loaded.
9784    The caller is required to load PER_CU if we return non-zero.  */
9785
9786 static int
9787 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9788                        struct dwarf2_per_cu_data *per_cu,
9789                        enum language pretend_language)
9790 {
9791   /* We may arrive here during partial symbol reading, if we need full
9792      DIEs to process an unusual case (e.g. template arguments).  Do
9793      not queue PER_CU, just tell our caller to load its DIEs.  */
9794   if (dwarf2_per_objfile->reading_partial_symbols)
9795     {
9796       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9797         return 1;
9798       return 0;
9799     }
9800
9801   /* Mark the dependence relation so that we don't flush PER_CU
9802      too early.  */
9803   if (dependent_cu != NULL)
9804     dwarf2_add_dependence (dependent_cu, per_cu);
9805
9806   /* If it's already on the queue, we have nothing to do.  */
9807   if (per_cu->queued)
9808     return 0;
9809
9810   /* If the compilation unit is already loaded, just mark it as
9811      used.  */
9812   if (per_cu->cu != NULL)
9813     {
9814       per_cu->cu->last_used = 0;
9815       return 0;
9816     }
9817
9818   /* Add it to the queue.  */
9819   queue_comp_unit (per_cu, pretend_language);
9820
9821   return 1;
9822 }
9823
9824 /* Process the queue.  */
9825
9826 static void
9827 process_queue (void)
9828 {
9829   struct dwarf2_queue_item *item, *next_item;
9830
9831   if (dwarf_read_debug)
9832     {
9833       fprintf_unfiltered (gdb_stdlog,
9834                           "Expanding one or more symtabs of objfile %s ...\n",
9835                           objfile_name (dwarf2_per_objfile->objfile));
9836     }
9837
9838   /* The queue starts out with one item, but following a DIE reference
9839      may load a new CU, adding it to the end of the queue.  */
9840   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9841     {
9842       if ((dwarf2_per_objfile->using_index
9843            ? !item->per_cu->v.quick->compunit_symtab
9844            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9845           /* Skip dummy CUs.  */
9846           && item->per_cu->cu != NULL)
9847         {
9848           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9849           unsigned int debug_print_threshold;
9850           char buf[100];
9851
9852           if (per_cu->is_debug_types)
9853             {
9854               struct signatured_type *sig_type =
9855                 (struct signatured_type *) per_cu;
9856
9857               sprintf (buf, "TU %s at offset 0x%x",
9858                        hex_string (sig_type->signature),
9859                        to_underlying (per_cu->sect_off));
9860               /* There can be 100s of TUs.
9861                  Only print them in verbose mode.  */
9862               debug_print_threshold = 2;
9863             }
9864           else
9865             {
9866               sprintf (buf, "CU at offset 0x%x",
9867                        to_underlying (per_cu->sect_off));
9868               debug_print_threshold = 1;
9869             }
9870
9871           if (dwarf_read_debug >= debug_print_threshold)
9872             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9873
9874           if (per_cu->is_debug_types)
9875             process_full_type_unit (per_cu, item->pretend_language);
9876           else
9877             process_full_comp_unit (per_cu, item->pretend_language);
9878
9879           if (dwarf_read_debug >= debug_print_threshold)
9880             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9881         }
9882
9883       item->per_cu->queued = 0;
9884       next_item = item->next;
9885       xfree (item);
9886     }
9887
9888   dwarf2_queue_tail = NULL;
9889
9890   if (dwarf_read_debug)
9891     {
9892       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9893                           objfile_name (dwarf2_per_objfile->objfile));
9894     }
9895 }
9896
9897 /* Free all allocated queue entries.  This function only releases anything if
9898    an error was thrown; if the queue was processed then it would have been
9899    freed as we went along.  */
9900
9901 static void
9902 dwarf2_release_queue (void *dummy)
9903 {
9904   struct dwarf2_queue_item *item, *last;
9905
9906   item = dwarf2_queue;
9907   while (item)
9908     {
9909       /* Anything still marked queued is likely to be in an
9910          inconsistent state, so discard it.  */
9911       if (item->per_cu->queued)
9912         {
9913           if (item->per_cu->cu != NULL)
9914             free_one_cached_comp_unit (item->per_cu);
9915           item->per_cu->queued = 0;
9916         }
9917
9918       last = item;
9919       item = item->next;
9920       xfree (last);
9921     }
9922
9923   dwarf2_queue = dwarf2_queue_tail = NULL;
9924 }
9925
9926 /* Read in full symbols for PST, and anything it depends on.  */
9927
9928 static void
9929 psymtab_to_symtab_1 (struct partial_symtab *pst)
9930 {
9931   struct dwarf2_per_cu_data *per_cu;
9932   int i;
9933
9934   if (pst->readin)
9935     return;
9936
9937   for (i = 0; i < pst->number_of_dependencies; i++)
9938     if (!pst->dependencies[i]->readin
9939         && pst->dependencies[i]->user == NULL)
9940       {
9941         /* Inform about additional files that need to be read in.  */
9942         if (info_verbose)
9943           {
9944             /* FIXME: i18n: Need to make this a single string.  */
9945             fputs_filtered (" ", gdb_stdout);
9946             wrap_here ("");
9947             fputs_filtered ("and ", gdb_stdout);
9948             wrap_here ("");
9949             printf_filtered ("%s...", pst->dependencies[i]->filename);
9950             wrap_here ("");     /* Flush output.  */
9951             gdb_flush (gdb_stdout);
9952           }
9953         psymtab_to_symtab_1 (pst->dependencies[i]);
9954       }
9955
9956   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9957
9958   if (per_cu == NULL)
9959     {
9960       /* It's an include file, no symbols to read for it.
9961          Everything is in the parent symtab.  */
9962       pst->readin = 1;
9963       return;
9964     }
9965
9966   dw2_do_instantiate_symtab (per_cu);
9967 }
9968
9969 /* Trivial hash function for die_info: the hash value of a DIE
9970    is its offset in .debug_info for this objfile.  */
9971
9972 static hashval_t
9973 die_hash (const void *item)
9974 {
9975   const struct die_info *die = (const struct die_info *) item;
9976
9977   return to_underlying (die->sect_off);
9978 }
9979
9980 /* Trivial comparison function for die_info structures: two DIEs
9981    are equal if they have the same offset.  */
9982
9983 static int
9984 die_eq (const void *item_lhs, const void *item_rhs)
9985 {
9986   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9987   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9988
9989   return die_lhs->sect_off == die_rhs->sect_off;
9990 }
9991
9992 /* die_reader_func for load_full_comp_unit.
9993    This is identical to read_signatured_type_reader,
9994    but is kept separate for now.  */
9995
9996 static void
9997 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9998                             const gdb_byte *info_ptr,
9999                             struct die_info *comp_unit_die,
10000                             int has_children,
10001                             void *data)
10002 {
10003   struct dwarf2_cu *cu = reader->cu;
10004   enum language *language_ptr = (enum language *) data;
10005
10006   gdb_assert (cu->die_hash == NULL);
10007   cu->die_hash =
10008     htab_create_alloc_ex (cu->header.length / 12,
10009                           die_hash,
10010                           die_eq,
10011                           NULL,
10012                           &cu->comp_unit_obstack,
10013                           hashtab_obstack_allocate,
10014                           dummy_obstack_deallocate);
10015
10016   if (has_children)
10017     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10018                                                   &info_ptr, comp_unit_die);
10019   cu->dies = comp_unit_die;
10020   /* comp_unit_die is not stored in die_hash, no need.  */
10021
10022   /* We try not to read any attributes in this function, because not
10023      all CUs needed for references have been loaded yet, and symbol
10024      table processing isn't initialized.  But we have to set the CU language,
10025      or we won't be able to build types correctly.
10026      Similarly, if we do not read the producer, we can not apply
10027      producer-specific interpretation.  */
10028   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10029 }
10030
10031 /* Load the DIEs associated with PER_CU into memory.  */
10032
10033 static void
10034 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10035                      enum language pretend_language)
10036 {
10037   gdb_assert (! this_cu->is_debug_types);
10038
10039   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10040                            load_full_comp_unit_reader, &pretend_language);
10041 }
10042
10043 /* Add a DIE to the delayed physname list.  */
10044
10045 static void
10046 add_to_method_list (struct type *type, int fnfield_index, int index,
10047                     const char *name, struct die_info *die,
10048                     struct dwarf2_cu *cu)
10049 {
10050   struct delayed_method_info mi;
10051   mi.type = type;
10052   mi.fnfield_index = fnfield_index;
10053   mi.index = index;
10054   mi.name = name;
10055   mi.die = die;
10056   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
10057 }
10058
10059 /* A cleanup for freeing the delayed method list.  */
10060
10061 static void
10062 free_delayed_list (void *ptr)
10063 {
10064   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
10065   if (cu->method_list != NULL)
10066     {
10067       VEC_free (delayed_method_info, cu->method_list);
10068       cu->method_list = NULL;
10069     }
10070 }
10071
10072 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10073    "const" / "volatile".  If so, decrements LEN by the length of the
10074    modifier and return true.  Otherwise return false.  */
10075
10076 template<size_t N>
10077 static bool
10078 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10079 {
10080   size_t mod_len = sizeof (mod) - 1;
10081   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10082     {
10083       len -= mod_len;
10084       return true;
10085     }
10086   return false;
10087 }
10088
10089 /* Compute the physnames of any methods on the CU's method list.
10090
10091    The computation of method physnames is delayed in order to avoid the
10092    (bad) condition that one of the method's formal parameters is of an as yet
10093    incomplete type.  */
10094
10095 static void
10096 compute_delayed_physnames (struct dwarf2_cu *cu)
10097 {
10098   int i;
10099   struct delayed_method_info *mi;
10100
10101   /* Only C++ delays computing physnames.  */
10102   if (VEC_empty (delayed_method_info, cu->method_list))
10103     return;
10104   gdb_assert (cu->language == language_cplus);
10105
10106   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
10107     {
10108       const char *physname;
10109       struct fn_fieldlist *fn_flp
10110         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
10111       physname = dwarf2_physname (mi->name, mi->die, cu);
10112       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
10113         = physname ? physname : "";
10114
10115       /* Since there's no tag to indicate whether a method is a
10116          const/volatile overload, extract that information out of the
10117          demangled name.  */
10118       if (physname != NULL)
10119         {
10120           size_t len = strlen (physname);
10121
10122           while (1)
10123             {
10124               if (physname[len] == ')') /* shortcut */
10125                 break;
10126               else if (check_modifier (physname, len, " const"))
10127                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
10128               else if (check_modifier (physname, len, " volatile"))
10129                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
10130               else
10131                 break;
10132             }
10133         }
10134     }
10135 }
10136
10137 /* Go objects should be embedded in a DW_TAG_module DIE,
10138    and it's not clear if/how imported objects will appear.
10139    To keep Go support simple until that's worked out,
10140    go back through what we've read and create something usable.
10141    We could do this while processing each DIE, and feels kinda cleaner,
10142    but that way is more invasive.
10143    This is to, for example, allow the user to type "p var" or "b main"
10144    without having to specify the package name, and allow lookups
10145    of module.object to work in contexts that use the expression
10146    parser.  */
10147
10148 static void
10149 fixup_go_packaging (struct dwarf2_cu *cu)
10150 {
10151   char *package_name = NULL;
10152   struct pending *list;
10153   int i;
10154
10155   for (list = global_symbols; list != NULL; list = list->next)
10156     {
10157       for (i = 0; i < list->nsyms; ++i)
10158         {
10159           struct symbol *sym = list->symbol[i];
10160
10161           if (SYMBOL_LANGUAGE (sym) == language_go
10162               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10163             {
10164               char *this_package_name = go_symbol_package_name (sym);
10165
10166               if (this_package_name == NULL)
10167                 continue;
10168               if (package_name == NULL)
10169                 package_name = this_package_name;
10170               else
10171                 {
10172                   if (strcmp (package_name, this_package_name) != 0)
10173                     complaint (&symfile_complaints,
10174                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10175                                (symbol_symtab (sym) != NULL
10176                                 ? symtab_to_filename_for_display
10177                                     (symbol_symtab (sym))
10178                                 : objfile_name (cu->objfile)),
10179                                this_package_name, package_name);
10180                   xfree (this_package_name);
10181                 }
10182             }
10183         }
10184     }
10185
10186   if (package_name != NULL)
10187     {
10188       struct objfile *objfile = cu->objfile;
10189       const char *saved_package_name
10190         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10191                                         package_name,
10192                                         strlen (package_name));
10193       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10194                                      saved_package_name);
10195       struct symbol *sym;
10196
10197       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10198
10199       sym = allocate_symbol (objfile);
10200       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10201       SYMBOL_SET_NAMES (sym, saved_package_name,
10202                         strlen (saved_package_name), 0, objfile);
10203       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10204          e.g., "main" finds the "main" module and not C's main().  */
10205       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10206       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10207       SYMBOL_TYPE (sym) = type;
10208
10209       add_symbol_to_list (sym, &global_symbols);
10210
10211       xfree (package_name);
10212     }
10213 }
10214
10215 /* Return the symtab for PER_CU.  This works properly regardless of
10216    whether we're using the index or psymtabs.  */
10217
10218 static struct compunit_symtab *
10219 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10220 {
10221   return (dwarf2_per_objfile->using_index
10222           ? per_cu->v.quick->compunit_symtab
10223           : per_cu->v.psymtab->compunit_symtab);
10224 }
10225
10226 /* A helper function for computing the list of all symbol tables
10227    included by PER_CU.  */
10228
10229 static void
10230 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10231                                 htab_t all_children, htab_t all_type_symtabs,
10232                                 struct dwarf2_per_cu_data *per_cu,
10233                                 struct compunit_symtab *immediate_parent)
10234 {
10235   void **slot;
10236   int ix;
10237   struct compunit_symtab *cust;
10238   struct dwarf2_per_cu_data *iter;
10239
10240   slot = htab_find_slot (all_children, per_cu, INSERT);
10241   if (*slot != NULL)
10242     {
10243       /* This inclusion and its children have been processed.  */
10244       return;
10245     }
10246
10247   *slot = per_cu;
10248   /* Only add a CU if it has a symbol table.  */
10249   cust = get_compunit_symtab (per_cu);
10250   if (cust != NULL)
10251     {
10252       /* If this is a type unit only add its symbol table if we haven't
10253          seen it yet (type unit per_cu's can share symtabs).  */
10254       if (per_cu->is_debug_types)
10255         {
10256           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10257           if (*slot == NULL)
10258             {
10259               *slot = cust;
10260               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10261               if (cust->user == NULL)
10262                 cust->user = immediate_parent;
10263             }
10264         }
10265       else
10266         {
10267           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10268           if (cust->user == NULL)
10269             cust->user = immediate_parent;
10270         }
10271     }
10272
10273   for (ix = 0;
10274        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10275        ++ix)
10276     {
10277       recursively_compute_inclusions (result, all_children,
10278                                       all_type_symtabs, iter, cust);
10279     }
10280 }
10281
10282 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10283    PER_CU.  */
10284
10285 static void
10286 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10287 {
10288   gdb_assert (! per_cu->is_debug_types);
10289
10290   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10291     {
10292       int ix, len;
10293       struct dwarf2_per_cu_data *per_cu_iter;
10294       struct compunit_symtab *compunit_symtab_iter;
10295       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10296       htab_t all_children, all_type_symtabs;
10297       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10298
10299       /* If we don't have a symtab, we can just skip this case.  */
10300       if (cust == NULL)
10301         return;
10302
10303       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10304                                         NULL, xcalloc, xfree);
10305       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10306                                             NULL, xcalloc, xfree);
10307
10308       for (ix = 0;
10309            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10310                         ix, per_cu_iter);
10311            ++ix)
10312         {
10313           recursively_compute_inclusions (&result_symtabs, all_children,
10314                                           all_type_symtabs, per_cu_iter,
10315                                           cust);
10316         }
10317
10318       /* Now we have a transitive closure of all the included symtabs.  */
10319       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10320       cust->includes
10321         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
10322                      struct compunit_symtab *, len + 1);
10323       for (ix = 0;
10324            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10325                         compunit_symtab_iter);
10326            ++ix)
10327         cust->includes[ix] = compunit_symtab_iter;
10328       cust->includes[len] = NULL;
10329
10330       VEC_free (compunit_symtab_ptr, result_symtabs);
10331       htab_delete (all_children);
10332       htab_delete (all_type_symtabs);
10333     }
10334 }
10335
10336 /* Compute the 'includes' field for the symtabs of all the CUs we just
10337    read.  */
10338
10339 static void
10340 process_cu_includes (void)
10341 {
10342   int ix;
10343   struct dwarf2_per_cu_data *iter;
10344
10345   for (ix = 0;
10346        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10347                     ix, iter);
10348        ++ix)
10349     {
10350       if (! iter->is_debug_types)
10351         compute_compunit_symtab_includes (iter);
10352     }
10353
10354   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10355 }
10356
10357 /* Generate full symbol information for PER_CU, whose DIEs have
10358    already been loaded into memory.  */
10359
10360 static void
10361 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10362                         enum language pretend_language)
10363 {
10364   struct dwarf2_cu *cu = per_cu->cu;
10365   struct objfile *objfile = per_cu->objfile;
10366   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10367   CORE_ADDR lowpc, highpc;
10368   struct compunit_symtab *cust;
10369   struct cleanup *delayed_list_cleanup;
10370   CORE_ADDR baseaddr;
10371   struct block *static_block;
10372   CORE_ADDR addr;
10373
10374   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10375
10376   buildsym_init ();
10377   scoped_free_pendings free_pending;
10378   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10379
10380   cu->list_in_scope = &file_symbols;
10381
10382   cu->language = pretend_language;
10383   cu->language_defn = language_def (cu->language);
10384
10385   /* Do line number decoding in read_file_scope () */
10386   process_die (cu->dies, cu);
10387
10388   /* For now fudge the Go package.  */
10389   if (cu->language == language_go)
10390     fixup_go_packaging (cu);
10391
10392   /* Now that we have processed all the DIEs in the CU, all the types 
10393      should be complete, and it should now be safe to compute all of the
10394      physnames.  */
10395   compute_delayed_physnames (cu);
10396   do_cleanups (delayed_list_cleanup);
10397
10398   /* Some compilers don't define a DW_AT_high_pc attribute for the
10399      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10400      it, by scanning the DIE's below the compilation unit.  */
10401   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10402
10403   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10404   static_block = end_symtab_get_static_block (addr, 0, 1);
10405
10406   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10407      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10408      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10409      addrmap to help ensure it has an accurate map of pc values belonging to
10410      this comp unit.  */
10411   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10412
10413   cust = end_symtab_from_static_block (static_block,
10414                                        SECT_OFF_TEXT (objfile), 0);
10415
10416   if (cust != NULL)
10417     {
10418       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10419
10420       /* Set symtab language to language from DW_AT_language.  If the
10421          compilation is from a C file generated by language preprocessors, do
10422          not set the language if it was already deduced by start_subfile.  */
10423       if (!(cu->language == language_c
10424             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10425         COMPUNIT_FILETABS (cust)->language = cu->language;
10426
10427       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10428          produce DW_AT_location with location lists but it can be possibly
10429          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10430          there were bugs in prologue debug info, fixed later in GCC-4.5
10431          by "unwind info for epilogues" patch (which is not directly related).
10432
10433          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10434          needed, it would be wrong due to missing DW_AT_producer there.
10435
10436          Still one can confuse GDB by using non-standard GCC compilation
10437          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10438          */ 
10439       if (cu->has_loclist && gcc_4_minor >= 5)
10440         cust->locations_valid = 1;
10441
10442       if (gcc_4_minor >= 5)
10443         cust->epilogue_unwind_valid = 1;
10444
10445       cust->call_site_htab = cu->call_site_htab;
10446     }
10447
10448   if (dwarf2_per_objfile->using_index)
10449     per_cu->v.quick->compunit_symtab = cust;
10450   else
10451     {
10452       struct partial_symtab *pst = per_cu->v.psymtab;
10453       pst->compunit_symtab = cust;
10454       pst->readin = 1;
10455     }
10456
10457   /* Push it for inclusion processing later.  */
10458   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10459 }
10460
10461 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10462    already been loaded into memory.  */
10463
10464 static void
10465 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10466                         enum language pretend_language)
10467 {
10468   struct dwarf2_cu *cu = per_cu->cu;
10469   struct objfile *objfile = per_cu->objfile;
10470   struct compunit_symtab *cust;
10471   struct cleanup *delayed_list_cleanup;
10472   struct signatured_type *sig_type;
10473
10474   gdb_assert (per_cu->is_debug_types);
10475   sig_type = (struct signatured_type *) per_cu;
10476
10477   buildsym_init ();
10478   scoped_free_pendings free_pending;
10479   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10480
10481   cu->list_in_scope = &file_symbols;
10482
10483   cu->language = pretend_language;
10484   cu->language_defn = language_def (cu->language);
10485
10486   /* The symbol tables are set up in read_type_unit_scope.  */
10487   process_die (cu->dies, cu);
10488
10489   /* For now fudge the Go package.  */
10490   if (cu->language == language_go)
10491     fixup_go_packaging (cu);
10492
10493   /* Now that we have processed all the DIEs in the CU, all the types 
10494      should be complete, and it should now be safe to compute all of the
10495      physnames.  */
10496   compute_delayed_physnames (cu);
10497   do_cleanups (delayed_list_cleanup);
10498
10499   /* TUs share symbol tables.
10500      If this is the first TU to use this symtab, complete the construction
10501      of it with end_expandable_symtab.  Otherwise, complete the addition of
10502      this TU's symbols to the existing symtab.  */
10503   if (sig_type->type_unit_group->compunit_symtab == NULL)
10504     {
10505       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10506       sig_type->type_unit_group->compunit_symtab = cust;
10507
10508       if (cust != NULL)
10509         {
10510           /* Set symtab language to language from DW_AT_language.  If the
10511              compilation is from a C file generated by language preprocessors,
10512              do not set the language if it was already deduced by
10513              start_subfile.  */
10514           if (!(cu->language == language_c
10515                 && COMPUNIT_FILETABS (cust)->language != language_c))
10516             COMPUNIT_FILETABS (cust)->language = cu->language;
10517         }
10518     }
10519   else
10520     {
10521       augment_type_symtab ();
10522       cust = sig_type->type_unit_group->compunit_symtab;
10523     }
10524
10525   if (dwarf2_per_objfile->using_index)
10526     per_cu->v.quick->compunit_symtab = cust;
10527   else
10528     {
10529       struct partial_symtab *pst = per_cu->v.psymtab;
10530       pst->compunit_symtab = cust;
10531       pst->readin = 1;
10532     }
10533 }
10534
10535 /* Process an imported unit DIE.  */
10536
10537 static void
10538 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10539 {
10540   struct attribute *attr;
10541
10542   /* For now we don't handle imported units in type units.  */
10543   if (cu->per_cu->is_debug_types)
10544     {
10545       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10546                " supported in type units [in module %s]"),
10547              objfile_name (cu->objfile));
10548     }
10549
10550   attr = dwarf2_attr (die, DW_AT_import, cu);
10551   if (attr != NULL)
10552     {
10553       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10554       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10555       dwarf2_per_cu_data *per_cu
10556         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
10557
10558       /* If necessary, add it to the queue and load its DIEs.  */
10559       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10560         load_full_comp_unit (per_cu, cu->language);
10561
10562       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10563                      per_cu);
10564     }
10565 }
10566
10567 /* RAII object that represents a process_die scope: i.e.,
10568    starts/finishes processing a DIE.  */
10569 class process_die_scope
10570 {
10571 public:
10572   process_die_scope (die_info *die, dwarf2_cu *cu)
10573     : m_die (die), m_cu (cu)
10574   {
10575     /* We should only be processing DIEs not already in process.  */
10576     gdb_assert (!m_die->in_process);
10577     m_die->in_process = true;
10578   }
10579
10580   ~process_die_scope ()
10581   {
10582     m_die->in_process = false;
10583
10584     /* If we're done processing the DIE for the CU that owns the line
10585        header, we don't need the line header anymore.  */
10586     if (m_cu->line_header_die_owner == m_die)
10587       {
10588         delete m_cu->line_header;
10589         m_cu->line_header = NULL;
10590         m_cu->line_header_die_owner = NULL;
10591       }
10592   }
10593
10594 private:
10595   die_info *m_die;
10596   dwarf2_cu *m_cu;
10597 };
10598
10599 /* Process a die and its children.  */
10600
10601 static void
10602 process_die (struct die_info *die, struct dwarf2_cu *cu)
10603 {
10604   process_die_scope scope (die, cu);
10605
10606   switch (die->tag)
10607     {
10608     case DW_TAG_padding:
10609       break;
10610     case DW_TAG_compile_unit:
10611     case DW_TAG_partial_unit:
10612       read_file_scope (die, cu);
10613       break;
10614     case DW_TAG_type_unit:
10615       read_type_unit_scope (die, cu);
10616       break;
10617     case DW_TAG_subprogram:
10618     case DW_TAG_inlined_subroutine:
10619       read_func_scope (die, cu);
10620       break;
10621     case DW_TAG_lexical_block:
10622     case DW_TAG_try_block:
10623     case DW_TAG_catch_block:
10624       read_lexical_block_scope (die, cu);
10625       break;
10626     case DW_TAG_call_site:
10627     case DW_TAG_GNU_call_site:
10628       read_call_site_scope (die, cu);
10629       break;
10630     case DW_TAG_class_type:
10631     case DW_TAG_interface_type:
10632     case DW_TAG_structure_type:
10633     case DW_TAG_union_type:
10634       process_structure_scope (die, cu);
10635       break;
10636     case DW_TAG_enumeration_type:
10637       process_enumeration_scope (die, cu);
10638       break;
10639
10640     /* These dies have a type, but processing them does not create
10641        a symbol or recurse to process the children.  Therefore we can
10642        read them on-demand through read_type_die.  */
10643     case DW_TAG_subroutine_type:
10644     case DW_TAG_set_type:
10645     case DW_TAG_array_type:
10646     case DW_TAG_pointer_type:
10647     case DW_TAG_ptr_to_member_type:
10648     case DW_TAG_reference_type:
10649     case DW_TAG_rvalue_reference_type:
10650     case DW_TAG_string_type:
10651       break;
10652
10653     case DW_TAG_base_type:
10654     case DW_TAG_subrange_type:
10655     case DW_TAG_typedef:
10656       /* Add a typedef symbol for the type definition, if it has a
10657          DW_AT_name.  */
10658       new_symbol (die, read_type_die (die, cu), cu);
10659       break;
10660     case DW_TAG_common_block:
10661       read_common_block (die, cu);
10662       break;
10663     case DW_TAG_common_inclusion:
10664       break;
10665     case DW_TAG_namespace:
10666       cu->processing_has_namespace_info = 1;
10667       read_namespace (die, cu);
10668       break;
10669     case DW_TAG_module:
10670       cu->processing_has_namespace_info = 1;
10671       read_module (die, cu);
10672       break;
10673     case DW_TAG_imported_declaration:
10674       cu->processing_has_namespace_info = 1;
10675       if (read_namespace_alias (die, cu))
10676         break;
10677       /* The declaration is not a global namespace alias: fall through.  */
10678     case DW_TAG_imported_module:
10679       cu->processing_has_namespace_info = 1;
10680       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10681                                  || cu->language != language_fortran))
10682         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10683                    dwarf_tag_name (die->tag));
10684       read_import_statement (die, cu);
10685       break;
10686
10687     case DW_TAG_imported_unit:
10688       process_imported_unit_die (die, cu);
10689       break;
10690
10691     case DW_TAG_variable:
10692       read_variable (die, cu);
10693       break;
10694
10695     default:
10696       new_symbol (die, NULL, cu);
10697       break;
10698     }
10699 }
10700 \f
10701 /* DWARF name computation.  */
10702
10703 /* A helper function for dwarf2_compute_name which determines whether DIE
10704    needs to have the name of the scope prepended to the name listed in the
10705    die.  */
10706
10707 static int
10708 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10709 {
10710   struct attribute *attr;
10711
10712   switch (die->tag)
10713     {
10714     case DW_TAG_namespace:
10715     case DW_TAG_typedef:
10716     case DW_TAG_class_type:
10717     case DW_TAG_interface_type:
10718     case DW_TAG_structure_type:
10719     case DW_TAG_union_type:
10720     case DW_TAG_enumeration_type:
10721     case DW_TAG_enumerator:
10722     case DW_TAG_subprogram:
10723     case DW_TAG_inlined_subroutine:
10724     case DW_TAG_member:
10725     case DW_TAG_imported_declaration:
10726       return 1;
10727
10728     case DW_TAG_variable:
10729     case DW_TAG_constant:
10730       /* We only need to prefix "globally" visible variables.  These include
10731          any variable marked with DW_AT_external or any variable that
10732          lives in a namespace.  [Variables in anonymous namespaces
10733          require prefixing, but they are not DW_AT_external.]  */
10734
10735       if (dwarf2_attr (die, DW_AT_specification, cu))
10736         {
10737           struct dwarf2_cu *spec_cu = cu;
10738
10739           return die_needs_namespace (die_specification (die, &spec_cu),
10740                                       spec_cu);
10741         }
10742
10743       attr = dwarf2_attr (die, DW_AT_external, cu);
10744       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10745           && die->parent->tag != DW_TAG_module)
10746         return 0;
10747       /* A variable in a lexical block of some kind does not need a
10748          namespace, even though in C++ such variables may be external
10749          and have a mangled name.  */
10750       if (die->parent->tag ==  DW_TAG_lexical_block
10751           || die->parent->tag ==  DW_TAG_try_block
10752           || die->parent->tag ==  DW_TAG_catch_block
10753           || die->parent->tag == DW_TAG_subprogram)
10754         return 0;
10755       return 1;
10756
10757     default:
10758       return 0;
10759     }
10760 }
10761
10762 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10763    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10764    defined for the given DIE.  */
10765
10766 static struct attribute *
10767 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10768 {
10769   struct attribute *attr;
10770
10771   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10772   if (attr == NULL)
10773     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10774
10775   return attr;
10776 }
10777
10778 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10779    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10780    defined for the given DIE.  */
10781
10782 static const char *
10783 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10784 {
10785   const char *linkage_name;
10786
10787   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10788   if (linkage_name == NULL)
10789     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10790
10791   return linkage_name;
10792 }
10793
10794 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10795    compute the physname for the object, which include a method's:
10796    - formal parameters (C++),
10797    - receiver type (Go),
10798
10799    The term "physname" is a bit confusing.
10800    For C++, for example, it is the demangled name.
10801    For Go, for example, it's the mangled name.
10802
10803    For Ada, return the DIE's linkage name rather than the fully qualified
10804    name.  PHYSNAME is ignored..
10805
10806    The result is allocated on the objfile_obstack and canonicalized.  */
10807
10808 static const char *
10809 dwarf2_compute_name (const char *name,
10810                      struct die_info *die, struct dwarf2_cu *cu,
10811                      int physname)
10812 {
10813   struct objfile *objfile = cu->objfile;
10814
10815   if (name == NULL)
10816     name = dwarf2_name (die, cu);
10817
10818   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10819      but otherwise compute it by typename_concat inside GDB.
10820      FIXME: Actually this is not really true, or at least not always true.
10821      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10822      Fortran names because there is no mangling standard.  So new_symbol_full
10823      will set the demangled name to the result of dwarf2_full_name, and it is
10824      the demangled name that GDB uses if it exists.  */
10825   if (cu->language == language_ada
10826       || (cu->language == language_fortran && physname))
10827     {
10828       /* For Ada unit, we prefer the linkage name over the name, as
10829          the former contains the exported name, which the user expects
10830          to be able to reference.  Ideally, we want the user to be able
10831          to reference this entity using either natural or linkage name,
10832          but we haven't started looking at this enhancement yet.  */
10833       const char *linkage_name = dw2_linkage_name (die, cu);
10834
10835       if (linkage_name != NULL)
10836         return linkage_name;
10837     }
10838
10839   /* These are the only languages we know how to qualify names in.  */
10840   if (name != NULL
10841       && (cu->language == language_cplus
10842           || cu->language == language_fortran || cu->language == language_d
10843           || cu->language == language_rust))
10844     {
10845       if (die_needs_namespace (die, cu))
10846         {
10847           const char *prefix;
10848           const char *canonical_name = NULL;
10849
10850           string_file buf;
10851
10852           prefix = determine_prefix (die, cu);
10853           if (*prefix != '\0')
10854             {
10855               char *prefixed_name = typename_concat (NULL, prefix, name,
10856                                                      physname, cu);
10857
10858               buf.puts (prefixed_name);
10859               xfree (prefixed_name);
10860             }
10861           else
10862             buf.puts (name);
10863
10864           /* Template parameters may be specified in the DIE's DW_AT_name, or
10865              as children with DW_TAG_template_type_param or
10866              DW_TAG_value_type_param.  If the latter, add them to the name
10867              here.  If the name already has template parameters, then
10868              skip this step; some versions of GCC emit both, and
10869              it is more efficient to use the pre-computed name.
10870
10871              Something to keep in mind about this process: it is very
10872              unlikely, or in some cases downright impossible, to produce
10873              something that will match the mangled name of a function.
10874              If the definition of the function has the same debug info,
10875              we should be able to match up with it anyway.  But fallbacks
10876              using the minimal symbol, for instance to find a method
10877              implemented in a stripped copy of libstdc++, will not work.
10878              If we do not have debug info for the definition, we will have to
10879              match them up some other way.
10880
10881              When we do name matching there is a related problem with function
10882              templates; two instantiated function templates are allowed to
10883              differ only by their return types, which we do not add here.  */
10884
10885           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10886             {
10887               struct attribute *attr;
10888               struct die_info *child;
10889               int first = 1;
10890
10891               die->building_fullname = 1;
10892
10893               for (child = die->child; child != NULL; child = child->sibling)
10894                 {
10895                   struct type *type;
10896                   LONGEST value;
10897                   const gdb_byte *bytes;
10898                   struct dwarf2_locexpr_baton *baton;
10899                   struct value *v;
10900
10901                   if (child->tag != DW_TAG_template_type_param
10902                       && child->tag != DW_TAG_template_value_param)
10903                     continue;
10904
10905                   if (first)
10906                     {
10907                       buf.puts ("<");
10908                       first = 0;
10909                     }
10910                   else
10911                     buf.puts (", ");
10912
10913                   attr = dwarf2_attr (child, DW_AT_type, cu);
10914                   if (attr == NULL)
10915                     {
10916                       complaint (&symfile_complaints,
10917                                  _("template parameter missing DW_AT_type"));
10918                       buf.puts ("UNKNOWN_TYPE");
10919                       continue;
10920                     }
10921                   type = die_type (child, cu);
10922
10923                   if (child->tag == DW_TAG_template_type_param)
10924                     {
10925                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10926                       continue;
10927                     }
10928
10929                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10930                   if (attr == NULL)
10931                     {
10932                       complaint (&symfile_complaints,
10933                                  _("template parameter missing "
10934                                    "DW_AT_const_value"));
10935                       buf.puts ("UNKNOWN_VALUE");
10936                       continue;
10937                     }
10938
10939                   dwarf2_const_value_attr (attr, type, name,
10940                                            &cu->comp_unit_obstack, cu,
10941                                            &value, &bytes, &baton);
10942
10943                   if (TYPE_NOSIGN (type))
10944                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10945                        changed, this can use value_print instead.  */
10946                     c_printchar (value, type, &buf);
10947                   else
10948                     {
10949                       struct value_print_options opts;
10950
10951                       if (baton != NULL)
10952                         v = dwarf2_evaluate_loc_desc (type, NULL,
10953                                                       baton->data,
10954                                                       baton->size,
10955                                                       baton->per_cu);
10956                       else if (bytes != NULL)
10957                         {
10958                           v = allocate_value (type);
10959                           memcpy (value_contents_writeable (v), bytes,
10960                                   TYPE_LENGTH (type));
10961                         }
10962                       else
10963                         v = value_from_longest (type, value);
10964
10965                       /* Specify decimal so that we do not depend on
10966                          the radix.  */
10967                       get_formatted_print_options (&opts, 'd');
10968                       opts.raw = 1;
10969                       value_print (v, &buf, &opts);
10970                       release_value (v);
10971                       value_free (v);
10972                     }
10973                 }
10974
10975               die->building_fullname = 0;
10976
10977               if (!first)
10978                 {
10979                   /* Close the argument list, with a space if necessary
10980                      (nested templates).  */
10981                   if (!buf.empty () && buf.string ().back () == '>')
10982                     buf.puts (" >");
10983                   else
10984                     buf.puts (">");
10985                 }
10986             }
10987
10988           /* For C++ methods, append formal parameter type
10989              information, if PHYSNAME.  */
10990
10991           if (physname && die->tag == DW_TAG_subprogram
10992               && cu->language == language_cplus)
10993             {
10994               struct type *type = read_type_die (die, cu);
10995
10996               c_type_print_args (type, &buf, 1, cu->language,
10997                                  &type_print_raw_options);
10998
10999               if (cu->language == language_cplus)
11000                 {
11001                   /* Assume that an artificial first parameter is
11002                      "this", but do not crash if it is not.  RealView
11003                      marks unnamed (and thus unused) parameters as
11004                      artificial; there is no way to differentiate
11005                      the two cases.  */
11006                   if (TYPE_NFIELDS (type) > 0
11007                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11008                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11009                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11010                                                                         0))))
11011                     buf.puts (" const");
11012                 }
11013             }
11014
11015           const std::string &intermediate_name = buf.string ();
11016
11017           if (cu->language == language_cplus)
11018             canonical_name
11019               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11020                                           &objfile->per_bfd->storage_obstack);
11021
11022           /* If we only computed INTERMEDIATE_NAME, or if
11023              INTERMEDIATE_NAME is already canonical, then we need to
11024              copy it to the appropriate obstack.  */
11025           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11026             name = ((const char *)
11027                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11028                                    intermediate_name.c_str (),
11029                                    intermediate_name.length ()));
11030           else
11031             name = canonical_name;
11032         }
11033     }
11034
11035   return name;
11036 }
11037
11038 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11039    If scope qualifiers are appropriate they will be added.  The result
11040    will be allocated on the storage_obstack, or NULL if the DIE does
11041    not have a name.  NAME may either be from a previous call to
11042    dwarf2_name or NULL.
11043
11044    The output string will be canonicalized (if C++).  */
11045
11046 static const char *
11047 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11048 {
11049   return dwarf2_compute_name (name, die, cu, 0);
11050 }
11051
11052 /* Construct a physname for the given DIE in CU.  NAME may either be
11053    from a previous call to dwarf2_name or NULL.  The result will be
11054    allocated on the objfile_objstack or NULL if the DIE does not have a
11055    name.
11056
11057    The output string will be canonicalized (if C++).  */
11058
11059 static const char *
11060 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11061 {
11062   struct objfile *objfile = cu->objfile;
11063   const char *retval, *mangled = NULL, *canon = NULL;
11064   int need_copy = 1;
11065
11066   /* In this case dwarf2_compute_name is just a shortcut not building anything
11067      on its own.  */
11068   if (!die_needs_namespace (die, cu))
11069     return dwarf2_compute_name (name, die, cu, 1);
11070
11071   mangled = dw2_linkage_name (die, cu);
11072
11073   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11074      See https://github.com/rust-lang/rust/issues/32925.  */
11075   if (cu->language == language_rust && mangled != NULL
11076       && strchr (mangled, '{') != NULL)
11077     mangled = NULL;
11078
11079   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11080      has computed.  */
11081   gdb::unique_xmalloc_ptr<char> demangled;
11082   if (mangled != NULL)
11083     {
11084       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
11085          type.  It is easier for GDB users to search for such functions as
11086          `name(params)' than `long name(params)'.  In such case the minimal
11087          symbol names do not match the full symbol names but for template
11088          functions there is never a need to look up their definition from their
11089          declaration so the only disadvantage remains the minimal symbol
11090          variant `long name(params)' does not have the proper inferior type.
11091          */
11092
11093       if (cu->language == language_go)
11094         {
11095           /* This is a lie, but we already lie to the caller new_symbol_full.
11096              new_symbol_full assumes we return the mangled name.
11097              This just undoes that lie until things are cleaned up.  */
11098         }
11099       else
11100         {
11101           demangled.reset (gdb_demangle (mangled,
11102                                          (DMGL_PARAMS | DMGL_ANSI
11103                                           | DMGL_RET_DROP)));
11104         }
11105       if (demangled)
11106         canon = demangled.get ();
11107       else
11108         {
11109           canon = mangled;
11110           need_copy = 0;
11111         }
11112     }
11113
11114   if (canon == NULL || check_physname)
11115     {
11116       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11117
11118       if (canon != NULL && strcmp (physname, canon) != 0)
11119         {
11120           /* It may not mean a bug in GDB.  The compiler could also
11121              compute DW_AT_linkage_name incorrectly.  But in such case
11122              GDB would need to be bug-to-bug compatible.  */
11123
11124           complaint (&symfile_complaints,
11125                      _("Computed physname <%s> does not match demangled <%s> "
11126                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11127                      physname, canon, mangled, to_underlying (die->sect_off),
11128                      objfile_name (objfile));
11129
11130           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11131              is available here - over computed PHYSNAME.  It is safer
11132              against both buggy GDB and buggy compilers.  */
11133
11134           retval = canon;
11135         }
11136       else
11137         {
11138           retval = physname;
11139           need_copy = 0;
11140         }
11141     }
11142   else
11143     retval = canon;
11144
11145   if (need_copy)
11146     retval = ((const char *)
11147               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11148                              retval, strlen (retval)));
11149
11150   return retval;
11151 }
11152
11153 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11154    a new symbol for it.
11155
11156    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11157
11158 static int
11159 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11160 {
11161   struct attribute *attr;
11162
11163   /* If the die does not have a name, this is not a namespace
11164      alias.  */
11165   attr = dwarf2_attr (die, DW_AT_name, cu);
11166   if (attr != NULL)
11167     {
11168       int num;
11169       struct die_info *d = die;
11170       struct dwarf2_cu *imported_cu = cu;
11171
11172       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11173          keep inspecting DIEs until we hit the underlying import.  */
11174 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11175       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11176         {
11177           attr = dwarf2_attr (d, DW_AT_import, cu);
11178           if (attr == NULL)
11179             break;
11180
11181           d = follow_die_ref (d, attr, &imported_cu);
11182           if (d->tag != DW_TAG_imported_declaration)
11183             break;
11184         }
11185
11186       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11187         {
11188           complaint (&symfile_complaints,
11189                      _("DIE at 0x%x has too many recursively imported "
11190                        "declarations"), to_underlying (d->sect_off));
11191           return 0;
11192         }
11193
11194       if (attr != NULL)
11195         {
11196           struct type *type;
11197           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11198
11199           type = get_die_type_at_offset (sect_off, cu->per_cu);
11200           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11201             {
11202               /* This declaration is a global namespace alias.  Add
11203                  a symbol for it whose type is the aliased namespace.  */
11204               new_symbol (die, type, cu);
11205               return 1;
11206             }
11207         }
11208     }
11209
11210   return 0;
11211 }
11212
11213 /* Return the using directives repository (global or local?) to use in the
11214    current context for LANGUAGE.
11215
11216    For Ada, imported declarations can materialize renamings, which *may* be
11217    global.  However it is impossible (for now?) in DWARF to distinguish
11218    "external" imported declarations and "static" ones.  As all imported
11219    declarations seem to be static in all other languages, make them all CU-wide
11220    global only in Ada.  */
11221
11222 static struct using_direct **
11223 using_directives (enum language language)
11224 {
11225   if (language == language_ada && context_stack_depth == 0)
11226     return &global_using_directives;
11227   else
11228     return &local_using_directives;
11229 }
11230
11231 /* Read the import statement specified by the given die and record it.  */
11232
11233 static void
11234 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11235 {
11236   struct objfile *objfile = cu->objfile;
11237   struct attribute *import_attr;
11238   struct die_info *imported_die, *child_die;
11239   struct dwarf2_cu *imported_cu;
11240   const char *imported_name;
11241   const char *imported_name_prefix;
11242   const char *canonical_name;
11243   const char *import_alias;
11244   const char *imported_declaration = NULL;
11245   const char *import_prefix;
11246   std::vector<const char *> excludes;
11247
11248   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11249   if (import_attr == NULL)
11250     {
11251       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11252                  dwarf_tag_name (die->tag));
11253       return;
11254     }
11255
11256   imported_cu = cu;
11257   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11258   imported_name = dwarf2_name (imported_die, imported_cu);
11259   if (imported_name == NULL)
11260     {
11261       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11262
11263         The import in the following code:
11264         namespace A
11265           {
11266             typedef int B;
11267           }
11268
11269         int main ()
11270           {
11271             using A::B;
11272             B b;
11273             return b;
11274           }
11275
11276         ...
11277          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11278             <52>   DW_AT_decl_file   : 1
11279             <53>   DW_AT_decl_line   : 6
11280             <54>   DW_AT_import      : <0x75>
11281          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11282             <59>   DW_AT_name        : B
11283             <5b>   DW_AT_decl_file   : 1
11284             <5c>   DW_AT_decl_line   : 2
11285             <5d>   DW_AT_type        : <0x6e>
11286         ...
11287          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11288             <76>   DW_AT_byte_size   : 4
11289             <77>   DW_AT_encoding    : 5        (signed)
11290
11291         imports the wrong die ( 0x75 instead of 0x58 ).
11292         This case will be ignored until the gcc bug is fixed.  */
11293       return;
11294     }
11295
11296   /* Figure out the local name after import.  */
11297   import_alias = dwarf2_name (die, cu);
11298
11299   /* Figure out where the statement is being imported to.  */
11300   import_prefix = determine_prefix (die, cu);
11301
11302   /* Figure out what the scope of the imported die is and prepend it
11303      to the name of the imported die.  */
11304   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11305
11306   if (imported_die->tag != DW_TAG_namespace
11307       && imported_die->tag != DW_TAG_module)
11308     {
11309       imported_declaration = imported_name;
11310       canonical_name = imported_name_prefix;
11311     }
11312   else if (strlen (imported_name_prefix) > 0)
11313     canonical_name = obconcat (&objfile->objfile_obstack,
11314                                imported_name_prefix,
11315                                (cu->language == language_d ? "." : "::"),
11316                                imported_name, (char *) NULL);
11317   else
11318     canonical_name = imported_name;
11319
11320   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11321     for (child_die = die->child; child_die && child_die->tag;
11322          child_die = sibling_die (child_die))
11323       {
11324         /* DWARF-4: A Fortran use statement with a “rename list” may be
11325            represented by an imported module entry with an import attribute
11326            referring to the module and owned entries corresponding to those
11327            entities that are renamed as part of being imported.  */
11328
11329         if (child_die->tag != DW_TAG_imported_declaration)
11330           {
11331             complaint (&symfile_complaints,
11332                        _("child DW_TAG_imported_declaration expected "
11333                          "- DIE at 0x%x [in module %s]"),
11334                        to_underlying (child_die->sect_off), objfile_name (objfile));
11335             continue;
11336           }
11337
11338         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11339         if (import_attr == NULL)
11340           {
11341             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11342                        dwarf_tag_name (child_die->tag));
11343             continue;
11344           }
11345
11346         imported_cu = cu;
11347         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11348                                               &imported_cu);
11349         imported_name = dwarf2_name (imported_die, imported_cu);
11350         if (imported_name == NULL)
11351           {
11352             complaint (&symfile_complaints,
11353                        _("child DW_TAG_imported_declaration has unknown "
11354                          "imported name - DIE at 0x%x [in module %s]"),
11355                        to_underlying (child_die->sect_off), objfile_name (objfile));
11356             continue;
11357           }
11358
11359         excludes.push_back (imported_name);
11360
11361         process_die (child_die, cu);
11362       }
11363
11364   add_using_directive (using_directives (cu->language),
11365                        import_prefix,
11366                        canonical_name,
11367                        import_alias,
11368                        imported_declaration,
11369                        excludes,
11370                        0,
11371                        &objfile->objfile_obstack);
11372 }
11373
11374 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11375    types, but gives them a size of zero.  Starting with version 14,
11376    ICC is compatible with GCC.  */
11377
11378 static int
11379 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11380 {
11381   if (!cu->checked_producer)
11382     check_producer (cu);
11383
11384   return cu->producer_is_icc_lt_14;
11385 }
11386
11387 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11388    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11389    this, it was first present in GCC release 4.3.0.  */
11390
11391 static int
11392 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11393 {
11394   if (!cu->checked_producer)
11395     check_producer (cu);
11396
11397   return cu->producer_is_gcc_lt_4_3;
11398 }
11399
11400 static file_and_directory
11401 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11402 {
11403   file_and_directory res;
11404
11405   /* Find the filename.  Do not use dwarf2_name here, since the filename
11406      is not a source language identifier.  */
11407   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11408   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11409
11410   if (res.comp_dir == NULL
11411       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11412       && IS_ABSOLUTE_PATH (res.name))
11413     {
11414       res.comp_dir_storage = ldirname (res.name);
11415       if (!res.comp_dir_storage.empty ())
11416         res.comp_dir = res.comp_dir_storage.c_str ();
11417     }
11418   if (res.comp_dir != NULL)
11419     {
11420       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11421          directory, get rid of it.  */
11422       const char *cp = strchr (res.comp_dir, ':');
11423
11424       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11425         res.comp_dir = cp + 1;
11426     }
11427
11428   if (res.name == NULL)
11429     res.name = "<unknown>";
11430
11431   return res;
11432 }
11433
11434 /* Handle DW_AT_stmt_list for a compilation unit.
11435    DIE is the DW_TAG_compile_unit die for CU.
11436    COMP_DIR is the compilation directory.  LOWPC is passed to
11437    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11438
11439 static void
11440 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11441                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11442 {
11443   struct objfile *objfile = dwarf2_per_objfile->objfile;
11444   struct attribute *attr;
11445   struct line_header line_header_local;
11446   hashval_t line_header_local_hash;
11447   void **slot;
11448   int decode_mapping;
11449
11450   gdb_assert (! cu->per_cu->is_debug_types);
11451
11452   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11453   if (attr == NULL)
11454     return;
11455
11456   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11457
11458   /* The line header hash table is only created if needed (it exists to
11459      prevent redundant reading of the line table for partial_units).
11460      If we're given a partial_unit, we'll need it.  If we're given a
11461      compile_unit, then use the line header hash table if it's already
11462      created, but don't create one just yet.  */
11463
11464   if (dwarf2_per_objfile->line_header_hash == NULL
11465       && die->tag == DW_TAG_partial_unit)
11466     {
11467       dwarf2_per_objfile->line_header_hash
11468         = htab_create_alloc_ex (127, line_header_hash_voidp,
11469                                 line_header_eq_voidp,
11470                                 free_line_header_voidp,
11471                                 &objfile->objfile_obstack,
11472                                 hashtab_obstack_allocate,
11473                                 dummy_obstack_deallocate);
11474     }
11475
11476   line_header_local.sect_off = line_offset;
11477   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11478   line_header_local_hash = line_header_hash (&line_header_local);
11479   if (dwarf2_per_objfile->line_header_hash != NULL)
11480     {
11481       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11482                                        &line_header_local,
11483                                        line_header_local_hash, NO_INSERT);
11484
11485       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11486          is not present in *SLOT (since if there is something in *SLOT then
11487          it will be for a partial_unit).  */
11488       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11489         {
11490           gdb_assert (*slot != NULL);
11491           cu->line_header = (struct line_header *) *slot;
11492           return;
11493         }
11494     }
11495
11496   /* dwarf_decode_line_header does not yet provide sufficient information.
11497      We always have to call also dwarf_decode_lines for it.  */
11498   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11499   if (lh == NULL)
11500     return;
11501
11502   cu->line_header = lh.release ();
11503   cu->line_header_die_owner = die;
11504
11505   if (dwarf2_per_objfile->line_header_hash == NULL)
11506     slot = NULL;
11507   else
11508     {
11509       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11510                                        &line_header_local,
11511                                        line_header_local_hash, INSERT);
11512       gdb_assert (slot != NULL);
11513     }
11514   if (slot != NULL && *slot == NULL)
11515     {
11516       /* This newly decoded line number information unit will be owned
11517          by line_header_hash hash table.  */
11518       *slot = cu->line_header;
11519       cu->line_header_die_owner = NULL;
11520     }
11521   else
11522     {
11523       /* We cannot free any current entry in (*slot) as that struct line_header
11524          may be already used by multiple CUs.  Create only temporary decoded
11525          line_header for this CU - it may happen at most once for each line
11526          number information unit.  And if we're not using line_header_hash
11527          then this is what we want as well.  */
11528       gdb_assert (die->tag != DW_TAG_partial_unit);
11529     }
11530   decode_mapping = (die->tag != DW_TAG_partial_unit);
11531   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11532                       decode_mapping);
11533
11534 }
11535
11536 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11537
11538 static void
11539 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11540 {
11541   struct objfile *objfile = dwarf2_per_objfile->objfile;
11542   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11543   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11544   CORE_ADDR highpc = ((CORE_ADDR) 0);
11545   struct attribute *attr;
11546   struct die_info *child_die;
11547   CORE_ADDR baseaddr;
11548
11549   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11550
11551   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11552
11553   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11554      from finish_block.  */
11555   if (lowpc == ((CORE_ADDR) -1))
11556     lowpc = highpc;
11557   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11558
11559   file_and_directory fnd = find_file_and_directory (die, cu);
11560
11561   prepare_one_comp_unit (cu, die, cu->language);
11562
11563   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11564      standardised yet.  As a workaround for the language detection we fall
11565      back to the DW_AT_producer string.  */
11566   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11567     cu->language = language_opencl;
11568
11569   /* Similar hack for Go.  */
11570   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11571     set_cu_language (DW_LANG_Go, cu);
11572
11573   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11574
11575   /* Decode line number information if present.  We do this before
11576      processing child DIEs, so that the line header table is available
11577      for DW_AT_decl_file.  */
11578   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11579
11580   /* Process all dies in compilation unit.  */
11581   if (die->child != NULL)
11582     {
11583       child_die = die->child;
11584       while (child_die && child_die->tag)
11585         {
11586           process_die (child_die, cu);
11587           child_die = sibling_die (child_die);
11588         }
11589     }
11590
11591   /* Decode macro information, if present.  Dwarf 2 macro information
11592      refers to information in the line number info statement program
11593      header, so we can only read it if we've read the header
11594      successfully.  */
11595   attr = dwarf2_attr (die, DW_AT_macros, cu);
11596   if (attr == NULL)
11597     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11598   if (attr && cu->line_header)
11599     {
11600       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11601         complaint (&symfile_complaints,
11602                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11603
11604       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11605     }
11606   else
11607     {
11608       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11609       if (attr && cu->line_header)
11610         {
11611           unsigned int macro_offset = DW_UNSND (attr);
11612
11613           dwarf_decode_macros (cu, macro_offset, 0);
11614         }
11615     }
11616 }
11617
11618 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11619    Create the set of symtabs used by this TU, or if this TU is sharing
11620    symtabs with another TU and the symtabs have already been created
11621    then restore those symtabs in the line header.
11622    We don't need the pc/line-number mapping for type units.  */
11623
11624 static void
11625 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11626 {
11627   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11628   struct type_unit_group *tu_group;
11629   int first_time;
11630   struct attribute *attr;
11631   unsigned int i;
11632   struct signatured_type *sig_type;
11633
11634   gdb_assert (per_cu->is_debug_types);
11635   sig_type = (struct signatured_type *) per_cu;
11636
11637   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11638
11639   /* If we're using .gdb_index (includes -readnow) then
11640      per_cu->type_unit_group may not have been set up yet.  */
11641   if (sig_type->type_unit_group == NULL)
11642     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11643   tu_group = sig_type->type_unit_group;
11644
11645   /* If we've already processed this stmt_list there's no real need to
11646      do it again, we could fake it and just recreate the part we need
11647      (file name,index -> symtab mapping).  If data shows this optimization
11648      is useful we can do it then.  */
11649   first_time = tu_group->compunit_symtab == NULL;
11650
11651   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11652      debug info.  */
11653   line_header_up lh;
11654   if (attr != NULL)
11655     {
11656       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11657       lh = dwarf_decode_line_header (line_offset, cu);
11658     }
11659   if (lh == NULL)
11660     {
11661       if (first_time)
11662         dwarf2_start_symtab (cu, "", NULL, 0);
11663       else
11664         {
11665           gdb_assert (tu_group->symtabs == NULL);
11666           restart_symtab (tu_group->compunit_symtab, "", 0);
11667         }
11668       return;
11669     }
11670
11671   cu->line_header = lh.release ();
11672   cu->line_header_die_owner = die;
11673
11674   if (first_time)
11675     {
11676       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11677
11678       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11679          still initializing it, and our caller (a few levels up)
11680          process_full_type_unit still needs to know if this is the first
11681          time.  */
11682
11683       tu_group->num_symtabs = cu->line_header->file_names.size ();
11684       tu_group->symtabs = XNEWVEC (struct symtab *,
11685                                    cu->line_header->file_names.size ());
11686
11687       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11688         {
11689           file_entry &fe = cu->line_header->file_names[i];
11690
11691           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11692
11693           if (current_subfile->symtab == NULL)
11694             {
11695               /* NOTE: start_subfile will recognize when it's been
11696                  passed a file it has already seen.  So we can't
11697                  assume there's a simple mapping from
11698                  cu->line_header->file_names to subfiles, plus
11699                  cu->line_header->file_names may contain dups.  */
11700               current_subfile->symtab
11701                 = allocate_symtab (cust, current_subfile->name);
11702             }
11703
11704           fe.symtab = current_subfile->symtab;
11705           tu_group->symtabs[i] = fe.symtab;
11706         }
11707     }
11708   else
11709     {
11710       restart_symtab (tu_group->compunit_symtab, "", 0);
11711
11712       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11713         {
11714           file_entry &fe = cu->line_header->file_names[i];
11715
11716           fe.symtab = tu_group->symtabs[i];
11717         }
11718     }
11719
11720   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11721      so they don't have a "real" (so to speak) symtab anyway.
11722      There is later code that will assign the main symtab to all symbols
11723      that don't have one.  We need to handle the case of a symbol with a
11724      missing symtab (DW_AT_decl_file) anyway.  */
11725 }
11726
11727 /* Process DW_TAG_type_unit.
11728    For TUs we want to skip the first top level sibling if it's not the
11729    actual type being defined by this TU.  In this case the first top
11730    level sibling is there to provide context only.  */
11731
11732 static void
11733 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11734 {
11735   struct die_info *child_die;
11736
11737   prepare_one_comp_unit (cu, die, language_minimal);
11738
11739   /* Initialize (or reinitialize) the machinery for building symtabs.
11740      We do this before processing child DIEs, so that the line header table
11741      is available for DW_AT_decl_file.  */
11742   setup_type_unit_groups (die, cu);
11743
11744   if (die->child != NULL)
11745     {
11746       child_die = die->child;
11747       while (child_die && child_die->tag)
11748         {
11749           process_die (child_die, cu);
11750           child_die = sibling_die (child_die);
11751         }
11752     }
11753 }
11754 \f
11755 /* DWO/DWP files.
11756
11757    http://gcc.gnu.org/wiki/DebugFission
11758    http://gcc.gnu.org/wiki/DebugFissionDWP
11759
11760    To simplify handling of both DWO files ("object" files with the DWARF info)
11761    and DWP files (a file with the DWOs packaged up into one file), we treat
11762    DWP files as having a collection of virtual DWO files.  */
11763
11764 static hashval_t
11765 hash_dwo_file (const void *item)
11766 {
11767   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11768   hashval_t hash;
11769
11770   hash = htab_hash_string (dwo_file->dwo_name);
11771   if (dwo_file->comp_dir != NULL)
11772     hash += htab_hash_string (dwo_file->comp_dir);
11773   return hash;
11774 }
11775
11776 static int
11777 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11778 {
11779   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11780   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11781
11782   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11783     return 0;
11784   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11785     return lhs->comp_dir == rhs->comp_dir;
11786   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11787 }
11788
11789 /* Allocate a hash table for DWO files.  */
11790
11791 static htab_t
11792 allocate_dwo_file_hash_table (void)
11793 {
11794   struct objfile *objfile = dwarf2_per_objfile->objfile;
11795
11796   return htab_create_alloc_ex (41,
11797                                hash_dwo_file,
11798                                eq_dwo_file,
11799                                NULL,
11800                                &objfile->objfile_obstack,
11801                                hashtab_obstack_allocate,
11802                                dummy_obstack_deallocate);
11803 }
11804
11805 /* Lookup DWO file DWO_NAME.  */
11806
11807 static void **
11808 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
11809 {
11810   struct dwo_file find_entry;
11811   void **slot;
11812
11813   if (dwarf2_per_objfile->dwo_files == NULL)
11814     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
11815
11816   memset (&find_entry, 0, sizeof (find_entry));
11817   find_entry.dwo_name = dwo_name;
11818   find_entry.comp_dir = comp_dir;
11819   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11820
11821   return slot;
11822 }
11823
11824 static hashval_t
11825 hash_dwo_unit (const void *item)
11826 {
11827   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11828
11829   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11830   return dwo_unit->signature;
11831 }
11832
11833 static int
11834 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11835 {
11836   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11837   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11838
11839   /* The signature is assumed to be unique within the DWO file.
11840      So while object file CU dwo_id's always have the value zero,
11841      that's OK, assuming each object file DWO file has only one CU,
11842      and that's the rule for now.  */
11843   return lhs->signature == rhs->signature;
11844 }
11845
11846 /* Allocate a hash table for DWO CUs,TUs.
11847    There is one of these tables for each of CUs,TUs for each DWO file.  */
11848
11849 static htab_t
11850 allocate_dwo_unit_table (struct objfile *objfile)
11851 {
11852   /* Start out with a pretty small number.
11853      Generally DWO files contain only one CU and maybe some TUs.  */
11854   return htab_create_alloc_ex (3,
11855                                hash_dwo_unit,
11856                                eq_dwo_unit,
11857                                NULL,
11858                                &objfile->objfile_obstack,
11859                                hashtab_obstack_allocate,
11860                                dummy_obstack_deallocate);
11861 }
11862
11863 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11864
11865 struct create_dwo_cu_data
11866 {
11867   struct dwo_file *dwo_file;
11868   struct dwo_unit dwo_unit;
11869 };
11870
11871 /* die_reader_func for create_dwo_cu.  */
11872
11873 static void
11874 create_dwo_cu_reader (const struct die_reader_specs *reader,
11875                       const gdb_byte *info_ptr,
11876                       struct die_info *comp_unit_die,
11877                       int has_children,
11878                       void *datap)
11879 {
11880   struct dwarf2_cu *cu = reader->cu;
11881   sect_offset sect_off = cu->per_cu->sect_off;
11882   struct dwarf2_section_info *section = cu->per_cu->section;
11883   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11884   struct dwo_file *dwo_file = data->dwo_file;
11885   struct dwo_unit *dwo_unit = &data->dwo_unit;
11886   struct attribute *attr;
11887
11888   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11889   if (attr == NULL)
11890     {
11891       complaint (&symfile_complaints,
11892                  _("Dwarf Error: debug entry at offset 0x%x is missing"
11893                    " its dwo_id [in module %s]"),
11894                  to_underlying (sect_off), dwo_file->dwo_name);
11895       return;
11896     }
11897
11898   dwo_unit->dwo_file = dwo_file;
11899   dwo_unit->signature = DW_UNSND (attr);
11900   dwo_unit->section = section;
11901   dwo_unit->sect_off = sect_off;
11902   dwo_unit->length = cu->per_cu->length;
11903
11904   if (dwarf_read_debug)
11905     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
11906                         to_underlying (sect_off),
11907                         hex_string (dwo_unit->signature));
11908 }
11909
11910 /* Create the dwo_units for the CUs in a DWO_FILE.
11911    Note: This function processes DWO files only, not DWP files.  */
11912
11913 static void
11914 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
11915                        htab_t &cus_htab)
11916 {
11917   struct objfile *objfile = dwarf2_per_objfile->objfile;
11918   const gdb_byte *info_ptr, *end_ptr;
11919
11920   dwarf2_read_section (objfile, &section);
11921   info_ptr = section.buffer;
11922
11923   if (info_ptr == NULL)
11924     return;
11925
11926   if (dwarf_read_debug)
11927     {
11928       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11929                           get_section_name (&section),
11930                           get_section_file_name (&section));
11931     }
11932
11933   end_ptr = info_ptr + section.size;
11934   while (info_ptr < end_ptr)
11935     {
11936       struct dwarf2_per_cu_data per_cu;
11937       struct create_dwo_cu_data create_dwo_cu_data;
11938       struct dwo_unit *dwo_unit;
11939       void **slot;
11940       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11941
11942       memset (&create_dwo_cu_data.dwo_unit, 0,
11943               sizeof (create_dwo_cu_data.dwo_unit));
11944       memset (&per_cu, 0, sizeof (per_cu));
11945       per_cu.objfile = objfile;
11946       per_cu.is_debug_types = 0;
11947       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11948       per_cu.section = &section;
11949       create_dwo_cu_data.dwo_file = &dwo_file;
11950
11951       init_cutu_and_read_dies_no_follow (
11952           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11953       info_ptr += per_cu.length;
11954
11955       // If the unit could not be parsed, skip it.
11956       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11957         continue;
11958
11959       if (cus_htab == NULL)
11960         cus_htab = allocate_dwo_unit_table (objfile);
11961
11962       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11963       *dwo_unit = create_dwo_cu_data.dwo_unit;
11964       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11965       gdb_assert (slot != NULL);
11966       if (*slot != NULL)
11967         {
11968           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11969           sect_offset dup_sect_off = dup_cu->sect_off;
11970
11971           complaint (&symfile_complaints,
11972                      _("debug cu entry at offset 0x%x is duplicate to"
11973                        " the entry at offset 0x%x, signature %s"),
11974                      to_underlying (sect_off), to_underlying (dup_sect_off),
11975                      hex_string (dwo_unit->signature));
11976         }
11977       *slot = (void *)dwo_unit;
11978     }
11979 }
11980
11981 /* DWP file .debug_{cu,tu}_index section format:
11982    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11983
11984    DWP Version 1:
11985
11986    Both index sections have the same format, and serve to map a 64-bit
11987    signature to a set of section numbers.  Each section begins with a header,
11988    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11989    indexes, and a pool of 32-bit section numbers.  The index sections will be
11990    aligned at 8-byte boundaries in the file.
11991
11992    The index section header consists of:
11993
11994     V, 32 bit version number
11995     -, 32 bits unused
11996     N, 32 bit number of compilation units or type units in the index
11997     M, 32 bit number of slots in the hash table
11998
11999    Numbers are recorded using the byte order of the application binary.
12000
12001    The hash table begins at offset 16 in the section, and consists of an array
12002    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12003    order of the application binary).  Unused slots in the hash table are 0.
12004    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12005
12006    The parallel table begins immediately after the hash table
12007    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12008    array of 32-bit indexes (using the byte order of the application binary),
12009    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12010    table contains a 32-bit index into the pool of section numbers.  For unused
12011    hash table slots, the corresponding entry in the parallel table will be 0.
12012
12013    The pool of section numbers begins immediately following the hash table
12014    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12015    section numbers consists of an array of 32-bit words (using the byte order
12016    of the application binary).  Each item in the array is indexed starting
12017    from 0.  The hash table entry provides the index of the first section
12018    number in the set.  Additional section numbers in the set follow, and the
12019    set is terminated by a 0 entry (section number 0 is not used in ELF).
12020
12021    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12022    section must be the first entry in the set, and the .debug_abbrev.dwo must
12023    be the second entry. Other members of the set may follow in any order.
12024
12025    ---
12026
12027    DWP Version 2:
12028
12029    DWP Version 2 combines all the .debug_info, etc. sections into one,
12030    and the entries in the index tables are now offsets into these sections.
12031    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12032    section.
12033
12034    Index Section Contents:
12035     Header
12036     Hash Table of Signatures   dwp_hash_table.hash_table
12037     Parallel Table of Indices  dwp_hash_table.unit_table
12038     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12039     Table of Section Sizes     dwp_hash_table.v2.sizes
12040
12041    The index section header consists of:
12042
12043     V, 32 bit version number
12044     L, 32 bit number of columns in the table of section offsets
12045     N, 32 bit number of compilation units or type units in the index
12046     M, 32 bit number of slots in the hash table
12047
12048    Numbers are recorded using the byte order of the application binary.
12049
12050    The hash table has the same format as version 1.
12051    The parallel table of indices has the same format as version 1,
12052    except that the entries are origin-1 indices into the table of sections
12053    offsets and the table of section sizes.
12054
12055    The table of offsets begins immediately following the parallel table
12056    (at offset 16 + 12 * M from the beginning of the section).  The table is
12057    a two-dimensional array of 32-bit words (using the byte order of the
12058    application binary), with L columns and N+1 rows, in row-major order.
12059    Each row in the array is indexed starting from 0.  The first row provides
12060    a key to the remaining rows: each column in this row provides an identifier
12061    for a debug section, and the offsets in the same column of subsequent rows
12062    refer to that section.  The section identifiers are:
12063
12064     DW_SECT_INFO         1  .debug_info.dwo
12065     DW_SECT_TYPES        2  .debug_types.dwo
12066     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12067     DW_SECT_LINE         4  .debug_line.dwo
12068     DW_SECT_LOC          5  .debug_loc.dwo
12069     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12070     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12071     DW_SECT_MACRO        8  .debug_macro.dwo
12072
12073    The offsets provided by the CU and TU index sections are the base offsets
12074    for the contributions made by each CU or TU to the corresponding section
12075    in the package file.  Each CU and TU header contains an abbrev_offset
12076    field, used to find the abbreviations table for that CU or TU within the
12077    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12078    be interpreted as relative to the base offset given in the index section.
12079    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12080    should be interpreted as relative to the base offset for .debug_line.dwo,
12081    and offsets into other debug sections obtained from DWARF attributes should
12082    also be interpreted as relative to the corresponding base offset.
12083
12084    The table of sizes begins immediately following the table of offsets.
12085    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12086    with L columns and N rows, in row-major order.  Each row in the array is
12087    indexed starting from 1 (row 0 is shared by the two tables).
12088
12089    ---
12090
12091    Hash table lookup is handled the same in version 1 and 2:
12092
12093    We assume that N and M will not exceed 2^32 - 1.
12094    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12095
12096    Given a 64-bit compilation unit signature or a type signature S, an entry
12097    in the hash table is located as follows:
12098
12099    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12100       the low-order k bits all set to 1.
12101
12102    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12103
12104    3) If the hash table entry at index H matches the signature, use that
12105       entry.  If the hash table entry at index H is unused (all zeroes),
12106       terminate the search: the signature is not present in the table.
12107
12108    4) Let H = (H + H') modulo M. Repeat at Step 3.
12109
12110    Because M > N and H' and M are relatively prime, the search is guaranteed
12111    to stop at an unused slot or find the match.  */
12112
12113 /* Create a hash table to map DWO IDs to their CU/TU entry in
12114    .debug_{info,types}.dwo in DWP_FILE.
12115    Returns NULL if there isn't one.
12116    Note: This function processes DWP files only, not DWO files.  */
12117
12118 static struct dwp_hash_table *
12119 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
12120 {
12121   struct objfile *objfile = dwarf2_per_objfile->objfile;
12122   bfd *dbfd = dwp_file->dbfd;
12123   const gdb_byte *index_ptr, *index_end;
12124   struct dwarf2_section_info *index;
12125   uint32_t version, nr_columns, nr_units, nr_slots;
12126   struct dwp_hash_table *htab;
12127
12128   if (is_debug_types)
12129     index = &dwp_file->sections.tu_index;
12130   else
12131     index = &dwp_file->sections.cu_index;
12132
12133   if (dwarf2_section_empty_p (index))
12134     return NULL;
12135   dwarf2_read_section (objfile, index);
12136
12137   index_ptr = index->buffer;
12138   index_end = index_ptr + index->size;
12139
12140   version = read_4_bytes (dbfd, index_ptr);
12141   index_ptr += 4;
12142   if (version == 2)
12143     nr_columns = read_4_bytes (dbfd, index_ptr);
12144   else
12145     nr_columns = 0;
12146   index_ptr += 4;
12147   nr_units = read_4_bytes (dbfd, index_ptr);
12148   index_ptr += 4;
12149   nr_slots = read_4_bytes (dbfd, index_ptr);
12150   index_ptr += 4;
12151
12152   if (version != 1 && version != 2)
12153     {
12154       error (_("Dwarf Error: unsupported DWP file version (%s)"
12155                " [in module %s]"),
12156              pulongest (version), dwp_file->name);
12157     }
12158   if (nr_slots != (nr_slots & -nr_slots))
12159     {
12160       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12161                " is not power of 2 [in module %s]"),
12162              pulongest (nr_slots), dwp_file->name);
12163     }
12164
12165   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12166   htab->version = version;
12167   htab->nr_columns = nr_columns;
12168   htab->nr_units = nr_units;
12169   htab->nr_slots = nr_slots;
12170   htab->hash_table = index_ptr;
12171   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12172
12173   /* Exit early if the table is empty.  */
12174   if (nr_slots == 0 || nr_units == 0
12175       || (version == 2 && nr_columns == 0))
12176     {
12177       /* All must be zero.  */
12178       if (nr_slots != 0 || nr_units != 0
12179           || (version == 2 && nr_columns != 0))
12180         {
12181           complaint (&symfile_complaints,
12182                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12183                        " all zero [in modules %s]"),
12184                      dwp_file->name);
12185         }
12186       return htab;
12187     }
12188
12189   if (version == 1)
12190     {
12191       htab->section_pool.v1.indices =
12192         htab->unit_table + sizeof (uint32_t) * nr_slots;
12193       /* It's harder to decide whether the section is too small in v1.
12194          V1 is deprecated anyway so we punt.  */
12195     }
12196   else
12197     {
12198       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12199       int *ids = htab->section_pool.v2.section_ids;
12200       /* Reverse map for error checking.  */
12201       int ids_seen[DW_SECT_MAX + 1];
12202       int i;
12203
12204       if (nr_columns < 2)
12205         {
12206           error (_("Dwarf Error: bad DWP hash table, too few columns"
12207                    " in section table [in module %s]"),
12208                  dwp_file->name);
12209         }
12210       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12211         {
12212           error (_("Dwarf Error: bad DWP hash table, too many columns"
12213                    " in section table [in module %s]"),
12214                  dwp_file->name);
12215         }
12216       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12217       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12218       for (i = 0; i < nr_columns; ++i)
12219         {
12220           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12221
12222           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12223             {
12224               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12225                        " in section table [in module %s]"),
12226                      id, dwp_file->name);
12227             }
12228           if (ids_seen[id] != -1)
12229             {
12230               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12231                        " id %d in section table [in module %s]"),
12232                      id, dwp_file->name);
12233             }
12234           ids_seen[id] = i;
12235           ids[i] = id;
12236         }
12237       /* Must have exactly one info or types section.  */
12238       if (((ids_seen[DW_SECT_INFO] != -1)
12239            + (ids_seen[DW_SECT_TYPES] != -1))
12240           != 1)
12241         {
12242           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12243                    " DWO info/types section [in module %s]"),
12244                  dwp_file->name);
12245         }
12246       /* Must have an abbrev section.  */
12247       if (ids_seen[DW_SECT_ABBREV] == -1)
12248         {
12249           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12250                    " section [in module %s]"),
12251                  dwp_file->name);
12252         }
12253       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12254       htab->section_pool.v2.sizes =
12255         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12256                                          * nr_units * nr_columns);
12257       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12258                                           * nr_units * nr_columns))
12259           > index_end)
12260         {
12261           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12262                    " [in module %s]"),
12263                  dwp_file->name);
12264         }
12265     }
12266
12267   return htab;
12268 }
12269
12270 /* Update SECTIONS with the data from SECTP.
12271
12272    This function is like the other "locate" section routines that are
12273    passed to bfd_map_over_sections, but in this context the sections to
12274    read comes from the DWP V1 hash table, not the full ELF section table.
12275
12276    The result is non-zero for success, or zero if an error was found.  */
12277
12278 static int
12279 locate_v1_virtual_dwo_sections (asection *sectp,
12280                                 struct virtual_v1_dwo_sections *sections)
12281 {
12282   const struct dwop_section_names *names = &dwop_section_names;
12283
12284   if (section_is_p (sectp->name, &names->abbrev_dwo))
12285     {
12286       /* There can be only one.  */
12287       if (sections->abbrev.s.section != NULL)
12288         return 0;
12289       sections->abbrev.s.section = sectp;
12290       sections->abbrev.size = bfd_get_section_size (sectp);
12291     }
12292   else if (section_is_p (sectp->name, &names->info_dwo)
12293            || section_is_p (sectp->name, &names->types_dwo))
12294     {
12295       /* There can be only one.  */
12296       if (sections->info_or_types.s.section != NULL)
12297         return 0;
12298       sections->info_or_types.s.section = sectp;
12299       sections->info_or_types.size = bfd_get_section_size (sectp);
12300     }
12301   else if (section_is_p (sectp->name, &names->line_dwo))
12302     {
12303       /* There can be only one.  */
12304       if (sections->line.s.section != NULL)
12305         return 0;
12306       sections->line.s.section = sectp;
12307       sections->line.size = bfd_get_section_size (sectp);
12308     }
12309   else if (section_is_p (sectp->name, &names->loc_dwo))
12310     {
12311       /* There can be only one.  */
12312       if (sections->loc.s.section != NULL)
12313         return 0;
12314       sections->loc.s.section = sectp;
12315       sections->loc.size = bfd_get_section_size (sectp);
12316     }
12317   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12318     {
12319       /* There can be only one.  */
12320       if (sections->macinfo.s.section != NULL)
12321         return 0;
12322       sections->macinfo.s.section = sectp;
12323       sections->macinfo.size = bfd_get_section_size (sectp);
12324     }
12325   else if (section_is_p (sectp->name, &names->macro_dwo))
12326     {
12327       /* There can be only one.  */
12328       if (sections->macro.s.section != NULL)
12329         return 0;
12330       sections->macro.s.section = sectp;
12331       sections->macro.size = bfd_get_section_size (sectp);
12332     }
12333   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12334     {
12335       /* There can be only one.  */
12336       if (sections->str_offsets.s.section != NULL)
12337         return 0;
12338       sections->str_offsets.s.section = sectp;
12339       sections->str_offsets.size = bfd_get_section_size (sectp);
12340     }
12341   else
12342     {
12343       /* No other kind of section is valid.  */
12344       return 0;
12345     }
12346
12347   return 1;
12348 }
12349
12350 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12351    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12352    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12353    This is for DWP version 1 files.  */
12354
12355 static struct dwo_unit *
12356 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
12357                            uint32_t unit_index,
12358                            const char *comp_dir,
12359                            ULONGEST signature, int is_debug_types)
12360 {
12361   struct objfile *objfile = dwarf2_per_objfile->objfile;
12362   const struct dwp_hash_table *dwp_htab =
12363     is_debug_types ? dwp_file->tus : dwp_file->cus;
12364   bfd *dbfd = dwp_file->dbfd;
12365   const char *kind = is_debug_types ? "TU" : "CU";
12366   struct dwo_file *dwo_file;
12367   struct dwo_unit *dwo_unit;
12368   struct virtual_v1_dwo_sections sections;
12369   void **dwo_file_slot;
12370   int i;
12371
12372   gdb_assert (dwp_file->version == 1);
12373
12374   if (dwarf_read_debug)
12375     {
12376       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12377                           kind,
12378                           pulongest (unit_index), hex_string (signature),
12379                           dwp_file->name);
12380     }
12381
12382   /* Fetch the sections of this DWO unit.
12383      Put a limit on the number of sections we look for so that bad data
12384      doesn't cause us to loop forever.  */
12385
12386 #define MAX_NR_V1_DWO_SECTIONS \
12387   (1 /* .debug_info or .debug_types */ \
12388    + 1 /* .debug_abbrev */ \
12389    + 1 /* .debug_line */ \
12390    + 1 /* .debug_loc */ \
12391    + 1 /* .debug_str_offsets */ \
12392    + 1 /* .debug_macro or .debug_macinfo */ \
12393    + 1 /* trailing zero */)
12394
12395   memset (&sections, 0, sizeof (sections));
12396
12397   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12398     {
12399       asection *sectp;
12400       uint32_t section_nr =
12401         read_4_bytes (dbfd,
12402                       dwp_htab->section_pool.v1.indices
12403                       + (unit_index + i) * sizeof (uint32_t));
12404
12405       if (section_nr == 0)
12406         break;
12407       if (section_nr >= dwp_file->num_sections)
12408         {
12409           error (_("Dwarf Error: bad DWP hash table, section number too large"
12410                    " [in module %s]"),
12411                  dwp_file->name);
12412         }
12413
12414       sectp = dwp_file->elf_sections[section_nr];
12415       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12416         {
12417           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12418                    " [in module %s]"),
12419                  dwp_file->name);
12420         }
12421     }
12422
12423   if (i < 2
12424       || dwarf2_section_empty_p (&sections.info_or_types)
12425       || dwarf2_section_empty_p (&sections.abbrev))
12426     {
12427       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12428                " [in module %s]"),
12429              dwp_file->name);
12430     }
12431   if (i == MAX_NR_V1_DWO_SECTIONS)
12432     {
12433       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12434                " [in module %s]"),
12435              dwp_file->name);
12436     }
12437
12438   /* It's easier for the rest of the code if we fake a struct dwo_file and
12439      have dwo_unit "live" in that.  At least for now.
12440
12441      The DWP file can be made up of a random collection of CUs and TUs.
12442      However, for each CU + set of TUs that came from the same original DWO
12443      file, we can combine them back into a virtual DWO file to save space
12444      (fewer struct dwo_file objects to allocate).  Remember that for really
12445      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12446
12447   std::string virtual_dwo_name =
12448     string_printf ("virtual-dwo/%d-%d-%d-%d",
12449                    get_section_id (&sections.abbrev),
12450                    get_section_id (&sections.line),
12451                    get_section_id (&sections.loc),
12452                    get_section_id (&sections.str_offsets));
12453   /* Can we use an existing virtual DWO file?  */
12454   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
12455   /* Create one if necessary.  */
12456   if (*dwo_file_slot == NULL)
12457     {
12458       if (dwarf_read_debug)
12459         {
12460           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12461                               virtual_dwo_name.c_str ());
12462         }
12463       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12464       dwo_file->dwo_name
12465         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12466                                         virtual_dwo_name.c_str (),
12467                                         virtual_dwo_name.size ());
12468       dwo_file->comp_dir = comp_dir;
12469       dwo_file->sections.abbrev = sections.abbrev;
12470       dwo_file->sections.line = sections.line;
12471       dwo_file->sections.loc = sections.loc;
12472       dwo_file->sections.macinfo = sections.macinfo;
12473       dwo_file->sections.macro = sections.macro;
12474       dwo_file->sections.str_offsets = sections.str_offsets;
12475       /* The "str" section is global to the entire DWP file.  */
12476       dwo_file->sections.str = dwp_file->sections.str;
12477       /* The info or types section is assigned below to dwo_unit,
12478          there's no need to record it in dwo_file.
12479          Also, we can't simply record type sections in dwo_file because
12480          we record a pointer into the vector in dwo_unit.  As we collect more
12481          types we'll grow the vector and eventually have to reallocate space
12482          for it, invalidating all copies of pointers into the previous
12483          contents.  */
12484       *dwo_file_slot = dwo_file;
12485     }
12486   else
12487     {
12488       if (dwarf_read_debug)
12489         {
12490           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12491                               virtual_dwo_name.c_str ());
12492         }
12493       dwo_file = (struct dwo_file *) *dwo_file_slot;
12494     }
12495
12496   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12497   dwo_unit->dwo_file = dwo_file;
12498   dwo_unit->signature = signature;
12499   dwo_unit->section =
12500     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12501   *dwo_unit->section = sections.info_or_types;
12502   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12503
12504   return dwo_unit;
12505 }
12506
12507 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12508    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12509    piece within that section used by a TU/CU, return a virtual section
12510    of just that piece.  */
12511
12512 static struct dwarf2_section_info
12513 create_dwp_v2_section (struct dwarf2_section_info *section,
12514                        bfd_size_type offset, bfd_size_type size)
12515 {
12516   struct dwarf2_section_info result;
12517   asection *sectp;
12518
12519   gdb_assert (section != NULL);
12520   gdb_assert (!section->is_virtual);
12521
12522   memset (&result, 0, sizeof (result));
12523   result.s.containing_section = section;
12524   result.is_virtual = 1;
12525
12526   if (size == 0)
12527     return result;
12528
12529   sectp = get_section_bfd_section (section);
12530
12531   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12532      bounds of the real section.  This is a pretty-rare event, so just
12533      flag an error (easier) instead of a warning and trying to cope.  */
12534   if (sectp == NULL
12535       || offset + size > bfd_get_section_size (sectp))
12536     {
12537       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12538                " in section %s [in module %s]"),
12539              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12540              objfile_name (dwarf2_per_objfile->objfile));
12541     }
12542
12543   result.virtual_offset = offset;
12544   result.size = size;
12545   return result;
12546 }
12547
12548 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12549    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12550    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12551    This is for DWP version 2 files.  */
12552
12553 static struct dwo_unit *
12554 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
12555                            uint32_t unit_index,
12556                            const char *comp_dir,
12557                            ULONGEST signature, int is_debug_types)
12558 {
12559   struct objfile *objfile = dwarf2_per_objfile->objfile;
12560   const struct dwp_hash_table *dwp_htab =
12561     is_debug_types ? dwp_file->tus : dwp_file->cus;
12562   bfd *dbfd = dwp_file->dbfd;
12563   const char *kind = is_debug_types ? "TU" : "CU";
12564   struct dwo_file *dwo_file;
12565   struct dwo_unit *dwo_unit;
12566   struct virtual_v2_dwo_sections sections;
12567   void **dwo_file_slot;
12568   int i;
12569
12570   gdb_assert (dwp_file->version == 2);
12571
12572   if (dwarf_read_debug)
12573     {
12574       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12575                           kind,
12576                           pulongest (unit_index), hex_string (signature),
12577                           dwp_file->name);
12578     }
12579
12580   /* Fetch the section offsets of this DWO unit.  */
12581
12582   memset (&sections, 0, sizeof (sections));
12583
12584   for (i = 0; i < dwp_htab->nr_columns; ++i)
12585     {
12586       uint32_t offset = read_4_bytes (dbfd,
12587                                       dwp_htab->section_pool.v2.offsets
12588                                       + (((unit_index - 1) * dwp_htab->nr_columns
12589                                           + i)
12590                                          * sizeof (uint32_t)));
12591       uint32_t size = read_4_bytes (dbfd,
12592                                     dwp_htab->section_pool.v2.sizes
12593                                     + (((unit_index - 1) * dwp_htab->nr_columns
12594                                         + i)
12595                                        * sizeof (uint32_t)));
12596
12597       switch (dwp_htab->section_pool.v2.section_ids[i])
12598         {
12599         case DW_SECT_INFO:
12600         case DW_SECT_TYPES:
12601           sections.info_or_types_offset = offset;
12602           sections.info_or_types_size = size;
12603           break;
12604         case DW_SECT_ABBREV:
12605           sections.abbrev_offset = offset;
12606           sections.abbrev_size = size;
12607           break;
12608         case DW_SECT_LINE:
12609           sections.line_offset = offset;
12610           sections.line_size = size;
12611           break;
12612         case DW_SECT_LOC:
12613           sections.loc_offset = offset;
12614           sections.loc_size = size;
12615           break;
12616         case DW_SECT_STR_OFFSETS:
12617           sections.str_offsets_offset = offset;
12618           sections.str_offsets_size = size;
12619           break;
12620         case DW_SECT_MACINFO:
12621           sections.macinfo_offset = offset;
12622           sections.macinfo_size = size;
12623           break;
12624         case DW_SECT_MACRO:
12625           sections.macro_offset = offset;
12626           sections.macro_size = size;
12627           break;
12628         }
12629     }
12630
12631   /* It's easier for the rest of the code if we fake a struct dwo_file and
12632      have dwo_unit "live" in that.  At least for now.
12633
12634      The DWP file can be made up of a random collection of CUs and TUs.
12635      However, for each CU + set of TUs that came from the same original DWO
12636      file, we can combine them back into a virtual DWO file to save space
12637      (fewer struct dwo_file objects to allocate).  Remember that for really
12638      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12639
12640   std::string virtual_dwo_name =
12641     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12642                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12643                    (long) (sections.line_size ? sections.line_offset : 0),
12644                    (long) (sections.loc_size ? sections.loc_offset : 0),
12645                    (long) (sections.str_offsets_size
12646                            ? sections.str_offsets_offset : 0));
12647   /* Can we use an existing virtual DWO file?  */
12648   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
12649   /* Create one if necessary.  */
12650   if (*dwo_file_slot == NULL)
12651     {
12652       if (dwarf_read_debug)
12653         {
12654           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12655                               virtual_dwo_name.c_str ());
12656         }
12657       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12658       dwo_file->dwo_name
12659         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12660                                         virtual_dwo_name.c_str (),
12661                                         virtual_dwo_name.size ());
12662       dwo_file->comp_dir = comp_dir;
12663       dwo_file->sections.abbrev =
12664         create_dwp_v2_section (&dwp_file->sections.abbrev,
12665                                sections.abbrev_offset, sections.abbrev_size);
12666       dwo_file->sections.line =
12667         create_dwp_v2_section (&dwp_file->sections.line,
12668                                sections.line_offset, sections.line_size);
12669       dwo_file->sections.loc =
12670         create_dwp_v2_section (&dwp_file->sections.loc,
12671                                sections.loc_offset, sections.loc_size);
12672       dwo_file->sections.macinfo =
12673         create_dwp_v2_section (&dwp_file->sections.macinfo,
12674                                sections.macinfo_offset, sections.macinfo_size);
12675       dwo_file->sections.macro =
12676         create_dwp_v2_section (&dwp_file->sections.macro,
12677                                sections.macro_offset, sections.macro_size);
12678       dwo_file->sections.str_offsets =
12679         create_dwp_v2_section (&dwp_file->sections.str_offsets,
12680                                sections.str_offsets_offset,
12681                                sections.str_offsets_size);
12682       /* The "str" section is global to the entire DWP file.  */
12683       dwo_file->sections.str = dwp_file->sections.str;
12684       /* The info or types section is assigned below to dwo_unit,
12685          there's no need to record it in dwo_file.
12686          Also, we can't simply record type sections in dwo_file because
12687          we record a pointer into the vector in dwo_unit.  As we collect more
12688          types we'll grow the vector and eventually have to reallocate space
12689          for it, invalidating all copies of pointers into the previous
12690          contents.  */
12691       *dwo_file_slot = dwo_file;
12692     }
12693   else
12694     {
12695       if (dwarf_read_debug)
12696         {
12697           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12698                               virtual_dwo_name.c_str ());
12699         }
12700       dwo_file = (struct dwo_file *) *dwo_file_slot;
12701     }
12702
12703   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12704   dwo_unit->dwo_file = dwo_file;
12705   dwo_unit->signature = signature;
12706   dwo_unit->section =
12707     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12708   *dwo_unit->section = create_dwp_v2_section (is_debug_types
12709                                               ? &dwp_file->sections.types
12710                                               : &dwp_file->sections.info,
12711                                               sections.info_or_types_offset,
12712                                               sections.info_or_types_size);
12713   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12714
12715   return dwo_unit;
12716 }
12717
12718 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12719    Returns NULL if the signature isn't found.  */
12720
12721 static struct dwo_unit *
12722 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
12723                         ULONGEST signature, int is_debug_types)
12724 {
12725   const struct dwp_hash_table *dwp_htab =
12726     is_debug_types ? dwp_file->tus : dwp_file->cus;
12727   bfd *dbfd = dwp_file->dbfd;
12728   uint32_t mask = dwp_htab->nr_slots - 1;
12729   uint32_t hash = signature & mask;
12730   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12731   unsigned int i;
12732   void **slot;
12733   struct dwo_unit find_dwo_cu;
12734
12735   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12736   find_dwo_cu.signature = signature;
12737   slot = htab_find_slot (is_debug_types
12738                          ? dwp_file->loaded_tus
12739                          : dwp_file->loaded_cus,
12740                          &find_dwo_cu, INSERT);
12741
12742   if (*slot != NULL)
12743     return (struct dwo_unit *) *slot;
12744
12745   /* Use a for loop so that we don't loop forever on bad debug info.  */
12746   for (i = 0; i < dwp_htab->nr_slots; ++i)
12747     {
12748       ULONGEST signature_in_table;
12749
12750       signature_in_table =
12751         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12752       if (signature_in_table == signature)
12753         {
12754           uint32_t unit_index =
12755             read_4_bytes (dbfd,
12756                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12757
12758           if (dwp_file->version == 1)
12759             {
12760               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
12761                                                  comp_dir, signature,
12762                                                  is_debug_types);
12763             }
12764           else
12765             {
12766               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
12767                                                  comp_dir, signature,
12768                                                  is_debug_types);
12769             }
12770           return (struct dwo_unit *) *slot;
12771         }
12772       if (signature_in_table == 0)
12773         return NULL;
12774       hash = (hash + hash2) & mask;
12775     }
12776
12777   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12778            " [in module %s]"),
12779          dwp_file->name);
12780 }
12781
12782 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12783    Open the file specified by FILE_NAME and hand it off to BFD for
12784    preliminary analysis.  Return a newly initialized bfd *, which
12785    includes a canonicalized copy of FILE_NAME.
12786    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12787    SEARCH_CWD is true if the current directory is to be searched.
12788    It will be searched before debug-file-directory.
12789    If successful, the file is added to the bfd include table of the
12790    objfile's bfd (see gdb_bfd_record_inclusion).
12791    If unable to find/open the file, return NULL.
12792    NOTE: This function is derived from symfile_bfd_open.  */
12793
12794 static gdb_bfd_ref_ptr
12795 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
12796 {
12797   int desc, flags;
12798   char *absolute_name;
12799   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12800      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12801      to debug_file_directory.  */
12802   char *search_path;
12803   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12804
12805   if (search_cwd)
12806     {
12807       if (*debug_file_directory != '\0')
12808         search_path = concat (".", dirname_separator_string,
12809                               debug_file_directory, (char *) NULL);
12810       else
12811         search_path = xstrdup (".");
12812     }
12813   else
12814     search_path = xstrdup (debug_file_directory);
12815
12816   flags = OPF_RETURN_REALPATH;
12817   if (is_dwp)
12818     flags |= OPF_SEARCH_IN_PATH;
12819   desc = openp (search_path, flags, file_name,
12820                 O_RDONLY | O_BINARY, &absolute_name);
12821   xfree (search_path);
12822   if (desc < 0)
12823     return NULL;
12824
12825   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12826   xfree (absolute_name);
12827   if (sym_bfd == NULL)
12828     return NULL;
12829   bfd_set_cacheable (sym_bfd.get (), 1);
12830
12831   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12832     return NULL;
12833
12834   /* Success.  Record the bfd as having been included by the objfile's bfd.
12835      This is important because things like demangled_names_hash lives in the
12836      objfile's per_bfd space and may have references to things like symbol
12837      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12838   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12839
12840   return sym_bfd;
12841 }
12842
12843 /* Try to open DWO file FILE_NAME.
12844    COMP_DIR is the DW_AT_comp_dir attribute.
12845    The result is the bfd handle of the file.
12846    If there is a problem finding or opening the file, return NULL.
12847    Upon success, the canonicalized path of the file is stored in the bfd,
12848    same as symfile_bfd_open.  */
12849
12850 static gdb_bfd_ref_ptr
12851 open_dwo_file (const char *file_name, const char *comp_dir)
12852 {
12853   if (IS_ABSOLUTE_PATH (file_name))
12854     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
12855
12856   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12857
12858   if (comp_dir != NULL)
12859     {
12860       char *path_to_try = concat (comp_dir, SLASH_STRING,
12861                                   file_name, (char *) NULL);
12862
12863       /* NOTE: If comp_dir is a relative path, this will also try the
12864          search path, which seems useful.  */
12865       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
12866                                                 1 /*search_cwd*/));
12867       xfree (path_to_try);
12868       if (abfd != NULL)
12869         return abfd;
12870     }
12871
12872   /* That didn't work, try debug-file-directory, which, despite its name,
12873      is a list of paths.  */
12874
12875   if (*debug_file_directory == '\0')
12876     return NULL;
12877
12878   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
12879 }
12880
12881 /* This function is mapped across the sections and remembers the offset and
12882    size of each of the DWO debugging sections we are interested in.  */
12883
12884 static void
12885 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12886 {
12887   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12888   const struct dwop_section_names *names = &dwop_section_names;
12889
12890   if (section_is_p (sectp->name, &names->abbrev_dwo))
12891     {
12892       dwo_sections->abbrev.s.section = sectp;
12893       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12894     }
12895   else if (section_is_p (sectp->name, &names->info_dwo))
12896     {
12897       dwo_sections->info.s.section = sectp;
12898       dwo_sections->info.size = bfd_get_section_size (sectp);
12899     }
12900   else if (section_is_p (sectp->name, &names->line_dwo))
12901     {
12902       dwo_sections->line.s.section = sectp;
12903       dwo_sections->line.size = bfd_get_section_size (sectp);
12904     }
12905   else if (section_is_p (sectp->name, &names->loc_dwo))
12906     {
12907       dwo_sections->loc.s.section = sectp;
12908       dwo_sections->loc.size = bfd_get_section_size (sectp);
12909     }
12910   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12911     {
12912       dwo_sections->macinfo.s.section = sectp;
12913       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12914     }
12915   else if (section_is_p (sectp->name, &names->macro_dwo))
12916     {
12917       dwo_sections->macro.s.section = sectp;
12918       dwo_sections->macro.size = bfd_get_section_size (sectp);
12919     }
12920   else if (section_is_p (sectp->name, &names->str_dwo))
12921     {
12922       dwo_sections->str.s.section = sectp;
12923       dwo_sections->str.size = bfd_get_section_size (sectp);
12924     }
12925   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12926     {
12927       dwo_sections->str_offsets.s.section = sectp;
12928       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12929     }
12930   else if (section_is_p (sectp->name, &names->types_dwo))
12931     {
12932       struct dwarf2_section_info type_section;
12933
12934       memset (&type_section, 0, sizeof (type_section));
12935       type_section.s.section = sectp;
12936       type_section.size = bfd_get_section_size (sectp);
12937       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12938                      &type_section);
12939     }
12940 }
12941
12942 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12943    by PER_CU.  This is for the non-DWP case.
12944    The result is NULL if DWO_NAME can't be found.  */
12945
12946 static struct dwo_file *
12947 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12948                         const char *dwo_name, const char *comp_dir)
12949 {
12950   struct objfile *objfile = dwarf2_per_objfile->objfile;
12951   struct dwo_file *dwo_file;
12952   struct cleanup *cleanups;
12953
12954   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
12955   if (dbfd == NULL)
12956     {
12957       if (dwarf_read_debug)
12958         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12959       return NULL;
12960     }
12961   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12962   dwo_file->dwo_name = dwo_name;
12963   dwo_file->comp_dir = comp_dir;
12964   dwo_file->dbfd = dbfd.release ();
12965
12966   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
12967
12968   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12969                          &dwo_file->sections);
12970
12971   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
12972
12973   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
12974                                  dwo_file->tus);
12975
12976   discard_cleanups (cleanups);
12977
12978   if (dwarf_read_debug)
12979     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12980
12981   return dwo_file;
12982 }
12983
12984 /* This function is mapped across the sections and remembers the offset and
12985    size of each of the DWP debugging sections common to version 1 and 2 that
12986    we are interested in.  */
12987
12988 static void
12989 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12990                                    void *dwp_file_ptr)
12991 {
12992   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12993   const struct dwop_section_names *names = &dwop_section_names;
12994   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12995
12996   /* Record the ELF section number for later lookup: this is what the
12997      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12998   gdb_assert (elf_section_nr < dwp_file->num_sections);
12999   dwp_file->elf_sections[elf_section_nr] = sectp;
13000
13001   /* Look for specific sections that we need.  */
13002   if (section_is_p (sectp->name, &names->str_dwo))
13003     {
13004       dwp_file->sections.str.s.section = sectp;
13005       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13006     }
13007   else if (section_is_p (sectp->name, &names->cu_index))
13008     {
13009       dwp_file->sections.cu_index.s.section = sectp;
13010       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13011     }
13012   else if (section_is_p (sectp->name, &names->tu_index))
13013     {
13014       dwp_file->sections.tu_index.s.section = sectp;
13015       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13016     }
13017 }
13018
13019 /* This function is mapped across the sections and remembers the offset and
13020    size of each of the DWP version 2 debugging sections that we are interested
13021    in.  This is split into a separate function because we don't know if we
13022    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13023
13024 static void
13025 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13026 {
13027   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13028   const struct dwop_section_names *names = &dwop_section_names;
13029   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13030
13031   /* Record the ELF section number for later lookup: this is what the
13032      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13033   gdb_assert (elf_section_nr < dwp_file->num_sections);
13034   dwp_file->elf_sections[elf_section_nr] = sectp;
13035
13036   /* Look for specific sections that we need.  */
13037   if (section_is_p (sectp->name, &names->abbrev_dwo))
13038     {
13039       dwp_file->sections.abbrev.s.section = sectp;
13040       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13041     }
13042   else if (section_is_p (sectp->name, &names->info_dwo))
13043     {
13044       dwp_file->sections.info.s.section = sectp;
13045       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13046     }
13047   else if (section_is_p (sectp->name, &names->line_dwo))
13048     {
13049       dwp_file->sections.line.s.section = sectp;
13050       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13051     }
13052   else if (section_is_p (sectp->name, &names->loc_dwo))
13053     {
13054       dwp_file->sections.loc.s.section = sectp;
13055       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13056     }
13057   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13058     {
13059       dwp_file->sections.macinfo.s.section = sectp;
13060       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13061     }
13062   else if (section_is_p (sectp->name, &names->macro_dwo))
13063     {
13064       dwp_file->sections.macro.s.section = sectp;
13065       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13066     }
13067   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13068     {
13069       dwp_file->sections.str_offsets.s.section = sectp;
13070       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13071     }
13072   else if (section_is_p (sectp->name, &names->types_dwo))
13073     {
13074       dwp_file->sections.types.s.section = sectp;
13075       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13076     }
13077 }
13078
13079 /* Hash function for dwp_file loaded CUs/TUs.  */
13080
13081 static hashval_t
13082 hash_dwp_loaded_cutus (const void *item)
13083 {
13084   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13085
13086   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13087   return dwo_unit->signature;
13088 }
13089
13090 /* Equality function for dwp_file loaded CUs/TUs.  */
13091
13092 static int
13093 eq_dwp_loaded_cutus (const void *a, const void *b)
13094 {
13095   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13096   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13097
13098   return dua->signature == dub->signature;
13099 }
13100
13101 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13102
13103 static htab_t
13104 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13105 {
13106   return htab_create_alloc_ex (3,
13107                                hash_dwp_loaded_cutus,
13108                                eq_dwp_loaded_cutus,
13109                                NULL,
13110                                &objfile->objfile_obstack,
13111                                hashtab_obstack_allocate,
13112                                dummy_obstack_deallocate);
13113 }
13114
13115 /* Try to open DWP file FILE_NAME.
13116    The result is the bfd handle of the file.
13117    If there is a problem finding or opening the file, return NULL.
13118    Upon success, the canonicalized path of the file is stored in the bfd,
13119    same as symfile_bfd_open.  */
13120
13121 static gdb_bfd_ref_ptr
13122 open_dwp_file (const char *file_name)
13123 {
13124   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
13125                                             1 /*search_cwd*/));
13126   if (abfd != NULL)
13127     return abfd;
13128
13129   /* Work around upstream bug 15652.
13130      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13131      [Whether that's a "bug" is debatable, but it is getting in our way.]
13132      We have no real idea where the dwp file is, because gdb's realpath-ing
13133      of the executable's path may have discarded the needed info.
13134      [IWBN if the dwp file name was recorded in the executable, akin to
13135      .gnu_debuglink, but that doesn't exist yet.]
13136      Strip the directory from FILE_NAME and search again.  */
13137   if (*debug_file_directory != '\0')
13138     {
13139       /* Don't implicitly search the current directory here.
13140          If the user wants to search "." to handle this case,
13141          it must be added to debug-file-directory.  */
13142       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
13143                                  0 /*search_cwd*/);
13144     }
13145
13146   return NULL;
13147 }
13148
13149 /* Initialize the use of the DWP file for the current objfile.
13150    By convention the name of the DWP file is ${objfile}.dwp.
13151    The result is NULL if it can't be found.  */
13152
13153 static struct dwp_file *
13154 open_and_init_dwp_file (void)
13155 {
13156   struct objfile *objfile = dwarf2_per_objfile->objfile;
13157   struct dwp_file *dwp_file;
13158
13159   /* Try to find first .dwp for the binary file before any symbolic links
13160      resolving.  */
13161
13162   /* If the objfile is a debug file, find the name of the real binary
13163      file and get the name of dwp file from there.  */
13164   std::string dwp_name;
13165   if (objfile->separate_debug_objfile_backlink != NULL)
13166     {
13167       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13168       const char *backlink_basename = lbasename (backlink->original_name);
13169
13170       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13171     }
13172   else
13173     dwp_name = objfile->original_name;
13174
13175   dwp_name += ".dwp";
13176
13177   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
13178   if (dbfd == NULL
13179       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13180     {
13181       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13182       dwp_name = objfile_name (objfile);
13183       dwp_name += ".dwp";
13184       dbfd = open_dwp_file (dwp_name.c_str ());
13185     }
13186
13187   if (dbfd == NULL)
13188     {
13189       if (dwarf_read_debug)
13190         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13191       return NULL;
13192     }
13193   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13194   dwp_file->name = bfd_get_filename (dbfd.get ());
13195   dwp_file->dbfd = dbfd.release ();
13196
13197   /* +1: section 0 is unused */
13198   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13199   dwp_file->elf_sections =
13200     OBSTACK_CALLOC (&objfile->objfile_obstack,
13201                     dwp_file->num_sections, asection *);
13202
13203   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13204                          dwp_file);
13205
13206   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
13207
13208   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
13209
13210   /* The DWP file version is stored in the hash table.  Oh well.  */
13211   if (dwp_file->cus && dwp_file->tus
13212       && dwp_file->cus->version != dwp_file->tus->version)
13213     {
13214       /* Technically speaking, we should try to limp along, but this is
13215          pretty bizarre.  We use pulongest here because that's the established
13216          portability solution (e.g, we cannot use %u for uint32_t).  */
13217       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13218                " TU version %s [in DWP file %s]"),
13219              pulongest (dwp_file->cus->version),
13220              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13221     }
13222
13223   if (dwp_file->cus)
13224     dwp_file->version = dwp_file->cus->version;
13225   else if (dwp_file->tus)
13226     dwp_file->version = dwp_file->tus->version;
13227   else
13228     dwp_file->version = 2;
13229
13230   if (dwp_file->version == 2)
13231     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13232                            dwp_file);
13233
13234   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13235   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13236
13237   if (dwarf_read_debug)
13238     {
13239       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13240       fprintf_unfiltered (gdb_stdlog,
13241                           "    %s CUs, %s TUs\n",
13242                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13243                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13244     }
13245
13246   return dwp_file;
13247 }
13248
13249 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13250
13251 static struct dwp_file *
13252 get_dwp_file (void)
13253 {
13254   if (! dwarf2_per_objfile->dwp_checked)
13255     {
13256       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
13257       dwarf2_per_objfile->dwp_checked = 1;
13258     }
13259   return dwarf2_per_objfile->dwp_file;
13260 }
13261
13262 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13263    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13264    or in the DWP file for the objfile, referenced by THIS_UNIT.
13265    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13266    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13267
13268    This is called, for example, when wanting to read a variable with a
13269    complex location.  Therefore we don't want to do file i/o for every call.
13270    Therefore we don't want to look for a DWO file on every call.
13271    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13272    then we check if we've already seen DWO_NAME, and only THEN do we check
13273    for a DWO file.
13274
13275    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13276    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13277
13278 static struct dwo_unit *
13279 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13280                  const char *dwo_name, const char *comp_dir,
13281                  ULONGEST signature, int is_debug_types)
13282 {
13283   struct objfile *objfile = dwarf2_per_objfile->objfile;
13284   const char *kind = is_debug_types ? "TU" : "CU";
13285   void **dwo_file_slot;
13286   struct dwo_file *dwo_file;
13287   struct dwp_file *dwp_file;
13288
13289   /* First see if there's a DWP file.
13290      If we have a DWP file but didn't find the DWO inside it, don't
13291      look for the original DWO file.  It makes gdb behave differently
13292      depending on whether one is debugging in the build tree.  */
13293
13294   dwp_file = get_dwp_file ();
13295   if (dwp_file != NULL)
13296     {
13297       const struct dwp_hash_table *dwp_htab =
13298         is_debug_types ? dwp_file->tus : dwp_file->cus;
13299
13300       if (dwp_htab != NULL)
13301         {
13302           struct dwo_unit *dwo_cutu =
13303             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
13304                                     signature, is_debug_types);
13305
13306           if (dwo_cutu != NULL)
13307             {
13308               if (dwarf_read_debug)
13309                 {
13310                   fprintf_unfiltered (gdb_stdlog,
13311                                       "Virtual DWO %s %s found: @%s\n",
13312                                       kind, hex_string (signature),
13313                                       host_address_to_string (dwo_cutu));
13314                 }
13315               return dwo_cutu;
13316             }
13317         }
13318     }
13319   else
13320     {
13321       /* No DWP file, look for the DWO file.  */
13322
13323       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
13324       if (*dwo_file_slot == NULL)
13325         {
13326           /* Read in the file and build a table of the CUs/TUs it contains.  */
13327           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13328         }
13329       /* NOTE: This will be NULL if unable to open the file.  */
13330       dwo_file = (struct dwo_file *) *dwo_file_slot;
13331
13332       if (dwo_file != NULL)
13333         {
13334           struct dwo_unit *dwo_cutu = NULL;
13335
13336           if (is_debug_types && dwo_file->tus)
13337             {
13338               struct dwo_unit find_dwo_cutu;
13339
13340               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13341               find_dwo_cutu.signature = signature;
13342               dwo_cutu
13343                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13344             }
13345           else if (!is_debug_types && dwo_file->cus)
13346             {
13347               struct dwo_unit find_dwo_cutu;
13348
13349               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13350               find_dwo_cutu.signature = signature;
13351               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13352                                                        &find_dwo_cutu);
13353             }
13354
13355           if (dwo_cutu != NULL)
13356             {
13357               if (dwarf_read_debug)
13358                 {
13359                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13360                                       kind, dwo_name, hex_string (signature),
13361                                       host_address_to_string (dwo_cutu));
13362                 }
13363               return dwo_cutu;
13364             }
13365         }
13366     }
13367
13368   /* We didn't find it.  This could mean a dwo_id mismatch, or
13369      someone deleted the DWO/DWP file, or the search path isn't set up
13370      correctly to find the file.  */
13371
13372   if (dwarf_read_debug)
13373     {
13374       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13375                           kind, dwo_name, hex_string (signature));
13376     }
13377
13378   /* This is a warning and not a complaint because it can be caused by
13379      pilot error (e.g., user accidentally deleting the DWO).  */
13380   {
13381     /* Print the name of the DWP file if we looked there, helps the user
13382        better diagnose the problem.  */
13383     std::string dwp_text;
13384
13385     if (dwp_file != NULL)
13386       dwp_text = string_printf (" [in DWP file %s]",
13387                                 lbasename (dwp_file->name));
13388
13389     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13390                " [in module %s]"),
13391              kind, dwo_name, hex_string (signature),
13392              dwp_text.c_str (),
13393              this_unit->is_debug_types ? "TU" : "CU",
13394              to_underlying (this_unit->sect_off), objfile_name (objfile));
13395   }
13396   return NULL;
13397 }
13398
13399 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13400    See lookup_dwo_cutu_unit for details.  */
13401
13402 static struct dwo_unit *
13403 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13404                       const char *dwo_name, const char *comp_dir,
13405                       ULONGEST signature)
13406 {
13407   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13408 }
13409
13410 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13411    See lookup_dwo_cutu_unit for details.  */
13412
13413 static struct dwo_unit *
13414 lookup_dwo_type_unit (struct signatured_type *this_tu,
13415                       const char *dwo_name, const char *comp_dir)
13416 {
13417   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13418 }
13419
13420 /* Traversal function for queue_and_load_all_dwo_tus.  */
13421
13422 static int
13423 queue_and_load_dwo_tu (void **slot, void *info)
13424 {
13425   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13426   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13427   ULONGEST signature = dwo_unit->signature;
13428   struct signatured_type *sig_type =
13429     lookup_dwo_signatured_type (per_cu->cu, signature);
13430
13431   if (sig_type != NULL)
13432     {
13433       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13434
13435       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13436          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13437          while processing PER_CU.  */
13438       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13439         load_full_type_unit (sig_cu);
13440       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13441     }
13442
13443   return 1;
13444 }
13445
13446 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13447    The DWO may have the only definition of the type, though it may not be
13448    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13449    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13450
13451 static void
13452 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13453 {
13454   struct dwo_unit *dwo_unit;
13455   struct dwo_file *dwo_file;
13456
13457   gdb_assert (!per_cu->is_debug_types);
13458   gdb_assert (get_dwp_file () == NULL);
13459   gdb_assert (per_cu->cu != NULL);
13460
13461   dwo_unit = per_cu->cu->dwo_unit;
13462   gdb_assert (dwo_unit != NULL);
13463
13464   dwo_file = dwo_unit->dwo_file;
13465   if (dwo_file->tus != NULL)
13466     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13467 }
13468
13469 /* Free all resources associated with DWO_FILE.
13470    Close the DWO file and munmap the sections.
13471    All memory should be on the objfile obstack.  */
13472
13473 static void
13474 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13475 {
13476
13477   /* Note: dbfd is NULL for virtual DWO files.  */
13478   gdb_bfd_unref (dwo_file->dbfd);
13479
13480   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13481 }
13482
13483 /* Wrapper for free_dwo_file for use in cleanups.  */
13484
13485 static void
13486 free_dwo_file_cleanup (void *arg)
13487 {
13488   struct dwo_file *dwo_file = (struct dwo_file *) arg;
13489   struct objfile *objfile = dwarf2_per_objfile->objfile;
13490
13491   free_dwo_file (dwo_file, objfile);
13492 }
13493
13494 /* Traversal function for free_dwo_files.  */
13495
13496 static int
13497 free_dwo_file_from_slot (void **slot, void *info)
13498 {
13499   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13500   struct objfile *objfile = (struct objfile *) info;
13501
13502   free_dwo_file (dwo_file, objfile);
13503
13504   return 1;
13505 }
13506
13507 /* Free all resources associated with DWO_FILES.  */
13508
13509 static void
13510 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13511 {
13512   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13513 }
13514 \f
13515 /* Read in various DIEs.  */
13516
13517 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13518    Inherit only the children of the DW_AT_abstract_origin DIE not being
13519    already referenced by DW_AT_abstract_origin from the children of the
13520    current DIE.  */
13521
13522 static void
13523 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13524 {
13525   struct die_info *child_die;
13526   sect_offset *offsetp;
13527   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13528   struct die_info *origin_die;
13529   /* Iterator of the ORIGIN_DIE children.  */
13530   struct die_info *origin_child_die;
13531   struct attribute *attr;
13532   struct dwarf2_cu *origin_cu;
13533   struct pending **origin_previous_list_in_scope;
13534
13535   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13536   if (!attr)
13537     return;
13538
13539   /* Note that following die references may follow to a die in a
13540      different cu.  */
13541
13542   origin_cu = cu;
13543   origin_die = follow_die_ref (die, attr, &origin_cu);
13544
13545   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13546      symbols in.  */
13547   origin_previous_list_in_scope = origin_cu->list_in_scope;
13548   origin_cu->list_in_scope = cu->list_in_scope;
13549
13550   if (die->tag != origin_die->tag
13551       && !(die->tag == DW_TAG_inlined_subroutine
13552            && origin_die->tag == DW_TAG_subprogram))
13553     complaint (&symfile_complaints,
13554                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13555                to_underlying (die->sect_off),
13556                to_underlying (origin_die->sect_off));
13557
13558   std::vector<sect_offset> offsets;
13559
13560   for (child_die = die->child;
13561        child_die && child_die->tag;
13562        child_die = sibling_die (child_die))
13563     {
13564       struct die_info *child_origin_die;
13565       struct dwarf2_cu *child_origin_cu;
13566
13567       /* We are trying to process concrete instance entries:
13568          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13569          it's not relevant to our analysis here. i.e. detecting DIEs that are
13570          present in the abstract instance but not referenced in the concrete
13571          one.  */
13572       if (child_die->tag == DW_TAG_call_site
13573           || child_die->tag == DW_TAG_GNU_call_site)
13574         continue;
13575
13576       /* For each CHILD_DIE, find the corresponding child of
13577          ORIGIN_DIE.  If there is more than one layer of
13578          DW_AT_abstract_origin, follow them all; there shouldn't be,
13579          but GCC versions at least through 4.4 generate this (GCC PR
13580          40573).  */
13581       child_origin_die = child_die;
13582       child_origin_cu = cu;
13583       while (1)
13584         {
13585           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13586                               child_origin_cu);
13587           if (attr == NULL)
13588             break;
13589           child_origin_die = follow_die_ref (child_origin_die, attr,
13590                                              &child_origin_cu);
13591         }
13592
13593       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13594          counterpart may exist.  */
13595       if (child_origin_die != child_die)
13596         {
13597           if (child_die->tag != child_origin_die->tag
13598               && !(child_die->tag == DW_TAG_inlined_subroutine
13599                    && child_origin_die->tag == DW_TAG_subprogram))
13600             complaint (&symfile_complaints,
13601                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13602                          "different tags"),
13603                        to_underlying (child_die->sect_off),
13604                        to_underlying (child_origin_die->sect_off));
13605           if (child_origin_die->parent != origin_die)
13606             complaint (&symfile_complaints,
13607                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13608                          "different parents"),
13609                        to_underlying (child_die->sect_off),
13610                        to_underlying (child_origin_die->sect_off));
13611           else
13612             offsets.push_back (child_origin_die->sect_off);
13613         }
13614     }
13615   std::sort (offsets.begin (), offsets.end ());
13616   sect_offset *offsets_end = offsets.data () + offsets.size ();
13617   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13618     if (offsetp[-1] == *offsetp)
13619       complaint (&symfile_complaints,
13620                  _("Multiple children of DIE 0x%x refer "
13621                    "to DIE 0x%x as their abstract origin"),
13622                  to_underlying (die->sect_off), to_underlying (*offsetp));
13623
13624   offsetp = offsets.data ();
13625   origin_child_die = origin_die->child;
13626   while (origin_child_die && origin_child_die->tag)
13627     {
13628       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13629       while (offsetp < offsets_end
13630              && *offsetp < origin_child_die->sect_off)
13631         offsetp++;
13632       if (offsetp >= offsets_end
13633           || *offsetp > origin_child_die->sect_off)
13634         {
13635           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13636              Check whether we're already processing ORIGIN_CHILD_DIE.
13637              This can happen with mutually referenced abstract_origins.
13638              PR 16581.  */
13639           if (!origin_child_die->in_process)
13640             process_die (origin_child_die, origin_cu);
13641         }
13642       origin_child_die = sibling_die (origin_child_die);
13643     }
13644   origin_cu->list_in_scope = origin_previous_list_in_scope;
13645 }
13646
13647 static void
13648 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13649 {
13650   struct objfile *objfile = cu->objfile;
13651   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13652   struct context_stack *newobj;
13653   CORE_ADDR lowpc;
13654   CORE_ADDR highpc;
13655   struct die_info *child_die;
13656   struct attribute *attr, *call_line, *call_file;
13657   const char *name;
13658   CORE_ADDR baseaddr;
13659   struct block *block;
13660   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13661   std::vector<struct symbol *> template_args;
13662   struct template_symbol *templ_func = NULL;
13663
13664   if (inlined_func)
13665     {
13666       /* If we do not have call site information, we can't show the
13667          caller of this inlined function.  That's too confusing, so
13668          only use the scope for local variables.  */
13669       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13670       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13671       if (call_line == NULL || call_file == NULL)
13672         {
13673           read_lexical_block_scope (die, cu);
13674           return;
13675         }
13676     }
13677
13678   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13679
13680   name = dwarf2_name (die, cu);
13681
13682   /* Ignore functions with missing or empty names.  These are actually
13683      illegal according to the DWARF standard.  */
13684   if (name == NULL)
13685     {
13686       complaint (&symfile_complaints,
13687                  _("missing name for subprogram DIE at %d"),
13688                  to_underlying (die->sect_off));
13689       return;
13690     }
13691
13692   /* Ignore functions with missing or invalid low and high pc attributes.  */
13693   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13694       <= PC_BOUNDS_INVALID)
13695     {
13696       attr = dwarf2_attr (die, DW_AT_external, cu);
13697       if (!attr || !DW_UNSND (attr))
13698         complaint (&symfile_complaints,
13699                    _("cannot get low and high bounds "
13700                      "for subprogram DIE at %d"),
13701                    to_underlying (die->sect_off));
13702       return;
13703     }
13704
13705   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13706   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13707
13708   /* If we have any template arguments, then we must allocate a
13709      different sort of symbol.  */
13710   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13711     {
13712       if (child_die->tag == DW_TAG_template_type_param
13713           || child_die->tag == DW_TAG_template_value_param)
13714         {
13715           templ_func = allocate_template_symbol (objfile);
13716           templ_func->subclass = SYMBOL_TEMPLATE;
13717           break;
13718         }
13719     }
13720
13721   newobj = push_context (0, lowpc);
13722   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
13723                                (struct symbol *) templ_func);
13724
13725   /* If there is a location expression for DW_AT_frame_base, record
13726      it.  */
13727   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13728   if (attr)
13729     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13730
13731   /* If there is a location for the static link, record it.  */
13732   newobj->static_link = NULL;
13733   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13734   if (attr)
13735     {
13736       newobj->static_link
13737         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13738       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13739     }
13740
13741   cu->list_in_scope = &local_symbols;
13742
13743   if (die->child != NULL)
13744     {
13745       child_die = die->child;
13746       while (child_die && child_die->tag)
13747         {
13748           if (child_die->tag == DW_TAG_template_type_param
13749               || child_die->tag == DW_TAG_template_value_param)
13750             {
13751               struct symbol *arg = new_symbol (child_die, NULL, cu);
13752
13753               if (arg != NULL)
13754                 template_args.push_back (arg);
13755             }
13756           else
13757             process_die (child_die, cu);
13758           child_die = sibling_die (child_die);
13759         }
13760     }
13761
13762   inherit_abstract_dies (die, cu);
13763
13764   /* If we have a DW_AT_specification, we might need to import using
13765      directives from the context of the specification DIE.  See the
13766      comment in determine_prefix.  */
13767   if (cu->language == language_cplus
13768       && dwarf2_attr (die, DW_AT_specification, cu))
13769     {
13770       struct dwarf2_cu *spec_cu = cu;
13771       struct die_info *spec_die = die_specification (die, &spec_cu);
13772
13773       while (spec_die)
13774         {
13775           child_die = spec_die->child;
13776           while (child_die && child_die->tag)
13777             {
13778               if (child_die->tag == DW_TAG_imported_module)
13779                 process_die (child_die, spec_cu);
13780               child_die = sibling_die (child_die);
13781             }
13782
13783           /* In some cases, GCC generates specification DIEs that
13784              themselves contain DW_AT_specification attributes.  */
13785           spec_die = die_specification (spec_die, &spec_cu);
13786         }
13787     }
13788
13789   newobj = pop_context ();
13790   /* Make a block for the local symbols within.  */
13791   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13792                         newobj->static_link, lowpc, highpc);
13793
13794   /* For C++, set the block's scope.  */
13795   if ((cu->language == language_cplus
13796        || cu->language == language_fortran
13797        || cu->language == language_d
13798        || cu->language == language_rust)
13799       && cu->processing_has_namespace_info)
13800     block_set_scope (block, determine_prefix (die, cu),
13801                      &objfile->objfile_obstack);
13802
13803   /* If we have address ranges, record them.  */
13804   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13805
13806   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13807
13808   /* Attach template arguments to function.  */
13809   if (!template_args.empty ())
13810     {
13811       gdb_assert (templ_func != NULL);
13812
13813       templ_func->n_template_arguments = template_args.size ();
13814       templ_func->template_arguments
13815         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13816                      templ_func->n_template_arguments);
13817       memcpy (templ_func->template_arguments,
13818               template_args.data (),
13819               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13820     }
13821
13822   /* In C++, we can have functions nested inside functions (e.g., when
13823      a function declares a class that has methods).  This means that
13824      when we finish processing a function scope, we may need to go
13825      back to building a containing block's symbol lists.  */
13826   local_symbols = newobj->locals;
13827   local_using_directives = newobj->local_using_directives;
13828
13829   /* If we've finished processing a top-level function, subsequent
13830      symbols go in the file symbol list.  */
13831   if (outermost_context_p ())
13832     cu->list_in_scope = &file_symbols;
13833 }
13834
13835 /* Process all the DIES contained within a lexical block scope.  Start
13836    a new scope, process the dies, and then close the scope.  */
13837
13838 static void
13839 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13840 {
13841   struct objfile *objfile = cu->objfile;
13842   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13843   struct context_stack *newobj;
13844   CORE_ADDR lowpc, highpc;
13845   struct die_info *child_die;
13846   CORE_ADDR baseaddr;
13847
13848   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13849
13850   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13851   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13852      as multiple lexical blocks?  Handling children in a sane way would
13853      be nasty.  Might be easier to properly extend generic blocks to
13854      describe ranges.  */
13855   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13856     {
13857     case PC_BOUNDS_NOT_PRESENT:
13858       /* DW_TAG_lexical_block has no attributes, process its children as if
13859          there was no wrapping by that DW_TAG_lexical_block.
13860          GCC does no longer produces such DWARF since GCC r224161.  */
13861       for (child_die = die->child;
13862            child_die != NULL && child_die->tag;
13863            child_die = sibling_die (child_die))
13864         process_die (child_die, cu);
13865       return;
13866     case PC_BOUNDS_INVALID:
13867       return;
13868     }
13869   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13870   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13871
13872   push_context (0, lowpc);
13873   if (die->child != NULL)
13874     {
13875       child_die = die->child;
13876       while (child_die && child_die->tag)
13877         {
13878           process_die (child_die, cu);
13879           child_die = sibling_die (child_die);
13880         }
13881     }
13882   inherit_abstract_dies (die, cu);
13883   newobj = pop_context ();
13884
13885   if (local_symbols != NULL || local_using_directives != NULL)
13886     {
13887       struct block *block
13888         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13889                         newobj->start_addr, highpc);
13890
13891       /* Note that recording ranges after traversing children, as we
13892          do here, means that recording a parent's ranges entails
13893          walking across all its children's ranges as they appear in
13894          the address map, which is quadratic behavior.
13895
13896          It would be nicer to record the parent's ranges before
13897          traversing its children, simply overriding whatever you find
13898          there.  But since we don't even decide whether to create a
13899          block until after we've traversed its children, that's hard
13900          to do.  */
13901       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13902     }
13903   local_symbols = newobj->locals;
13904   local_using_directives = newobj->local_using_directives;
13905 }
13906
13907 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13908
13909 static void
13910 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13911 {
13912   struct objfile *objfile = cu->objfile;
13913   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13914   CORE_ADDR pc, baseaddr;
13915   struct attribute *attr;
13916   struct call_site *call_site, call_site_local;
13917   void **slot;
13918   int nparams;
13919   struct die_info *child_die;
13920
13921   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13922
13923   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13924   if (attr == NULL)
13925     {
13926       /* This was a pre-DWARF-5 GNU extension alias
13927          for DW_AT_call_return_pc.  */
13928       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13929     }
13930   if (!attr)
13931     {
13932       complaint (&symfile_complaints,
13933                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
13934                    "DIE 0x%x [in module %s]"),
13935                  to_underlying (die->sect_off), objfile_name (objfile));
13936       return;
13937     }
13938   pc = attr_value_as_address (attr) + baseaddr;
13939   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13940
13941   if (cu->call_site_htab == NULL)
13942     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13943                                                NULL, &objfile->objfile_obstack,
13944                                                hashtab_obstack_allocate, NULL);
13945   call_site_local.pc = pc;
13946   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13947   if (*slot != NULL)
13948     {
13949       complaint (&symfile_complaints,
13950                  _("Duplicate PC %s for DW_TAG_call_site "
13951                    "DIE 0x%x [in module %s]"),
13952                  paddress (gdbarch, pc), to_underlying (die->sect_off),
13953                  objfile_name (objfile));
13954       return;
13955     }
13956
13957   /* Count parameters at the caller.  */
13958
13959   nparams = 0;
13960   for (child_die = die->child; child_die && child_die->tag;
13961        child_die = sibling_die (child_die))
13962     {
13963       if (child_die->tag != DW_TAG_call_site_parameter
13964           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13965         {
13966           complaint (&symfile_complaints,
13967                      _("Tag %d is not DW_TAG_call_site_parameter in "
13968                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13969                      child_die->tag, to_underlying (child_die->sect_off),
13970                      objfile_name (objfile));
13971           continue;
13972         }
13973
13974       nparams++;
13975     }
13976
13977   call_site
13978     = ((struct call_site *)
13979        obstack_alloc (&objfile->objfile_obstack,
13980                       sizeof (*call_site)
13981                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13982   *slot = call_site;
13983   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13984   call_site->pc = pc;
13985
13986   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13987       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13988     {
13989       struct die_info *func_die;
13990
13991       /* Skip also over DW_TAG_inlined_subroutine.  */
13992       for (func_die = die->parent;
13993            func_die && func_die->tag != DW_TAG_subprogram
13994            && func_die->tag != DW_TAG_subroutine_type;
13995            func_die = func_die->parent);
13996
13997       /* DW_AT_call_all_calls is a superset
13998          of DW_AT_call_all_tail_calls.  */
13999       if (func_die
14000           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14001           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14002           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14003           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14004         {
14005           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14006              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14007              both the initial caller containing the real return address PC and
14008              the final callee containing the current PC of a chain of tail
14009              calls do not need to have the tail call list complete.  But any
14010              function candidate for a virtual tail call frame searched via
14011              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14012              determined unambiguously.  */
14013         }
14014       else
14015         {
14016           struct type *func_type = NULL;
14017
14018           if (func_die)
14019             func_type = get_die_type (func_die, cu);
14020           if (func_type != NULL)
14021             {
14022               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14023
14024               /* Enlist this call site to the function.  */
14025               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14026               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14027             }
14028           else
14029             complaint (&symfile_complaints,
14030                        _("Cannot find function owning DW_TAG_call_site "
14031                          "DIE 0x%x [in module %s]"),
14032                        to_underlying (die->sect_off), objfile_name (objfile));
14033         }
14034     }
14035
14036   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14037   if (attr == NULL)
14038     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14039   if (attr == NULL)
14040     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14041   if (attr == NULL)
14042     {
14043       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14044       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14045     }
14046   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14047   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14048     /* Keep NULL DWARF_BLOCK.  */;
14049   else if (attr_form_is_block (attr))
14050     {
14051       struct dwarf2_locexpr_baton *dlbaton;
14052
14053       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14054       dlbaton->data = DW_BLOCK (attr)->data;
14055       dlbaton->size = DW_BLOCK (attr)->size;
14056       dlbaton->per_cu = cu->per_cu;
14057
14058       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14059     }
14060   else if (attr_form_is_ref (attr))
14061     {
14062       struct dwarf2_cu *target_cu = cu;
14063       struct die_info *target_die;
14064
14065       target_die = follow_die_ref (die, attr, &target_cu);
14066       gdb_assert (target_cu->objfile == objfile);
14067       if (die_is_declaration (target_die, target_cu))
14068         {
14069           const char *target_physname;
14070
14071           /* Prefer the mangled name; otherwise compute the demangled one.  */
14072           target_physname = dw2_linkage_name (target_die, target_cu);
14073           if (target_physname == NULL)
14074             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14075           if (target_physname == NULL)
14076             complaint (&symfile_complaints,
14077                        _("DW_AT_call_target target DIE has invalid "
14078                          "physname, for referencing DIE 0x%x [in module %s]"),
14079                        to_underlying (die->sect_off), objfile_name (objfile));
14080           else
14081             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14082         }
14083       else
14084         {
14085           CORE_ADDR lowpc;
14086
14087           /* DW_AT_entry_pc should be preferred.  */
14088           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14089               <= PC_BOUNDS_INVALID)
14090             complaint (&symfile_complaints,
14091                        _("DW_AT_call_target target DIE has invalid "
14092                          "low pc, for referencing DIE 0x%x [in module %s]"),
14093                        to_underlying (die->sect_off), objfile_name (objfile));
14094           else
14095             {
14096               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14097               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14098             }
14099         }
14100     }
14101   else
14102     complaint (&symfile_complaints,
14103                _("DW_TAG_call_site DW_AT_call_target is neither "
14104                  "block nor reference, for DIE 0x%x [in module %s]"),
14105                to_underlying (die->sect_off), objfile_name (objfile));
14106
14107   call_site->per_cu = cu->per_cu;
14108
14109   for (child_die = die->child;
14110        child_die && child_die->tag;
14111        child_die = sibling_die (child_die))
14112     {
14113       struct call_site_parameter *parameter;
14114       struct attribute *loc, *origin;
14115
14116       if (child_die->tag != DW_TAG_call_site_parameter
14117           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14118         {
14119           /* Already printed the complaint above.  */
14120           continue;
14121         }
14122
14123       gdb_assert (call_site->parameter_count < nparams);
14124       parameter = &call_site->parameter[call_site->parameter_count];
14125
14126       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14127          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14128          register is contained in DW_AT_call_value.  */
14129
14130       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14131       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14132       if (origin == NULL)
14133         {
14134           /* This was a pre-DWARF-5 GNU extension alias
14135              for DW_AT_call_parameter.  */
14136           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14137         }
14138       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14139         {
14140           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14141
14142           sect_offset sect_off
14143             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14144           if (!offset_in_cu_p (&cu->header, sect_off))
14145             {
14146               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14147                  binding can be done only inside one CU.  Such referenced DIE
14148                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14149               complaint (&symfile_complaints,
14150                          _("DW_AT_call_parameter offset is not in CU for "
14151                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14152                          to_underlying (child_die->sect_off),
14153                          objfile_name (objfile));
14154               continue;
14155             }
14156           parameter->u.param_cu_off
14157             = (cu_offset) (sect_off - cu->header.sect_off);
14158         }
14159       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14160         {
14161           complaint (&symfile_complaints,
14162                      _("No DW_FORM_block* DW_AT_location for "
14163                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14164                      to_underlying (child_die->sect_off), objfile_name (objfile));
14165           continue;
14166         }
14167       else
14168         {
14169           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14170             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14171           if (parameter->u.dwarf_reg != -1)
14172             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14173           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14174                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14175                                              &parameter->u.fb_offset))
14176             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14177           else
14178             {
14179               complaint (&symfile_complaints,
14180                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14181                            "for DW_FORM_block* DW_AT_location is supported for "
14182                            "DW_TAG_call_site child DIE 0x%x "
14183                            "[in module %s]"),
14184                          to_underlying (child_die->sect_off),
14185                          objfile_name (objfile));
14186               continue;
14187             }
14188         }
14189
14190       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14191       if (attr == NULL)
14192         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14193       if (!attr_form_is_block (attr))
14194         {
14195           complaint (&symfile_complaints,
14196                      _("No DW_FORM_block* DW_AT_call_value for "
14197                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14198                      to_underlying (child_die->sect_off),
14199                      objfile_name (objfile));
14200           continue;
14201         }
14202       parameter->value = DW_BLOCK (attr)->data;
14203       parameter->value_size = DW_BLOCK (attr)->size;
14204
14205       /* Parameters are not pre-cleared by memset above.  */
14206       parameter->data_value = NULL;
14207       parameter->data_value_size = 0;
14208       call_site->parameter_count++;
14209
14210       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14211       if (attr == NULL)
14212         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14213       if (attr)
14214         {
14215           if (!attr_form_is_block (attr))
14216             complaint (&symfile_complaints,
14217                        _("No DW_FORM_block* DW_AT_call_data_value for "
14218                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14219                        to_underlying (child_die->sect_off),
14220                        objfile_name (objfile));
14221           else
14222             {
14223               parameter->data_value = DW_BLOCK (attr)->data;
14224               parameter->data_value_size = DW_BLOCK (attr)->size;
14225             }
14226         }
14227     }
14228 }
14229
14230 /* Helper function for read_variable.  If DIE represents a virtual
14231    table, then return the type of the concrete object that is
14232    associated with the virtual table.  Otherwise, return NULL.  */
14233
14234 static struct type *
14235 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14236 {
14237   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14238   if (attr == NULL)
14239     return NULL;
14240
14241   /* Find the type DIE.  */
14242   struct die_info *type_die = NULL;
14243   struct dwarf2_cu *type_cu = cu;
14244
14245   if (attr_form_is_ref (attr))
14246     type_die = follow_die_ref (die, attr, &type_cu);
14247   if (type_die == NULL)
14248     return NULL;
14249
14250   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14251     return NULL;
14252   return die_containing_type (type_die, type_cu);
14253 }
14254
14255 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14256
14257 static void
14258 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14259 {
14260   struct rust_vtable_symbol *storage = NULL;
14261
14262   if (cu->language == language_rust)
14263     {
14264       struct type *containing_type = rust_containing_type (die, cu);
14265
14266       if (containing_type != NULL)
14267         {
14268           struct objfile *objfile = cu->objfile;
14269
14270           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14271                                     struct rust_vtable_symbol);
14272           initialize_objfile_symbol (storage);
14273           storage->concrete_type = containing_type;
14274           storage->subclass = SYMBOL_RUST_VTABLE;
14275         }
14276     }
14277
14278   new_symbol_full (die, NULL, cu, storage);
14279 }
14280
14281 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14282    reading .debug_rnglists.
14283    Callback's type should be:
14284     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14285    Return true if the attributes are present and valid, otherwise,
14286    return false.  */
14287
14288 template <typename Callback>
14289 static bool
14290 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14291                          Callback &&callback)
14292 {
14293   struct objfile *objfile = cu->objfile;
14294   bfd *obfd = objfile->obfd;
14295   /* Base address selection entry.  */
14296   CORE_ADDR base;
14297   int found_base;
14298   const gdb_byte *buffer;
14299   CORE_ADDR baseaddr;
14300   bool overflow = false;
14301
14302   found_base = cu->base_known;
14303   base = cu->base_address;
14304
14305   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14306   if (offset >= dwarf2_per_objfile->rnglists.size)
14307     {
14308       complaint (&symfile_complaints,
14309                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14310                  offset);
14311       return false;
14312     }
14313   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14314
14315   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14316
14317   while (1)
14318     {
14319       /* Initialize it due to a false compiler warning.  */
14320       CORE_ADDR range_beginning = 0, range_end = 0;
14321       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14322                                  + dwarf2_per_objfile->rnglists.size);
14323       unsigned int bytes_read;
14324
14325       if (buffer == buf_end)
14326         {
14327           overflow = true;
14328           break;
14329         }
14330       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14331       switch (rlet)
14332         {
14333         case DW_RLE_end_of_list:
14334           break;
14335         case DW_RLE_base_address:
14336           if (buffer + cu->header.addr_size > buf_end)
14337             {
14338               overflow = true;
14339               break;
14340             }
14341           base = read_address (obfd, buffer, cu, &bytes_read);
14342           found_base = 1;
14343           buffer += bytes_read;
14344           break;
14345         case DW_RLE_start_length:
14346           if (buffer + cu->header.addr_size > buf_end)
14347             {
14348               overflow = true;
14349               break;
14350             }
14351           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14352           buffer += bytes_read;
14353           range_end = (range_beginning
14354                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14355           buffer += bytes_read;
14356           if (buffer > buf_end)
14357             {
14358               overflow = true;
14359               break;
14360             }
14361           break;
14362         case DW_RLE_offset_pair:
14363           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14364           buffer += bytes_read;
14365           if (buffer > buf_end)
14366             {
14367               overflow = true;
14368               break;
14369             }
14370           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14371           buffer += bytes_read;
14372           if (buffer > buf_end)
14373             {
14374               overflow = true;
14375               break;
14376             }
14377           break;
14378         case DW_RLE_start_end:
14379           if (buffer + 2 * cu->header.addr_size > buf_end)
14380             {
14381               overflow = true;
14382               break;
14383             }
14384           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14385           buffer += bytes_read;
14386           range_end = read_address (obfd, buffer, cu, &bytes_read);
14387           buffer += bytes_read;
14388           break;
14389         default:
14390           complaint (&symfile_complaints,
14391                      _("Invalid .debug_rnglists data (no base address)"));
14392           return false;
14393         }
14394       if (rlet == DW_RLE_end_of_list || overflow)
14395         break;
14396       if (rlet == DW_RLE_base_address)
14397         continue;
14398
14399       if (!found_base)
14400         {
14401           /* We have no valid base address for the ranges
14402              data.  */
14403           complaint (&symfile_complaints,
14404                      _("Invalid .debug_rnglists data (no base address)"));
14405           return false;
14406         }
14407
14408       if (range_beginning > range_end)
14409         {
14410           /* Inverted range entries are invalid.  */
14411           complaint (&symfile_complaints,
14412                      _("Invalid .debug_rnglists data (inverted range)"));
14413           return false;
14414         }
14415
14416       /* Empty range entries have no effect.  */
14417       if (range_beginning == range_end)
14418         continue;
14419
14420       range_beginning += base;
14421       range_end += base;
14422
14423       /* A not-uncommon case of bad debug info.
14424          Don't pollute the addrmap with bad data.  */
14425       if (range_beginning + baseaddr == 0
14426           && !dwarf2_per_objfile->has_section_at_zero)
14427         {
14428           complaint (&symfile_complaints,
14429                      _(".debug_rnglists entry has start address of zero"
14430                        " [in module %s]"), objfile_name (objfile));
14431           continue;
14432         }
14433
14434       callback (range_beginning, range_end);
14435     }
14436
14437   if (overflow)
14438     {
14439       complaint (&symfile_complaints,
14440                  _("Offset %d is not terminated "
14441                    "for DW_AT_ranges attribute"),
14442                  offset);
14443       return false;
14444     }
14445
14446   return true;
14447 }
14448
14449 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14450    Callback's type should be:
14451     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14452    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14453
14454 template <typename Callback>
14455 static int
14456 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14457                        Callback &&callback)
14458 {
14459   struct objfile *objfile = cu->objfile;
14460   struct comp_unit_head *cu_header = &cu->header;
14461   bfd *obfd = objfile->obfd;
14462   unsigned int addr_size = cu_header->addr_size;
14463   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14464   /* Base address selection entry.  */
14465   CORE_ADDR base;
14466   int found_base;
14467   unsigned int dummy;
14468   const gdb_byte *buffer;
14469   CORE_ADDR baseaddr;
14470
14471   if (cu_header->version >= 5)
14472     return dwarf2_rnglists_process (offset, cu, callback);
14473
14474   found_base = cu->base_known;
14475   base = cu->base_address;
14476
14477   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14478   if (offset >= dwarf2_per_objfile->ranges.size)
14479     {
14480       complaint (&symfile_complaints,
14481                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14482                  offset);
14483       return 0;
14484     }
14485   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14486
14487   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14488
14489   while (1)
14490     {
14491       CORE_ADDR range_beginning, range_end;
14492
14493       range_beginning = read_address (obfd, buffer, cu, &dummy);
14494       buffer += addr_size;
14495       range_end = read_address (obfd, buffer, cu, &dummy);
14496       buffer += addr_size;
14497       offset += 2 * addr_size;
14498
14499       /* An end of list marker is a pair of zero addresses.  */
14500       if (range_beginning == 0 && range_end == 0)
14501         /* Found the end of list entry.  */
14502         break;
14503
14504       /* Each base address selection entry is a pair of 2 values.
14505          The first is the largest possible address, the second is
14506          the base address.  Check for a base address here.  */
14507       if ((range_beginning & mask) == mask)
14508         {
14509           /* If we found the largest possible address, then we already
14510              have the base address in range_end.  */
14511           base = range_end;
14512           found_base = 1;
14513           continue;
14514         }
14515
14516       if (!found_base)
14517         {
14518           /* We have no valid base address for the ranges
14519              data.  */
14520           complaint (&symfile_complaints,
14521                      _("Invalid .debug_ranges data (no base address)"));
14522           return 0;
14523         }
14524
14525       if (range_beginning > range_end)
14526         {
14527           /* Inverted range entries are invalid.  */
14528           complaint (&symfile_complaints,
14529                      _("Invalid .debug_ranges data (inverted range)"));
14530           return 0;
14531         }
14532
14533       /* Empty range entries have no effect.  */
14534       if (range_beginning == range_end)
14535         continue;
14536
14537       range_beginning += base;
14538       range_end += base;
14539
14540       /* A not-uncommon case of bad debug info.
14541          Don't pollute the addrmap with bad data.  */
14542       if (range_beginning + baseaddr == 0
14543           && !dwarf2_per_objfile->has_section_at_zero)
14544         {
14545           complaint (&symfile_complaints,
14546                      _(".debug_ranges entry has start address of zero"
14547                        " [in module %s]"), objfile_name (objfile));
14548           continue;
14549         }
14550
14551       callback (range_beginning, range_end);
14552     }
14553
14554   return 1;
14555 }
14556
14557 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14558    Return 1 if the attributes are present and valid, otherwise, return 0.
14559    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14560
14561 static int
14562 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14563                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14564                     struct partial_symtab *ranges_pst)
14565 {
14566   struct objfile *objfile = cu->objfile;
14567   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14568   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14569                                        SECT_OFF_TEXT (objfile));
14570   int low_set = 0;
14571   CORE_ADDR low = 0;
14572   CORE_ADDR high = 0;
14573   int retval;
14574
14575   retval = dwarf2_ranges_process (offset, cu,
14576     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14577     {
14578       if (ranges_pst != NULL)
14579         {
14580           CORE_ADDR lowpc;
14581           CORE_ADDR highpc;
14582
14583           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14584                                               range_beginning + baseaddr);
14585           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14586                                                range_end + baseaddr);
14587           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14588                              ranges_pst);
14589         }
14590
14591       /* FIXME: This is recording everything as a low-high
14592          segment of consecutive addresses.  We should have a
14593          data structure for discontiguous block ranges
14594          instead.  */
14595       if (! low_set)
14596         {
14597           low = range_beginning;
14598           high = range_end;
14599           low_set = 1;
14600         }
14601       else
14602         {
14603           if (range_beginning < low)
14604             low = range_beginning;
14605           if (range_end > high)
14606             high = range_end;
14607         }
14608     });
14609   if (!retval)
14610     return 0;
14611
14612   if (! low_set)
14613     /* If the first entry is an end-of-list marker, the range
14614        describes an empty scope, i.e. no instructions.  */
14615     return 0;
14616
14617   if (low_return)
14618     *low_return = low;
14619   if (high_return)
14620     *high_return = high;
14621   return 1;
14622 }
14623
14624 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14625    definition for the return value.  *LOWPC and *HIGHPC are set iff
14626    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14627
14628 static enum pc_bounds_kind
14629 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14630                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14631                       struct partial_symtab *pst)
14632 {
14633   struct attribute *attr;
14634   struct attribute *attr_high;
14635   CORE_ADDR low = 0;
14636   CORE_ADDR high = 0;
14637   enum pc_bounds_kind ret;
14638
14639   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14640   if (attr_high)
14641     {
14642       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14643       if (attr)
14644         {
14645           low = attr_value_as_address (attr);
14646           high = attr_value_as_address (attr_high);
14647           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14648             high += low;
14649         }
14650       else
14651         /* Found high w/o low attribute.  */
14652         return PC_BOUNDS_INVALID;
14653
14654       /* Found consecutive range of addresses.  */
14655       ret = PC_BOUNDS_HIGH_LOW;
14656     }
14657   else
14658     {
14659       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14660       if (attr != NULL)
14661         {
14662           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14663              We take advantage of the fact that DW_AT_ranges does not appear
14664              in DW_TAG_compile_unit of DWO files.  */
14665           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14666           unsigned int ranges_offset = (DW_UNSND (attr)
14667                                         + (need_ranges_base
14668                                            ? cu->ranges_base
14669                                            : 0));
14670
14671           /* Value of the DW_AT_ranges attribute is the offset in the
14672              .debug_ranges section.  */
14673           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14674             return PC_BOUNDS_INVALID;
14675           /* Found discontinuous range of addresses.  */
14676           ret = PC_BOUNDS_RANGES;
14677         }
14678       else
14679         return PC_BOUNDS_NOT_PRESENT;
14680     }
14681
14682   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14683   if (high <= low)
14684     return PC_BOUNDS_INVALID;
14685
14686   /* When using the GNU linker, .gnu.linkonce. sections are used to
14687      eliminate duplicate copies of functions and vtables and such.
14688      The linker will arbitrarily choose one and discard the others.
14689      The AT_*_pc values for such functions refer to local labels in
14690      these sections.  If the section from that file was discarded, the
14691      labels are not in the output, so the relocs get a value of 0.
14692      If this is a discarded function, mark the pc bounds as invalid,
14693      so that GDB will ignore it.  */
14694   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14695     return PC_BOUNDS_INVALID;
14696
14697   *lowpc = low;
14698   if (highpc)
14699     *highpc = high;
14700   return ret;
14701 }
14702
14703 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14704    its low and high PC addresses.  Do nothing if these addresses could not
14705    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14706    and HIGHPC to the high address if greater than HIGHPC.  */
14707
14708 static void
14709 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14710                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14711                                  struct dwarf2_cu *cu)
14712 {
14713   CORE_ADDR low, high;
14714   struct die_info *child = die->child;
14715
14716   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14717     {
14718       *lowpc = std::min (*lowpc, low);
14719       *highpc = std::max (*highpc, high);
14720     }
14721
14722   /* If the language does not allow nested subprograms (either inside
14723      subprograms or lexical blocks), we're done.  */
14724   if (cu->language != language_ada)
14725     return;
14726
14727   /* Check all the children of the given DIE.  If it contains nested
14728      subprograms, then check their pc bounds.  Likewise, we need to
14729      check lexical blocks as well, as they may also contain subprogram
14730      definitions.  */
14731   while (child && child->tag)
14732     {
14733       if (child->tag == DW_TAG_subprogram
14734           || child->tag == DW_TAG_lexical_block)
14735         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14736       child = sibling_die (child);
14737     }
14738 }
14739
14740 /* Get the low and high pc's represented by the scope DIE, and store
14741    them in *LOWPC and *HIGHPC.  If the correct values can't be
14742    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14743
14744 static void
14745 get_scope_pc_bounds (struct die_info *die,
14746                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14747                      struct dwarf2_cu *cu)
14748 {
14749   CORE_ADDR best_low = (CORE_ADDR) -1;
14750   CORE_ADDR best_high = (CORE_ADDR) 0;
14751   CORE_ADDR current_low, current_high;
14752
14753   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14754       >= PC_BOUNDS_RANGES)
14755     {
14756       best_low = current_low;
14757       best_high = current_high;
14758     }
14759   else
14760     {
14761       struct die_info *child = die->child;
14762
14763       while (child && child->tag)
14764         {
14765           switch (child->tag) {
14766           case DW_TAG_subprogram:
14767             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14768             break;
14769           case DW_TAG_namespace:
14770           case DW_TAG_module:
14771             /* FIXME: carlton/2004-01-16: Should we do this for
14772                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14773                that current GCC's always emit the DIEs corresponding
14774                to definitions of methods of classes as children of a
14775                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14776                the DIEs giving the declarations, which could be
14777                anywhere).  But I don't see any reason why the
14778                standards says that they have to be there.  */
14779             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14780
14781             if (current_low != ((CORE_ADDR) -1))
14782               {
14783                 best_low = std::min (best_low, current_low);
14784                 best_high = std::max (best_high, current_high);
14785               }
14786             break;
14787           default:
14788             /* Ignore.  */
14789             break;
14790           }
14791
14792           child = sibling_die (child);
14793         }
14794     }
14795
14796   *lowpc = best_low;
14797   *highpc = best_high;
14798 }
14799
14800 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14801    in DIE.  */
14802
14803 static void
14804 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14805                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14806 {
14807   struct objfile *objfile = cu->objfile;
14808   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14809   struct attribute *attr;
14810   struct attribute *attr_high;
14811
14812   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14813   if (attr_high)
14814     {
14815       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14816       if (attr)
14817         {
14818           CORE_ADDR low = attr_value_as_address (attr);
14819           CORE_ADDR high = attr_value_as_address (attr_high);
14820
14821           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14822             high += low;
14823
14824           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14825           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14826           record_block_range (block, low, high - 1);
14827         }
14828     }
14829
14830   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14831   if (attr)
14832     {
14833       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14834          We take advantage of the fact that DW_AT_ranges does not appear
14835          in DW_TAG_compile_unit of DWO files.  */
14836       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14837
14838       /* The value of the DW_AT_ranges attribute is the offset of the
14839          address range list in the .debug_ranges section.  */
14840       unsigned long offset = (DW_UNSND (attr)
14841                               + (need_ranges_base ? cu->ranges_base : 0));
14842       const gdb_byte *buffer;
14843
14844       /* For some target architectures, but not others, the
14845          read_address function sign-extends the addresses it returns.
14846          To recognize base address selection entries, we need a
14847          mask.  */
14848       unsigned int addr_size = cu->header.addr_size;
14849       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14850
14851       /* The base address, to which the next pair is relative.  Note
14852          that this 'base' is a DWARF concept: most entries in a range
14853          list are relative, to reduce the number of relocs against the
14854          debugging information.  This is separate from this function's
14855          'baseaddr' argument, which GDB uses to relocate debugging
14856          information from a shared library based on the address at
14857          which the library was loaded.  */
14858       CORE_ADDR base = cu->base_address;
14859       int base_known = cu->base_known;
14860
14861       dwarf2_ranges_process (offset, cu,
14862         [&] (CORE_ADDR start, CORE_ADDR end)
14863         {
14864           start += baseaddr;
14865           end += baseaddr;
14866           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14867           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14868           record_block_range (block, start, end - 1);
14869         });
14870     }
14871 }
14872
14873 /* Check whether the producer field indicates either of GCC < 4.6, or the
14874    Intel C/C++ compiler, and cache the result in CU.  */
14875
14876 static void
14877 check_producer (struct dwarf2_cu *cu)
14878 {
14879   int major, minor;
14880
14881   if (cu->producer == NULL)
14882     {
14883       /* For unknown compilers expect their behavior is DWARF version
14884          compliant.
14885
14886          GCC started to support .debug_types sections by -gdwarf-4 since
14887          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14888          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14889          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14890          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14891     }
14892   else if (producer_is_gcc (cu->producer, &major, &minor))
14893     {
14894       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14895       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14896     }
14897   else if (producer_is_icc (cu->producer, &major, &minor))
14898     cu->producer_is_icc_lt_14 = major < 14;
14899   else
14900     {
14901       /* For other non-GCC compilers, expect their behavior is DWARF version
14902          compliant.  */
14903     }
14904
14905   cu->checked_producer = 1;
14906 }
14907
14908 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14909    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14910    during 4.6.0 experimental.  */
14911
14912 static int
14913 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14914 {
14915   if (!cu->checked_producer)
14916     check_producer (cu);
14917
14918   return cu->producer_is_gxx_lt_4_6;
14919 }
14920
14921 /* Return the default accessibility type if it is not overriden by
14922    DW_AT_accessibility.  */
14923
14924 static enum dwarf_access_attribute
14925 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14926 {
14927   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14928     {
14929       /* The default DWARF 2 accessibility for members is public, the default
14930          accessibility for inheritance is private.  */
14931
14932       if (die->tag != DW_TAG_inheritance)
14933         return DW_ACCESS_public;
14934       else
14935         return DW_ACCESS_private;
14936     }
14937   else
14938     {
14939       /* DWARF 3+ defines the default accessibility a different way.  The same
14940          rules apply now for DW_TAG_inheritance as for the members and it only
14941          depends on the container kind.  */
14942
14943       if (die->parent->tag == DW_TAG_class_type)
14944         return DW_ACCESS_private;
14945       else
14946         return DW_ACCESS_public;
14947     }
14948 }
14949
14950 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14951    offset.  If the attribute was not found return 0, otherwise return
14952    1.  If it was found but could not properly be handled, set *OFFSET
14953    to 0.  */
14954
14955 static int
14956 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14957                              LONGEST *offset)
14958 {
14959   struct attribute *attr;
14960
14961   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14962   if (attr != NULL)
14963     {
14964       *offset = 0;
14965
14966       /* Note that we do not check for a section offset first here.
14967          This is because DW_AT_data_member_location is new in DWARF 4,
14968          so if we see it, we can assume that a constant form is really
14969          a constant and not a section offset.  */
14970       if (attr_form_is_constant (attr))
14971         *offset = dwarf2_get_attr_constant_value (attr, 0);
14972       else if (attr_form_is_section_offset (attr))
14973         dwarf2_complex_location_expr_complaint ();
14974       else if (attr_form_is_block (attr))
14975         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14976       else
14977         dwarf2_complex_location_expr_complaint ();
14978
14979       return 1;
14980     }
14981
14982   return 0;
14983 }
14984
14985 /* Add an aggregate field to the field list.  */
14986
14987 static void
14988 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14989                   struct dwarf2_cu *cu)
14990 {
14991   struct objfile *objfile = cu->objfile;
14992   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14993   struct nextfield *new_field;
14994   struct attribute *attr;
14995   struct field *fp;
14996   const char *fieldname = "";
14997
14998   /* Allocate a new field list entry and link it in.  */
14999   new_field = XNEW (struct nextfield);
15000   make_cleanup (xfree, new_field);
15001   memset (new_field, 0, sizeof (struct nextfield));
15002
15003   if (die->tag == DW_TAG_inheritance)
15004     {
15005       new_field->next = fip->baseclasses;
15006       fip->baseclasses = new_field;
15007     }
15008   else
15009     {
15010       new_field->next = fip->fields;
15011       fip->fields = new_field;
15012     }
15013   fip->nfields++;
15014
15015   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15016   if (attr)
15017     new_field->accessibility = DW_UNSND (attr);
15018   else
15019     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15020   if (new_field->accessibility != DW_ACCESS_public)
15021     fip->non_public_fields = 1;
15022
15023   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15024   if (attr)
15025     new_field->virtuality = DW_UNSND (attr);
15026   else
15027     new_field->virtuality = DW_VIRTUALITY_none;
15028
15029   fp = &new_field->field;
15030
15031   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15032     {
15033       LONGEST offset;
15034
15035       /* Data member other than a C++ static data member.  */
15036
15037       /* Get type of field.  */
15038       fp->type = die_type (die, cu);
15039
15040       SET_FIELD_BITPOS (*fp, 0);
15041
15042       /* Get bit size of field (zero if none).  */
15043       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15044       if (attr)
15045         {
15046           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15047         }
15048       else
15049         {
15050           FIELD_BITSIZE (*fp) = 0;
15051         }
15052
15053       /* Get bit offset of field.  */
15054       if (handle_data_member_location (die, cu, &offset))
15055         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15056       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15057       if (attr)
15058         {
15059           if (gdbarch_bits_big_endian (gdbarch))
15060             {
15061               /* For big endian bits, the DW_AT_bit_offset gives the
15062                  additional bit offset from the MSB of the containing
15063                  anonymous object to the MSB of the field.  We don't
15064                  have to do anything special since we don't need to
15065                  know the size of the anonymous object.  */
15066               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15067             }
15068           else
15069             {
15070               /* For little endian bits, compute the bit offset to the
15071                  MSB of the anonymous object, subtract off the number of
15072                  bits from the MSB of the field to the MSB of the
15073                  object, and then subtract off the number of bits of
15074                  the field itself.  The result is the bit offset of
15075                  the LSB of the field.  */
15076               int anonymous_size;
15077               int bit_offset = DW_UNSND (attr);
15078
15079               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15080               if (attr)
15081                 {
15082                   /* The size of the anonymous object containing
15083                      the bit field is explicit, so use the
15084                      indicated size (in bytes).  */
15085                   anonymous_size = DW_UNSND (attr);
15086                 }
15087               else
15088                 {
15089                   /* The size of the anonymous object containing
15090                      the bit field must be inferred from the type
15091                      attribute of the data member containing the
15092                      bit field.  */
15093                   anonymous_size = TYPE_LENGTH (fp->type);
15094                 }
15095               SET_FIELD_BITPOS (*fp,
15096                                 (FIELD_BITPOS (*fp)
15097                                  + anonymous_size * bits_per_byte
15098                                  - bit_offset - FIELD_BITSIZE (*fp)));
15099             }
15100         }
15101       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15102       if (attr != NULL)
15103         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15104                                 + dwarf2_get_attr_constant_value (attr, 0)));
15105
15106       /* Get name of field.  */
15107       fieldname = dwarf2_name (die, cu);
15108       if (fieldname == NULL)
15109         fieldname = "";
15110
15111       /* The name is already allocated along with this objfile, so we don't
15112          need to duplicate it for the type.  */
15113       fp->name = fieldname;
15114
15115       /* Change accessibility for artificial fields (e.g. virtual table
15116          pointer or virtual base class pointer) to private.  */
15117       if (dwarf2_attr (die, DW_AT_artificial, cu))
15118         {
15119           FIELD_ARTIFICIAL (*fp) = 1;
15120           new_field->accessibility = DW_ACCESS_private;
15121           fip->non_public_fields = 1;
15122         }
15123     }
15124   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15125     {
15126       /* C++ static member.  */
15127
15128       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15129          is a declaration, but all versions of G++ as of this writing
15130          (so through at least 3.2.1) incorrectly generate
15131          DW_TAG_variable tags.  */
15132
15133       const char *physname;
15134
15135       /* Get name of field.  */
15136       fieldname = dwarf2_name (die, cu);
15137       if (fieldname == NULL)
15138         return;
15139
15140       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15141       if (attr
15142           /* Only create a symbol if this is an external value.
15143              new_symbol checks this and puts the value in the global symbol
15144              table, which we want.  If it is not external, new_symbol
15145              will try to put the value in cu->list_in_scope which is wrong.  */
15146           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15147         {
15148           /* A static const member, not much different than an enum as far as
15149              we're concerned, except that we can support more types.  */
15150           new_symbol (die, NULL, cu);
15151         }
15152
15153       /* Get physical name.  */
15154       physname = dwarf2_physname (fieldname, die, cu);
15155
15156       /* The name is already allocated along with this objfile, so we don't
15157          need to duplicate it for the type.  */
15158       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15159       FIELD_TYPE (*fp) = die_type (die, cu);
15160       FIELD_NAME (*fp) = fieldname;
15161     }
15162   else if (die->tag == DW_TAG_inheritance)
15163     {
15164       LONGEST offset;
15165
15166       /* C++ base class field.  */
15167       if (handle_data_member_location (die, cu, &offset))
15168         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15169       FIELD_BITSIZE (*fp) = 0;
15170       FIELD_TYPE (*fp) = die_type (die, cu);
15171       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15172       fip->nbaseclasses++;
15173     }
15174 }
15175
15176 /* Can the type given by DIE define another type?  */
15177
15178 static bool
15179 type_can_define_types (const struct die_info *die)
15180 {
15181   switch (die->tag)
15182     {
15183     case DW_TAG_typedef:
15184     case DW_TAG_class_type:
15185     case DW_TAG_structure_type:
15186     case DW_TAG_union_type:
15187     case DW_TAG_enumeration_type:
15188       return true;
15189
15190     default:
15191       return false;
15192     }
15193 }
15194
15195 /* Add a type definition defined in the scope of the FIP's class.  */
15196
15197 static void
15198 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15199                       struct dwarf2_cu *cu)
15200 {
15201   struct decl_field_list *new_field;
15202   struct decl_field *fp;
15203
15204   /* Allocate a new field list entry and link it in.  */
15205   new_field = XCNEW (struct decl_field_list);
15206   make_cleanup (xfree, new_field);
15207
15208   gdb_assert (type_can_define_types (die));
15209
15210   fp = &new_field->field;
15211
15212   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15213   fp->name = dwarf2_name (die, cu);
15214   fp->type = read_type_die (die, cu);
15215
15216   /* Save accessibility.  */
15217   enum dwarf_access_attribute accessibility;
15218   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15219   if (attr != NULL)
15220     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15221   else
15222     accessibility = dwarf2_default_access_attribute (die, cu);
15223   switch (accessibility)
15224     {
15225     case DW_ACCESS_public:
15226       /* The assumed value if neither private nor protected.  */
15227       break;
15228     case DW_ACCESS_private:
15229       fp->is_private = 1;
15230       break;
15231     case DW_ACCESS_protected:
15232       fp->is_protected = 1;
15233       break;
15234     default:
15235       complaint (&symfile_complaints,
15236                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15237     }
15238
15239   if (die->tag == DW_TAG_typedef)
15240     {
15241       new_field->next = fip->typedef_field_list;
15242       fip->typedef_field_list = new_field;
15243       fip->typedef_field_list_count++;
15244     }
15245   else
15246     {
15247       new_field->next = fip->nested_types_list;
15248       fip->nested_types_list = new_field;
15249       fip->nested_types_list_count++;
15250     }
15251 }
15252
15253 /* Create the vector of fields, and attach it to the type.  */
15254
15255 static void
15256 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15257                               struct dwarf2_cu *cu)
15258 {
15259   int nfields = fip->nfields;
15260
15261   /* Record the field count, allocate space for the array of fields,
15262      and create blank accessibility bitfields if necessary.  */
15263   TYPE_NFIELDS (type) = nfields;
15264   TYPE_FIELDS (type) = (struct field *)
15265     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15266   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15267
15268   if (fip->non_public_fields && cu->language != language_ada)
15269     {
15270       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15271
15272       TYPE_FIELD_PRIVATE_BITS (type) =
15273         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15274       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15275
15276       TYPE_FIELD_PROTECTED_BITS (type) =
15277         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15278       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15279
15280       TYPE_FIELD_IGNORE_BITS (type) =
15281         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15282       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15283     }
15284
15285   /* If the type has baseclasses, allocate and clear a bit vector for
15286      TYPE_FIELD_VIRTUAL_BITS.  */
15287   if (fip->nbaseclasses && cu->language != language_ada)
15288     {
15289       int num_bytes = B_BYTES (fip->nbaseclasses);
15290       unsigned char *pointer;
15291
15292       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15293       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15294       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15295       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15296       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15297     }
15298
15299   /* Copy the saved-up fields into the field vector.  Start from the head of
15300      the list, adding to the tail of the field array, so that they end up in
15301      the same order in the array in which they were added to the list.  */
15302   while (nfields-- > 0)
15303     {
15304       struct nextfield *fieldp;
15305
15306       if (fip->fields)
15307         {
15308           fieldp = fip->fields;
15309           fip->fields = fieldp->next;
15310         }
15311       else
15312         {
15313           fieldp = fip->baseclasses;
15314           fip->baseclasses = fieldp->next;
15315         }
15316
15317       TYPE_FIELD (type, nfields) = fieldp->field;
15318       switch (fieldp->accessibility)
15319         {
15320         case DW_ACCESS_private:
15321           if (cu->language != language_ada)
15322             SET_TYPE_FIELD_PRIVATE (type, nfields);
15323           break;
15324
15325         case DW_ACCESS_protected:
15326           if (cu->language != language_ada)
15327             SET_TYPE_FIELD_PROTECTED (type, nfields);
15328           break;
15329
15330         case DW_ACCESS_public:
15331           break;
15332
15333         default:
15334           /* Unknown accessibility.  Complain and treat it as public.  */
15335           {
15336             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15337                        fieldp->accessibility);
15338           }
15339           break;
15340         }
15341       if (nfields < fip->nbaseclasses)
15342         {
15343           switch (fieldp->virtuality)
15344             {
15345             case DW_VIRTUALITY_virtual:
15346             case DW_VIRTUALITY_pure_virtual:
15347               if (cu->language == language_ada)
15348                 error (_("unexpected virtuality in component of Ada type"));
15349               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15350               break;
15351             }
15352         }
15353     }
15354 }
15355
15356 /* Return true if this member function is a constructor, false
15357    otherwise.  */
15358
15359 static int
15360 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15361 {
15362   const char *fieldname;
15363   const char *type_name;
15364   int len;
15365
15366   if (die->parent == NULL)
15367     return 0;
15368
15369   if (die->parent->tag != DW_TAG_structure_type
15370       && die->parent->tag != DW_TAG_union_type
15371       && die->parent->tag != DW_TAG_class_type)
15372     return 0;
15373
15374   fieldname = dwarf2_name (die, cu);
15375   type_name = dwarf2_name (die->parent, cu);
15376   if (fieldname == NULL || type_name == NULL)
15377     return 0;
15378
15379   len = strlen (fieldname);
15380   return (strncmp (fieldname, type_name, len) == 0
15381           && (type_name[len] == '\0' || type_name[len] == '<'));
15382 }
15383
15384 /* Add a member function to the proper fieldlist.  */
15385
15386 static void
15387 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15388                       struct type *type, struct dwarf2_cu *cu)
15389 {
15390   struct objfile *objfile = cu->objfile;
15391   struct attribute *attr;
15392   struct fnfieldlist *flp;
15393   int i;
15394   struct fn_field *fnp;
15395   const char *fieldname;
15396   struct nextfnfield *new_fnfield;
15397   struct type *this_type;
15398   enum dwarf_access_attribute accessibility;
15399
15400   if (cu->language == language_ada)
15401     error (_("unexpected member function in Ada type"));
15402
15403   /* Get name of member function.  */
15404   fieldname = dwarf2_name (die, cu);
15405   if (fieldname == NULL)
15406     return;
15407
15408   /* Look up member function name in fieldlist.  */
15409   for (i = 0; i < fip->nfnfields; i++)
15410     {
15411       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15412         break;
15413     }
15414
15415   /* Create new list element if necessary.  */
15416   if (i < fip->nfnfields)
15417     flp = &fip->fnfieldlists[i];
15418   else
15419     {
15420       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15421         {
15422           fip->fnfieldlists = (struct fnfieldlist *)
15423             xrealloc (fip->fnfieldlists,
15424                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15425                       * sizeof (struct fnfieldlist));
15426           if (fip->nfnfields == 0)
15427             make_cleanup (free_current_contents, &fip->fnfieldlists);
15428         }
15429       flp = &fip->fnfieldlists[fip->nfnfields];
15430       flp->name = fieldname;
15431       flp->length = 0;
15432       flp->head = NULL;
15433       i = fip->nfnfields++;
15434     }
15435
15436   /* Create a new member function field and chain it to the field list
15437      entry.  */
15438   new_fnfield = XNEW (struct nextfnfield);
15439   make_cleanup (xfree, new_fnfield);
15440   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15441   new_fnfield->next = flp->head;
15442   flp->head = new_fnfield;
15443   flp->length++;
15444
15445   /* Fill in the member function field info.  */
15446   fnp = &new_fnfield->fnfield;
15447
15448   /* Delay processing of the physname until later.  */
15449   if (cu->language == language_cplus)
15450     {
15451       add_to_method_list (type, i, flp->length - 1, fieldname,
15452                           die, cu);
15453     }
15454   else
15455     {
15456       const char *physname = dwarf2_physname (fieldname, die, cu);
15457       fnp->physname = physname ? physname : "";
15458     }
15459
15460   fnp->type = alloc_type (objfile);
15461   this_type = read_type_die (die, cu);
15462   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15463     {
15464       int nparams = TYPE_NFIELDS (this_type);
15465
15466       /* TYPE is the domain of this method, and THIS_TYPE is the type
15467            of the method itself (TYPE_CODE_METHOD).  */
15468       smash_to_method_type (fnp->type, type,
15469                             TYPE_TARGET_TYPE (this_type),
15470                             TYPE_FIELDS (this_type),
15471                             TYPE_NFIELDS (this_type),
15472                             TYPE_VARARGS (this_type));
15473
15474       /* Handle static member functions.
15475          Dwarf2 has no clean way to discern C++ static and non-static
15476          member functions.  G++ helps GDB by marking the first
15477          parameter for non-static member functions (which is the this
15478          pointer) as artificial.  We obtain this information from
15479          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15480       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15481         fnp->voffset = VOFFSET_STATIC;
15482     }
15483   else
15484     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15485                dwarf2_full_name (fieldname, die, cu));
15486
15487   /* Get fcontext from DW_AT_containing_type if present.  */
15488   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15489     fnp->fcontext = die_containing_type (die, cu);
15490
15491   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15492      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15493
15494   /* Get accessibility.  */
15495   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15496   if (attr)
15497     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15498   else
15499     accessibility = dwarf2_default_access_attribute (die, cu);
15500   switch (accessibility)
15501     {
15502     case DW_ACCESS_private:
15503       fnp->is_private = 1;
15504       break;
15505     case DW_ACCESS_protected:
15506       fnp->is_protected = 1;
15507       break;
15508     }
15509
15510   /* Check for artificial methods.  */
15511   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15512   if (attr && DW_UNSND (attr) != 0)
15513     fnp->is_artificial = 1;
15514
15515   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15516
15517   /* Get index in virtual function table if it is a virtual member
15518      function.  For older versions of GCC, this is an offset in the
15519      appropriate virtual table, as specified by DW_AT_containing_type.
15520      For everyone else, it is an expression to be evaluated relative
15521      to the object address.  */
15522
15523   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15524   if (attr)
15525     {
15526       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15527         {
15528           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15529             {
15530               /* Old-style GCC.  */
15531               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15532             }
15533           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15534                    || (DW_BLOCK (attr)->size > 1
15535                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15536                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15537             {
15538               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15539               if ((fnp->voffset % cu->header.addr_size) != 0)
15540                 dwarf2_complex_location_expr_complaint ();
15541               else
15542                 fnp->voffset /= cu->header.addr_size;
15543               fnp->voffset += 2;
15544             }
15545           else
15546             dwarf2_complex_location_expr_complaint ();
15547
15548           if (!fnp->fcontext)
15549             {
15550               /* If there is no `this' field and no DW_AT_containing_type,
15551                  we cannot actually find a base class context for the
15552                  vtable!  */
15553               if (TYPE_NFIELDS (this_type) == 0
15554                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15555                 {
15556                   complaint (&symfile_complaints,
15557                              _("cannot determine context for virtual member "
15558                                "function \"%s\" (offset %d)"),
15559                              fieldname, to_underlying (die->sect_off));
15560                 }
15561               else
15562                 {
15563                   fnp->fcontext
15564                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15565                 }
15566             }
15567         }
15568       else if (attr_form_is_section_offset (attr))
15569         {
15570           dwarf2_complex_location_expr_complaint ();
15571         }
15572       else
15573         {
15574           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15575                                                  fieldname);
15576         }
15577     }
15578   else
15579     {
15580       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15581       if (attr && DW_UNSND (attr))
15582         {
15583           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15584           complaint (&symfile_complaints,
15585                      _("Member function \"%s\" (offset %d) is virtual "
15586                        "but the vtable offset is not specified"),
15587                      fieldname, to_underlying (die->sect_off));
15588           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15589           TYPE_CPLUS_DYNAMIC (type) = 1;
15590         }
15591     }
15592 }
15593
15594 /* Create the vector of member function fields, and attach it to the type.  */
15595
15596 static void
15597 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15598                                  struct dwarf2_cu *cu)
15599 {
15600   struct fnfieldlist *flp;
15601   int i;
15602
15603   if (cu->language == language_ada)
15604     error (_("unexpected member functions in Ada type"));
15605
15606   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15607   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15608     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15609
15610   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15611     {
15612       struct nextfnfield *nfp = flp->head;
15613       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15614       int k;
15615
15616       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15617       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15618       fn_flp->fn_fields = (struct fn_field *)
15619         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15620       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15621         fn_flp->fn_fields[k] = nfp->fnfield;
15622     }
15623
15624   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15625 }
15626
15627 /* Returns non-zero if NAME is the name of a vtable member in CU's
15628    language, zero otherwise.  */
15629 static int
15630 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15631 {
15632   static const char vptr[] = "_vptr";
15633
15634   /* Look for the C++ form of the vtable.  */
15635   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15636     return 1;
15637
15638   return 0;
15639 }
15640
15641 /* GCC outputs unnamed structures that are really pointers to member
15642    functions, with the ABI-specified layout.  If TYPE describes
15643    such a structure, smash it into a member function type.
15644
15645    GCC shouldn't do this; it should just output pointer to member DIEs.
15646    This is GCC PR debug/28767.  */
15647
15648 static void
15649 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15650 {
15651   struct type *pfn_type, *self_type, *new_type;
15652
15653   /* Check for a structure with no name and two children.  */
15654   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15655     return;
15656
15657   /* Check for __pfn and __delta members.  */
15658   if (TYPE_FIELD_NAME (type, 0) == NULL
15659       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15660       || TYPE_FIELD_NAME (type, 1) == NULL
15661       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15662     return;
15663
15664   /* Find the type of the method.  */
15665   pfn_type = TYPE_FIELD_TYPE (type, 0);
15666   if (pfn_type == NULL
15667       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15668       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15669     return;
15670
15671   /* Look for the "this" argument.  */
15672   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15673   if (TYPE_NFIELDS (pfn_type) == 0
15674       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15675       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15676     return;
15677
15678   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15679   new_type = alloc_type (objfile);
15680   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15681                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15682                         TYPE_VARARGS (pfn_type));
15683   smash_to_methodptr_type (type, new_type);
15684 }
15685
15686
15687 /* Called when we find the DIE that starts a structure or union scope
15688    (definition) to create a type for the structure or union.  Fill in
15689    the type's name and general properties; the members will not be
15690    processed until process_structure_scope.  A symbol table entry for
15691    the type will also not be done until process_structure_scope (assuming
15692    the type has a name).
15693
15694    NOTE: we need to call these functions regardless of whether or not the
15695    DIE has a DW_AT_name attribute, since it might be an anonymous
15696    structure or union.  This gets the type entered into our set of
15697    user defined types.  */
15698
15699 static struct type *
15700 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15701 {
15702   struct objfile *objfile = cu->objfile;
15703   struct type *type;
15704   struct attribute *attr;
15705   const char *name;
15706
15707   /* If the definition of this type lives in .debug_types, read that type.
15708      Don't follow DW_AT_specification though, that will take us back up
15709      the chain and we want to go down.  */
15710   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15711   if (attr)
15712     {
15713       type = get_DW_AT_signature_type (die, attr, cu);
15714
15715       /* The type's CU may not be the same as CU.
15716          Ensure TYPE is recorded with CU in die_type_hash.  */
15717       return set_die_type (die, type, cu);
15718     }
15719
15720   type = alloc_type (objfile);
15721   INIT_CPLUS_SPECIFIC (type);
15722
15723   name = dwarf2_name (die, cu);
15724   if (name != NULL)
15725     {
15726       if (cu->language == language_cplus
15727           || cu->language == language_d
15728           || cu->language == language_rust)
15729         {
15730           const char *full_name = dwarf2_full_name (name, die, cu);
15731
15732           /* dwarf2_full_name might have already finished building the DIE's
15733              type.  If so, there is no need to continue.  */
15734           if (get_die_type (die, cu) != NULL)
15735             return get_die_type (die, cu);
15736
15737           TYPE_TAG_NAME (type) = full_name;
15738           if (die->tag == DW_TAG_structure_type
15739               || die->tag == DW_TAG_class_type)
15740             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15741         }
15742       else
15743         {
15744           /* The name is already allocated along with this objfile, so
15745              we don't need to duplicate it for the type.  */
15746           TYPE_TAG_NAME (type) = name;
15747           if (die->tag == DW_TAG_class_type)
15748             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15749         }
15750     }
15751
15752   if (die->tag == DW_TAG_structure_type)
15753     {
15754       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15755     }
15756   else if (die->tag == DW_TAG_union_type)
15757     {
15758       TYPE_CODE (type) = TYPE_CODE_UNION;
15759     }
15760   else
15761     {
15762       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15763     }
15764
15765   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15766     TYPE_DECLARED_CLASS (type) = 1;
15767
15768   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15769   if (attr)
15770     {
15771       if (attr_form_is_constant (attr))
15772         TYPE_LENGTH (type) = DW_UNSND (attr);
15773       else
15774         {
15775           /* For the moment, dynamic type sizes are not supported
15776              by GDB's struct type.  The actual size is determined
15777              on-demand when resolving the type of a given object,
15778              so set the type's length to zero for now.  Otherwise,
15779              we record an expression as the length, and that expression
15780              could lead to a very large value, which could eventually
15781              lead to us trying to allocate that much memory when creating
15782              a value of that type.  */
15783           TYPE_LENGTH (type) = 0;
15784         }
15785     }
15786   else
15787     {
15788       TYPE_LENGTH (type) = 0;
15789     }
15790
15791   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15792     {
15793       /* ICC<14 does not output the required DW_AT_declaration on
15794          incomplete types, but gives them a size of zero.  */
15795       TYPE_STUB (type) = 1;
15796     }
15797   else
15798     TYPE_STUB_SUPPORTED (type) = 1;
15799
15800   if (die_is_declaration (die, cu))
15801     TYPE_STUB (type) = 1;
15802   else if (attr == NULL && die->child == NULL
15803            && producer_is_realview (cu->producer))
15804     /* RealView does not output the required DW_AT_declaration
15805        on incomplete types.  */
15806     TYPE_STUB (type) = 1;
15807
15808   /* We need to add the type field to the die immediately so we don't
15809      infinitely recurse when dealing with pointers to the structure
15810      type within the structure itself.  */
15811   set_die_type (die, type, cu);
15812
15813   /* set_die_type should be already done.  */
15814   set_descriptive_type (type, die, cu);
15815
15816   return type;
15817 }
15818
15819 /* Finish creating a structure or union type, including filling in
15820    its members and creating a symbol for it.  */
15821
15822 static void
15823 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15824 {
15825   struct objfile *objfile = cu->objfile;
15826   struct die_info *child_die;
15827   struct type *type;
15828
15829   type = get_die_type (die, cu);
15830   if (type == NULL)
15831     type = read_structure_type (die, cu);
15832
15833   if (die->child != NULL && ! die_is_declaration (die, cu))
15834     {
15835       struct field_info fi;
15836       std::vector<struct symbol *> template_args;
15837       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15838
15839       memset (&fi, 0, sizeof (struct field_info));
15840
15841       child_die = die->child;
15842
15843       while (child_die && child_die->tag)
15844         {
15845           if (child_die->tag == DW_TAG_member
15846               || child_die->tag == DW_TAG_variable)
15847             {
15848               /* NOTE: carlton/2002-11-05: A C++ static data member
15849                  should be a DW_TAG_member that is a declaration, but
15850                  all versions of G++ as of this writing (so through at
15851                  least 3.2.1) incorrectly generate DW_TAG_variable
15852                  tags for them instead.  */
15853               dwarf2_add_field (&fi, child_die, cu);
15854             }
15855           else if (child_die->tag == DW_TAG_subprogram)
15856             {
15857               /* Rust doesn't have member functions in the C++ sense.
15858                  However, it does emit ordinary functions as children
15859                  of a struct DIE.  */
15860               if (cu->language == language_rust)
15861                 read_func_scope (child_die, cu);
15862               else
15863                 {
15864                   /* C++ member function.  */
15865                   dwarf2_add_member_fn (&fi, child_die, type, cu);
15866                 }
15867             }
15868           else if (child_die->tag == DW_TAG_inheritance)
15869             {
15870               /* C++ base class field.  */
15871               dwarf2_add_field (&fi, child_die, cu);
15872             }
15873           else if (type_can_define_types (child_die))
15874             dwarf2_add_type_defn (&fi, child_die, cu);
15875           else if (child_die->tag == DW_TAG_template_type_param
15876                    || child_die->tag == DW_TAG_template_value_param)
15877             {
15878               struct symbol *arg = new_symbol (child_die, NULL, cu);
15879
15880               if (arg != NULL)
15881                 template_args.push_back (arg);
15882             }
15883
15884           child_die = sibling_die (child_die);
15885         }
15886
15887       /* Attach template arguments to type.  */
15888       if (!template_args.empty ())
15889         {
15890           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15891           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15892           TYPE_TEMPLATE_ARGUMENTS (type)
15893             = XOBNEWVEC (&objfile->objfile_obstack,
15894                          struct symbol *,
15895                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15896           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15897                   template_args.data (),
15898                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15899                    * sizeof (struct symbol *)));
15900         }
15901
15902       /* Attach fields and member functions to the type.  */
15903       if (fi.nfields)
15904         dwarf2_attach_fields_to_type (&fi, type, cu);
15905       if (fi.nfnfields)
15906         {
15907           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15908
15909           /* Get the type which refers to the base class (possibly this
15910              class itself) which contains the vtable pointer for the current
15911              class from the DW_AT_containing_type attribute.  This use of
15912              DW_AT_containing_type is a GNU extension.  */
15913
15914           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15915             {
15916               struct type *t = die_containing_type (die, cu);
15917
15918               set_type_vptr_basetype (type, t);
15919               if (type == t)
15920                 {
15921                   int i;
15922
15923                   /* Our own class provides vtbl ptr.  */
15924                   for (i = TYPE_NFIELDS (t) - 1;
15925                        i >= TYPE_N_BASECLASSES (t);
15926                        --i)
15927                     {
15928                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15929
15930                       if (is_vtable_name (fieldname, cu))
15931                         {
15932                           set_type_vptr_fieldno (type, i);
15933                           break;
15934                         }
15935                     }
15936
15937                   /* Complain if virtual function table field not found.  */
15938                   if (i < TYPE_N_BASECLASSES (t))
15939                     complaint (&symfile_complaints,
15940                                _("virtual function table pointer "
15941                                  "not found when defining class '%s'"),
15942                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
15943                                "");
15944                 }
15945               else
15946                 {
15947                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15948                 }
15949             }
15950           else if (cu->producer
15951                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15952             {
15953               /* The IBM XLC compiler does not provide direct indication
15954                  of the containing type, but the vtable pointer is
15955                  always named __vfp.  */
15956
15957               int i;
15958
15959               for (i = TYPE_NFIELDS (type) - 1;
15960                    i >= TYPE_N_BASECLASSES (type);
15961                    --i)
15962                 {
15963                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15964                     {
15965                       set_type_vptr_fieldno (type, i);
15966                       set_type_vptr_basetype (type, type);
15967                       break;
15968                     }
15969                 }
15970             }
15971         }
15972
15973       /* Copy fi.typedef_field_list linked list elements content into the
15974          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15975       if (fi.typedef_field_list)
15976         {
15977           int i = fi.typedef_field_list_count;
15978
15979           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15980           TYPE_TYPEDEF_FIELD_ARRAY (type)
15981             = ((struct decl_field *)
15982                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
15983           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
15984
15985           /* Reverse the list order to keep the debug info elements order.  */
15986           while (--i >= 0)
15987             {
15988               struct decl_field *dest, *src;
15989
15990               dest = &TYPE_TYPEDEF_FIELD (type, i);
15991               src = &fi.typedef_field_list->field;
15992               fi.typedef_field_list = fi.typedef_field_list->next;
15993               *dest = *src;
15994             }
15995         }
15996
15997       /* Copy fi.nested_types_list linked list elements content into the
15998          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15999       if (fi.nested_types_list != NULL && cu->language != language_ada)
16000         {
16001           int i = fi.nested_types_list_count;
16002
16003           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16004           TYPE_NESTED_TYPES_ARRAY (type)
16005             = ((struct decl_field *)
16006                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16007           TYPE_NESTED_TYPES_COUNT (type) = i;
16008
16009           /* Reverse the list order to keep the debug info elements order.  */
16010           while (--i >= 0)
16011             {
16012               struct decl_field *dest, *src;
16013
16014               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16015               src = &fi.nested_types_list->field;
16016               fi.nested_types_list = fi.nested_types_list->next;
16017               *dest = *src;
16018             }
16019         }
16020
16021       do_cleanups (back_to);
16022     }
16023
16024   quirk_gcc_member_function_pointer (type, objfile);
16025
16026   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16027      snapshots) has been known to create a die giving a declaration
16028      for a class that has, as a child, a die giving a definition for a
16029      nested class.  So we have to process our children even if the
16030      current die is a declaration.  Normally, of course, a declaration
16031      won't have any children at all.  */
16032
16033   child_die = die->child;
16034
16035   while (child_die != NULL && child_die->tag)
16036     {
16037       if (child_die->tag == DW_TAG_member
16038           || child_die->tag == DW_TAG_variable
16039           || child_die->tag == DW_TAG_inheritance
16040           || child_die->tag == DW_TAG_template_value_param
16041           || child_die->tag == DW_TAG_template_type_param)
16042         {
16043           /* Do nothing.  */
16044         }
16045       else
16046         process_die (child_die, cu);
16047
16048       child_die = sibling_die (child_die);
16049     }
16050
16051   /* Do not consider external references.  According to the DWARF standard,
16052      these DIEs are identified by the fact that they have no byte_size
16053      attribute, and a declaration attribute.  */
16054   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16055       || !die_is_declaration (die, cu))
16056     new_symbol (die, type, cu);
16057 }
16058
16059 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16060    update TYPE using some information only available in DIE's children.  */
16061
16062 static void
16063 update_enumeration_type_from_children (struct die_info *die,
16064                                        struct type *type,
16065                                        struct dwarf2_cu *cu)
16066 {
16067   struct die_info *child_die;
16068   int unsigned_enum = 1;
16069   int flag_enum = 1;
16070   ULONGEST mask = 0;
16071
16072   auto_obstack obstack;
16073
16074   for (child_die = die->child;
16075        child_die != NULL && child_die->tag;
16076        child_die = sibling_die (child_die))
16077     {
16078       struct attribute *attr;
16079       LONGEST value;
16080       const gdb_byte *bytes;
16081       struct dwarf2_locexpr_baton *baton;
16082       const char *name;
16083
16084       if (child_die->tag != DW_TAG_enumerator)
16085         continue;
16086
16087       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16088       if (attr == NULL)
16089         continue;
16090
16091       name = dwarf2_name (child_die, cu);
16092       if (name == NULL)
16093         name = "<anonymous enumerator>";
16094
16095       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16096                                &value, &bytes, &baton);
16097       if (value < 0)
16098         {
16099           unsigned_enum = 0;
16100           flag_enum = 0;
16101         }
16102       else if ((mask & value) != 0)
16103         flag_enum = 0;
16104       else
16105         mask |= value;
16106
16107       /* If we already know that the enum type is neither unsigned, nor
16108          a flag type, no need to look at the rest of the enumerates.  */
16109       if (!unsigned_enum && !flag_enum)
16110         break;
16111     }
16112
16113   if (unsigned_enum)
16114     TYPE_UNSIGNED (type) = 1;
16115   if (flag_enum)
16116     TYPE_FLAG_ENUM (type) = 1;
16117 }
16118
16119 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16120    complete the type's fields yet, or create any symbols.  */
16121
16122 static struct type *
16123 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16124 {
16125   struct objfile *objfile = cu->objfile;
16126   struct type *type;
16127   struct attribute *attr;
16128   const char *name;
16129
16130   /* If the definition of this type lives in .debug_types, read that type.
16131      Don't follow DW_AT_specification though, that will take us back up
16132      the chain and we want to go down.  */
16133   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16134   if (attr)
16135     {
16136       type = get_DW_AT_signature_type (die, attr, cu);
16137
16138       /* The type's CU may not be the same as CU.
16139          Ensure TYPE is recorded with CU in die_type_hash.  */
16140       return set_die_type (die, type, cu);
16141     }
16142
16143   type = alloc_type (objfile);
16144
16145   TYPE_CODE (type) = TYPE_CODE_ENUM;
16146   name = dwarf2_full_name (NULL, die, cu);
16147   if (name != NULL)
16148     TYPE_TAG_NAME (type) = name;
16149
16150   attr = dwarf2_attr (die, DW_AT_type, cu);
16151   if (attr != NULL)
16152     {
16153       struct type *underlying_type = die_type (die, cu);
16154
16155       TYPE_TARGET_TYPE (type) = underlying_type;
16156     }
16157
16158   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16159   if (attr)
16160     {
16161       TYPE_LENGTH (type) = DW_UNSND (attr);
16162     }
16163   else
16164     {
16165       TYPE_LENGTH (type) = 0;
16166     }
16167
16168   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16169      declared as private in the package spec, and then defined only
16170      inside the package body.  Such types are known as Taft Amendment
16171      Types.  When another package uses such a type, an incomplete DIE
16172      may be generated by the compiler.  */
16173   if (die_is_declaration (die, cu))
16174     TYPE_STUB (type) = 1;
16175
16176   /* Finish the creation of this type by using the enum's children.
16177      We must call this even when the underlying type has been provided
16178      so that we can determine if we're looking at a "flag" enum.  */
16179   update_enumeration_type_from_children (die, type, cu);
16180
16181   /* If this type has an underlying type that is not a stub, then we
16182      may use its attributes.  We always use the "unsigned" attribute
16183      in this situation, because ordinarily we guess whether the type
16184      is unsigned -- but the guess can be wrong and the underlying type
16185      can tell us the reality.  However, we defer to a local size
16186      attribute if one exists, because this lets the compiler override
16187      the underlying type if needed.  */
16188   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16189     {
16190       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16191       if (TYPE_LENGTH (type) == 0)
16192         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16193     }
16194
16195   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16196
16197   return set_die_type (die, type, cu);
16198 }
16199
16200 /* Given a pointer to a die which begins an enumeration, process all
16201    the dies that define the members of the enumeration, and create the
16202    symbol for the enumeration type.
16203
16204    NOTE: We reverse the order of the element list.  */
16205
16206 static void
16207 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16208 {
16209   struct type *this_type;
16210
16211   this_type = get_die_type (die, cu);
16212   if (this_type == NULL)
16213     this_type = read_enumeration_type (die, cu);
16214
16215   if (die->child != NULL)
16216     {
16217       struct die_info *child_die;
16218       struct symbol *sym;
16219       struct field *fields = NULL;
16220       int num_fields = 0;
16221       const char *name;
16222
16223       child_die = die->child;
16224       while (child_die && child_die->tag)
16225         {
16226           if (child_die->tag != DW_TAG_enumerator)
16227             {
16228               process_die (child_die, cu);
16229             }
16230           else
16231             {
16232               name = dwarf2_name (child_die, cu);
16233               if (name)
16234                 {
16235                   sym = new_symbol (child_die, this_type, cu);
16236
16237                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16238                     {
16239                       fields = (struct field *)
16240                         xrealloc (fields,
16241                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16242                                   * sizeof (struct field));
16243                     }
16244
16245                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16246                   FIELD_TYPE (fields[num_fields]) = NULL;
16247                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16248                   FIELD_BITSIZE (fields[num_fields]) = 0;
16249
16250                   num_fields++;
16251                 }
16252             }
16253
16254           child_die = sibling_die (child_die);
16255         }
16256
16257       if (num_fields)
16258         {
16259           TYPE_NFIELDS (this_type) = num_fields;
16260           TYPE_FIELDS (this_type) = (struct field *)
16261             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16262           memcpy (TYPE_FIELDS (this_type), fields,
16263                   sizeof (struct field) * num_fields);
16264           xfree (fields);
16265         }
16266     }
16267
16268   /* If we are reading an enum from a .debug_types unit, and the enum
16269      is a declaration, and the enum is not the signatured type in the
16270      unit, then we do not want to add a symbol for it.  Adding a
16271      symbol would in some cases obscure the true definition of the
16272      enum, giving users an incomplete type when the definition is
16273      actually available.  Note that we do not want to do this for all
16274      enums which are just declarations, because C++0x allows forward
16275      enum declarations.  */
16276   if (cu->per_cu->is_debug_types
16277       && die_is_declaration (die, cu))
16278     {
16279       struct signatured_type *sig_type;
16280
16281       sig_type = (struct signatured_type *) cu->per_cu;
16282       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16283       if (sig_type->type_offset_in_section != die->sect_off)
16284         return;
16285     }
16286
16287   new_symbol (die, this_type, cu);
16288 }
16289
16290 /* Extract all information from a DW_TAG_array_type DIE and put it in
16291    the DIE's type field.  For now, this only handles one dimensional
16292    arrays.  */
16293
16294 static struct type *
16295 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16296 {
16297   struct objfile *objfile = cu->objfile;
16298   struct die_info *child_die;
16299   struct type *type;
16300   struct type *element_type, *range_type, *index_type;
16301   struct attribute *attr;
16302   const char *name;
16303   unsigned int bit_stride = 0;
16304
16305   element_type = die_type (die, cu);
16306
16307   /* The die_type call above may have already set the type for this DIE.  */
16308   type = get_die_type (die, cu);
16309   if (type)
16310     return type;
16311
16312   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16313   if (attr != NULL)
16314     bit_stride = DW_UNSND (attr) * 8;
16315
16316   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16317   if (attr != NULL)
16318     bit_stride = DW_UNSND (attr);
16319
16320   /* Irix 6.2 native cc creates array types without children for
16321      arrays with unspecified length.  */
16322   if (die->child == NULL)
16323     {
16324       index_type = objfile_type (objfile)->builtin_int;
16325       range_type = create_static_range_type (NULL, index_type, 0, -1);
16326       type = create_array_type_with_stride (NULL, element_type, range_type,
16327                                             bit_stride);
16328       return set_die_type (die, type, cu);
16329     }
16330
16331   std::vector<struct type *> range_types;
16332   child_die = die->child;
16333   while (child_die && child_die->tag)
16334     {
16335       if (child_die->tag == DW_TAG_subrange_type)
16336         {
16337           struct type *child_type = read_type_die (child_die, cu);
16338
16339           if (child_type != NULL)
16340             {
16341               /* The range type was succesfully read.  Save it for the
16342                  array type creation.  */
16343               range_types.push_back (child_type);
16344             }
16345         }
16346       child_die = sibling_die (child_die);
16347     }
16348
16349   /* Dwarf2 dimensions are output from left to right, create the
16350      necessary array types in backwards order.  */
16351
16352   type = element_type;
16353
16354   if (read_array_order (die, cu) == DW_ORD_col_major)
16355     {
16356       int i = 0;
16357
16358       while (i < range_types.size ())
16359         type = create_array_type_with_stride (NULL, type, range_types[i++],
16360                                               bit_stride);
16361     }
16362   else
16363     {
16364       size_t ndim = range_types.size ();
16365       while (ndim-- > 0)
16366         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16367                                               bit_stride);
16368     }
16369
16370   /* Understand Dwarf2 support for vector types (like they occur on
16371      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16372      array type.  This is not part of the Dwarf2/3 standard yet, but a
16373      custom vendor extension.  The main difference between a regular
16374      array and the vector variant is that vectors are passed by value
16375      to functions.  */
16376   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16377   if (attr)
16378     make_vector_type (type);
16379
16380   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16381      implementation may choose to implement triple vectors using this
16382      attribute.  */
16383   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16384   if (attr)
16385     {
16386       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16387         TYPE_LENGTH (type) = DW_UNSND (attr);
16388       else
16389         complaint (&symfile_complaints,
16390                    _("DW_AT_byte_size for array type smaller "
16391                      "than the total size of elements"));
16392     }
16393
16394   name = dwarf2_name (die, cu);
16395   if (name)
16396     TYPE_NAME (type) = name;
16397
16398   /* Install the type in the die.  */
16399   set_die_type (die, type, cu);
16400
16401   /* set_die_type should be already done.  */
16402   set_descriptive_type (type, die, cu);
16403
16404   return type;
16405 }
16406
16407 static enum dwarf_array_dim_ordering
16408 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16409 {
16410   struct attribute *attr;
16411
16412   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16413
16414   if (attr)
16415     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16416
16417   /* GNU F77 is a special case, as at 08/2004 array type info is the
16418      opposite order to the dwarf2 specification, but data is still
16419      laid out as per normal fortran.
16420
16421      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16422      version checking.  */
16423
16424   if (cu->language == language_fortran
16425       && cu->producer && strstr (cu->producer, "GNU F77"))
16426     {
16427       return DW_ORD_row_major;
16428     }
16429
16430   switch (cu->language_defn->la_array_ordering)
16431     {
16432     case array_column_major:
16433       return DW_ORD_col_major;
16434     case array_row_major:
16435     default:
16436       return DW_ORD_row_major;
16437     };
16438 }
16439
16440 /* Extract all information from a DW_TAG_set_type DIE and put it in
16441    the DIE's type field.  */
16442
16443 static struct type *
16444 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16445 {
16446   struct type *domain_type, *set_type;
16447   struct attribute *attr;
16448
16449   domain_type = die_type (die, cu);
16450
16451   /* The die_type call above may have already set the type for this DIE.  */
16452   set_type = get_die_type (die, cu);
16453   if (set_type)
16454     return set_type;
16455
16456   set_type = create_set_type (NULL, domain_type);
16457
16458   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16459   if (attr)
16460     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16461
16462   return set_die_type (die, set_type, cu);
16463 }
16464
16465 /* A helper for read_common_block that creates a locexpr baton.
16466    SYM is the symbol which we are marking as computed.
16467    COMMON_DIE is the DIE for the common block.
16468    COMMON_LOC is the location expression attribute for the common
16469    block itself.
16470    MEMBER_LOC is the location expression attribute for the particular
16471    member of the common block that we are processing.
16472    CU is the CU from which the above come.  */
16473
16474 static void
16475 mark_common_block_symbol_computed (struct symbol *sym,
16476                                    struct die_info *common_die,
16477                                    struct attribute *common_loc,
16478                                    struct attribute *member_loc,
16479                                    struct dwarf2_cu *cu)
16480 {
16481   struct objfile *objfile = dwarf2_per_objfile->objfile;
16482   struct dwarf2_locexpr_baton *baton;
16483   gdb_byte *ptr;
16484   unsigned int cu_off;
16485   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16486   LONGEST offset = 0;
16487
16488   gdb_assert (common_loc && member_loc);
16489   gdb_assert (attr_form_is_block (common_loc));
16490   gdb_assert (attr_form_is_block (member_loc)
16491               || attr_form_is_constant (member_loc));
16492
16493   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16494   baton->per_cu = cu->per_cu;
16495   gdb_assert (baton->per_cu);
16496
16497   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16498
16499   if (attr_form_is_constant (member_loc))
16500     {
16501       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16502       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16503     }
16504   else
16505     baton->size += DW_BLOCK (member_loc)->size;
16506
16507   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16508   baton->data = ptr;
16509
16510   *ptr++ = DW_OP_call4;
16511   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16512   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16513   ptr += 4;
16514
16515   if (attr_form_is_constant (member_loc))
16516     {
16517       *ptr++ = DW_OP_addr;
16518       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16519       ptr += cu->header.addr_size;
16520     }
16521   else
16522     {
16523       /* We have to copy the data here, because DW_OP_call4 will only
16524          use a DW_AT_location attribute.  */
16525       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16526       ptr += DW_BLOCK (member_loc)->size;
16527     }
16528
16529   *ptr++ = DW_OP_plus;
16530   gdb_assert (ptr - baton->data == baton->size);
16531
16532   SYMBOL_LOCATION_BATON (sym) = baton;
16533   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16534 }
16535
16536 /* Create appropriate locally-scoped variables for all the
16537    DW_TAG_common_block entries.  Also create a struct common_block
16538    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16539    is used to sepate the common blocks name namespace from regular
16540    variable names.  */
16541
16542 static void
16543 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16544 {
16545   struct attribute *attr;
16546
16547   attr = dwarf2_attr (die, DW_AT_location, cu);
16548   if (attr)
16549     {
16550       /* Support the .debug_loc offsets.  */
16551       if (attr_form_is_block (attr))
16552         {
16553           /* Ok.  */
16554         }
16555       else if (attr_form_is_section_offset (attr))
16556         {
16557           dwarf2_complex_location_expr_complaint ();
16558           attr = NULL;
16559         }
16560       else
16561         {
16562           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16563                                                  "common block member");
16564           attr = NULL;
16565         }
16566     }
16567
16568   if (die->child != NULL)
16569     {
16570       struct objfile *objfile = cu->objfile;
16571       struct die_info *child_die;
16572       size_t n_entries = 0, size;
16573       struct common_block *common_block;
16574       struct symbol *sym;
16575
16576       for (child_die = die->child;
16577            child_die && child_die->tag;
16578            child_die = sibling_die (child_die))
16579         ++n_entries;
16580
16581       size = (sizeof (struct common_block)
16582               + (n_entries - 1) * sizeof (struct symbol *));
16583       common_block
16584         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16585                                                  size);
16586       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16587       common_block->n_entries = 0;
16588
16589       for (child_die = die->child;
16590            child_die && child_die->tag;
16591            child_die = sibling_die (child_die))
16592         {
16593           /* Create the symbol in the DW_TAG_common_block block in the current
16594              symbol scope.  */
16595           sym = new_symbol (child_die, NULL, cu);
16596           if (sym != NULL)
16597             {
16598               struct attribute *member_loc;
16599
16600               common_block->contents[common_block->n_entries++] = sym;
16601
16602               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16603                                         cu);
16604               if (member_loc)
16605                 {
16606                   /* GDB has handled this for a long time, but it is
16607                      not specified by DWARF.  It seems to have been
16608                      emitted by gfortran at least as recently as:
16609                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16610                   complaint (&symfile_complaints,
16611                              _("Variable in common block has "
16612                                "DW_AT_data_member_location "
16613                                "- DIE at 0x%x [in module %s]"),
16614                              to_underlying (child_die->sect_off),
16615                              objfile_name (cu->objfile));
16616
16617                   if (attr_form_is_section_offset (member_loc))
16618                     dwarf2_complex_location_expr_complaint ();
16619                   else if (attr_form_is_constant (member_loc)
16620                            || attr_form_is_block (member_loc))
16621                     {
16622                       if (attr)
16623                         mark_common_block_symbol_computed (sym, die, attr,
16624                                                            member_loc, cu);
16625                     }
16626                   else
16627                     dwarf2_complex_location_expr_complaint ();
16628                 }
16629             }
16630         }
16631
16632       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16633       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16634     }
16635 }
16636
16637 /* Create a type for a C++ namespace.  */
16638
16639 static struct type *
16640 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16641 {
16642   struct objfile *objfile = cu->objfile;
16643   const char *previous_prefix, *name;
16644   int is_anonymous;
16645   struct type *type;
16646
16647   /* For extensions, reuse the type of the original namespace.  */
16648   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16649     {
16650       struct die_info *ext_die;
16651       struct dwarf2_cu *ext_cu = cu;
16652
16653       ext_die = dwarf2_extension (die, &ext_cu);
16654       type = read_type_die (ext_die, ext_cu);
16655
16656       /* EXT_CU may not be the same as CU.
16657          Ensure TYPE is recorded with CU in die_type_hash.  */
16658       return set_die_type (die, type, cu);
16659     }
16660
16661   name = namespace_name (die, &is_anonymous, cu);
16662
16663   /* Now build the name of the current namespace.  */
16664
16665   previous_prefix = determine_prefix (die, cu);
16666   if (previous_prefix[0] != '\0')
16667     name = typename_concat (&objfile->objfile_obstack,
16668                             previous_prefix, name, 0, cu);
16669
16670   /* Create the type.  */
16671   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16672   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16673
16674   return set_die_type (die, type, cu);
16675 }
16676
16677 /* Read a namespace scope.  */
16678
16679 static void
16680 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16681 {
16682   struct objfile *objfile = cu->objfile;
16683   int is_anonymous;
16684
16685   /* Add a symbol associated to this if we haven't seen the namespace
16686      before.  Also, add a using directive if it's an anonymous
16687      namespace.  */
16688
16689   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16690     {
16691       struct type *type;
16692
16693       type = read_type_die (die, cu);
16694       new_symbol (die, type, cu);
16695
16696       namespace_name (die, &is_anonymous, cu);
16697       if (is_anonymous)
16698         {
16699           const char *previous_prefix = determine_prefix (die, cu);
16700
16701           std::vector<const char *> excludes;
16702           add_using_directive (using_directives (cu->language),
16703                                previous_prefix, TYPE_NAME (type), NULL,
16704                                NULL, excludes, 0, &objfile->objfile_obstack);
16705         }
16706     }
16707
16708   if (die->child != NULL)
16709     {
16710       struct die_info *child_die = die->child;
16711
16712       while (child_die && child_die->tag)
16713         {
16714           process_die (child_die, cu);
16715           child_die = sibling_die (child_die);
16716         }
16717     }
16718 }
16719
16720 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16721    imported module.  Still we need that type as local Fortran "use ... only"
16722    declaration imports depend on the created type in determine_prefix.  */
16723
16724 static struct type *
16725 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16726 {
16727   struct objfile *objfile = cu->objfile;
16728   const char *module_name;
16729   struct type *type;
16730
16731   module_name = dwarf2_name (die, cu);
16732   if (!module_name)
16733     complaint (&symfile_complaints,
16734                _("DW_TAG_module has no name, offset 0x%x"),
16735                to_underlying (die->sect_off));
16736   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16737
16738   /* determine_prefix uses TYPE_TAG_NAME.  */
16739   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16740
16741   return set_die_type (die, type, cu);
16742 }
16743
16744 /* Read a Fortran module.  */
16745
16746 static void
16747 read_module (struct die_info *die, struct dwarf2_cu *cu)
16748 {
16749   struct die_info *child_die = die->child;
16750   struct type *type;
16751
16752   type = read_type_die (die, cu);
16753   new_symbol (die, type, cu);
16754
16755   while (child_die && child_die->tag)
16756     {
16757       process_die (child_die, cu);
16758       child_die = sibling_die (child_die);
16759     }
16760 }
16761
16762 /* Return the name of the namespace represented by DIE.  Set
16763    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16764    namespace.  */
16765
16766 static const char *
16767 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16768 {
16769   struct die_info *current_die;
16770   const char *name = NULL;
16771
16772   /* Loop through the extensions until we find a name.  */
16773
16774   for (current_die = die;
16775        current_die != NULL;
16776        current_die = dwarf2_extension (die, &cu))
16777     {
16778       /* We don't use dwarf2_name here so that we can detect the absence
16779          of a name -> anonymous namespace.  */
16780       name = dwarf2_string_attr (die, DW_AT_name, cu);
16781
16782       if (name != NULL)
16783         break;
16784     }
16785
16786   /* Is it an anonymous namespace?  */
16787
16788   *is_anonymous = (name == NULL);
16789   if (*is_anonymous)
16790     name = CP_ANONYMOUS_NAMESPACE_STR;
16791
16792   return name;
16793 }
16794
16795 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16796    the user defined type vector.  */
16797
16798 static struct type *
16799 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16800 {
16801   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
16802   struct comp_unit_head *cu_header = &cu->header;
16803   struct type *type;
16804   struct attribute *attr_byte_size;
16805   struct attribute *attr_address_class;
16806   int byte_size, addr_class;
16807   struct type *target_type;
16808
16809   target_type = die_type (die, cu);
16810
16811   /* The die_type call above may have already set the type for this DIE.  */
16812   type = get_die_type (die, cu);
16813   if (type)
16814     return type;
16815
16816   type = lookup_pointer_type (target_type);
16817
16818   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16819   if (attr_byte_size)
16820     byte_size = DW_UNSND (attr_byte_size);
16821   else
16822     byte_size = cu_header->addr_size;
16823
16824   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16825   if (attr_address_class)
16826     addr_class = DW_UNSND (attr_address_class);
16827   else
16828     addr_class = DW_ADDR_none;
16829
16830   /* If the pointer size or address class is different than the
16831      default, create a type variant marked as such and set the
16832      length accordingly.  */
16833   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16834     {
16835       if (gdbarch_address_class_type_flags_p (gdbarch))
16836         {
16837           int type_flags;
16838
16839           type_flags = gdbarch_address_class_type_flags
16840                          (gdbarch, byte_size, addr_class);
16841           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16842                       == 0);
16843           type = make_type_with_address_space (type, type_flags);
16844         }
16845       else if (TYPE_LENGTH (type) != byte_size)
16846         {
16847           complaint (&symfile_complaints,
16848                      _("invalid pointer size %d"), byte_size);
16849         }
16850       else
16851         {
16852           /* Should we also complain about unhandled address classes?  */
16853         }
16854     }
16855
16856   TYPE_LENGTH (type) = byte_size;
16857   return set_die_type (die, type, cu);
16858 }
16859
16860 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16861    the user defined type vector.  */
16862
16863 static struct type *
16864 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16865 {
16866   struct type *type;
16867   struct type *to_type;
16868   struct type *domain;
16869
16870   to_type = die_type (die, cu);
16871   domain = die_containing_type (die, cu);
16872
16873   /* The calls above may have already set the type for this DIE.  */
16874   type = get_die_type (die, cu);
16875   if (type)
16876     return type;
16877
16878   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16879     type = lookup_methodptr_type (to_type);
16880   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16881     {
16882       struct type *new_type = alloc_type (cu->objfile);
16883
16884       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16885                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16886                             TYPE_VARARGS (to_type));
16887       type = lookup_methodptr_type (new_type);
16888     }
16889   else
16890     type = lookup_memberptr_type (to_type, domain);
16891
16892   return set_die_type (die, type, cu);
16893 }
16894
16895 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16896    the user defined type vector.  */
16897
16898 static struct type *
16899 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16900                           enum type_code refcode)
16901 {
16902   struct comp_unit_head *cu_header = &cu->header;
16903   struct type *type, *target_type;
16904   struct attribute *attr;
16905
16906   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16907
16908   target_type = die_type (die, cu);
16909
16910   /* The die_type call above may have already set the type for this DIE.  */
16911   type = get_die_type (die, cu);
16912   if (type)
16913     return type;
16914
16915   type = lookup_reference_type (target_type, refcode);
16916   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16917   if (attr)
16918     {
16919       TYPE_LENGTH (type) = DW_UNSND (attr);
16920     }
16921   else
16922     {
16923       TYPE_LENGTH (type) = cu_header->addr_size;
16924     }
16925   return set_die_type (die, type, cu);
16926 }
16927
16928 /* Add the given cv-qualifiers to the element type of the array.  GCC
16929    outputs DWARF type qualifiers that apply to an array, not the
16930    element type.  But GDB relies on the array element type to carry
16931    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16932    specification.  */
16933
16934 static struct type *
16935 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16936                    struct type *base_type, int cnst, int voltl)
16937 {
16938   struct type *el_type, *inner_array;
16939
16940   base_type = copy_type (base_type);
16941   inner_array = base_type;
16942
16943   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16944     {
16945       TYPE_TARGET_TYPE (inner_array) =
16946         copy_type (TYPE_TARGET_TYPE (inner_array));
16947       inner_array = TYPE_TARGET_TYPE (inner_array);
16948     }
16949
16950   el_type = TYPE_TARGET_TYPE (inner_array);
16951   cnst |= TYPE_CONST (el_type);
16952   voltl |= TYPE_VOLATILE (el_type);
16953   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16954
16955   return set_die_type (die, base_type, cu);
16956 }
16957
16958 static struct type *
16959 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16960 {
16961   struct type *base_type, *cv_type;
16962
16963   base_type = die_type (die, cu);
16964
16965   /* The die_type call above may have already set the type for this DIE.  */
16966   cv_type = get_die_type (die, cu);
16967   if (cv_type)
16968     return cv_type;
16969
16970   /* In case the const qualifier is applied to an array type, the element type
16971      is so qualified, not the array type (section 6.7.3 of C99).  */
16972   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16973     return add_array_cv_type (die, cu, base_type, 1, 0);
16974
16975   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16976   return set_die_type (die, cv_type, cu);
16977 }
16978
16979 static struct type *
16980 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16981 {
16982   struct type *base_type, *cv_type;
16983
16984   base_type = die_type (die, cu);
16985
16986   /* The die_type call above may have already set the type for this DIE.  */
16987   cv_type = get_die_type (die, cu);
16988   if (cv_type)
16989     return cv_type;
16990
16991   /* In case the volatile qualifier is applied to an array type, the
16992      element type is so qualified, not the array type (section 6.7.3
16993      of C99).  */
16994   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16995     return add_array_cv_type (die, cu, base_type, 0, 1);
16996
16997   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
16998   return set_die_type (die, cv_type, cu);
16999 }
17000
17001 /* Handle DW_TAG_restrict_type.  */
17002
17003 static struct type *
17004 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17005 {
17006   struct type *base_type, *cv_type;
17007
17008   base_type = die_type (die, cu);
17009
17010   /* The die_type call above may have already set the type for this DIE.  */
17011   cv_type = get_die_type (die, cu);
17012   if (cv_type)
17013     return cv_type;
17014
17015   cv_type = make_restrict_type (base_type);
17016   return set_die_type (die, cv_type, cu);
17017 }
17018
17019 /* Handle DW_TAG_atomic_type.  */
17020
17021 static struct type *
17022 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17023 {
17024   struct type *base_type, *cv_type;
17025
17026   base_type = die_type (die, cu);
17027
17028   /* The die_type call above may have already set the type for this DIE.  */
17029   cv_type = get_die_type (die, cu);
17030   if (cv_type)
17031     return cv_type;
17032
17033   cv_type = make_atomic_type (base_type);
17034   return set_die_type (die, cv_type, cu);
17035 }
17036
17037 /* Extract all information from a DW_TAG_string_type DIE and add to
17038    the user defined type vector.  It isn't really a user defined type,
17039    but it behaves like one, with other DIE's using an AT_user_def_type
17040    attribute to reference it.  */
17041
17042 static struct type *
17043 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17044 {
17045   struct objfile *objfile = cu->objfile;
17046   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17047   struct type *type, *range_type, *index_type, *char_type;
17048   struct attribute *attr;
17049   unsigned int length;
17050
17051   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17052   if (attr)
17053     {
17054       length = DW_UNSND (attr);
17055     }
17056   else
17057     {
17058       /* Check for the DW_AT_byte_size attribute.  */
17059       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17060       if (attr)
17061         {
17062           length = DW_UNSND (attr);
17063         }
17064       else
17065         {
17066           length = 1;
17067         }
17068     }
17069
17070   index_type = objfile_type (objfile)->builtin_int;
17071   range_type = create_static_range_type (NULL, index_type, 1, length);
17072   char_type = language_string_char_type (cu->language_defn, gdbarch);
17073   type = create_string_type (NULL, char_type, range_type);
17074
17075   return set_die_type (die, type, cu);
17076 }
17077
17078 /* Assuming that DIE corresponds to a function, returns nonzero
17079    if the function is prototyped.  */
17080
17081 static int
17082 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17083 {
17084   struct attribute *attr;
17085
17086   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17087   if (attr && (DW_UNSND (attr) != 0))
17088     return 1;
17089
17090   /* The DWARF standard implies that the DW_AT_prototyped attribute
17091      is only meaninful for C, but the concept also extends to other
17092      languages that allow unprototyped functions (Eg: Objective C).
17093      For all other languages, assume that functions are always
17094      prototyped.  */
17095   if (cu->language != language_c
17096       && cu->language != language_objc
17097       && cu->language != language_opencl)
17098     return 1;
17099
17100   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17101      prototyped and unprototyped functions; default to prototyped,
17102      since that is more common in modern code (and RealView warns
17103      about unprototyped functions).  */
17104   if (producer_is_realview (cu->producer))
17105     return 1;
17106
17107   return 0;
17108 }
17109
17110 /* Handle DIES due to C code like:
17111
17112    struct foo
17113    {
17114    int (*funcp)(int a, long l);
17115    int b;
17116    };
17117
17118    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17119
17120 static struct type *
17121 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17122 {
17123   struct objfile *objfile = cu->objfile;
17124   struct type *type;            /* Type that this function returns.  */
17125   struct type *ftype;           /* Function that returns above type.  */
17126   struct attribute *attr;
17127
17128   type = die_type (die, cu);
17129
17130   /* The die_type call above may have already set the type for this DIE.  */
17131   ftype = get_die_type (die, cu);
17132   if (ftype)
17133     return ftype;
17134
17135   ftype = lookup_function_type (type);
17136
17137   if (prototyped_function_p (die, cu))
17138     TYPE_PROTOTYPED (ftype) = 1;
17139
17140   /* Store the calling convention in the type if it's available in
17141      the subroutine die.  Otherwise set the calling convention to
17142      the default value DW_CC_normal.  */
17143   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17144   if (attr)
17145     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17146   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17147     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17148   else
17149     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17150
17151   /* Record whether the function returns normally to its caller or not
17152      if the DWARF producer set that information.  */
17153   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17154   if (attr && (DW_UNSND (attr) != 0))
17155     TYPE_NO_RETURN (ftype) = 1;
17156
17157   /* We need to add the subroutine type to the die immediately so
17158      we don't infinitely recurse when dealing with parameters
17159      declared as the same subroutine type.  */
17160   set_die_type (die, ftype, cu);
17161
17162   if (die->child != NULL)
17163     {
17164       struct type *void_type = objfile_type (objfile)->builtin_void;
17165       struct die_info *child_die;
17166       int nparams, iparams;
17167
17168       /* Count the number of parameters.
17169          FIXME: GDB currently ignores vararg functions, but knows about
17170          vararg member functions.  */
17171       nparams = 0;
17172       child_die = die->child;
17173       while (child_die && child_die->tag)
17174         {
17175           if (child_die->tag == DW_TAG_formal_parameter)
17176             nparams++;
17177           else if (child_die->tag == DW_TAG_unspecified_parameters)
17178             TYPE_VARARGS (ftype) = 1;
17179           child_die = sibling_die (child_die);
17180         }
17181
17182       /* Allocate storage for parameters and fill them in.  */
17183       TYPE_NFIELDS (ftype) = nparams;
17184       TYPE_FIELDS (ftype) = (struct field *)
17185         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17186
17187       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17188          even if we error out during the parameters reading below.  */
17189       for (iparams = 0; iparams < nparams; iparams++)
17190         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17191
17192       iparams = 0;
17193       child_die = die->child;
17194       while (child_die && child_die->tag)
17195         {
17196           if (child_die->tag == DW_TAG_formal_parameter)
17197             {
17198               struct type *arg_type;
17199
17200               /* DWARF version 2 has no clean way to discern C++
17201                  static and non-static member functions.  G++ helps
17202                  GDB by marking the first parameter for non-static
17203                  member functions (which is the this pointer) as
17204                  artificial.  We pass this information to
17205                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17206
17207                  DWARF version 3 added DW_AT_object_pointer, which GCC
17208                  4.5 does not yet generate.  */
17209               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17210               if (attr)
17211                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17212               else
17213                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17214               arg_type = die_type (child_die, cu);
17215
17216               /* RealView does not mark THIS as const, which the testsuite
17217                  expects.  GCC marks THIS as const in method definitions,
17218                  but not in the class specifications (GCC PR 43053).  */
17219               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17220                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17221                 {
17222                   int is_this = 0;
17223                   struct dwarf2_cu *arg_cu = cu;
17224                   const char *name = dwarf2_name (child_die, cu);
17225
17226                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17227                   if (attr)
17228                     {
17229                       /* If the compiler emits this, use it.  */
17230                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17231                         is_this = 1;
17232                     }
17233                   else if (name && strcmp (name, "this") == 0)
17234                     /* Function definitions will have the argument names.  */
17235                     is_this = 1;
17236                   else if (name == NULL && iparams == 0)
17237                     /* Declarations may not have the names, so like
17238                        elsewhere in GDB, assume an artificial first
17239                        argument is "this".  */
17240                     is_this = 1;
17241
17242                   if (is_this)
17243                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17244                                              arg_type, 0);
17245                 }
17246
17247               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17248               iparams++;
17249             }
17250           child_die = sibling_die (child_die);
17251         }
17252     }
17253
17254   return ftype;
17255 }
17256
17257 static struct type *
17258 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17259 {
17260   struct objfile *objfile = cu->objfile;
17261   const char *name = NULL;
17262   struct type *this_type, *target_type;
17263
17264   name = dwarf2_full_name (NULL, die, cu);
17265   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17266   TYPE_TARGET_STUB (this_type) = 1;
17267   set_die_type (die, this_type, cu);
17268   target_type = die_type (die, cu);
17269   if (target_type != this_type)
17270     TYPE_TARGET_TYPE (this_type) = target_type;
17271   else
17272     {
17273       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17274          spec and cause infinite loops in GDB.  */
17275       complaint (&symfile_complaints,
17276                  _("Self-referential DW_TAG_typedef "
17277                    "- DIE at 0x%x [in module %s]"),
17278                  to_underlying (die->sect_off), objfile_name (objfile));
17279       TYPE_TARGET_TYPE (this_type) = NULL;
17280     }
17281   return this_type;
17282 }
17283
17284 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17285    (which may be different from NAME) to the architecture back-end to allow
17286    it to guess the correct format if necessary.  */
17287
17288 static struct type *
17289 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17290                         const char *name_hint)
17291 {
17292   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17293   const struct floatformat **format;
17294   struct type *type;
17295
17296   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17297   if (format)
17298     type = init_float_type (objfile, bits, name, format);
17299   else
17300     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17301
17302   return type;
17303 }
17304
17305 /* Find a representation of a given base type and install
17306    it in the TYPE field of the die.  */
17307
17308 static struct type *
17309 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17310 {
17311   struct objfile *objfile = cu->objfile;
17312   struct type *type;
17313   struct attribute *attr;
17314   int encoding = 0, bits = 0;
17315   const char *name;
17316
17317   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17318   if (attr)
17319     {
17320       encoding = DW_UNSND (attr);
17321     }
17322   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17323   if (attr)
17324     {
17325       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17326     }
17327   name = dwarf2_name (die, cu);
17328   if (!name)
17329     {
17330       complaint (&symfile_complaints,
17331                  _("DW_AT_name missing from DW_TAG_base_type"));
17332     }
17333
17334   switch (encoding)
17335     {
17336       case DW_ATE_address:
17337         /* Turn DW_ATE_address into a void * pointer.  */
17338         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17339         type = init_pointer_type (objfile, bits, name, type);
17340         break;
17341       case DW_ATE_boolean:
17342         type = init_boolean_type (objfile, bits, 1, name);
17343         break;
17344       case DW_ATE_complex_float:
17345         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17346         type = init_complex_type (objfile, name, type);
17347         break;
17348       case DW_ATE_decimal_float:
17349         type = init_decfloat_type (objfile, bits, name);
17350         break;
17351       case DW_ATE_float:
17352         type = dwarf2_init_float_type (objfile, bits, name, name);
17353         break;
17354       case DW_ATE_signed:
17355         type = init_integer_type (objfile, bits, 0, name);
17356         break;
17357       case DW_ATE_unsigned:
17358         if (cu->language == language_fortran
17359             && name
17360             && startswith (name, "character("))
17361           type = init_character_type (objfile, bits, 1, name);
17362         else
17363           type = init_integer_type (objfile, bits, 1, name);
17364         break;
17365       case DW_ATE_signed_char:
17366         if (cu->language == language_ada || cu->language == language_m2
17367             || cu->language == language_pascal
17368             || cu->language == language_fortran)
17369           type = init_character_type (objfile, bits, 0, name);
17370         else
17371           type = init_integer_type (objfile, bits, 0, name);
17372         break;
17373       case DW_ATE_unsigned_char:
17374         if (cu->language == language_ada || cu->language == language_m2
17375             || cu->language == language_pascal
17376             || cu->language == language_fortran
17377             || cu->language == language_rust)
17378           type = init_character_type (objfile, bits, 1, name);
17379         else
17380           type = init_integer_type (objfile, bits, 1, name);
17381         break;
17382       case DW_ATE_UTF:
17383         {
17384           gdbarch *arch = get_objfile_arch (objfile);
17385
17386           if (bits == 16)
17387             type = builtin_type (arch)->builtin_char16;
17388           else if (bits == 32)
17389             type = builtin_type (arch)->builtin_char32;
17390           else
17391             {
17392               complaint (&symfile_complaints,
17393                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17394                          bits);
17395               type = init_integer_type (objfile, bits, 1, name);
17396             }
17397           return set_die_type (die, type, cu);
17398         }
17399         break;
17400
17401       default:
17402         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17403                    dwarf_type_encoding_name (encoding));
17404         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17405         break;
17406     }
17407
17408   if (name && strcmp (name, "char") == 0)
17409     TYPE_NOSIGN (type) = 1;
17410
17411   return set_die_type (die, type, cu);
17412 }
17413
17414 /* Parse dwarf attribute if it's a block, reference or constant and put the
17415    resulting value of the attribute into struct bound_prop.
17416    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17417
17418 static int
17419 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17420                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17421 {
17422   struct dwarf2_property_baton *baton;
17423   struct obstack *obstack = &cu->objfile->objfile_obstack;
17424
17425   if (attr == NULL || prop == NULL)
17426     return 0;
17427
17428   if (attr_form_is_block (attr))
17429     {
17430       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17431       baton->referenced_type = NULL;
17432       baton->locexpr.per_cu = cu->per_cu;
17433       baton->locexpr.size = DW_BLOCK (attr)->size;
17434       baton->locexpr.data = DW_BLOCK (attr)->data;
17435       prop->data.baton = baton;
17436       prop->kind = PROP_LOCEXPR;
17437       gdb_assert (prop->data.baton != NULL);
17438     }
17439   else if (attr_form_is_ref (attr))
17440     {
17441       struct dwarf2_cu *target_cu = cu;
17442       struct die_info *target_die;
17443       struct attribute *target_attr;
17444
17445       target_die = follow_die_ref (die, attr, &target_cu);
17446       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17447       if (target_attr == NULL)
17448         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17449                                    target_cu);
17450       if (target_attr == NULL)
17451         return 0;
17452
17453       switch (target_attr->name)
17454         {
17455           case DW_AT_location:
17456             if (attr_form_is_section_offset (target_attr))
17457               {
17458                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17459                 baton->referenced_type = die_type (target_die, target_cu);
17460                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17461                 prop->data.baton = baton;
17462                 prop->kind = PROP_LOCLIST;
17463                 gdb_assert (prop->data.baton != NULL);
17464               }
17465             else if (attr_form_is_block (target_attr))
17466               {
17467                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17468                 baton->referenced_type = die_type (target_die, target_cu);
17469                 baton->locexpr.per_cu = cu->per_cu;
17470                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17471                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17472                 prop->data.baton = baton;
17473                 prop->kind = PROP_LOCEXPR;
17474                 gdb_assert (prop->data.baton != NULL);
17475               }
17476             else
17477               {
17478                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17479                                                        "dynamic property");
17480                 return 0;
17481               }
17482             break;
17483           case DW_AT_data_member_location:
17484             {
17485               LONGEST offset;
17486
17487               if (!handle_data_member_location (target_die, target_cu,
17488                                                 &offset))
17489                 return 0;
17490
17491               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17492               baton->referenced_type = read_type_die (target_die->parent,
17493                                                       target_cu);
17494               baton->offset_info.offset = offset;
17495               baton->offset_info.type = die_type (target_die, target_cu);
17496               prop->data.baton = baton;
17497               prop->kind = PROP_ADDR_OFFSET;
17498               break;
17499             }
17500         }
17501     }
17502   else if (attr_form_is_constant (attr))
17503     {
17504       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17505       prop->kind = PROP_CONST;
17506     }
17507   else
17508     {
17509       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17510                                              dwarf2_name (die, cu));
17511       return 0;
17512     }
17513
17514   return 1;
17515 }
17516
17517 /* Read the given DW_AT_subrange DIE.  */
17518
17519 static struct type *
17520 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17521 {
17522   struct type *base_type, *orig_base_type;
17523   struct type *range_type;
17524   struct attribute *attr;
17525   struct dynamic_prop low, high;
17526   int low_default_is_valid;
17527   int high_bound_is_count = 0;
17528   const char *name;
17529   LONGEST negative_mask;
17530
17531   orig_base_type = die_type (die, cu);
17532   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17533      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17534      creating the range type, but we use the result of check_typedef
17535      when examining properties of the type.  */
17536   base_type = check_typedef (orig_base_type);
17537
17538   /* The die_type call above may have already set the type for this DIE.  */
17539   range_type = get_die_type (die, cu);
17540   if (range_type)
17541     return range_type;
17542
17543   low.kind = PROP_CONST;
17544   high.kind = PROP_CONST;
17545   high.data.const_val = 0;
17546
17547   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17548      omitting DW_AT_lower_bound.  */
17549   switch (cu->language)
17550     {
17551     case language_c:
17552     case language_cplus:
17553       low.data.const_val = 0;
17554       low_default_is_valid = 1;
17555       break;
17556     case language_fortran:
17557       low.data.const_val = 1;
17558       low_default_is_valid = 1;
17559       break;
17560     case language_d:
17561     case language_objc:
17562     case language_rust:
17563       low.data.const_val = 0;
17564       low_default_is_valid = (cu->header.version >= 4);
17565       break;
17566     case language_ada:
17567     case language_m2:
17568     case language_pascal:
17569       low.data.const_val = 1;
17570       low_default_is_valid = (cu->header.version >= 4);
17571       break;
17572     default:
17573       low.data.const_val = 0;
17574       low_default_is_valid = 0;
17575       break;
17576     }
17577
17578   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17579   if (attr)
17580     attr_to_dynamic_prop (attr, die, cu, &low);
17581   else if (!low_default_is_valid)
17582     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17583                                       "- DIE at 0x%x [in module %s]"),
17584                to_underlying (die->sect_off), objfile_name (cu->objfile));
17585
17586   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17587   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17588     {
17589       attr = dwarf2_attr (die, DW_AT_count, cu);
17590       if (attr_to_dynamic_prop (attr, die, cu, &high))
17591         {
17592           /* If bounds are constant do the final calculation here.  */
17593           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17594             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17595           else
17596             high_bound_is_count = 1;
17597         }
17598     }
17599
17600   /* Dwarf-2 specifications explicitly allows to create subrange types
17601      without specifying a base type.
17602      In that case, the base type must be set to the type of
17603      the lower bound, upper bound or count, in that order, if any of these
17604      three attributes references an object that has a type.
17605      If no base type is found, the Dwarf-2 specifications say that
17606      a signed integer type of size equal to the size of an address should
17607      be used.
17608      For the following C code: `extern char gdb_int [];'
17609      GCC produces an empty range DIE.
17610      FIXME: muller/2010-05-28: Possible references to object for low bound,
17611      high bound or count are not yet handled by this code.  */
17612   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17613     {
17614       struct objfile *objfile = cu->objfile;
17615       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17616       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17617       struct type *int_type = objfile_type (objfile)->builtin_int;
17618
17619       /* Test "int", "long int", and "long long int" objfile types,
17620          and select the first one having a size above or equal to the
17621          architecture address size.  */
17622       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17623         base_type = int_type;
17624       else
17625         {
17626           int_type = objfile_type (objfile)->builtin_long;
17627           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17628             base_type = int_type;
17629           else
17630             {
17631               int_type = objfile_type (objfile)->builtin_long_long;
17632               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17633                 base_type = int_type;
17634             }
17635         }
17636     }
17637
17638   /* Normally, the DWARF producers are expected to use a signed
17639      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17640      But this is unfortunately not always the case, as witnessed
17641      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17642      is used instead.  To work around that ambiguity, we treat
17643      the bounds as signed, and thus sign-extend their values, when
17644      the base type is signed.  */
17645   negative_mask =
17646     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17647   if (low.kind == PROP_CONST
17648       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17649     low.data.const_val |= negative_mask;
17650   if (high.kind == PROP_CONST
17651       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17652     high.data.const_val |= negative_mask;
17653
17654   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17655
17656   if (high_bound_is_count)
17657     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17658
17659   /* Ada expects an empty array on no boundary attributes.  */
17660   if (attr == NULL && cu->language != language_ada)
17661     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17662
17663   name = dwarf2_name (die, cu);
17664   if (name)
17665     TYPE_NAME (range_type) = name;
17666
17667   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17668   if (attr)
17669     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17670
17671   set_die_type (die, range_type, cu);
17672
17673   /* set_die_type should be already done.  */
17674   set_descriptive_type (range_type, die, cu);
17675
17676   return range_type;
17677 }
17678
17679 static struct type *
17680 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17681 {
17682   struct type *type;
17683
17684   /* For now, we only support the C meaning of an unspecified type: void.  */
17685
17686   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
17687   TYPE_NAME (type) = dwarf2_name (die, cu);
17688
17689   return set_die_type (die, type, cu);
17690 }
17691
17692 /* Read a single die and all its descendents.  Set the die's sibling
17693    field to NULL; set other fields in the die correctly, and set all
17694    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17695    location of the info_ptr after reading all of those dies.  PARENT
17696    is the parent of the die in question.  */
17697
17698 static struct die_info *
17699 read_die_and_children (const struct die_reader_specs *reader,
17700                        const gdb_byte *info_ptr,
17701                        const gdb_byte **new_info_ptr,
17702                        struct die_info *parent)
17703 {
17704   struct die_info *die;
17705   const gdb_byte *cur_ptr;
17706   int has_children;
17707
17708   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17709   if (die == NULL)
17710     {
17711       *new_info_ptr = cur_ptr;
17712       return NULL;
17713     }
17714   store_in_ref_table (die, reader->cu);
17715
17716   if (has_children)
17717     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17718   else
17719     {
17720       die->child = NULL;
17721       *new_info_ptr = cur_ptr;
17722     }
17723
17724   die->sibling = NULL;
17725   die->parent = parent;
17726   return die;
17727 }
17728
17729 /* Read a die, all of its descendents, and all of its siblings; set
17730    all of the fields of all of the dies correctly.  Arguments are as
17731    in read_die_and_children.  */
17732
17733 static struct die_info *
17734 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17735                          const gdb_byte *info_ptr,
17736                          const gdb_byte **new_info_ptr,
17737                          struct die_info *parent)
17738 {
17739   struct die_info *first_die, *last_sibling;
17740   const gdb_byte *cur_ptr;
17741
17742   cur_ptr = info_ptr;
17743   first_die = last_sibling = NULL;
17744
17745   while (1)
17746     {
17747       struct die_info *die
17748         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17749
17750       if (die == NULL)
17751         {
17752           *new_info_ptr = cur_ptr;
17753           return first_die;
17754         }
17755
17756       if (!first_die)
17757         first_die = die;
17758       else
17759         last_sibling->sibling = die;
17760
17761       last_sibling = die;
17762     }
17763 }
17764
17765 /* Read a die, all of its descendents, and all of its siblings; set
17766    all of the fields of all of the dies correctly.  Arguments are as
17767    in read_die_and_children.
17768    This the main entry point for reading a DIE and all its children.  */
17769
17770 static struct die_info *
17771 read_die_and_siblings (const struct die_reader_specs *reader,
17772                        const gdb_byte *info_ptr,
17773                        const gdb_byte **new_info_ptr,
17774                        struct die_info *parent)
17775 {
17776   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17777                                                   new_info_ptr, parent);
17778
17779   if (dwarf_die_debug)
17780     {
17781       fprintf_unfiltered (gdb_stdlog,
17782                           "Read die from %s@0x%x of %s:\n",
17783                           get_section_name (reader->die_section),
17784                           (unsigned) (info_ptr - reader->die_section->buffer),
17785                           bfd_get_filename (reader->abfd));
17786       dump_die (die, dwarf_die_debug);
17787     }
17788
17789   return die;
17790 }
17791
17792 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17793    attributes.
17794    The caller is responsible for filling in the extra attributes
17795    and updating (*DIEP)->num_attrs.
17796    Set DIEP to point to a newly allocated die with its information,
17797    except for its child, sibling, and parent fields.
17798    Set HAS_CHILDREN to tell whether the die has children or not.  */
17799
17800 static const gdb_byte *
17801 read_full_die_1 (const struct die_reader_specs *reader,
17802                  struct die_info **diep, const gdb_byte *info_ptr,
17803                  int *has_children, int num_extra_attrs)
17804 {
17805   unsigned int abbrev_number, bytes_read, i;
17806   struct abbrev_info *abbrev;
17807   struct die_info *die;
17808   struct dwarf2_cu *cu = reader->cu;
17809   bfd *abfd = reader->abfd;
17810
17811   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17812   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17813   info_ptr += bytes_read;
17814   if (!abbrev_number)
17815     {
17816       *diep = NULL;
17817       *has_children = 0;
17818       return info_ptr;
17819     }
17820
17821   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
17822   if (!abbrev)
17823     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17824            abbrev_number,
17825            bfd_get_filename (abfd));
17826
17827   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17828   die->sect_off = sect_off;
17829   die->tag = abbrev->tag;
17830   die->abbrev = abbrev_number;
17831
17832   /* Make the result usable.
17833      The caller needs to update num_attrs after adding the extra
17834      attributes.  */
17835   die->num_attrs = abbrev->num_attrs;
17836
17837   for (i = 0; i < abbrev->num_attrs; ++i)
17838     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17839                                info_ptr);
17840
17841   *diep = die;
17842   *has_children = abbrev->has_children;
17843   return info_ptr;
17844 }
17845
17846 /* Read a die and all its attributes.
17847    Set DIEP to point to a newly allocated die with its information,
17848    except for its child, sibling, and parent fields.
17849    Set HAS_CHILDREN to tell whether the die has children or not.  */
17850
17851 static const gdb_byte *
17852 read_full_die (const struct die_reader_specs *reader,
17853                struct die_info **diep, const gdb_byte *info_ptr,
17854                int *has_children)
17855 {
17856   const gdb_byte *result;
17857
17858   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17859
17860   if (dwarf_die_debug)
17861     {
17862       fprintf_unfiltered (gdb_stdlog,
17863                           "Read die from %s@0x%x of %s:\n",
17864                           get_section_name (reader->die_section),
17865                           (unsigned) (info_ptr - reader->die_section->buffer),
17866                           bfd_get_filename (reader->abfd));
17867       dump_die (*diep, dwarf_die_debug);
17868     }
17869
17870   return result;
17871 }
17872 \f
17873 /* Abbreviation tables.
17874
17875    In DWARF version 2, the description of the debugging information is
17876    stored in a separate .debug_abbrev section.  Before we read any
17877    dies from a section we read in all abbreviations and install them
17878    in a hash table.  */
17879
17880 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17881
17882 static struct abbrev_info *
17883 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
17884 {
17885   struct abbrev_info *abbrev;
17886
17887   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
17888   memset (abbrev, 0, sizeof (struct abbrev_info));
17889
17890   return abbrev;
17891 }
17892
17893 /* Add an abbreviation to the table.  */
17894
17895 static void
17896 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
17897                          unsigned int abbrev_number,
17898                          struct abbrev_info *abbrev)
17899 {
17900   unsigned int hash_number;
17901
17902   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17903   abbrev->next = abbrev_table->abbrevs[hash_number];
17904   abbrev_table->abbrevs[hash_number] = abbrev;
17905 }
17906
17907 /* Look up an abbrev in the table.
17908    Returns NULL if the abbrev is not found.  */
17909
17910 static struct abbrev_info *
17911 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
17912                             unsigned int abbrev_number)
17913 {
17914   unsigned int hash_number;
17915   struct abbrev_info *abbrev;
17916
17917   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17918   abbrev = abbrev_table->abbrevs[hash_number];
17919
17920   while (abbrev)
17921     {
17922       if (abbrev->number == abbrev_number)
17923         return abbrev;
17924       abbrev = abbrev->next;
17925     }
17926   return NULL;
17927 }
17928
17929 /* Read in an abbrev table.  */
17930
17931 static struct abbrev_table *
17932 abbrev_table_read_table (struct dwarf2_section_info *section,
17933                          sect_offset sect_off)
17934 {
17935   struct objfile *objfile = dwarf2_per_objfile->objfile;
17936   bfd *abfd = get_section_bfd_owner (section);
17937   struct abbrev_table *abbrev_table;
17938   const gdb_byte *abbrev_ptr;
17939   struct abbrev_info *cur_abbrev;
17940   unsigned int abbrev_number, bytes_read, abbrev_name;
17941   unsigned int abbrev_form;
17942   struct attr_abbrev *cur_attrs;
17943   unsigned int allocated_attrs;
17944
17945   abbrev_table = XNEW (struct abbrev_table);
17946   abbrev_table->sect_off = sect_off;
17947   obstack_init (&abbrev_table->abbrev_obstack);
17948   abbrev_table->abbrevs =
17949     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
17950                ABBREV_HASH_SIZE);
17951   memset (abbrev_table->abbrevs, 0,
17952           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
17953
17954   dwarf2_read_section (objfile, section);
17955   abbrev_ptr = section->buffer + to_underlying (sect_off);
17956   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17957   abbrev_ptr += bytes_read;
17958
17959   allocated_attrs = ATTR_ALLOC_CHUNK;
17960   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
17961
17962   /* Loop until we reach an abbrev number of 0.  */
17963   while (abbrev_number)
17964     {
17965       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
17966
17967       /* read in abbrev header */
17968       cur_abbrev->number = abbrev_number;
17969       cur_abbrev->tag
17970         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17971       abbrev_ptr += bytes_read;
17972       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
17973       abbrev_ptr += 1;
17974
17975       /* now read in declarations */
17976       for (;;)
17977         {
17978           LONGEST implicit_const;
17979
17980           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17981           abbrev_ptr += bytes_read;
17982           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17983           abbrev_ptr += bytes_read;
17984           if (abbrev_form == DW_FORM_implicit_const)
17985             {
17986               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
17987                                                    &bytes_read);
17988               abbrev_ptr += bytes_read;
17989             }
17990           else
17991             {
17992               /* Initialize it due to a false compiler warning.  */
17993               implicit_const = -1;
17994             }
17995
17996           if (abbrev_name == 0)
17997             break;
17998
17999           if (cur_abbrev->num_attrs == allocated_attrs)
18000             {
18001               allocated_attrs += ATTR_ALLOC_CHUNK;
18002               cur_attrs
18003                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18004             }
18005
18006           cur_attrs[cur_abbrev->num_attrs].name
18007             = (enum dwarf_attribute) abbrev_name;
18008           cur_attrs[cur_abbrev->num_attrs].form
18009             = (enum dwarf_form) abbrev_form;
18010           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18011           ++cur_abbrev->num_attrs;
18012         }
18013
18014       cur_abbrev->attrs =
18015         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18016                    cur_abbrev->num_attrs);
18017       memcpy (cur_abbrev->attrs, cur_attrs,
18018               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18019
18020       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
18021
18022       /* Get next abbreviation.
18023          Under Irix6 the abbreviations for a compilation unit are not
18024          always properly terminated with an abbrev number of 0.
18025          Exit loop if we encounter an abbreviation which we have
18026          already read (which means we are about to read the abbreviations
18027          for the next compile unit) or if the end of the abbreviation
18028          table is reached.  */
18029       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18030         break;
18031       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18032       abbrev_ptr += bytes_read;
18033       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
18034         break;
18035     }
18036
18037   xfree (cur_attrs);
18038   return abbrev_table;
18039 }
18040
18041 /* Free the resources held by ABBREV_TABLE.  */
18042
18043 static void
18044 abbrev_table_free (struct abbrev_table *abbrev_table)
18045 {
18046   obstack_free (&abbrev_table->abbrev_obstack, NULL);
18047   xfree (abbrev_table);
18048 }
18049
18050 /* Same as abbrev_table_free but as a cleanup.
18051    We pass in a pointer to the pointer to the table so that we can
18052    set the pointer to NULL when we're done.  It also simplifies
18053    build_type_psymtabs_1.  */
18054
18055 static void
18056 abbrev_table_free_cleanup (void *table_ptr)
18057 {
18058   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
18059
18060   if (*abbrev_table_ptr != NULL)
18061     abbrev_table_free (*abbrev_table_ptr);
18062   *abbrev_table_ptr = NULL;
18063 }
18064
18065 /* Read the abbrev table for CU from ABBREV_SECTION.  */
18066
18067 static void
18068 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
18069                      struct dwarf2_section_info *abbrev_section)
18070 {
18071   cu->abbrev_table =
18072     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
18073 }
18074
18075 /* Release the memory used by the abbrev table for a compilation unit.  */
18076
18077 static void
18078 dwarf2_free_abbrev_table (void *ptr_to_cu)
18079 {
18080   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
18081
18082   if (cu->abbrev_table != NULL)
18083     abbrev_table_free (cu->abbrev_table);
18084   /* Set this to NULL so that we SEGV if we try to read it later,
18085      and also because free_comp_unit verifies this is NULL.  */
18086   cu->abbrev_table = NULL;
18087 }
18088 \f
18089 /* Returns nonzero if TAG represents a type that we might generate a partial
18090    symbol for.  */
18091
18092 static int
18093 is_type_tag_for_partial (int tag)
18094 {
18095   switch (tag)
18096     {
18097 #if 0
18098     /* Some types that would be reasonable to generate partial symbols for,
18099        that we don't at present.  */
18100     case DW_TAG_array_type:
18101     case DW_TAG_file_type:
18102     case DW_TAG_ptr_to_member_type:
18103     case DW_TAG_set_type:
18104     case DW_TAG_string_type:
18105     case DW_TAG_subroutine_type:
18106 #endif
18107     case DW_TAG_base_type:
18108     case DW_TAG_class_type:
18109     case DW_TAG_interface_type:
18110     case DW_TAG_enumeration_type:
18111     case DW_TAG_structure_type:
18112     case DW_TAG_subrange_type:
18113     case DW_TAG_typedef:
18114     case DW_TAG_union_type:
18115       return 1;
18116     default:
18117       return 0;
18118     }
18119 }
18120
18121 /* Load all DIEs that are interesting for partial symbols into memory.  */
18122
18123 static struct partial_die_info *
18124 load_partial_dies (const struct die_reader_specs *reader,
18125                    const gdb_byte *info_ptr, int building_psymtab)
18126 {
18127   struct dwarf2_cu *cu = reader->cu;
18128   struct objfile *objfile = cu->objfile;
18129   struct partial_die_info *part_die;
18130   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18131   struct abbrev_info *abbrev;
18132   unsigned int bytes_read;
18133   unsigned int load_all = 0;
18134   int nesting_level = 1;
18135
18136   parent_die = NULL;
18137   last_die = NULL;
18138
18139   gdb_assert (cu->per_cu != NULL);
18140   if (cu->per_cu->load_all_dies)
18141     load_all = 1;
18142
18143   cu->partial_dies
18144     = htab_create_alloc_ex (cu->header.length / 12,
18145                             partial_die_hash,
18146                             partial_die_eq,
18147                             NULL,
18148                             &cu->comp_unit_obstack,
18149                             hashtab_obstack_allocate,
18150                             dummy_obstack_deallocate);
18151
18152   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18153
18154   while (1)
18155     {
18156       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
18157
18158       /* A NULL abbrev means the end of a series of children.  */
18159       if (abbrev == NULL)
18160         {
18161           if (--nesting_level == 0)
18162             {
18163               /* PART_DIE was probably the last thing allocated on the
18164                  comp_unit_obstack, so we could call obstack_free
18165                  here.  We don't do that because the waste is small,
18166                  and will be cleaned up when we're done with this
18167                  compilation unit.  This way, we're also more robust
18168                  against other users of the comp_unit_obstack.  */
18169               return first_die;
18170             }
18171           info_ptr += bytes_read;
18172           last_die = parent_die;
18173           parent_die = parent_die->die_parent;
18174           continue;
18175         }
18176
18177       /* Check for template arguments.  We never save these; if
18178          they're seen, we just mark the parent, and go on our way.  */
18179       if (parent_die != NULL
18180           && cu->language == language_cplus
18181           && (abbrev->tag == DW_TAG_template_type_param
18182               || abbrev->tag == DW_TAG_template_value_param))
18183         {
18184           parent_die->has_template_arguments = 1;
18185
18186           if (!load_all)
18187             {
18188               /* We don't need a partial DIE for the template argument.  */
18189               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18190               continue;
18191             }
18192         }
18193
18194       /* We only recurse into c++ subprograms looking for template arguments.
18195          Skip their other children.  */
18196       if (!load_all
18197           && cu->language == language_cplus
18198           && parent_die != NULL
18199           && parent_die->tag == DW_TAG_subprogram)
18200         {
18201           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18202           continue;
18203         }
18204
18205       /* Check whether this DIE is interesting enough to save.  Normally
18206          we would not be interested in members here, but there may be
18207          later variables referencing them via DW_AT_specification (for
18208          static members).  */
18209       if (!load_all
18210           && !is_type_tag_for_partial (abbrev->tag)
18211           && abbrev->tag != DW_TAG_constant
18212           && abbrev->tag != DW_TAG_enumerator
18213           && abbrev->tag != DW_TAG_subprogram
18214           && abbrev->tag != DW_TAG_lexical_block
18215           && abbrev->tag != DW_TAG_variable
18216           && abbrev->tag != DW_TAG_namespace
18217           && abbrev->tag != DW_TAG_module
18218           && abbrev->tag != DW_TAG_member
18219           && abbrev->tag != DW_TAG_imported_unit
18220           && abbrev->tag != DW_TAG_imported_declaration)
18221         {
18222           /* Otherwise we skip to the next sibling, if any.  */
18223           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18224           continue;
18225         }
18226
18227       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18228                                    info_ptr);
18229
18230       /* This two-pass algorithm for processing partial symbols has a
18231          high cost in cache pressure.  Thus, handle some simple cases
18232          here which cover the majority of C partial symbols.  DIEs
18233          which neither have specification tags in them, nor could have
18234          specification tags elsewhere pointing at them, can simply be
18235          processed and discarded.
18236
18237          This segment is also optional; scan_partial_symbols and
18238          add_partial_symbol will handle these DIEs if we chain
18239          them in normally.  When compilers which do not emit large
18240          quantities of duplicate debug information are more common,
18241          this code can probably be removed.  */
18242
18243       /* Any complete simple types at the top level (pretty much all
18244          of them, for a language without namespaces), can be processed
18245          directly.  */
18246       if (parent_die == NULL
18247           && part_die->has_specification == 0
18248           && part_die->is_declaration == 0
18249           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18250               || part_die->tag == DW_TAG_base_type
18251               || part_die->tag == DW_TAG_subrange_type))
18252         {
18253           if (building_psymtab && part_die->name != NULL)
18254             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18255                                  VAR_DOMAIN, LOC_TYPEDEF,
18256                                  &objfile->static_psymbols,
18257                                  0, cu->language, objfile);
18258           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18259           continue;
18260         }
18261
18262       /* The exception for DW_TAG_typedef with has_children above is
18263          a workaround of GCC PR debug/47510.  In the case of this complaint
18264          type_name_no_tag_or_error will error on such types later.
18265
18266          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18267          it could not find the child DIEs referenced later, this is checked
18268          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18269
18270       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18271         complaint (&symfile_complaints,
18272                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18273                      "- DIE at 0x%x [in module %s]"),
18274                    to_underlying (part_die->sect_off), objfile_name (objfile));
18275
18276       /* If we're at the second level, and we're an enumerator, and
18277          our parent has no specification (meaning possibly lives in a
18278          namespace elsewhere), then we can add the partial symbol now
18279          instead of queueing it.  */
18280       if (part_die->tag == DW_TAG_enumerator
18281           && parent_die != NULL
18282           && parent_die->die_parent == NULL
18283           && parent_die->tag == DW_TAG_enumeration_type
18284           && parent_die->has_specification == 0)
18285         {
18286           if (part_die->name == NULL)
18287             complaint (&symfile_complaints,
18288                        _("malformed enumerator DIE ignored"));
18289           else if (building_psymtab)
18290             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18291                                  VAR_DOMAIN, LOC_CONST,
18292                                  cu->language == language_cplus
18293                                  ? &objfile->global_psymbols
18294                                  : &objfile->static_psymbols,
18295                                  0, cu->language, objfile);
18296
18297           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18298           continue;
18299         }
18300
18301       /* We'll save this DIE so link it in.  */
18302       part_die->die_parent = parent_die;
18303       part_die->die_sibling = NULL;
18304       part_die->die_child = NULL;
18305
18306       if (last_die && last_die == parent_die)
18307         last_die->die_child = part_die;
18308       else if (last_die)
18309         last_die->die_sibling = part_die;
18310
18311       last_die = part_die;
18312
18313       if (first_die == NULL)
18314         first_die = part_die;
18315
18316       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18317          find interesting need to be in the hash table, because we
18318          also have the parent/sibling/child chains; only those that we
18319          might refer to by offset later during partial symbol reading.
18320
18321          For now this means things that might have be the target of a
18322          DW_AT_specification, DW_AT_abstract_origin, or
18323          DW_AT_extension.  DW_AT_extension will refer only to
18324          namespaces; DW_AT_abstract_origin refers to functions (and
18325          many things under the function DIE, but we do not recurse
18326          into function DIEs during partial symbol reading) and
18327          possibly variables as well; DW_AT_specification refers to
18328          declarations.  Declarations ought to have the DW_AT_declaration
18329          flag.  It happens that GCC forgets to put it in sometimes, but
18330          only for functions, not for types.
18331
18332          Adding more things than necessary to the hash table is harmless
18333          except for the performance cost.  Adding too few will result in
18334          wasted time in find_partial_die, when we reread the compilation
18335          unit with load_all_dies set.  */
18336
18337       if (load_all
18338           || abbrev->tag == DW_TAG_constant
18339           || abbrev->tag == DW_TAG_subprogram
18340           || abbrev->tag == DW_TAG_variable
18341           || abbrev->tag == DW_TAG_namespace
18342           || part_die->is_declaration)
18343         {
18344           void **slot;
18345
18346           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18347                                            to_underlying (part_die->sect_off),
18348                                            INSERT);
18349           *slot = part_die;
18350         }
18351
18352       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18353
18354       /* For some DIEs we want to follow their children (if any).  For C
18355          we have no reason to follow the children of structures; for other
18356          languages we have to, so that we can get at method physnames
18357          to infer fully qualified class names, for DW_AT_specification,
18358          and for C++ template arguments.  For C++, we also look one level
18359          inside functions to find template arguments (if the name of the
18360          function does not already contain the template arguments).
18361
18362          For Ada, we need to scan the children of subprograms and lexical
18363          blocks as well because Ada allows the definition of nested
18364          entities that could be interesting for the debugger, such as
18365          nested subprograms for instance.  */
18366       if (last_die->has_children
18367           && (load_all
18368               || last_die->tag == DW_TAG_namespace
18369               || last_die->tag == DW_TAG_module
18370               || last_die->tag == DW_TAG_enumeration_type
18371               || (cu->language == language_cplus
18372                   && last_die->tag == DW_TAG_subprogram
18373                   && (last_die->name == NULL
18374                       || strchr (last_die->name, '<') == NULL))
18375               || (cu->language != language_c
18376                   && (last_die->tag == DW_TAG_class_type
18377                       || last_die->tag == DW_TAG_interface_type
18378                       || last_die->tag == DW_TAG_structure_type
18379                       || last_die->tag == DW_TAG_union_type))
18380               || (cu->language == language_ada
18381                   && (last_die->tag == DW_TAG_subprogram
18382                       || last_die->tag == DW_TAG_lexical_block))))
18383         {
18384           nesting_level++;
18385           parent_die = last_die;
18386           continue;
18387         }
18388
18389       /* Otherwise we skip to the next sibling, if any.  */
18390       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18391
18392       /* Back to the top, do it again.  */
18393     }
18394 }
18395
18396 /* Read a minimal amount of information into the minimal die structure.  */
18397
18398 static const gdb_byte *
18399 read_partial_die (const struct die_reader_specs *reader,
18400                   struct partial_die_info *part_die,
18401                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18402                   const gdb_byte *info_ptr)
18403 {
18404   struct dwarf2_cu *cu = reader->cu;
18405   struct objfile *objfile = cu->objfile;
18406   const gdb_byte *buffer = reader->buffer;
18407   unsigned int i;
18408   struct attribute attr;
18409   int has_low_pc_attr = 0;
18410   int has_high_pc_attr = 0;
18411   int high_pc_relative = 0;
18412
18413   memset (part_die, 0, sizeof (struct partial_die_info));
18414
18415   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18416
18417   info_ptr += abbrev_len;
18418
18419   if (abbrev == NULL)
18420     return info_ptr;
18421
18422   part_die->tag = abbrev->tag;
18423   part_die->has_children = abbrev->has_children;
18424
18425   for (i = 0; i < abbrev->num_attrs; ++i)
18426     {
18427       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18428
18429       /* Store the data if it is of an attribute we want to keep in a
18430          partial symbol table.  */
18431       switch (attr.name)
18432         {
18433         case DW_AT_name:
18434           switch (part_die->tag)
18435             {
18436             case DW_TAG_compile_unit:
18437             case DW_TAG_partial_unit:
18438             case DW_TAG_type_unit:
18439               /* Compilation units have a DW_AT_name that is a filename, not
18440                  a source language identifier.  */
18441             case DW_TAG_enumeration_type:
18442             case DW_TAG_enumerator:
18443               /* These tags always have simple identifiers already; no need
18444                  to canonicalize them.  */
18445               part_die->name = DW_STRING (&attr);
18446               break;
18447             default:
18448               part_die->name
18449                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18450                                             &objfile->per_bfd->storage_obstack);
18451               break;
18452             }
18453           break;
18454         case DW_AT_linkage_name:
18455         case DW_AT_MIPS_linkage_name:
18456           /* Note that both forms of linkage name might appear.  We
18457              assume they will be the same, and we only store the last
18458              one we see.  */
18459           if (cu->language == language_ada)
18460             part_die->name = DW_STRING (&attr);
18461           part_die->linkage_name = DW_STRING (&attr);
18462           break;
18463         case DW_AT_low_pc:
18464           has_low_pc_attr = 1;
18465           part_die->lowpc = attr_value_as_address (&attr);
18466           break;
18467         case DW_AT_high_pc:
18468           has_high_pc_attr = 1;
18469           part_die->highpc = attr_value_as_address (&attr);
18470           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18471                 high_pc_relative = 1;
18472           break;
18473         case DW_AT_location:
18474           /* Support the .debug_loc offsets.  */
18475           if (attr_form_is_block (&attr))
18476             {
18477                part_die->d.locdesc = DW_BLOCK (&attr);
18478             }
18479           else if (attr_form_is_section_offset (&attr))
18480             {
18481               dwarf2_complex_location_expr_complaint ();
18482             }
18483           else
18484             {
18485               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18486                                                      "partial symbol information");
18487             }
18488           break;
18489         case DW_AT_external:
18490           part_die->is_external = DW_UNSND (&attr);
18491           break;
18492         case DW_AT_declaration:
18493           part_die->is_declaration = DW_UNSND (&attr);
18494           break;
18495         case DW_AT_type:
18496           part_die->has_type = 1;
18497           break;
18498         case DW_AT_abstract_origin:
18499         case DW_AT_specification:
18500         case DW_AT_extension:
18501           part_die->has_specification = 1;
18502           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18503           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18504                                    || cu->per_cu->is_dwz);
18505           break;
18506         case DW_AT_sibling:
18507           /* Ignore absolute siblings, they might point outside of
18508              the current compile unit.  */
18509           if (attr.form == DW_FORM_ref_addr)
18510             complaint (&symfile_complaints,
18511                        _("ignoring absolute DW_AT_sibling"));
18512           else
18513             {
18514               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18515               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18516
18517               if (sibling_ptr < info_ptr)
18518                 complaint (&symfile_complaints,
18519                            _("DW_AT_sibling points backwards"));
18520               else if (sibling_ptr > reader->buffer_end)
18521                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18522               else
18523                 part_die->sibling = sibling_ptr;
18524             }
18525           break;
18526         case DW_AT_byte_size:
18527           part_die->has_byte_size = 1;
18528           break;
18529         case DW_AT_const_value:
18530           part_die->has_const_value = 1;
18531           break;
18532         case DW_AT_calling_convention:
18533           /* DWARF doesn't provide a way to identify a program's source-level
18534              entry point.  DW_AT_calling_convention attributes are only meant
18535              to describe functions' calling conventions.
18536
18537              However, because it's a necessary piece of information in
18538              Fortran, and before DWARF 4 DW_CC_program was the only
18539              piece of debugging information whose definition refers to
18540              a 'main program' at all, several compilers marked Fortran
18541              main programs with DW_CC_program --- even when those
18542              functions use the standard calling conventions.
18543
18544              Although DWARF now specifies a way to provide this
18545              information, we support this practice for backward
18546              compatibility.  */
18547           if (DW_UNSND (&attr) == DW_CC_program
18548               && cu->language == language_fortran)
18549             part_die->main_subprogram = 1;
18550           break;
18551         case DW_AT_inline:
18552           if (DW_UNSND (&attr) == DW_INL_inlined
18553               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18554             part_die->may_be_inlined = 1;
18555           break;
18556
18557         case DW_AT_import:
18558           if (part_die->tag == DW_TAG_imported_unit)
18559             {
18560               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18561               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18562                                   || cu->per_cu->is_dwz);
18563             }
18564           break;
18565
18566         case DW_AT_main_subprogram:
18567           part_die->main_subprogram = DW_UNSND (&attr);
18568           break;
18569
18570         default:
18571           break;
18572         }
18573     }
18574
18575   if (high_pc_relative)
18576     part_die->highpc += part_die->lowpc;
18577
18578   if (has_low_pc_attr && has_high_pc_attr)
18579     {
18580       /* When using the GNU linker, .gnu.linkonce. sections are used to
18581          eliminate duplicate copies of functions and vtables and such.
18582          The linker will arbitrarily choose one and discard the others.
18583          The AT_*_pc values for such functions refer to local labels in
18584          these sections.  If the section from that file was discarded, the
18585          labels are not in the output, so the relocs get a value of 0.
18586          If this is a discarded function, mark the pc bounds as invalid,
18587          so that GDB will ignore it.  */
18588       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18589         {
18590           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18591
18592           complaint (&symfile_complaints,
18593                      _("DW_AT_low_pc %s is zero "
18594                        "for DIE at 0x%x [in module %s]"),
18595                      paddress (gdbarch, part_die->lowpc),
18596                      to_underlying (part_die->sect_off), objfile_name (objfile));
18597         }
18598       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18599       else if (part_die->lowpc >= part_die->highpc)
18600         {
18601           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18602
18603           complaint (&symfile_complaints,
18604                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18605                        "for DIE at 0x%x [in module %s]"),
18606                      paddress (gdbarch, part_die->lowpc),
18607                      paddress (gdbarch, part_die->highpc),
18608                      to_underlying (part_die->sect_off),
18609                      objfile_name (objfile));
18610         }
18611       else
18612         part_die->has_pc_info = 1;
18613     }
18614
18615   return info_ptr;
18616 }
18617
18618 /* Find a cached partial DIE at OFFSET in CU.  */
18619
18620 static struct partial_die_info *
18621 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18622 {
18623   struct partial_die_info *lookup_die = NULL;
18624   struct partial_die_info part_die;
18625
18626   part_die.sect_off = sect_off;
18627   lookup_die = ((struct partial_die_info *)
18628                 htab_find_with_hash (cu->partial_dies, &part_die,
18629                                      to_underlying (sect_off)));
18630
18631   return lookup_die;
18632 }
18633
18634 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18635    except in the case of .debug_types DIEs which do not reference
18636    outside their CU (they do however referencing other types via
18637    DW_FORM_ref_sig8).  */
18638
18639 static struct partial_die_info *
18640 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18641 {
18642   struct objfile *objfile = cu->objfile;
18643   struct dwarf2_per_cu_data *per_cu = NULL;
18644   struct partial_die_info *pd = NULL;
18645
18646   if (offset_in_dwz == cu->per_cu->is_dwz
18647       && offset_in_cu_p (&cu->header, sect_off))
18648     {
18649       pd = find_partial_die_in_comp_unit (sect_off, cu);
18650       if (pd != NULL)
18651         return pd;
18652       /* We missed recording what we needed.
18653          Load all dies and try again.  */
18654       per_cu = cu->per_cu;
18655     }
18656   else
18657     {
18658       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18659       if (cu->per_cu->is_debug_types)
18660         {
18661           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18662                    " external reference to offset 0x%x [in module %s].\n"),
18663                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18664                  bfd_get_filename (objfile->obfd));
18665         }
18666       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18667                                                  objfile);
18668
18669       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18670         load_partial_comp_unit (per_cu);
18671
18672       per_cu->cu->last_used = 0;
18673       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18674     }
18675
18676   /* If we didn't find it, and not all dies have been loaded,
18677      load them all and try again.  */
18678
18679   if (pd == NULL && per_cu->load_all_dies == 0)
18680     {
18681       per_cu->load_all_dies = 1;
18682
18683       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18684          THIS_CU->cu may already be in use.  So we can't just free it and
18685          replace its DIEs with the ones we read in.  Instead, we leave those
18686          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18687          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18688          set.  */
18689       load_partial_comp_unit (per_cu);
18690
18691       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18692     }
18693
18694   if (pd == NULL)
18695     internal_error (__FILE__, __LINE__,
18696                     _("could not find partial DIE 0x%x "
18697                       "in cache [from module %s]\n"),
18698                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18699   return pd;
18700 }
18701
18702 /* See if we can figure out if the class lives in a namespace.  We do
18703    this by looking for a member function; its demangled name will
18704    contain namespace info, if there is any.  */
18705
18706 static void
18707 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18708                                   struct dwarf2_cu *cu)
18709 {
18710   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18711      what template types look like, because the demangler
18712      frequently doesn't give the same name as the debug info.  We
18713      could fix this by only using the demangled name to get the
18714      prefix (but see comment in read_structure_type).  */
18715
18716   struct partial_die_info *real_pdi;
18717   struct partial_die_info *child_pdi;
18718
18719   /* If this DIE (this DIE's specification, if any) has a parent, then
18720      we should not do this.  We'll prepend the parent's fully qualified
18721      name when we create the partial symbol.  */
18722
18723   real_pdi = struct_pdi;
18724   while (real_pdi->has_specification)
18725     real_pdi = find_partial_die (real_pdi->spec_offset,
18726                                  real_pdi->spec_is_dwz, cu);
18727
18728   if (real_pdi->die_parent != NULL)
18729     return;
18730
18731   for (child_pdi = struct_pdi->die_child;
18732        child_pdi != NULL;
18733        child_pdi = child_pdi->die_sibling)
18734     {
18735       if (child_pdi->tag == DW_TAG_subprogram
18736           && child_pdi->linkage_name != NULL)
18737         {
18738           char *actual_class_name
18739             = language_class_name_from_physname (cu->language_defn,
18740                                                  child_pdi->linkage_name);
18741           if (actual_class_name != NULL)
18742             {
18743               struct_pdi->name
18744                 = ((const char *)
18745                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
18746                                   actual_class_name,
18747                                   strlen (actual_class_name)));
18748               xfree (actual_class_name);
18749             }
18750           break;
18751         }
18752     }
18753 }
18754
18755 /* Adjust PART_DIE before generating a symbol for it.  This function
18756    may set the is_external flag or change the DIE's name.  */
18757
18758 static void
18759 fixup_partial_die (struct partial_die_info *part_die,
18760                    struct dwarf2_cu *cu)
18761 {
18762   /* Once we've fixed up a die, there's no point in doing so again.
18763      This also avoids a memory leak if we were to call
18764      guess_partial_die_structure_name multiple times.  */
18765   if (part_die->fixup_called)
18766     return;
18767
18768   /* If we found a reference attribute and the DIE has no name, try
18769      to find a name in the referred to DIE.  */
18770
18771   if (part_die->name == NULL && part_die->has_specification)
18772     {
18773       struct partial_die_info *spec_die;
18774
18775       spec_die = find_partial_die (part_die->spec_offset,
18776                                    part_die->spec_is_dwz, cu);
18777
18778       fixup_partial_die (spec_die, cu);
18779
18780       if (spec_die->name)
18781         {
18782           part_die->name = spec_die->name;
18783
18784           /* Copy DW_AT_external attribute if it is set.  */
18785           if (spec_die->is_external)
18786             part_die->is_external = spec_die->is_external;
18787         }
18788     }
18789
18790   /* Set default names for some unnamed DIEs.  */
18791
18792   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18793     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18794
18795   /* If there is no parent die to provide a namespace, and there are
18796      children, see if we can determine the namespace from their linkage
18797      name.  */
18798   if (cu->language == language_cplus
18799       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18800       && part_die->die_parent == NULL
18801       && part_die->has_children
18802       && (part_die->tag == DW_TAG_class_type
18803           || part_die->tag == DW_TAG_structure_type
18804           || part_die->tag == DW_TAG_union_type))
18805     guess_partial_die_structure_name (part_die, cu);
18806
18807   /* GCC might emit a nameless struct or union that has a linkage
18808      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18809   if (part_die->name == NULL
18810       && (part_die->tag == DW_TAG_class_type
18811           || part_die->tag == DW_TAG_interface_type
18812           || part_die->tag == DW_TAG_structure_type
18813           || part_die->tag == DW_TAG_union_type)
18814       && part_die->linkage_name != NULL)
18815     {
18816       char *demangled;
18817
18818       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18819       if (demangled)
18820         {
18821           const char *base;
18822
18823           /* Strip any leading namespaces/classes, keep only the base name.
18824              DW_AT_name for named DIEs does not contain the prefixes.  */
18825           base = strrchr (demangled, ':');
18826           if (base && base > demangled && base[-1] == ':')
18827             base++;
18828           else
18829             base = demangled;
18830
18831           part_die->name
18832             = ((const char *)
18833                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
18834                               base, strlen (base)));
18835           xfree (demangled);
18836         }
18837     }
18838
18839   part_die->fixup_called = 1;
18840 }
18841
18842 /* Read an attribute value described by an attribute form.  */
18843
18844 static const gdb_byte *
18845 read_attribute_value (const struct die_reader_specs *reader,
18846                       struct attribute *attr, unsigned form,
18847                       LONGEST implicit_const, const gdb_byte *info_ptr)
18848 {
18849   struct dwarf2_cu *cu = reader->cu;
18850   struct objfile *objfile = cu->objfile;
18851   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18852   bfd *abfd = reader->abfd;
18853   struct comp_unit_head *cu_header = &cu->header;
18854   unsigned int bytes_read;
18855   struct dwarf_block *blk;
18856
18857   attr->form = (enum dwarf_form) form;
18858   switch (form)
18859     {
18860     case DW_FORM_ref_addr:
18861       if (cu->header.version == 2)
18862         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18863       else
18864         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18865                                        &cu->header, &bytes_read);
18866       info_ptr += bytes_read;
18867       break;
18868     case DW_FORM_GNU_ref_alt:
18869       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18870       info_ptr += bytes_read;
18871       break;
18872     case DW_FORM_addr:
18873       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18874       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18875       info_ptr += bytes_read;
18876       break;
18877     case DW_FORM_block2:
18878       blk = dwarf_alloc_block (cu);
18879       blk->size = read_2_bytes (abfd, info_ptr);
18880       info_ptr += 2;
18881       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18882       info_ptr += blk->size;
18883       DW_BLOCK (attr) = blk;
18884       break;
18885     case DW_FORM_block4:
18886       blk = dwarf_alloc_block (cu);
18887       blk->size = read_4_bytes (abfd, info_ptr);
18888       info_ptr += 4;
18889       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18890       info_ptr += blk->size;
18891       DW_BLOCK (attr) = blk;
18892       break;
18893     case DW_FORM_data2:
18894       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18895       info_ptr += 2;
18896       break;
18897     case DW_FORM_data4:
18898       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18899       info_ptr += 4;
18900       break;
18901     case DW_FORM_data8:
18902       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18903       info_ptr += 8;
18904       break;
18905     case DW_FORM_data16:
18906       blk = dwarf_alloc_block (cu);
18907       blk->size = 16;
18908       blk->data = read_n_bytes (abfd, info_ptr, 16);
18909       info_ptr += 16;
18910       DW_BLOCK (attr) = blk;
18911       break;
18912     case DW_FORM_sec_offset:
18913       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18914       info_ptr += bytes_read;
18915       break;
18916     case DW_FORM_string:
18917       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18918       DW_STRING_IS_CANONICAL (attr) = 0;
18919       info_ptr += bytes_read;
18920       break;
18921     case DW_FORM_strp:
18922       if (!cu->per_cu->is_dwz)
18923         {
18924           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
18925                                                    &bytes_read);
18926           DW_STRING_IS_CANONICAL (attr) = 0;
18927           info_ptr += bytes_read;
18928           break;
18929         }
18930       /* FALLTHROUGH */
18931     case DW_FORM_line_strp:
18932       if (!cu->per_cu->is_dwz)
18933         {
18934           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
18935                                                         cu_header, &bytes_read);
18936           DW_STRING_IS_CANONICAL (attr) = 0;
18937           info_ptr += bytes_read;
18938           break;
18939         }
18940       /* FALLTHROUGH */
18941     case DW_FORM_GNU_strp_alt:
18942       {
18943         struct dwz_file *dwz = dwarf2_get_dwz_file ();
18944         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18945                                           &bytes_read);
18946
18947         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
18948         DW_STRING_IS_CANONICAL (attr) = 0;
18949         info_ptr += bytes_read;
18950       }
18951       break;
18952     case DW_FORM_exprloc:
18953     case DW_FORM_block:
18954       blk = dwarf_alloc_block (cu);
18955       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18956       info_ptr += bytes_read;
18957       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18958       info_ptr += blk->size;
18959       DW_BLOCK (attr) = blk;
18960       break;
18961     case DW_FORM_block1:
18962       blk = dwarf_alloc_block (cu);
18963       blk->size = read_1_byte (abfd, info_ptr);
18964       info_ptr += 1;
18965       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18966       info_ptr += blk->size;
18967       DW_BLOCK (attr) = blk;
18968       break;
18969     case DW_FORM_data1:
18970       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18971       info_ptr += 1;
18972       break;
18973     case DW_FORM_flag:
18974       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18975       info_ptr += 1;
18976       break;
18977     case DW_FORM_flag_present:
18978       DW_UNSND (attr) = 1;
18979       break;
18980     case DW_FORM_sdata:
18981       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18982       info_ptr += bytes_read;
18983       break;
18984     case DW_FORM_udata:
18985       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18986       info_ptr += bytes_read;
18987       break;
18988     case DW_FORM_ref1:
18989       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18990                          + read_1_byte (abfd, info_ptr));
18991       info_ptr += 1;
18992       break;
18993     case DW_FORM_ref2:
18994       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18995                          + read_2_bytes (abfd, info_ptr));
18996       info_ptr += 2;
18997       break;
18998     case DW_FORM_ref4:
18999       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19000                          + read_4_bytes (abfd, info_ptr));
19001       info_ptr += 4;
19002       break;
19003     case DW_FORM_ref8:
19004       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19005                          + read_8_bytes (abfd, info_ptr));
19006       info_ptr += 8;
19007       break;
19008     case DW_FORM_ref_sig8:
19009       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19010       info_ptr += 8;
19011       break;
19012     case DW_FORM_ref_udata:
19013       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19014                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19015       info_ptr += bytes_read;
19016       break;
19017     case DW_FORM_indirect:
19018       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19019       info_ptr += bytes_read;
19020       if (form == DW_FORM_implicit_const)
19021         {
19022           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19023           info_ptr += bytes_read;
19024         }
19025       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19026                                        info_ptr);
19027       break;
19028     case DW_FORM_implicit_const:
19029       DW_SND (attr) = implicit_const;
19030       break;
19031     case DW_FORM_GNU_addr_index:
19032       if (reader->dwo_file == NULL)
19033         {
19034           /* For now flag a hard error.
19035              Later we can turn this into a complaint.  */
19036           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19037                  dwarf_form_name (form),
19038                  bfd_get_filename (abfd));
19039         }
19040       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19041       info_ptr += bytes_read;
19042       break;
19043     case DW_FORM_GNU_str_index:
19044       if (reader->dwo_file == NULL)
19045         {
19046           /* For now flag a hard error.
19047              Later we can turn this into a complaint if warranted.  */
19048           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19049                  dwarf_form_name (form),
19050                  bfd_get_filename (abfd));
19051         }
19052       {
19053         ULONGEST str_index =
19054           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19055
19056         DW_STRING (attr) = read_str_index (reader, str_index);
19057         DW_STRING_IS_CANONICAL (attr) = 0;
19058         info_ptr += bytes_read;
19059       }
19060       break;
19061     default:
19062       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19063              dwarf_form_name (form),
19064              bfd_get_filename (abfd));
19065     }
19066
19067   /* Super hack.  */
19068   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19069     attr->form = DW_FORM_GNU_ref_alt;
19070
19071   /* We have seen instances where the compiler tried to emit a byte
19072      size attribute of -1 which ended up being encoded as an unsigned
19073      0xffffffff.  Although 0xffffffff is technically a valid size value,
19074      an object of this size seems pretty unlikely so we can relatively
19075      safely treat these cases as if the size attribute was invalid and
19076      treat them as zero by default.  */
19077   if (attr->name == DW_AT_byte_size
19078       && form == DW_FORM_data4
19079       && DW_UNSND (attr) >= 0xffffffff)
19080     {
19081       complaint
19082         (&symfile_complaints,
19083          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19084          hex_string (DW_UNSND (attr)));
19085       DW_UNSND (attr) = 0;
19086     }
19087
19088   return info_ptr;
19089 }
19090
19091 /* Read an attribute described by an abbreviated attribute.  */
19092
19093 static const gdb_byte *
19094 read_attribute (const struct die_reader_specs *reader,
19095                 struct attribute *attr, struct attr_abbrev *abbrev,
19096                 const gdb_byte *info_ptr)
19097 {
19098   attr->name = abbrev->name;
19099   return read_attribute_value (reader, attr, abbrev->form,
19100                                abbrev->implicit_const, info_ptr);
19101 }
19102
19103 /* Read dwarf information from a buffer.  */
19104
19105 static unsigned int
19106 read_1_byte (bfd *abfd, const gdb_byte *buf)
19107 {
19108   return bfd_get_8 (abfd, buf);
19109 }
19110
19111 static int
19112 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19113 {
19114   return bfd_get_signed_8 (abfd, buf);
19115 }
19116
19117 static unsigned int
19118 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19119 {
19120   return bfd_get_16 (abfd, buf);
19121 }
19122
19123 static int
19124 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19125 {
19126   return bfd_get_signed_16 (abfd, buf);
19127 }
19128
19129 static unsigned int
19130 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19131 {
19132   return bfd_get_32 (abfd, buf);
19133 }
19134
19135 static int
19136 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19137 {
19138   return bfd_get_signed_32 (abfd, buf);
19139 }
19140
19141 static ULONGEST
19142 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19143 {
19144   return bfd_get_64 (abfd, buf);
19145 }
19146
19147 static CORE_ADDR
19148 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19149               unsigned int *bytes_read)
19150 {
19151   struct comp_unit_head *cu_header = &cu->header;
19152   CORE_ADDR retval = 0;
19153
19154   if (cu_header->signed_addr_p)
19155     {
19156       switch (cu_header->addr_size)
19157         {
19158         case 2:
19159           retval = bfd_get_signed_16 (abfd, buf);
19160           break;
19161         case 4:
19162           retval = bfd_get_signed_32 (abfd, buf);
19163           break;
19164         case 8:
19165           retval = bfd_get_signed_64 (abfd, buf);
19166           break;
19167         default:
19168           internal_error (__FILE__, __LINE__,
19169                           _("read_address: bad switch, signed [in module %s]"),
19170                           bfd_get_filename (abfd));
19171         }
19172     }
19173   else
19174     {
19175       switch (cu_header->addr_size)
19176         {
19177         case 2:
19178           retval = bfd_get_16 (abfd, buf);
19179           break;
19180         case 4:
19181           retval = bfd_get_32 (abfd, buf);
19182           break;
19183         case 8:
19184           retval = bfd_get_64 (abfd, buf);
19185           break;
19186         default:
19187           internal_error (__FILE__, __LINE__,
19188                           _("read_address: bad switch, "
19189                             "unsigned [in module %s]"),
19190                           bfd_get_filename (abfd));
19191         }
19192     }
19193
19194   *bytes_read = cu_header->addr_size;
19195   return retval;
19196 }
19197
19198 /* Read the initial length from a section.  The (draft) DWARF 3
19199    specification allows the initial length to take up either 4 bytes
19200    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19201    bytes describe the length and all offsets will be 8 bytes in length
19202    instead of 4.
19203
19204    An older, non-standard 64-bit format is also handled by this
19205    function.  The older format in question stores the initial length
19206    as an 8-byte quantity without an escape value.  Lengths greater
19207    than 2^32 aren't very common which means that the initial 4 bytes
19208    is almost always zero.  Since a length value of zero doesn't make
19209    sense for the 32-bit format, this initial zero can be considered to
19210    be an escape value which indicates the presence of the older 64-bit
19211    format.  As written, the code can't detect (old format) lengths
19212    greater than 4GB.  If it becomes necessary to handle lengths
19213    somewhat larger than 4GB, we could allow other small values (such
19214    as the non-sensical values of 1, 2, and 3) to also be used as
19215    escape values indicating the presence of the old format.
19216
19217    The value returned via bytes_read should be used to increment the
19218    relevant pointer after calling read_initial_length().
19219
19220    [ Note:  read_initial_length() and read_offset() are based on the
19221      document entitled "DWARF Debugging Information Format", revision
19222      3, draft 8, dated November 19, 2001.  This document was obtained
19223      from:
19224
19225         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19226
19227      This document is only a draft and is subject to change.  (So beware.)
19228
19229      Details regarding the older, non-standard 64-bit format were
19230      determined empirically by examining 64-bit ELF files produced by
19231      the SGI toolchain on an IRIX 6.5 machine.
19232
19233      - Kevin, July 16, 2002
19234    ] */
19235
19236 static LONGEST
19237 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19238 {
19239   LONGEST length = bfd_get_32 (abfd, buf);
19240
19241   if (length == 0xffffffff)
19242     {
19243       length = bfd_get_64 (abfd, buf + 4);
19244       *bytes_read = 12;
19245     }
19246   else if (length == 0)
19247     {
19248       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19249       length = bfd_get_64 (abfd, buf);
19250       *bytes_read = 8;
19251     }
19252   else
19253     {
19254       *bytes_read = 4;
19255     }
19256
19257   return length;
19258 }
19259
19260 /* Cover function for read_initial_length.
19261    Returns the length of the object at BUF, and stores the size of the
19262    initial length in *BYTES_READ and stores the size that offsets will be in
19263    *OFFSET_SIZE.
19264    If the initial length size is not equivalent to that specified in
19265    CU_HEADER then issue a complaint.
19266    This is useful when reading non-comp-unit headers.  */
19267
19268 static LONGEST
19269 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19270                                         const struct comp_unit_head *cu_header,
19271                                         unsigned int *bytes_read,
19272                                         unsigned int *offset_size)
19273 {
19274   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19275
19276   gdb_assert (cu_header->initial_length_size == 4
19277               || cu_header->initial_length_size == 8
19278               || cu_header->initial_length_size == 12);
19279
19280   if (cu_header->initial_length_size != *bytes_read)
19281     complaint (&symfile_complaints,
19282                _("intermixed 32-bit and 64-bit DWARF sections"));
19283
19284   *offset_size = (*bytes_read == 4) ? 4 : 8;
19285   return length;
19286 }
19287
19288 /* Read an offset from the data stream.  The size of the offset is
19289    given by cu_header->offset_size.  */
19290
19291 static LONGEST
19292 read_offset (bfd *abfd, const gdb_byte *buf,
19293              const struct comp_unit_head *cu_header,
19294              unsigned int *bytes_read)
19295 {
19296   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19297
19298   *bytes_read = cu_header->offset_size;
19299   return offset;
19300 }
19301
19302 /* Read an offset from the data stream.  */
19303
19304 static LONGEST
19305 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19306 {
19307   LONGEST retval = 0;
19308
19309   switch (offset_size)
19310     {
19311     case 4:
19312       retval = bfd_get_32 (abfd, buf);
19313       break;
19314     case 8:
19315       retval = bfd_get_64 (abfd, buf);
19316       break;
19317     default:
19318       internal_error (__FILE__, __LINE__,
19319                       _("read_offset_1: bad switch [in module %s]"),
19320                       bfd_get_filename (abfd));
19321     }
19322
19323   return retval;
19324 }
19325
19326 static const gdb_byte *
19327 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19328 {
19329   /* If the size of a host char is 8 bits, we can return a pointer
19330      to the buffer, otherwise we have to copy the data to a buffer
19331      allocated on the temporary obstack.  */
19332   gdb_assert (HOST_CHAR_BIT == 8);
19333   return buf;
19334 }
19335
19336 static const char *
19337 read_direct_string (bfd *abfd, const gdb_byte *buf,
19338                     unsigned int *bytes_read_ptr)
19339 {
19340   /* If the size of a host char is 8 bits, we can return a pointer
19341      to the string, otherwise we have to copy the string to a buffer
19342      allocated on the temporary obstack.  */
19343   gdb_assert (HOST_CHAR_BIT == 8);
19344   if (*buf == '\0')
19345     {
19346       *bytes_read_ptr = 1;
19347       return NULL;
19348     }
19349   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19350   return (const char *) buf;
19351 }
19352
19353 /* Return pointer to string at section SECT offset STR_OFFSET with error
19354    reporting strings FORM_NAME and SECT_NAME.  */
19355
19356 static const char *
19357 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
19358                                      struct dwarf2_section_info *sect,
19359                                      const char *form_name,
19360                                      const char *sect_name)
19361 {
19362   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
19363   if (sect->buffer == NULL)
19364     error (_("%s used without %s section [in module %s]"),
19365            form_name, sect_name, bfd_get_filename (abfd));
19366   if (str_offset >= sect->size)
19367     error (_("%s pointing outside of %s section [in module %s]"),
19368            form_name, sect_name, bfd_get_filename (abfd));
19369   gdb_assert (HOST_CHAR_BIT == 8);
19370   if (sect->buffer[str_offset] == '\0')
19371     return NULL;
19372   return (const char *) (sect->buffer + str_offset);
19373 }
19374
19375 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19376
19377 static const char *
19378 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
19379 {
19380   return read_indirect_string_at_offset_from (abfd, str_offset,
19381                                               &dwarf2_per_objfile->str,
19382                                               "DW_FORM_strp", ".debug_str");
19383 }
19384
19385 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19386
19387 static const char *
19388 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
19389 {
19390   return read_indirect_string_at_offset_from (abfd, str_offset,
19391                                               &dwarf2_per_objfile->line_str,
19392                                               "DW_FORM_line_strp",
19393                                               ".debug_line_str");
19394 }
19395
19396 /* Read a string at offset STR_OFFSET in the .debug_str section from
19397    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19398    the string consists of a single NUL byte, return NULL; otherwise
19399    return a pointer to the string.  */
19400
19401 static const char *
19402 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
19403 {
19404   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
19405
19406   if (dwz->str.buffer == NULL)
19407     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19408              "section [in module %s]"),
19409            bfd_get_filename (dwz->dwz_bfd));
19410   if (str_offset >= dwz->str.size)
19411     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19412              ".debug_str section [in module %s]"),
19413            bfd_get_filename (dwz->dwz_bfd));
19414   gdb_assert (HOST_CHAR_BIT == 8);
19415   if (dwz->str.buffer[str_offset] == '\0')
19416     return NULL;
19417   return (const char *) (dwz->str.buffer + str_offset);
19418 }
19419
19420 /* Return pointer to string at .debug_str offset as read from BUF.
19421    BUF is assumed to be in a compilation unit described by CU_HEADER.
19422    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19423
19424 static const char *
19425 read_indirect_string (bfd *abfd, const gdb_byte *buf,
19426                       const struct comp_unit_head *cu_header,
19427                       unsigned int *bytes_read_ptr)
19428 {
19429   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19430
19431   return read_indirect_string_at_offset (abfd, str_offset);
19432 }
19433
19434 /* Return pointer to string at .debug_line_str offset as read from BUF.
19435    BUF is assumed to be in a compilation unit described by CU_HEADER.
19436    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19437
19438 static const char *
19439 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
19440                            const struct comp_unit_head *cu_header,
19441                            unsigned int *bytes_read_ptr)
19442 {
19443   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19444
19445   return read_indirect_line_string_at_offset (abfd, str_offset);
19446 }
19447
19448 ULONGEST
19449 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19450                           unsigned int *bytes_read_ptr)
19451 {
19452   ULONGEST result;
19453   unsigned int num_read;
19454   int shift;
19455   unsigned char byte;
19456
19457   result = 0;
19458   shift = 0;
19459   num_read = 0;
19460   while (1)
19461     {
19462       byte = bfd_get_8 (abfd, buf);
19463       buf++;
19464       num_read++;
19465       result |= ((ULONGEST) (byte & 127) << shift);
19466       if ((byte & 128) == 0)
19467         {
19468           break;
19469         }
19470       shift += 7;
19471     }
19472   *bytes_read_ptr = num_read;
19473   return result;
19474 }
19475
19476 static LONGEST
19477 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19478                     unsigned int *bytes_read_ptr)
19479 {
19480   LONGEST result;
19481   int shift, num_read;
19482   unsigned char byte;
19483
19484   result = 0;
19485   shift = 0;
19486   num_read = 0;
19487   while (1)
19488     {
19489       byte = bfd_get_8 (abfd, buf);
19490       buf++;
19491       num_read++;
19492       result |= ((LONGEST) (byte & 127) << shift);
19493       shift += 7;
19494       if ((byte & 128) == 0)
19495         {
19496           break;
19497         }
19498     }
19499   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19500     result |= -(((LONGEST) 1) << shift);
19501   *bytes_read_ptr = num_read;
19502   return result;
19503 }
19504
19505 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19506    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19507    ADDR_SIZE is the size of addresses from the CU header.  */
19508
19509 static CORE_ADDR
19510 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
19511 {
19512   struct objfile *objfile = dwarf2_per_objfile->objfile;
19513   bfd *abfd = objfile->obfd;
19514   const gdb_byte *info_ptr;
19515
19516   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19517   if (dwarf2_per_objfile->addr.buffer == NULL)
19518     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19519            objfile_name (objfile));
19520   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19521     error (_("DW_FORM_addr_index pointing outside of "
19522              ".debug_addr section [in module %s]"),
19523            objfile_name (objfile));
19524   info_ptr = (dwarf2_per_objfile->addr.buffer
19525               + addr_base + addr_index * addr_size);
19526   if (addr_size == 4)
19527     return bfd_get_32 (abfd, info_ptr);
19528   else
19529     return bfd_get_64 (abfd, info_ptr);
19530 }
19531
19532 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19533
19534 static CORE_ADDR
19535 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19536 {
19537   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
19538 }
19539
19540 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19541
19542 static CORE_ADDR
19543 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19544                              unsigned int *bytes_read)
19545 {
19546   bfd *abfd = cu->objfile->obfd;
19547   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19548
19549   return read_addr_index (cu, addr_index);
19550 }
19551
19552 /* Data structure to pass results from dwarf2_read_addr_index_reader
19553    back to dwarf2_read_addr_index.  */
19554
19555 struct dwarf2_read_addr_index_data
19556 {
19557   ULONGEST addr_base;
19558   int addr_size;
19559 };
19560
19561 /* die_reader_func for dwarf2_read_addr_index.  */
19562
19563 static void
19564 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19565                                const gdb_byte *info_ptr,
19566                                struct die_info *comp_unit_die,
19567                                int has_children,
19568                                void *data)
19569 {
19570   struct dwarf2_cu *cu = reader->cu;
19571   struct dwarf2_read_addr_index_data *aidata =
19572     (struct dwarf2_read_addr_index_data *) data;
19573
19574   aidata->addr_base = cu->addr_base;
19575   aidata->addr_size = cu->header.addr_size;
19576 }
19577
19578 /* Given an index in .debug_addr, fetch the value.
19579    NOTE: This can be called during dwarf expression evaluation,
19580    long after the debug information has been read, and thus per_cu->cu
19581    may no longer exist.  */
19582
19583 CORE_ADDR
19584 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19585                         unsigned int addr_index)
19586 {
19587   struct objfile *objfile = per_cu->objfile;
19588   struct dwarf2_cu *cu = per_cu->cu;
19589   ULONGEST addr_base;
19590   int addr_size;
19591
19592   /* This is intended to be called from outside this file.  */
19593   dw2_setup (objfile);
19594
19595   /* We need addr_base and addr_size.
19596      If we don't have PER_CU->cu, we have to get it.
19597      Nasty, but the alternative is storing the needed info in PER_CU,
19598      which at this point doesn't seem justified: it's not clear how frequently
19599      it would get used and it would increase the size of every PER_CU.
19600      Entry points like dwarf2_per_cu_addr_size do a similar thing
19601      so we're not in uncharted territory here.
19602      Alas we need to be a bit more complicated as addr_base is contained
19603      in the DIE.
19604
19605      We don't need to read the entire CU(/TU).
19606      We just need the header and top level die.
19607
19608      IWBN to use the aging mechanism to let us lazily later discard the CU.
19609      For now we skip this optimization.  */
19610
19611   if (cu != NULL)
19612     {
19613       addr_base = cu->addr_base;
19614       addr_size = cu->header.addr_size;
19615     }
19616   else
19617     {
19618       struct dwarf2_read_addr_index_data aidata;
19619
19620       /* Note: We can't use init_cutu_and_read_dies_simple here,
19621          we need addr_base.  */
19622       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19623                                dwarf2_read_addr_index_reader, &aidata);
19624       addr_base = aidata.addr_base;
19625       addr_size = aidata.addr_size;
19626     }
19627
19628   return read_addr_index_1 (addr_index, addr_base, addr_size);
19629 }
19630
19631 /* Given a DW_FORM_GNU_str_index, fetch the string.
19632    This is only used by the Fission support.  */
19633
19634 static const char *
19635 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19636 {
19637   struct objfile *objfile = dwarf2_per_objfile->objfile;
19638   const char *objf_name = objfile_name (objfile);
19639   bfd *abfd = objfile->obfd;
19640   struct dwarf2_cu *cu = reader->cu;
19641   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19642   struct dwarf2_section_info *str_offsets_section =
19643     &reader->dwo_file->sections.str_offsets;
19644   const gdb_byte *info_ptr;
19645   ULONGEST str_offset;
19646   static const char form_name[] = "DW_FORM_GNU_str_index";
19647
19648   dwarf2_read_section (objfile, str_section);
19649   dwarf2_read_section (objfile, str_offsets_section);
19650   if (str_section->buffer == NULL)
19651     error (_("%s used without .debug_str.dwo section"
19652              " in CU at offset 0x%x [in module %s]"),
19653            form_name, to_underlying (cu->header.sect_off), objf_name);
19654   if (str_offsets_section->buffer == NULL)
19655     error (_("%s used without .debug_str_offsets.dwo section"
19656              " in CU at offset 0x%x [in module %s]"),
19657            form_name, to_underlying (cu->header.sect_off), objf_name);
19658   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19659     error (_("%s pointing outside of .debug_str_offsets.dwo"
19660              " section in CU at offset 0x%x [in module %s]"),
19661            form_name, to_underlying (cu->header.sect_off), objf_name);
19662   info_ptr = (str_offsets_section->buffer
19663               + str_index * cu->header.offset_size);
19664   if (cu->header.offset_size == 4)
19665     str_offset = bfd_get_32 (abfd, info_ptr);
19666   else
19667     str_offset = bfd_get_64 (abfd, info_ptr);
19668   if (str_offset >= str_section->size)
19669     error (_("Offset from %s pointing outside of"
19670              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19671            form_name, to_underlying (cu->header.sect_off), objf_name);
19672   return (const char *) (str_section->buffer + str_offset);
19673 }
19674
19675 /* Return the length of an LEB128 number in BUF.  */
19676
19677 static int
19678 leb128_size (const gdb_byte *buf)
19679 {
19680   const gdb_byte *begin = buf;
19681   gdb_byte byte;
19682
19683   while (1)
19684     {
19685       byte = *buf++;
19686       if ((byte & 128) == 0)
19687         return buf - begin;
19688     }
19689 }
19690
19691 static void
19692 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19693 {
19694   switch (lang)
19695     {
19696     case DW_LANG_C89:
19697     case DW_LANG_C99:
19698     case DW_LANG_C11:
19699     case DW_LANG_C:
19700     case DW_LANG_UPC:
19701       cu->language = language_c;
19702       break;
19703     case DW_LANG_Java:
19704     case DW_LANG_C_plus_plus:
19705     case DW_LANG_C_plus_plus_11:
19706     case DW_LANG_C_plus_plus_14:
19707       cu->language = language_cplus;
19708       break;
19709     case DW_LANG_D:
19710       cu->language = language_d;
19711       break;
19712     case DW_LANG_Fortran77:
19713     case DW_LANG_Fortran90:
19714     case DW_LANG_Fortran95:
19715     case DW_LANG_Fortran03:
19716     case DW_LANG_Fortran08:
19717       cu->language = language_fortran;
19718       break;
19719     case DW_LANG_Go:
19720       cu->language = language_go;
19721       break;
19722     case DW_LANG_Mips_Assembler:
19723       cu->language = language_asm;
19724       break;
19725     case DW_LANG_Ada83:
19726     case DW_LANG_Ada95:
19727       cu->language = language_ada;
19728       break;
19729     case DW_LANG_Modula2:
19730       cu->language = language_m2;
19731       break;
19732     case DW_LANG_Pascal83:
19733       cu->language = language_pascal;
19734       break;
19735     case DW_LANG_ObjC:
19736       cu->language = language_objc;
19737       break;
19738     case DW_LANG_Rust:
19739     case DW_LANG_Rust_old:
19740       cu->language = language_rust;
19741       break;
19742     case DW_LANG_Cobol74:
19743     case DW_LANG_Cobol85:
19744     default:
19745       cu->language = language_minimal;
19746       break;
19747     }
19748   cu->language_defn = language_def (cu->language);
19749 }
19750
19751 /* Return the named attribute or NULL if not there.  */
19752
19753 static struct attribute *
19754 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19755 {
19756   for (;;)
19757     {
19758       unsigned int i;
19759       struct attribute *spec = NULL;
19760
19761       for (i = 0; i < die->num_attrs; ++i)
19762         {
19763           if (die->attrs[i].name == name)
19764             return &die->attrs[i];
19765           if (die->attrs[i].name == DW_AT_specification
19766               || die->attrs[i].name == DW_AT_abstract_origin)
19767             spec = &die->attrs[i];
19768         }
19769
19770       if (!spec)
19771         break;
19772
19773       die = follow_die_ref (die, spec, &cu);
19774     }
19775
19776   return NULL;
19777 }
19778
19779 /* Return the named attribute or NULL if not there,
19780    but do not follow DW_AT_specification, etc.
19781    This is for use in contexts where we're reading .debug_types dies.
19782    Following DW_AT_specification, DW_AT_abstract_origin will take us
19783    back up the chain, and we want to go down.  */
19784
19785 static struct attribute *
19786 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19787 {
19788   unsigned int i;
19789
19790   for (i = 0; i < die->num_attrs; ++i)
19791     if (die->attrs[i].name == name)
19792       return &die->attrs[i];
19793
19794   return NULL;
19795 }
19796
19797 /* Return the string associated with a string-typed attribute, or NULL if it
19798    is either not found or is of an incorrect type.  */
19799
19800 static const char *
19801 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19802 {
19803   struct attribute *attr;
19804   const char *str = NULL;
19805
19806   attr = dwarf2_attr (die, name, cu);
19807
19808   if (attr != NULL)
19809     {
19810       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19811           || attr->form == DW_FORM_string
19812           || attr->form == DW_FORM_GNU_str_index
19813           || attr->form == DW_FORM_GNU_strp_alt)
19814         str = DW_STRING (attr);
19815       else
19816         complaint (&symfile_complaints,
19817                    _("string type expected for attribute %s for "
19818                      "DIE at 0x%x in module %s"),
19819                    dwarf_attr_name (name), to_underlying (die->sect_off),
19820                    objfile_name (cu->objfile));
19821     }
19822
19823   return str;
19824 }
19825
19826 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19827    and holds a non-zero value.  This function should only be used for
19828    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19829
19830 static int
19831 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19832 {
19833   struct attribute *attr = dwarf2_attr (die, name, cu);
19834
19835   return (attr && DW_UNSND (attr));
19836 }
19837
19838 static int
19839 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19840 {
19841   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19842      which value is non-zero.  However, we have to be careful with
19843      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19844      (via dwarf2_flag_true_p) follows this attribute.  So we may
19845      end up accidently finding a declaration attribute that belongs
19846      to a different DIE referenced by the specification attribute,
19847      even though the given DIE does not have a declaration attribute.  */
19848   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19849           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19850 }
19851
19852 /* Return the die giving the specification for DIE, if there is
19853    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19854    containing the return value on output.  If there is no
19855    specification, but there is an abstract origin, that is
19856    returned.  */
19857
19858 static struct die_info *
19859 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19860 {
19861   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19862                                              *spec_cu);
19863
19864   if (spec_attr == NULL)
19865     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19866
19867   if (spec_attr == NULL)
19868     return NULL;
19869   else
19870     return follow_die_ref (die, spec_attr, spec_cu);
19871 }
19872
19873 /* Stub for free_line_header to match void * callback types.  */
19874
19875 static void
19876 free_line_header_voidp (void *arg)
19877 {
19878   struct line_header *lh = (struct line_header *) arg;
19879
19880   delete lh;
19881 }
19882
19883 void
19884 line_header::add_include_dir (const char *include_dir)
19885 {
19886   if (dwarf_line_debug >= 2)
19887     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19888                         include_dirs.size () + 1, include_dir);
19889
19890   include_dirs.push_back (include_dir);
19891 }
19892
19893 void
19894 line_header::add_file_name (const char *name,
19895                             dir_index d_index,
19896                             unsigned int mod_time,
19897                             unsigned int length)
19898 {
19899   if (dwarf_line_debug >= 2)
19900     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19901                         (unsigned) file_names.size () + 1, name);
19902
19903   file_names.emplace_back (name, d_index, mod_time, length);
19904 }
19905
19906 /* A convenience function to find the proper .debug_line section for a CU.  */
19907
19908 static struct dwarf2_section_info *
19909 get_debug_line_section (struct dwarf2_cu *cu)
19910 {
19911   struct dwarf2_section_info *section;
19912
19913   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19914      DWO file.  */
19915   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19916     section = &cu->dwo_unit->dwo_file->sections.line;
19917   else if (cu->per_cu->is_dwz)
19918     {
19919       struct dwz_file *dwz = dwarf2_get_dwz_file ();
19920
19921       section = &dwz->line;
19922     }
19923   else
19924     section = &dwarf2_per_objfile->line;
19925
19926   return section;
19927 }
19928
19929 /* Read directory or file name entry format, starting with byte of
19930    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19931    entries count and the entries themselves in the described entry
19932    format.  */
19933
19934 static void
19935 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
19936                         struct line_header *lh,
19937                         const struct comp_unit_head *cu_header,
19938                         void (*callback) (struct line_header *lh,
19939                                           const char *name,
19940                                           dir_index d_index,
19941                                           unsigned int mod_time,
19942                                           unsigned int length))
19943 {
19944   gdb_byte format_count, formati;
19945   ULONGEST data_count, datai;
19946   const gdb_byte *buf = *bufp;
19947   const gdb_byte *format_header_data;
19948   unsigned int bytes_read;
19949
19950   format_count = read_1_byte (abfd, buf);
19951   buf += 1;
19952   format_header_data = buf;
19953   for (formati = 0; formati < format_count; formati++)
19954     {
19955       read_unsigned_leb128 (abfd, buf, &bytes_read);
19956       buf += bytes_read;
19957       read_unsigned_leb128 (abfd, buf, &bytes_read);
19958       buf += bytes_read;
19959     }
19960
19961   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19962   buf += bytes_read;
19963   for (datai = 0; datai < data_count; datai++)
19964     {
19965       const gdb_byte *format = format_header_data;
19966       struct file_entry fe;
19967
19968       for (formati = 0; formati < format_count; formati++)
19969         {
19970           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19971           format += bytes_read;
19972
19973           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19974           format += bytes_read;
19975
19976           gdb::optional<const char *> string;
19977           gdb::optional<unsigned int> uint;
19978
19979           switch (form)
19980             {
19981             case DW_FORM_string:
19982               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19983               buf += bytes_read;
19984               break;
19985
19986             case DW_FORM_line_strp:
19987               string.emplace (read_indirect_line_string (abfd, buf,
19988                                                          cu_header,
19989                                                          &bytes_read));
19990               buf += bytes_read;
19991               break;
19992
19993             case DW_FORM_data1:
19994               uint.emplace (read_1_byte (abfd, buf));
19995               buf += 1;
19996               break;
19997
19998             case DW_FORM_data2:
19999               uint.emplace (read_2_bytes (abfd, buf));
20000               buf += 2;
20001               break;
20002
20003             case DW_FORM_data4:
20004               uint.emplace (read_4_bytes (abfd, buf));
20005               buf += 4;
20006               break;
20007
20008             case DW_FORM_data8:
20009               uint.emplace (read_8_bytes (abfd, buf));
20010               buf += 8;
20011               break;
20012
20013             case DW_FORM_udata:
20014               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20015               buf += bytes_read;
20016               break;
20017
20018             case DW_FORM_block:
20019               /* It is valid only for DW_LNCT_timestamp which is ignored by
20020                  current GDB.  */
20021               break;
20022             }
20023
20024           switch (content_type)
20025             {
20026             case DW_LNCT_path:
20027               if (string.has_value ())
20028                 fe.name = *string;
20029               break;
20030             case DW_LNCT_directory_index:
20031               if (uint.has_value ())
20032                 fe.d_index = (dir_index) *uint;
20033               break;
20034             case DW_LNCT_timestamp:
20035               if (uint.has_value ())
20036                 fe.mod_time = *uint;
20037               break;
20038             case DW_LNCT_size:
20039               if (uint.has_value ())
20040                 fe.length = *uint;
20041               break;
20042             case DW_LNCT_MD5:
20043               break;
20044             default:
20045               complaint (&symfile_complaints,
20046                          _("Unknown format content type %s"),
20047                          pulongest (content_type));
20048             }
20049         }
20050
20051       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20052     }
20053
20054   *bufp = buf;
20055 }
20056
20057 /* Read the statement program header starting at OFFSET in
20058    .debug_line, or .debug_line.dwo.  Return a pointer
20059    to a struct line_header, allocated using xmalloc.
20060    Returns NULL if there is a problem reading the header, e.g., if it
20061    has a version we don't understand.
20062
20063    NOTE: the strings in the include directory and file name tables of
20064    the returned object point into the dwarf line section buffer,
20065    and must not be freed.  */
20066
20067 static line_header_up
20068 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20069 {
20070   const gdb_byte *line_ptr;
20071   unsigned int bytes_read, offset_size;
20072   int i;
20073   const char *cur_dir, *cur_file;
20074   struct dwarf2_section_info *section;
20075   bfd *abfd;
20076
20077   section = get_debug_line_section (cu);
20078   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20079   if (section->buffer == NULL)
20080     {
20081       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20082         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20083       else
20084         complaint (&symfile_complaints, _("missing .debug_line section"));
20085       return 0;
20086     }
20087
20088   /* We can't do this until we know the section is non-empty.
20089      Only then do we know we have such a section.  */
20090   abfd = get_section_bfd_owner (section);
20091
20092   /* Make sure that at least there's room for the total_length field.
20093      That could be 12 bytes long, but we're just going to fudge that.  */
20094   if (to_underlying (sect_off) + 4 >= section->size)
20095     {
20096       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20097       return 0;
20098     }
20099
20100   line_header_up lh (new line_header ());
20101
20102   lh->sect_off = sect_off;
20103   lh->offset_in_dwz = cu->per_cu->is_dwz;
20104
20105   line_ptr = section->buffer + to_underlying (sect_off);
20106
20107   /* Read in the header.  */
20108   lh->total_length =
20109     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20110                                             &bytes_read, &offset_size);
20111   line_ptr += bytes_read;
20112   if (line_ptr + lh->total_length > (section->buffer + section->size))
20113     {
20114       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20115       return 0;
20116     }
20117   lh->statement_program_end = line_ptr + lh->total_length;
20118   lh->version = read_2_bytes (abfd, line_ptr);
20119   line_ptr += 2;
20120   if (lh->version > 5)
20121     {
20122       /* This is a version we don't understand.  The format could have
20123          changed in ways we don't handle properly so just punt.  */
20124       complaint (&symfile_complaints,
20125                  _("unsupported version in .debug_line section"));
20126       return NULL;
20127     }
20128   if (lh->version >= 5)
20129     {
20130       gdb_byte segment_selector_size;
20131
20132       /* Skip address size.  */
20133       read_1_byte (abfd, line_ptr);
20134       line_ptr += 1;
20135
20136       segment_selector_size = read_1_byte (abfd, line_ptr);
20137       line_ptr += 1;
20138       if (segment_selector_size != 0)
20139         {
20140           complaint (&symfile_complaints,
20141                      _("unsupported segment selector size %u "
20142                        "in .debug_line section"),
20143                      segment_selector_size);
20144           return NULL;
20145         }
20146     }
20147   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20148   line_ptr += offset_size;
20149   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20150   line_ptr += 1;
20151   if (lh->version >= 4)
20152     {
20153       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20154       line_ptr += 1;
20155     }
20156   else
20157     lh->maximum_ops_per_instruction = 1;
20158
20159   if (lh->maximum_ops_per_instruction == 0)
20160     {
20161       lh->maximum_ops_per_instruction = 1;
20162       complaint (&symfile_complaints,
20163                  _("invalid maximum_ops_per_instruction "
20164                    "in `.debug_line' section"));
20165     }
20166
20167   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20168   line_ptr += 1;
20169   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20170   line_ptr += 1;
20171   lh->line_range = read_1_byte (abfd, line_ptr);
20172   line_ptr += 1;
20173   lh->opcode_base = read_1_byte (abfd, line_ptr);
20174   line_ptr += 1;
20175   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20176
20177   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20178   for (i = 1; i < lh->opcode_base; ++i)
20179     {
20180       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20181       line_ptr += 1;
20182     }
20183
20184   if (lh->version >= 5)
20185     {
20186       /* Read directory table.  */
20187       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
20188                               [] (struct line_header *lh, const char *name,
20189                                   dir_index d_index, unsigned int mod_time,
20190                                   unsigned int length)
20191         {
20192           lh->add_include_dir (name);
20193         });
20194
20195       /* Read file name table.  */
20196       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
20197                               [] (struct line_header *lh, const char *name,
20198                                   dir_index d_index, unsigned int mod_time,
20199                                   unsigned int length)
20200         {
20201           lh->add_file_name (name, d_index, mod_time, length);
20202         });
20203     }
20204   else
20205     {
20206       /* Read directory table.  */
20207       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20208         {
20209           line_ptr += bytes_read;
20210           lh->add_include_dir (cur_dir);
20211         }
20212       line_ptr += bytes_read;
20213
20214       /* Read file name table.  */
20215       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20216         {
20217           unsigned int mod_time, length;
20218           dir_index d_index;
20219
20220           line_ptr += bytes_read;
20221           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20222           line_ptr += bytes_read;
20223           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20224           line_ptr += bytes_read;
20225           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20226           line_ptr += bytes_read;
20227
20228           lh->add_file_name (cur_file, d_index, mod_time, length);
20229         }
20230       line_ptr += bytes_read;
20231     }
20232   lh->statement_program_start = line_ptr;
20233
20234   if (line_ptr > (section->buffer + section->size))
20235     complaint (&symfile_complaints,
20236                _("line number info header doesn't "
20237                  "fit in `.debug_line' section"));
20238
20239   return lh;
20240 }
20241
20242 /* Subroutine of dwarf_decode_lines to simplify it.
20243    Return the file name of the psymtab for included file FILE_INDEX
20244    in line header LH of PST.
20245    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20246    If space for the result is malloc'd, it will be freed by a cleanup.
20247    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
20248
20249    The function creates dangling cleanup registration.  */
20250
20251 static const char *
20252 psymtab_include_file_name (const struct line_header *lh, int file_index,
20253                            const struct partial_symtab *pst,
20254                            const char *comp_dir)
20255 {
20256   const file_entry &fe = lh->file_names[file_index];
20257   const char *include_name = fe.name;
20258   const char *include_name_to_compare = include_name;
20259   const char *pst_filename;
20260   char *copied_name = NULL;
20261   int file_is_pst;
20262
20263   const char *dir_name = fe.include_dir (lh);
20264
20265   if (!IS_ABSOLUTE_PATH (include_name)
20266       && (dir_name != NULL || comp_dir != NULL))
20267     {
20268       /* Avoid creating a duplicate psymtab for PST.
20269          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20270          Before we do the comparison, however, we need to account
20271          for DIR_NAME and COMP_DIR.
20272          First prepend dir_name (if non-NULL).  If we still don't
20273          have an absolute path prepend comp_dir (if non-NULL).
20274          However, the directory we record in the include-file's
20275          psymtab does not contain COMP_DIR (to match the
20276          corresponding symtab(s)).
20277
20278          Example:
20279
20280          bash$ cd /tmp
20281          bash$ gcc -g ./hello.c
20282          include_name = "hello.c"
20283          dir_name = "."
20284          DW_AT_comp_dir = comp_dir = "/tmp"
20285          DW_AT_name = "./hello.c"
20286
20287       */
20288
20289       if (dir_name != NULL)
20290         {
20291           char *tem = concat (dir_name, SLASH_STRING,
20292                               include_name, (char *)NULL);
20293
20294           make_cleanup (xfree, tem);
20295           include_name = tem;
20296           include_name_to_compare = include_name;
20297         }
20298       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20299         {
20300           char *tem = concat (comp_dir, SLASH_STRING,
20301                               include_name, (char *)NULL);
20302
20303           make_cleanup (xfree, tem);
20304           include_name_to_compare = tem;
20305         }
20306     }
20307
20308   pst_filename = pst->filename;
20309   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20310     {
20311       copied_name = concat (pst->dirname, SLASH_STRING,
20312                             pst_filename, (char *)NULL);
20313       pst_filename = copied_name;
20314     }
20315
20316   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20317
20318   if (copied_name != NULL)
20319     xfree (copied_name);
20320
20321   if (file_is_pst)
20322     return NULL;
20323   return include_name;
20324 }
20325
20326 /* State machine to track the state of the line number program.  */
20327
20328 class lnp_state_machine
20329 {
20330 public:
20331   /* Initialize a machine state for the start of a line number
20332      program.  */
20333   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20334
20335   file_entry *current_file ()
20336   {
20337     /* lh->file_names is 0-based, but the file name numbers in the
20338        statement program are 1-based.  */
20339     return m_line_header->file_name_at (m_file);
20340   }
20341
20342   /* Record the line in the state machine.  END_SEQUENCE is true if
20343      we're processing the end of a sequence.  */
20344   void record_line (bool end_sequence);
20345
20346   /* Check address and if invalid nop-out the rest of the lines in this
20347      sequence.  */
20348   void check_line_address (struct dwarf2_cu *cu,
20349                            const gdb_byte *line_ptr,
20350                            CORE_ADDR lowpc, CORE_ADDR address);
20351
20352   void handle_set_discriminator (unsigned int discriminator)
20353   {
20354     m_discriminator = discriminator;
20355     m_line_has_non_zero_discriminator |= discriminator != 0;
20356   }
20357
20358   /* Handle DW_LNE_set_address.  */
20359   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20360   {
20361     m_op_index = 0;
20362     address += baseaddr;
20363     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20364   }
20365
20366   /* Handle DW_LNS_advance_pc.  */
20367   void handle_advance_pc (CORE_ADDR adjust);
20368
20369   /* Handle a special opcode.  */
20370   void handle_special_opcode (unsigned char op_code);
20371
20372   /* Handle DW_LNS_advance_line.  */
20373   void handle_advance_line (int line_delta)
20374   {
20375     advance_line (line_delta);
20376   }
20377
20378   /* Handle DW_LNS_set_file.  */
20379   void handle_set_file (file_name_index file);
20380
20381   /* Handle DW_LNS_negate_stmt.  */
20382   void handle_negate_stmt ()
20383   {
20384     m_is_stmt = !m_is_stmt;
20385   }
20386
20387   /* Handle DW_LNS_const_add_pc.  */
20388   void handle_const_add_pc ();
20389
20390   /* Handle DW_LNS_fixed_advance_pc.  */
20391   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20392   {
20393     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20394     m_op_index = 0;
20395   }
20396
20397   /* Handle DW_LNS_copy.  */
20398   void handle_copy ()
20399   {
20400     record_line (false);
20401     m_discriminator = 0;
20402   }
20403
20404   /* Handle DW_LNE_end_sequence.  */
20405   void handle_end_sequence ()
20406   {
20407     m_record_line_callback = ::record_line;
20408   }
20409
20410 private:
20411   /* Advance the line by LINE_DELTA.  */
20412   void advance_line (int line_delta)
20413   {
20414     m_line += line_delta;
20415
20416     if (line_delta != 0)
20417       m_line_has_non_zero_discriminator = m_discriminator != 0;
20418   }
20419
20420   gdbarch *m_gdbarch;
20421
20422   /* True if we're recording lines.
20423      Otherwise we're building partial symtabs and are just interested in
20424      finding include files mentioned by the line number program.  */
20425   bool m_record_lines_p;
20426
20427   /* The line number header.  */
20428   line_header *m_line_header;
20429
20430   /* These are part of the standard DWARF line number state machine,
20431      and initialized according to the DWARF spec.  */
20432
20433   unsigned char m_op_index = 0;
20434   /* The line table index (1-based) of the current file.  */
20435   file_name_index m_file = (file_name_index) 1;
20436   unsigned int m_line = 1;
20437
20438   /* These are initialized in the constructor.  */
20439
20440   CORE_ADDR m_address;
20441   bool m_is_stmt;
20442   unsigned int m_discriminator;
20443
20444   /* Additional bits of state we need to track.  */
20445
20446   /* The last file that we called dwarf2_start_subfile for.
20447      This is only used for TLLs.  */
20448   unsigned int m_last_file = 0;
20449   /* The last file a line number was recorded for.  */
20450   struct subfile *m_last_subfile = NULL;
20451
20452   /* The function to call to record a line.  */
20453   record_line_ftype *m_record_line_callback = NULL;
20454
20455   /* The last line number that was recorded, used to coalesce
20456      consecutive entries for the same line.  This can happen, for
20457      example, when discriminators are present.  PR 17276.  */
20458   unsigned int m_last_line = 0;
20459   bool m_line_has_non_zero_discriminator = false;
20460 };
20461
20462 void
20463 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20464 {
20465   CORE_ADDR addr_adj = (((m_op_index + adjust)
20466                          / m_line_header->maximum_ops_per_instruction)
20467                         * m_line_header->minimum_instruction_length);
20468   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20469   m_op_index = ((m_op_index + adjust)
20470                 % m_line_header->maximum_ops_per_instruction);
20471 }
20472
20473 void
20474 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20475 {
20476   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20477   CORE_ADDR addr_adj = (((m_op_index
20478                           + (adj_opcode / m_line_header->line_range))
20479                          / m_line_header->maximum_ops_per_instruction)
20480                         * m_line_header->minimum_instruction_length);
20481   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20482   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20483                 % m_line_header->maximum_ops_per_instruction);
20484
20485   int line_delta = (m_line_header->line_base
20486                     + (adj_opcode % m_line_header->line_range));
20487   advance_line (line_delta);
20488   record_line (false);
20489   m_discriminator = 0;
20490 }
20491
20492 void
20493 lnp_state_machine::handle_set_file (file_name_index file)
20494 {
20495   m_file = file;
20496
20497   const file_entry *fe = current_file ();
20498   if (fe == NULL)
20499     dwarf2_debug_line_missing_file_complaint ();
20500   else if (m_record_lines_p)
20501     {
20502       const char *dir = fe->include_dir (m_line_header);
20503
20504       m_last_subfile = current_subfile;
20505       m_line_has_non_zero_discriminator = m_discriminator != 0;
20506       dwarf2_start_subfile (fe->name, dir);
20507     }
20508 }
20509
20510 void
20511 lnp_state_machine::handle_const_add_pc ()
20512 {
20513   CORE_ADDR adjust
20514     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20515
20516   CORE_ADDR addr_adj
20517     = (((m_op_index + adjust)
20518         / m_line_header->maximum_ops_per_instruction)
20519        * m_line_header->minimum_instruction_length);
20520
20521   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20522   m_op_index = ((m_op_index + adjust)
20523                 % m_line_header->maximum_ops_per_instruction);
20524 }
20525
20526 /* Ignore this record_line request.  */
20527
20528 static void
20529 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20530 {
20531   return;
20532 }
20533
20534 /* Return non-zero if we should add LINE to the line number table.
20535    LINE is the line to add, LAST_LINE is the last line that was added,
20536    LAST_SUBFILE is the subfile for LAST_LINE.
20537    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20538    had a non-zero discriminator.
20539
20540    We have to be careful in the presence of discriminators.
20541    E.g., for this line:
20542
20543      for (i = 0; i < 100000; i++);
20544
20545    clang can emit four line number entries for that one line,
20546    each with a different discriminator.
20547    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20548
20549    However, we want gdb to coalesce all four entries into one.
20550    Otherwise the user could stepi into the middle of the line and
20551    gdb would get confused about whether the pc really was in the
20552    middle of the line.
20553
20554    Things are further complicated by the fact that two consecutive
20555    line number entries for the same line is a heuristic used by gcc
20556    to denote the end of the prologue.  So we can't just discard duplicate
20557    entries, we have to be selective about it.  The heuristic we use is
20558    that we only collapse consecutive entries for the same line if at least
20559    one of those entries has a non-zero discriminator.  PR 17276.
20560
20561    Note: Addresses in the line number state machine can never go backwards
20562    within one sequence, thus this coalescing is ok.  */
20563
20564 static int
20565 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20566                      int line_has_non_zero_discriminator,
20567                      struct subfile *last_subfile)
20568 {
20569   if (current_subfile != last_subfile)
20570     return 1;
20571   if (line != last_line)
20572     return 1;
20573   /* Same line for the same file that we've seen already.
20574      As a last check, for pr 17276, only record the line if the line
20575      has never had a non-zero discriminator.  */
20576   if (!line_has_non_zero_discriminator)
20577     return 1;
20578   return 0;
20579 }
20580
20581 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20582    in the line table of subfile SUBFILE.  */
20583
20584 static void
20585 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20586                      unsigned int line, CORE_ADDR address,
20587                      record_line_ftype p_record_line)
20588 {
20589   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20590
20591   if (dwarf_line_debug)
20592     {
20593       fprintf_unfiltered (gdb_stdlog,
20594                           "Recording line %u, file %s, address %s\n",
20595                           line, lbasename (subfile->name),
20596                           paddress (gdbarch, address));
20597     }
20598
20599   (*p_record_line) (subfile, line, addr);
20600 }
20601
20602 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20603    Mark the end of a set of line number records.
20604    The arguments are the same as for dwarf_record_line_1.
20605    If SUBFILE is NULL the request is ignored.  */
20606
20607 static void
20608 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20609                    CORE_ADDR address, record_line_ftype p_record_line)
20610 {
20611   if (subfile == NULL)
20612     return;
20613
20614   if (dwarf_line_debug)
20615     {
20616       fprintf_unfiltered (gdb_stdlog,
20617                           "Finishing current line, file %s, address %s\n",
20618                           lbasename (subfile->name),
20619                           paddress (gdbarch, address));
20620     }
20621
20622   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20623 }
20624
20625 void
20626 lnp_state_machine::record_line (bool end_sequence)
20627 {
20628   if (dwarf_line_debug)
20629     {
20630       fprintf_unfiltered (gdb_stdlog,
20631                           "Processing actual line %u: file %u,"
20632                           " address %s, is_stmt %u, discrim %u\n",
20633                           m_line, to_underlying (m_file),
20634                           paddress (m_gdbarch, m_address),
20635                           m_is_stmt, m_discriminator);
20636     }
20637
20638   file_entry *fe = current_file ();
20639
20640   if (fe == NULL)
20641     dwarf2_debug_line_missing_file_complaint ();
20642   /* For now we ignore lines not starting on an instruction boundary.
20643      But not when processing end_sequence for compatibility with the
20644      previous version of the code.  */
20645   else if (m_op_index == 0 || end_sequence)
20646     {
20647       fe->included_p = 1;
20648       if (m_record_lines_p && m_is_stmt)
20649         {
20650           if (m_last_subfile != current_subfile || end_sequence)
20651             {
20652               dwarf_finish_line (m_gdbarch, m_last_subfile,
20653                                  m_address, m_record_line_callback);
20654             }
20655
20656           if (!end_sequence)
20657             {
20658               if (dwarf_record_line_p (m_line, m_last_line,
20659                                        m_line_has_non_zero_discriminator,
20660                                        m_last_subfile))
20661                 {
20662                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20663                                        m_line, m_address,
20664                                        m_record_line_callback);
20665                 }
20666               m_last_subfile = current_subfile;
20667               m_last_line = m_line;
20668             }
20669         }
20670     }
20671 }
20672
20673 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20674                                       bool record_lines_p)
20675 {
20676   m_gdbarch = arch;
20677   m_record_lines_p = record_lines_p;
20678   m_line_header = lh;
20679
20680   m_record_line_callback = ::record_line;
20681
20682   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20683      was a line entry for it so that the backend has a chance to adjust it
20684      and also record it in case it needs it.  This is currently used by MIPS
20685      code, cf. `mips_adjust_dwarf2_line'.  */
20686   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20687   m_is_stmt = lh->default_is_stmt;
20688   m_discriminator = 0;
20689 }
20690
20691 void
20692 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20693                                        const gdb_byte *line_ptr,
20694                                        CORE_ADDR lowpc, CORE_ADDR address)
20695 {
20696   /* If address < lowpc then it's not a usable value, it's outside the
20697      pc range of the CU.  However, we restrict the test to only address
20698      values of zero to preserve GDB's previous behaviour which is to
20699      handle the specific case of a function being GC'd by the linker.  */
20700
20701   if (address == 0 && address < lowpc)
20702     {
20703       /* This line table is for a function which has been
20704          GCd by the linker.  Ignore it.  PR gdb/12528 */
20705
20706       struct objfile *objfile = cu->objfile;
20707       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20708
20709       complaint (&symfile_complaints,
20710                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20711                  line_offset, objfile_name (objfile));
20712       m_record_line_callback = noop_record_line;
20713       /* Note: record_line_callback is left as noop_record_line until
20714          we see DW_LNE_end_sequence.  */
20715     }
20716 }
20717
20718 /* Subroutine of dwarf_decode_lines to simplify it.
20719    Process the line number information in LH.
20720    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20721    program in order to set included_p for every referenced header.  */
20722
20723 static void
20724 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20725                       const int decode_for_pst_p, CORE_ADDR lowpc)
20726 {
20727   const gdb_byte *line_ptr, *extended_end;
20728   const gdb_byte *line_end;
20729   unsigned int bytes_read, extended_len;
20730   unsigned char op_code, extended_op;
20731   CORE_ADDR baseaddr;
20732   struct objfile *objfile = cu->objfile;
20733   bfd *abfd = objfile->obfd;
20734   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20735   /* True if we're recording line info (as opposed to building partial
20736      symtabs and just interested in finding include files mentioned by
20737      the line number program).  */
20738   bool record_lines_p = !decode_for_pst_p;
20739
20740   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20741
20742   line_ptr = lh->statement_program_start;
20743   line_end = lh->statement_program_end;
20744
20745   /* Read the statement sequences until there's nothing left.  */
20746   while (line_ptr < line_end)
20747     {
20748       /* The DWARF line number program state machine.  Reset the state
20749          machine at the start of each sequence.  */
20750       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20751       bool end_sequence = false;
20752
20753       if (record_lines_p)
20754         {
20755           /* Start a subfile for the current file of the state
20756              machine.  */
20757           const file_entry *fe = state_machine.current_file ();
20758
20759           if (fe != NULL)
20760             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20761         }
20762
20763       /* Decode the table.  */
20764       while (line_ptr < line_end && !end_sequence)
20765         {
20766           op_code = read_1_byte (abfd, line_ptr);
20767           line_ptr += 1;
20768
20769           if (op_code >= lh->opcode_base)
20770             {
20771               /* Special opcode.  */
20772               state_machine.handle_special_opcode (op_code);
20773             }
20774           else switch (op_code)
20775             {
20776             case DW_LNS_extended_op:
20777               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20778                                                    &bytes_read);
20779               line_ptr += bytes_read;
20780               extended_end = line_ptr + extended_len;
20781               extended_op = read_1_byte (abfd, line_ptr);
20782               line_ptr += 1;
20783               switch (extended_op)
20784                 {
20785                 case DW_LNE_end_sequence:
20786                   state_machine.handle_end_sequence ();
20787                   end_sequence = true;
20788                   break;
20789                 case DW_LNE_set_address:
20790                   {
20791                     CORE_ADDR address
20792                       = read_address (abfd, line_ptr, cu, &bytes_read);
20793                     line_ptr += bytes_read;
20794
20795                     state_machine.check_line_address (cu, line_ptr,
20796                                                       lowpc, address);
20797                     state_machine.handle_set_address (baseaddr, address);
20798                   }
20799                   break;
20800                 case DW_LNE_define_file:
20801                   {
20802                     const char *cur_file;
20803                     unsigned int mod_time, length;
20804                     dir_index dindex;
20805
20806                     cur_file = read_direct_string (abfd, line_ptr,
20807                                                    &bytes_read);
20808                     line_ptr += bytes_read;
20809                     dindex = (dir_index)
20810                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20811                     line_ptr += bytes_read;
20812                     mod_time =
20813                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20814                     line_ptr += bytes_read;
20815                     length =
20816                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20817                     line_ptr += bytes_read;
20818                     lh->add_file_name (cur_file, dindex, mod_time, length);
20819                   }
20820                   break;
20821                 case DW_LNE_set_discriminator:
20822                   {
20823                     /* The discriminator is not interesting to the
20824                        debugger; just ignore it.  We still need to
20825                        check its value though:
20826                        if there are consecutive entries for the same
20827                        (non-prologue) line we want to coalesce them.
20828                        PR 17276.  */
20829                     unsigned int discr
20830                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20831                     line_ptr += bytes_read;
20832
20833                     state_machine.handle_set_discriminator (discr);
20834                   }
20835                   break;
20836                 default:
20837                   complaint (&symfile_complaints,
20838                              _("mangled .debug_line section"));
20839                   return;
20840                 }
20841               /* Make sure that we parsed the extended op correctly.  If e.g.
20842                  we expected a different address size than the producer used,
20843                  we may have read the wrong number of bytes.  */
20844               if (line_ptr != extended_end)
20845                 {
20846                   complaint (&symfile_complaints,
20847                              _("mangled .debug_line section"));
20848                   return;
20849                 }
20850               break;
20851             case DW_LNS_copy:
20852               state_machine.handle_copy ();
20853               break;
20854             case DW_LNS_advance_pc:
20855               {
20856                 CORE_ADDR adjust
20857                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20858                 line_ptr += bytes_read;
20859
20860                 state_machine.handle_advance_pc (adjust);
20861               }
20862               break;
20863             case DW_LNS_advance_line:
20864               {
20865                 int line_delta
20866                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20867                 line_ptr += bytes_read;
20868
20869                 state_machine.handle_advance_line (line_delta);
20870               }
20871               break;
20872             case DW_LNS_set_file:
20873               {
20874                 file_name_index file
20875                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20876                                                             &bytes_read);
20877                 line_ptr += bytes_read;
20878
20879                 state_machine.handle_set_file (file);
20880               }
20881               break;
20882             case DW_LNS_set_column:
20883               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20884               line_ptr += bytes_read;
20885               break;
20886             case DW_LNS_negate_stmt:
20887               state_machine.handle_negate_stmt ();
20888               break;
20889             case DW_LNS_set_basic_block:
20890               break;
20891             /* Add to the address register of the state machine the
20892                address increment value corresponding to special opcode
20893                255.  I.e., this value is scaled by the minimum
20894                instruction length since special opcode 255 would have
20895                scaled the increment.  */
20896             case DW_LNS_const_add_pc:
20897               state_machine.handle_const_add_pc ();
20898               break;
20899             case DW_LNS_fixed_advance_pc:
20900               {
20901                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20902                 line_ptr += 2;
20903
20904                 state_machine.handle_fixed_advance_pc (addr_adj);
20905               }
20906               break;
20907             default:
20908               {
20909                 /* Unknown standard opcode, ignore it.  */
20910                 int i;
20911
20912                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20913                   {
20914                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20915                     line_ptr += bytes_read;
20916                   }
20917               }
20918             }
20919         }
20920
20921       if (!end_sequence)
20922         dwarf2_debug_line_missing_end_sequence_complaint ();
20923
20924       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20925          in which case we still finish recording the last line).  */
20926       state_machine.record_line (true);
20927     }
20928 }
20929
20930 /* Decode the Line Number Program (LNP) for the given line_header
20931    structure and CU.  The actual information extracted and the type
20932    of structures created from the LNP depends on the value of PST.
20933
20934    1. If PST is NULL, then this procedure uses the data from the program
20935       to create all necessary symbol tables, and their linetables.
20936
20937    2. If PST is not NULL, this procedure reads the program to determine
20938       the list of files included by the unit represented by PST, and
20939       builds all the associated partial symbol tables.
20940
20941    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20942    It is used for relative paths in the line table.
20943    NOTE: When processing partial symtabs (pst != NULL),
20944    comp_dir == pst->dirname.
20945
20946    NOTE: It is important that psymtabs have the same file name (via strcmp)
20947    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20948    symtab we don't use it in the name of the psymtabs we create.
20949    E.g. expand_line_sal requires this when finding psymtabs to expand.
20950    A good testcase for this is mb-inline.exp.
20951
20952    LOWPC is the lowest address in CU (or 0 if not known).
20953
20954    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20955    for its PC<->lines mapping information.  Otherwise only the filename
20956    table is read in.  */
20957
20958 static void
20959 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20960                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20961                     CORE_ADDR lowpc, int decode_mapping)
20962 {
20963   struct objfile *objfile = cu->objfile;
20964   const int decode_for_pst_p = (pst != NULL);
20965
20966   if (decode_mapping)
20967     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20968
20969   if (decode_for_pst_p)
20970     {
20971       int file_index;
20972
20973       /* Now that we're done scanning the Line Header Program, we can
20974          create the psymtab of each included file.  */
20975       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
20976         if (lh->file_names[file_index].included_p == 1)
20977           {
20978             const char *include_name =
20979               psymtab_include_file_name (lh, file_index, pst, comp_dir);
20980             if (include_name != NULL)
20981               dwarf2_create_include_psymtab (include_name, pst, objfile);
20982           }
20983     }
20984   else
20985     {
20986       /* Make sure a symtab is created for every file, even files
20987          which contain only variables (i.e. no code with associated
20988          line numbers).  */
20989       struct compunit_symtab *cust = buildsym_compunit_symtab ();
20990       int i;
20991
20992       for (i = 0; i < lh->file_names.size (); i++)
20993         {
20994           file_entry &fe = lh->file_names[i];
20995
20996           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
20997
20998           if (current_subfile->symtab == NULL)
20999             {
21000               current_subfile->symtab
21001                 = allocate_symtab (cust, current_subfile->name);
21002             }
21003           fe.symtab = current_subfile->symtab;
21004         }
21005     }
21006 }
21007
21008 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21009    DIRNAME the name of the source directory which contains FILENAME
21010    or NULL if not known.
21011    This routine tries to keep line numbers from identical absolute and
21012    relative file names in a common subfile.
21013
21014    Using the `list' example from the GDB testsuite, which resides in
21015    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21016    of /srcdir/list0.c yields the following debugging information for list0.c:
21017
21018    DW_AT_name:          /srcdir/list0.c
21019    DW_AT_comp_dir:      /compdir
21020    files.files[0].name: list0.h
21021    files.files[0].dir:  /srcdir
21022    files.files[1].name: list0.c
21023    files.files[1].dir:  /srcdir
21024
21025    The line number information for list0.c has to end up in a single
21026    subfile, so that `break /srcdir/list0.c:1' works as expected.
21027    start_subfile will ensure that this happens provided that we pass the
21028    concatenation of files.files[1].dir and files.files[1].name as the
21029    subfile's name.  */
21030
21031 static void
21032 dwarf2_start_subfile (const char *filename, const char *dirname)
21033 {
21034   char *copy = NULL;
21035
21036   /* In order not to lose the line information directory,
21037      we concatenate it to the filename when it makes sense.
21038      Note that the Dwarf3 standard says (speaking of filenames in line
21039      information): ``The directory index is ignored for file names
21040      that represent full path names''.  Thus ignoring dirname in the
21041      `else' branch below isn't an issue.  */
21042
21043   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21044     {
21045       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21046       filename = copy;
21047     }
21048
21049   start_subfile (filename);
21050
21051   if (copy != NULL)
21052     xfree (copy);
21053 }
21054
21055 /* Start a symtab for DWARF.
21056    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21057
21058 static struct compunit_symtab *
21059 dwarf2_start_symtab (struct dwarf2_cu *cu,
21060                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21061 {
21062   struct compunit_symtab *cust
21063     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
21064
21065   record_debugformat ("DWARF 2");
21066   record_producer (cu->producer);
21067
21068   /* We assume that we're processing GCC output.  */
21069   processing_gcc_compilation = 2;
21070
21071   cu->processing_has_namespace_info = 0;
21072
21073   return cust;
21074 }
21075
21076 static void
21077 var_decode_location (struct attribute *attr, struct symbol *sym,
21078                      struct dwarf2_cu *cu)
21079 {
21080   struct objfile *objfile = cu->objfile;
21081   struct comp_unit_head *cu_header = &cu->header;
21082
21083   /* NOTE drow/2003-01-30: There used to be a comment and some special
21084      code here to turn a symbol with DW_AT_external and a
21085      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21086      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21087      with some versions of binutils) where shared libraries could have
21088      relocations against symbols in their debug information - the
21089      minimal symbol would have the right address, but the debug info
21090      would not.  It's no longer necessary, because we will explicitly
21091      apply relocations when we read in the debug information now.  */
21092
21093   /* A DW_AT_location attribute with no contents indicates that a
21094      variable has been optimized away.  */
21095   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21096     {
21097       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21098       return;
21099     }
21100
21101   /* Handle one degenerate form of location expression specially, to
21102      preserve GDB's previous behavior when section offsets are
21103      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21104      then mark this symbol as LOC_STATIC.  */
21105
21106   if (attr_form_is_block (attr)
21107       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21108            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21109           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21110               && (DW_BLOCK (attr)->size
21111                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21112     {
21113       unsigned int dummy;
21114
21115       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21116         SYMBOL_VALUE_ADDRESS (sym) =
21117           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21118       else
21119         SYMBOL_VALUE_ADDRESS (sym) =
21120           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21121       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21122       fixup_symbol_section (sym, objfile);
21123       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21124                                               SYMBOL_SECTION (sym));
21125       return;
21126     }
21127
21128   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21129      expression evaluator, and use LOC_COMPUTED only when necessary
21130      (i.e. when the value of a register or memory location is
21131      referenced, or a thread-local block, etc.).  Then again, it might
21132      not be worthwhile.  I'm assuming that it isn't unless performance
21133      or memory numbers show me otherwise.  */
21134
21135   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21136
21137   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21138     cu->has_loclist = 1;
21139 }
21140
21141 /* Given a pointer to a DWARF information entry, figure out if we need
21142    to make a symbol table entry for it, and if so, create a new entry
21143    and return a pointer to it.
21144    If TYPE is NULL, determine symbol type from the die, otherwise
21145    used the passed type.
21146    If SPACE is not NULL, use it to hold the new symbol.  If it is
21147    NULL, allocate a new symbol on the objfile's obstack.  */
21148
21149 static struct symbol *
21150 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21151                  struct symbol *space)
21152 {
21153   struct objfile *objfile = cu->objfile;
21154   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21155   struct symbol *sym = NULL;
21156   const char *name;
21157   struct attribute *attr = NULL;
21158   struct attribute *attr2 = NULL;
21159   CORE_ADDR baseaddr;
21160   struct pending **list_to_add = NULL;
21161
21162   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21163
21164   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21165
21166   name = dwarf2_name (die, cu);
21167   if (name)
21168     {
21169       const char *linkagename;
21170       int suppress_add = 0;
21171
21172       if (space)
21173         sym = space;
21174       else
21175         sym = allocate_symbol (objfile);
21176       OBJSTAT (objfile, n_syms++);
21177
21178       /* Cache this symbol's name and the name's demangled form (if any).  */
21179       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21180       linkagename = dwarf2_physname (name, die, cu);
21181       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21182
21183       /* Fortran does not have mangling standard and the mangling does differ
21184          between gfortran, iFort etc.  */
21185       if (cu->language == language_fortran
21186           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21187         symbol_set_demangled_name (&(sym->ginfo),
21188                                    dwarf2_full_name (name, die, cu),
21189                                    NULL);
21190
21191       /* Default assumptions.
21192          Use the passed type or decode it from the die.  */
21193       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21194       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21195       if (type != NULL)
21196         SYMBOL_TYPE (sym) = type;
21197       else
21198         SYMBOL_TYPE (sym) = die_type (die, cu);
21199       attr = dwarf2_attr (die,
21200                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21201                           cu);
21202       if (attr)
21203         {
21204           SYMBOL_LINE (sym) = DW_UNSND (attr);
21205         }
21206
21207       attr = dwarf2_attr (die,
21208                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21209                           cu);
21210       if (attr)
21211         {
21212           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21213           struct file_entry *fe;
21214
21215           if (cu->line_header != NULL)
21216             fe = cu->line_header->file_name_at (file_index);
21217           else
21218             fe = NULL;
21219
21220           if (fe == NULL)
21221             complaint (&symfile_complaints,
21222                        _("file index out of range"));
21223           else
21224             symbol_set_symtab (sym, fe->symtab);
21225         }
21226
21227       switch (die->tag)
21228         {
21229         case DW_TAG_label:
21230           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21231           if (attr)
21232             {
21233               CORE_ADDR addr;
21234
21235               addr = attr_value_as_address (attr);
21236               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21237               SYMBOL_VALUE_ADDRESS (sym) = addr;
21238             }
21239           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21240           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21241           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21242           add_symbol_to_list (sym, cu->list_in_scope);
21243           break;
21244         case DW_TAG_subprogram:
21245           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21246              finish_block.  */
21247           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21248           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21249           if ((attr2 && (DW_UNSND (attr2) != 0))
21250               || cu->language == language_ada)
21251             {
21252               /* Subprograms marked external are stored as a global symbol.
21253                  Ada subprograms, whether marked external or not, are always
21254                  stored as a global symbol, because we want to be able to
21255                  access them globally.  For instance, we want to be able
21256                  to break on a nested subprogram without having to
21257                  specify the context.  */
21258               list_to_add = &global_symbols;
21259             }
21260           else
21261             {
21262               list_to_add = cu->list_in_scope;
21263             }
21264           break;
21265         case DW_TAG_inlined_subroutine:
21266           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21267              finish_block.  */
21268           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21269           SYMBOL_INLINED (sym) = 1;
21270           list_to_add = cu->list_in_scope;
21271           break;
21272         case DW_TAG_template_value_param:
21273           suppress_add = 1;
21274           /* Fall through.  */
21275         case DW_TAG_constant:
21276         case DW_TAG_variable:
21277         case DW_TAG_member:
21278           /* Compilation with minimal debug info may result in
21279              variables with missing type entries.  Change the
21280              misleading `void' type to something sensible.  */
21281           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21282             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21283
21284           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21285           /* In the case of DW_TAG_member, we should only be called for
21286              static const members.  */
21287           if (die->tag == DW_TAG_member)
21288             {
21289               /* dwarf2_add_field uses die_is_declaration,
21290                  so we do the same.  */
21291               gdb_assert (die_is_declaration (die, cu));
21292               gdb_assert (attr);
21293             }
21294           if (attr)
21295             {
21296               dwarf2_const_value (attr, sym, cu);
21297               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21298               if (!suppress_add)
21299                 {
21300                   if (attr2 && (DW_UNSND (attr2) != 0))
21301                     list_to_add = &global_symbols;
21302                   else
21303                     list_to_add = cu->list_in_scope;
21304                 }
21305               break;
21306             }
21307           attr = dwarf2_attr (die, DW_AT_location, cu);
21308           if (attr)
21309             {
21310               var_decode_location (attr, sym, cu);
21311               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21312
21313               /* Fortran explicitly imports any global symbols to the local
21314                  scope by DW_TAG_common_block.  */
21315               if (cu->language == language_fortran && die->parent
21316                   && die->parent->tag == DW_TAG_common_block)
21317                 attr2 = NULL;
21318
21319               if (SYMBOL_CLASS (sym) == LOC_STATIC
21320                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21321                   && !dwarf2_per_objfile->has_section_at_zero)
21322                 {
21323                   /* When a static variable is eliminated by the linker,
21324                      the corresponding debug information is not stripped
21325                      out, but the variable address is set to null;
21326                      do not add such variables into symbol table.  */
21327                 }
21328               else if (attr2 && (DW_UNSND (attr2) != 0))
21329                 {
21330                   /* Workaround gfortran PR debug/40040 - it uses
21331                      DW_AT_location for variables in -fPIC libraries which may
21332                      get overriden by other libraries/executable and get
21333                      a different address.  Resolve it by the minimal symbol
21334                      which may come from inferior's executable using copy
21335                      relocation.  Make this workaround only for gfortran as for
21336                      other compilers GDB cannot guess the minimal symbol
21337                      Fortran mangling kind.  */
21338                   if (cu->language == language_fortran && die->parent
21339                       && die->parent->tag == DW_TAG_module
21340                       && cu->producer
21341                       && startswith (cu->producer, "GNU Fortran"))
21342                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21343
21344                   /* A variable with DW_AT_external is never static,
21345                      but it may be block-scoped.  */
21346                   list_to_add = (cu->list_in_scope == &file_symbols
21347                                  ? &global_symbols : cu->list_in_scope);
21348                 }
21349               else
21350                 list_to_add = cu->list_in_scope;
21351             }
21352           else
21353             {
21354               /* We do not know the address of this symbol.
21355                  If it is an external symbol and we have type information
21356                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21357                  The address of the variable will then be determined from
21358                  the minimal symbol table whenever the variable is
21359                  referenced.  */
21360               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21361
21362               /* Fortran explicitly imports any global symbols to the local
21363                  scope by DW_TAG_common_block.  */
21364               if (cu->language == language_fortran && die->parent
21365                   && die->parent->tag == DW_TAG_common_block)
21366                 {
21367                   /* SYMBOL_CLASS doesn't matter here because
21368                      read_common_block is going to reset it.  */
21369                   if (!suppress_add)
21370                     list_to_add = cu->list_in_scope;
21371                 }
21372               else if (attr2 && (DW_UNSND (attr2) != 0)
21373                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21374                 {
21375                   /* A variable with DW_AT_external is never static, but it
21376                      may be block-scoped.  */
21377                   list_to_add = (cu->list_in_scope == &file_symbols
21378                                  ? &global_symbols : cu->list_in_scope);
21379
21380                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21381                 }
21382               else if (!die_is_declaration (die, cu))
21383                 {
21384                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21385                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21386                   if (!suppress_add)
21387                     list_to_add = cu->list_in_scope;
21388                 }
21389             }
21390           break;
21391         case DW_TAG_formal_parameter:
21392           /* If we are inside a function, mark this as an argument.  If
21393              not, we might be looking at an argument to an inlined function
21394              when we do not have enough information to show inlined frames;
21395              pretend it's a local variable in that case so that the user can
21396              still see it.  */
21397           if (context_stack_depth > 0
21398               && context_stack[context_stack_depth - 1].name != NULL)
21399             SYMBOL_IS_ARGUMENT (sym) = 1;
21400           attr = dwarf2_attr (die, DW_AT_location, cu);
21401           if (attr)
21402             {
21403               var_decode_location (attr, sym, cu);
21404             }
21405           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21406           if (attr)
21407             {
21408               dwarf2_const_value (attr, sym, cu);
21409             }
21410
21411           list_to_add = cu->list_in_scope;
21412           break;
21413         case DW_TAG_unspecified_parameters:
21414           /* From varargs functions; gdb doesn't seem to have any
21415              interest in this information, so just ignore it for now.
21416              (FIXME?) */
21417           break;
21418         case DW_TAG_template_type_param:
21419           suppress_add = 1;
21420           /* Fall through.  */
21421         case DW_TAG_class_type:
21422         case DW_TAG_interface_type:
21423         case DW_TAG_structure_type:
21424         case DW_TAG_union_type:
21425         case DW_TAG_set_type:
21426         case DW_TAG_enumeration_type:
21427           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21428           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21429
21430           {
21431             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21432                really ever be static objects: otherwise, if you try
21433                to, say, break of a class's method and you're in a file
21434                which doesn't mention that class, it won't work unless
21435                the check for all static symbols in lookup_symbol_aux
21436                saves you.  See the OtherFileClass tests in
21437                gdb.c++/namespace.exp.  */
21438
21439             if (!suppress_add)
21440               {
21441                 list_to_add = (cu->list_in_scope == &file_symbols
21442                                && cu->language == language_cplus
21443                                ? &global_symbols : cu->list_in_scope);
21444
21445                 /* The semantics of C++ state that "struct foo {
21446                    ... }" also defines a typedef for "foo".  */
21447                 if (cu->language == language_cplus
21448                     || cu->language == language_ada
21449                     || cu->language == language_d
21450                     || cu->language == language_rust)
21451                   {
21452                     /* The symbol's name is already allocated along
21453                        with this objfile, so we don't need to
21454                        duplicate it for the type.  */
21455                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21456                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21457                   }
21458               }
21459           }
21460           break;
21461         case DW_TAG_typedef:
21462           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21463           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21464           list_to_add = cu->list_in_scope;
21465           break;
21466         case DW_TAG_base_type:
21467         case DW_TAG_subrange_type:
21468           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21469           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21470           list_to_add = cu->list_in_scope;
21471           break;
21472         case DW_TAG_enumerator:
21473           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21474           if (attr)
21475             {
21476               dwarf2_const_value (attr, sym, cu);
21477             }
21478           {
21479             /* NOTE: carlton/2003-11-10: See comment above in the
21480                DW_TAG_class_type, etc. block.  */
21481
21482             list_to_add = (cu->list_in_scope == &file_symbols
21483                            && cu->language == language_cplus
21484                            ? &global_symbols : cu->list_in_scope);
21485           }
21486           break;
21487         case DW_TAG_imported_declaration:
21488         case DW_TAG_namespace:
21489           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21490           list_to_add = &global_symbols;
21491           break;
21492         case DW_TAG_module:
21493           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21494           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21495           list_to_add = &global_symbols;
21496           break;
21497         case DW_TAG_common_block:
21498           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21499           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21500           add_symbol_to_list (sym, cu->list_in_scope);
21501           break;
21502         default:
21503           /* Not a tag we recognize.  Hopefully we aren't processing
21504              trash data, but since we must specifically ignore things
21505              we don't recognize, there is nothing else we should do at
21506              this point.  */
21507           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21508                      dwarf_tag_name (die->tag));
21509           break;
21510         }
21511
21512       if (suppress_add)
21513         {
21514           sym->hash_next = objfile->template_symbols;
21515           objfile->template_symbols = sym;
21516           list_to_add = NULL;
21517         }
21518
21519       if (list_to_add != NULL)
21520         add_symbol_to_list (sym, list_to_add);
21521
21522       /* For the benefit of old versions of GCC, check for anonymous
21523          namespaces based on the demangled name.  */
21524       if (!cu->processing_has_namespace_info
21525           && cu->language == language_cplus)
21526         cp_scan_for_anonymous_namespaces (sym, objfile);
21527     }
21528   return (sym);
21529 }
21530
21531 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
21532
21533 static struct symbol *
21534 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21535 {
21536   return new_symbol_full (die, type, cu, NULL);
21537 }
21538
21539 /* Given an attr with a DW_FORM_dataN value in host byte order,
21540    zero-extend it as appropriate for the symbol's type.  The DWARF
21541    standard (v4) is not entirely clear about the meaning of using
21542    DW_FORM_dataN for a constant with a signed type, where the type is
21543    wider than the data.  The conclusion of a discussion on the DWARF
21544    list was that this is unspecified.  We choose to always zero-extend
21545    because that is the interpretation long in use by GCC.  */
21546
21547 static gdb_byte *
21548 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21549                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21550 {
21551   struct objfile *objfile = cu->objfile;
21552   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21553                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21554   LONGEST l = DW_UNSND (attr);
21555
21556   if (bits < sizeof (*value) * 8)
21557     {
21558       l &= ((LONGEST) 1 << bits) - 1;
21559       *value = l;
21560     }
21561   else if (bits == sizeof (*value) * 8)
21562     *value = l;
21563   else
21564     {
21565       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21566       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21567       return bytes;
21568     }
21569
21570   return NULL;
21571 }
21572
21573 /* Read a constant value from an attribute.  Either set *VALUE, or if
21574    the value does not fit in *VALUE, set *BYTES - either already
21575    allocated on the objfile obstack, or newly allocated on OBSTACK,
21576    or, set *BATON, if we translated the constant to a location
21577    expression.  */
21578
21579 static void
21580 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21581                          const char *name, struct obstack *obstack,
21582                          struct dwarf2_cu *cu,
21583                          LONGEST *value, const gdb_byte **bytes,
21584                          struct dwarf2_locexpr_baton **baton)
21585 {
21586   struct objfile *objfile = cu->objfile;
21587   struct comp_unit_head *cu_header = &cu->header;
21588   struct dwarf_block *blk;
21589   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21590                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21591
21592   *value = 0;
21593   *bytes = NULL;
21594   *baton = NULL;
21595
21596   switch (attr->form)
21597     {
21598     case DW_FORM_addr:
21599     case DW_FORM_GNU_addr_index:
21600       {
21601         gdb_byte *data;
21602
21603         if (TYPE_LENGTH (type) != cu_header->addr_size)
21604           dwarf2_const_value_length_mismatch_complaint (name,
21605                                                         cu_header->addr_size,
21606                                                         TYPE_LENGTH (type));
21607         /* Symbols of this form are reasonably rare, so we just
21608            piggyback on the existing location code rather than writing
21609            a new implementation of symbol_computed_ops.  */
21610         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21611         (*baton)->per_cu = cu->per_cu;
21612         gdb_assert ((*baton)->per_cu);
21613
21614         (*baton)->size = 2 + cu_header->addr_size;
21615         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21616         (*baton)->data = data;
21617
21618         data[0] = DW_OP_addr;
21619         store_unsigned_integer (&data[1], cu_header->addr_size,
21620                                 byte_order, DW_ADDR (attr));
21621         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21622       }
21623       break;
21624     case DW_FORM_string:
21625     case DW_FORM_strp:
21626     case DW_FORM_GNU_str_index:
21627     case DW_FORM_GNU_strp_alt:
21628       /* DW_STRING is already allocated on the objfile obstack, point
21629          directly to it.  */
21630       *bytes = (const gdb_byte *) DW_STRING (attr);
21631       break;
21632     case DW_FORM_block1:
21633     case DW_FORM_block2:
21634     case DW_FORM_block4:
21635     case DW_FORM_block:
21636     case DW_FORM_exprloc:
21637     case DW_FORM_data16:
21638       blk = DW_BLOCK (attr);
21639       if (TYPE_LENGTH (type) != blk->size)
21640         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21641                                                       TYPE_LENGTH (type));
21642       *bytes = blk->data;
21643       break;
21644
21645       /* The DW_AT_const_value attributes are supposed to carry the
21646          symbol's value "represented as it would be on the target
21647          architecture."  By the time we get here, it's already been
21648          converted to host endianness, so we just need to sign- or
21649          zero-extend it as appropriate.  */
21650     case DW_FORM_data1:
21651       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21652       break;
21653     case DW_FORM_data2:
21654       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21655       break;
21656     case DW_FORM_data4:
21657       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21658       break;
21659     case DW_FORM_data8:
21660       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21661       break;
21662
21663     case DW_FORM_sdata:
21664     case DW_FORM_implicit_const:
21665       *value = DW_SND (attr);
21666       break;
21667
21668     case DW_FORM_udata:
21669       *value = DW_UNSND (attr);
21670       break;
21671
21672     default:
21673       complaint (&symfile_complaints,
21674                  _("unsupported const value attribute form: '%s'"),
21675                  dwarf_form_name (attr->form));
21676       *value = 0;
21677       break;
21678     }
21679 }
21680
21681
21682 /* Copy constant value from an attribute to a symbol.  */
21683
21684 static void
21685 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21686                     struct dwarf2_cu *cu)
21687 {
21688   struct objfile *objfile = cu->objfile;
21689   LONGEST value;
21690   const gdb_byte *bytes;
21691   struct dwarf2_locexpr_baton *baton;
21692
21693   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21694                            SYMBOL_PRINT_NAME (sym),
21695                            &objfile->objfile_obstack, cu,
21696                            &value, &bytes, &baton);
21697
21698   if (baton != NULL)
21699     {
21700       SYMBOL_LOCATION_BATON (sym) = baton;
21701       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21702     }
21703   else if (bytes != NULL)
21704      {
21705       SYMBOL_VALUE_BYTES (sym) = bytes;
21706       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21707     }
21708   else
21709     {
21710       SYMBOL_VALUE (sym) = value;
21711       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21712     }
21713 }
21714
21715 /* Return the type of the die in question using its DW_AT_type attribute.  */
21716
21717 static struct type *
21718 die_type (struct die_info *die, struct dwarf2_cu *cu)
21719 {
21720   struct attribute *type_attr;
21721
21722   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21723   if (!type_attr)
21724     {
21725       /* A missing DW_AT_type represents a void type.  */
21726       return objfile_type (cu->objfile)->builtin_void;
21727     }
21728
21729   return lookup_die_type (die, type_attr, cu);
21730 }
21731
21732 /* True iff CU's producer generates GNAT Ada auxiliary information
21733    that allows to find parallel types through that information instead
21734    of having to do expensive parallel lookups by type name.  */
21735
21736 static int
21737 need_gnat_info (struct dwarf2_cu *cu)
21738 {
21739   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
21740      of GNAT produces this auxiliary information, without any indication
21741      that it is produced.  Part of enhancing the FSF version of GNAT
21742      to produce that information will be to put in place an indicator
21743      that we can use in order to determine whether the descriptive type
21744      info is available or not.  One suggestion that has been made is
21745      to use a new attribute, attached to the CU die.  For now, assume
21746      that the descriptive type info is not available.  */
21747   return 0;
21748 }
21749
21750 /* Return the auxiliary type of the die in question using its
21751    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21752    attribute is not present.  */
21753
21754 static struct type *
21755 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21756 {
21757   struct attribute *type_attr;
21758
21759   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21760   if (!type_attr)
21761     return NULL;
21762
21763   return lookup_die_type (die, type_attr, cu);
21764 }
21765
21766 /* If DIE has a descriptive_type attribute, then set the TYPE's
21767    descriptive type accordingly.  */
21768
21769 static void
21770 set_descriptive_type (struct type *type, struct die_info *die,
21771                       struct dwarf2_cu *cu)
21772 {
21773   struct type *descriptive_type = die_descriptive_type (die, cu);
21774
21775   if (descriptive_type)
21776     {
21777       ALLOCATE_GNAT_AUX_TYPE (type);
21778       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21779     }
21780 }
21781
21782 /* Return the containing type of the die in question using its
21783    DW_AT_containing_type attribute.  */
21784
21785 static struct type *
21786 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21787 {
21788   struct attribute *type_attr;
21789
21790   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21791   if (!type_attr)
21792     error (_("Dwarf Error: Problem turning containing type into gdb type "
21793              "[in module %s]"), objfile_name (cu->objfile));
21794
21795   return lookup_die_type (die, type_attr, cu);
21796 }
21797
21798 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21799
21800 static struct type *
21801 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21802 {
21803   struct objfile *objfile = dwarf2_per_objfile->objfile;
21804   char *message, *saved;
21805
21806   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
21807                         objfile_name (objfile),
21808                         to_underlying (cu->header.sect_off),
21809                         to_underlying (die->sect_off));
21810   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21811                                   message, strlen (message));
21812   xfree (message);
21813
21814   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21815 }
21816
21817 /* Look up the type of DIE in CU using its type attribute ATTR.
21818    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21819    DW_AT_containing_type.
21820    If there is no type substitute an error marker.  */
21821
21822 static struct type *
21823 lookup_die_type (struct die_info *die, const struct attribute *attr,
21824                  struct dwarf2_cu *cu)
21825 {
21826   struct objfile *objfile = cu->objfile;
21827   struct type *this_type;
21828
21829   gdb_assert (attr->name == DW_AT_type
21830               || attr->name == DW_AT_GNAT_descriptive_type
21831               || attr->name == DW_AT_containing_type);
21832
21833   /* First see if we have it cached.  */
21834
21835   if (attr->form == DW_FORM_GNU_ref_alt)
21836     {
21837       struct dwarf2_per_cu_data *per_cu;
21838       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21839
21840       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
21841       this_type = get_die_type_at_offset (sect_off, per_cu);
21842     }
21843   else if (attr_form_is_ref (attr))
21844     {
21845       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21846
21847       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21848     }
21849   else if (attr->form == DW_FORM_ref_sig8)
21850     {
21851       ULONGEST signature = DW_SIGNATURE (attr);
21852
21853       return get_signatured_type (die, signature, cu);
21854     }
21855   else
21856     {
21857       complaint (&symfile_complaints,
21858                  _("Dwarf Error: Bad type attribute %s in DIE"
21859                    " at 0x%x [in module %s]"),
21860                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
21861                  objfile_name (objfile));
21862       return build_error_marker_type (cu, die);
21863     }
21864
21865   /* If not cached we need to read it in.  */
21866
21867   if (this_type == NULL)
21868     {
21869       struct die_info *type_die = NULL;
21870       struct dwarf2_cu *type_cu = cu;
21871
21872       if (attr_form_is_ref (attr))
21873         type_die = follow_die_ref (die, attr, &type_cu);
21874       if (type_die == NULL)
21875         return build_error_marker_type (cu, die);
21876       /* If we find the type now, it's probably because the type came
21877          from an inter-CU reference and the type's CU got expanded before
21878          ours.  */
21879       this_type = read_type_die (type_die, type_cu);
21880     }
21881
21882   /* If we still don't have a type use an error marker.  */
21883
21884   if (this_type == NULL)
21885     return build_error_marker_type (cu, die);
21886
21887   return this_type;
21888 }
21889
21890 /* Return the type in DIE, CU.
21891    Returns NULL for invalid types.
21892
21893    This first does a lookup in die_type_hash,
21894    and only reads the die in if necessary.
21895
21896    NOTE: This can be called when reading in partial or full symbols.  */
21897
21898 static struct type *
21899 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21900 {
21901   struct type *this_type;
21902
21903   this_type = get_die_type (die, cu);
21904   if (this_type)
21905     return this_type;
21906
21907   return read_type_die_1 (die, cu);
21908 }
21909
21910 /* Read the type in DIE, CU.
21911    Returns NULL for invalid types.  */
21912
21913 static struct type *
21914 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21915 {
21916   struct type *this_type = NULL;
21917
21918   switch (die->tag)
21919     {
21920     case DW_TAG_class_type:
21921     case DW_TAG_interface_type:
21922     case DW_TAG_structure_type:
21923     case DW_TAG_union_type:
21924       this_type = read_structure_type (die, cu);
21925       break;
21926     case DW_TAG_enumeration_type:
21927       this_type = read_enumeration_type (die, cu);
21928       break;
21929     case DW_TAG_subprogram:
21930     case DW_TAG_subroutine_type:
21931     case DW_TAG_inlined_subroutine:
21932       this_type = read_subroutine_type (die, cu);
21933       break;
21934     case DW_TAG_array_type:
21935       this_type = read_array_type (die, cu);
21936       break;
21937     case DW_TAG_set_type:
21938       this_type = read_set_type (die, cu);
21939       break;
21940     case DW_TAG_pointer_type:
21941       this_type = read_tag_pointer_type (die, cu);
21942       break;
21943     case DW_TAG_ptr_to_member_type:
21944       this_type = read_tag_ptr_to_member_type (die, cu);
21945       break;
21946     case DW_TAG_reference_type:
21947       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21948       break;
21949     case DW_TAG_rvalue_reference_type:
21950       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21951       break;
21952     case DW_TAG_const_type:
21953       this_type = read_tag_const_type (die, cu);
21954       break;
21955     case DW_TAG_volatile_type:
21956       this_type = read_tag_volatile_type (die, cu);
21957       break;
21958     case DW_TAG_restrict_type:
21959       this_type = read_tag_restrict_type (die, cu);
21960       break;
21961     case DW_TAG_string_type:
21962       this_type = read_tag_string_type (die, cu);
21963       break;
21964     case DW_TAG_typedef:
21965       this_type = read_typedef (die, cu);
21966       break;
21967     case DW_TAG_subrange_type:
21968       this_type = read_subrange_type (die, cu);
21969       break;
21970     case DW_TAG_base_type:
21971       this_type = read_base_type (die, cu);
21972       break;
21973     case DW_TAG_unspecified_type:
21974       this_type = read_unspecified_type (die, cu);
21975       break;
21976     case DW_TAG_namespace:
21977       this_type = read_namespace_type (die, cu);
21978       break;
21979     case DW_TAG_module:
21980       this_type = read_module_type (die, cu);
21981       break;
21982     case DW_TAG_atomic_type:
21983       this_type = read_tag_atomic_type (die, cu);
21984       break;
21985     default:
21986       complaint (&symfile_complaints,
21987                  _("unexpected tag in read_type_die: '%s'"),
21988                  dwarf_tag_name (die->tag));
21989       break;
21990     }
21991
21992   return this_type;
21993 }
21994
21995 /* See if we can figure out if the class lives in a namespace.  We do
21996    this by looking for a member function; its demangled name will
21997    contain namespace info, if there is any.
21998    Return the computed name or NULL.
21999    Space for the result is allocated on the objfile's obstack.
22000    This is the full-die version of guess_partial_die_structure_name.
22001    In this case we know DIE has no useful parent.  */
22002
22003 static char *
22004 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22005 {
22006   struct die_info *spec_die;
22007   struct dwarf2_cu *spec_cu;
22008   struct die_info *child;
22009
22010   spec_cu = cu;
22011   spec_die = die_specification (die, &spec_cu);
22012   if (spec_die != NULL)
22013     {
22014       die = spec_die;
22015       cu = spec_cu;
22016     }
22017
22018   for (child = die->child;
22019        child != NULL;
22020        child = child->sibling)
22021     {
22022       if (child->tag == DW_TAG_subprogram)
22023         {
22024           const char *linkage_name = dw2_linkage_name (child, cu);
22025
22026           if (linkage_name != NULL)
22027             {
22028               char *actual_name
22029                 = language_class_name_from_physname (cu->language_defn,
22030                                                      linkage_name);
22031               char *name = NULL;
22032
22033               if (actual_name != NULL)
22034                 {
22035                   const char *die_name = dwarf2_name (die, cu);
22036
22037                   if (die_name != NULL
22038                       && strcmp (die_name, actual_name) != 0)
22039                     {
22040                       /* Strip off the class name from the full name.
22041                          We want the prefix.  */
22042                       int die_name_len = strlen (die_name);
22043                       int actual_name_len = strlen (actual_name);
22044
22045                       /* Test for '::' as a sanity check.  */
22046                       if (actual_name_len > die_name_len + 2
22047                           && actual_name[actual_name_len
22048                                          - die_name_len - 1] == ':')
22049                         name = (char *) obstack_copy0 (
22050                           &cu->objfile->per_bfd->storage_obstack,
22051                           actual_name, actual_name_len - die_name_len - 2);
22052                     }
22053                 }
22054               xfree (actual_name);
22055               return name;
22056             }
22057         }
22058     }
22059
22060   return NULL;
22061 }
22062
22063 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22064    prefix part in such case.  See
22065    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22066
22067 static const char *
22068 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22069 {
22070   struct attribute *attr;
22071   const char *base;
22072
22073   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22074       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22075     return NULL;
22076
22077   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22078     return NULL;
22079
22080   attr = dw2_linkage_name_attr (die, cu);
22081   if (attr == NULL || DW_STRING (attr) == NULL)
22082     return NULL;
22083
22084   /* dwarf2_name had to be already called.  */
22085   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22086
22087   /* Strip the base name, keep any leading namespaces/classes.  */
22088   base = strrchr (DW_STRING (attr), ':');
22089   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22090     return "";
22091
22092   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
22093                                  DW_STRING (attr),
22094                                  &base[-1] - DW_STRING (attr));
22095 }
22096
22097 /* Return the name of the namespace/class that DIE is defined within,
22098    or "" if we can't tell.  The caller should not xfree the result.
22099
22100    For example, if we're within the method foo() in the following
22101    code:
22102
22103    namespace N {
22104      class C {
22105        void foo () {
22106        }
22107      };
22108    }
22109
22110    then determine_prefix on foo's die will return "N::C".  */
22111
22112 static const char *
22113 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22114 {
22115   struct die_info *parent, *spec_die;
22116   struct dwarf2_cu *spec_cu;
22117   struct type *parent_type;
22118   const char *retval;
22119
22120   if (cu->language != language_cplus
22121       && cu->language != language_fortran && cu->language != language_d
22122       && cu->language != language_rust)
22123     return "";
22124
22125   retval = anonymous_struct_prefix (die, cu);
22126   if (retval)
22127     return retval;
22128
22129   /* We have to be careful in the presence of DW_AT_specification.
22130      For example, with GCC 3.4, given the code
22131
22132      namespace N {
22133        void foo() {
22134          // Definition of N::foo.
22135        }
22136      }
22137
22138      then we'll have a tree of DIEs like this:
22139
22140      1: DW_TAG_compile_unit
22141        2: DW_TAG_namespace        // N
22142          3: DW_TAG_subprogram     // declaration of N::foo
22143        4: DW_TAG_subprogram       // definition of N::foo
22144             DW_AT_specification   // refers to die #3
22145
22146      Thus, when processing die #4, we have to pretend that we're in
22147      the context of its DW_AT_specification, namely the contex of die
22148      #3.  */
22149   spec_cu = cu;
22150   spec_die = die_specification (die, &spec_cu);
22151   if (spec_die == NULL)
22152     parent = die->parent;
22153   else
22154     {
22155       parent = spec_die->parent;
22156       cu = spec_cu;
22157     }
22158
22159   if (parent == NULL)
22160     return "";
22161   else if (parent->building_fullname)
22162     {
22163       const char *name;
22164       const char *parent_name;
22165
22166       /* It has been seen on RealView 2.2 built binaries,
22167          DW_TAG_template_type_param types actually _defined_ as
22168          children of the parent class:
22169
22170          enum E {};
22171          template class <class Enum> Class{};
22172          Class<enum E> class_e;
22173
22174          1: DW_TAG_class_type (Class)
22175            2: DW_TAG_enumeration_type (E)
22176              3: DW_TAG_enumerator (enum1:0)
22177              3: DW_TAG_enumerator (enum2:1)
22178              ...
22179            2: DW_TAG_template_type_param
22180               DW_AT_type  DW_FORM_ref_udata (E)
22181
22182          Besides being broken debug info, it can put GDB into an
22183          infinite loop.  Consider:
22184
22185          When we're building the full name for Class<E>, we'll start
22186          at Class, and go look over its template type parameters,
22187          finding E.  We'll then try to build the full name of E, and
22188          reach here.  We're now trying to build the full name of E,
22189          and look over the parent DIE for containing scope.  In the
22190          broken case, if we followed the parent DIE of E, we'd again
22191          find Class, and once again go look at its template type
22192          arguments, etc., etc.  Simply don't consider such parent die
22193          as source-level parent of this die (it can't be, the language
22194          doesn't allow it), and break the loop here.  */
22195       name = dwarf2_name (die, cu);
22196       parent_name = dwarf2_name (parent, cu);
22197       complaint (&symfile_complaints,
22198                  _("template param type '%s' defined within parent '%s'"),
22199                  name ? name : "<unknown>",
22200                  parent_name ? parent_name : "<unknown>");
22201       return "";
22202     }
22203   else
22204     switch (parent->tag)
22205       {
22206       case DW_TAG_namespace:
22207         parent_type = read_type_die (parent, cu);
22208         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22209            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22210            Work around this problem here.  */
22211         if (cu->language == language_cplus
22212             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22213           return "";
22214         /* We give a name to even anonymous namespaces.  */
22215         return TYPE_TAG_NAME (parent_type);
22216       case DW_TAG_class_type:
22217       case DW_TAG_interface_type:
22218       case DW_TAG_structure_type:
22219       case DW_TAG_union_type:
22220       case DW_TAG_module:
22221         parent_type = read_type_die (parent, cu);
22222         if (TYPE_TAG_NAME (parent_type) != NULL)
22223           return TYPE_TAG_NAME (parent_type);
22224         else
22225           /* An anonymous structure is only allowed non-static data
22226              members; no typedefs, no member functions, et cetera.
22227              So it does not need a prefix.  */
22228           return "";
22229       case DW_TAG_compile_unit:
22230       case DW_TAG_partial_unit:
22231         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22232         if (cu->language == language_cplus
22233             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22234             && die->child != NULL
22235             && (die->tag == DW_TAG_class_type
22236                 || die->tag == DW_TAG_structure_type
22237                 || die->tag == DW_TAG_union_type))
22238           {
22239             char *name = guess_full_die_structure_name (die, cu);
22240             if (name != NULL)
22241               return name;
22242           }
22243         return "";
22244       case DW_TAG_enumeration_type:
22245         parent_type = read_type_die (parent, cu);
22246         if (TYPE_DECLARED_CLASS (parent_type))
22247           {
22248             if (TYPE_TAG_NAME (parent_type) != NULL)
22249               return TYPE_TAG_NAME (parent_type);
22250             return "";
22251           }
22252         /* Fall through.  */
22253       default:
22254         return determine_prefix (parent, cu);
22255       }
22256 }
22257
22258 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22259    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22260    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22261    an obconcat, otherwise allocate storage for the result.  The CU argument is
22262    used to determine the language and hence, the appropriate separator.  */
22263
22264 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22265
22266 static char *
22267 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22268                  int physname, struct dwarf2_cu *cu)
22269 {
22270   const char *lead = "";
22271   const char *sep;
22272
22273   if (suffix == NULL || suffix[0] == '\0'
22274       || prefix == NULL || prefix[0] == '\0')
22275     sep = "";
22276   else if (cu->language == language_d)
22277     {
22278       /* For D, the 'main' function could be defined in any module, but it
22279          should never be prefixed.  */
22280       if (strcmp (suffix, "D main") == 0)
22281         {
22282           prefix = "";
22283           sep = "";
22284         }
22285       else
22286         sep = ".";
22287     }
22288   else if (cu->language == language_fortran && physname)
22289     {
22290       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22291          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22292
22293       lead = "__";
22294       sep = "_MOD_";
22295     }
22296   else
22297     sep = "::";
22298
22299   if (prefix == NULL)
22300     prefix = "";
22301   if (suffix == NULL)
22302     suffix = "";
22303
22304   if (obs == NULL)
22305     {
22306       char *retval
22307         = ((char *)
22308            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22309
22310       strcpy (retval, lead);
22311       strcat (retval, prefix);
22312       strcat (retval, sep);
22313       strcat (retval, suffix);
22314       return retval;
22315     }
22316   else
22317     {
22318       /* We have an obstack.  */
22319       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22320     }
22321 }
22322
22323 /* Return sibling of die, NULL if no sibling.  */
22324
22325 static struct die_info *
22326 sibling_die (struct die_info *die)
22327 {
22328   return die->sibling;
22329 }
22330
22331 /* Get name of a die, return NULL if not found.  */
22332
22333 static const char *
22334 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22335                           struct obstack *obstack)
22336 {
22337   if (name && cu->language == language_cplus)
22338     {
22339       std::string canon_name = cp_canonicalize_string (name);
22340
22341       if (!canon_name.empty ())
22342         {
22343           if (canon_name != name)
22344             name = (const char *) obstack_copy0 (obstack,
22345                                                  canon_name.c_str (),
22346                                                  canon_name.length ());
22347         }
22348     }
22349
22350   return name;
22351 }
22352
22353 /* Get name of a die, return NULL if not found.
22354    Anonymous namespaces are converted to their magic string.  */
22355
22356 static const char *
22357 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22358 {
22359   struct attribute *attr;
22360
22361   attr = dwarf2_attr (die, DW_AT_name, cu);
22362   if ((!attr || !DW_STRING (attr))
22363       && die->tag != DW_TAG_namespace
22364       && die->tag != DW_TAG_class_type
22365       && die->tag != DW_TAG_interface_type
22366       && die->tag != DW_TAG_structure_type
22367       && die->tag != DW_TAG_union_type)
22368     return NULL;
22369
22370   switch (die->tag)
22371     {
22372     case DW_TAG_compile_unit:
22373     case DW_TAG_partial_unit:
22374       /* Compilation units have a DW_AT_name that is a filename, not
22375          a source language identifier.  */
22376     case DW_TAG_enumeration_type:
22377     case DW_TAG_enumerator:
22378       /* These tags always have simple identifiers already; no need
22379          to canonicalize them.  */
22380       return DW_STRING (attr);
22381
22382     case DW_TAG_namespace:
22383       if (attr != NULL && DW_STRING (attr) != NULL)
22384         return DW_STRING (attr);
22385       return CP_ANONYMOUS_NAMESPACE_STR;
22386
22387     case DW_TAG_class_type:
22388     case DW_TAG_interface_type:
22389     case DW_TAG_structure_type:
22390     case DW_TAG_union_type:
22391       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22392          structures or unions.  These were of the form "._%d" in GCC 4.1,
22393          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22394          and GCC 4.4.  We work around this problem by ignoring these.  */
22395       if (attr && DW_STRING (attr)
22396           && (startswith (DW_STRING (attr), "._")
22397               || startswith (DW_STRING (attr), "<anonymous")))
22398         return NULL;
22399
22400       /* GCC might emit a nameless typedef that has a linkage name.  See
22401          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22402       if (!attr || DW_STRING (attr) == NULL)
22403         {
22404           char *demangled = NULL;
22405
22406           attr = dw2_linkage_name_attr (die, cu);
22407           if (attr == NULL || DW_STRING (attr) == NULL)
22408             return NULL;
22409
22410           /* Avoid demangling DW_STRING (attr) the second time on a second
22411              call for the same DIE.  */
22412           if (!DW_STRING_IS_CANONICAL (attr))
22413             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22414
22415           if (demangled)
22416             {
22417               const char *base;
22418
22419               /* FIXME: we already did this for the partial symbol... */
22420               DW_STRING (attr)
22421                 = ((const char *)
22422                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
22423                                   demangled, strlen (demangled)));
22424               DW_STRING_IS_CANONICAL (attr) = 1;
22425               xfree (demangled);
22426
22427               /* Strip any leading namespaces/classes, keep only the base name.
22428                  DW_AT_name for named DIEs does not contain the prefixes.  */
22429               base = strrchr (DW_STRING (attr), ':');
22430               if (base && base > DW_STRING (attr) && base[-1] == ':')
22431                 return &base[1];
22432               else
22433                 return DW_STRING (attr);
22434             }
22435         }
22436       break;
22437
22438     default:
22439       break;
22440     }
22441
22442   if (!DW_STRING_IS_CANONICAL (attr))
22443     {
22444       DW_STRING (attr)
22445         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22446                                     &cu->objfile->per_bfd->storage_obstack);
22447       DW_STRING_IS_CANONICAL (attr) = 1;
22448     }
22449   return DW_STRING (attr);
22450 }
22451
22452 /* Return the die that this die in an extension of, or NULL if there
22453    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22454    containing the return value on output.  */
22455
22456 static struct die_info *
22457 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22458 {
22459   struct attribute *attr;
22460
22461   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22462   if (attr == NULL)
22463     return NULL;
22464
22465   return follow_die_ref (die, attr, ext_cu);
22466 }
22467
22468 /* Convert a DIE tag into its string name.  */
22469
22470 static const char *
22471 dwarf_tag_name (unsigned tag)
22472 {
22473   const char *name = get_DW_TAG_name (tag);
22474
22475   if (name == NULL)
22476     return "DW_TAG_<unknown>";
22477
22478   return name;
22479 }
22480
22481 /* Convert a DWARF attribute code into its string name.  */
22482
22483 static const char *
22484 dwarf_attr_name (unsigned attr)
22485 {
22486   const char *name;
22487
22488 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22489   if (attr == DW_AT_MIPS_fde)
22490     return "DW_AT_MIPS_fde";
22491 #else
22492   if (attr == DW_AT_HP_block_index)
22493     return "DW_AT_HP_block_index";
22494 #endif
22495
22496   name = get_DW_AT_name (attr);
22497
22498   if (name == NULL)
22499     return "DW_AT_<unknown>";
22500
22501   return name;
22502 }
22503
22504 /* Convert a DWARF value form code into its string name.  */
22505
22506 static const char *
22507 dwarf_form_name (unsigned form)
22508 {
22509   const char *name = get_DW_FORM_name (form);
22510
22511   if (name == NULL)
22512     return "DW_FORM_<unknown>";
22513
22514   return name;
22515 }
22516
22517 static const char *
22518 dwarf_bool_name (unsigned mybool)
22519 {
22520   if (mybool)
22521     return "TRUE";
22522   else
22523     return "FALSE";
22524 }
22525
22526 /* Convert a DWARF type code into its string name.  */
22527
22528 static const char *
22529 dwarf_type_encoding_name (unsigned enc)
22530 {
22531   const char *name = get_DW_ATE_name (enc);
22532
22533   if (name == NULL)
22534     return "DW_ATE_<unknown>";
22535
22536   return name;
22537 }
22538
22539 static void
22540 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22541 {
22542   unsigned int i;
22543
22544   print_spaces (indent, f);
22545   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22546                       dwarf_tag_name (die->tag), die->abbrev,
22547                       to_underlying (die->sect_off));
22548
22549   if (die->parent != NULL)
22550     {
22551       print_spaces (indent, f);
22552       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22553                           to_underlying (die->parent->sect_off));
22554     }
22555
22556   print_spaces (indent, f);
22557   fprintf_unfiltered (f, "  has children: %s\n",
22558            dwarf_bool_name (die->child != NULL));
22559
22560   print_spaces (indent, f);
22561   fprintf_unfiltered (f, "  attributes:\n");
22562
22563   for (i = 0; i < die->num_attrs; ++i)
22564     {
22565       print_spaces (indent, f);
22566       fprintf_unfiltered (f, "    %s (%s) ",
22567                dwarf_attr_name (die->attrs[i].name),
22568                dwarf_form_name (die->attrs[i].form));
22569
22570       switch (die->attrs[i].form)
22571         {
22572         case DW_FORM_addr:
22573         case DW_FORM_GNU_addr_index:
22574           fprintf_unfiltered (f, "address: ");
22575           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22576           break;
22577         case DW_FORM_block2:
22578         case DW_FORM_block4:
22579         case DW_FORM_block:
22580         case DW_FORM_block1:
22581           fprintf_unfiltered (f, "block: size %s",
22582                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22583           break;
22584         case DW_FORM_exprloc:
22585           fprintf_unfiltered (f, "expression: size %s",
22586                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22587           break;
22588         case DW_FORM_data16:
22589           fprintf_unfiltered (f, "constant of 16 bytes");
22590           break;
22591         case DW_FORM_ref_addr:
22592           fprintf_unfiltered (f, "ref address: ");
22593           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22594           break;
22595         case DW_FORM_GNU_ref_alt:
22596           fprintf_unfiltered (f, "alt ref address: ");
22597           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22598           break;
22599         case DW_FORM_ref1:
22600         case DW_FORM_ref2:
22601         case DW_FORM_ref4:
22602         case DW_FORM_ref8:
22603         case DW_FORM_ref_udata:
22604           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22605                               (long) (DW_UNSND (&die->attrs[i])));
22606           break;
22607         case DW_FORM_data1:
22608         case DW_FORM_data2:
22609         case DW_FORM_data4:
22610         case DW_FORM_data8:
22611         case DW_FORM_udata:
22612         case DW_FORM_sdata:
22613           fprintf_unfiltered (f, "constant: %s",
22614                               pulongest (DW_UNSND (&die->attrs[i])));
22615           break;
22616         case DW_FORM_sec_offset:
22617           fprintf_unfiltered (f, "section offset: %s",
22618                               pulongest (DW_UNSND (&die->attrs[i])));
22619           break;
22620         case DW_FORM_ref_sig8:
22621           fprintf_unfiltered (f, "signature: %s",
22622                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22623           break;
22624         case DW_FORM_string:
22625         case DW_FORM_strp:
22626         case DW_FORM_line_strp:
22627         case DW_FORM_GNU_str_index:
22628         case DW_FORM_GNU_strp_alt:
22629           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22630                    DW_STRING (&die->attrs[i])
22631                    ? DW_STRING (&die->attrs[i]) : "",
22632                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22633           break;
22634         case DW_FORM_flag:
22635           if (DW_UNSND (&die->attrs[i]))
22636             fprintf_unfiltered (f, "flag: TRUE");
22637           else
22638             fprintf_unfiltered (f, "flag: FALSE");
22639           break;
22640         case DW_FORM_flag_present:
22641           fprintf_unfiltered (f, "flag: TRUE");
22642           break;
22643         case DW_FORM_indirect:
22644           /* The reader will have reduced the indirect form to
22645              the "base form" so this form should not occur.  */
22646           fprintf_unfiltered (f, 
22647                               "unexpected attribute form: DW_FORM_indirect");
22648           break;
22649         case DW_FORM_implicit_const:
22650           fprintf_unfiltered (f, "constant: %s",
22651                               plongest (DW_SND (&die->attrs[i])));
22652           break;
22653         default:
22654           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22655                    die->attrs[i].form);
22656           break;
22657         }
22658       fprintf_unfiltered (f, "\n");
22659     }
22660 }
22661
22662 static void
22663 dump_die_for_error (struct die_info *die)
22664 {
22665   dump_die_shallow (gdb_stderr, 0, die);
22666 }
22667
22668 static void
22669 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22670 {
22671   int indent = level * 4;
22672
22673   gdb_assert (die != NULL);
22674
22675   if (level >= max_level)
22676     return;
22677
22678   dump_die_shallow (f, indent, die);
22679
22680   if (die->child != NULL)
22681     {
22682       print_spaces (indent, f);
22683       fprintf_unfiltered (f, "  Children:");
22684       if (level + 1 < max_level)
22685         {
22686           fprintf_unfiltered (f, "\n");
22687           dump_die_1 (f, level + 1, max_level, die->child);
22688         }
22689       else
22690         {
22691           fprintf_unfiltered (f,
22692                               " [not printed, max nesting level reached]\n");
22693         }
22694     }
22695
22696   if (die->sibling != NULL && level > 0)
22697     {
22698       dump_die_1 (f, level, max_level, die->sibling);
22699     }
22700 }
22701
22702 /* This is called from the pdie macro in gdbinit.in.
22703    It's not static so gcc will keep a copy callable from gdb.  */
22704
22705 void
22706 dump_die (struct die_info *die, int max_level)
22707 {
22708   dump_die_1 (gdb_stdlog, 0, max_level, die);
22709 }
22710
22711 static void
22712 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22713 {
22714   void **slot;
22715
22716   slot = htab_find_slot_with_hash (cu->die_hash, die,
22717                                    to_underlying (die->sect_off),
22718                                    INSERT);
22719
22720   *slot = die;
22721 }
22722
22723 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22724    required kind.  */
22725
22726 static sect_offset
22727 dwarf2_get_ref_die_offset (const struct attribute *attr)
22728 {
22729   if (attr_form_is_ref (attr))
22730     return (sect_offset) DW_UNSND (attr);
22731
22732   complaint (&symfile_complaints,
22733              _("unsupported die ref attribute form: '%s'"),
22734              dwarf_form_name (attr->form));
22735   return {};
22736 }
22737
22738 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22739  * the value held by the attribute is not constant.  */
22740
22741 static LONGEST
22742 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22743 {
22744   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22745     return DW_SND (attr);
22746   else if (attr->form == DW_FORM_udata
22747            || attr->form == DW_FORM_data1
22748            || attr->form == DW_FORM_data2
22749            || attr->form == DW_FORM_data4
22750            || attr->form == DW_FORM_data8)
22751     return DW_UNSND (attr);
22752   else
22753     {
22754       /* For DW_FORM_data16 see attr_form_is_constant.  */
22755       complaint (&symfile_complaints,
22756                  _("Attribute value is not a constant (%s)"),
22757                  dwarf_form_name (attr->form));
22758       return default_value;
22759     }
22760 }
22761
22762 /* Follow reference or signature attribute ATTR of SRC_DIE.
22763    On entry *REF_CU is the CU of SRC_DIE.
22764    On exit *REF_CU is the CU of the result.  */
22765
22766 static struct die_info *
22767 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22768                        struct dwarf2_cu **ref_cu)
22769 {
22770   struct die_info *die;
22771
22772   if (attr_form_is_ref (attr))
22773     die = follow_die_ref (src_die, attr, ref_cu);
22774   else if (attr->form == DW_FORM_ref_sig8)
22775     die = follow_die_sig (src_die, attr, ref_cu);
22776   else
22777     {
22778       dump_die_for_error (src_die);
22779       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22780              objfile_name ((*ref_cu)->objfile));
22781     }
22782
22783   return die;
22784 }
22785
22786 /* Follow reference OFFSET.
22787    On entry *REF_CU is the CU of the source die referencing OFFSET.
22788    On exit *REF_CU is the CU of the result.
22789    Returns NULL if OFFSET is invalid.  */
22790
22791 static struct die_info *
22792 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22793                    struct dwarf2_cu **ref_cu)
22794 {
22795   struct die_info temp_die;
22796   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22797
22798   gdb_assert (cu->per_cu != NULL);
22799
22800   target_cu = cu;
22801
22802   if (cu->per_cu->is_debug_types)
22803     {
22804       /* .debug_types CUs cannot reference anything outside their CU.
22805          If they need to, they have to reference a signatured type via
22806          DW_FORM_ref_sig8.  */
22807       if (!offset_in_cu_p (&cu->header, sect_off))
22808         return NULL;
22809     }
22810   else if (offset_in_dwz != cu->per_cu->is_dwz
22811            || !offset_in_cu_p (&cu->header, sect_off))
22812     {
22813       struct dwarf2_per_cu_data *per_cu;
22814
22815       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22816                                                  cu->objfile);
22817
22818       /* If necessary, add it to the queue and load its DIEs.  */
22819       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22820         load_full_comp_unit (per_cu, cu->language);
22821
22822       target_cu = per_cu->cu;
22823     }
22824   else if (cu->dies == NULL)
22825     {
22826       /* We're loading full DIEs during partial symbol reading.  */
22827       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22828       load_full_comp_unit (cu->per_cu, language_minimal);
22829     }
22830
22831   *ref_cu = target_cu;
22832   temp_die.sect_off = sect_off;
22833   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22834                                                   &temp_die,
22835                                                   to_underlying (sect_off));
22836 }
22837
22838 /* Follow reference attribute ATTR of SRC_DIE.
22839    On entry *REF_CU is the CU of SRC_DIE.
22840    On exit *REF_CU is the CU of the result.  */
22841
22842 static struct die_info *
22843 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22844                 struct dwarf2_cu **ref_cu)
22845 {
22846   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22847   struct dwarf2_cu *cu = *ref_cu;
22848   struct die_info *die;
22849
22850   die = follow_die_offset (sect_off,
22851                            (attr->form == DW_FORM_GNU_ref_alt
22852                             || cu->per_cu->is_dwz),
22853                            ref_cu);
22854   if (!die)
22855     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
22856            "at 0x%x [in module %s]"),
22857            to_underlying (sect_off), to_underlying (src_die->sect_off),
22858            objfile_name (cu->objfile));
22859
22860   return die;
22861 }
22862
22863 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22864    Returned value is intended for DW_OP_call*.  Returned
22865    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
22866
22867 struct dwarf2_locexpr_baton
22868 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22869                                struct dwarf2_per_cu_data *per_cu,
22870                                CORE_ADDR (*get_frame_pc) (void *baton),
22871                                void *baton)
22872 {
22873   struct dwarf2_cu *cu;
22874   struct die_info *die;
22875   struct attribute *attr;
22876   struct dwarf2_locexpr_baton retval;
22877
22878   dw2_setup (per_cu->objfile);
22879
22880   if (per_cu->cu == NULL)
22881     load_cu (per_cu);
22882   cu = per_cu->cu;
22883   if (cu == NULL)
22884     {
22885       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22886          Instead just throw an error, not much else we can do.  */
22887       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
22888              to_underlying (sect_off), objfile_name (per_cu->objfile));
22889     }
22890
22891   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22892   if (!die)
22893     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
22894            to_underlying (sect_off), objfile_name (per_cu->objfile));
22895
22896   attr = dwarf2_attr (die, DW_AT_location, cu);
22897   if (!attr)
22898     {
22899       /* DWARF: "If there is no such attribute, then there is no effect.".
22900          DATA is ignored if SIZE is 0.  */
22901
22902       retval.data = NULL;
22903       retval.size = 0;
22904     }
22905   else if (attr_form_is_section_offset (attr))
22906     {
22907       struct dwarf2_loclist_baton loclist_baton;
22908       CORE_ADDR pc = (*get_frame_pc) (baton);
22909       size_t size;
22910
22911       fill_in_loclist_baton (cu, &loclist_baton, attr);
22912
22913       retval.data = dwarf2_find_location_expression (&loclist_baton,
22914                                                      &size, pc);
22915       retval.size = size;
22916     }
22917   else
22918     {
22919       if (!attr_form_is_block (attr))
22920         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
22921                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22922                to_underlying (sect_off), objfile_name (per_cu->objfile));
22923
22924       retval.data = DW_BLOCK (attr)->data;
22925       retval.size = DW_BLOCK (attr)->size;
22926     }
22927   retval.per_cu = cu->per_cu;
22928
22929   age_cached_comp_units ();
22930
22931   return retval;
22932 }
22933
22934 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22935    offset.  */
22936
22937 struct dwarf2_locexpr_baton
22938 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22939                              struct dwarf2_per_cu_data *per_cu,
22940                              CORE_ADDR (*get_frame_pc) (void *baton),
22941                              void *baton)
22942 {
22943   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22944
22945   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22946 }
22947
22948 /* Write a constant of a given type as target-ordered bytes into
22949    OBSTACK.  */
22950
22951 static const gdb_byte *
22952 write_constant_as_bytes (struct obstack *obstack,
22953                          enum bfd_endian byte_order,
22954                          struct type *type,
22955                          ULONGEST value,
22956                          LONGEST *len)
22957 {
22958   gdb_byte *result;
22959
22960   *len = TYPE_LENGTH (type);
22961   result = (gdb_byte *) obstack_alloc (obstack, *len);
22962   store_unsigned_integer (result, *len, byte_order, value);
22963
22964   return result;
22965 }
22966
22967 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22968    pointer to the constant bytes and set LEN to the length of the
22969    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22970    does not have a DW_AT_const_value, return NULL.  */
22971
22972 const gdb_byte *
22973 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22974                              struct dwarf2_per_cu_data *per_cu,
22975                              struct obstack *obstack,
22976                              LONGEST *len)
22977 {
22978   struct dwarf2_cu *cu;
22979   struct die_info *die;
22980   struct attribute *attr;
22981   const gdb_byte *result = NULL;
22982   struct type *type;
22983   LONGEST value;
22984   enum bfd_endian byte_order;
22985
22986   dw2_setup (per_cu->objfile);
22987
22988   if (per_cu->cu == NULL)
22989     load_cu (per_cu);
22990   cu = per_cu->cu;
22991   if (cu == NULL)
22992     {
22993       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22994          Instead just throw an error, not much else we can do.  */
22995       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
22996              to_underlying (sect_off), objfile_name (per_cu->objfile));
22997     }
22998
22999   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23000   if (!die)
23001     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23002            to_underlying (sect_off), objfile_name (per_cu->objfile));
23003
23004
23005   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23006   if (attr == NULL)
23007     return NULL;
23008
23009   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
23010                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23011
23012   switch (attr->form)
23013     {
23014     case DW_FORM_addr:
23015     case DW_FORM_GNU_addr_index:
23016       {
23017         gdb_byte *tem;
23018
23019         *len = cu->header.addr_size;
23020         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23021         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23022         result = tem;
23023       }
23024       break;
23025     case DW_FORM_string:
23026     case DW_FORM_strp:
23027     case DW_FORM_GNU_str_index:
23028     case DW_FORM_GNU_strp_alt:
23029       /* DW_STRING is already allocated on the objfile obstack, point
23030          directly to it.  */
23031       result = (const gdb_byte *) DW_STRING (attr);
23032       *len = strlen (DW_STRING (attr));
23033       break;
23034     case DW_FORM_block1:
23035     case DW_FORM_block2:
23036     case DW_FORM_block4:
23037     case DW_FORM_block:
23038     case DW_FORM_exprloc:
23039     case DW_FORM_data16:
23040       result = DW_BLOCK (attr)->data;
23041       *len = DW_BLOCK (attr)->size;
23042       break;
23043
23044       /* The DW_AT_const_value attributes are supposed to carry the
23045          symbol's value "represented as it would be on the target
23046          architecture."  By the time we get here, it's already been
23047          converted to host endianness, so we just need to sign- or
23048          zero-extend it as appropriate.  */
23049     case DW_FORM_data1:
23050       type = die_type (die, cu);
23051       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23052       if (result == NULL)
23053         result = write_constant_as_bytes (obstack, byte_order,
23054                                           type, value, len);
23055       break;
23056     case DW_FORM_data2:
23057       type = die_type (die, cu);
23058       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23059       if (result == NULL)
23060         result = write_constant_as_bytes (obstack, byte_order,
23061                                           type, value, len);
23062       break;
23063     case DW_FORM_data4:
23064       type = die_type (die, cu);
23065       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23066       if (result == NULL)
23067         result = write_constant_as_bytes (obstack, byte_order,
23068                                           type, value, len);
23069       break;
23070     case DW_FORM_data8:
23071       type = die_type (die, cu);
23072       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23073       if (result == NULL)
23074         result = write_constant_as_bytes (obstack, byte_order,
23075                                           type, value, len);
23076       break;
23077
23078     case DW_FORM_sdata:
23079     case DW_FORM_implicit_const:
23080       type = die_type (die, cu);
23081       result = write_constant_as_bytes (obstack, byte_order,
23082                                         type, DW_SND (attr), len);
23083       break;
23084
23085     case DW_FORM_udata:
23086       type = die_type (die, cu);
23087       result = write_constant_as_bytes (obstack, byte_order,
23088                                         type, DW_UNSND (attr), len);
23089       break;
23090
23091     default:
23092       complaint (&symfile_complaints,
23093                  _("unsupported const value attribute form: '%s'"),
23094                  dwarf_form_name (attr->form));
23095       break;
23096     }
23097
23098   return result;
23099 }
23100
23101 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23102    valid type for this die is found.  */
23103
23104 struct type *
23105 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23106                                 struct dwarf2_per_cu_data *per_cu)
23107 {
23108   struct dwarf2_cu *cu;
23109   struct die_info *die;
23110
23111   dw2_setup (per_cu->objfile);
23112
23113   if (per_cu->cu == NULL)
23114     load_cu (per_cu);
23115   cu = per_cu->cu;
23116   if (!cu)
23117     return NULL;
23118
23119   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23120   if (!die)
23121     return NULL;
23122
23123   return die_type (die, cu);
23124 }
23125
23126 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23127    PER_CU.  */
23128
23129 struct type *
23130 dwarf2_get_die_type (cu_offset die_offset,
23131                      struct dwarf2_per_cu_data *per_cu)
23132 {
23133   dw2_setup (per_cu->objfile);
23134
23135   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23136   return get_die_type_at_offset (die_offset_sect, per_cu);
23137 }
23138
23139 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23140    On entry *REF_CU is the CU of SRC_DIE.
23141    On exit *REF_CU is the CU of the result.
23142    Returns NULL if the referenced DIE isn't found.  */
23143
23144 static struct die_info *
23145 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23146                   struct dwarf2_cu **ref_cu)
23147 {
23148   struct die_info temp_die;
23149   struct dwarf2_cu *sig_cu;
23150   struct die_info *die;
23151
23152   /* While it might be nice to assert sig_type->type == NULL here,
23153      we can get here for DW_AT_imported_declaration where we need
23154      the DIE not the type.  */
23155
23156   /* If necessary, add it to the queue and load its DIEs.  */
23157
23158   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23159     read_signatured_type (sig_type);
23160
23161   sig_cu = sig_type->per_cu.cu;
23162   gdb_assert (sig_cu != NULL);
23163   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23164   temp_die.sect_off = sig_type->type_offset_in_section;
23165   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23166                                                  to_underlying (temp_die.sect_off));
23167   if (die)
23168     {
23169       /* For .gdb_index version 7 keep track of included TUs.
23170          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23171       if (dwarf2_per_objfile->index_table != NULL
23172           && dwarf2_per_objfile->index_table->version <= 7)
23173         {
23174           VEC_safe_push (dwarf2_per_cu_ptr,
23175                          (*ref_cu)->per_cu->imported_symtabs,
23176                          sig_cu->per_cu);
23177         }
23178
23179       *ref_cu = sig_cu;
23180       return die;
23181     }
23182
23183   return NULL;
23184 }
23185
23186 /* Follow signatured type referenced by ATTR in SRC_DIE.
23187    On entry *REF_CU is the CU of SRC_DIE.
23188    On exit *REF_CU is the CU of the result.
23189    The result is the DIE of the type.
23190    If the referenced type cannot be found an error is thrown.  */
23191
23192 static struct die_info *
23193 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23194                 struct dwarf2_cu **ref_cu)
23195 {
23196   ULONGEST signature = DW_SIGNATURE (attr);
23197   struct signatured_type *sig_type;
23198   struct die_info *die;
23199
23200   gdb_assert (attr->form == DW_FORM_ref_sig8);
23201
23202   sig_type = lookup_signatured_type (*ref_cu, signature);
23203   /* sig_type will be NULL if the signatured type is missing from
23204      the debug info.  */
23205   if (sig_type == NULL)
23206     {
23207       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23208                " from DIE at 0x%x [in module %s]"),
23209              hex_string (signature), to_underlying (src_die->sect_off),
23210              objfile_name ((*ref_cu)->objfile));
23211     }
23212
23213   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23214   if (die == NULL)
23215     {
23216       dump_die_for_error (src_die);
23217       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23218                " from DIE at 0x%x [in module %s]"),
23219              hex_string (signature), to_underlying (src_die->sect_off),
23220              objfile_name ((*ref_cu)->objfile));
23221     }
23222
23223   return die;
23224 }
23225
23226 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23227    reading in and processing the type unit if necessary.  */
23228
23229 static struct type *
23230 get_signatured_type (struct die_info *die, ULONGEST signature,
23231                      struct dwarf2_cu *cu)
23232 {
23233   struct signatured_type *sig_type;
23234   struct dwarf2_cu *type_cu;
23235   struct die_info *type_die;
23236   struct type *type;
23237
23238   sig_type = lookup_signatured_type (cu, signature);
23239   /* sig_type will be NULL if the signatured type is missing from
23240      the debug info.  */
23241   if (sig_type == NULL)
23242     {
23243       complaint (&symfile_complaints,
23244                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23245                    " from DIE at 0x%x [in module %s]"),
23246                  hex_string (signature), to_underlying (die->sect_off),
23247                  objfile_name (dwarf2_per_objfile->objfile));
23248       return build_error_marker_type (cu, die);
23249     }
23250
23251   /* If we already know the type we're done.  */
23252   if (sig_type->type != NULL)
23253     return sig_type->type;
23254
23255   type_cu = cu;
23256   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23257   if (type_die != NULL)
23258     {
23259       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23260          is created.  This is important, for example, because for c++ classes
23261          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23262       type = read_type_die (type_die, type_cu);
23263       if (type == NULL)
23264         {
23265           complaint (&symfile_complaints,
23266                      _("Dwarf Error: Cannot build signatured type %s"
23267                        " referenced from DIE at 0x%x [in module %s]"),
23268                      hex_string (signature), to_underlying (die->sect_off),
23269                      objfile_name (dwarf2_per_objfile->objfile));
23270           type = build_error_marker_type (cu, die);
23271         }
23272     }
23273   else
23274     {
23275       complaint (&symfile_complaints,
23276                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23277                    " from DIE at 0x%x [in module %s]"),
23278                  hex_string (signature), to_underlying (die->sect_off),
23279                  objfile_name (dwarf2_per_objfile->objfile));
23280       type = build_error_marker_type (cu, die);
23281     }
23282   sig_type->type = type;
23283
23284   return type;
23285 }
23286
23287 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23288    reading in and processing the type unit if necessary.  */
23289
23290 static struct type *
23291 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23292                           struct dwarf2_cu *cu) /* ARI: editCase function */
23293 {
23294   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23295   if (attr_form_is_ref (attr))
23296     {
23297       struct dwarf2_cu *type_cu = cu;
23298       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23299
23300       return read_type_die (type_die, type_cu);
23301     }
23302   else if (attr->form == DW_FORM_ref_sig8)
23303     {
23304       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23305     }
23306   else
23307     {
23308       complaint (&symfile_complaints,
23309                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23310                    " at 0x%x [in module %s]"),
23311                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23312                  objfile_name (dwarf2_per_objfile->objfile));
23313       return build_error_marker_type (cu, die);
23314     }
23315 }
23316
23317 /* Load the DIEs associated with type unit PER_CU into memory.  */
23318
23319 static void
23320 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23321 {
23322   struct signatured_type *sig_type;
23323
23324   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23325   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23326
23327   /* We have the per_cu, but we need the signatured_type.
23328      Fortunately this is an easy translation.  */
23329   gdb_assert (per_cu->is_debug_types);
23330   sig_type = (struct signatured_type *) per_cu;
23331
23332   gdb_assert (per_cu->cu == NULL);
23333
23334   read_signatured_type (sig_type);
23335
23336   gdb_assert (per_cu->cu != NULL);
23337 }
23338
23339 /* die_reader_func for read_signatured_type.
23340    This is identical to load_full_comp_unit_reader,
23341    but is kept separate for now.  */
23342
23343 static void
23344 read_signatured_type_reader (const struct die_reader_specs *reader,
23345                              const gdb_byte *info_ptr,
23346                              struct die_info *comp_unit_die,
23347                              int has_children,
23348                              void *data)
23349 {
23350   struct dwarf2_cu *cu = reader->cu;
23351
23352   gdb_assert (cu->die_hash == NULL);
23353   cu->die_hash =
23354     htab_create_alloc_ex (cu->header.length / 12,
23355                           die_hash,
23356                           die_eq,
23357                           NULL,
23358                           &cu->comp_unit_obstack,
23359                           hashtab_obstack_allocate,
23360                           dummy_obstack_deallocate);
23361
23362   if (has_children)
23363     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23364                                                   &info_ptr, comp_unit_die);
23365   cu->dies = comp_unit_die;
23366   /* comp_unit_die is not stored in die_hash, no need.  */
23367
23368   /* We try not to read any attributes in this function, because not
23369      all CUs needed for references have been loaded yet, and symbol
23370      table processing isn't initialized.  But we have to set the CU language,
23371      or we won't be able to build types correctly.
23372      Similarly, if we do not read the producer, we can not apply
23373      producer-specific interpretation.  */
23374   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23375 }
23376
23377 /* Read in a signatured type and build its CU and DIEs.
23378    If the type is a stub for the real type in a DWO file,
23379    read in the real type from the DWO file as well.  */
23380
23381 static void
23382 read_signatured_type (struct signatured_type *sig_type)
23383 {
23384   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23385
23386   gdb_assert (per_cu->is_debug_types);
23387   gdb_assert (per_cu->cu == NULL);
23388
23389   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23390                            read_signatured_type_reader, NULL);
23391   sig_type->per_cu.tu_read = 1;
23392 }
23393
23394 /* Decode simple location descriptions.
23395    Given a pointer to a dwarf block that defines a location, compute
23396    the location and return the value.
23397
23398    NOTE drow/2003-11-18: This function is called in two situations
23399    now: for the address of static or global variables (partial symbols
23400    only) and for offsets into structures which are expected to be
23401    (more or less) constant.  The partial symbol case should go away,
23402    and only the constant case should remain.  That will let this
23403    function complain more accurately.  A few special modes are allowed
23404    without complaint for global variables (for instance, global
23405    register values and thread-local values).
23406
23407    A location description containing no operations indicates that the
23408    object is optimized out.  The return value is 0 for that case.
23409    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23410    callers will only want a very basic result and this can become a
23411    complaint.
23412
23413    Note that stack[0] is unused except as a default error return.  */
23414
23415 static CORE_ADDR
23416 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23417 {
23418   struct objfile *objfile = cu->objfile;
23419   size_t i;
23420   size_t size = blk->size;
23421   const gdb_byte *data = blk->data;
23422   CORE_ADDR stack[64];
23423   int stacki;
23424   unsigned int bytes_read, unsnd;
23425   gdb_byte op;
23426
23427   i = 0;
23428   stacki = 0;
23429   stack[stacki] = 0;
23430   stack[++stacki] = 0;
23431
23432   while (i < size)
23433     {
23434       op = data[i++];
23435       switch (op)
23436         {
23437         case DW_OP_lit0:
23438         case DW_OP_lit1:
23439         case DW_OP_lit2:
23440         case DW_OP_lit3:
23441         case DW_OP_lit4:
23442         case DW_OP_lit5:
23443         case DW_OP_lit6:
23444         case DW_OP_lit7:
23445         case DW_OP_lit8:
23446         case DW_OP_lit9:
23447         case DW_OP_lit10:
23448         case DW_OP_lit11:
23449         case DW_OP_lit12:
23450         case DW_OP_lit13:
23451         case DW_OP_lit14:
23452         case DW_OP_lit15:
23453         case DW_OP_lit16:
23454         case DW_OP_lit17:
23455         case DW_OP_lit18:
23456         case DW_OP_lit19:
23457         case DW_OP_lit20:
23458         case DW_OP_lit21:
23459         case DW_OP_lit22:
23460         case DW_OP_lit23:
23461         case DW_OP_lit24:
23462         case DW_OP_lit25:
23463         case DW_OP_lit26:
23464         case DW_OP_lit27:
23465         case DW_OP_lit28:
23466         case DW_OP_lit29:
23467         case DW_OP_lit30:
23468         case DW_OP_lit31:
23469           stack[++stacki] = op - DW_OP_lit0;
23470           break;
23471
23472         case DW_OP_reg0:
23473         case DW_OP_reg1:
23474         case DW_OP_reg2:
23475         case DW_OP_reg3:
23476         case DW_OP_reg4:
23477         case DW_OP_reg5:
23478         case DW_OP_reg6:
23479         case DW_OP_reg7:
23480         case DW_OP_reg8:
23481         case DW_OP_reg9:
23482         case DW_OP_reg10:
23483         case DW_OP_reg11:
23484         case DW_OP_reg12:
23485         case DW_OP_reg13:
23486         case DW_OP_reg14:
23487         case DW_OP_reg15:
23488         case DW_OP_reg16:
23489         case DW_OP_reg17:
23490         case DW_OP_reg18:
23491         case DW_OP_reg19:
23492         case DW_OP_reg20:
23493         case DW_OP_reg21:
23494         case DW_OP_reg22:
23495         case DW_OP_reg23:
23496         case DW_OP_reg24:
23497         case DW_OP_reg25:
23498         case DW_OP_reg26:
23499         case DW_OP_reg27:
23500         case DW_OP_reg28:
23501         case DW_OP_reg29:
23502         case DW_OP_reg30:
23503         case DW_OP_reg31:
23504           stack[++stacki] = op - DW_OP_reg0;
23505           if (i < size)
23506             dwarf2_complex_location_expr_complaint ();
23507           break;
23508
23509         case DW_OP_regx:
23510           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23511           i += bytes_read;
23512           stack[++stacki] = unsnd;
23513           if (i < size)
23514             dwarf2_complex_location_expr_complaint ();
23515           break;
23516
23517         case DW_OP_addr:
23518           stack[++stacki] = read_address (objfile->obfd, &data[i],
23519                                           cu, &bytes_read);
23520           i += bytes_read;
23521           break;
23522
23523         case DW_OP_const1u:
23524           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23525           i += 1;
23526           break;
23527
23528         case DW_OP_const1s:
23529           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23530           i += 1;
23531           break;
23532
23533         case DW_OP_const2u:
23534           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23535           i += 2;
23536           break;
23537
23538         case DW_OP_const2s:
23539           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23540           i += 2;
23541           break;
23542
23543         case DW_OP_const4u:
23544           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23545           i += 4;
23546           break;
23547
23548         case DW_OP_const4s:
23549           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23550           i += 4;
23551           break;
23552
23553         case DW_OP_const8u:
23554           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23555           i += 8;
23556           break;
23557
23558         case DW_OP_constu:
23559           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23560                                                   &bytes_read);
23561           i += bytes_read;
23562           break;
23563
23564         case DW_OP_consts:
23565           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23566           i += bytes_read;
23567           break;
23568
23569         case DW_OP_dup:
23570           stack[stacki + 1] = stack[stacki];
23571           stacki++;
23572           break;
23573
23574         case DW_OP_plus:
23575           stack[stacki - 1] += stack[stacki];
23576           stacki--;
23577           break;
23578
23579         case DW_OP_plus_uconst:
23580           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23581                                                  &bytes_read);
23582           i += bytes_read;
23583           break;
23584
23585         case DW_OP_minus:
23586           stack[stacki - 1] -= stack[stacki];
23587           stacki--;
23588           break;
23589
23590         case DW_OP_deref:
23591           /* If we're not the last op, then we definitely can't encode
23592              this using GDB's address_class enum.  This is valid for partial
23593              global symbols, although the variable's address will be bogus
23594              in the psymtab.  */
23595           if (i < size)
23596             dwarf2_complex_location_expr_complaint ();
23597           break;
23598
23599         case DW_OP_GNU_push_tls_address:
23600         case DW_OP_form_tls_address:
23601           /* The top of the stack has the offset from the beginning
23602              of the thread control block at which the variable is located.  */
23603           /* Nothing should follow this operator, so the top of stack would
23604              be returned.  */
23605           /* This is valid for partial global symbols, but the variable's
23606              address will be bogus in the psymtab.  Make it always at least
23607              non-zero to not look as a variable garbage collected by linker
23608              which have DW_OP_addr 0.  */
23609           if (i < size)
23610             dwarf2_complex_location_expr_complaint ();
23611           stack[stacki]++;
23612           break;
23613
23614         case DW_OP_GNU_uninit:
23615           break;
23616
23617         case DW_OP_GNU_addr_index:
23618         case DW_OP_GNU_const_index:
23619           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23620                                                          &bytes_read);
23621           i += bytes_read;
23622           break;
23623
23624         default:
23625           {
23626             const char *name = get_DW_OP_name (op);
23627
23628             if (name)
23629               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23630                          name);
23631             else
23632               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23633                          op);
23634           }
23635
23636           return (stack[stacki]);
23637         }
23638
23639       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23640          outside of the allocated space.  Also enforce minimum>0.  */
23641       if (stacki >= ARRAY_SIZE (stack) - 1)
23642         {
23643           complaint (&symfile_complaints,
23644                      _("location description stack overflow"));
23645           return 0;
23646         }
23647
23648       if (stacki <= 0)
23649         {
23650           complaint (&symfile_complaints,
23651                      _("location description stack underflow"));
23652           return 0;
23653         }
23654     }
23655   return (stack[stacki]);
23656 }
23657
23658 /* memory allocation interface */
23659
23660 static struct dwarf_block *
23661 dwarf_alloc_block (struct dwarf2_cu *cu)
23662 {
23663   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23664 }
23665
23666 static struct die_info *
23667 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23668 {
23669   struct die_info *die;
23670   size_t size = sizeof (struct die_info);
23671
23672   if (num_attrs > 1)
23673     size += (num_attrs - 1) * sizeof (struct attribute);
23674
23675   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23676   memset (die, 0, sizeof (struct die_info));
23677   return (die);
23678 }
23679
23680 \f
23681 /* Macro support.  */
23682
23683 /* Return file name relative to the compilation directory of file number I in
23684    *LH's file name table.  The result is allocated using xmalloc; the caller is
23685    responsible for freeing it.  */
23686
23687 static char *
23688 file_file_name (int file, struct line_header *lh)
23689 {
23690   /* Is the file number a valid index into the line header's file name
23691      table?  Remember that file numbers start with one, not zero.  */
23692   if (1 <= file && file <= lh->file_names.size ())
23693     {
23694       const file_entry &fe = lh->file_names[file - 1];
23695
23696       if (!IS_ABSOLUTE_PATH (fe.name))
23697         {
23698           const char *dir = fe.include_dir (lh);
23699           if (dir != NULL)
23700             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23701         }
23702       return xstrdup (fe.name);
23703     }
23704   else
23705     {
23706       /* The compiler produced a bogus file number.  We can at least
23707          record the macro definitions made in the file, even if we
23708          won't be able to find the file by name.  */
23709       char fake_name[80];
23710
23711       xsnprintf (fake_name, sizeof (fake_name),
23712                  "<bad macro file number %d>", file);
23713
23714       complaint (&symfile_complaints,
23715                  _("bad file number in macro information (%d)"),
23716                  file);
23717
23718       return xstrdup (fake_name);
23719     }
23720 }
23721
23722 /* Return the full name of file number I in *LH's file name table.
23723    Use COMP_DIR as the name of the current directory of the
23724    compilation.  The result is allocated using xmalloc; the caller is
23725    responsible for freeing it.  */
23726 static char *
23727 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23728 {
23729   /* Is the file number a valid index into the line header's file name
23730      table?  Remember that file numbers start with one, not zero.  */
23731   if (1 <= file && file <= lh->file_names.size ())
23732     {
23733       char *relative = file_file_name (file, lh);
23734
23735       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23736         return relative;
23737       return reconcat (relative, comp_dir, SLASH_STRING,
23738                        relative, (char *) NULL);
23739     }
23740   else
23741     return file_file_name (file, lh);
23742 }
23743
23744
23745 static struct macro_source_file *
23746 macro_start_file (int file, int line,
23747                   struct macro_source_file *current_file,
23748                   struct line_header *lh)
23749 {
23750   /* File name relative to the compilation directory of this source file.  */
23751   char *file_name = file_file_name (file, lh);
23752
23753   if (! current_file)
23754     {
23755       /* Note: We don't create a macro table for this compilation unit
23756          at all until we actually get a filename.  */
23757       struct macro_table *macro_table = get_macro_table ();
23758
23759       /* If we have no current file, then this must be the start_file
23760          directive for the compilation unit's main source file.  */
23761       current_file = macro_set_main (macro_table, file_name);
23762       macro_define_special (macro_table);
23763     }
23764   else
23765     current_file = macro_include (current_file, line, file_name);
23766
23767   xfree (file_name);
23768
23769   return current_file;
23770 }
23771
23772 static const char *
23773 consume_improper_spaces (const char *p, const char *body)
23774 {
23775   if (*p == ' ')
23776     {
23777       complaint (&symfile_complaints,
23778                  _("macro definition contains spaces "
23779                    "in formal argument list:\n`%s'"),
23780                  body);
23781
23782       while (*p == ' ')
23783         p++;
23784     }
23785
23786   return p;
23787 }
23788
23789
23790 static void
23791 parse_macro_definition (struct macro_source_file *file, int line,
23792                         const char *body)
23793 {
23794   const char *p;
23795
23796   /* The body string takes one of two forms.  For object-like macro
23797      definitions, it should be:
23798
23799         <macro name> " " <definition>
23800
23801      For function-like macro definitions, it should be:
23802
23803         <macro name> "() " <definition>
23804      or
23805         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23806
23807      Spaces may appear only where explicitly indicated, and in the
23808      <definition>.
23809
23810      The Dwarf 2 spec says that an object-like macro's name is always
23811      followed by a space, but versions of GCC around March 2002 omit
23812      the space when the macro's definition is the empty string.
23813
23814      The Dwarf 2 spec says that there should be no spaces between the
23815      formal arguments in a function-like macro's formal argument list,
23816      but versions of GCC around March 2002 include spaces after the
23817      commas.  */
23818
23819
23820   /* Find the extent of the macro name.  The macro name is terminated
23821      by either a space or null character (for an object-like macro) or
23822      an opening paren (for a function-like macro).  */
23823   for (p = body; *p; p++)
23824     if (*p == ' ' || *p == '(')
23825       break;
23826
23827   if (*p == ' ' || *p == '\0')
23828     {
23829       /* It's an object-like macro.  */
23830       int name_len = p - body;
23831       char *name = savestring (body, name_len);
23832       const char *replacement;
23833
23834       if (*p == ' ')
23835         replacement = body + name_len + 1;
23836       else
23837         {
23838           dwarf2_macro_malformed_definition_complaint (body);
23839           replacement = body + name_len;
23840         }
23841
23842       macro_define_object (file, line, name, replacement);
23843
23844       xfree (name);
23845     }
23846   else if (*p == '(')
23847     {
23848       /* It's a function-like macro.  */
23849       char *name = savestring (body, p - body);
23850       int argc = 0;
23851       int argv_size = 1;
23852       char **argv = XNEWVEC (char *, argv_size);
23853
23854       p++;
23855
23856       p = consume_improper_spaces (p, body);
23857
23858       /* Parse the formal argument list.  */
23859       while (*p && *p != ')')
23860         {
23861           /* Find the extent of the current argument name.  */
23862           const char *arg_start = p;
23863
23864           while (*p && *p != ',' && *p != ')' && *p != ' ')
23865             p++;
23866
23867           if (! *p || p == arg_start)
23868             dwarf2_macro_malformed_definition_complaint (body);
23869           else
23870             {
23871               /* Make sure argv has room for the new argument.  */
23872               if (argc >= argv_size)
23873                 {
23874                   argv_size *= 2;
23875                   argv = XRESIZEVEC (char *, argv, argv_size);
23876                 }
23877
23878               argv[argc++] = savestring (arg_start, p - arg_start);
23879             }
23880
23881           p = consume_improper_spaces (p, body);
23882
23883           /* Consume the comma, if present.  */
23884           if (*p == ',')
23885             {
23886               p++;
23887
23888               p = consume_improper_spaces (p, body);
23889             }
23890         }
23891
23892       if (*p == ')')
23893         {
23894           p++;
23895
23896           if (*p == ' ')
23897             /* Perfectly formed definition, no complaints.  */
23898             macro_define_function (file, line, name,
23899                                    argc, (const char **) argv,
23900                                    p + 1);
23901           else if (*p == '\0')
23902             {
23903               /* Complain, but do define it.  */
23904               dwarf2_macro_malformed_definition_complaint (body);
23905               macro_define_function (file, line, name,
23906                                      argc, (const char **) argv,
23907                                      p);
23908             }
23909           else
23910             /* Just complain.  */
23911             dwarf2_macro_malformed_definition_complaint (body);
23912         }
23913       else
23914         /* Just complain.  */
23915         dwarf2_macro_malformed_definition_complaint (body);
23916
23917       xfree (name);
23918       {
23919         int i;
23920
23921         for (i = 0; i < argc; i++)
23922           xfree (argv[i]);
23923       }
23924       xfree (argv);
23925     }
23926   else
23927     dwarf2_macro_malformed_definition_complaint (body);
23928 }
23929
23930 /* Skip some bytes from BYTES according to the form given in FORM.
23931    Returns the new pointer.  */
23932
23933 static const gdb_byte *
23934 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23935                  enum dwarf_form form,
23936                  unsigned int offset_size,
23937                  struct dwarf2_section_info *section)
23938 {
23939   unsigned int bytes_read;
23940
23941   switch (form)
23942     {
23943     case DW_FORM_data1:
23944     case DW_FORM_flag:
23945       ++bytes;
23946       break;
23947
23948     case DW_FORM_data2:
23949       bytes += 2;
23950       break;
23951
23952     case DW_FORM_data4:
23953       bytes += 4;
23954       break;
23955
23956     case DW_FORM_data8:
23957       bytes += 8;
23958       break;
23959
23960     case DW_FORM_data16:
23961       bytes += 16;
23962       break;
23963
23964     case DW_FORM_string:
23965       read_direct_string (abfd, bytes, &bytes_read);
23966       bytes += bytes_read;
23967       break;
23968
23969     case DW_FORM_sec_offset:
23970     case DW_FORM_strp:
23971     case DW_FORM_GNU_strp_alt:
23972       bytes += offset_size;
23973       break;
23974
23975     case DW_FORM_block:
23976       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23977       bytes += bytes_read;
23978       break;
23979
23980     case DW_FORM_block1:
23981       bytes += 1 + read_1_byte (abfd, bytes);
23982       break;
23983     case DW_FORM_block2:
23984       bytes += 2 + read_2_bytes (abfd, bytes);
23985       break;
23986     case DW_FORM_block4:
23987       bytes += 4 + read_4_bytes (abfd, bytes);
23988       break;
23989
23990     case DW_FORM_sdata:
23991     case DW_FORM_udata:
23992     case DW_FORM_GNU_addr_index:
23993     case DW_FORM_GNU_str_index:
23994       bytes = gdb_skip_leb128 (bytes, buffer_end);
23995       if (bytes == NULL)
23996         {
23997           dwarf2_section_buffer_overflow_complaint (section);
23998           return NULL;
23999         }
24000       break;
24001
24002     case DW_FORM_implicit_const:
24003       break;
24004
24005     default:
24006       {
24007         complaint (&symfile_complaints,
24008                    _("invalid form 0x%x in `%s'"),
24009                    form, get_section_name (section));
24010         return NULL;
24011       }
24012     }
24013
24014   return bytes;
24015 }
24016
24017 /* A helper for dwarf_decode_macros that handles skipping an unknown
24018    opcode.  Returns an updated pointer to the macro data buffer; or,
24019    on error, issues a complaint and returns NULL.  */
24020
24021 static const gdb_byte *
24022 skip_unknown_opcode (unsigned int opcode,
24023                      const gdb_byte **opcode_definitions,
24024                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24025                      bfd *abfd,
24026                      unsigned int offset_size,
24027                      struct dwarf2_section_info *section)
24028 {
24029   unsigned int bytes_read, i;
24030   unsigned long arg;
24031   const gdb_byte *defn;
24032
24033   if (opcode_definitions[opcode] == NULL)
24034     {
24035       complaint (&symfile_complaints,
24036                  _("unrecognized DW_MACFINO opcode 0x%x"),
24037                  opcode);
24038       return NULL;
24039     }
24040
24041   defn = opcode_definitions[opcode];
24042   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24043   defn += bytes_read;
24044
24045   for (i = 0; i < arg; ++i)
24046     {
24047       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24048                                  (enum dwarf_form) defn[i], offset_size,
24049                                  section);
24050       if (mac_ptr == NULL)
24051         {
24052           /* skip_form_bytes already issued the complaint.  */
24053           return NULL;
24054         }
24055     }
24056
24057   return mac_ptr;
24058 }
24059
24060 /* A helper function which parses the header of a macro section.
24061    If the macro section is the extended (for now called "GNU") type,
24062    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24063    the header, or issues a complaint and returns NULL on error.  */
24064
24065 static const gdb_byte *
24066 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24067                           bfd *abfd,
24068                           const gdb_byte *mac_ptr,
24069                           unsigned int *offset_size,
24070                           int section_is_gnu)
24071 {
24072   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24073
24074   if (section_is_gnu)
24075     {
24076       unsigned int version, flags;
24077
24078       version = read_2_bytes (abfd, mac_ptr);
24079       if (version != 4 && version != 5)
24080         {
24081           complaint (&symfile_complaints,
24082                      _("unrecognized version `%d' in .debug_macro section"),
24083                      version);
24084           return NULL;
24085         }
24086       mac_ptr += 2;
24087
24088       flags = read_1_byte (abfd, mac_ptr);
24089       ++mac_ptr;
24090       *offset_size = (flags & 1) ? 8 : 4;
24091
24092       if ((flags & 2) != 0)
24093         /* We don't need the line table offset.  */
24094         mac_ptr += *offset_size;
24095
24096       /* Vendor opcode descriptions.  */
24097       if ((flags & 4) != 0)
24098         {
24099           unsigned int i, count;
24100
24101           count = read_1_byte (abfd, mac_ptr);
24102           ++mac_ptr;
24103           for (i = 0; i < count; ++i)
24104             {
24105               unsigned int opcode, bytes_read;
24106               unsigned long arg;
24107
24108               opcode = read_1_byte (abfd, mac_ptr);
24109               ++mac_ptr;
24110               opcode_definitions[opcode] = mac_ptr;
24111               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24112               mac_ptr += bytes_read;
24113               mac_ptr += arg;
24114             }
24115         }
24116     }
24117
24118   return mac_ptr;
24119 }
24120
24121 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24122    including DW_MACRO_import.  */
24123
24124 static void
24125 dwarf_decode_macro_bytes (bfd *abfd,
24126                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24127                           struct macro_source_file *current_file,
24128                           struct line_header *lh,
24129                           struct dwarf2_section_info *section,
24130                           int section_is_gnu, int section_is_dwz,
24131                           unsigned int offset_size,
24132                           htab_t include_hash)
24133 {
24134   struct objfile *objfile = dwarf2_per_objfile->objfile;
24135   enum dwarf_macro_record_type macinfo_type;
24136   int at_commandline;
24137   const gdb_byte *opcode_definitions[256];
24138
24139   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24140                                       &offset_size, section_is_gnu);
24141   if (mac_ptr == NULL)
24142     {
24143       /* We already issued a complaint.  */
24144       return;
24145     }
24146
24147   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24148      GDB is still reading the definitions from command line.  First
24149      DW_MACINFO_start_file will need to be ignored as it was already executed
24150      to create CURRENT_FILE for the main source holding also the command line
24151      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24152      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24153
24154   at_commandline = 1;
24155
24156   do
24157     {
24158       /* Do we at least have room for a macinfo type byte?  */
24159       if (mac_ptr >= mac_end)
24160         {
24161           dwarf2_section_buffer_overflow_complaint (section);
24162           break;
24163         }
24164
24165       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24166       mac_ptr++;
24167
24168       /* Note that we rely on the fact that the corresponding GNU and
24169          DWARF constants are the same.  */
24170       switch (macinfo_type)
24171         {
24172           /* A zero macinfo type indicates the end of the macro
24173              information.  */
24174         case 0:
24175           break;
24176
24177         case DW_MACRO_define:
24178         case DW_MACRO_undef:
24179         case DW_MACRO_define_strp:
24180         case DW_MACRO_undef_strp:
24181         case DW_MACRO_define_sup:
24182         case DW_MACRO_undef_sup:
24183           {
24184             unsigned int bytes_read;
24185             int line;
24186             const char *body;
24187             int is_define;
24188
24189             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24190             mac_ptr += bytes_read;
24191
24192             if (macinfo_type == DW_MACRO_define
24193                 || macinfo_type == DW_MACRO_undef)
24194               {
24195                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24196                 mac_ptr += bytes_read;
24197               }
24198             else
24199               {
24200                 LONGEST str_offset;
24201
24202                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24203                 mac_ptr += offset_size;
24204
24205                 if (macinfo_type == DW_MACRO_define_sup
24206                     || macinfo_type == DW_MACRO_undef_sup
24207                     || section_is_dwz)
24208                   {
24209                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
24210
24211                     body = read_indirect_string_from_dwz (dwz, str_offset);
24212                   }
24213                 else
24214                   body = read_indirect_string_at_offset (abfd, str_offset);
24215               }
24216
24217             is_define = (macinfo_type == DW_MACRO_define
24218                          || macinfo_type == DW_MACRO_define_strp
24219                          || macinfo_type == DW_MACRO_define_sup);
24220             if (! current_file)
24221               {
24222                 /* DWARF violation as no main source is present.  */
24223                 complaint (&symfile_complaints,
24224                            _("debug info with no main source gives macro %s "
24225                              "on line %d: %s"),
24226                            is_define ? _("definition") : _("undefinition"),
24227                            line, body);
24228                 break;
24229               }
24230             if ((line == 0 && !at_commandline)
24231                 || (line != 0 && at_commandline))
24232               complaint (&symfile_complaints,
24233                          _("debug info gives %s macro %s with %s line %d: %s"),
24234                          at_commandline ? _("command-line") : _("in-file"),
24235                          is_define ? _("definition") : _("undefinition"),
24236                          line == 0 ? _("zero") : _("non-zero"), line, body);
24237
24238             if (is_define)
24239               parse_macro_definition (current_file, line, body);
24240             else
24241               {
24242                 gdb_assert (macinfo_type == DW_MACRO_undef
24243                             || macinfo_type == DW_MACRO_undef_strp
24244                             || macinfo_type == DW_MACRO_undef_sup);
24245                 macro_undef (current_file, line, body);
24246               }
24247           }
24248           break;
24249
24250         case DW_MACRO_start_file:
24251           {
24252             unsigned int bytes_read;
24253             int line, file;
24254
24255             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24256             mac_ptr += bytes_read;
24257             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24258             mac_ptr += bytes_read;
24259
24260             if ((line == 0 && !at_commandline)
24261                 || (line != 0 && at_commandline))
24262               complaint (&symfile_complaints,
24263                          _("debug info gives source %d included "
24264                            "from %s at %s line %d"),
24265                          file, at_commandline ? _("command-line") : _("file"),
24266                          line == 0 ? _("zero") : _("non-zero"), line);
24267
24268             if (at_commandline)
24269               {
24270                 /* This DW_MACRO_start_file was executed in the
24271                    pass one.  */
24272                 at_commandline = 0;
24273               }
24274             else
24275               current_file = macro_start_file (file, line, current_file, lh);
24276           }
24277           break;
24278
24279         case DW_MACRO_end_file:
24280           if (! current_file)
24281             complaint (&symfile_complaints,
24282                        _("macro debug info has an unmatched "
24283                          "`close_file' directive"));
24284           else
24285             {
24286               current_file = current_file->included_by;
24287               if (! current_file)
24288                 {
24289                   enum dwarf_macro_record_type next_type;
24290
24291                   /* GCC circa March 2002 doesn't produce the zero
24292                      type byte marking the end of the compilation
24293                      unit.  Complain if it's not there, but exit no
24294                      matter what.  */
24295
24296                   /* Do we at least have room for a macinfo type byte?  */
24297                   if (mac_ptr >= mac_end)
24298                     {
24299                       dwarf2_section_buffer_overflow_complaint (section);
24300                       return;
24301                     }
24302
24303                   /* We don't increment mac_ptr here, so this is just
24304                      a look-ahead.  */
24305                   next_type
24306                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24307                                                                   mac_ptr);
24308                   if (next_type != 0)
24309                     complaint (&symfile_complaints,
24310                                _("no terminating 0-type entry for "
24311                                  "macros in `.debug_macinfo' section"));
24312
24313                   return;
24314                 }
24315             }
24316           break;
24317
24318         case DW_MACRO_import:
24319         case DW_MACRO_import_sup:
24320           {
24321             LONGEST offset;
24322             void **slot;
24323             bfd *include_bfd = abfd;
24324             struct dwarf2_section_info *include_section = section;
24325             const gdb_byte *include_mac_end = mac_end;
24326             int is_dwz = section_is_dwz;
24327             const gdb_byte *new_mac_ptr;
24328
24329             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24330             mac_ptr += offset_size;
24331
24332             if (macinfo_type == DW_MACRO_import_sup)
24333               {
24334                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
24335
24336                 dwarf2_read_section (objfile, &dwz->macro);
24337
24338                 include_section = &dwz->macro;
24339                 include_bfd = get_section_bfd_owner (include_section);
24340                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24341                 is_dwz = 1;
24342               }
24343
24344             new_mac_ptr = include_section->buffer + offset;
24345             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24346
24347             if (*slot != NULL)
24348               {
24349                 /* This has actually happened; see
24350                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24351                 complaint (&symfile_complaints,
24352                            _("recursive DW_MACRO_import in "
24353                              ".debug_macro section"));
24354               }
24355             else
24356               {
24357                 *slot = (void *) new_mac_ptr;
24358
24359                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
24360                                           include_mac_end, current_file, lh,
24361                                           section, section_is_gnu, is_dwz,
24362                                           offset_size, include_hash);
24363
24364                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24365               }
24366           }
24367           break;
24368
24369         case DW_MACINFO_vendor_ext:
24370           if (!section_is_gnu)
24371             {
24372               unsigned int bytes_read;
24373
24374               /* This reads the constant, but since we don't recognize
24375                  any vendor extensions, we ignore it.  */
24376               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24377               mac_ptr += bytes_read;
24378               read_direct_string (abfd, mac_ptr, &bytes_read);
24379               mac_ptr += bytes_read;
24380
24381               /* We don't recognize any vendor extensions.  */
24382               break;
24383             }
24384           /* FALLTHROUGH */
24385
24386         default:
24387           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24388                                          mac_ptr, mac_end, abfd, offset_size,
24389                                          section);
24390           if (mac_ptr == NULL)
24391             return;
24392           break;
24393         }
24394     } while (macinfo_type != 0);
24395 }
24396
24397 static void
24398 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24399                      int section_is_gnu)
24400 {
24401   struct objfile *objfile = dwarf2_per_objfile->objfile;
24402   struct line_header *lh = cu->line_header;
24403   bfd *abfd;
24404   const gdb_byte *mac_ptr, *mac_end;
24405   struct macro_source_file *current_file = 0;
24406   enum dwarf_macro_record_type macinfo_type;
24407   unsigned int offset_size = cu->header.offset_size;
24408   const gdb_byte *opcode_definitions[256];
24409   void **slot;
24410   struct dwarf2_section_info *section;
24411   const char *section_name;
24412
24413   if (cu->dwo_unit != NULL)
24414     {
24415       if (section_is_gnu)
24416         {
24417           section = &cu->dwo_unit->dwo_file->sections.macro;
24418           section_name = ".debug_macro.dwo";
24419         }
24420       else
24421         {
24422           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24423           section_name = ".debug_macinfo.dwo";
24424         }
24425     }
24426   else
24427     {
24428       if (section_is_gnu)
24429         {
24430           section = &dwarf2_per_objfile->macro;
24431           section_name = ".debug_macro";
24432         }
24433       else
24434         {
24435           section = &dwarf2_per_objfile->macinfo;
24436           section_name = ".debug_macinfo";
24437         }
24438     }
24439
24440   dwarf2_read_section (objfile, section);
24441   if (section->buffer == NULL)
24442     {
24443       complaint (&symfile_complaints, _("missing %s section"), section_name);
24444       return;
24445     }
24446   abfd = get_section_bfd_owner (section);
24447
24448   /* First pass: Find the name of the base filename.
24449      This filename is needed in order to process all macros whose definition
24450      (or undefinition) comes from the command line.  These macros are defined
24451      before the first DW_MACINFO_start_file entry, and yet still need to be
24452      associated to the base file.
24453
24454      To determine the base file name, we scan the macro definitions until we
24455      reach the first DW_MACINFO_start_file entry.  We then initialize
24456      CURRENT_FILE accordingly so that any macro definition found before the
24457      first DW_MACINFO_start_file can still be associated to the base file.  */
24458
24459   mac_ptr = section->buffer + offset;
24460   mac_end = section->buffer + section->size;
24461
24462   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24463                                       &offset_size, section_is_gnu);
24464   if (mac_ptr == NULL)
24465     {
24466       /* We already issued a complaint.  */
24467       return;
24468     }
24469
24470   do
24471     {
24472       /* Do we at least have room for a macinfo type byte?  */
24473       if (mac_ptr >= mac_end)
24474         {
24475           /* Complaint is printed during the second pass as GDB will probably
24476              stop the first pass earlier upon finding
24477              DW_MACINFO_start_file.  */
24478           break;
24479         }
24480
24481       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24482       mac_ptr++;
24483
24484       /* Note that we rely on the fact that the corresponding GNU and
24485          DWARF constants are the same.  */
24486       switch (macinfo_type)
24487         {
24488           /* A zero macinfo type indicates the end of the macro
24489              information.  */
24490         case 0:
24491           break;
24492
24493         case DW_MACRO_define:
24494         case DW_MACRO_undef:
24495           /* Only skip the data by MAC_PTR.  */
24496           {
24497             unsigned int bytes_read;
24498
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           break;
24505
24506         case DW_MACRO_start_file:
24507           {
24508             unsigned int bytes_read;
24509             int line, file;
24510
24511             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24512             mac_ptr += bytes_read;
24513             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24514             mac_ptr += bytes_read;
24515
24516             current_file = macro_start_file (file, line, current_file, lh);
24517           }
24518           break;
24519
24520         case DW_MACRO_end_file:
24521           /* No data to skip by MAC_PTR.  */
24522           break;
24523
24524         case DW_MACRO_define_strp:
24525         case DW_MACRO_undef_strp:
24526         case DW_MACRO_define_sup:
24527         case DW_MACRO_undef_sup:
24528           {
24529             unsigned int bytes_read;
24530
24531             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24532             mac_ptr += bytes_read;
24533             mac_ptr += offset_size;
24534           }
24535           break;
24536
24537         case DW_MACRO_import:
24538         case DW_MACRO_import_sup:
24539           /* Note that, according to the spec, a transparent include
24540              chain cannot call DW_MACRO_start_file.  So, we can just
24541              skip this opcode.  */
24542           mac_ptr += offset_size;
24543           break;
24544
24545         case DW_MACINFO_vendor_ext:
24546           /* Only skip the data by MAC_PTR.  */
24547           if (!section_is_gnu)
24548             {
24549               unsigned int bytes_read;
24550
24551               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24552               mac_ptr += bytes_read;
24553               read_direct_string (abfd, mac_ptr, &bytes_read);
24554               mac_ptr += bytes_read;
24555             }
24556           /* FALLTHROUGH */
24557
24558         default:
24559           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24560                                          mac_ptr, mac_end, abfd, offset_size,
24561                                          section);
24562           if (mac_ptr == NULL)
24563             return;
24564           break;
24565         }
24566     } while (macinfo_type != 0 && current_file == NULL);
24567
24568   /* Second pass: Process all entries.
24569
24570      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24571      command-line macro definitions/undefinitions.  This flag is unset when we
24572      reach the first DW_MACINFO_start_file entry.  */
24573
24574   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24575                                            htab_eq_pointer,
24576                                            NULL, xcalloc, xfree));
24577   mac_ptr = section->buffer + offset;
24578   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24579   *slot = (void *) mac_ptr;
24580   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
24581                             current_file, lh, section,
24582                             section_is_gnu, 0, offset_size,
24583                             include_hash.get ());
24584 }
24585
24586 /* Check if the attribute's form is a DW_FORM_block*
24587    if so return true else false.  */
24588
24589 static int
24590 attr_form_is_block (const struct attribute *attr)
24591 {
24592   return (attr == NULL ? 0 :
24593       attr->form == DW_FORM_block1
24594       || attr->form == DW_FORM_block2
24595       || attr->form == DW_FORM_block4
24596       || attr->form == DW_FORM_block
24597       || attr->form == DW_FORM_exprloc);
24598 }
24599
24600 /* Return non-zero if ATTR's value is a section offset --- classes
24601    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24602    You may use DW_UNSND (attr) to retrieve such offsets.
24603
24604    Section 7.5.4, "Attribute Encodings", explains that no attribute
24605    may have a value that belongs to more than one of these classes; it
24606    would be ambiguous if we did, because we use the same forms for all
24607    of them.  */
24608
24609 static int
24610 attr_form_is_section_offset (const struct attribute *attr)
24611 {
24612   return (attr->form == DW_FORM_data4
24613           || attr->form == DW_FORM_data8
24614           || attr->form == DW_FORM_sec_offset);
24615 }
24616
24617 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24618    zero otherwise.  When this function returns true, you can apply
24619    dwarf2_get_attr_constant_value to it.
24620
24621    However, note that for some attributes you must check
24622    attr_form_is_section_offset before using this test.  DW_FORM_data4
24623    and DW_FORM_data8 are members of both the constant class, and of
24624    the classes that contain offsets into other debug sections
24625    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24626    that, if an attribute's can be either a constant or one of the
24627    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24628    taken as section offsets, not constants.
24629
24630    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24631    cannot handle that.  */
24632
24633 static int
24634 attr_form_is_constant (const struct attribute *attr)
24635 {
24636   switch (attr->form)
24637     {
24638     case DW_FORM_sdata:
24639     case DW_FORM_udata:
24640     case DW_FORM_data1:
24641     case DW_FORM_data2:
24642     case DW_FORM_data4:
24643     case DW_FORM_data8:
24644     case DW_FORM_implicit_const:
24645       return 1;
24646     default:
24647       return 0;
24648     }
24649 }
24650
24651
24652 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24653    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24654
24655 static int
24656 attr_form_is_ref (const struct attribute *attr)
24657 {
24658   switch (attr->form)
24659     {
24660     case DW_FORM_ref_addr:
24661     case DW_FORM_ref1:
24662     case DW_FORM_ref2:
24663     case DW_FORM_ref4:
24664     case DW_FORM_ref8:
24665     case DW_FORM_ref_udata:
24666     case DW_FORM_GNU_ref_alt:
24667       return 1;
24668     default:
24669       return 0;
24670     }
24671 }
24672
24673 /* Return the .debug_loc section to use for CU.
24674    For DWO files use .debug_loc.dwo.  */
24675
24676 static struct dwarf2_section_info *
24677 cu_debug_loc_section (struct dwarf2_cu *cu)
24678 {
24679   if (cu->dwo_unit)
24680     {
24681       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24682       
24683       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24684     }
24685   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24686                                   : &dwarf2_per_objfile->loc);
24687 }
24688
24689 /* A helper function that fills in a dwarf2_loclist_baton.  */
24690
24691 static void
24692 fill_in_loclist_baton (struct dwarf2_cu *cu,
24693                        struct dwarf2_loclist_baton *baton,
24694                        const struct attribute *attr)
24695 {
24696   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24697
24698   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24699
24700   baton->per_cu = cu->per_cu;
24701   gdb_assert (baton->per_cu);
24702   /* We don't know how long the location list is, but make sure we
24703      don't run off the edge of the section.  */
24704   baton->size = section->size - DW_UNSND (attr);
24705   baton->data = section->buffer + DW_UNSND (attr);
24706   baton->base_address = cu->base_address;
24707   baton->from_dwo = cu->dwo_unit != NULL;
24708 }
24709
24710 static void
24711 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24712                              struct dwarf2_cu *cu, int is_block)
24713 {
24714   struct objfile *objfile = dwarf2_per_objfile->objfile;
24715   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24716
24717   if (attr_form_is_section_offset (attr)
24718       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24719          the section.  If so, fall through to the complaint in the
24720          other branch.  */
24721       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24722     {
24723       struct dwarf2_loclist_baton *baton;
24724
24725       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24726
24727       fill_in_loclist_baton (cu, baton, attr);
24728
24729       if (cu->base_known == 0)
24730         complaint (&symfile_complaints,
24731                    _("Location list used without "
24732                      "specifying the CU base address."));
24733
24734       SYMBOL_ACLASS_INDEX (sym) = (is_block
24735                                    ? dwarf2_loclist_block_index
24736                                    : dwarf2_loclist_index);
24737       SYMBOL_LOCATION_BATON (sym) = baton;
24738     }
24739   else
24740     {
24741       struct dwarf2_locexpr_baton *baton;
24742
24743       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24744       baton->per_cu = cu->per_cu;
24745       gdb_assert (baton->per_cu);
24746
24747       if (attr_form_is_block (attr))
24748         {
24749           /* Note that we're just copying the block's data pointer
24750              here, not the actual data.  We're still pointing into the
24751              info_buffer for SYM's objfile; right now we never release
24752              that buffer, but when we do clean up properly this may
24753              need to change.  */
24754           baton->size = DW_BLOCK (attr)->size;
24755           baton->data = DW_BLOCK (attr)->data;
24756         }
24757       else
24758         {
24759           dwarf2_invalid_attrib_class_complaint ("location description",
24760                                                  SYMBOL_NATURAL_NAME (sym));
24761           baton->size = 0;
24762         }
24763
24764       SYMBOL_ACLASS_INDEX (sym) = (is_block
24765                                    ? dwarf2_locexpr_block_index
24766                                    : dwarf2_locexpr_index);
24767       SYMBOL_LOCATION_BATON (sym) = baton;
24768     }
24769 }
24770
24771 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24772    came from a separate debuginfo file, then the master objfile is
24773    returned.  */
24774
24775 struct objfile *
24776 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24777 {
24778   struct objfile *objfile = per_cu->objfile;
24779
24780   /* Return the master objfile, so that we can report and look up the
24781      correct file containing this variable.  */
24782   if (objfile->separate_debug_objfile_backlink)
24783     objfile = objfile->separate_debug_objfile_backlink;
24784
24785   return objfile;
24786 }
24787
24788 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24789    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24790    CU_HEADERP first.  */
24791
24792 static const struct comp_unit_head *
24793 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24794                        struct dwarf2_per_cu_data *per_cu)
24795 {
24796   const gdb_byte *info_ptr;
24797
24798   if (per_cu->cu)
24799     return &per_cu->cu->header;
24800
24801   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24802
24803   memset (cu_headerp, 0, sizeof (*cu_headerp));
24804   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24805                        rcuh_kind::COMPILE);
24806
24807   return cu_headerp;
24808 }
24809
24810 /* Return the address size given in the compilation unit header for CU.  */
24811
24812 int
24813 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24814 {
24815   struct comp_unit_head cu_header_local;
24816   const struct comp_unit_head *cu_headerp;
24817
24818   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24819
24820   return cu_headerp->addr_size;
24821 }
24822
24823 /* Return the offset size given in the compilation unit header for CU.  */
24824
24825 int
24826 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24827 {
24828   struct comp_unit_head cu_header_local;
24829   const struct comp_unit_head *cu_headerp;
24830
24831   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24832
24833   return cu_headerp->offset_size;
24834 }
24835
24836 /* See its dwarf2loc.h declaration.  */
24837
24838 int
24839 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24840 {
24841   struct comp_unit_head cu_header_local;
24842   const struct comp_unit_head *cu_headerp;
24843
24844   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24845
24846   if (cu_headerp->version == 2)
24847     return cu_headerp->addr_size;
24848   else
24849     return cu_headerp->offset_size;
24850 }
24851
24852 /* Return the text offset of the CU.  The returned offset comes from
24853    this CU's objfile.  If this objfile came from a separate debuginfo
24854    file, then the offset may be different from the corresponding
24855    offset in the parent objfile.  */
24856
24857 CORE_ADDR
24858 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24859 {
24860   struct objfile *objfile = per_cu->objfile;
24861
24862   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24863 }
24864
24865 /* Return DWARF version number of PER_CU.  */
24866
24867 short
24868 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24869 {
24870   return per_cu->dwarf_version;
24871 }
24872
24873 /* Locate the .debug_info compilation unit from CU's objfile which contains
24874    the DIE at OFFSET.  Raises an error on failure.  */
24875
24876 static struct dwarf2_per_cu_data *
24877 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24878                                   unsigned int offset_in_dwz,
24879                                   struct objfile *objfile)
24880 {
24881   struct dwarf2_per_cu_data *this_cu;
24882   int low, high;
24883   const sect_offset *cu_off;
24884
24885   low = 0;
24886   high = dwarf2_per_objfile->n_comp_units - 1;
24887   while (high > low)
24888     {
24889       struct dwarf2_per_cu_data *mid_cu;
24890       int mid = low + (high - low) / 2;
24891
24892       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24893       cu_off = &mid_cu->sect_off;
24894       if (mid_cu->is_dwz > offset_in_dwz
24895           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24896         high = mid;
24897       else
24898         low = mid + 1;
24899     }
24900   gdb_assert (low == high);
24901   this_cu = dwarf2_per_objfile->all_comp_units[low];
24902   cu_off = &this_cu->sect_off;
24903   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24904     {
24905       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24906         error (_("Dwarf Error: could not find partial DIE containing "
24907                "offset 0x%x [in module %s]"),
24908                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
24909
24910       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24911                   <= sect_off);
24912       return dwarf2_per_objfile->all_comp_units[low-1];
24913     }
24914   else
24915     {
24916       this_cu = dwarf2_per_objfile->all_comp_units[low];
24917       if (low == dwarf2_per_objfile->n_comp_units - 1
24918           && sect_off >= this_cu->sect_off + this_cu->length)
24919         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
24920       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24921       return this_cu;
24922     }
24923 }
24924
24925 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24926
24927 static void
24928 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
24929 {
24930   memset (cu, 0, sizeof (*cu));
24931   per_cu->cu = cu;
24932   cu->per_cu = per_cu;
24933   cu->objfile = per_cu->objfile;
24934   obstack_init (&cu->comp_unit_obstack);
24935 }
24936
24937 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24938
24939 static void
24940 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24941                        enum language pretend_language)
24942 {
24943   struct attribute *attr;
24944
24945   /* Set the language we're debugging.  */
24946   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24947   if (attr)
24948     set_cu_language (DW_UNSND (attr), cu);
24949   else
24950     {
24951       cu->language = pretend_language;
24952       cu->language_defn = language_def (cu->language);
24953     }
24954
24955   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24956 }
24957
24958 /* Release one cached compilation unit, CU.  We unlink it from the tree
24959    of compilation units, but we don't remove it from the read_in_chain;
24960    the caller is responsible for that.
24961    NOTE: DATA is a void * because this function is also used as a
24962    cleanup routine.  */
24963
24964 static void
24965 free_heap_comp_unit (void *data)
24966 {
24967   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
24968
24969   gdb_assert (cu->per_cu != NULL);
24970   cu->per_cu->cu = NULL;
24971   cu->per_cu = NULL;
24972
24973   obstack_free (&cu->comp_unit_obstack, NULL);
24974
24975   xfree (cu);
24976 }
24977
24978 /* This cleanup function is passed the address of a dwarf2_cu on the stack
24979    when we're finished with it.  We can't free the pointer itself, but be
24980    sure to unlink it from the cache.  Also release any associated storage.  */
24981
24982 static void
24983 free_stack_comp_unit (void *data)
24984 {
24985   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
24986
24987   gdb_assert (cu->per_cu != NULL);
24988   cu->per_cu->cu = NULL;
24989   cu->per_cu = NULL;
24990
24991   obstack_free (&cu->comp_unit_obstack, NULL);
24992   cu->partial_dies = NULL;
24993 }
24994
24995 /* Free all cached compilation units.  */
24996
24997 static void
24998 free_cached_comp_units (void *data)
24999 {
25000   dwarf2_per_objfile->free_cached_comp_units ();
25001 }
25002
25003 /* Increase the age counter on each cached compilation unit, and free
25004    any that are too old.  */
25005
25006 static void
25007 age_cached_comp_units (void)
25008 {
25009   struct dwarf2_per_cu_data *per_cu, **last_chain;
25010
25011   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25012   per_cu = dwarf2_per_objfile->read_in_chain;
25013   while (per_cu != NULL)
25014     {
25015       per_cu->cu->last_used ++;
25016       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25017         dwarf2_mark (per_cu->cu);
25018       per_cu = per_cu->cu->read_in_chain;
25019     }
25020
25021   per_cu = dwarf2_per_objfile->read_in_chain;
25022   last_chain = &dwarf2_per_objfile->read_in_chain;
25023   while (per_cu != NULL)
25024     {
25025       struct dwarf2_per_cu_data *next_cu;
25026
25027       next_cu = per_cu->cu->read_in_chain;
25028
25029       if (!per_cu->cu->mark)
25030         {
25031           free_heap_comp_unit (per_cu->cu);
25032           *last_chain = next_cu;
25033         }
25034       else
25035         last_chain = &per_cu->cu->read_in_chain;
25036
25037       per_cu = next_cu;
25038     }
25039 }
25040
25041 /* Remove a single compilation unit from the cache.  */
25042
25043 static void
25044 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25045 {
25046   struct dwarf2_per_cu_data *per_cu, **last_chain;
25047
25048   per_cu = dwarf2_per_objfile->read_in_chain;
25049   last_chain = &dwarf2_per_objfile->read_in_chain;
25050   while (per_cu != NULL)
25051     {
25052       struct dwarf2_per_cu_data *next_cu;
25053
25054       next_cu = per_cu->cu->read_in_chain;
25055
25056       if (per_cu == target_per_cu)
25057         {
25058           free_heap_comp_unit (per_cu->cu);
25059           per_cu->cu = NULL;
25060           *last_chain = next_cu;
25061           break;
25062         }
25063       else
25064         last_chain = &per_cu->cu->read_in_chain;
25065
25066       per_cu = next_cu;
25067     }
25068 }
25069
25070 /* Release all extra memory associated with OBJFILE.  */
25071
25072 void
25073 dwarf2_free_objfile (struct objfile *objfile)
25074 {
25075   dwarf2_per_objfile
25076     = (struct dwarf2_per_objfile *) objfile_data (objfile,
25077                                                   dwarf2_objfile_data_key);
25078
25079   if (dwarf2_per_objfile == NULL)
25080     return;
25081
25082   dwarf2_per_objfile->~dwarf2_per_objfile ();
25083 }
25084
25085 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25086    We store these in a hash table separate from the DIEs, and preserve them
25087    when the DIEs are flushed out of cache.
25088
25089    The CU "per_cu" pointer is needed because offset alone is not enough to
25090    uniquely identify the type.  A file may have multiple .debug_types sections,
25091    or the type may come from a DWO file.  Furthermore, while it's more logical
25092    to use per_cu->section+offset, with Fission the section with the data is in
25093    the DWO file but we don't know that section at the point we need it.
25094    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25095    because we can enter the lookup routine, get_die_type_at_offset, from
25096    outside this file, and thus won't necessarily have PER_CU->cu.
25097    Fortunately, PER_CU is stable for the life of the objfile.  */
25098
25099 struct dwarf2_per_cu_offset_and_type
25100 {
25101   const struct dwarf2_per_cu_data *per_cu;
25102   sect_offset sect_off;
25103   struct type *type;
25104 };
25105
25106 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25107
25108 static hashval_t
25109 per_cu_offset_and_type_hash (const void *item)
25110 {
25111   const struct dwarf2_per_cu_offset_and_type *ofs
25112     = (const struct dwarf2_per_cu_offset_and_type *) item;
25113
25114   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25115 }
25116
25117 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25118
25119 static int
25120 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25121 {
25122   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25123     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25124   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25125     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25126
25127   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25128           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25129 }
25130
25131 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25132    table if necessary.  For convenience, return TYPE.
25133
25134    The DIEs reading must have careful ordering to:
25135     * Not cause infite loops trying to read in DIEs as a prerequisite for
25136       reading current DIE.
25137     * Not trying to dereference contents of still incompletely read in types
25138       while reading in other DIEs.
25139     * Enable referencing still incompletely read in types just by a pointer to
25140       the type without accessing its fields.
25141
25142    Therefore caller should follow these rules:
25143      * Try to fetch any prerequisite types we may need to build this DIE type
25144        before building the type and calling set_die_type.
25145      * After building type call set_die_type for current DIE as soon as
25146        possible before fetching more types to complete the current type.
25147      * Make the type as complete as possible before fetching more types.  */
25148
25149 static struct type *
25150 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25151 {
25152   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25153   struct objfile *objfile = cu->objfile;
25154   struct attribute *attr;
25155   struct dynamic_prop prop;
25156
25157   /* For Ada types, make sure that the gnat-specific data is always
25158      initialized (if not already set).  There are a few types where
25159      we should not be doing so, because the type-specific area is
25160      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25161      where the type-specific area is used to store the floatformat).
25162      But this is not a problem, because the gnat-specific information
25163      is actually not needed for these types.  */
25164   if (need_gnat_info (cu)
25165       && TYPE_CODE (type) != TYPE_CODE_FUNC
25166       && TYPE_CODE (type) != TYPE_CODE_FLT
25167       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25168       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25169       && TYPE_CODE (type) != TYPE_CODE_METHOD
25170       && !HAVE_GNAT_AUX_INFO (type))
25171     INIT_GNAT_SPECIFIC (type);
25172
25173   /* Read DW_AT_allocated and set in type.  */
25174   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25175   if (attr_form_is_block (attr))
25176     {
25177       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25178         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
25179     }
25180   else if (attr != NULL)
25181     {
25182       complaint (&symfile_complaints,
25183                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25184                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25185                  to_underlying (die->sect_off));
25186     }
25187
25188   /* Read DW_AT_associated and set in type.  */
25189   attr = dwarf2_attr (die, DW_AT_associated, cu);
25190   if (attr_form_is_block (attr))
25191     {
25192       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25193         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
25194     }
25195   else if (attr != NULL)
25196     {
25197       complaint (&symfile_complaints,
25198                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25199                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25200                  to_underlying (die->sect_off));
25201     }
25202
25203   /* Read DW_AT_data_location and set in type.  */
25204   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25205   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25206     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
25207
25208   if (dwarf2_per_objfile->die_type_hash == NULL)
25209     {
25210       dwarf2_per_objfile->die_type_hash =
25211         htab_create_alloc_ex (127,
25212                               per_cu_offset_and_type_hash,
25213                               per_cu_offset_and_type_eq,
25214                               NULL,
25215                               &objfile->objfile_obstack,
25216                               hashtab_obstack_allocate,
25217                               dummy_obstack_deallocate);
25218     }
25219
25220   ofs.per_cu = cu->per_cu;
25221   ofs.sect_off = die->sect_off;
25222   ofs.type = type;
25223   slot = (struct dwarf2_per_cu_offset_and_type **)
25224     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25225   if (*slot)
25226     complaint (&symfile_complaints,
25227                _("A problem internal to GDB: DIE 0x%x has type already set"),
25228                to_underlying (die->sect_off));
25229   *slot = XOBNEW (&objfile->objfile_obstack,
25230                   struct dwarf2_per_cu_offset_and_type);
25231   **slot = ofs;
25232   return type;
25233 }
25234
25235 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25236    or return NULL if the die does not have a saved type.  */
25237
25238 static struct type *
25239 get_die_type_at_offset (sect_offset sect_off,
25240                         struct dwarf2_per_cu_data *per_cu)
25241 {
25242   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25243
25244   if (dwarf2_per_objfile->die_type_hash == NULL)
25245     return NULL;
25246
25247   ofs.per_cu = per_cu;
25248   ofs.sect_off = sect_off;
25249   slot = ((struct dwarf2_per_cu_offset_and_type *)
25250           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25251   if (slot)
25252     return slot->type;
25253   else
25254     return NULL;
25255 }
25256
25257 /* Look up the type for DIE in CU in die_type_hash,
25258    or return NULL if DIE does not have a saved type.  */
25259
25260 static struct type *
25261 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25262 {
25263   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25264 }
25265
25266 /* Add a dependence relationship from CU to REF_PER_CU.  */
25267
25268 static void
25269 dwarf2_add_dependence (struct dwarf2_cu *cu,
25270                        struct dwarf2_per_cu_data *ref_per_cu)
25271 {
25272   void **slot;
25273
25274   if (cu->dependencies == NULL)
25275     cu->dependencies
25276       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25277                               NULL, &cu->comp_unit_obstack,
25278                               hashtab_obstack_allocate,
25279                               dummy_obstack_deallocate);
25280
25281   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25282   if (*slot == NULL)
25283     *slot = ref_per_cu;
25284 }
25285
25286 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25287    Set the mark field in every compilation unit in the
25288    cache that we must keep because we are keeping CU.  */
25289
25290 static int
25291 dwarf2_mark_helper (void **slot, void *data)
25292 {
25293   struct dwarf2_per_cu_data *per_cu;
25294
25295   per_cu = (struct dwarf2_per_cu_data *) *slot;
25296
25297   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25298      reading of the chain.  As such dependencies remain valid it is not much
25299      useful to track and undo them during QUIT cleanups.  */
25300   if (per_cu->cu == NULL)
25301     return 1;
25302
25303   if (per_cu->cu->mark)
25304     return 1;
25305   per_cu->cu->mark = 1;
25306
25307   if (per_cu->cu->dependencies != NULL)
25308     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25309
25310   return 1;
25311 }
25312
25313 /* Set the mark field in CU and in every other compilation unit in the
25314    cache that we must keep because we are keeping CU.  */
25315
25316 static void
25317 dwarf2_mark (struct dwarf2_cu *cu)
25318 {
25319   if (cu->mark)
25320     return;
25321   cu->mark = 1;
25322   if (cu->dependencies != NULL)
25323     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25324 }
25325
25326 static void
25327 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25328 {
25329   while (per_cu)
25330     {
25331       per_cu->cu->mark = 0;
25332       per_cu = per_cu->cu->read_in_chain;
25333     }
25334 }
25335
25336 /* Trivial hash function for partial_die_info: the hash value of a DIE
25337    is its offset in .debug_info for this objfile.  */
25338
25339 static hashval_t
25340 partial_die_hash (const void *item)
25341 {
25342   const struct partial_die_info *part_die
25343     = (const struct partial_die_info *) item;
25344
25345   return to_underlying (part_die->sect_off);
25346 }
25347
25348 /* Trivial comparison function for partial_die_info structures: two DIEs
25349    are equal if they have the same offset.  */
25350
25351 static int
25352 partial_die_eq (const void *item_lhs, const void *item_rhs)
25353 {
25354   const struct partial_die_info *part_die_lhs
25355     = (const struct partial_die_info *) item_lhs;
25356   const struct partial_die_info *part_die_rhs
25357     = (const struct partial_die_info *) item_rhs;
25358
25359   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25360 }
25361
25362 static struct cmd_list_element *set_dwarf_cmdlist;
25363 static struct cmd_list_element *show_dwarf_cmdlist;
25364
25365 static void
25366 set_dwarf_cmd (const char *args, int from_tty)
25367 {
25368   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25369              gdb_stdout);
25370 }
25371
25372 static void
25373 show_dwarf_cmd (const char *args, int from_tty)
25374 {
25375   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25376 }
25377
25378 /* Free data associated with OBJFILE, if necessary.  */
25379
25380 static void
25381 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
25382 {
25383   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
25384   int ix;
25385
25386   /* Make sure we don't accidentally use dwarf2_per_objfile while
25387      cleaning up.  */
25388   dwarf2_per_objfile = NULL;
25389
25390   for (ix = 0; ix < data->n_comp_units; ++ix)
25391    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
25392
25393   for (ix = 0; ix < data->n_type_units; ++ix)
25394     VEC_free (dwarf2_per_cu_ptr,
25395               data->all_type_units[ix]->per_cu.imported_symtabs);
25396   xfree (data->all_type_units);
25397
25398   VEC_free (dwarf2_section_info_def, data->types);
25399
25400   if (data->dwo_files)
25401     free_dwo_files (data->dwo_files, objfile);
25402   if (data->dwp_file)
25403     gdb_bfd_unref (data->dwp_file->dbfd);
25404
25405   if (data->dwz_file && data->dwz_file->dwz_bfd)
25406     gdb_bfd_unref (data->dwz_file->dwz_bfd);
25407
25408   if (data->index_table != NULL)
25409     data->index_table->~mapped_index ();
25410 }
25411
25412 \f
25413 /* The "save gdb-index" command.  */
25414
25415 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25416    error checking.  */
25417
25418 static void
25419 file_write (FILE *file, const void *data, size_t size)
25420 {
25421   if (fwrite (data, 1, size, file) != size)
25422     error (_("couldn't data write to file"));
25423 }
25424
25425 /* Write the contents of VEC to FILE, with error checking.  */
25426
25427 template<typename Elem, typename Alloc>
25428 static void
25429 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25430 {
25431   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25432 }
25433
25434 /* In-memory buffer to prepare data to be written later to a file.  */
25435 class data_buf
25436 {
25437 public:
25438   /* Copy DATA to the end of the buffer.  */
25439   template<typename T>
25440   void append_data (const T &data)
25441   {
25442     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25443                reinterpret_cast<const gdb_byte *> (&data + 1),
25444                grow (sizeof (data)));
25445   }
25446
25447   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25448      terminating zero is appended too.  */
25449   void append_cstr0 (const char *cstr)
25450   {
25451     const size_t size = strlen (cstr) + 1;
25452     std::copy (cstr, cstr + size, grow (size));
25453   }
25454
25455   /* Store INPUT as ULEB128 to the end of buffer.  */
25456   void append_unsigned_leb128 (ULONGEST input)
25457   {
25458     for (;;)
25459       {
25460         gdb_byte output = input & 0x7f;
25461         input >>= 7;
25462         if (input)
25463           output |= 0x80;
25464         append_data (output);
25465         if (input == 0)
25466           break;
25467       }
25468   }
25469
25470   /* Accept a host-format integer in VAL and append it to the buffer
25471      as a target-format integer which is LEN bytes long.  */
25472   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25473   {
25474     ::store_unsigned_integer (grow (len), len, byte_order, val);
25475   }
25476
25477   /* Return the size of the buffer.  */
25478   size_t size () const
25479   {
25480     return m_vec.size ();
25481   }
25482
25483   /* Return true iff the buffer is empty.  */
25484   bool empty () const
25485   {
25486     return m_vec.empty ();
25487   }
25488
25489   /* Write the buffer to FILE.  */
25490   void file_write (FILE *file) const
25491   {
25492     ::file_write (file, m_vec);
25493   }
25494
25495 private:
25496   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25497      the start of the new block.  */
25498   gdb_byte *grow (size_t size)
25499   {
25500     m_vec.resize (m_vec.size () + size);
25501     return &*m_vec.end () - size;
25502   }
25503
25504   gdb::byte_vector m_vec;
25505 };
25506
25507 /* An entry in the symbol table.  */
25508 struct symtab_index_entry
25509 {
25510   /* The name of the symbol.  */
25511   const char *name;
25512   /* The offset of the name in the constant pool.  */
25513   offset_type index_offset;
25514   /* A sorted vector of the indices of all the CUs that hold an object
25515      of this name.  */
25516   std::vector<offset_type> cu_indices;
25517 };
25518
25519 /* The symbol table.  This is a power-of-2-sized hash table.  */
25520 struct mapped_symtab
25521 {
25522   mapped_symtab ()
25523   {
25524     data.resize (1024);
25525   }
25526
25527   offset_type n_elements = 0;
25528   std::vector<symtab_index_entry> data;
25529 };
25530
25531 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25532    the slot.
25533    
25534    Function is used only during write_hash_table so no index format backward
25535    compatibility is needed.  */
25536
25537 static symtab_index_entry &
25538 find_slot (struct mapped_symtab *symtab, const char *name)
25539 {
25540   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25541
25542   index = hash & (symtab->data.size () - 1);
25543   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25544
25545   for (;;)
25546     {
25547       if (symtab->data[index].name == NULL
25548           || strcmp (name, symtab->data[index].name) == 0)
25549         return symtab->data[index];
25550       index = (index + step) & (symtab->data.size () - 1);
25551     }
25552 }
25553
25554 /* Expand SYMTAB's hash table.  */
25555
25556 static void
25557 hash_expand (struct mapped_symtab *symtab)
25558 {
25559   auto old_entries = std::move (symtab->data);
25560
25561   symtab->data.clear ();
25562   symtab->data.resize (old_entries.size () * 2);
25563
25564   for (auto &it : old_entries)
25565     if (it.name != NULL)
25566       {
25567         auto &ref = find_slot (symtab, it.name);
25568         ref = std::move (it);
25569       }
25570 }
25571
25572 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25573    CU_INDEX is the index of the CU in which the symbol appears.
25574    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25575
25576 static void
25577 add_index_entry (struct mapped_symtab *symtab, const char *name,
25578                  int is_static, gdb_index_symbol_kind kind,
25579                  offset_type cu_index)
25580 {
25581   offset_type cu_index_and_attrs;
25582
25583   ++symtab->n_elements;
25584   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25585     hash_expand (symtab);
25586
25587   symtab_index_entry &slot = find_slot (symtab, name);
25588   if (slot.name == NULL)
25589     {
25590       slot.name = name;
25591       /* index_offset is set later.  */
25592     }
25593
25594   cu_index_and_attrs = 0;
25595   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25596   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25597   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25598
25599   /* We don't want to record an index value twice as we want to avoid the
25600      duplication.
25601      We process all global symbols and then all static symbols
25602      (which would allow us to avoid the duplication by only having to check
25603      the last entry pushed), but a symbol could have multiple kinds in one CU.
25604      To keep things simple we don't worry about the duplication here and
25605      sort and uniqufy the list after we've processed all symbols.  */
25606   slot.cu_indices.push_back (cu_index_and_attrs);
25607 }
25608
25609 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25610
25611 static void
25612 uniquify_cu_indices (struct mapped_symtab *symtab)
25613 {
25614   for (auto &entry : symtab->data)
25615     {
25616       if (entry.name != NULL && !entry.cu_indices.empty ())
25617         {
25618           auto &cu_indices = entry.cu_indices;
25619           std::sort (cu_indices.begin (), cu_indices.end ());
25620           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25621           cu_indices.erase (from, cu_indices.end ());
25622         }
25623     }
25624 }
25625
25626 /* A form of 'const char *' suitable for container keys.  Only the
25627    pointer is stored.  The strings themselves are compared, not the
25628    pointers.  */
25629 class c_str_view
25630 {
25631 public:
25632   c_str_view (const char *cstr)
25633     : m_cstr (cstr)
25634   {}
25635
25636   bool operator== (const c_str_view &other) const
25637   {
25638     return strcmp (m_cstr, other.m_cstr) == 0;
25639   }
25640
25641   /* Return the underlying C string.  Note, the returned string is
25642      only a reference with lifetime of this object.  */
25643   const char *c_str () const
25644   {
25645     return m_cstr;
25646   }
25647
25648 private:
25649   friend class c_str_view_hasher;
25650   const char *const m_cstr;
25651 };
25652
25653 /* A std::unordered_map::hasher for c_str_view that uses the right
25654    hash function for strings in a mapped index.  */
25655 class c_str_view_hasher
25656 {
25657 public:
25658   size_t operator () (const c_str_view &x) const
25659   {
25660     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25661   }
25662 };
25663
25664 /* A std::unordered_map::hasher for std::vector<>.  */
25665 template<typename T>
25666 class vector_hasher
25667 {
25668 public:
25669   size_t operator () (const std::vector<T> &key) const
25670   {
25671     return iterative_hash (key.data (),
25672                            sizeof (key.front ()) * key.size (), 0);
25673   }
25674 };
25675
25676 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25677    constant pool entries going into the data buffer CPOOL.  */
25678
25679 static void
25680 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25681 {
25682   {
25683     /* Elements are sorted vectors of the indices of all the CUs that
25684        hold an object of this name.  */
25685     std::unordered_map<std::vector<offset_type>, offset_type,
25686                        vector_hasher<offset_type>>
25687       symbol_hash_table;
25688
25689     /* We add all the index vectors to the constant pool first, to
25690        ensure alignment is ok.  */
25691     for (symtab_index_entry &entry : symtab->data)
25692       {
25693         if (entry.name == NULL)
25694           continue;
25695         gdb_assert (entry.index_offset == 0);
25696
25697         /* Finding before inserting is faster than always trying to
25698            insert, because inserting always allocates a node, does the
25699            lookup, and then destroys the new node if another node
25700            already had the same key.  C++17 try_emplace will avoid
25701            this.  */
25702         const auto found
25703           = symbol_hash_table.find (entry.cu_indices);
25704         if (found != symbol_hash_table.end ())
25705           {
25706             entry.index_offset = found->second;
25707             continue;
25708           }
25709
25710         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25711         entry.index_offset = cpool.size ();
25712         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25713         for (const auto index : entry.cu_indices)
25714           cpool.append_data (MAYBE_SWAP (index));
25715       }
25716   }
25717
25718   /* Now write out the hash table.  */
25719   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25720   for (const auto &entry : symtab->data)
25721     {
25722       offset_type str_off, vec_off;
25723
25724       if (entry.name != NULL)
25725         {
25726           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25727           if (insertpair.second)
25728             cpool.append_cstr0 (entry.name);
25729           str_off = insertpair.first->second;
25730           vec_off = entry.index_offset;
25731         }
25732       else
25733         {
25734           /* While 0 is a valid constant pool index, it is not valid
25735              to have 0 for both offsets.  */
25736           str_off = 0;
25737           vec_off = 0;
25738         }
25739
25740       output.append_data (MAYBE_SWAP (str_off));
25741       output.append_data (MAYBE_SWAP (vec_off));
25742     }
25743 }
25744
25745 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25746
25747 /* Helper struct for building the address table.  */
25748 struct addrmap_index_data
25749 {
25750   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25751     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25752   {}
25753
25754   struct objfile *objfile;
25755   data_buf &addr_vec;
25756   psym_index_map &cu_index_htab;
25757
25758   /* Non-zero if the previous_* fields are valid.
25759      We can't write an entry until we see the next entry (since it is only then
25760      that we know the end of the entry).  */
25761   int previous_valid;
25762   /* Index of the CU in the table of all CUs in the index file.  */
25763   unsigned int previous_cu_index;
25764   /* Start address of the CU.  */
25765   CORE_ADDR previous_cu_start;
25766 };
25767
25768 /* Write an address entry to ADDR_VEC.  */
25769
25770 static void
25771 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25772                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25773 {
25774   CORE_ADDR baseaddr;
25775
25776   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25777
25778   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25779   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25780   addr_vec.append_data (MAYBE_SWAP (cu_index));
25781 }
25782
25783 /* Worker function for traversing an addrmap to build the address table.  */
25784
25785 static int
25786 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25787 {
25788   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25789   struct partial_symtab *pst = (struct partial_symtab *) obj;
25790
25791   if (data->previous_valid)
25792     add_address_entry (data->objfile, data->addr_vec,
25793                        data->previous_cu_start, start_addr,
25794                        data->previous_cu_index);
25795
25796   data->previous_cu_start = start_addr;
25797   if (pst != NULL)
25798     {
25799       const auto it = data->cu_index_htab.find (pst);
25800       gdb_assert (it != data->cu_index_htab.cend ());
25801       data->previous_cu_index = it->second;
25802       data->previous_valid = 1;
25803     }
25804   else
25805     data->previous_valid = 0;
25806
25807   return 0;
25808 }
25809
25810 /* Write OBJFILE's address map to ADDR_VEC.
25811    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25812    in the index file.  */
25813
25814 static void
25815 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25816                    psym_index_map &cu_index_htab)
25817 {
25818   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25819
25820   /* When writing the address table, we have to cope with the fact that
25821      the addrmap iterator only provides the start of a region; we have to
25822      wait until the next invocation to get the start of the next region.  */
25823
25824   addrmap_index_data.objfile = objfile;
25825   addrmap_index_data.previous_valid = 0;
25826
25827   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25828                    &addrmap_index_data);
25829
25830   /* It's highly unlikely the last entry (end address = 0xff...ff)
25831      is valid, but we should still handle it.
25832      The end address is recorded as the start of the next region, but that
25833      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25834      anyway.  */
25835   if (addrmap_index_data.previous_valid)
25836     add_address_entry (objfile, addr_vec,
25837                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25838                        addrmap_index_data.previous_cu_index);
25839 }
25840
25841 /* Return the symbol kind of PSYM.  */
25842
25843 static gdb_index_symbol_kind
25844 symbol_kind (struct partial_symbol *psym)
25845 {
25846   domain_enum domain = PSYMBOL_DOMAIN (psym);
25847   enum address_class aclass = PSYMBOL_CLASS (psym);
25848
25849   switch (domain)
25850     {
25851     case VAR_DOMAIN:
25852       switch (aclass)
25853         {
25854         case LOC_BLOCK:
25855           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25856         case LOC_TYPEDEF:
25857           return GDB_INDEX_SYMBOL_KIND_TYPE;
25858         case LOC_COMPUTED:
25859         case LOC_CONST_BYTES:
25860         case LOC_OPTIMIZED_OUT:
25861         case LOC_STATIC:
25862           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25863         case LOC_CONST:
25864           /* Note: It's currently impossible to recognize psyms as enum values
25865              short of reading the type info.  For now punt.  */
25866           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25867         default:
25868           /* There are other LOC_FOO values that one might want to classify
25869              as variables, but dwarf2read.c doesn't currently use them.  */
25870           return GDB_INDEX_SYMBOL_KIND_OTHER;
25871         }
25872     case STRUCT_DOMAIN:
25873       return GDB_INDEX_SYMBOL_KIND_TYPE;
25874     default:
25875       return GDB_INDEX_SYMBOL_KIND_OTHER;
25876     }
25877 }
25878
25879 /* Add a list of partial symbols to SYMTAB.  */
25880
25881 static void
25882 write_psymbols (struct mapped_symtab *symtab,
25883                 std::unordered_set<partial_symbol *> &psyms_seen,
25884                 struct partial_symbol **psymp,
25885                 int count,
25886                 offset_type cu_index,
25887                 int is_static)
25888 {
25889   for (; count-- > 0; ++psymp)
25890     {
25891       struct partial_symbol *psym = *psymp;
25892
25893       if (SYMBOL_LANGUAGE (psym) == language_ada)
25894         error (_("Ada is not currently supported by the index"));
25895
25896       /* Only add a given psymbol once.  */
25897       if (psyms_seen.insert (psym).second)
25898         {
25899           gdb_index_symbol_kind kind = symbol_kind (psym);
25900
25901           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
25902                            is_static, kind, cu_index);
25903         }
25904     }
25905 }
25906
25907 /* A helper struct used when iterating over debug_types.  */
25908 struct signatured_type_index_data
25909 {
25910   signatured_type_index_data (data_buf &types_list_,
25911                               std::unordered_set<partial_symbol *> &psyms_seen_)
25912     : types_list (types_list_), psyms_seen (psyms_seen_)
25913   {}
25914
25915   struct objfile *objfile;
25916   struct mapped_symtab *symtab;
25917   data_buf &types_list;
25918   std::unordered_set<partial_symbol *> &psyms_seen;
25919   int cu_index;
25920 };
25921
25922 /* A helper function that writes a single signatured_type to an
25923    obstack.  */
25924
25925 static int
25926 write_one_signatured_type (void **slot, void *d)
25927 {
25928   struct signatured_type_index_data *info
25929     = (struct signatured_type_index_data *) d;
25930   struct signatured_type *entry = (struct signatured_type *) *slot;
25931   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
25932
25933   write_psymbols (info->symtab,
25934                   info->psyms_seen,
25935                   &info->objfile->global_psymbols[psymtab->globals_offset],
25936                   psymtab->n_global_syms, info->cu_index,
25937                   0);
25938   write_psymbols (info->symtab,
25939                   info->psyms_seen,
25940                   &info->objfile->static_psymbols[psymtab->statics_offset],
25941                   psymtab->n_static_syms, info->cu_index,
25942                   1);
25943
25944   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
25945                                 to_underlying (entry->per_cu.sect_off));
25946   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
25947                                 to_underlying (entry->type_offset_in_tu));
25948   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
25949
25950   ++info->cu_index;
25951
25952   return 1;
25953 }
25954
25955 /* Recurse into all "included" dependencies and count their symbols as
25956    if they appeared in this psymtab.  */
25957
25958 static void
25959 recursively_count_psymbols (struct partial_symtab *psymtab,
25960                             size_t &psyms_seen)
25961 {
25962   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
25963     if (psymtab->dependencies[i]->user != NULL)
25964       recursively_count_psymbols (psymtab->dependencies[i],
25965                                   psyms_seen);
25966
25967   psyms_seen += psymtab->n_global_syms;
25968   psyms_seen += psymtab->n_static_syms;
25969 }
25970
25971 /* Recurse into all "included" dependencies and write their symbols as
25972    if they appeared in this psymtab.  */
25973
25974 static void
25975 recursively_write_psymbols (struct objfile *objfile,
25976                             struct partial_symtab *psymtab,
25977                             struct mapped_symtab *symtab,
25978                             std::unordered_set<partial_symbol *> &psyms_seen,
25979                             offset_type cu_index)
25980 {
25981   int i;
25982
25983   for (i = 0; i < psymtab->number_of_dependencies; ++i)
25984     if (psymtab->dependencies[i]->user != NULL)
25985       recursively_write_psymbols (objfile, psymtab->dependencies[i],
25986                                   symtab, psyms_seen, cu_index);
25987
25988   write_psymbols (symtab,
25989                   psyms_seen,
25990                   &objfile->global_psymbols[psymtab->globals_offset],
25991                   psymtab->n_global_syms, cu_index,
25992                   0);
25993   write_psymbols (symtab,
25994                   psyms_seen,
25995                   &objfile->static_psymbols[psymtab->statics_offset],
25996                   psymtab->n_static_syms, cu_index,
25997                   1);
25998 }
25999
26000 /* DWARF-5 .debug_names builder.  */
26001 class debug_names
26002 {
26003 public:
26004   debug_names (bool is_dwarf64, bfd_endian dwarf5_byte_order)
26005     : m_dwarf5_byte_order (dwarf5_byte_order),
26006       m_dwarf32 (dwarf5_byte_order),
26007       m_dwarf64 (dwarf5_byte_order),
26008       m_dwarf (is_dwarf64
26009                ? static_cast<dwarf &> (m_dwarf64)
26010                : static_cast<dwarf &> (m_dwarf32)),
26011       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26012       m_name_table_entry_offs (m_dwarf.name_table_entry_offs)
26013   {}
26014
26015   /* Insert one symbol.  */
26016   void insert (const partial_symbol *psym, int cu_index, bool is_static)
26017   {
26018     const int dwarf_tag = psymbol_tag (psym);
26019     if (dwarf_tag == 0)
26020       return;
26021     const char *const name = SYMBOL_SEARCH_NAME (psym);
26022     const auto insertpair
26023       = m_name_to_value_set.emplace (c_str_view (name),
26024                                      std::set<symbol_value> ());
26025     std::set<symbol_value> &value_set = insertpair.first->second;
26026     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static));
26027   }
26028
26029   /* Build all the tables.  All symbols must be already inserted.
26030      This function does not call file_write, caller has to do it
26031      afterwards.  */
26032   void build ()
26033   {
26034     /* Verify the build method has not be called twice.  */
26035     gdb_assert (m_abbrev_table.empty ());
26036     const size_t name_count = m_name_to_value_set.size ();
26037     m_bucket_table.resize
26038       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26039     m_hash_table.reserve (name_count);
26040     m_name_table_string_offs.reserve (name_count);
26041     m_name_table_entry_offs.reserve (name_count);
26042
26043     /* Map each hash of symbol to its name and value.  */
26044     struct hash_it_pair
26045     {
26046       uint32_t hash;
26047       decltype (m_name_to_value_set)::const_iterator it;
26048     };
26049     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26050     bucket_hash.resize (m_bucket_table.size ());
26051     for (decltype (m_name_to_value_set)::const_iterator it
26052            = m_name_to_value_set.cbegin ();
26053          it != m_name_to_value_set.cend ();
26054          ++it)
26055       {
26056         const char *const name = it->first.c_str ();
26057         const uint32_t hash = dwarf5_djb_hash (name);
26058         hash_it_pair hashitpair;
26059         hashitpair.hash = hash;
26060         hashitpair.it = it;
26061         auto &slot = bucket_hash[hash % bucket_hash.size()];
26062         slot.push_front (std::move (hashitpair));
26063       }
26064     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26065       {
26066         const std::forward_list<hash_it_pair> &hashitlist
26067           = bucket_hash[bucket_ix];
26068         if (hashitlist.empty ())
26069           continue;
26070         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26071         /* The hashes array is indexed starting at 1.  */
26072         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26073                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26074                                 m_hash_table.size () + 1);
26075         for (const hash_it_pair &hashitpair : hashitlist)
26076           {
26077             m_hash_table.push_back (0);
26078             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26079                                                         (&m_hash_table.back ()),
26080                                     sizeof (m_hash_table.back ()),
26081                                     m_dwarf5_byte_order, hashitpair.hash);
26082             const c_str_view &name = hashitpair.it->first;
26083             const std::set<symbol_value> &value_set = hashitpair.it->second;
26084             m_name_table_string_offs.push_back_reorder
26085               (m_debugstrlookup.lookup (name.c_str ()));
26086             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26087             gdb_assert (!value_set.empty ());
26088             for (const symbol_value &value : value_set)
26089               {
26090                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26091                                                         value.is_static)];
26092                 if (idx == 0)
26093                   {
26094                     idx = m_idx_next++;
26095                     m_abbrev_table.append_unsigned_leb128 (idx);
26096                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26097                     m_abbrev_table.append_unsigned_leb128 (DW_IDX_compile_unit);
26098                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26099                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26100                                                            ? DW_IDX_GNU_internal
26101                                                            : DW_IDX_GNU_external);
26102                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26103
26104                     /* Terminate attributes list.  */
26105                     m_abbrev_table.append_unsigned_leb128 (0);
26106                     m_abbrev_table.append_unsigned_leb128 (0);
26107                   }
26108
26109                 m_entry_pool.append_unsigned_leb128 (idx);
26110                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26111               }
26112
26113             /* Terminate the list of CUs.  */
26114             m_entry_pool.append_unsigned_leb128 (0);
26115           }
26116       }
26117     gdb_assert (m_hash_table.size () == name_count);
26118
26119     /* Terminate tags list.  */
26120     m_abbrev_table.append_unsigned_leb128 (0);
26121   }
26122
26123   /* Return .debug_names bucket count.  This must be called only after
26124      calling the build method.  */
26125   uint32_t bucket_count () const
26126   {
26127     /* Verify the build method has been already called.  */
26128     gdb_assert (!m_abbrev_table.empty ());
26129     const uint32_t retval = m_bucket_table.size ();
26130
26131     /* Check for overflow.  */
26132     gdb_assert (retval == m_bucket_table.size ());
26133     return retval;
26134   }
26135
26136   /* Return .debug_names names count.  This must be called only after
26137      calling the build method.  */
26138   uint32_t name_count () const
26139   {
26140     /* Verify the build method has been already called.  */
26141     gdb_assert (!m_abbrev_table.empty ());
26142     const uint32_t retval = m_hash_table.size ();
26143
26144     /* Check for overflow.  */
26145     gdb_assert (retval == m_hash_table.size ());
26146     return retval;
26147   }
26148
26149   /* Return number of bytes of .debug_names abbreviation table.  This
26150      must be called only after calling the build method.  */
26151   uint32_t abbrev_table_bytes () const
26152   {
26153     gdb_assert (!m_abbrev_table.empty ());
26154     return m_abbrev_table.size ();
26155   }
26156
26157   /* Recurse into all "included" dependencies and store their symbols
26158      as if they appeared in this psymtab.  */
26159   void recursively_write_psymbols
26160     (struct objfile *objfile,
26161      struct partial_symtab *psymtab,
26162      std::unordered_set<partial_symbol *> &psyms_seen,
26163      int cu_index)
26164   {
26165     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26166       if (psymtab->dependencies[i]->user != NULL)
26167         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26168                                     psyms_seen, cu_index);
26169
26170     write_psymbols (psyms_seen,
26171                     &objfile->global_psymbols[psymtab->globals_offset],
26172                     psymtab->n_global_syms, cu_index, false);
26173     write_psymbols (psyms_seen,
26174                     &objfile->static_psymbols[psymtab->statics_offset],
26175                     psymtab->n_static_syms, cu_index, true);
26176   }
26177
26178   /* Return number of bytes the .debug_names section will have.  This
26179      must be called only after calling the build method.  */
26180   size_t bytes () const
26181   {
26182     /* Verify the build method has been already called.  */
26183     gdb_assert (!m_abbrev_table.empty ());
26184     size_t expected_bytes = 0;
26185     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26186     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26187     expected_bytes += m_name_table_string_offs.bytes ();
26188     expected_bytes += m_name_table_entry_offs.bytes ();
26189     expected_bytes += m_abbrev_table.size ();
26190     expected_bytes += m_entry_pool.size ();
26191     return expected_bytes;
26192   }
26193
26194   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26195      FILE_STR.  This must be called only after calling the build
26196      method.  */
26197   void file_write (FILE *file_names, FILE *file_str) const
26198   {
26199     /* Verify the build method has been already called.  */
26200     gdb_assert (!m_abbrev_table.empty ());
26201     ::file_write (file_names, m_bucket_table);
26202     ::file_write (file_names, m_hash_table);
26203     m_name_table_string_offs.file_write (file_names);
26204     m_name_table_entry_offs.file_write (file_names);
26205     m_abbrev_table.file_write (file_names);
26206     m_entry_pool.file_write (file_names);
26207     m_debugstrlookup.file_write (file_str);
26208   }
26209
26210 private:
26211
26212   /* Storage for symbol names mapping them to their .debug_str section
26213      offsets.  */
26214   class debug_str_lookup
26215   {
26216   public:
26217
26218     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26219        All .debug_str section strings are automatically stored.  */
26220     debug_str_lookup ()
26221       : m_abfd (dwarf2_per_objfile->objfile->obfd)
26222     {
26223       dwarf2_read_section (dwarf2_per_objfile->objfile,
26224                            &dwarf2_per_objfile->str);
26225       if (dwarf2_per_objfile->str.buffer == NULL)
26226         return;
26227       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26228            data < (dwarf2_per_objfile->str.buffer
26229                    + dwarf2_per_objfile->str.size);)
26230         {
26231           const char *const s = reinterpret_cast<const char *> (data);
26232           const auto insertpair
26233             = m_str_table.emplace (c_str_view (s),
26234                                    data - dwarf2_per_objfile->str.buffer);
26235           if (!insertpair.second)
26236             complaint (&symfile_complaints,
26237                        _("Duplicate string \"%s\" in "
26238                          ".debug_str section [in module %s]"),
26239                        s, bfd_get_filename (m_abfd));
26240           data += strlen (s) + 1;
26241         }
26242     }
26243
26244     /* Return offset of symbol name S in the .debug_str section.  Add
26245        such symbol to the section's end if it does not exist there
26246        yet.  */
26247     size_t lookup (const char *s)
26248     {
26249       const auto it = m_str_table.find (c_str_view (s));
26250       if (it != m_str_table.end ())
26251         return it->second;
26252       const size_t offset = (dwarf2_per_objfile->str.size
26253                              + m_str_add_buf.size ());
26254       m_str_table.emplace (c_str_view (s), offset);
26255       m_str_add_buf.append_cstr0 (s);
26256       return offset;
26257     }
26258
26259     /* Append the end of the .debug_str section to FILE.  */
26260     void file_write (FILE *file) const
26261     {
26262       m_str_add_buf.file_write (file);
26263     }
26264
26265   private:
26266     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26267     bfd *const m_abfd;
26268
26269     /* Data to add at the end of .debug_str for new needed symbol names.  */
26270     data_buf m_str_add_buf;
26271   };
26272
26273   /* Container to map used DWARF tags to their .debug_names abbreviation
26274      tags.  */
26275   class index_key
26276   {
26277   public:
26278     index_key (int dwarf_tag_, bool is_static_)
26279       : dwarf_tag (dwarf_tag_), is_static (is_static_)
26280     {
26281     }
26282
26283     bool
26284     operator== (const index_key &other) const
26285     {
26286       return dwarf_tag == other.dwarf_tag && is_static == other.is_static;
26287     }
26288
26289     const int dwarf_tag;
26290     const bool is_static;
26291   };
26292
26293   /* Provide std::unordered_map::hasher for index_key.  */
26294   class index_key_hasher
26295   {
26296   public:
26297     size_t
26298     operator () (const index_key &key) const
26299     {
26300       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26301     }
26302   };
26303
26304   /* Parameters of one symbol entry.  */
26305   class symbol_value
26306   {
26307   public:
26308     const int dwarf_tag, cu_index;
26309     const bool is_static;
26310
26311     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_)
26312       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_)
26313     {}
26314
26315     bool
26316     operator< (const symbol_value &other) const
26317     {
26318 #define X(n) \
26319   do \
26320     { \
26321       if (n < other.n) \
26322         return true; \
26323       if (n > other.n) \
26324         return false; \
26325     } \
26326   while (0)
26327       X (dwarf_tag);
26328       X (is_static);
26329       X (cu_index);
26330 #undef X
26331       return false;
26332     }
26333   };
26334
26335   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26336      output.  */
26337   class offset_vec
26338   {
26339   protected:
26340     const bfd_endian dwarf5_byte_order;
26341   public:
26342     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26343       : dwarf5_byte_order (dwarf5_byte_order_)
26344     {}
26345
26346     /* Call std::vector::reserve for NELEM elements.  */
26347     virtual void reserve (size_t nelem) = 0;
26348
26349     /* Call std::vector::push_back with store_unsigned_integer byte
26350        reordering for ELEM.  */
26351     virtual void push_back_reorder (size_t elem) = 0;
26352
26353     /* Return expected output size in bytes.  */
26354     virtual size_t bytes () const = 0;
26355
26356     /* Write name table to FILE.  */
26357     virtual void file_write (FILE *file) const = 0;
26358   };
26359
26360   /* Template to unify DWARF-32 and DWARF-64 output.  */
26361   template<typename OffsetSize>
26362   class offset_vec_tmpl : public offset_vec
26363   {
26364   public:
26365     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26366       : offset_vec (dwarf5_byte_order_)
26367     {}
26368
26369     /* Implement offset_vec::reserve.  */
26370     void reserve (size_t nelem) override
26371     {
26372       m_vec.reserve (nelem);
26373     }
26374
26375     /* Implement offset_vec::push_back_reorder.  */
26376     void push_back_reorder (size_t elem) override
26377     {
26378       m_vec.push_back (elem);
26379       /* Check for overflow.  */
26380       gdb_assert (m_vec.back () == elem);
26381       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26382                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26383     }
26384
26385     /* Implement offset_vec::bytes.  */
26386     size_t bytes () const override
26387     {
26388       return m_vec.size () * sizeof (m_vec[0]);
26389     }
26390
26391     /* Implement offset_vec::file_write.  */
26392     void file_write (FILE *file) const override
26393     {
26394       ::file_write (file, m_vec);
26395     }
26396
26397   private:
26398     std::vector<OffsetSize> m_vec;
26399   };
26400
26401   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26402      respecting name table width.  */
26403   class dwarf
26404   {
26405   public:
26406     offset_vec &name_table_string_offs, &name_table_entry_offs;
26407
26408     dwarf (offset_vec &name_table_string_offs_,
26409            offset_vec &name_table_entry_offs_)
26410       : name_table_string_offs (name_table_string_offs_),
26411         name_table_entry_offs (name_table_entry_offs_)
26412     {
26413     }
26414   };
26415
26416   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26417      respecting name table width.  */
26418   template<typename OffsetSize>
26419   class dwarf_tmpl : public dwarf
26420   {
26421   public:
26422     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26423       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26424         m_name_table_string_offs (dwarf5_byte_order_),
26425         m_name_table_entry_offs (dwarf5_byte_order_)
26426     {}
26427
26428   private:
26429     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26430     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26431   };
26432
26433   /* Try to reconstruct original DWARF tag for given partial_symbol.
26434      This function is not DWARF-5 compliant but it is sufficient for
26435      GDB as a DWARF-5 index consumer.  */
26436   static int psymbol_tag (const struct partial_symbol *psym)
26437   {
26438     domain_enum domain = PSYMBOL_DOMAIN (psym);
26439     enum address_class aclass = PSYMBOL_CLASS (psym);
26440
26441     switch (domain)
26442       {
26443       case VAR_DOMAIN:
26444         switch (aclass)
26445           {
26446           case LOC_BLOCK:
26447             return DW_TAG_subprogram;
26448           case LOC_TYPEDEF:
26449             return DW_TAG_typedef;
26450           case LOC_COMPUTED:
26451           case LOC_CONST_BYTES:
26452           case LOC_OPTIMIZED_OUT:
26453           case LOC_STATIC:
26454             return DW_TAG_variable;
26455           case LOC_CONST:
26456             /* Note: It's currently impossible to recognize psyms as enum values
26457                short of reading the type info.  For now punt.  */
26458             return DW_TAG_variable;
26459           default:
26460             /* There are other LOC_FOO values that one might want to classify
26461                as variables, but dwarf2read.c doesn't currently use them.  */
26462             return DW_TAG_variable;
26463           }
26464       case STRUCT_DOMAIN:
26465         return DW_TAG_structure_type;
26466       default:
26467         return 0;
26468       }
26469   }
26470
26471   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26472   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26473                        struct partial_symbol **psymp, int count, int cu_index,
26474                        bool is_static)
26475   {
26476     for (; count-- > 0; ++psymp)
26477       {
26478         struct partial_symbol *psym = *psymp;
26479
26480         if (SYMBOL_LANGUAGE (psym) == language_ada)
26481           error (_("Ada is not currently supported by the index"));
26482
26483         /* Only add a given psymbol once.  */
26484         if (psyms_seen.insert (psym).second)
26485           insert (psym, cu_index, is_static);
26486       }
26487   }
26488
26489   /* Store value of each symbol.  */
26490   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26491     m_name_to_value_set;
26492
26493   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26494      order.  */
26495   std::vector<uint32_t> m_bucket_table;
26496   std::vector<uint32_t> m_hash_table;
26497
26498   const bfd_endian m_dwarf5_byte_order;
26499   dwarf_tmpl<uint32_t> m_dwarf32;
26500   dwarf_tmpl<uint64_t> m_dwarf64;
26501   dwarf &m_dwarf;
26502   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26503   debug_str_lookup m_debugstrlookup;
26504
26505   /* Map each used .debug_names abbreviation tag parameter to its
26506      index value.  */
26507   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26508
26509   /* Next unused .debug_names abbreviation tag for
26510      m_indexkey_to_idx.  */
26511   int m_idx_next = 1;
26512
26513   /* .debug_names abbreviation table.  */
26514   data_buf m_abbrev_table;
26515
26516   /* .debug_names entry pool.  */
26517   data_buf m_entry_pool;
26518 };
26519
26520 /* Return iff any of the needed offsets does not fit into 32-bit
26521    .debug_names section.  */
26522
26523 static bool
26524 check_dwarf64_offsets ()
26525 {
26526   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26527     {
26528       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26529
26530       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26531         return true;
26532     }
26533   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26534     {
26535       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26536       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26537
26538       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26539         return true;
26540     }
26541   return false;
26542 }
26543
26544 /* The psyms_seen set is potentially going to be largish (~40k
26545    elements when indexing a -g3 build of GDB itself).  Estimate the
26546    number of elements in order to avoid too many rehashes, which
26547    require rebuilding buckets and thus many trips to
26548    malloc/free.  */
26549
26550 static size_t
26551 psyms_seen_size ()
26552 {
26553   size_t psyms_count = 0;
26554   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26555     {
26556       struct dwarf2_per_cu_data *per_cu
26557         = dwarf2_per_objfile->all_comp_units[i];
26558       struct partial_symtab *psymtab = per_cu->v.psymtab;
26559
26560       if (psymtab != NULL && psymtab->user == NULL)
26561         recursively_count_psymbols (psymtab, psyms_count);
26562     }
26563   /* Generating an index for gdb itself shows a ratio of
26564      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26565   return psyms_count / 4;
26566 }
26567
26568 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26569    Return how many bytes were expected to be written into OUT_FILE.  */
26570
26571 static size_t
26572 write_gdbindex (struct objfile *objfile, FILE *out_file)
26573 {
26574   mapped_symtab symtab;
26575   data_buf cu_list;
26576
26577   /* While we're scanning CU's create a table that maps a psymtab pointer
26578      (which is what addrmap records) to its index (which is what is recorded
26579      in the index file).  This will later be needed to write the address
26580      table.  */
26581   psym_index_map cu_index_htab;
26582   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26583
26584   /* The CU list is already sorted, so we don't need to do additional
26585      work here.  Also, the debug_types entries do not appear in
26586      all_comp_units, but only in their own hash table.  */
26587
26588   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
26589   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26590     {
26591       struct dwarf2_per_cu_data *per_cu
26592         = dwarf2_per_objfile->all_comp_units[i];
26593       struct partial_symtab *psymtab = per_cu->v.psymtab;
26594
26595       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26596          It may be referenced from a local scope but in such case it does not
26597          need to be present in .gdb_index.  */
26598       if (psymtab == NULL)
26599         continue;
26600
26601       if (psymtab->user == NULL)
26602         recursively_write_psymbols (objfile, psymtab, &symtab,
26603                                     psyms_seen, i);
26604
26605       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26606       gdb_assert (insertpair.second);
26607
26608       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26609                            to_underlying (per_cu->sect_off));
26610       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26611     }
26612
26613   /* Dump the address map.  */
26614   data_buf addr_vec;
26615   write_address_map (objfile, addr_vec, cu_index_htab);
26616
26617   /* Write out the .debug_type entries, if any.  */
26618   data_buf types_cu_list;
26619   if (dwarf2_per_objfile->signatured_types)
26620     {
26621       signatured_type_index_data sig_data (types_cu_list,
26622                                            psyms_seen);
26623
26624       sig_data.objfile = objfile;
26625       sig_data.symtab = &symtab;
26626       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26627       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26628                               write_one_signatured_type, &sig_data);
26629     }
26630
26631   /* Now that we've processed all symbols we can shrink their cu_indices
26632      lists.  */
26633   uniquify_cu_indices (&symtab);
26634
26635   data_buf symtab_vec, constant_pool;
26636   write_hash_table (&symtab, symtab_vec, constant_pool);
26637
26638   data_buf contents;
26639   const offset_type size_of_contents = 6 * sizeof (offset_type);
26640   offset_type total_len = size_of_contents;
26641
26642   /* The version number.  */
26643   contents.append_data (MAYBE_SWAP (8));
26644
26645   /* The offset of the CU list from the start of the file.  */
26646   contents.append_data (MAYBE_SWAP (total_len));
26647   total_len += cu_list.size ();
26648
26649   /* The offset of the types CU list from the start of the file.  */
26650   contents.append_data (MAYBE_SWAP (total_len));
26651   total_len += types_cu_list.size ();
26652
26653   /* The offset of the address table from the start of the file.  */
26654   contents.append_data (MAYBE_SWAP (total_len));
26655   total_len += addr_vec.size ();
26656
26657   /* The offset of the symbol table from the start of the file.  */
26658   contents.append_data (MAYBE_SWAP (total_len));
26659   total_len += symtab_vec.size ();
26660
26661   /* The offset of the constant pool from the start of the file.  */
26662   contents.append_data (MAYBE_SWAP (total_len));
26663   total_len += constant_pool.size ();
26664
26665   gdb_assert (contents.size () == size_of_contents);
26666
26667   contents.file_write (out_file);
26668   cu_list.file_write (out_file);
26669   types_cu_list.file_write (out_file);
26670   addr_vec.file_write (out_file);
26671   symtab_vec.file_write (out_file);
26672   constant_pool.file_write (out_file);
26673
26674   return total_len;
26675 }
26676
26677 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26678 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26679
26680 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26681    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26682    many bytes were expected to be written into OUT_FILE.  */
26683
26684 static size_t
26685 write_debug_names (struct objfile *objfile, FILE *out_file, FILE *out_file_str)
26686 {
26687   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets ();
26688   const int dwarf5_offset_size = dwarf5_is_dwarf64 ? 8 : 4;
26689   const enum bfd_endian dwarf5_byte_order
26690     = gdbarch_byte_order (get_objfile_arch (objfile));
26691
26692   /* The CU list is already sorted, so we don't need to do additional
26693      work here.  Also, the debug_types entries do not appear in
26694      all_comp_units, but only in their own hash table.  */
26695   data_buf cu_list;
26696   debug_names nametable (dwarf5_is_dwarf64, dwarf5_byte_order);
26697   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
26698   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26699     {
26700       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26701       partial_symtab *psymtab = per_cu->v.psymtab;
26702
26703       /* CU of a shared file from 'dwz -m' may be unused by this main
26704          file.  It may be referenced from a local scope but in such
26705          case it does not need to be present in .debug_names.  */
26706       if (psymtab == NULL)
26707         continue;
26708
26709       if (psymtab->user == NULL)
26710         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26711
26712       cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
26713                            to_underlying (per_cu->sect_off));
26714     }
26715   nametable.build ();
26716
26717   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26718
26719   data_buf types_cu_list;
26720   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26721     {
26722       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26723       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26724
26725       types_cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
26726                                  to_underlying (per_cu.sect_off));
26727     }
26728
26729   const offset_type bytes_of_header
26730     = ((dwarf5_is_dwarf64 ? 12 : 4)
26731        + 2 + 2 + 7 * 4
26732        + sizeof (dwarf5_gdb_augmentation));
26733   size_t expected_bytes = 0;
26734   expected_bytes += bytes_of_header;
26735   expected_bytes += cu_list.size ();
26736   expected_bytes += types_cu_list.size ();
26737   expected_bytes += nametable.bytes ();
26738   data_buf header;
26739
26740   if (!dwarf5_is_dwarf64)
26741     {
26742       const uint64_t size64 = expected_bytes - 4;
26743       gdb_assert (size64 < 0xfffffff0);
26744       header.append_uint (4, dwarf5_byte_order, size64);
26745     }
26746   else
26747     {
26748       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26749       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26750     }
26751
26752   /* The version number.  */
26753   header.append_uint (2, dwarf5_byte_order, 5);
26754
26755   /* Padding.  */
26756   header.append_uint (2, dwarf5_byte_order, 0);
26757
26758   /* comp_unit_count - The number of CUs in the CU list.  */
26759   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26760
26761   /* local_type_unit_count - The number of TUs in the local TU
26762      list.  */
26763   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26764
26765   /* foreign_type_unit_count - The number of TUs in the foreign TU
26766      list.  */
26767   header.append_uint (4, dwarf5_byte_order, 0);
26768
26769   /* bucket_count - The number of hash buckets in the hash lookup
26770      table.  */
26771   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26772
26773   /* name_count - The number of unique names in the index.  */
26774   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26775
26776   /* abbrev_table_size - The size in bytes of the abbreviations
26777      table.  */
26778   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26779
26780   /* augmentation_string_size - The size in bytes of the augmentation
26781      string.  This value is rounded up to a multiple of 4.  */
26782   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26783   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26784   header.append_data (dwarf5_gdb_augmentation);
26785
26786   gdb_assert (header.size () == bytes_of_header);
26787
26788   header.file_write (out_file);
26789   cu_list.file_write (out_file);
26790   types_cu_list.file_write (out_file);
26791   nametable.file_write (out_file, out_file_str);
26792
26793   return expected_bytes;
26794 }
26795
26796 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26797    position is at the end of the file.  */
26798
26799 static void
26800 assert_file_size (FILE *file, const char *filename, size_t expected_size)
26801 {
26802   const auto file_size = ftell (file);
26803   if (file_size == -1)
26804     error (_("Can't get `%s' size"), filename);
26805   gdb_assert (file_size == expected_size);
26806 }
26807
26808 /* Create an index file for OBJFILE in the directory DIR.  */
26809
26810 static void
26811 write_psymtabs_to_index (struct objfile *objfile, const char *dir,
26812                          dw_index_kind index_kind)
26813 {
26814   if (dwarf2_per_objfile->using_index)
26815     error (_("Cannot use an index to create the index"));
26816
26817   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
26818     error (_("Cannot make an index when the file has multiple .debug_types sections"));
26819
26820   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
26821     return;
26822
26823   struct stat st;
26824   if (stat (objfile_name (objfile), &st) < 0)
26825     perror_with_name (objfile_name (objfile));
26826
26827   std::string filename (std::string (dir) + SLASH_STRING
26828                         + lbasename (objfile_name (objfile))
26829                         + (index_kind == dw_index_kind::DEBUG_NAMES
26830                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
26831
26832   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
26833   if (!out_file)
26834     error (_("Can't open `%s' for writing"), filename.c_str ());
26835
26836   /* Order matters here; we want FILE to be closed before FILENAME is
26837      unlinked, because on MS-Windows one cannot delete a file that is
26838      still open.  (Don't call anything here that might throw until
26839      file_closer is created.)  */
26840   gdb::unlinker unlink_file (filename.c_str ());
26841   gdb_file_up close_out_file (out_file);
26842
26843   if (index_kind == dw_index_kind::DEBUG_NAMES)
26844     {
26845       std::string filename_str (std::string (dir) + SLASH_STRING
26846                                 + lbasename (objfile_name (objfile))
26847                                 + DEBUG_STR_SUFFIX);
26848       FILE *out_file_str
26849         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
26850       if (!out_file_str)
26851         error (_("Can't open `%s' for writing"), filename_str.c_str ());
26852       gdb::unlinker unlink_file_str (filename_str.c_str ());
26853       gdb_file_up close_out_file_str (out_file_str);
26854
26855       const size_t total_len
26856         = write_debug_names (objfile, out_file, out_file_str);
26857       assert_file_size (out_file, filename.c_str (), total_len);
26858
26859       /* We want to keep the file .debug_str file too.  */
26860       unlink_file_str.keep ();
26861     }
26862   else
26863     {
26864       const size_t total_len
26865         = write_gdbindex (objfile, out_file);
26866       assert_file_size (out_file, filename.c_str (), total_len);
26867     }
26868
26869   /* We want to keep the file.  */
26870   unlink_file.keep ();
26871 }
26872
26873 /* Implementation of the `save gdb-index' command.
26874    
26875    Note that the .gdb_index file format used by this command is
26876    documented in the GDB manual.  Any changes here must be documented
26877    there.  */
26878
26879 static void
26880 save_gdb_index_command (const char *arg, int from_tty)
26881 {
26882   struct objfile *objfile;
26883   const char dwarf5space[] = "-dwarf-5 ";
26884   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
26885
26886   if (!arg)
26887     arg = "";
26888
26889   arg = skip_spaces (arg);
26890   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
26891     {
26892       index_kind = dw_index_kind::DEBUG_NAMES;
26893       arg += strlen (dwarf5space);
26894       arg = skip_spaces (arg);
26895     }
26896
26897   if (!*arg)
26898     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
26899
26900   ALL_OBJFILES (objfile)
26901   {
26902     struct stat st;
26903
26904     /* If the objfile does not correspond to an actual file, skip it.  */
26905     if (stat (objfile_name (objfile), &st) < 0)
26906       continue;
26907
26908     dwarf2_per_objfile
26909       = (struct dwarf2_per_objfile *) objfile_data (objfile,
26910                                                     dwarf2_objfile_data_key);
26911     if (dwarf2_per_objfile)
26912       {
26913
26914         TRY
26915           {
26916             write_psymtabs_to_index (objfile, arg, index_kind);
26917           }
26918         CATCH (except, RETURN_MASK_ERROR)
26919           {
26920             exception_fprintf (gdb_stderr, except,
26921                                _("Error while writing index for `%s': "),
26922                                objfile_name (objfile));
26923           }
26924         END_CATCH
26925       }
26926   }
26927 }
26928
26929 \f
26930
26931 int dwarf_always_disassemble;
26932
26933 static void
26934 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
26935                                struct cmd_list_element *c, const char *value)
26936 {
26937   fprintf_filtered (file,
26938                     _("Whether to always disassemble "
26939                       "DWARF expressions is %s.\n"),
26940                     value);
26941 }
26942
26943 static void
26944 show_check_physname (struct ui_file *file, int from_tty,
26945                      struct cmd_list_element *c, const char *value)
26946 {
26947   fprintf_filtered (file,
26948                     _("Whether to check \"physname\" is %s.\n"),
26949                     value);
26950 }
26951
26952 void
26953 _initialize_dwarf2_read (void)
26954 {
26955   struct cmd_list_element *c;
26956
26957   dwarf2_objfile_data_key
26958     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
26959
26960   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
26961 Set DWARF specific variables.\n\
26962 Configure DWARF variables such as the cache size"),
26963                   &set_dwarf_cmdlist, "maintenance set dwarf ",
26964                   0/*allow-unknown*/, &maintenance_set_cmdlist);
26965
26966   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
26967 Show DWARF specific variables\n\
26968 Show DWARF variables such as the cache size"),
26969                   &show_dwarf_cmdlist, "maintenance show dwarf ",
26970                   0/*allow-unknown*/, &maintenance_show_cmdlist);
26971
26972   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
26973                             &dwarf_max_cache_age, _("\
26974 Set the upper bound on the age of cached DWARF compilation units."), _("\
26975 Show the upper bound on the age of cached DWARF compilation units."), _("\
26976 A higher limit means that cached compilation units will be stored\n\
26977 in memory longer, and more total memory will be used.  Zero disables\n\
26978 caching, which can slow down startup."),
26979                             NULL,
26980                             show_dwarf_max_cache_age,
26981                             &set_dwarf_cmdlist,
26982                             &show_dwarf_cmdlist);
26983
26984   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
26985                            &dwarf_always_disassemble, _("\
26986 Set whether `info address' always disassembles DWARF expressions."), _("\
26987 Show whether `info address' always disassembles DWARF expressions."), _("\
26988 When enabled, DWARF expressions are always printed in an assembly-like\n\
26989 syntax.  When disabled, expressions will be printed in a more\n\
26990 conversational style, when possible."),
26991                            NULL,
26992                            show_dwarf_always_disassemble,
26993                            &set_dwarf_cmdlist,
26994                            &show_dwarf_cmdlist);
26995
26996   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
26997 Set debugging of the DWARF reader."), _("\
26998 Show debugging of the DWARF reader."), _("\
26999 When enabled (non-zero), debugging messages are printed during DWARF\n\
27000 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27001 information.  A value greater than 1 provides more verbose information."),
27002                             NULL,
27003                             NULL,
27004                             &setdebuglist, &showdebuglist);
27005
27006   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27007 Set debugging of the DWARF DIE reader."), _("\
27008 Show debugging of the DWARF DIE reader."), _("\
27009 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27010 The value is the maximum depth to print."),
27011                              NULL,
27012                              NULL,
27013                              &setdebuglist, &showdebuglist);
27014
27015   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27016 Set debugging of the dwarf line reader."), _("\
27017 Show debugging of the dwarf line reader."), _("\
27018 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27019 A value of 1 (one) provides basic information.\n\
27020 A value greater than 1 provides more verbose information."),
27021                              NULL,
27022                              NULL,
27023                              &setdebuglist, &showdebuglist);
27024
27025   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27026 Set cross-checking of \"physname\" code against demangler."), _("\
27027 Show cross-checking of \"physname\" code against demangler."), _("\
27028 When enabled, GDB's internal \"physname\" code is checked against\n\
27029 the demangler."),
27030                            NULL, show_check_physname,
27031                            &setdebuglist, &showdebuglist);
27032
27033   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27034                            no_class, &use_deprecated_index_sections, _("\
27035 Set whether to use deprecated gdb_index sections."), _("\
27036 Show whether to use deprecated gdb_index sections."), _("\
27037 When enabled, deprecated .gdb_index sections are used anyway.\n\
27038 Normally they are ignored either because of a missing feature or\n\
27039 performance issue.\n\
27040 Warning: This option must be enabled before gdb reads the file."),
27041                            NULL,
27042                            NULL,
27043                            &setlist, &showlist);
27044
27045   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27046                _("\
27047 Save a gdb-index file.\n\
27048 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27049 \n\
27050 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27051 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27052 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27053                &save_cmdlist);
27054   set_cmd_completer (c, filename_completer);
27055
27056   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27057                                                         &dwarf2_locexpr_funcs);
27058   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27059                                                         &dwarf2_loclist_funcs);
27060
27061   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27062                                         &dwarf2_block_frame_base_locexpr_funcs);
27063   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27064                                         &dwarf2_block_frame_base_loclist_funcs);
27065
27066 #if GDB_SELF_TEST
27067   selftests::register_test ("dw2_expand_symtabs_matching",
27068                             selftests::dw2_expand_symtabs_matching::run_test);
27069 #endif
27070 }